avienc.c 21.3 KB
Newer Older
Fabrice Bellard's avatar
Fabrice Bellard committed
1
/*
2
 * AVI muxer
3
 * Copyright (c) 2000 Fabrice Bellard
Fabrice Bellard's avatar
Fabrice Bellard committed
4
 *
5
 * This file is part of Libav.
6
 *
7
 * Libav is free software; you can redistribute it and/or
8 9
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
10
 * version 2.1 of the License, or (at your option) any later version.
Fabrice Bellard's avatar
Fabrice Bellard committed
11
 *
12
 * Libav is distributed in the hope that it will be useful,
Fabrice Bellard's avatar
Fabrice Bellard committed
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
Fabrice Bellard's avatar
Fabrice Bellard committed
16
 *
17
 * You should have received a copy of the GNU Lesser General Public
18
 * License along with Libav; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Fabrice Bellard's avatar
Fabrice Bellard committed
20 21
 */
#include "avformat.h"
22
#include "internal.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
23
#include "avi.h"
24
#include "avio_internal.h"
25
#include "riff.h"
26
#include "libavutil/intreadwrite.h"
27
#include "libavutil/dict.h"
Fabrice Bellard's avatar
Fabrice Bellard committed
28 29

/*
30
 * TODO:
Fabrice Bellard's avatar
Fabrice Bellard committed
31 32 33
 *  - fill all fields if non streamed (nb_frames for example)
 */

34
typedef struct AVIIentry {
Fabrice Bellard's avatar
Fabrice Bellard committed
35
    unsigned int flags, pos, len;
36 37 38 39 40
} AVIIentry;

#define AVI_INDEX_CLUSTER_SIZE 16384

typedef struct AVIIndex {
41
    int64_t     indx_start;
42 43 44
    int         entry;
    int         ents_allocated;
    AVIIentry** cluster;
Fabrice Bellard's avatar
Fabrice Bellard committed
45 46 47
} AVIIndex;

typedef struct {
48
    int64_t riff_start, movi_list, odml_list;
49
    int64_t frames_hdr_all;
50
    int riff_id;
Fabrice Bellard's avatar
Fabrice Bellard committed
51 52
} AVIContext;

53 54 55 56
typedef struct  {
    int64_t frames_hdr_strm;
    int audio_strm_length;
    int packet_count;
57
    int entry;
58 59 60 61

    AVIIndex indexes;
} AVIStream ;

62
static inline AVIIentry* avi_get_ientry(AVIIndex* idx, int ent_id)
63 64 65 66 67 68
{
    int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
    int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
    return &idx->cluster[cl][id];
}

69
static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
70
                                  const char* riff_tag, const char* list_tag)
71
{
72
    AVIContext *avi= s->priv_data;
73
    int64_t loff;
74
    int i;
75

76
    avi->riff_id++;
77 78 79 80
    for (i=0; i<s->nb_streams; i++){
        AVIStream *avist= s->streams[i]->priv_data;
        avist->indexes.entry = 0;
    }
81

82
    avi->riff_start = ff_start_tag(pb, "RIFF");
83
    ffio_wfourcc(pb, riff_tag);
84
    loff = ff_start_tag(pb, "LIST");
85
    ffio_wfourcc(pb, list_tag);
86 87 88
    return loff;
}

89
static char* avi_stream2fourcc(char* tag, int index, enum AVMediaType type)
90
{
91 92
    tag[0] = '0' + index/10;
    tag[1] = '0' + index%10;
93
    if (type == AVMEDIA_TYPE_VIDEO) {
94 95
        tag[2] = 'd';
        tag[3] = 'c';
96
    } else if (type == AVMEDIA_TYPE_SUBTITLE) {
97 98 99
        // note: this is not an official code
        tag[2] = 's';
        tag[3] = 'b';
100 101 102 103 104 105 106 107
    } else {
        tag[2] = 'w';
        tag[3] = 'b';
    }
    tag[4] = '\0';
    return tag;
}

