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