]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
bb27131cfd1e13cfa907c6e923bd4cb2757485e3
[ffmpeg] / libavformat / flvdec.c
1 /*
2  * FLV demuxer
3  * Copyright (c) 2003 The FFmpeg Project
4  *
5  * This demuxer will generate a 1 byte extradata for VP6F content.
6  * It is composed of:
7  *  - upper 4bits: difference between encoded width and visible width
8  *  - lower 4bits: difference between encoded height and visible height
9  *
10  * This file is part of FFmpeg.
11  *
12  * FFmpeg is free software; you can redistribute it and/or
13  * modify it under the terms of the GNU Lesser General Public
14  * License as published by the Free Software Foundation; either
15  * version 2.1 of the License, or (at your option) any later version.
16  *
17  * FFmpeg is distributed in the hope that it will be useful,
18  * but WITHOUT ANY WARRANTY; without even the implied warranty of
19  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20  * Lesser General Public License for more details.
21  *
22  * You should have received a copy of the GNU Lesser General Public
23  * License along with FFmpeg; if not, write to the Free Software
24  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
25  */
26
27 #include "libavutil/avstring.h"
28 #include "libavcodec/bytestream.h"
29 #include "libavcodec/mpeg4audio.h"
30 #include "avformat.h"
31 #include "flv.h"
32
33 typedef struct {
34     int wrong_dts; ///< wrong dts due to negative cts
35 } FLVContext;
36
37 static int flv_probe(AVProbeData *p)
38 {
39     const uint8_t *d;
40
41     d = p->buf;
42     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
43         return AVPROBE_SCORE_MAX;
44     }
45     return 0;
46 }
47
48 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) {
49     AVCodecContext *acodec = astream->codec;
50     switch(flv_codecid) {
51         //no distinction between S16 and S8 PCM codec flags
52         case FLV_CODECID_PCM:
53             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
54 #if HAVE_BIGENDIAN
55                                 CODEC_ID_PCM_S16BE;
56 #else
57                                 CODEC_ID_PCM_S16LE;
58 #endif
59             break;
60         case FLV_CODECID_PCM_LE:
61             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
62         case FLV_CODECID_AAC  : acodec->codec_id = CODEC_ID_AAC;                                    break;
63         case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF;                              break;
64         case FLV_CODECID_SPEEX:
65             acodec->codec_id = CODEC_ID_SPEEX;
66             acodec->sample_rate = 16000;
67             break;
68         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
69         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
70             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
71             acodec->codec_id = CODEC_ID_NELLYMOSER;
72             break;
73         case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
74             acodec->sample_rate = 16000;
75             acodec->codec_id = CODEC_ID_NELLYMOSER;
76             break;
77         case FLV_CODECID_NELLYMOSER:
78             acodec->codec_id = CODEC_ID_NELLYMOSER;
79             break;
80         default:
81             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
82             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
83     }
84 }
85
86 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
87     AVCodecContext *vcodec = vstream->codec;
88     switch(flv_codecid) {
89         case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;
90         case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
91         case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
92         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
93         case FLV_CODECID_VP6A  :
94             if(flv_codecid == FLV_CODECID_VP6A)
95                 vcodec->codec_id = CODEC_ID_VP6A;
96             if(vcodec->extradata_size != 1) {
97                 vcodec->extradata_size = 1;
98                 vcodec->extradata = av_malloc(1);
99             }
100             vcodec->extradata[0] = avio_r8(s->pb);
101             return 1; // 1 byte body size adjustment for flv_read_packet()
102         case FLV_CODECID_H264:
103             vcodec->codec_id = CODEC_ID_H264;
104             return 3; // not 4, reading packet type will consume one byte
105         default:
106             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
107             vcodec->codec_tag = flv_codecid;
108     }
109
110     return 0;
111 }
112
113 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
114     int length = avio_rb16(ioc);
115     if(length >= buffsize) {
116         avio_seek(ioc, length, SEEK_CUR);
117         return -1;
118     }
119
120     avio_read(ioc, buffer, length);
121
122     buffer[length] = '\0';
123
124     return length;
125 }
126
127 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
128     AVCodecContext *acodec, *vcodec;
129     AVIOContext *ioc;
130     AMFDataType amf_type;
131     char str_val[256];
132     double num_val;
133
134     num_val = 0;
135     ioc = s->pb;
136
137     amf_type = avio_r8(ioc);
138
139     switch(amf_type) {
140         case AMF_DATA_TYPE_NUMBER:
141             num_val = av_int2dbl(avio_rb64(ioc)); break;
142         case AMF_DATA_TYPE_BOOL:
143             num_val = avio_r8(ioc); break;
144         case AMF_DATA_TYPE_STRING:
145             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
146                 return -1;
147             break;
148         case AMF_DATA_TYPE_OBJECT: {
149             unsigned int keylen;
150
151             while(avio_tell(ioc) < max_pos - 2 && (keylen = avio_rb16(ioc))) {
152                 avio_seek(ioc, keylen, SEEK_CUR); //skip key string
153                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
154                     return -1; //if we couldn't skip, bomb out.
155             }
156             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
157                 return -1;
158         }
159             break;
160         case AMF_DATA_TYPE_NULL:
161         case AMF_DATA_TYPE_UNDEFINED:
162         case AMF_DATA_TYPE_UNSUPPORTED:
163             break; //these take up no additional space
164         case AMF_DATA_TYPE_MIXEDARRAY:
165             avio_seek(ioc, 4, SEEK_CUR); //skip 32-bit max array index
166             while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
167                 //this is the only case in which we would want a nested parse to not skip over the object
168                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
169                     return -1;
170             }
171             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
172                 return -1;
173             break;
174         case AMF_DATA_TYPE_ARRAY: {
175             unsigned int arraylen, i;
176
177             arraylen = avio_rb32(ioc);
178             for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
179                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
180                     return -1; //if we couldn't skip, bomb out.
181             }
182         }
183             break;
184         case AMF_DATA_TYPE_DATE:
185             avio_seek(ioc, 8 + 2, SEEK_CUR); //timestamp (double) and UTC offset (int16)
186             break;
187         default: //unsupported type, we couldn't skip
188             return -1;
189     }
190
191     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
192         acodec = astream ? astream->codec : NULL;
193         vcodec = vstream ? vstream->codec : NULL;
194
195         if(amf_type == AMF_DATA_TYPE_BOOL) {
196             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
197             av_metadata_set2(&s->metadata, key, str_val, 0);
198         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
199             snprintf(str_val, sizeof(str_val), "%.f", num_val);
200             av_metadata_set2(&s->metadata, key, str_val, 0);
201             if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
202             else if(!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
203                 vcodec->bit_rate = num_val * 1024.0;
204             else if(!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
205                 acodec->bit_rate = num_val * 1024.0;
206         } else if (amf_type == AMF_DATA_TYPE_STRING)
207             av_metadata_set2(&s->metadata, key, str_val, 0);
208     }
209
210     return 0;
211 }
212
213 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
214     AMFDataType type;
215     AVStream *stream, *astream, *vstream;
216     AVIOContext *ioc;
217     int i;
218     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
219
220     astream = NULL;
221     vstream = NULL;
222     ioc = s->pb;
223
224     //first object needs to be "onMetaData" string
225     type = avio_r8(ioc);
226     if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
227         return -1;
228
229     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
230     for(i = 0; i < s->nb_streams; i++) {
231         stream = s->streams[i];
232         if     (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
233         else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
234     }
235
236     //parse the second object (we want a mixed array)
237     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
238         return -1;
239
240     return 0;
241 }
242
243 static AVStream *create_stream(AVFormatContext *s, int is_audio){
244     AVStream *st = av_new_stream(s, is_audio);
245     if (!st)
246         return NULL;
247     st->codec->codec_type = is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
248     av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
249     return st;
250 }
251
252 static int flv_read_header(AVFormatContext *s,
253                            AVFormatParameters *ap)
254 {
255     int offset, flags;
256
257     avio_seek(s->pb, 4, SEEK_CUR);
258     flags = avio_r8(s->pb);
259     /* old flvtool cleared this field */
260     /* FIXME: better fix needed */
261     if (!flags) {
262         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
263         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
264     }
265
266     if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
267              != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
268         s->ctx_flags |= AVFMTCTX_NOHEADER;
269
270     if(flags & FLV_HEADER_FLAG_HASVIDEO){
271         if(!create_stream(s, 0))
272             return AVERROR(ENOMEM);
273     }
274     if(flags & FLV_HEADER_FLAG_HASAUDIO){
275         if(!create_stream(s, 1))
276             return AVERROR(ENOMEM);
277     }
278
279     offset = avio_rb32(s->pb);
280     avio_seek(s->pb, offset, SEEK_SET);
281     avio_seek(s->pb, 4, SEEK_CUR);
282
283     s->start_time = 0;
284
285     return 0;
286 }
287
288 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
289 {
290     av_free(st->codec->extradata);
291     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
292     if (!st->codec->extradata)
293         return AVERROR(ENOMEM);
294     st->codec->extradata_size = size;
295     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
296     return 0;
297 }
298
299 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
300 {
301     FLVContext *flv = s->priv_data;
302     int ret, i, type, size, flags, is_audio;
303     int64_t next, pos;
304     int64_t dts, pts = AV_NOPTS_VALUE;
305     AVStream *st = NULL;
306
307  for(;;avio_seek(s->pb, 4, SEEK_CUR)){ /* pkt size is repeated at end. skip it */
308     pos = avio_tell(s->pb);
309     type = avio_r8(s->pb);
310     size = avio_rb24(s->pb);
311     dts = avio_rb24(s->pb);
312     dts |= avio_r8(s->pb) << 24;
313 //    av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
314     if (s->pb->eof_reached)
315         return AVERROR_EOF;
316     avio_seek(s->pb, 3, SEEK_CUR); /* stream id, always 0 */
317     flags = 0;
318
319     if(size == 0)
320         continue;
321
322     next= size + avio_tell(s->pb);
323
324     if (type == FLV_TAG_TYPE_AUDIO) {
325         is_audio=1;
326         flags = avio_r8(s->pb);
327         size--;
328     } else if (type == FLV_TAG_TYPE_VIDEO) {
329         is_audio=0;
330         flags = avio_r8(s->pb);
331         size--;
332         if ((flags & 0xf0) == 0x50) /* video info / command frame */
333             goto skip;
334     } else {
335         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
336             flv_read_metabody(s, next);
337         else /* skip packet */
338             av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
339     skip:
340         avio_seek(s->pb, next, SEEK_SET);
341         continue;
342     }
343
344     /* skip empty data packets */
345     if (!size)
346         continue;
347
348     /* now find stream */
349     for(i=0;i<s->nb_streams;i++) {
350         st = s->streams[i];
351         if (st->id == is_audio)
352             break;
353     }
354     if(i == s->nb_streams){
355         av_log(s, AV_LOG_ERROR, "invalid stream\n");
356         st= create_stream(s, is_audio);
357         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
358     }
359 //    av_log(s, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
360     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
361        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
362        || st->discard >= AVDISCARD_ALL
363        ){
364         avio_seek(s->pb, next, SEEK_SET);
365         continue;
366     }
367     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
368         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
369     break;
370  }
371
372     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
373     if(!url_is_streamed(s->pb) && (!s->duration || s->duration==AV_NOPTS_VALUE)){
374         int size;
375         const int64_t pos= avio_tell(s->pb);
376         const int64_t fsize= avio_size(s->pb);
377         avio_seek(s->pb, fsize-4, SEEK_SET);
378         size= avio_rb32(s->pb);
379         avio_seek(s->pb, fsize-3-size, SEEK_SET);
380         if(size == avio_rb24(s->pb) + 11){
381             uint32_t ts = avio_rb24(s->pb);
382             ts |= avio_r8(s->pb) << 24;
383             s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
384         }
385         avio_seek(s->pb, pos, SEEK_SET);
386     }
387
388     if(is_audio){
389         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
390             st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
391             st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
392             st->codec->bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
393         }
394         if(!st->codec->codec_id){
395             flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
396         }
397     }else{
398         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
399     }
400
401     if (st->codec->codec_id == CODEC_ID_AAC ||
402         st->codec->codec_id == CODEC_ID_H264) {
403         int type = avio_r8(s->pb);
404         size--;
405         if (st->codec->codec_id == CODEC_ID_H264) {
406             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
407             pts = dts + cts;
408             if (cts < 0) { // dts are wrong
409                 flv->wrong_dts = 1;
410                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
411             }
412             if (flv->wrong_dts)
413                 dts = AV_NOPTS_VALUE;
414         }
415         if (type == 0) {
416             if ((ret = flv_get_extradata(s, st, size)) < 0)
417                 return ret;
418             if (st->codec->codec_id == CODEC_ID_AAC) {
419                 MPEG4AudioConfig cfg;
420                 ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
421                                          st->codec->extradata_size);
422                 st->codec->channels = cfg.channels;
423                 if (cfg.ext_sample_rate)
424                     st->codec->sample_rate = cfg.ext_sample_rate;
425                 else
426                     st->codec->sample_rate = cfg.sample_rate;
427                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
428                         st->codec->channels, st->codec->sample_rate);
429             }
430
431             ret = AVERROR(EAGAIN);
432             goto leave;
433         }
434     }
435
436     /* skip empty data packets */
437     if (!size) {
438         ret = AVERROR(EAGAIN);
439         goto leave;
440     }
441
442     ret= av_get_packet(s->pb, pkt, size);
443     if (ret < 0) {
444         return AVERROR(EIO);
445     }
446     /* note: we need to modify the packet size here to handle the last
447        packet */
448     pkt->size = ret;
449     pkt->dts = dts;
450     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
451     pkt->stream_index = st->index;
452
453     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
454         pkt->flags |= AV_PKT_FLAG_KEY;
455
456 leave:
457     avio_seek(s->pb, 4, SEEK_CUR);
458     return ret;
459 }
460
461 static int flv_read_seek(AVFormatContext *s, int stream_index,
462     int64_t ts, int flags)
463 {
464     return av_url_read_fseek(s->pb, stream_index, ts, flags);
465 }
466
467 #if 0 /* don't know enough to implement this */
468 static int flv_read_seek2(AVFormatContext *s, int stream_index,
469     int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
470 {
471     int ret = AVERROR(ENOSYS);
472
473     if (ts - min_ts > (uint64_t)(max_ts - ts)) flags |= AVSEEK_FLAG_BACKWARD;
474
475     if (url_is_streamed(s->pb)) {
476         if (stream_index < 0) {
477             stream_index = av_find_default_stream_index(s);
478             if (stream_index < 0)
479                 return -1;
480
481             /* timestamp for default must be expressed in AV_TIME_BASE units */
482             ts = av_rescale_rnd(ts, 1000, AV_TIME_BASE,
483                 flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
484         }
485         ret = av_url_read_fseek(s->pb, stream_index, ts, flags);
486     }
487
488     if (ret == AVERROR(ENOSYS))
489         ret = av_seek_frame(s, stream_index, ts, flags);
490     return ret;
491 }
492 #endif
493
494 AVInputFormat ff_flv_demuxer = {
495     "flv",
496     NULL_IF_CONFIG_SMALL("FLV format"),
497     sizeof(FLVContext),
498     flv_probe,
499     flv_read_header,
500     flv_read_packet,
501     .read_seek = flv_read_seek,
502 #if 0
503     .read_seek2 = flv_read_seek2,
504 #endif
505     .extensions = "flv",
506     .value = CODEC_ID_FLV1,
507 };