]> git.sesse.net Git - ffmpeg/blob - libavformat/avienc.c
avformat/avienc: factor write_odml_master() out
[ffmpeg] / libavformat / avienc.c
1 /*
2  * AVI muxer
3  * Copyright (c) 2000 Fabrice Bellard
4  *
5  * This file is part of FFmpeg.
6  *
7  * FFmpeg is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU Lesser General Public
9  * License as published by the Free Software Foundation; either
10  * version 2.1 of the License, or (at your option) any later version.
11  *
12  * FFmpeg is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15  * Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with FFmpeg; if not, write to the Free Software
19  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20  */
21
22 //#define DEBUG
23
24 #include "avformat.h"
25 #include "internal.h"
26 #include "avi.h"
27 #include "avio_internal.h"
28 #include "riff.h"
29 #include "mpegts.h"
30 #include "libavformat/avlanguage.h"
31 #include "libavutil/avstring.h"
32 #include "libavutil/intreadwrite.h"
33 #include "libavutil/dict.h"
34 #include "libavutil/avassert.h"
35 #include "libavutil/timestamp.h"
36 #include "libavutil/pixdesc.h"
37 #include "libavcodec/raw.h"
38
39 /*
40  * TODO:
41  *  - fill all fields if non streamed (nb_frames for example)
42  */
43
44 typedef struct AVIIentry {
45     unsigned int flags, pos, len;
46 } AVIIentry;
47
48 #define AVI_INDEX_CLUSTER_SIZE 16384
49
50 typedef struct AVIIndex {
51     int64_t     indx_start;
52     int64_t     audio_strm_offset;
53     int         entry;
54     int         ents_allocated;
55     AVIIentry** cluster;
56 } AVIIndex;
57
58 typedef struct AVIContext {
59     int64_t riff_start, movi_list, odml_list;
60     int64_t frames_hdr_all;
61     int riff_id;
62 } AVIContext;
63
64 typedef struct AVIStream {
65     int64_t frames_hdr_strm;
66     int64_t audio_strm_length;
67     int packet_count;
68     int entry;
69     int max_size;
70     int sample_requested;
71
72     int64_t last_dts;
73
74     AVIIndex indexes;
75 } AVIStream;
76
77 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt);
78
79 static inline AVIIentry *avi_get_ientry(const AVIIndex *idx, int ent_id)
80 {
81     int cl = ent_id / AVI_INDEX_CLUSTER_SIZE;
82     int id = ent_id % AVI_INDEX_CLUSTER_SIZE;
83     return &idx->cluster[cl][id];
84 }
85
86 static int64_t avi_start_new_riff(AVFormatContext *s, AVIOContext *pb,
87                                   const char *riff_tag, const char *list_tag)
88 {
89     AVIContext *avi = s->priv_data;
90     int64_t loff;
91     int i;
92
93     avi->riff_id++;
94     for (i = 0; i < s->nb_streams; i++) {
95         AVIStream *avist = s->streams[i]->priv_data;
96         avist->indexes.audio_strm_offset = avist->audio_strm_length;
97         avist->indexes.entry = 0;
98     }
99
100     avi->riff_start = ff_start_tag(pb, "RIFF");
101     ffio_wfourcc(pb, riff_tag);
102     loff = ff_start_tag(pb, "LIST");
103     ffio_wfourcc(pb, list_tag);
104     return loff;
105 }
106
107 static char *avi_stream2fourcc(char *tag, int index, enum AVMediaType type)
108 {
109     tag[0] = '0' + index / 10;
110     tag[1] = '0' + index % 10;
111     if (type == AVMEDIA_TYPE_VIDEO) {
112         tag[2] = 'd';
113         tag[3] = 'c';
114     } else if (type == AVMEDIA_TYPE_SUBTITLE) {
115         // note: this is not an official code
116         tag[2] = 's';
117         tag[3] = 'b';
118     } else {
119         tag[2] = 'w';
120         tag[3] = 'b';
121     }
122     tag[4] = '\0';
123     return tag;
124 }
125
126 static int avi_write_counters(AVFormatContext *s, int riff_id)
127 {
128     AVIOContext *pb = s->pb;
129     AVIContext *avi = s->priv_data;
130     int n, au_byterate, au_ssize, au_scale, nb_frames = 0;
131     int64_t file_size;
132     AVCodecContext *stream;
133
134     file_size = avio_tell(pb);
135     for (n = 0; n < s->nb_streams; n++) {
136         AVIStream *avist = s->streams[n]->priv_data;
137
138         av_assert0(avist->frames_hdr_strm);
139         stream = s->streams[n]->codec;
140         avio_seek(pb, avist->frames_hdr_strm, SEEK_SET);
141         ff_parse_specific_params(s->streams[n], &au_byterate, &au_ssize, &au_scale);
142         if (au_ssize == 0)
143             avio_wl32(pb, avist->packet_count);
144         else
145             avio_wl32(pb, avist->audio_strm_length / au_ssize);
146         if (stream->codec_type == AVMEDIA_TYPE_VIDEO)
147             nb_frames = FFMAX(nb_frames, avist->packet_count);
148     }
149     if (riff_id == 1) {
150         av_assert0(avi->frames_hdr_all);
151         avio_seek(pb, avi->frames_hdr_all, SEEK_SET);
152         avio_wl32(pb, nb_frames);
153     }
154     avio_seek(pb, file_size, SEEK_SET);
155
156     return 0;
157 }
158
159 static void write_odml_master(AVFormatContext *s, int stream_index)
160 {
161     AVIOContext *pb = s->pb;
162     AVStream *st = s->streams[stream_index];
163     AVCodecContext *enc = st->codec;
164     AVIStream *avist = st->priv_data;
165     unsigned char tag[5];
166     int j;
167
168     /* Starting to lay out AVI OpenDML master index.
169         * We want to make it JUNK entry for now, since we'd
170         * like to get away without making AVI an OpenDML one
171         * for compatibility reasons. */
172     avist->indexes.entry      = avist->indexes.ents_allocated = 0;
173     avist->indexes.indx_start = ff_start_tag(pb, "JUNK");
174     avio_wl16(pb, 4);   /* wLongsPerEntry */
175     avio_w8(pb, 0);     /* bIndexSubType (0 == frame index) */
176     avio_w8(pb, 0);     /* bIndexType (0 == AVI_INDEX_OF_INDEXES) */
177     avio_wl32(pb, 0);   /* nEntriesInUse (will fill out later on) */
178     ffio_wfourcc(pb, avi_stream2fourcc(tag, stream_index, enc->codec_type));
179                         /* dwChunkId */
180     avio_wl64(pb, 0);   /* dwReserved[3] */
181     // avio_wl32(pb, 0);   /* Must be 0.    */
182     for (j = 0; j < AVI_MASTER_INDEX_SIZE * 2; j++)
183         avio_wl64(pb, 0);
184     ff_end_tag(pb, avist->indexes.indx_start);
185 }
186
187 static int avi_write_header(AVFormatContext *s)
188 {
189     AVIContext *avi = s->priv_data;
190     AVIOContext *pb = s->pb;
191     int bitrate, n, i, nb_frames, au_byterate, au_ssize, au_scale;
192     AVCodecContext *video_enc;
193     AVStream *video_st = NULL;
194     int64_t list1, list2, strh, strf;
195     AVDictionaryEntry *t = NULL;
196     int padding;
197
198     if (s->nb_streams > AVI_MAX_STREAM_COUNT) {
199         av_log(s, AV_LOG_ERROR, "AVI does not support >%d streams\n",
200                AVI_MAX_STREAM_COUNT);
201         return AVERROR(EINVAL);
202     }
203
204     for (n = 0; n < s->nb_streams; n++) {
205         s->streams[n]->priv_data = av_mallocz(sizeof(AVIStream));
206         if (!s->streams[n]->priv_data)
207             return AVERROR(ENOMEM);
208     }
209
210     /* header list */
211     avi->riff_id = 0;
212     list1 = avi_start_new_riff(s, pb, "AVI ", "hdrl");
213
214     /* avi header */
215     ffio_wfourcc(pb, "avih");
216     avio_wl32(pb, 14 * 4);
217     bitrate = 0;
218
219     video_enc = NULL;
220     for (n = 0; n < s->nb_streams; n++) {
221         AVCodecContext *codec = s->streams[n]->codec;
222         bitrate += codec->bit_rate;
223         if (codec->codec_type == AVMEDIA_TYPE_VIDEO) {
224             video_enc = codec;
225             video_st = s->streams[n];
226         }
227     }
228
229     nb_frames = 0;
230
231     // TODO: should be avg_frame_rate
232     if (video_st)
233         avio_wl32(pb, (uint32_t) (INT64_C(1000000) * video_st->time_base.num /
234                                   video_st->time_base.den));
235     else
236         avio_wl32(pb, 0);
237     avio_wl32(pb, bitrate / 8); /* XXX: not quite exact */
238     avio_wl32(pb, 0); /* padding */
239     if (!pb->seekable)
240         avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_ISINTERLEAVED);  /* flags */
241     else
242         avio_wl32(pb, AVIF_TRUSTCKTYPE | AVIF_HASINDEX | AVIF_ISINTERLEAVED);  /* flags */
243     avi->frames_hdr_all = avio_tell(pb); /* remember this offset to fill later */
244     avio_wl32(pb, nb_frames); /* nb frames, filled later */
245     avio_wl32(pb, 0); /* initial frame */
246     avio_wl32(pb, s->nb_streams); /* nb streams */
247     avio_wl32(pb, 1024 * 1024); /* suggested buffer size */
248     if (video_enc) {
249         avio_wl32(pb, video_enc->width);
250         avio_wl32(pb, video_enc->height);
251     } else {
252         avio_wl32(pb, 0);
253         avio_wl32(pb, 0);
254     }
255     avio_wl32(pb, 0); /* reserved */
256     avio_wl32(pb, 0); /* reserved */
257     avio_wl32(pb, 0); /* reserved */
258     avio_wl32(pb, 0); /* reserved */
259
260     /* stream list */
261     for (i = 0; i < n; i++) {
262         AVStream *st = s->streams[i];
263         AVCodecContext *enc = st->codec;
264         AVIStream *avist = st->priv_data;
265         list2 = ff_start_tag(pb, "LIST");
266         ffio_wfourcc(pb, "strl");
267
268         /* stream generic header */
269         strh = ff_start_tag(pb, "strh");
270         switch (enc->codec_type) {
271         case AVMEDIA_TYPE_SUBTITLE:
272             // XSUB subtitles behave like video tracks, other subtitles
273             // are not (yet) supported.
274             if (enc->codec_id != AV_CODEC_ID_XSUB) {
275                 av_log(s, AV_LOG_ERROR,
276                        "Subtitle streams other than DivX XSUB are not supported by the AVI muxer.\n");
277                 return AVERROR_PATCHWELCOME;
278             }
279         case AVMEDIA_TYPE_VIDEO:
280             ffio_wfourcc(pb, "vids");
281             break;
282         case AVMEDIA_TYPE_AUDIO:
283             ffio_wfourcc(pb, "auds");
284             break;
285 //      case AVMEDIA_TYPE_TEXT:
286 //          ffio_wfourcc(pb, "txts");
287 //          break;
288         case AVMEDIA_TYPE_DATA:
289             ffio_wfourcc(pb, "dats");
290             break;
291         }
292         if (enc->codec_type == AVMEDIA_TYPE_VIDEO ||
293             enc->codec_id == AV_CODEC_ID_XSUB)
294             avio_wl32(pb, enc->codec_tag);
295         else
296             avio_wl32(pb, 1);
297         avio_wl32(pb, 0); /* flags */
298         avio_wl16(pb, 0); /* priority */
299         avio_wl16(pb, 0); /* language */
300         avio_wl32(pb, 0); /* initial frame */
301
302         ff_parse_specific_params(st, &au_byterate, &au_ssize, &au_scale);
303
304         if (   enc->codec_type == AVMEDIA_TYPE_VIDEO
305             && enc->codec_id != AV_CODEC_ID_XSUB
306             && au_byterate > 1000LL*au_scale) {
307             au_byterate = 600;
308             au_scale    = 1;
309         }
310         avpriv_set_pts_info(st, 64, au_scale, au_byterate);
311         if (enc->codec_id == AV_CODEC_ID_XSUB)
312             au_scale = au_byterate = 0;
313
314         avio_wl32(pb, au_scale); /* scale */
315         avio_wl32(pb, au_byterate); /* rate */
316
317         avio_wl32(pb, 0); /* start */
318         /* remember this offset to fill later */
319         avist->frames_hdr_strm = avio_tell(pb);
320         if (!pb->seekable)
321             /* FIXME: this may be broken, but who cares */
322             avio_wl32(pb, AVI_MAX_RIFF_SIZE);
323         else
324             avio_wl32(pb, 0);  /* length, XXX: filled later */
325
326         /* suggested buffer size, is set to largest chunk size in avi_write_trailer */
327         if (enc->codec_type == AVMEDIA_TYPE_VIDEO)
328             avio_wl32(pb, 1024 * 1024);
329         else if (enc->codec_type == AVMEDIA_TYPE_AUDIO)
330             avio_wl32(pb, 12 * 1024);
331         else
332             avio_wl32(pb, 0);
333         avio_wl32(pb, -1); /* quality */
334         avio_wl32(pb, au_ssize); /* sample size */
335         avio_wl32(pb, 0);
336         avio_wl16(pb, enc->width);
337         avio_wl16(pb, enc->height);
338         ff_end_tag(pb, strh);
339
340         if (enc->codec_type != AVMEDIA_TYPE_DATA) {
341             int ret;
342             enum AVPixelFormat pix_fmt;
343
344             strf = ff_start_tag(pb, "strf");
345             switch (enc->codec_type) {
346             case AVMEDIA_TYPE_SUBTITLE:
347                 /* XSUB subtitles behave like video tracks, other subtitles
348                  * are not (yet) supported. */
349                 if (enc->codec_id != AV_CODEC_ID_XSUB)
350                     break;
351             case AVMEDIA_TYPE_VIDEO:
352                 /* WMP expects RGB 5:5:5 rawvideo in avi to have bpp set to 16. */
353                 if (  !enc->codec_tag
354                     && enc->codec_id == AV_CODEC_ID_RAWVIDEO
355                     && enc->pix_fmt == AV_PIX_FMT_RGB555LE
356                     && enc->bits_per_coded_sample == 15)
357                     enc->bits_per_coded_sample = 16;
358                 ff_put_bmp_header(pb, enc, ff_codec_bmp_tags, 0, 0);
359                 pix_fmt = avpriv_find_pix_fmt(avpriv_pix_fmt_bps_avi,
360                                               enc->bits_per_coded_sample);
361                 if (   !enc->codec_tag
362                     && enc->codec_id == AV_CODEC_ID_RAWVIDEO
363                     && enc->pix_fmt != pix_fmt
364                     && enc->pix_fmt != AV_PIX_FMT_NONE)
365                     av_log(s, AV_LOG_ERROR, "%s rawvideo cannot be written to avi, output file will be unreadable\n",
366                           av_get_pix_fmt_name(enc->pix_fmt));
367                 break;
368             case AVMEDIA_TYPE_AUDIO:
369                 if ((ret = ff_put_wav_header(pb, enc, 0)) < 0)
370                     return ret;
371                 break;
372             default:
373                 av_log(s, AV_LOG_ERROR,
374                     "Invalid or not supported codec type '%s' found in the input\n",
375                     (char *)av_x_if_null(av_get_media_type_string(enc->codec_type), "?"));
376                 return AVERROR(EINVAL);
377             }
378             ff_end_tag(pb, strf);
379             if ((t = av_dict_get(st->metadata, "title", NULL, 0))) {
380                 ff_riff_write_info_tag(s->pb, "strn", t->value);
381                 t = NULL;
382             }
383             if (enc->codec_id == AV_CODEC_ID_XSUB
384             && (t = av_dict_get(s->streams[i]->metadata, "language", NULL, 0))) {
385                 const char* langstr = av_convert_lang_to(t->value, AV_LANG_ISO639_1);
386                 t = NULL;
387                 if (langstr) {
388                     char* str = av_asprintf("Subtitle - %s-xx;02", langstr);
389                     ff_riff_write_info_tag(s->pb, "strn", str);
390                     av_free(str);
391                 }
392             }
393         }
394
395         if (pb->seekable) {
396             write_odml_master(s, i);
397         }
398
399         if (enc->codec_type == AVMEDIA_TYPE_VIDEO   &&
400             st->sample_aspect_ratio.num > 0 &&
401             st->sample_aspect_ratio.den > 0) {
402             int vprp       = ff_start_tag(pb, "vprp");
403             AVRational dar = av_mul_q(st->sample_aspect_ratio,
404                                       (AVRational) { enc->width,
405                                                      enc->height });
406             int num, den;
407             av_reduce(&num, &den, dar.num, dar.den, 0xFFFF);
408
409             avio_wl32(pb, 0); // video format   = unknown
410             avio_wl32(pb, 0); // video standard = unknown
411             // TODO: should be avg_frame_rate
412             avio_wl32(pb, lrintf(1.0 / av_q2d(st->time_base)));
413             avio_wl32(pb, enc->width);
414             avio_wl32(pb, enc->height);
415             avio_wl16(pb, den);
416             avio_wl16(pb, num);
417             avio_wl32(pb, enc->width);
418             avio_wl32(pb, enc->height);
419             avio_wl32(pb, 1); // progressive FIXME
420
421             avio_wl32(pb, enc->height);
422             avio_wl32(pb, enc->width);
423             avio_wl32(pb, enc->height);
424             avio_wl32(pb, enc->width);
425             avio_wl32(pb, 0);
426             avio_wl32(pb, 0);
427
428             avio_wl32(pb, 0);
429             avio_wl32(pb, 0);
430             ff_end_tag(pb, vprp);
431         }
432
433         ff_end_tag(pb, list2);
434     }
435
436     if (pb->seekable) {
437         /* AVI could become an OpenDML one, if it grows beyond 2Gb range */
438         avi->odml_list = ff_start_tag(pb, "JUNK");
439         ffio_wfourcc(pb, "odml");
440         ffio_wfourcc(pb, "dmlh");
441         avio_wl32(pb, 248);
442         for (i = 0; i < 248; i += 4)
443             avio_wl32(pb, 0);
444         ff_end_tag(pb, avi->odml_list);
445     }
446
447     ff_end_tag(pb, list1);
448
449     ff_riff_write_info(s);
450
451
452     padding = s->metadata_header_padding;
453     if (padding < 0)
454         padding = 1016;
455
456     /* some padding for easier tag editing */
457     if (padding) {
458         list2 = ff_start_tag(pb, "JUNK");
459         for (i = padding; i > 0; i -= 4)
460             avio_wl32(pb, 0);
461         ff_end_tag(pb, list2);
462     }
463
464     avi->movi_list = ff_start_tag(pb, "LIST");
465     ffio_wfourcc(pb, "movi");
466
467     avio_flush(pb);
468
469     return 0;
470 }
471
472 static int avi_write_ix(AVFormatContext *s)
473 {
474     AVIOContext *pb = s->pb;
475     AVIContext *avi = s->priv_data;
476     char tag[5];
477     char ix_tag[] = "ix00";
478     int i, j;
479
480     av_assert0(pb->seekable);
481
482     if (avi->riff_id > AVI_MASTER_INDEX_SIZE) {
483         av_log(s, AV_LOG_ERROR, "Invalid riff index %d > %d\n",
484                avi->riff_id, AVI_MASTER_INDEX_SIZE);
485         return AVERROR(EINVAL);
486     }
487
488     for (i = 0; i < s->nb_streams; i++) {
489         AVIStream *avist = s->streams[i]->priv_data;
490         int64_t ix, pos;
491         int au_byterate, au_ssize, au_scale;
492
493         avi_stream2fourcc(tag, i, s->streams[i]->codec->codec_type);
494         ix_tag[3] = '0' + i;
495
496         /* Writing AVI OpenDML leaf index chunk */
497         ix = avio_tell(pb);
498         ffio_wfourcc(pb, ix_tag);      /* ix?? */
499         avio_wl32(pb, avist->indexes.entry * 8 + 24);
500         /* chunk size */
501         avio_wl16(pb, 2);           /* wLongsPerEntry */
502         avio_w8(pb, 0);             /* bIndexSubType (0 == frame index) */
503         avio_w8(pb, 1);             /* bIndexType (1 == AVI_INDEX_OF_CHUNKS) */
504         avio_wl32(pb, avist->indexes.entry);
505         /* nEntriesInUse */
506         ffio_wfourcc(pb, tag);         /* dwChunkId */
507         avio_wl64(pb, avi->movi_list); /* qwBaseOffset */
508         avio_wl32(pb, 0);              /* dwReserved_3 (must be 0) */
509
510         for (j = 0; j < avist->indexes.entry; j++) {
511             AVIIentry *ie = avi_get_ientry(&avist->indexes, j);
512             avio_wl32(pb, ie->pos + 8);
513             avio_wl32(pb, ((uint32_t) ie->len & ~0x80000000) |
514                           (ie->flags & 0x10 ? 0 : 0x80000000));
515         }
516         avio_flush(pb);
517         pos = avio_tell(pb);
518
519         /* Updating one entry in the AVI OpenDML master index */
520         avio_seek(pb, avist->indexes.indx_start - 8, SEEK_SET);
521         ffio_wfourcc(pb, "indx");             /* enabling this entry */
522         avio_skip(pb, 8);
523         avio_wl32(pb, avi->riff_id);          /* nEntriesInUse */
524         avio_skip(pb, 16 * avi->riff_id);
525         avio_wl64(pb, ix);                    /* qwOffset */
526         avio_wl32(pb, pos - ix);              /* dwSize */
527         ff_parse_specific_params(s->streams[i], &au_byterate, &au_ssize, &au_scale);
528         if (s->streams[i]->codec->codec_type == AVMEDIA_TYPE_AUDIO && au_ssize > 0) {
529             uint32_t audio_segm_size = (avist->audio_strm_length - avist->indexes.audio_strm_offset);
530             if ((audio_segm_size % au_ssize > 0) && !avist->sample_requested) {
531                 avpriv_request_sample(s, "OpenDML index duration for audio packets with partial frames");
532                 avist->sample_requested = 1;
533             }
534             avio_wl32(pb, audio_segm_size / au_ssize);  /* dwDuration (sample count) */
535         } else
536             avio_wl32(pb, avist->indexes.entry);  /* dwDuration (packet count) */
537
538         avio_seek(pb, pos, SEEK_SET);
539     }
540     return 0;
541 }
542
543 static int avi_write_idx1(AVFormatContext *s)
544 {
545     AVIOContext *pb = s->pb;
546     AVIContext *avi = s->priv_data;
547     int64_t idx_chunk;
548     int i;
549     char tag[5];
550
551     if (pb->seekable) {
552         AVIStream *avist;
553         AVIIentry *ie = 0, *tie;
554         int empty, stream_id = -1;
555
556         idx_chunk = ff_start_tag(pb, "idx1");
557         for (i = 0; i < s->nb_streams; i++) {
558             avist        = s->streams[i]->priv_data;
559             avist->entry = 0;
560         }
561
562         do {
563             empty = 1;
564             for (i = 0; i < s->nb_streams; i++) {
565                 avist = s->streams[i]->priv_data;
566                 if (avist->indexes.entry <= avist->entry)
567                     continue;
568
569                 tie = avi_get_ientry(&avist->indexes, avist->entry);
570                 if (empty || tie->pos < ie->pos) {
571                     ie        = tie;
572                     stream_id = i;
573                 }
574                 empty = 0;
575             }
576             if (!empty) {
577                 avist = s->streams[stream_id]->priv_data;
578                 avi_stream2fourcc(tag, stream_id,
579                                   s->streams[stream_id]->codec->codec_type);
580                 ffio_wfourcc(pb, tag);
581                 avio_wl32(pb, ie->flags);
582                 avio_wl32(pb, ie->pos);
583                 avio_wl32(pb, ie->len);
584                 avist->entry++;
585             }
586         } while (!empty);
587         ff_end_tag(pb, idx_chunk);
588
589         avi_write_counters(s, avi->riff_id);
590     }
591     return 0;
592 }
593
594 static int write_skip_frames(AVFormatContext *s, int stream_index, int64_t dts)
595 {
596     AVIStream *avist    = s->streams[stream_index]->priv_data;
597     AVCodecContext *enc = s->streams[stream_index]->codec;
598
599     av_dlog(s, "dts:%s packet_count:%d stream_index:%d\n", av_ts2str(dts), avist->packet_count, stream_index);
600     while (enc->block_align == 0 && dts != AV_NOPTS_VALUE &&
601            dts > avist->packet_count && enc->codec_id != AV_CODEC_ID_XSUB && avist->packet_count) {
602         AVPacket empty_packet;
603
604         if (dts - avist->packet_count > 60000) {
605             av_log(s, AV_LOG_ERROR, "Too large number of skipped frames %"PRId64" > 60000\n", dts - avist->packet_count);
606             return AVERROR(EINVAL);
607         }
608
609         av_init_packet(&empty_packet);
610         empty_packet.size         = 0;
611         empty_packet.data         = NULL;
612         empty_packet.stream_index = stream_index;
613         avi_write_packet(s, &empty_packet);
614         av_dlog(s, "dup dts:%s packet_count:%d\n", av_ts2str(dts), avist->packet_count);
615     }
616
617     return 0;
618 }
619
620 static int avi_write_packet(AVFormatContext *s, AVPacket *pkt)
621 {
622     unsigned char tag[5];
623     unsigned int flags = 0;
624     const int stream_index = pkt->stream_index;
625     int size               = pkt->size;
626     AVIContext *avi     = s->priv_data;
627     AVIOContext *pb     = s->pb;
628     AVIStream *avist    = s->streams[stream_index]->priv_data;
629     AVCodecContext *enc = s->streams[stream_index]->codec;
630     int ret;
631
632     if (enc->codec_id == AV_CODEC_ID_H264 && enc->codec_tag == MKTAG('H','2','6','4') && pkt->size) {
633         ret = ff_check_h264_startcode(s, s->streams[stream_index], pkt);
634         if (ret < 0)
635             return ret;
636     }
637
638     if ((ret = write_skip_frames(s, stream_index, pkt->dts)) < 0)
639         return ret;
640
641     if (pkt->dts != AV_NOPTS_VALUE)
642         avist->last_dts = pkt->dts + pkt->duration;
643
644     avist->packet_count++;
645
646     // Make sure to put an OpenDML chunk when the file size exceeds the limits
647     if (pb->seekable &&
648         (avio_tell(pb) - avi->riff_start > AVI_MAX_RIFF_SIZE)) {
649         avi_write_ix(s);
650         ff_end_tag(pb, avi->movi_list);
651
652         if (avi->riff_id == 1)
653             avi_write_idx1(s);
654
655         ff_end_tag(pb, avi->riff_start);
656         avi->movi_list = avi_start_new_riff(s, pb, "AVIX", "movi");
657     }
658
659     avi_stream2fourcc(tag, stream_index, enc->codec_type);
660     if (pkt->flags & AV_PKT_FLAG_KEY)
661         flags = 0x10;
662     if (enc->codec_type == AVMEDIA_TYPE_AUDIO)
663         avist->audio_strm_length += size;
664
665     if (s->pb->seekable) {
666         AVIIndex *idx = &avist->indexes;
667         int cl = idx->entry / AVI_INDEX_CLUSTER_SIZE;
668         int id = idx->entry % AVI_INDEX_CLUSTER_SIZE;
669         if (idx->ents_allocated <= idx->entry) {
670             idx->cluster = av_realloc_f(idx->cluster, sizeof(void*), cl+1);
671             if (!idx->cluster) {
672                 idx->ents_allocated = 0;
673                 idx->entry          = 0;
674                 return AVERROR(ENOMEM);
675             }
676             idx->cluster[cl] =
677                 av_malloc(AVI_INDEX_CLUSTER_SIZE * sizeof(AVIIentry));
678             if (!idx->cluster[cl])
679                 return AVERROR(ENOMEM);
680             idx->ents_allocated += AVI_INDEX_CLUSTER_SIZE;
681         }
682
683         idx->cluster[cl][id].flags = flags;
684         idx->cluster[cl][id].pos   = avio_tell(pb) - avi->movi_list;
685         idx->cluster[cl][id].len   = size;
686         avist->max_size = FFMAX(avist->max_size, size);
687         idx->entry++;
688     }
689
690     avio_write(pb, tag, 4);
691     avio_wl32(pb, size);
692     avio_write(pb, pkt->data, size);
693     if (size & 1)
694         avio_w8(pb, 0);
695
696     return 0;
697 }
698
699 static int avi_write_trailer(AVFormatContext *s)
700 {
701     AVIContext *avi = s->priv_data;
702     AVIOContext *pb = s->pb;
703     int res = 0;
704     int i, j, n, nb_frames;
705     int64_t file_size;
706
707     for (i = 0; i < s->nb_streams; i++) {
708         AVIStream *avist = s->streams[i]->priv_data;
709         write_skip_frames(s, i, avist->last_dts);
710     }
711
712     if (pb->seekable) {
713         if (avi->riff_id == 1) {
714             ff_end_tag(pb, avi->movi_list);
715             res = avi_write_idx1(s);
716             ff_end_tag(pb, avi->riff_start);
717         } else {
718             avi_write_ix(s);
719             ff_end_tag(pb, avi->movi_list);
720             ff_end_tag(pb, avi->riff_start);
721
722             file_size = avio_tell(pb);
723             avio_seek(pb, avi->odml_list - 8, SEEK_SET);
724             ffio_wfourcc(pb, "LIST"); /* Making this AVI OpenDML one */
725             avio_skip(pb, 16);
726
727             for (n = nb_frames = 0; n < s->nb_streams; n++) {
728                 AVCodecContext *stream = s->streams[n]->codec;
729                 AVIStream *avist       = s->streams[n]->priv_data;
730
731                 if (stream->codec_type == AVMEDIA_TYPE_VIDEO) {
732                     if (nb_frames < avist->packet_count)
733                         nb_frames = avist->packet_count;
734                 } else {
735                     if (stream->codec_id == AV_CODEC_ID_MP2 ||
736                         stream->codec_id == AV_CODEC_ID_MP3)
737                         nb_frames += avist->packet_count;
738                 }
739             }
740             avio_wl32(pb, nb_frames);
741             avio_seek(pb, file_size, SEEK_SET);
742
743             avi_write_counters(s, avi->riff_id);
744         }
745     }
746
747     for (i = 0; i < s->nb_streams; i++) {
748         AVIStream *avist = s->streams[i]->priv_data;
749         for (j = 0; j < avist->indexes.ents_allocated / AVI_INDEX_CLUSTER_SIZE; j++)
750             av_freep(&avist->indexes.cluster[j]);
751         av_freep(&avist->indexes.cluster);
752         avist->indexes.ents_allocated = avist->indexes.entry = 0;
753         if (pb->seekable) {
754             avio_seek(pb, avist->frames_hdr_strm + 4, SEEK_SET);
755             avio_wl32(pb, avist->max_size);
756         }
757     }
758
759     return res;
760 }
761
762 AVOutputFormat ff_avi_muxer = {
763     .name           = "avi",
764     .long_name      = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
765     .mime_type      = "video/x-msvideo",
766     .extensions     = "avi",
767     .priv_data_size = sizeof(AVIContext),
768     .audio_codec    = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_AC3,
769     .video_codec    = AV_CODEC_ID_MPEG4,
770     .write_header   = avi_write_header,
771     .write_packet   = avi_write_packet,
772     .write_trailer  = avi_write_trailer,
773     .codec_tag      = (const AVCodecTag * const []) {
774         ff_codec_bmp_tags, ff_codec_wav_tags, 0
775     },
776 };