Git init
[framework/multimedia/ffmpeg.git] / 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 #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;
181     double framerate = 0.0;
182     int64_t metadata_size_pos, data_size;
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     avio_wb32(pb, 5*!!video_enc + 5*!!audio_enc + 2); // +2 for duration and file size
241
242     put_amf_string(pb, "duration");
243     flv->duration_offset= avio_tell(pb);
244     put_amf_double(pb, s->duration / AV_TIME_BASE); // fill in the guessed duration, it'll be corrected later if incorrect
245
246     if(video_enc){
247         put_amf_string(pb, "width");
248         put_amf_double(pb, video_enc->width);
249
250         put_amf_string(pb, "height");
251         put_amf_double(pb, video_enc->height);
252
253         put_amf_string(pb, "videodatarate");
254         put_amf_double(pb, video_enc->bit_rate / 1024.0);
255
256         put_amf_string(pb, "framerate");
257         put_amf_double(pb, framerate);
258
259         put_amf_string(pb, "videocodecid");
260         put_amf_double(pb, video_enc->codec_tag);
261     }
262
263     if(audio_enc){
264         put_amf_string(pb, "audiodatarate");
265         put_amf_double(pb, audio_enc->bit_rate / 1024.0);
266
267         put_amf_string(pb, "audiosamplerate");
268         put_amf_double(pb, audio_enc->sample_rate);
269
270         put_amf_string(pb, "audiosamplesize");
271         put_amf_double(pb, audio_enc->codec_id == CODEC_ID_PCM_U8 ? 8 : 16);
272
273         put_amf_string(pb, "stereo");
274         put_amf_bool(pb, audio_enc->channels == 2);
275
276         put_amf_string(pb, "audiocodecid");
277         put_amf_double(pb, audio_enc->codec_tag);
278     }
279
280     while ((tag = av_dict_get(s->metadata, "", tag, AV_DICT_IGNORE_SUFFIX))) {
281         put_amf_string(pb, tag->key);
282         avio_w8(pb, AMF_DATA_TYPE_STRING);
283         put_amf_string(pb, tag->value);
284     }
285
286     put_amf_string(pb, "filesize");
287     flv->filesize_offset= avio_tell(pb);
288     put_amf_double(pb, 0); // delayed write
289
290     put_amf_string(pb, "");
291     avio_w8(pb, AMF_END_OF_OBJECT);
292
293     /* write total size of tag */
294     data_size= avio_tell(pb) - metadata_size_pos - 10;
295     avio_seek(pb, metadata_size_pos, SEEK_SET);
296     avio_wb24(pb, data_size);
297     avio_skip(pb, data_size + 10 - 3);
298     avio_wb32(pb, data_size + 11);
299
300     for (i = 0; i < s->nb_streams; i++) {
301         AVCodecContext *enc = s->streams[i]->codec;
302         if (enc->codec_id == CODEC_ID_AAC || enc->codec_id == CODEC_ID_H264) {
303             int64_t pos;
304             avio_w8(pb, enc->codec_type == AVMEDIA_TYPE_VIDEO ?
305                      FLV_TAG_TYPE_VIDEO : FLV_TAG_TYPE_AUDIO);
306             avio_wb24(pb, 0); // size patched later
307             avio_wb24(pb, 0); // ts
308             avio_w8(pb, 0); // ts ext
309             avio_wb24(pb, 0); // streamid
310             pos = avio_tell(pb);
311             if (enc->codec_id == CODEC_ID_AAC) {
312                 avio_w8(pb, get_audio_flags(enc));
313                 avio_w8(pb, 0); // AAC sequence header
314                 avio_write(pb, enc->extradata, enc->extradata_size);
315             } else {
316                 avio_w8(pb, enc->codec_tag | FLV_FRAME_KEY); // flags
317                 avio_w8(pb, 0); // AVC sequence header
318                 avio_wb24(pb, 0); // composition time
319                 ff_isom_write_avcc(pb, enc->extradata, enc->extradata_size);
320             }
321             data_size = avio_tell(pb) - pos;
322             avio_seek(pb, -data_size - 10, SEEK_CUR);
323             avio_wb24(pb, data_size);
324             avio_skip(pb, data_size + 10 - 3);
325             avio_wb32(pb, data_size + 11); // previous tag size
326         }
327     }
328
329     return 0;
330 }
331
332 static int flv_write_trailer(AVFormatContext *s)
333 {
334     int64_t file_size;
335
336     AVIOContext *pb = s->pb;
337     FLVContext *flv = s->priv_data;
338     int i;
339
340     /* Add EOS tag */
341     for (i = 0; i < s->nb_streams; i++) {
342         AVCodecContext *enc = s->streams[i]->codec;
343         if (enc->codec_type == AVMEDIA_TYPE_VIDEO &&
344                 enc->codec_id == CODEC_ID_H264) {
345             put_avc_eos_tag(pb, flv->last_video_ts);
346         }
347     }
348
349     file_size = avio_tell(pb);
350
351     /* update informations */
352     avio_seek(pb, flv->duration_offset, SEEK_SET);
353     put_amf_double(pb, flv->duration / (double)1000);
354     avio_seek(pb, flv->filesize_offset, SEEK_SET);
355     put_amf_double(pb, file_size);
356
357     avio_seek(pb, file_size, SEEK_SET);
358     return 0;
359 }
360
361 static int flv_write_packet(AVFormatContext *s, AVPacket *pkt)
362 {
363     AVIOContext *pb = s->pb;
364     AVCodecContext *enc = s->streams[pkt->stream_index]->codec;
365     FLVContext *flv = s->priv_data;
366     unsigned ts;
367     int size= pkt->size;
368     uint8_t *data= NULL;
369     int flags, flags_size;
370
371 //    av_log(s, AV_LOG_DEBUG, "type:%d pts: %"PRId64" size:%d\n", enc->codec_type, timestamp, size);
372
373     if(enc->codec_id == CODEC_ID_VP6 || enc->codec_id == CODEC_ID_VP6F ||
374        enc->codec_id == CODEC_ID_AAC)
375         flags_size= 2;
376     else if(enc->codec_id == CODEC_ID_H264)
377         flags_size= 5;
378     else
379         flags_size= 1;
380
381     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
382         avio_w8(pb, FLV_TAG_TYPE_VIDEO);
383
384         flags = enc->codec_tag;
385         if(flags == 0) {
386             av_log(enc, AV_LOG_ERROR, "video codec %X not compatible with flv\n",enc->codec_id);
387             return -1;
388         }
389
390         flags |= pkt->flags & AV_PKT_FLAG_KEY ? FLV_FRAME_KEY : FLV_FRAME_INTER;
391     } else {
392         assert(enc->codec_type == AVMEDIA_TYPE_AUDIO);
393         flags = get_audio_flags(enc);
394
395         assert(size);
396
397         avio_w8(pb, FLV_TAG_TYPE_AUDIO);
398     }
399
400     if (enc->codec_id == CODEC_ID_H264) {
401         /* check if extradata looks like mp4 formated */
402         if (enc->extradata_size > 0 && *(uint8_t*)enc->extradata != 1) {
403             if (ff_avc_parse_nal_units_buf(pkt->data, &data, &size) < 0)
404                 return -1;
405         }
406         if (!flv->delay && pkt->dts < 0)
407             flv->delay = -pkt->dts;
408     } else if (enc->codec_id == CODEC_ID_AAC && pkt->size > 2 &&
409                (AV_RB16(pkt->data) & 0xfff0) == 0xfff0) {
410         av_log(s, AV_LOG_ERROR, "malformated aac bitstream, use -absf aac_adtstoasc\n");
411         return -1;
412     }
413
414     ts = pkt->dts + flv->delay; // add delay to force positive dts
415     if (enc->codec_type == AVMEDIA_TYPE_VIDEO) {
416         if (flv->last_video_ts < ts)
417             flv->last_video_ts = ts;
418     }
419     avio_wb24(pb,size + flags_size);
420     avio_wb24(pb,ts);
421     avio_w8(pb,(ts >> 24) & 0x7F); // timestamps are 32bits _signed_
422     avio_wb24(pb,flv->reserved);
423     avio_w8(pb,flags);
424     if (enc->codec_id == CODEC_ID_VP6)
425         avio_w8(pb,0);
426     if (enc->codec_id == CODEC_ID_VP6F)
427         avio_w8(pb, enc->extradata_size ? enc->extradata[0] : 0);
428     else if (enc->codec_id == CODEC_ID_AAC)
429         avio_w8(pb,1); // AAC raw
430     else if (enc->codec_id == CODEC_ID_H264) {
431         avio_w8(pb,1); // AVC NALU
432         avio_wb24(pb,pkt->pts - pkt->dts);
433     }
434
435     avio_write(pb, data ? data : pkt->data, size);
436
437     avio_wb32(pb,size+flags_size+11); // previous tag size
438     flv->duration = FFMAX(flv->duration, pkt->pts + flv->delay + pkt->duration);
439
440     avio_flush(pb);
441
442     av_free(data);
443
444     return pb->error;
445 }
446
447 AVOutputFormat ff_flv_muxer = {
448     "flv",
449     NULL_IF_CONFIG_SMALL("FLV format"),
450     "video/x-flv",
451     "flv",
452     sizeof(FLVContext),
453 #if CONFIG_LIBMP3LAME
454     CODEC_ID_MP3,
455 #else // CONFIG_LIBMP3LAME
456     CODEC_ID_ADPCM_SWF,
457 #endif // CONFIG_LIBMP3LAME
458     CODEC_ID_FLV1,
459     flv_write_header,
460     flv_write_packet,
461     flv_write_trailer,
462     .codec_tag= (const AVCodecTag* const []){flv_video_codec_ids, flv_audio_codec_ids, 0},
463     .flags= AVFMT_GLOBALHEADER | AVFMT_VARIABLE_FPS,
464 };