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