]> git.sesse.net Git - ffmpeg/blob - libavformat/flvenc.c
avformat/flvenc: add FLVFlags for flvflags options
[ffmpeg] / libavformat / flvenc.c
1 /*
2  * FLV muxer
3  * Copyright (c) 2003 The FFmpeg Project
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 #include "libavutil/intreadwrite.h"
23 #include "libavutil/dict.h"
24 #include "libavutil/intfloat.h"
25 #include "libavutil/avassert.h"
26 #include "libavutil/mathematics.h"
27 #include "avc.h"
28 #include "avformat.h"
29 #include "flv.h"
30 #include "internal.h"
31 #include "metadata.h"
32 #include "libavutil/opt.h"
33 #include "libavcodec/put_bits.h"
34 #include "libavcodec/aacenctab.h"
35
36
37 static const AVCodecTag flv_video_codec_ids[] = {
38     { AV_CODEC_ID_FLV1,     FLV_CODECID_H263 },
39     { AV_CODEC_ID_H263,     FLV_CODECID_REALH263 },
40     { AV_CODEC_ID_MPEG4,    FLV_CODECID_MPEG4 },
41     { AV_CODEC_ID_FLASHSV,  FLV_CODECID_SCREEN },
42     { AV_CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2 },
43     { AV_CODEC_ID_VP6F,     FLV_CODECID_VP6 },
44     { AV_CODEC_ID_VP6,      FLV_CODECID_VP6 },
45     { AV_CODEC_ID_VP6A,     FLV_CODECID_VP6A },
46     { AV_CODEC_ID_H264,     FLV_CODECID_H264 },
47     { AV_CODEC_ID_NONE,     0 }
48 };
49
50 static const AVCodecTag flv_audio_codec_ids[] = {
51     { AV_CODEC_ID_MP3,        FLV_CODECID_MP3        >> FLV_AUDIO_CODECID_OFFSET },
52     { AV_CODEC_ID_PCM_U8,     FLV_CODECID_PCM        >> FLV_AUDIO_CODECID_OFFSET },
53     { AV_CODEC_ID_PCM_S16BE,  FLV_CODECID_PCM        >> FLV_AUDIO_CODECID_OFFSET },
54     { AV_CODEC_ID_PCM_S16LE,  FLV_CODECID_PCM_LE     >> FLV_AUDIO_CODECID_OFFSET },
55     { AV_CODEC_ID_ADPCM_SWF,  FLV_CODECID_ADPCM      >> FLV_AUDIO_CODECID_OFFSET },
56     { AV_CODEC_ID_AAC,        FLV_CODECID_AAC        >> FLV_AUDIO_CODECID_OFFSET },
57     { AV_CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET },
58     { AV_CODEC_ID_PCM_MULAW,  FLV_CODECID_PCM_MULAW  >> FLV_AUDIO_CODECID_OFFSET },
59     { AV_CODEC_ID_PCM_ALAW,   FLV_CODECID_PCM_ALAW   >> FLV_AUDIO_CODECID_OFFSET },
60     { AV_CODEC_ID_SPEEX,      FLV_CODECID_SPEEX      >> FLV_AUDIO_CODECID_OFFSET },
61     { AV_CODEC_ID_NONE,       0 }
62 };
63
64 typedef enum {
65     FLV_AAC_SEQ_HEADER_DETECT = (1 << 0),
66 } FLVFlags;
67
68 typedef struct FLVContext {
69     AVClass *av_class;
70     int     reserved;
71     int64_t duration_offset;
72     int64_t filesize_offset;
73     int64_t duration;
74     int64_t delay;      ///< first dts delay (needed for AVC & Speex)
75
76     AVCodecParameters *audio_par;
77     AVCodecParameters *video_par;
78     double framerate;
79     AVCodecParameters *data_par;
80
81     int flags;
82 } FLVContext;
83
84 typedef struct FLVStreamContext {
85     int64_t last_ts;    ///< last timestamp for each stream
86 } FLVStreamContext;
87
88 static int get_audio_flags(AVFormatContext *s, AVCodecParameters *par)
89 {
90     int flags = (par->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT
91                                                    : FLV_SAMPLESSIZE_8BIT;
92
93     if (par->codec_id == AV_CODEC_ID_AAC) // specs force these parameters
94         return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ |
95                FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
96     else if (par->codec_id == AV_CODEC_ID_SPEEX) {
97         if (par->sample_rate != 16000) {
98             av_log(s, AV_LOG_ERROR,
99                    "FLV only supports wideband (16kHz) Speex audio\n");
100             return AVERROR(EINVAL);
101         }
102         if (par->channels != 1) {
103             av_log(s, AV_LOG_ERROR, "FLV only supports mono Speex audio\n");
104             return AVERROR(EINVAL);
105         }
106         return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
107     } else {
108         switch (par->sample_rate) {
109         case 44100:
110             flags |= FLV_SAMPLERATE_44100HZ;
111             break;
112         case 22050:
113             flags |= FLV_SAMPLERATE_22050HZ;
114             break;
115         case 11025:
116             flags |= FLV_SAMPLERATE_11025HZ;
117             break;
118         case 16000: // nellymoser only
119         case  8000: // nellymoser only
120         case  5512: // not MP3
121             if (par->codec_id != AV_CODEC_ID_MP3) {
122                 flags |= FLV_SAMPLERATE_SPECIAL;
123                 break;
124             }
125         default:
126             av_log(s, AV_LOG_ERROR,
127                    "FLV does not support sample rate %d, "
128                    "choose from (44100, 22050, 11025)\n", par->sample_rate);
129             return AVERROR(EINVAL);
130         }
131     }
132
133     if (par->channels > 1)
134         flags |= FLV_STEREO;
135
136     switch (par->codec_id) {
137     case AV_CODEC_ID_MP3:
138         flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
139         break;
140     case AV_CODEC_ID_PCM_U8:
141         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
142         break;
143     case AV_CODEC_ID_PCM_S16BE:
144         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
145         break;
146     case AV_CODEC_ID_PCM_S16LE:
147         flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
148         break;
149     case AV_CODEC_ID_ADPCM_SWF:
150         flags |= FLV_CODECID_ADPCM  | FLV_SAMPLESSIZE_16BIT;
151         break;
152     case AV_CODEC_ID_NELLYMOSER:
153         if (par->sample_rate == 8000)
154             flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO  | FLV_SAMPLESSIZE_16BIT;
155         else if (par->sample_rate == 16000)
156             flags |= FLV_CODECID_NELLYMOSER_16KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
157         else
158             flags |= FLV_CODECID_NELLYMOSER            | FLV_SAMPLESSIZE_16BIT;
159         break;
160     case AV_CODEC_ID_PCM_MULAW:
161         flags = FLV_CODECID_PCM_MULAW | FLV_SAMPLERATE_SPECIAL | FLV_SAMPLESSIZE_16BIT;
162         break;
163     case AV_CODEC_ID_PCM_ALAW:
164         flags = FLV_CODECID_PCM_ALAW  | FLV_SAMPLERATE_SPECIAL | FLV_SAMPLESSIZE_16BIT;
165         break;
166     case 0:
167         flags |= par->codec_tag << 4;
168         break;
169     default:
170         av_log(s, AV_LOG_ERROR, "Audio codec '%s' not compatible with FLV\n",
171                avcodec_get_name(par->codec_id));
172         return AVERROR(EINVAL);
173     }
174
175     return flags;
176 }
177
178 static void put_amf_string(AVIOContext *pb, const char *str)
179 {
180     size_t len = strlen(str);
181     avio_wb16(pb, len);
182     avio_write(pb, str, len);
183 }
184
185 static void put_avc_eos_tag(AVIOContext *pb, unsigned ts)
186 {
187     avio_w8(pb, FLV_TAG_TYPE_VIDEO);
188     avio_wb24(pb, 5);               /* Tag Data Size */
189     avio_wb24(pb, ts);              /* lower 24 bits of timestamp in ms */
190     avio_w8(pb, (ts >> 24) & 0x7F); /* MSB of ts in ms */
191     avio_wb24(pb, 0);               /* StreamId = 0 */
192     avio_w8(pb, 23);                /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
193     avio_w8(pb, 2);                 /* AVC end of sequence */
194     avio_wb24(pb, 0);               /* Always 0 for AVC EOS. */
195     avio_wb32(pb, 16);              /* Size of FLV tag */
196 }
197
198 static void put_amf_double(AVIOContext *pb, double d)
199 {
200     avio_w8(pb, AMF_DATA_TYPE_NUMBER);
201     avio_wb64(pb, av_double2int(d));
202 }
203
204 static void put_amf_bool(AVIOContext *pb, int b)
205 {
206     avio_w8(pb, AMF_DATA_TYPE_BOOL);
207     avio_w8(pb, !!b);
208 }
209
210 static void write_metadata(AVFormatContext *s, unsigned int ts)
211 {
212     AVIOContext *pb = s->pb;
213     FLVContext *flv = s->priv_data;
214     int metadata_count = 0;
215     int64_t metadata_size_pos, data_size, metadata_count_pos;
216     AVDictionaryEntry *tag = NULL;
217
218     /* write meta_tag */
219     avio_w8(pb, 18);            // tag type META
220     metadata_size_pos = avio_tell(pb);
221     avio_wb24(pb, 0);           // size of data part (sum of all parts below)
222     avio_wb24(pb, ts);          // timestamp
223     avio_wb32(pb, 0);           // reserved
224
225     /* now data of data_size size */
226
227     /* first event name as a string */
228     avio_w8(pb, AMF_DATA_TYPE_STRING);
229     put_amf_string(pb, "onMetaData"); // 12 bytes
230
231     /* mixed array (hash) with size and string/type/data tuples */
232     avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
233     metadata_count_pos = avio_tell(pb);
234     metadata_count = 4 * !!flv->video_par +
235                      5 * !!flv->audio_par +
236                      1 * !!flv->data_par  +
237                      2; // +2 for duration and file size
238
239     avio_wb32(pb, metadata_count);
240
241     put_amf_string(pb, "duration");
242     flv->duration_offset = avio_tell(pb);
243
244     // fill in the guessed duration, it'll be corrected later if incorrect
245     put_amf_double(pb, s->duration / AV_TIME_BASE);
246
247     if (flv->video_par) {
248         put_amf_string(pb, "width");
249         put_amf_double(pb, flv->video_par->width);
250
251         put_amf_string(pb, "height");
252         put_amf_double(pb, flv->video_par->height);
253
254         put_amf_string(pb, "videodatarate");
255         put_amf_double(pb, flv->video_par->bit_rate / 1024.0);
256
257         if (flv->framerate != 0.0) {
258             put_amf_string(pb, "framerate");
259             put_amf_double(pb, flv->framerate);
260             metadata_count++;
261         }
262
263         put_amf_string(pb, "videocodecid");
264         put_amf_double(pb, flv->video_par->codec_tag);
265     }
266
267     if (flv->audio_par) {
268         put_amf_string(pb, "audiodatarate");
269         put_amf_double(pb, flv->audio_par->bit_rate / 1024.0);
270
271         put_amf_string(pb, "audiosamplerate");
272         put_amf_double(pb, flv->audio_par->sample_rate);
273
274         put_amf_string(pb, "audiosamplesize");
275         put_amf_double(pb, flv->audio_par->codec_id == AV_CODEC_ID_PCM_U8 ? 8 : 16);
276
277         put_amf_string(pb, "stereo");
278         put_amf_bool(pb, flv->audio_par->channels == 2);
279
280         put_amf_string(pb, "audiocodecid");
281         put_amf_double(pb, flv->audio_par->codec_tag);
282     }
283
284     if (flv->data_par) {
285         put_amf_string(pb, "datastream");
286         put_amf_double(pb, 0.0);
287     }
288
289     ff_standardize_creation_time(s);
290     while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
291         if(   !strcmp(tag->key, "width")
292             ||!strcmp(tag->key, "height")
293             ||!strcmp(tag->key, "videodatarate")
294             ||!strcmp(tag->key, "framerate")
295             ||!strcmp(tag->key, "videocodecid")
296             ||!strcmp(tag->key, "audiodatarate")
297             ||!strcmp(tag->key, "audiosamplerate")
298             ||!strcmp(tag->key, "audiosamplesize")
299             ||!strcmp(tag->key, "stereo")
300             ||!strcmp(tag->key, "audiocodecid")
301             ||!strcmp(tag->key, "duration")
302             ||!strcmp(tag->key, "onMetaData")
303             ||!strcmp(tag->key, "datasize")
304             ||!strcmp(tag->key, "lasttimestamp")
305             ||!strcmp(tag->key, "totalframes")
306             ||!strcmp(tag->key, "hasAudio")
307             ||!strcmp(tag->key, "hasVideo")
308             ||!strcmp(tag->key, "hasCuePoints")
309             ||!strcmp(tag->key, "hasMetadata")
310             ||!strcmp(tag->key, "hasKeyframes")
311         ){
312             av_log(s, AV_LOG_DEBUG, "Ignoring metadata for %s\n", tag->key);
313             continue;
314         }
315         put_amf_string(pb, tag->key);
316         avio_w8(pb, AMF_DATA_TYPE_STRING);
317         put_amf_string(pb, tag->value);
318         metadata_count++;
319     }
320
321     put_amf_string(pb, "filesize");
322     flv->filesize_offset = avio_tell(pb);
323     put_amf_double(pb, 0); // delayed write
324
325     put_amf_string(pb, "");
326     avio_w8(pb, AMF_END_OF_OBJECT);
327
328     /* write total size of tag */
329     data_size = avio_tell(pb) - metadata_size_pos - 10;
330
331     avio_seek(pb, metadata_count_pos, SEEK_SET);
332     avio_wb32(pb, metadata_count);
333
334     avio_seek(pb, metadata_size_pos, SEEK_SET);
335     avio_wb24(pb, data_size);
336     avio_skip(pb, data_size + 10 - 3);
337     avio_wb32(pb, data_size + 11);
338 }
339
340 static int unsupported_codec(AVFormatContext *s,
341                              const char* type, int codec_id)
342 {
343     const AVCodecDescriptor *desc = avcodec_descriptor_get(codec_id);
344     av_log(s, AV_LOG_ERROR,
345            "%s codec %s not compatible with flv\n",
346             type,
347             desc ? desc->name : "unknown");
348     return AVERROR(ENOSYS);
349 }
350
351 static void flv_write_codec_header(AVFormatContext* s, AVCodecParameters* par) {
352     int64_t data_size;
353     AVIOContext *pb = s->pb;
354     FLVContext *flv = s->priv_data;
355
356     if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264
357             || par->codec_id == AV_CODEC_ID_MPEG4) {
358         int64_t pos;
359         avio_w8(pb,
360                 par->codec_type == AVMEDIA_TYPE_VIDEO ?
361                         FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
362         avio_wb24(pb, 0); // size patched later
363         avio_wb24(pb, 0); // ts
364         avio_w8(pb, 0);   // ts ext
365         avio_wb24(pb, 0); // streamid
366         pos = avio_tell(pb);
367         if (par->codec_id == AV_CODEC_ID_AAC) {
368             avio_w8(pb, get_audio_flags(s, par));
369             avio_w8(pb, 0); // AAC sequence header
370
371             if (!par->extradata_size && flv->flags & FLV_AAC_SEQ_HEADER_DETECT) {
372                 PutBitContext pbc;
373                 int samplerate_index;
374                 int channels = flv->audio_par->channels
375                         - (flv->audio_par->channels == 8 ? 1 : 0);
376                 uint8_t data[2];
377
378                 for (samplerate_index = 0; samplerate_index < 16;
379                         samplerate_index++)
380                     if (flv->audio_par->sample_rate
381                             == mpeg4audio_sample_rates[samplerate_index])
382                         break;
383
384                 init_put_bits(&pbc, data, sizeof(data));
385                 put_bits(&pbc, 5, flv->audio_par->profile + 1); //profile
386                 put_bits(&pbc, 4, samplerate_index); //sample rate index
387                 put_bits(&pbc, 4, channels);
388                 put_bits(&pbc, 1, 0); //frame length - 1024 samples
389                 put_bits(&pbc, 1, 0); //does not depend on core coder
390                 put_bits(&pbc, 1, 0); //is not extension
391                 flush_put_bits(&pbc);
392
393                 avio_w8(pb, data[0]);
394                 avio_w8(pb, data[1]);
395
396                 av_log(s, AV_LOG_WARNING, "AAC sequence header: %02x %02x.\n",
397                         data[0], data[1]);
398             }
399             avio_write(pb, par->extradata, par->extradata_size);
400         } else {
401             avio_w8(pb, par->codec_tag | FLV_FRAME_KEY); // flags
402             avio_w8(pb, 0); // AVC sequence header
403             avio_wb24(pb, 0); // composition time
404             ff_isom_write_avcc(pb, par->extradata, par->extradata_size);
405         }
406         data_size = avio_tell(pb) - pos;
407         avio_seek(pb, -data_size - 10, SEEK_CUR);
408         avio_wb24(pb, data_size);
409         avio_skip(pb, data_size + 10 - 3);
410         avio_wb32(pb, data_size + 11); // previous tag size
411     }
412 }
413
414 static int flv_write_header(AVFormatContext *s)
415 {
416     int i;
417     AVIOContext *pb = s->pb;
418     FLVContext *flv = s->priv_data;
419
420     for (i = 0; i < s->nb_streams; i++) {
421         AVCodecParameters *par = s->streams[i]->codecpar;
422         FLVStreamContext *sc;
423         switch (par->codec_type) {
424         case AVMEDIA_TYPE_VIDEO:
425             if (s->streams[i]->avg_frame_rate.den &&
426                 s->streams[i]->avg_frame_rate.num) {
427                 flv->framerate = av_q2d(s->streams[i]->avg_frame_rate);
428             }
429             if (flv->video_par) {
430                 av_log(s, AV_LOG_ERROR,
431                        "at most one video stream is supported in flv\n");
432                 return AVERROR(EINVAL);
433             }
434             flv->video_par = par;
435             if (!ff_codec_get_tag(flv_video_codec_ids, par->codec_id))
436                 return unsupported_codec(s, "Video", par->codec_id);
437
438             if (par->codec_id == AV_CODEC_ID_MPEG4 ||
439                 par->codec_id == AV_CODEC_ID_H263) {
440                 int error = s->strict_std_compliance > FF_COMPLIANCE_UNOFFICIAL;
441                 av_log(s, error ? AV_LOG_ERROR : AV_LOG_WARNING,
442                        "Codec %s is not supported in the official FLV specification,\n", avcodec_get_name(par->codec_id));
443
444                 if (error) {
445                     av_log(s, AV_LOG_ERROR,
446                            "use vstrict=-1 / -strict -1 to use it anyway.\n");
447                     return AVERROR(EINVAL);
448                 }
449             } else if (par->codec_id == AV_CODEC_ID_VP6) {
450                 av_log(s, AV_LOG_WARNING,
451                        "Muxing VP6 in flv will produce flipped video on playback.\n");
452             }
453             break;
454         case AVMEDIA_TYPE_AUDIO:
455             if (flv->audio_par) {
456                 av_log(s, AV_LOG_ERROR,
457                        "at most one audio stream is supported in flv\n");
458                 return AVERROR(EINVAL);
459             }
460             flv->audio_par = par;
461             if (get_audio_flags(s, par) < 0)
462                 return unsupported_codec(s, "Audio", par->codec_id);
463             if (par->codec_id == AV_CODEC_ID_PCM_S16BE)
464                 av_log(s, AV_LOG_WARNING,
465                        "16-bit big-endian audio in flv is valid but most likely unplayable (hardware dependent); use s16le\n");
466             break;
467         case AVMEDIA_TYPE_DATA:
468             if (par->codec_id != AV_CODEC_ID_TEXT && par->codec_id != AV_CODEC_ID_NONE)
469                 return unsupported_codec(s, "Data", par->codec_id);
470             flv->data_par = par;
471             break;
472         case AVMEDIA_TYPE_SUBTITLE:
473             if (par->codec_id != AV_CODEC_ID_TEXT) {
474                 av_log(s, AV_LOG_ERROR, "Subtitle codec '%s' for stream %d is not compatible with FLV\n",
475                        avcodec_get_name(par->codec_id), i);
476                 return AVERROR_INVALIDDATA;
477             }
478             flv->data_par = par;
479             break;
480         default:
481             av_log(s, AV_LOG_ERROR, "Codec type '%s' for stream %d is not compatible with FLV\n",
482                    av_get_media_type_string(par->codec_type), i);
483             return AVERROR(EINVAL);
484         }
485         avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
486
487         sc = av_mallocz(sizeof(FLVStreamContext));
488         if (!sc)
489             return AVERROR(ENOMEM);
490         s->streams[i]->priv_data = sc;
491         sc->last_ts = -1;
492     }
493
494     flv->delay = AV_NOPTS_VALUE;
495
496     avio_write(pb, "FLV", 3);
497     avio_w8(pb, 1);
498     avio_w8(pb, FLV_HEADER_FLAG_HASAUDIO * !!flv->audio_par +
499                 FLV_HEADER_FLAG_HASVIDEO * !!flv->video_par);
500     avio_wb32(pb, 9);
501     avio_wb32(pb, 0);
502
503     for (i = 0; i < s->nb_streams; i++)
504         if (s->streams[i]->codecpar->codec_tag == 5) {
505             avio_w8(pb, 8);     // message type
506             avio_wb24(pb, 0);   // include flags
507             avio_wb24(pb, 0);   // time stamp
508             avio_wb32(pb, 0);   // reserved
509             avio_wb32(pb, 11);  // size
510             flv->reserved = 5;
511         }
512
513     write_metadata(s, 0);
514
515     for (i = 0; i < s->nb_streams; i++) {
516         flv_write_codec_header(s, s->streams[i]->codecpar);
517     }
518
519     return 0;
520 }
521
522 static int flv_write_trailer(AVFormatContext *s)
523 {
524     int64_t file_size;
525
526     AVIOContext *pb = s->pb;
527     FLVContext *flv = s->priv_data;
528     int i;
529
530     /* Add EOS tag */
531     for (i = 0; i < s->nb_streams; i++) {
532         AVCodecParameters *par = s->streams[i]->codecpar;
533         FLVStreamContext *sc = s->streams[i]->priv_data;
534         if (par->codec_type == AVMEDIA_TYPE_VIDEO &&
535                 (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4))
536             put_avc_eos_tag(pb, sc->last_ts);
537     }
538
539     file_size = avio_tell(pb);
540
541     /* update information */
542     if (avio_seek(pb, flv->duration_offset, SEEK_SET) < 0)
543         av_log(s, AV_LOG_WARNING, "Failed to update header with correct duration.\n");
544     else
545         put_amf_double(pb, flv->duration / (double)1000);
546     if (avio_seek(pb, flv->filesize_offset, SEEK_SET) < 0)
547         av_log(s, AV_LOG_WARNING, "Failed to update header with correct filesize.\n");
548     else
549         put_amf_double(pb, file_size);
550
551     avio_seek(pb, file_size, SEEK_SET);
552     return 0;
553 }
554
555 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
556 {
557     AVIOContext *pb      = s->pb;
558     AVCodecParameters *par = s->streams[pkt->stream_index]->codecpar;
559     FLVContext *flv      = s->priv_data;
560     FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
561     unsigned ts;
562     int size = pkt->size;
563     uint8_t *data = NULL;
564     int flags = -1, flags_size, ret;
565
566     if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A ||
567         par->codec_id == AV_CODEC_ID_VP6  || par->codec_id == AV_CODEC_ID_AAC)
568         flags_size = 2;
569     else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4)
570         flags_size = 5;
571     else
572         flags_size = 1;
573
574     if (par->codec_id == AV_CODEC_ID_AAC || par->codec_id == AV_CODEC_ID_H264
575             || par->codec_id == AV_CODEC_ID_MPEG4) {
576         int side_size = 0;
577         uint8_t *side = av_packet_get_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA, &side_size);
578         if (side && side_size > 0 && (side_size != par->extradata_size || memcmp(side, par->extradata, side_size))) {
579             av_free(par->extradata);
580             par->extradata = av_mallocz(side_size + AV_INPUT_BUFFER_PADDING_SIZE);
581             memcpy(par->extradata, side, side_size);
582             par->extradata_size = side_size;
583             flv_write_codec_header(s, par);
584         }
585     }
586
587     if (flv->delay == AV_NOPTS_VALUE)
588         flv->delay = -pkt->dts;
589
590     if (pkt->dts < -flv->delay) {
591         av_log(s, AV_LOG_WARNING,
592                "Packets are not in the proper order with respect to DTS\n");
593         return AVERROR(EINVAL);
594     }
595
596     ts = pkt->dts;
597
598     if (s->event_flags & AVSTREAM_EVENT_FLAG_METADATA_UPDATED) {
599         write_metadata(s, ts);
600         s->event_flags &= ~AVSTREAM_EVENT_FLAG_METADATA_UPDATED;
601     }
602
603     avio_write_marker(pb, av_rescale(ts, AV_TIME_BASE, 1000),
604                       pkt->flags & AV_PKT_FLAG_KEY && (flv->video_par ? par->codec_type == AVMEDIA_TYPE_VIDEO : 1) ? AVIO_DATA_MARKER_SYNC_POINT : AVIO_DATA_MARKER_BOUNDARY_POINT);
605
606     switch (par->codec_type) {
607     case AVMEDIA_TYPE_VIDEO:
608         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
609
610         flags = ff_codec_get_tag(flv_video_codec_ids, par->codec_id);
611
612         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
613         break;
614     case AVMEDIA_TYPE_AUDIO:
615         flags = get_audio_flags(s, par);
616
617         av_assert0(size);
618
619         avio_w8(pb, FLV_TAG_TYPE_AUDIO);
620         break;
621     case AVMEDIA_TYPE_SUBTITLE:
622     case AVMEDIA_TYPE_DATA:
623         avio_w8(pb, FLV_TAG_TYPE_META);
624         break;
625     default:
626         return AVERROR(EINVAL);
627     }
628
629     if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) {
630         /* check if extradata looks like mp4 formatted */
631         if (par->extradata_size > 0 && *(uint8_t*)par->extradata != 1)
632             if ((ret = ff_avc_parse_nal_units_buf(pkt->data, &data, &size)) < 0)
633                 return ret;
634     } else if (par->codec_id == AV_CODEC_ID_AAC && pkt->size > 2 &&
635                (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
636         if (!s->streams[pkt->stream_index]->nb_frames) {
637         av_log(s, AV_LOG_ERROR, "Malformed AAC bitstream detected: "
638                "use the audio bitstream filter 'aac_adtstoasc' to fix it "
639                "('-bsf:a aac_adtstoasc' option with ffmpeg)\n");
640         return AVERROR_INVALIDDATA;
641         }
642         av_log(s, AV_LOG_WARNING, "aac bitstream error\n");
643     }
644
645     /* check Speex packet duration */
646     if (par->codec_id == AV_CODEC_ID_SPEEX && ts - sc->last_ts > 160)
647         av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "
648                                   "8 frames per packet. Adobe Flash "
649                                   "Player cannot handle this!\n");
650
651     if (sc->last_ts < ts)
652         sc->last_ts = ts;
653
654     if (size + flags_size >= 1<<24) {
655         av_log(s, AV_LOG_ERROR, "Too large packet with size %u >= %u\n",
656                size + flags_size, 1<<24);
657         return AVERROR(EINVAL);
658     }
659
660     avio_wb24(pb, size + flags_size);
661     avio_wb24(pb, ts & 0xFFFFFF);
662     avio_w8(pb, (ts >> 24) & 0x7F); // timestamps are 32 bits _signed_
663     avio_wb24(pb, flv->reserved);
664
665     if (par->codec_type == AVMEDIA_TYPE_DATA ||
666         par->codec_type == AVMEDIA_TYPE_SUBTITLE ) {
667         int data_size;
668         int64_t metadata_size_pos = avio_tell(pb);
669         if (par->codec_id == AV_CODEC_ID_TEXT) {
670             // legacy FFmpeg magic?
671             avio_w8(pb, AMF_DATA_TYPE_STRING);
672             put_amf_string(pb, "onTextData");
673             avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
674             avio_wb32(pb, 2);
675             put_amf_string(pb, "type");
676             avio_w8(pb, AMF_DATA_TYPE_STRING);
677             put_amf_string(pb, "Text");
678             put_amf_string(pb, "text");
679             avio_w8(pb, AMF_DATA_TYPE_STRING);
680             put_amf_string(pb, pkt->data);
681             put_amf_string(pb, "");
682             avio_w8(pb, AMF_END_OF_OBJECT);
683         } else {
684             // just pass the metadata through
685             avio_write(pb, data ? data : pkt->data, size);
686         }
687         /* write total size of tag */
688         data_size = avio_tell(pb) - metadata_size_pos;
689         avio_seek(pb, metadata_size_pos - 10, SEEK_SET);
690         avio_wb24(pb, data_size);
691         avio_seek(pb, data_size + 10 - 3, SEEK_CUR);
692         avio_wb32(pb, data_size + 11);
693     } else {
694         av_assert1(flags>=0);
695         avio_w8(pb,flags);
696         if (par->codec_id == AV_CODEC_ID_VP6)
697             avio_w8(pb,0);
698         if (par->codec_id == AV_CODEC_ID_VP6F || par->codec_id == AV_CODEC_ID_VP6A) {
699             if (par->extradata_size)
700                 avio_w8(pb, par->extradata[0]);
701             else
702                 avio_w8(pb, ((FFALIGN(par->width,  16) - par->width) << 4) |
703                              (FFALIGN(par->height, 16) - par->height));
704         } else if (par->codec_id == AV_CODEC_ID_AAC)
705             avio_w8(pb, 1); // AAC raw
706         else if (par->codec_id == AV_CODEC_ID_H264 || par->codec_id == AV_CODEC_ID_MPEG4) {
707             avio_w8(pb, 1); // AVC NALU
708             avio_wb24(pb, pkt->pts - pkt->dts);
709         }
710
711         avio_write(pb, data ? data : pkt->data, size);
712
713         avio_wb32(pb, size + flags_size + 11); // previous tag size
714         flv->duration = FFMAX(flv->duration,
715                               pkt->pts + flv->delay + pkt->duration);
716     }
717
718     av_free(data);
719
720     return pb->error;
721 }
722
723 static const AVOption options[] = {
724     { "flvflags", "FLV muxer flags", offsetof(FLVContext, flags), AV_OPT_TYPE_FLAGS, {.i64 = 0}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "flvflags" },
725     { "aac_seq_header_detect", "Put AAC sequence header based on stream data", 0, AV_OPT_TYPE_CONST, {.i64 = FLV_AAC_SEQ_HEADER_DETECT}, INT_MIN, INT_MAX, AV_OPT_FLAG_ENCODING_PARAM, "flvflags" },
726     { NULL },
727 };
728
729 static const AVClass flv_muxer_class = {
730     .class_name = "flv muxer",
731     .item_name  = av_default_item_name,
732     .option     = options,
733     .version    = LIBAVUTIL_VERSION_INT,
734 };
735
736 AVOutputFormat ff_flv_muxer = {
737     .name           = "flv",
738     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
739     .mime_type      = "video/x-flv",
740     .extensions     = "flv",
741     .priv_data_size = sizeof(FLVContext),
742     .audio_codec    = CONFIG_LIBMP3LAME ? AV_CODEC_ID_MP3 : AV_CODEC_ID_ADPCM_SWF,
743     .video_codec    = AV_CODEC_ID_FLV1,
744     .write_header   = flv_write_header,
745     .write_packet   = flv_write_packet,
746     .write_trailer  = flv_write_trailer,
747     .codec_tag      = (const AVCodecTag* const []) {
748                           flv_video_codec_ids, flv_audio_codec_ids, 0
749                       },
750     .flags          = AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS |
751                       AVFMT_TS_NONSTRICT,
752     .priv_class     = &flv_muxer_class,
753 };