108
static void avi_write_info_tag(AVIOContext *pb, const char *tag, const char *str)
109 110 111 112
{
    int len = strlen(str);
    if (len > 0) {
        len++;
113
        ffio_wfourcc(pb, tag);
114
        avio_wl32(pb, len);
115
        avio_put_str(pb, str);
116
        if (len & 1)
117
            avio_w8(pb, 0);
118 119 120
    }
}

121 122
static int avi_write_counters(AVFormatContext* s, int riff_id)
{
123
    AVIOContext *pb = s->pb;
124 125
    AVIContext *avi = s->priv_data;
    int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
126
    int64_t file_size;
127 128
    AVCodecContext* stream;

129
    file_size = avio_tell(pb);
130
    for(n = 0; n < s->nb_streams; n++) {
131 132 133
        AVIStream *avist= s->streams[n]->priv_data;

        assert(avist->frames_hdr_strm);
134
        stream = s->streams[n]->codec;
135
        avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
136 137
        ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);
        if(au_ssize == 0) {
138
            avio_wl32(pb, avist->packet_count);
139
        } else {
140
            avio_wl32(pb, avist->audio_strm_length / au_ssize);
141
        }
142
        if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
143
            nb_frames = FFMAX(nb_frames, avist->packet_count);
144 145 146
    }
    if(riff_id == 1) {
        assert(avi->frames_hdr_all);
147
        avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
148
        avio_wl32(pb, nb_frames);
149
    }
150
    avio_seek(pb, file_size, SEEK_SET);
151 152 153 154

    return 0;
}

Fabrice Bellard's avatar
Fabrice Bellard committed
155 156
static int avi_write_header(AVFormatContext *s)
{
Fabrice Bellard's avatar
Fabrice Bellard committed
157
    AVIContext *avi = s->priv_data;
158
    AVIOContext *pb = s->pb;
159
    int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
Fabrice Bellard's avatar
Fabrice Bellard committed
160
    AVCodecContext *stream, *video_enc;
161
    int64_t list1, list2, strh, strf;
162
    AVDictionaryEntry *t = NULL;
Fabrice Bellard's avatar
Fabrice Bellard committed
163

164 165 166 167 168 169
    if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
        av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
               AVI_MAX_STREAM_COUNT);
        return -1;
    }

170 171 172 173 174 175
    for(n=0;n<s->nb_streams;n++) {
        s->streams[n]->priv_data= av_mallocz(sizeof(AVIStream));
        if(!s->streams[n]->priv_data)
            return AVERROR(ENOMEM);
    }

Fabrice Bellard's avatar
Fabrice Bellard committed
176
    /* header list */
177
    avi->riff_id = 0;
178
    list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
Fabrice Bellard's avatar
Fabrice Bellard committed
179 180

    /* avi header */
181
    ffio_wfourcc(pb, "avih");
182
    avio_wl32(pb, 14 * 4);
Fabrice Bellard's avatar
Fabrice Bellard committed
183 184 185 186
    bitrate = 0;

    video_enc = NULL;
    for(n=0;n<s->nb_streams;n++) {
187
        stream = s->streams[n]->codec;
Fabrice Bellard's avatar
Fabrice Bellard committed
188
        bitrate += stream->bit_rate;
189
        if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
Fabrice Bellard's avatar
Fabrice Bellard committed
190 191
            video_enc = stream;
    }
192

Fabrice Bellard's avatar
Fabrice Bellard committed
193 194
    nb_frames = 0;

195
    if(video_enc){
196
        avio_wl32(pb, (uint32_t)(INT64_C(1000000) * video_enc->time_base.num / video_enc->time_base.den));
197
    } else {
198
        avio_wl32(pb, 0);
199
    }
200 201
    avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
    avio_wl32(pb, 0); /* padding */
202
    if (!pb->seekable)
203
        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED); /* flags */
204
    else
205
        avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED); /* flags */
206
    avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
207 208 209 210
    avio_wl32(pb, nb_frames); /* nb frames, filled later */
    avio_wl32(pb, 0); /* initial frame */
    avio_wl32(pb, s->nb_streams); /* nb streams */
    avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
