]> git.sesse.net Git - ffmpeg/blob - libavformat/flvenc.c
avidec: Fix infinite loop caused by rounding of timestamps in non interleaved avis.
[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/intfloat.h"
24 #include "avformat.h"
25 #include "flv.h"
26 #include "internal.h"
27 #include "avc.h"
28 #include "metadata.h"
29 #include "libavutil/dict.h"
30
31 #undef NDEBUG
32 #include <assert.h>
33
34 static const AVCodecTag flv_video_codec_ids[] = {
35     {CODEC_ID_FLV1,    FLV_CODECID_H263  },
36     {CODEC_ID_H263,    FLV_CODECID_REALH263},
37     {CODEC_ID_MPEG4,   FLV_CODECID_MPEG4 },
38     {CODEC_ID_FLASHSV, FLV_CODECID_SCREEN},
39     {CODEC_ID_FLASHSV2, FLV_CODECID_SCREEN2},
40     {CODEC_ID_VP6F,    FLV_CODECID_VP6   },
41     {CODEC_ID_VP6,     FLV_CODECID_VP6   },
42     {CODEC_ID_H264,    FLV_CODECID_H264  },
43     {CODEC_ID_NONE,    0}
44 };
45
46 static const AVCodecTag flv_audio_codec_ids[] = {
47     {CODEC_ID_MP3,       FLV_CODECID_MP3    >> FLV_AUDIO_CODECID_OFFSET},
48     {CODEC_ID_PCM_U8,    FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
49     {CODEC_ID_PCM_S16BE, FLV_CODECID_PCM    >> FLV_AUDIO_CODECID_OFFSET},
50     {CODEC_ID_PCM_S16LE, FLV_CODECID_PCM_LE >> FLV_AUDIO_CODECID_OFFSET},
51     {CODEC_ID_ADPCM_SWF, FLV_CODECID_ADPCM  >> FLV_AUDIO_CODECID_OFFSET},
52     {CODEC_ID_AAC,       FLV_CODECID_AAC    >> FLV_AUDIO_CODECID_OFFSET},
53     {CODEC_ID_NELLYMOSER, FLV_CODECID_NELLYMOSER >> FLV_AUDIO_CODECID_OFFSET},
54     {CODEC_ID_SPEEX,     FLV_CODECID_SPEEX  >> FLV_AUDIO_CODECID_OFFSET},
55     {CODEC_ID_NONE,      0}
56 };
57
58 typedef struct FLVContext {
59     int reserved;
60     int64_t duration_offset;
61     int64_t filesize_offset;
62     int64_t duration;
63     int64_t delay;      ///< first dts delay (needed for AVC & Speex)
64 } FLVContext;
65
66 typedef struct FLVStreamContext {
67     int64_t last_ts;    ///< last timestamp for each stream
68 } FLVStreamContext;
69
70 static int get_audio_flags(AVCodecContext *enc){
71     int flags = (enc->bits_per_coded_sample == 16) ? FLV_SAMPLESSIZE_16BIT : FLV_SAMPLESSIZE_8BIT;
72
73     if (enc->codec_id == CODEC_ID_AAC) // specs force these parameters
74         return FLV_CODECID_AAC | FLV_SAMPLERATE_44100HZ | FLV_SAMPLESSIZE_16BIT | FLV_STEREO;
75     else if (enc->codec_id == CODEC_ID_SPEEX) {
76         if (enc->sample_rate != 16000) {
77             av_log(enc, AV_LOG_ERROR, "flv only supports wideband (16kHz) Speex audio\n");
78             return -1;
79         }
80         if (enc->channels != 1) {
81             av_log(enc, AV_LOG_ERROR, "flv only supports mono Speex audio\n");
82             return -1;
83         }
84         return FLV_CODECID_SPEEX | FLV_SAMPLERATE_11025HZ | FLV_SAMPLESSIZE_16BIT;
85     } else {
86     switch (enc->sample_rate) {
87         case    44100:
88             flags |= FLV_SAMPLERATE_44100HZ;
89             break;
90         case    22050:
91             flags |= FLV_SAMPLERATE_22050HZ;
92             break;
93         case    11025:
94             flags |= FLV_SAMPLERATE_11025HZ;
95             break;
96         case    16000: //nellymoser only
97         case     8000: //nellymoser only
98         case     5512: //not mp3
99             if(enc->codec_id != CODEC_ID_MP3){
100                 flags |= FLV_SAMPLERATE_SPECIAL;
101                 break;
102             }
103         default:
104             av_log(enc, AV_LOG_ERROR, "flv does not support that sample rate, choose from (44100, 22050, 11025).\n");
105             return -1;
106     }
107     }
108
109     if (enc->channels > 1) {
110         flags |= FLV_STEREO;
111     }
112
113     switch(enc->codec_id){
114     case CODEC_ID_MP3:
115         flags |= FLV_CODECID_MP3    | FLV_SAMPLESSIZE_16BIT;
116         break;
117     case CODEC_ID_PCM_U8:
118         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_8BIT;
119         break;
120     case CODEC_ID_PCM_S16BE:
121         flags |= FLV_CODECID_PCM    | FLV_SAMPLESSIZE_16BIT;
122         break;
123     case CODEC_ID_PCM_S16LE:
124         flags |= FLV_CODECID_PCM_LE | FLV_SAMPLESSIZE_16BIT;
125         break;
126     case CODEC_ID_ADPCM_SWF:
127         flags |= FLV_CODECID_ADPCM | FLV_SAMPLESSIZE_16BIT;
128         break;
129     case CODEC_ID_NELLYMOSER:
130         if (enc->sample_rate == 8000) {
131             flags |= FLV_CODECID_NELLYMOSER_8KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
132         } else if (enc->sample_rate == 16000) {
133             flags |= FLV_CODECID_NELLYMOSER_16KHZ_MONO | FLV_SAMPLESSIZE_16BIT;
134         } else {
135             flags |= FLV_CODECID_NELLYMOSER | FLV_SAMPLESSIZE_16BIT;
136         }
137         break;
138     case 0:
139         flags |= enc->codec_tag<<4;
140         break;
141     default:
142         av_log(enc, AV_LOG_ERROR, "codec not compatible with flv\n");
143         return -1;
144     }
145
146     return flags;
147 }
148
149 static void put_amf_string(AVIOContext *pb, const char *str)
150 {
151     size_t len = strlen(str);
152     avio_wb16(pb, len);
153     avio_write(pb, str, len);
154 }
155
156 static void put_avc_eos_tag(AVIOContext *pb, unsigned ts) {
157     avio_w8(pb, FLV_TAG_TYPE_VIDEO);
158     avio_wb24(pb, 5);  /* Tag Data Size */
159     avio_wb24(pb, ts);  /* lower 24 bits of timestamp in ms*/
160     avio_w8(pb, (ts >> 24) & 0x7F);  /* MSB of ts in ms*/
161     avio_wb24(pb, 0);  /* StreamId = 0 */
162     avio_w8(pb, 23);  /* ub[4] FrameType = 1, ub[4] CodecId = 7 */
163     avio_w8(pb, 2);  /* AVC end of sequence */
164     avio_wb24(pb, 0);  /* Always 0 for AVC EOS. */
165     avio_wb32(pb, 16);  /* Size of FLV tag */
166 }
167
168 static void put_amf_double(AVIOContext *pb, double d)
169 {
170     avio_w8(pb, AMF_DATA_TYPE_NUMBER);
171     avio_wb64(pb, av_double2int(d));
172 }
173
174 static void put_amf_bool(AVIOContext *pb, int b) {
175     avio_w8(pb, AMF_DATA_TYPE_BOOL);
176     avio_w8(pb, !!b);
177 }
178
179 static int flv_write_header(AVFormatContext *s)
180 {
181     AVIOContext *pb = s->pb;
182     FLVContext *flv = s->priv_data;
183     AVCodecContext *audio_enc = NULL, *video_enc = NULL;
184     int i, metadata_count = 0;
185     double framerate = 0.0;
186     int64_t metadata_size_pos, data_size, metadata_count_pos;
187     AVDictionaryEntry *tag = NULL;
188
189     for(i=0; i<s->nb_streams; i++){
190         AVCodecContext *enc = s->streams[i]->codec;
191         FLVStreamContext *sc;
192         if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
193             if (s->streams[i]->r_frame_rate.den && s->streams[i]->r_frame_rate.num) {
194                 framerate = av_q2d(s->streams[i]->r_frame_rate);
195             } else {
196                 framerate = 1/av_q2d(s->streams[i]->codec->time_base);
197             }
198             video_enc = enc;
199             if(enc->codec_tag == 0) {
200                 av_log(enc, AV_LOG_ERROR, "video codec not compatible with flv\n");
201                 return -1;
202             }
203         } else if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
204             audio_enc = enc;
205             if(get_audio_flags(enc)<0)
206                 return -1;
207         }
208         avpriv_set_pts_info(s->streams[i], 32, 1, 1000); /* 32 bit pts in ms */
209
210         sc = av_mallocz(sizeof(FLVStreamContext));
211         if (!sc)
212             return AVERROR(ENOMEM);
213         s->streams[i]->priv_data = sc;
214         sc->last_ts = -1;
215     }
216     flv->delay = AV_NOPTS_VALUE;
217
218     avio_write(pb, "FLV", 3);
219     avio_w8(pb,1);
220     avio_w8(pb,   FLV_HEADER_FLAG_HASAUDIO * !!audio_enc
221                  + FLV_HEADER_FLAG_HASVIDEO * !!video_enc);
222     avio_wb32(pb,9);
223     avio_wb32(pb,0);
224
225     for(i=0; i<s->nb_streams; i++){
226         if(s->streams[i]->codec->codec_tag == 5){
227             avio_w8(pb,8); // message type
228             avio_wb24(pb,0); // include flags
229             avio_wb24(pb,0); // time stamp
230             avio_wb32(pb,0); // reserved
231             avio_wb32(pb,11); // size
232             flv->reserved=5;
233         }
234     }
235
236     /* write meta_tag */
237     avio_w8(pb, 18);         // tag type META
238     metadata_size_pos= avio_tell(pb);
239     avio_wb24(pb, 0);          // size of data part (sum of all parts below)
240     avio_wb24(pb, 0);          // time stamp
241     avio_wb32(pb, 0);          // reserved
242
243     /* now data of data_size size */
244
245     /* first event name as a string */
246     avio_w8(pb, AMF_DATA_TYPE_STRING);
247     put_amf_string(pb, "onMetaData"); // 12 bytes
248
249     /* mixed array (hash) with size and string/type/data tuples */
250     avio_w8(pb, AMF_DATA_TYPE_MIXEDARRAY);
251     metadata_count_pos = avio_tell(pb);
252     metadata_count = 5*!!video_enc + 5*!!audio_enc + 2; // +2 for duration and file size
253     avio_wb32(pb, metadata_count);
254
255     put_amf_string(pb, "duration");
256     flv->duration_offset= avio_tell(pb);
257     put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
258
259     if(video_enc){
260         put_amf_string(pb, "width");
261         put_amf_double(pb, video_enc->width);
262
263         put_amf_string(pb, "height");
264         put_amf_double(pb, video_enc->height);
265
266         put_amf_string(pb, "videodatarate");
267         put_amf_double(pb, video_enc->bit_rate / 1024.0);
268
269         put_amf_string(pb, "framerate");
270         put_amf_double(pb, framerate);
271
272         put_amf_string(pb, "videocodecid");
273         put_amf_double(pb, video_enc->codec_tag);
274     }
275
276     if(audio_enc){
277         put_amf_string(pb, "audiodatarate");
278         put_amf_double(pb, audio_enc->bit_rate / 1024.0);
279
280         put_amf_string(pb, "audiosamplerate");
281         put_amf_double(pb, audio_enc->sample_rate);
282
283         put_amf_string(pb, "audiosamplesize");
284         put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
285
286         put_amf_string(pb, "stereo");
287         put_amf_bool(pb, audio_enc->channels == 2);
288
289         put_amf_string(pb, "audiocodecid");
290         put_amf_double(pb, audio_enc->codec_tag);
291     }
292
293     while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
294         if(   !strcmp(tag->key, "width")
295             ||!strcmp(tag->key, "height")
296             ||!strcmp(tag->key, "videodatarate")
297             ||!strcmp(tag->key, "framerate")
298             ||!strcmp(tag->key, "videocodecid")
299             ||!strcmp(tag->key, "audiodatarate")
300             ||!strcmp(tag->key, "audiosamplerate")
301             ||!strcmp(tag->key, "audiosamplesize")
302             ||!strcmp(tag->key, "stereo")
303             ||!strcmp(tag->key, "audiocodecid")
304             ||!strcmp(tag->key, "duration")
305             ||!strcmp(tag->key, "onMetaData")
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     for (i = 0; i < s->nb_streams; i++) {
335         AVCodecContext *enc = s->streams[i]->codec;
336         if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264 || enc->codec_id == CODEC_ID_MPEG4) {
337             int64_t pos;
338             avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
339                      FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
340             avio_wb24(pb, 0); // size patched later
341             avio_wb24(pb, 0); // ts
342             avio_w8(pb, 0); // ts ext
343             avio_wb24(pb, 0); // streamid
344             pos = avio_tell(pb);
345             if (enc->codec_id == CODEC_ID_AAC) {
346                 avio_w8(pb, get_audio_flags(enc));
347                 avio_w8(pb, 0); // AAC sequence header
348                 avio_write(pb, enc->extradata, enc->extradata_size);
349             } else {
350                 avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
351                 avio_w8(pb, 0); // AVC sequence header
352                 avio_wb24(pb, 0); // composition time
353                 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
354             }
355             data_size = avio_tell(pb) - pos;
356             avio_seek(pb, -data_size - 10, SEEK_CUR);
357             avio_wb24(pb, data_size);
358             avio_skip(pb, data_size + 10 - 3);
359             avio_wb32(pb, data_size + 11); // previous tag size
360         }
361     }
362
363     return 0;
364 }
365
366 static int flv_write_trailer(AVFormatContext *s)
367 {
368     int64_t file_size;
369
370     AVIOContext *pb = s->pb;
371     FLVContext *flv = s->priv_data;
372     int i;
373
374     /* Add EOS tag */
375     for (i = 0; i < s->nb_streams; i++) {
376         AVCodecContext *enc = s->streams[i]->codec;
377         FLVStreamContext *sc = s->streams[i]->priv_data;
378         if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
379                 (enc->codec_id == CODEC_ID_H264 || enc->codec_id == CODEC_ID_MPEG4)) {
380             put_avc_eos_tag(pb, sc->last_ts);
381         }
382     }
383
384     file_size = avio_tell(pb);
385
386     /* update information */
387     avio_seek(pb, flv->duration_offset, SEEK_SET);
388     put_amf_double(pb, flv->duration / (double)1000);
389     avio_seek(pb, flv->filesize_offset, SEEK_SET);
390     put_amf_double(pb, file_size);
391
392     avio_seek(pb, file_size, SEEK_SET);
393     return 0;
394 }
395
396 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
397 {
398     AVIOContext *pb = s->pb;
399     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
400     FLVContext *flv = s->priv_data;
401     FLVStreamContext *sc = s->streams[pkt->stream_index]->priv_data;
402     unsigned ts;
403     int size= pkt->size;
404     uint8_t *data= NULL;
405     int flags, flags_size;
406
407 //    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
408
409     if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
410        enc->codec_id == CODEC_ID_AAC)
411         flags_size= 2;
412     else if(enc->codec_id == CODEC_ID_H264 || enc->codec_id == CODEC_ID_MPEG4)
413         flags_size= 5;
414     else
415         flags_size= 1;
416
417     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
418         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
419
420         flags = enc->codec_tag;
421         if(flags == 0) {
422             av_log(enc, AV_LOG_ERROR, "video codec %s not compatible with flv\n", avcodec_get_name(enc->codec_id));
423             return -1;
424         }
425
426         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
427     } else if (enc->codec_type == AVMEDIA_TYPE_AUDIO) {
428         flags = get_audio_flags(enc);
429
430         assert(size);
431
432         avio_w8(pb, FLV_TAG_TYPE_AUDIO);
433     } else {
434         // In-band flv metadata ("scriptdata")
435         assert(enc->codec_type == AVMEDIA_TYPE_DATA);
436         avio_w8(pb, FLV_TAG_TYPE_META);
437         flags_size = 0;
438         flags = 0;
439     }
440
441     if (enc->codec_id == CODEC_ID_H264 || enc->codec_id == CODEC_ID_MPEG4) {
442         /* check if extradata looks like mp4 formated */
443         if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
444             if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
445                 return -1;
446         }
447     } else if (enc->codec_id == CODEC_ID_AAC && pkt->size > 2 &&
448                (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
449         av_log(s, AV_LOG_ERROR, "malformated aac bitstream, use -absf aac_adtstoasc\n");
450         return -1;
451     }
452     if (flv->delay == AV_NOPTS_VALUE)
453         flv->delay = -pkt->dts;
454     if (pkt->dts < -flv->delay) {
455         av_log(s, AV_LOG_WARNING, "Packets are not in the proper order with "
456                                   "respect to DTS\n");
457         return AVERROR(EINVAL);
458     }
459
460     ts = pkt->dts + flv->delay; // add delay to force positive dts
461
462     /* check Speex packet duration */
463     if (enc->codec_id == CODEC_ID_SPEEX && ts - sc->last_ts > 160) {
464         av_log(s, AV_LOG_WARNING, "Warning: Speex stream has more than "
465                                   "8 frames per packet. Adobe Flash "
466                                   "Player cannot handle this!\n");
467     }
468
469     if (sc->last_ts < ts)
470         sc->last_ts = ts;
471
472     avio_wb24(pb,size + flags_size);
473     avio_wb24(pb,ts);
474     avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
475     avio_wb24(pb,flv->reserved);
476
477     if(flags_size)
478         avio_w8(pb,flags);
479
480     if (enc->codec_id == CODEC_ID_VP6)
481         avio_w8(pb,0);
482     if (enc->codec_id == CODEC_ID_VP6F)
483         avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
484     else if (enc->codec_id == CODEC_ID_AAC)
485         avio_w8(pb,1); // AAC raw
486     else if (enc->codec_id == CODEC_ID_H264 || enc->codec_id == CODEC_ID_MPEG4) {
487         avio_w8(pb,1); // AVC NALU
488         avio_wb24(pb,pkt->pts - pkt->dts);
489     }
490
491     avio_write(pb, data ? data : pkt->data, size);
492
493     avio_wb32(pb,size+flags_size+11); // previous tag size
494     flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
495
496     avio_flush(pb);
497
498     av_free(data);
499
500     return pb->error;
501 }
502
503 AVOutputFormat ff_flv_muxer = {
504     .name           = "flv",
505     .long_name      = NULL_IF_CONFIG_SMALL("FLV format"),
506     .mime_type      = "video/x-flv",
507     .extensions     = "flv",
508     .priv_data_size = sizeof(FLVContext),
509 #if CONFIG_LIBMP3LAME
510     .audio_codec    = CODEC_ID_MP3,
511 #else // CONFIG_LIBMP3LAME
512     .audio_codec    = CODEC_ID_ADPCM_SWF,
513 #endif // CONFIG_LIBMP3LAME
514     .video_codec    = CODEC_ID_FLV1,
515     .write_header   = flv_write_header,
516     .write_packet   = flv_write_packet,
517     .write_trailer  = flv_write_trailer,
518     .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
519     .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
520 };