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