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