211
    if(video_enc){
212 213
        avio_wl32(pb, video_enc->width);
        avio_wl32(pb, video_enc->height);
214
    } else {
215 216
        avio_wl32(pb, 0);
        avio_wl32(pb, 0);
217
    }
218 219 220 221
    avio_wl32(pb, 0); /* reserved */
    avio_wl32(pb, 0); /* reserved */
    avio_wl32(pb, 0); /* reserved */
    avio_wl32(pb, 0); /* reserved */
222

Fabrice Bellard's avatar
Fabrice Bellard committed
223 224
    /* stream list */
    for(i=0;i<n;i++) {
225
        AVIStream *avist= s->streams[i]->priv_data;
226
        list2 = ff_start_tag(pb, "LIST");
227
        ffio_wfourcc(pb, "strl");
228

229
        stream = s->streams[i]->codec;
Fabrice Bellard's avatar
Fabrice Bellard committed
230 231

        /* stream generic header */
232
        strh = ff_start_tag(pb, "strh");
Fabrice Bellard's avatar
Fabrice Bellard committed
233
        switch(stream->codec_type) {
234
        case AVMEDIA_TYPE_SUBTITLE:
235 236
            // XSUB subtitles behave like video tracks, other subtitles
            // are not (yet) supported.
237 238 239 240
            if (stream->codec_id != CODEC_ID_XSUB) {
                av_log(s, AV_LOG_ERROR, "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
                return AVERROR_PATCHWELCOME;
            }
241 242 243 244
        case AVMEDIA_TYPE_VIDEO: ffio_wfourcc(pb, "vids"); break;
        case AVMEDIA_TYPE_AUDIO: ffio_wfourcc(pb, "auds"); break;
//      case AVMEDIA_TYPE_TEXT : ffio_wfourcc(pb, "txts"); break;
        case AVMEDIA_TYPE_DATA : ffio_wfourcc(pb, "dats"); break;
Fabrice Bellard's avatar
Fabrice Bellard committed
245
        }
246
        if(stream->codec_type == AVMEDIA_TYPE_VIDEO ||
247
           stream->codec_id == CODEC_ID_XSUB)
248
            avio_wl32(pb, stream->codec_tag);
249
        else
250 251 252 253 254
            avio_wl32(pb, 1);
        avio_wl32(pb, 0); /* flags */
        avio_wl16(pb, 0); /* priority */
        avio_wl16(pb, 0); /* language */
        avio_wl32(pb, 0); /* initial frame */
255 256 257

        ff_parse_specific_params(stream, &au_byterate, &au_ssize, &au_scale);

258 259
        avio_wl32(pb, au_scale); /* scale */
        avio_wl32(pb, au_byterate); /* rate */
260
        avpriv_set_pts_info(s->streams[i], 64, au_scale, au_byterate);
261

262
        avio_wl32(pb, 0); /* start */
263
        avist->frames_hdr_strm = avio_tell(pb); /* remember this offset to fill later */
264
        if (!pb->seekable)
265
            avio_wl32(pb, AVI_MAX_RIFF_SIZE); /* FIXME: this may be broken, but who cares */
266
        else
267
            avio_wl32(pb, 0); /* length, XXX: filled later */
268

269
        /* suggested buffer size */ //FIXME set at the end to largest chunk
270
        if(stream->codec_type == AVMEDIA_TYPE_VIDEO)
271
            avio_wl32(pb, 1024 * 1024);
272
        else if(stream->codec_type == AVMEDIA_TYPE_AUDIO)
273
            avio_wl32(pb, 12 * 1024);
274
        else
275 276 277 278 279 280
            avio_wl32(pb, 0);
        avio_wl32(pb, -1); /* quality */
        avio_wl32(pb, au_ssize); /* sample size */
        avio_wl32(pb, 0);
        avio_wl16(pb, stream->width);
        avio_wl16(pb, stream->height);
281
        ff_end_tag(pb, strh);
Fabrice Bellard's avatar
Fabrice Bellard committed
282

283
      if(stream->codec_type != AVMEDIA_TYPE_DATA){
284
        strf = ff_start_tag(pb, "strf");
Fabrice Bellard's avatar
Fabrice Bellard committed
285
        switch(stream->codec_type) {
286
        case AVMEDIA_TYPE_SUBTITLE:
287 288 289
            // XSUB subtitles behave like video tracks, other subtitles
            // are not (yet) supported.
            if (stream->codec_id != CODEC_ID_XSUB) break;
290
        case AVMEDIA_TYPE_VIDEO:
291
            ff_put_bmp_header(pb, stream, ff_codec_bmp_tags, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
292
            break;
293
        case AVMEDIA_TYPE_AUDIO:
294
            if (ff_put_wav_header(pb, stream) < 0) {
295 296
                return -1;
            }
Fabrice Bellard's avatar
Fabrice Bellard committed
297
            break;
298
        default:
299
            return -1;
Fabrice Bellard's avatar
Fabrice Bellard committed
300
        }
301
        ff_end_tag(pb, strf);
302
        if ((t = av_dict_get(s->streams[i]->metadata, "title", NULL, 0))) {
303 304 305
            avi_write_info_tag(s->pb, "strn", t->value);
            t = NULL;
        }
306
      }
307

308
        if (pb->seekable) {
309 310
            unsigned char tag[5];
            int j;
311 312

            /* Starting to lay out AVI OpenDML master index.
313 314 315 316
             * We want to make it JUNK entry for now, since we'd
             * like to get away without making AVI an OpenDML one
             * for compatibility reasons.
             */
317 318
            avist->indexes.entry = avist->indexes.ents_allocated = 0;
            avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
319 320 321 322
            avio_wl16(pb, 4);        /* wLongsPerEntry */
            avio_w8(pb, 0);          /* bIndexSubType (0 == frame index) */
            avio_w8(pb, 0);          /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
            avio_wl32(pb, 0);        /* nEntriesInUse (will fill out later on) */
323
            ffio_wfourcc(pb, avi_stream2fourcc(tag, i, stream->codec_type));
324
                                    /* dwChunkId */
325 326
            avio_wl64(pb, 0);        /* dwReserved[3]
            avio_wl32(pb, 0);           Must be 0.    */
327
            for (j=0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
328
                 avio_wl64(pb, 0);
329
            ff_end_tag(pb, avist->indexes.indx_start);
330
        }
331

332
        if(   stream->codec_type == AVMEDIA_TYPE_VIDEO
333 334
           && s->streams[i]->sample_aspect_ratio.num>0
           && s->streams[i]->sample_aspect_ratio.den>0){
335
            int vprp= ff_start_tag(pb, "vprp");
336
            AVRational dar = av_mul_q(s->streams[i]->sample_aspect_ratio,
337 338 339 340
                                      (AVRational){stream->width, stream->height});
            int num, den;
            av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);

341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
            avio_wl32(pb, 0); //video format  = unknown
            avio_wl32(pb, 0); //video standard= unknown
            avio_wl32(pb, lrintf(1.0/av_q2d(stream->time_base)));
            avio_wl32(pb, stream->width );
            avio_wl32(pb, stream->height);
            avio_wl16(pb, den);
            avio_wl16(pb, num);
            avio_wl32(pb, stream->width );
            avio_wl32(pb, stream->height);
            avio_wl32(pb, 1); //progressive FIXME

            avio_wl32(pb, stream->height);
            avio_wl32(pb, stream->width );
            avio_wl32(pb, stream->height);
            avio_wl32(pb, stream->width );
            avio_wl32(pb, 0);
            avio_wl32(pb, 0);

            avio_wl32(pb, 0);
            avio_wl32(pb, 0);
361
            ff_end_tag(pb, vprp);
362 363
        }

364
        ff_end_tag(pb, list2);
Fabrice Bellard's avatar
Fabrice Bellard committed
365
    }
366

367
    if (pb->seekable) {
368
        /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
369
        avi->odml_list = ff_start_tag(pb, "JUNK");
370 371
        ffio_wfourcc(pb, "odml");
        ffio_wfourcc(pb, "dmlh");
372
        avio_wl32(pb, 248);
373
        for (i = 0; i < 248; i+= 4)
374
             avio_wl32(pb, 0);
375
        ff_end_tag(pb, avi->odml_list);
376
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
377

378
    ff_end_tag(pb, list1);
379

380
    list2 = ff_start_tag(pb, "LIST");
381
    ffio_wfourcc(pb, "INFO");
382 383 384
    ff_metadata_conv(&s->metadata, ff_riff_info_conv, NULL);
    for (i = 0; *ff_riff_tags[i]; i++) {
        if ((t = av_dict_get(s->metadata, ff_riff_tags[i], NULL, AV_DICT_MATCH_CASE)))
385 386
            avi_write_info_tag(s->pb, t->key, t->value);
    }
387
    ff_end_tag(pb, list2);
388 389

    /* some padding for easier tag editing */
390
    list2 = ff_start_tag(pb, "JUNK");
391
    for (i = 0; i < 1016; i += 4)
392
        avio_wl32(pb, 0);
393
    ff_end_tag(pb, list2);
394

395
    avi->movi_list = ff_start_tag(pb, "LIST");
396
    ffio_wfourcc(pb, "movi");
Fabrice Bellard's avatar
Fabrice Bellard committed
397

398
    avio_flush(pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
399 400 401 402

    return 0;
}

403 404
static int avi_write_ix(AVFormatContext *s)
{
405
    AVIOContext *pb = s->pb;
406
    AVIContext *avi = s->priv_data;
407 408
    char tag[5];
    char ix_tag[] = "ix00";
409
    int i, j;
410

411
    assert(pb->seekable);
412

413 414
    if (avi->riff_id > AVI_MASTER_INDEX_SIZE)
        return -1;
415

416
    for (i=0;i<s->nb_streams;i++) {
417
        AVIStream *avist= s->streams[i]->priv_data;
418
         int64_t ix, pos;
419

420
         avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
421
         ix_tag[3] = '0' + i;
422

423
         /* Writing AVI OpenDML leaf index chunk */
424
         ix = avio_tell(pb);
425
         ffio_wfourcc(pb, ix_tag);     /* ix?? */
426
         avio_wl32(pb, avist->indexes.entry * 8 + 24);
427
                                      /* chunk size */
428 429 430 431
         avio_wl16(pb, 2);             /* wLongsPerEntry */
         avio_w8(pb, 0);             /* bIndexSubType (0 == frame index) */
         avio_w8(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
         avio_wl32(pb, avist->indexes.entry);
432
                                      /* nEntriesInUse */
433
         ffio_wfourcc(pb, tag);        /* dwChunkId */
434 435
         avio_wl64(pb, avi->movi_list);/* qwBaseOffset */
         avio_wl32(pb, 0);             /* dwReserved_3 (must be 0) */
436

437 438
         for (j=0; j<avist->indexes.entry; j++) {
             AVIIentry* ie = avi_get_ientry(&avist->indexes, j);
439 440
             avio_wl32(pb, ie->pos + 8);
             avio_wl32(pb, ((uint32_t)ie->len & ~0x80000000) |
441
                          (ie->flags & 0x10 ? 0 : 0x80000000));
442
         }
443
         avio_flush(pb);
444
         pos = avio_tell(pb);
445

446
         /* Updating one entry in the AVI OpenDML master index */
447
         avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
448
         ffio_wfourcc(pb, "indx");            /* enabling this entry */
449
         avio_skip(pb, 8);
450
         avio_wl32(pb, avi->riff_id);         /* nEntriesInUse */
451
         avio_skip(pb, 16*avi->riff_id);
452 453 454
         avio_wl64(pb, ix);                   /* qwOffset */
         avio_wl32(pb, pos - ix);             /* dwSize */
         avio_wl32(pb, avist->indexes.entry); /* dwDuration */
455

456
         avio_seek(pb, pos, SEEK_SET);
457 458 459 460 461
    }
    return 0;
}

static int avi_write_idx1(AVFormatContext *s)
462
{
463
    AVIOContext *pb = s->pb;
464
    AVIContext *avi = s->priv_data;
465
    int64_t idx_chunk;
466
    int i;
467
    char tag[5];
468

469
    if (pb->seekable) {
470
        AVIStream *avist;
471 472 473
        AVIIentry* ie = 0, *tie;
        int empty, stream_id = -1;

474
        idx_chunk = ff_start_tag(pb, "idx1");
475 476 477 478 479
        for(i=0; i<s->nb_streams; i++){
            avist= s->streams[i]->priv_data;
            avist->entry=0;
        }

480 481 482
        do {
            empty = 1;
            for (i=0; i<s->nb_streams; i++) {
483 484
                avist= s->streams[i]->priv_data;
                 if (avist->indexes.entry <= avist->entry)
485 486
                     continue;

487
                 tie = avi_get_ientry(&avist->indexes, avist->entry);
488 489 490 491 492 493 494
                 if (empty || tie->pos < ie->pos) {
                     ie = tie;
                     stream_id = i;
                 }
                 empty = 0;
            }
            if (!empty) {
495
                avist= s->streams[stream_id]->priv_data;
496
                avi_stream2fourcc(tag, stream_id,
497
                                  s->streams[stream_id]->codec->codec_type);
498
                ffio_wfourcc(pb, tag);
499 500 501
                avio_wl32(pb, ie->flags);
                avio_wl32(pb, ie->pos);
                avio_wl32(pb, ie->len);
502
                avist->entry++;
503 504
            }
        } while (!empty);
505
        ff_end_tag(pb, idx_chunk);
506

507
        avi_write_counters(s, avi->riff_id);
508 509 510 511
    }
    return 0;
}

512
static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
Fabrice Bellard's avatar
Fabrice Bellard committed
513 514
{
    AVIContext *avi = s->priv_data;
515
    AVIOContext *pb = s->pb;
Fabrice Bellard's avatar
Fabrice Bellard committed
516
    unsigned char tag[5];
517 518
    unsigned int flags=0;
    const int stream_index= pkt->stream_index;
519
    AVIStream *avist= s->streams[stream_index]->priv_data;
520
    AVCodecContext *enc= s->streams[stream_index]->codec;
521
    int size= pkt->size;
522

523
//    av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %d\n", pkt->dts, avi->packet_count[stream_index], stream_index);
524
    while(enc->block_align==0 && pkt->dts != AV_NOPTS_VALUE && pkt->dts > avist->packet_count){
525 526 527 528 529 530 531
        AVPacket empty_packet;

        av_init_packet(&empty_packet);
        empty_packet.size= 0;
        empty_packet.data= NULL;
        empty_packet.stream_index= stream_index;
        avi_write_packet(s, &empty_packet);
532
//        av_log(s, AV_LOG_DEBUG, "dup %"PRId64" %d\n", pkt->dts, avi->packet_count[stream_index]);
533
    }
534
    avist->packet_count++;
535

536
    // Make sure to put an OpenDML chunk when the file size exceeds the limits
537
    if (pb->seekable &&
538
        (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
539

540
        avi_write_ix(s);
541
        ff_end_tag(pb, avi->movi_list);
542

543 544
        if (avi->riff_id == 1)
            avi_write_idx1(s);
545

546
        ff_end_tag(pb, avi->riff_start);
547
        avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
548
    }
549

550
    avi_stream2fourcc(tag, stream_index, enc->codec_type);
551
    if(pkt->flags&AV_PKT_FLAG_KEY)
552
        flags = 0x10;
553
    if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
554
       avist->audio_strm_length += size;
555
    }
Fabrice Bellard's avatar
Fabrice Bellard committed
556

557
    if (s->pb->seekable) {
558
        AVIIndex* idx = &avist->indexes;
559 560
        int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
        int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
561
        if (idx->ents_allocated <= idx->entry) {
562 563 564
            idx->cluster = av_realloc(idx->cluster, (cl+1)*sizeof(void*));
            if (!idx->cluster)
                return -1;
565
            idx->cluster[cl] = av_malloc(AVI_INDEX_CLUSTER_SIZE*sizeof(AVIIentry));
566 567 568 569
            if (!idx->cluster[cl])
                return -1;
            idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
        }
570

571
        idx->cluster[cl][id].flags = flags;
572
        idx->cluster[cl][id].pos = avio_tell(pb) - avi->movi_list;
573
        idx->cluster[cl][id].len = size;
574
        idx->entry++;
Fabrice Bellard's avatar
Fabrice Bellard committed
575
    }
576

577 578 579
    avio_write(pb, tag, 4);
    avio_wl32(pb, size);
    avio_write(pb, pkt->data, size);
Fabrice Bellard's avatar
Fabrice Bellard committed
580
    if (size & 1)
581
        avio_w8(pb, 0);
Fabrice Bellard's avatar
Fabrice Bellard committed
582

583
    avio_flush(pb);
Fabrice Bellard's avatar
Fabrice Bellard committed
584 585 586 587 588 589
    return 0;
}

static int avi_write_trailer(AVFormatContext *s)
{
    AVIContext *avi = s->priv_data;
590
    AVIOContext *pb = s->pb;
591
    int res = 0;
592
    int i, j, n, nb_frames;
593
    int64_t file_size;
594

595
    if (pb->seekable){
596
        if (avi->riff_id == 1) {
597
            ff_end_tag(pb, avi->movi_list);
598
            res = avi_write_idx1(s);
599
            ff_end_tag(pb, avi->riff_start);
600 601
        } else {
            avi_write_ix(s);
602 603
            ff_end_tag(pb, avi->movi_list);
            ff_end_tag(pb, avi->riff_start);
604

605
            file_size = avio_tell(pb);
606
            avio_seek(pb, avi->odml_list - 8, SEEK_SET);
607
            ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
608
            avio_skip(pb, 16);
609 610 611

            for (n=nb_frames=0;n<s->nb_streams;n++) {
                AVCodecContext *stream = s->streams[n]->codec;
612 613
                AVIStream *avist= s->streams[n]->priv_data;

614
                if (stream->codec_type == AVMEDIA_TYPE_VIDEO) {
615 616
                    if (nb_frames < avist->packet_count)
                        nb_frames = avist->packet_count;
617 618
                } else {
                    if (stream->codec_id == CODEC_ID_MP2 || stream->codec_id == CODEC_ID_MP3) {
619
                        nb_frames += avist->packet_count;
620
                    }
621 622
                }
            }
623
            avio_wl32(pb, nb_frames);
624
            avio_seek(pb, file_size, SEEK_SET);
625

626 627
            avi_write_counters(s, avi->riff_id);
        }
628
    }
629
    avio_flush(pb);
630

631 632 633 634 635 636
    for (i=0; i<s->nb_streams; i++) {
         AVIStream *avist= s->streams[i]->priv_data;
         for (j=0; j<avist->indexes.ents_allocated/AVI_INDEX_CLUSTER_SIZE; j++)
              av_free(avist->indexes.cluster[j]);
         av_freep(&avist->indexes.cluster);
         avist->indexes.ents_allocated = avist->indexes.entry = 0;
637
    }
638

639
    return res;
Fabrice Bellard's avatar
Fabrice Bellard committed
640 641
}

642
AVOutputFormat ff_avi_muxer = {
643 644 645 646 647
    .name              = "avi",
    .long_name         = NULL_IF_CONFIG_SMALL("AVI format"),
    .mime_type         = "video/x-msvideo",
    .extensions        = "avi",
    .priv_data_size    = sizeof(AVIContext),
648 649 650 651 652
#if CONFIG_LIBMP3LAME_ENCODER
    .audio_codec       = CODEC_ID_MP3,
#else
    .audio_codec       = CODEC_ID_AC3,
#endif
653 654 655 656
    .video_codec       = CODEC_ID_MPEG4,
    .write_header      = avi_write_header,
    .write_packet      = avi_write_packet,
    .write_trailer     = avi_write_trailer,
657 658 659 660
    .codec_tag         = (const AVCodecTag* const []){
        ff_codec_bmp_tags, ff_codec_wav_tags, 0
    },
    .flags             = AVFMT_VARIABLE_FPS,
Fabrice Bellard's avatar
Fabrice Bellard committed
661
};