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