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