OSDN Git Service

Fix compilation with TRACE
[coroid/ffmpeg_saccubus.git] / 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 #include "avformat.h"
27 #include "flv.h"
28
29 static int flv_probe(AVProbeData *p)
30 {
31     const uint8_t *d;
32
33     d = p->buf;
34     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0) {
35         return AVPROBE_SCORE_MAX;
36     }
37     return 0;
38 }
39
40 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) {
41     AVCodecContext *acodec = astream->codec;
42     switch(flv_codecid) {
43         //no distinction between S16 and S8 PCM codec flags
44         case FLV_CODECID_PCM:
45             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_S8 :
46 #ifdef WORDS_BIGENDIAN
47                                 CODEC_ID_PCM_S16BE;
48 #else
49                                 CODEC_ID_PCM_S16LE;
50 #endif
51             break;
52         case FLV_CODECID_PCM_LE:
53             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_S8 : CODEC_ID_PCM_S16LE; break;
54         case FLV_CODECID_AAC  : acodec->codec_id = CODEC_ID_AAC;                                    break;
55         case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF;                              break;
56         case FLV_CODECID_SPEEX:
57             acodec->codec_id = CODEC_ID_SPEEX;
58             acodec->sample_rate = 16000;
59             break;
60         case FLV_CODECID_MP3  : acodec->codec_id = CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
61         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
62             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
63         case FLV_CODECID_NELLYMOSER:
64             acodec->codec_id = CODEC_ID_NELLYMOSER;
65             break;
66         default:
67             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
68             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
69     }
70 }
71
72 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
73     AVCodecContext *vcodec = vstream->codec;
74     switch(flv_codecid) {
75         case FLV_CODECID_H263  : vcodec->codec_id = CODEC_ID_FLV1   ; break;
76         case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
77         case FLV_CODECID_VP6   : vcodec->codec_id = CODEC_ID_VP6F   ;
78         case FLV_CODECID_VP6A  :
79             if(flv_codecid == FLV_CODECID_VP6A)
80                 vcodec->codec_id = CODEC_ID_VP6A;
81             if(vcodec->extradata_size != 1) {
82                 vcodec->extradata_size = 1;
83                 vcodec->extradata = av_malloc(1);
84             }
85             vcodec->extradata[0] = get_byte(s->pb);
86             return 1; // 1 byte body size adjustment for flv_read_packet()
87         case FLV_CODECID_H264:
88             vcodec->codec_id = CODEC_ID_H264;
89             return 3; // not 4, reading packet type will consume one byte
90         default:
91             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
92             vcodec->codec_tag = flv_codecid;
93     }
94
95     return 0;
96 }
97
98 static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) {
99     int length = get_be16(ioc);
100     if(length >= buffsize) {
101         url_fskip(ioc, length);
102         return -1;
103     }
104
105     get_buffer(ioc, buffer, length);
106
107     buffer[length] = '\0';
108
109     return length;
110 }
111
112 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
113     AVCodecContext *acodec, *vcodec;
114     ByteIOContext *ioc;
115     AMFDataType amf_type;
116     char str_val[256];
117     double num_val;
118
119     num_val = 0;
120     ioc = s->pb;
121
122     amf_type = get_byte(ioc);
123
124     switch(amf_type) {
125         case AMF_DATA_TYPE_NUMBER:
126             num_val = av_int2dbl(get_be64(ioc)); break;
127         case AMF_DATA_TYPE_BOOL:
128             num_val = get_byte(ioc); break;
129         case AMF_DATA_TYPE_STRING:
130             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
131                 return -1;
132             break;
133         case AMF_DATA_TYPE_OBJECT: {
134             unsigned int keylen;
135
136             while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) {
137                 url_fskip(ioc, keylen); //skip key string
138                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
139                     return -1; //if we couldn't skip, bomb out.
140             }
141             if(get_byte(ioc) != AMF_END_OF_OBJECT)
142                 return -1;
143         }
144             break;
145         case AMF_DATA_TYPE_NULL:
146         case AMF_DATA_TYPE_UNDEFINED:
147         case AMF_DATA_TYPE_UNSUPPORTED:
148             break; //these take up no additional space
149         case AMF_DATA_TYPE_MIXEDARRAY:
150             url_fskip(ioc, 4); //skip 32-bit max array index
151             while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
152                 //this is the only case in which we would want a nested parse to not skip over the object
153                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
154                     return -1;
155             }
156             if(get_byte(ioc) != AMF_END_OF_OBJECT)
157                 return -1;
158             break;
159         case AMF_DATA_TYPE_ARRAY: {
160             unsigned int arraylen, i;
161
162             arraylen = get_be32(ioc);
163             for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) {
164                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
165                     return -1; //if we couldn't skip, bomb out.
166             }
167         }
168             break;
169         case AMF_DATA_TYPE_DATE:
170             url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
171             break;
172         default: //unsupported type, we couldn't skip
173             return -1;
174     }
175
176     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
177         acodec = astream ? astream->codec : NULL;
178         vcodec = vstream ? vstream->codec : NULL;
179
180         if(amf_type == AMF_DATA_TYPE_BOOL) {
181             if(!strcmp(key, "stereo") && acodec) acodec->channels = num_val > 0 ? 2 : 1;
182         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
183             if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
184 //            else if(!strcmp(key, "width")  && vcodec && num_val > 0) vcodec->width  = num_val;
185 //            else if(!strcmp(key, "height") && vcodec && num_val > 0) vcodec->height = num_val;
186             else if(!strcmp(key, "audiocodecid") && acodec && 0 <= (int)num_val)
187                 flv_set_audio_codec(s, astream, (int)num_val << FLV_AUDIO_CODECID_OFFSET);
188             else if(!strcmp(key, "videocodecid") && vcodec && 0 <= (int)num_val)
189                 flv_set_video_codec(s, vstream, (int)num_val);
190             else if(!strcmp(key, "audiosamplesize") && acodec && 0 < (int)num_val) {
191                 acodec->bits_per_coded_sample = num_val;
192                 //we may have to rewrite a previously read codecid because FLV only marks PCM endianness.
193                 if(num_val == 8 && (acodec->codec_id == CODEC_ID_PCM_S16BE || acodec->codec_id == CODEC_ID_PCM_S16LE))
194                     acodec->codec_id = CODEC_ID_PCM_S8;
195             }
196             else if(!strcmp(key, "audiosamplerate") && acodec && num_val >= 0) {
197                 //some tools, like FLVTool2, write consistently approximate metadata sample rates
198                 if (!acodec->sample_rate) {
199                     switch((int)num_val) {
200                         case 44000: acodec->sample_rate = 44100  ; break;
201                         case 22000: acodec->sample_rate = 22050  ; break;
202                         case 11000: acodec->sample_rate = 11025  ; break;
203                         case 5000 : acodec->sample_rate = 5512   ; break;
204                         default   : acodec->sample_rate = num_val;
205                     }
206                 }
207             }
208         }
209     }
210
211     return 0;
212 }
213
214 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
215     AMFDataType type;
216     AVStream *stream, *astream, *vstream;
217     ByteIOContext *ioc;
218     int i, keylen;
219     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
220
221     astream = NULL;
222     vstream = NULL;
223     keylen = 0;
224     ioc = s->pb;
225
226     //first object needs to be "onMetaData" string
227     type = get_byte(ioc);
228     if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
229         return -1;
230
231     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
232     for(i = 0; i < s->nb_streams; i++) {
233         stream = s->streams[i];
234         if     (stream->codec->codec_type == CODEC_TYPE_AUDIO) astream = stream;
235         else if(stream->codec->codec_type == CODEC_TYPE_VIDEO) vstream = stream;
236     }
237
238     //parse the second object (we want a mixed array)
239     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
240         return -1;
241
242     return 0;
243 }
244
245 static AVStream *create_stream(AVFormatContext *s, int is_audio){
246     AVStream *st = av_new_stream(s, is_audio);
247     if (!st)
248         return NULL;
249     st->codec->codec_type = is_audio ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
250     av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
251     return st;
252 }
253
254 static int flv_read_header(AVFormatContext *s,
255                            AVFormatParameters *ap)
256 {
257     int offset, flags;
258
259     url_fskip(s->pb, 4);
260     flags = get_byte(s->pb);
261     /* old flvtool cleared this field */
262     /* FIXME: better fix needed */
263     if (!flags) {
264         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
265         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
266     }
267
268     if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
269              != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
270         s->ctx_flags |= AVFMTCTX_NOHEADER;
271
272     if(flags & FLV_HEADER_FLAG_HASVIDEO){
273         if(!create_stream(s, 0))
274             return AVERROR(ENOMEM);
275     }
276     if(flags & FLV_HEADER_FLAG_HASAUDIO){
277         if(!create_stream(s, 1))
278             return AVERROR(ENOMEM);
279     }
280
281     offset = get_be32(s->pb);
282     url_fseek(s->pb, offset, SEEK_SET);
283
284     s->start_time = 0;
285
286     return 0;
287 }
288
289 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
290 {
291     av_free(st->codec->extradata);
292     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
293     if (!st->codec->extradata)
294         return AVERROR(ENOMEM);
295     st->codec->extradata_size = size;
296     get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
297     return 0;
298 }
299
300 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
301 {
302     int ret, i, type, size, flags, is_audio;
303     int64_t next, pos;
304     unsigned dts;
305     AVStream *st = NULL;
306
307  retry:
308  for(;;){
309     pos = url_ftell(s->pb);
310     url_fskip(s->pb, 4); /* size of previous packet */
311     type = get_byte(s->pb);
312     size = get_be24(s->pb);
313     dts = get_be24(s->pb);
314     dts |= get_byte(s->pb) << 24;
315 //    av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
316     if (url_feof(s->pb))
317         return AVERROR(EIO);
318     url_fskip(s->pb, 3); /* stream id, always 0 */
319     flags = 0;
320
321     if(size == 0)
322         continue;
323
324     next= size + url_ftell(s->pb);
325
326     if (type == FLV_TAG_TYPE_AUDIO) {
327         is_audio=1;
328         flags = get_byte(s->pb);
329         size--;
330     } else if (type == FLV_TAG_TYPE_VIDEO) {
331         is_audio=0;
332         flags = get_byte(s->pb);
333         size--;
334         if ((flags & 0xf0) == 0x50) /* video info / command frame */
335             goto skip;
336     } else {
337         if (type == FLV_TAG_TYPE_META && size > 13+1+4)
338             flv_read_metabody(s, next);
339         else /* skip packet */
340             av_log(s, AV_LOG_ERROR, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
341     skip:
342         url_fseek(s->pb, next, SEEK_SET);
343         continue;
344     }
345
346     /* skip empty data packets */
347     if (!size)
348         continue;
349
350     /* now find stream */
351     for(i=0;i<s->nb_streams;i++) {
352         st = s->streams[i];
353         if (st->id == is_audio)
354             break;
355     }
356     if(i == s->nb_streams){
357         av_log(NULL, AV_LOG_ERROR, "invalid stream\n");
358         st= create_stream(s, is_audio);
359         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
360     }
361 //    av_log(NULL, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
362     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||         is_audio))
363        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
364        || st->discard >= AVDISCARD_ALL
365        ){
366         url_fseek(s->pb, next, SEEK_SET);
367         continue;
368     }
369     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
370         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
371     break;
372  }
373
374     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
375     if(!url_is_streamed(s->pb) && s->duration==AV_NOPTS_VALUE){
376         int size;
377         const int64_t pos= url_ftell(s->pb);
378         const int64_t fsize= url_fsize(s->pb);
379         url_fseek(s->pb, fsize-4, SEEK_SET);
380         size= get_be32(s->pb);
381         url_fseek(s->pb, fsize-3-size, SEEK_SET);
382         if(size == get_be24(s->pb) + 11){
383             s->duration= get_be24(s->pb) * (int64_t)AV_TIME_BASE / 1000;
384         }
385         url_fseek(s->pb, pos, SEEK_SET);
386     }
387
388     if(is_audio){
389         if(!st->codec->sample_rate || !st->codec->bits_per_coded_sample || (!st->codec->codec_id && !st->codec->codec_tag)) {
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             flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
394         }
395     }else{
396         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
397     }
398
399     if (st->codec->codec_id == CODEC_ID_AAC ||
400         st->codec->codec_id == CODEC_ID_H264) {
401         int type = get_byte(s->pb);
402         size--;
403         if (st->codec->codec_id == CODEC_ID_H264) {
404             // cts offset ignored because it might to be signed
405             // and would cause pts < dts
406             get_be24(s->pb);
407         }
408         if (type == 0) {
409             if ((ret = flv_get_extradata(s, st, size)) < 0)
410                 return ret;
411             goto retry;
412         }
413     }
414
415     ret= av_get_packet(s->pb, pkt, size);
416     if (ret <= 0) {
417         return AVERROR(EIO);
418     }
419     /* note: we need to modify the packet size here to handle the last
420        packet */
421     pkt->size = ret;
422     pkt->dts = dts;
423     pkt->stream_index = st->index;
424
425     if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
426         pkt->flags |= PKT_FLAG_KEY;
427
428     return ret;
429 }
430
431 AVInputFormat flv_demuxer = {
432     "flv",
433     NULL_IF_CONFIG_SMALL("FLV format"),
434     0,
435     flv_probe,
436     flv_read_header,
437     flv_read_packet,
438     .extensions = "flv",
439     .value = CODEC_ID_FLV1,
440 };