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