]> git.sesse.net Git - ffmpeg/blob - libavformat/flvdec.c
Merge commit '218aefce4472dc02ee3f12830a9a894bf7916da9'
[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 "libavutil/channel_layout.h"
29 #include "libavutil/dict.h"
30 #include "libavutil/opt.h"
31 #include "libavutil/intfloat.h"
32 #include "libavutil/mathematics.h"
33 #include "libavcodec/bytestream.h"
34 #include "libavcodec/mpeg4audio.h"
35 #include "avformat.h"
36 #include "internal.h"
37 #include "avio_internal.h"
38 #include "flv.h"
39
40 #define VALIDATE_INDEX_TS_THRESH 2500
41
42 typedef struct {
43     const AVClass *class; ///< Class for private options.
44     int trust_metadata; ///< configure streams according onMetaData
45     int wrong_dts; ///< wrong dts due to negative cts
46     uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
47     int      new_extradata_size[FLV_STREAM_TYPE_NB];
48     int      last_sample_rate;
49     int      last_channels;
50     struct {
51         int64_t dts;
52         int64_t pos;
53     } validate_index[2];
54     int validate_next;
55     int validate_count;
56     int searched_for_end;
57 } FLVContext;
58
59 static int flv_probe(AVProbeData *p)
60 {
61     const uint8_t *d;
62
63     d = p->buf;
64     if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
65         return AVPROBE_SCORE_MAX;
66     }
67     return 0;
68 }
69
70 static AVStream *create_stream(AVFormatContext *s, int codec_type)
71 {
72     AVStream *st = avformat_new_stream(s, NULL);
73     if (!st)
74         return NULL;
75     st->codec->codec_type = codec_type;
76     if(s->nb_streams>=3 ||(   s->nb_streams==2
77                            && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
78                            && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
79         s->ctx_flags &= ~AVFMTCTX_NOHEADER;
80
81     avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
82     return st;
83 }
84 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
85 {
86     int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
87     int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
88     int codec_id;
89
90     if (!acodec->codec_id && !acodec->codec_tag)
91         return 1;
92
93     if (acodec->bits_per_coded_sample != bits_per_coded_sample)
94         return 0;
95
96     switch(flv_codecid) {
97         //no distinction between S16 and S8 PCM codec flags
98     case FLV_CODECID_PCM:
99         codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
100 #if HAVE_BIGENDIAN
101                             AV_CODEC_ID_PCM_S16BE;
102 #else
103                             AV_CODEC_ID_PCM_S16LE;
104 #endif
105         return codec_id == acodec->codec_id;
106     case FLV_CODECID_PCM_LE:
107         codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;
108         return codec_id == acodec->codec_id;
109     case FLV_CODECID_AAC:
110         return acodec->codec_id == AV_CODEC_ID_AAC;
111     case FLV_CODECID_ADPCM:
112         return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
113     case FLV_CODECID_SPEEX:
114         return acodec->codec_id == AV_CODEC_ID_SPEEX;
115     case FLV_CODECID_MP3:
116         return acodec->codec_id == AV_CODEC_ID_MP3;
117     case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
118     case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
119     case FLV_CODECID_NELLYMOSER:
120         return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
121     case FLV_CODECID_PCM_MULAW:
122         return acodec->sample_rate == 8000 &&
123                acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
124     case FLV_CODECID_PCM_ALAW:
125         return acodec->sample_rate = 8000 &&
126                acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
127     default:
128         return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
129     }
130 }
131
132 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
133     switch(flv_codecid) {
134         //no distinction between S16 and S8 PCM codec flags
135         case FLV_CODECID_PCM:
136             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
137 #if HAVE_BIGENDIAN
138                                 AV_CODEC_ID_PCM_S16BE;
139 #else
140                                 AV_CODEC_ID_PCM_S16LE;
141 #endif
142             break;
143         case FLV_CODECID_PCM_LE:
144             acodec->codec_id = acodec->bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE; break;
145         case FLV_CODECID_AAC  : acodec->codec_id = AV_CODEC_ID_AAC;                                    break;
146         case FLV_CODECID_ADPCM: acodec->codec_id = AV_CODEC_ID_ADPCM_SWF;                              break;
147         case FLV_CODECID_SPEEX:
148             acodec->codec_id = AV_CODEC_ID_SPEEX;
149             acodec->sample_rate = 16000;
150             break;
151         case FLV_CODECID_MP3  : acodec->codec_id = AV_CODEC_ID_MP3      ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
152         case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
153             acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
154             acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
155             break;
156         case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
157             acodec->sample_rate = 16000;
158             acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
159             break;
160         case FLV_CODECID_NELLYMOSER:
161             acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
162             break;
163         case FLV_CODECID_PCM_MULAW:
164             acodec->sample_rate = 8000;
165             acodec->codec_id = AV_CODEC_ID_PCM_MULAW;
166             break;
167         case FLV_CODECID_PCM_ALAW:
168             acodec->sample_rate = 8000;
169             acodec->codec_id = AV_CODEC_ID_PCM_ALAW;
170             break;
171         default:
172             av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
173             acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
174     }
175 }
176
177 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
178 {
179     int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
180
181     if (!vcodec->codec_id && !vcodec->codec_tag)
182         return 1;
183
184     switch (flv_codecid) {
185         case FLV_CODECID_H263:
186             return vcodec->codec_id == AV_CODEC_ID_FLV1;
187         case FLV_CODECID_SCREEN:
188             return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
189         case FLV_CODECID_SCREEN2:
190             return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
191         case FLV_CODECID_VP6:
192             return vcodec->codec_id == AV_CODEC_ID_VP6F;
193         case FLV_CODECID_VP6A:
194             return vcodec->codec_id == AV_CODEC_ID_VP6A;
195         case FLV_CODECID_H264:
196             return vcodec->codec_id == AV_CODEC_ID_H264;
197         default:
198             return vcodec->codec_tag == flv_codecid;
199     }
200 }
201
202 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
203     AVCodecContext *vcodec = vstream->codec;
204     switch(flv_codecid) {
205         case FLV_CODECID_H263  : vcodec->codec_id = AV_CODEC_ID_FLV1   ; break;
206         case FLV_CODECID_REALH263: vcodec->codec_id = AV_CODEC_ID_H263 ; break; // Really mean it this time
207         case FLV_CODECID_SCREEN: vcodec->codec_id = AV_CODEC_ID_FLASHSV; break;
208         case FLV_CODECID_SCREEN2: vcodec->codec_id = AV_CODEC_ID_FLASHSV2; break;
209         case FLV_CODECID_VP6   : vcodec->codec_id = AV_CODEC_ID_VP6F   ;
210         case FLV_CODECID_VP6A  :
211             if(flv_codecid == FLV_CODECID_VP6A)
212                 vcodec->codec_id = AV_CODEC_ID_VP6A;
213             if(vcodec->extradata_size != 1) {
214                 vcodec->extradata_size = 1;
215                 vcodec->extradata = av_malloc(1 + FF_INPUT_BUFFER_PADDING_SIZE);
216             }
217             vcodec->extradata[0] = avio_r8(s->pb);
218             return 1; // 1 byte body size adjustment for flv_read_packet()
219         case FLV_CODECID_H264:
220             vcodec->codec_id = AV_CODEC_ID_H264;
221             return 3; // not 4, reading packet type will consume one byte
222         case FLV_CODECID_MPEG4:
223             vcodec->codec_id = AV_CODEC_ID_MPEG4;
224             return 3;
225         default:
226             av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
227             vcodec->codec_tag = flv_codecid;
228     }
229
230     return 0;
231 }
232
233 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
234     int length = avio_rb16(ioc);
235     if(length >= buffsize) {
236         avio_skip(ioc, length);
237         return -1;
238     }
239
240     avio_read(ioc, buffer, length);
241
242     buffer[length] = '\0';
243
244     return length;
245 }
246
247 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
248     FLVContext *flv = s->priv_data;
249     unsigned int timeslen = 0, fileposlen = 0, i;
250     char str_val[256];
251     int64_t *times = NULL;
252     int64_t *filepositions = NULL;
253     int ret = AVERROR(ENOSYS);
254     int64_t initial_pos = avio_tell(ioc);
255
256     if(vstream->nb_index_entries>0){
257         av_log(s, AV_LOG_WARNING, "Skiping duplicate index\n");
258         return 0;
259     }
260
261     if (s->flags & AVFMT_FLAG_IGNIDX)
262         return 0;
263
264     while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
265         int64_t** current_array;
266         unsigned int arraylen;
267
268         // Expect array object in context
269         if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
270             break;
271
272         arraylen = avio_rb32(ioc);
273         if(arraylen>>28)
274             break;
275
276         if       (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times){
277             current_array= &times;
278             timeslen= arraylen;
279         }else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions){
280             current_array= &filepositions;
281             fileposlen= arraylen;
282         }else // unexpected metatag inside keyframes, will not use such metadata for indexing
283             break;
284
285         if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
286             ret = AVERROR(ENOMEM);
287             goto finish;
288         }
289
290         for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
291             if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
292                 goto invalid;
293             current_array[0][i] = av_int2double(avio_rb64(ioc));
294         }
295         if (times && filepositions) {
296             // All done, exiting at a position allowing amf_parse_object
297             // to finish parsing the object
298             ret = 0;
299             break;
300         }
301     }
302
303     if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
304         for (i = 0; i < fileposlen; i++) {
305             av_add_index_entry(vstream, filepositions[i], times[i]*1000,
306                                0, 0, AVINDEX_KEYFRAME);
307             if (i < 2) {
308                 flv->validate_index[i].pos = filepositions[i];
309                 flv->validate_index[i].dts = times[i] * 1000;
310                 flv->validate_count = i + 1;
311             }
312         }
313     } else {
314 invalid:
315         av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
316     }
317
318 finish:
319     av_freep(&times);
320     av_freep(&filepositions);
321     avio_seek(ioc, initial_pos, SEEK_SET);
322     return ret;
323 }
324
325 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
326     AVCodecContext *acodec, *vcodec;
327     FLVContext *flv = s->priv_data;
328     AVIOContext *ioc;
329     AMFDataType amf_type;
330     char str_val[256];
331     double num_val;
332
333     num_val = 0;
334     ioc = s->pb;
335
336     amf_type = avio_r8(ioc);
337
338     switch(amf_type) {
339         case AMF_DATA_TYPE_NUMBER:
340             num_val = av_int2double(avio_rb64(ioc)); break;
341         case AMF_DATA_TYPE_BOOL:
342             num_val = avio_r8(ioc); break;
343         case AMF_DATA_TYPE_STRING:
344             if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
345                 return -1;
346             break;
347         case AMF_DATA_TYPE_OBJECT:
348             if ((vstream || astream) && ioc->seekable && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
349                 if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
350                                           max_pos) < 0)
351                     av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
352
353             while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
354                 if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
355                     return -1; //if we couldn't skip, bomb out.
356             }
357             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
358                 return -1;
359             break;
360         case AMF_DATA_TYPE_NULL:
361         case AMF_DATA_TYPE_UNDEFINED:
362         case AMF_DATA_TYPE_UNSUPPORTED:
363             break; //these take up no additional space
364         case AMF_DATA_TYPE_MIXEDARRAY:
365             avio_skip(ioc, 4); //skip 32-bit max array index
366             while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
367                 //this is the only case in which we would want a nested parse to not skip over the object
368                 if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
369                     return -1;
370             }
371             if(avio_r8(ioc) != AMF_END_OF_OBJECT)
372                 return -1;
373             break;
374         case AMF_DATA_TYPE_ARRAY: {
375             unsigned int arraylen, i;
376
377             arraylen = avio_rb32(ioc);
378             for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
379                 if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
380                     return -1; //if we couldn't skip, bomb out.
381             }
382         }
383             break;
384         case AMF_DATA_TYPE_DATE:
385             avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
386             break;
387         default: //unsupported type, we couldn't skip
388             return -1;
389     }
390
391     if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
392         acodec = astream ? astream->codec : NULL;
393         vcodec = vstream ? vstream->codec : NULL;
394
395         if (amf_type == AMF_DATA_TYPE_NUMBER) {
396             if (!strcmp(key, "duration"))
397                 s->duration = num_val * AV_TIME_BASE;
398             else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
399                 vcodec->bit_rate = num_val * 1024.0;
400             else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
401                 acodec->bit_rate = num_val * 1024.0;
402             else if (!strcmp(key, "datastream")) {
403                 AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
404                 if (!st)
405                     return AVERROR(ENOMEM);
406                 st->codec->codec_id = AV_CODEC_ID_TEXT;
407             } else if (flv->trust_metadata) {
408                 if (!strcmp(key, "videocodecid") && vcodec) {
409                     flv_set_video_codec(s, vstream, num_val);
410                 } else
411                 if (!strcmp(key, "audiocodecid") && acodec) {
412                     flv_set_audio_codec(s, astream, acodec, num_val);
413                 } else
414                 if (!strcmp(key, "audiosamplerate") && acodec) {
415                     acodec->sample_rate = num_val;
416                 } else
417                 if (!strcmp(key, "width") && vcodec) {
418                     vcodec->width = num_val;
419                 } else
420                 if (!strcmp(key, "height") && vcodec) {
421                     vcodec->height = num_val;
422                 }
423             }
424         }
425
426         if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
427            ((!acodec && !strcmp(key, "audiocodecid")) ||
428             (!vcodec && !strcmp(key, "videocodecid"))))
429                 s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
430
431         if (!strcmp(key, "duration")        ||
432             !strcmp(key, "filesize")        ||
433             !strcmp(key, "width")           ||
434             !strcmp(key, "height")          ||
435             !strcmp(key, "videodatarate")   ||
436             !strcmp(key, "framerate")       ||
437             !strcmp(key, "videocodecid")    ||
438             !strcmp(key, "audiodatarate")   ||
439             !strcmp(key, "audiosamplerate") ||
440             !strcmp(key, "audiosamplesize") ||
441             !strcmp(key, "stereo")          ||
442             !strcmp(key, "audiocodecid"))
443             return 0;
444
445         if(amf_type == AMF_DATA_TYPE_BOOL) {
446             av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
447             av_dict_set(&s->metadata, key, str_val, 0);
448         } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
449             snprintf(str_val, sizeof(str_val), "%.f", num_val);
450             av_dict_set(&s->metadata, key, str_val, 0);
451         } else if (amf_type == AMF_DATA_TYPE_STRING)
452             av_dict_set(&s->metadata, key, str_val, 0);
453     }
454
455     return 0;
456 }
457
458 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
459     AMFDataType type;
460     AVStream *stream, *astream, *vstream, *dstream;
461     AVIOContext *ioc;
462     int i;
463     char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
464
465     vstream = astream = dstream = NULL;
466     ioc = s->pb;
467
468     //first object needs to be "onMetaData" string
469     type = avio_r8(ioc);
470     if (type != AMF_DATA_TYPE_STRING ||
471         amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
472         return -1;
473
474     if (!strcmp(buffer, "onTextData"))
475         return 1;
476
477     if (strcmp(buffer, "onMetaData"))
478         return -1;
479
480     //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
481     for(i = 0; i < s->nb_streams; i++) {
482         stream = s->streams[i];
483         if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
484         else if(stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
485         else if(stream->codec->codec_type == AVMEDIA_TYPE_DATA) dstream = stream;
486     }
487
488     //parse the second object (we want a mixed array)
489     if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
490         return -1;
491
492     return 0;
493 }
494
495 static int flv_read_header(AVFormatContext *s)
496 {
497     int offset, flags;
498
499     avio_skip(s->pb, 4);
500     flags = avio_r8(s->pb);
501     /* old flvtool cleared this field */
502     /* FIXME: better fix needed */
503     if (!flags) {
504         flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
505         av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
506     }
507
508     s->ctx_flags |= AVFMTCTX_NOHEADER;
509
510     if(flags & FLV_HEADER_FLAG_HASVIDEO){
511         if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
512             return AVERROR(ENOMEM);
513     }
514     if(flags & FLV_HEADER_FLAG_HASAUDIO){
515         if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
516             return AVERROR(ENOMEM);
517     }
518     // Flag doesn't indicate whether or not there is script-data present. Must
519     // create that stream if it's encountered.
520
521     offset = avio_rb32(s->pb);
522     avio_seek(s->pb, offset, SEEK_SET);
523     avio_skip(s->pb, 4);
524
525     s->start_time = 0;
526
527     return 0;
528 }
529
530 static int flv_read_close(AVFormatContext *s)
531 {
532     int i;
533     FLVContext *flv = s->priv_data;
534     for(i=0; i<FLV_STREAM_TYPE_NB; i++)
535         av_freep(&flv->new_extradata[i]);
536     return 0;
537 }
538
539 static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
540 {
541     av_free(st->codec->extradata);
542     st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
543     if (!st->codec->extradata)
544         return AVERROR(ENOMEM);
545     st->codec->extradata_size = size;
546     avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
547     return 0;
548 }
549
550 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
551                                int size)
552 {
553     av_free(flv->new_extradata[stream]);
554     flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
555     if (!flv->new_extradata[stream])
556         return AVERROR(ENOMEM);
557     flv->new_extradata_size[stream] = size;
558     avio_read(pb, flv->new_extradata[stream], size);
559     return 0;
560 }
561
562 static void clear_index_entries(AVFormatContext *s, int64_t pos)
563 {
564     int i, j, out;
565     av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
566     for (i = 0; i < s->nb_streams; i++) {
567         AVStream *st = s->streams[i];
568         /* Remove all index entries that point to >= pos */
569         out = 0;
570         for (j = 0; j < st->nb_index_entries; j++) {
571             if (st->index_entries[j].pos < pos)
572                 st->index_entries[out++] = st->index_entries[j];
573         }
574         st->nb_index_entries = out;
575     }
576 }
577
578
579 static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
580                            int64_t dts, int64_t next)
581 {
582     int ret = AVERROR_INVALIDDATA, i;
583     AVIOContext *pb = s->pb;
584     AVStream *st = NULL;
585     AMFDataType type;
586     char buf[20];
587     int length;
588
589     type = avio_r8(pb);
590     if (type == AMF_DATA_TYPE_MIXEDARRAY)
591         avio_seek(pb, 4, SEEK_CUR);
592     else if (type != AMF_DATA_TYPE_OBJECT)
593         goto out;
594
595     amf_get_string(pb, buf, sizeof(buf));
596     if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
597         goto out;
598
599     amf_get_string(pb, buf, sizeof(buf));
600     //FIXME parse it as codec_id
601     amf_get_string(pb, buf, sizeof(buf));
602     if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
603         goto out;
604
605     length = avio_rb16(pb);
606     ret = av_get_packet(s->pb, pkt, length);
607     if (ret < 0) {
608         ret = AVERROR(EIO);
609         goto out;
610     }
611
612     for (i = 0; i < s->nb_streams; i++) {
613         st = s->streams[i];
614         if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
615             break;
616     }
617
618     if (i == s->nb_streams) {
619         st = create_stream(s, AVMEDIA_TYPE_DATA);
620         if (!st)
621             goto out;
622         st->codec->codec_id = AV_CODEC_ID_TEXT;
623     }
624
625     pkt->dts  = dts;
626     pkt->pts  = dts;
627     pkt->size = ret;
628
629     pkt->stream_index = st->index;
630     pkt->flags |= AV_PKT_FLAG_KEY;
631
632     avio_seek(s->pb, next + 4, SEEK_SET);
633 out:
634     return ret;
635 }
636
637 static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
638 {
639     FLVContext *flv = s->priv_data;
640     int ret, i, type, size, flags;
641     int stream_type=-1;
642     int64_t next, pos;
643     int64_t dts, pts = AV_NOPTS_VALUE;
644     int av_uninit(channels);
645     int av_uninit(sample_rate);
646     AVStream *st = NULL;
647
648  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
649     pos = avio_tell(s->pb);
650     type = avio_r8(s->pb);
651     size = avio_rb24(s->pb);
652     dts = avio_rb24(s->pb);
653     dts |= avio_r8(s->pb) << 24;
654     av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
655     if (url_feof(s->pb))
656         return AVERROR_EOF;
657     avio_skip(s->pb, 3); /* stream id, always 0 */
658     flags = 0;
659
660     if (flv->validate_next < flv->validate_count) {
661         int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
662         if (pos == validate_pos) {
663             if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
664                 VALIDATE_INDEX_TS_THRESH) {
665                 flv->validate_next++;
666             } else {
667                 clear_index_entries(s, validate_pos);
668                 flv->validate_count = 0;
669             }
670         } else if (pos > validate_pos) {
671             clear_index_entries(s, validate_pos);
672             flv->validate_count = 0;
673         }
674     }
675
676     if(size == 0)
677         continue;
678
679     next= size + avio_tell(s->pb);
680
681     if (type == FLV_TAG_TYPE_AUDIO) {
682         stream_type=FLV_STREAM_TYPE_AUDIO;
683         flags = avio_r8(s->pb);
684         size--;
685     } else if (type == FLV_TAG_TYPE_VIDEO) {
686         stream_type=FLV_STREAM_TYPE_VIDEO;
687         flags = avio_r8(s->pb);
688         size--;
689         if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
690             goto skip;
691     } else if (type == FLV_TAG_TYPE_META) {
692         if (size > 13+1+4 && dts == 0) { // Header-type metadata stuff
693             flv_read_metabody(s, next);
694             goto skip;
695         } else if (dts != 0) { // Script-data "special" metadata frames - don't skip
696             stream_type=FLV_STREAM_TYPE_DATA;
697         } else {
698             goto skip;
699         }
700     } else {
701         av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
702     skip:
703         avio_seek(s->pb, next, SEEK_SET);
704         continue;
705     }
706
707     /* skip empty data packets */
708     if (!size)
709         continue;
710
711     /* now find stream */
712     for(i=0;i<s->nb_streams;i++) {
713         st = s->streams[i];
714         if (stream_type == FLV_STREAM_TYPE_AUDIO) {
715             if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
716                 (s->audio_codec_id || flv_same_audio_codec(st->codec, flags))) {
717                 break;
718             }
719         } else
720         if (stream_type == FLV_STREAM_TYPE_VIDEO) {
721             if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
722                 (s->video_codec_id || flv_same_video_codec(st->codec, flags))) {
723                 break;
724             }
725         } else if (stream_type == FLV_STREAM_TYPE_DATA) {
726             if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
727                 break;
728         }
729     }
730     if(i == s->nb_streams){
731         av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
732         st = create_stream(s,
733              (int[]){AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA}[stream_type]);
734         if (!st)
735             return AVERROR(ENOMEM);
736
737     }
738     av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
739     if(  (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
740        ||(st->discard >= AVDISCARD_BIDIR  &&  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
741        || st->discard >= AVDISCARD_ALL
742        ){
743         avio_seek(s->pb, next, SEEK_SET);
744         continue;
745     }
746     if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
747         av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
748     break;
749  }
750
751     // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
752     if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE) && !flv->searched_for_end){
753         int size;
754         const int64_t pos= avio_tell(s->pb);
755         int64_t fsize= avio_size(s->pb);
756 retry_duration:
757         avio_seek(s->pb, fsize-4, SEEK_SET);
758         size= avio_rb32(s->pb);
759         avio_seek(s->pb, fsize-3-size, SEEK_SET);
760         if(size == avio_rb24(s->pb) + 11){
761             uint32_t ts = avio_rb24(s->pb);
762             ts |= avio_r8(s->pb) << 24;
763             if(ts)
764                 s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
765             else if (fsize >= 8 && fsize - 8 >= size){
766                 fsize -= size+4;
767                 goto retry_duration;
768             }
769         }
770
771         avio_seek(s->pb, pos, SEEK_SET);
772         flv->searched_for_end = 1;
773     }
774
775     if(stream_type == FLV_STREAM_TYPE_AUDIO){
776         int bits_per_coded_sample;
777         channels    = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
778         sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
779         bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
780         if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
781             st->codec->channels              = channels;
782             st->codec->channel_layout        = channels == 1 ? AV_CH_LAYOUT_MONO :
783                                                                AV_CH_LAYOUT_STEREO;
784             st->codec->sample_rate           = sample_rate;
785             st->codec->bits_per_coded_sample = bits_per_coded_sample;
786         }
787         if(!st->codec->codec_id){
788             flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
789             flv->last_sample_rate = sample_rate = st->codec->sample_rate;
790             flv->last_channels    = channels    = st->codec->channels;
791         } else {
792             AVCodecContext ctx;
793             ctx.sample_rate = sample_rate;
794             flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
795             sample_rate = ctx.sample_rate;
796         }
797     } else if(stream_type == FLV_STREAM_TYPE_VIDEO) {
798         size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
799     }
800
801     if (st->codec->codec_id == AV_CODEC_ID_AAC ||
802         st->codec->codec_id == AV_CODEC_ID_H264 ||
803         st->codec->codec_id == AV_CODEC_ID_MPEG4) {
804         int type = avio_r8(s->pb);
805         size--;
806         if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
807             int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
808             pts = dts + cts;
809             if (cts < 0) { // dts are wrong
810                 flv->wrong_dts = 1;
811                 av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
812             }
813             if (flv->wrong_dts)
814                 dts = AV_NOPTS_VALUE;
815         }
816         if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
817             if (st->codec->extradata) {
818                 if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
819                     return ret;
820                 ret = AVERROR(EAGAIN);
821                 goto leave;
822             }
823             if ((ret = flv_get_extradata(s, st, size)) < 0)
824                 return ret;
825             if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
826                 MPEG4AudioConfig cfg;
827                 if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
828                                              st->codec->extradata_size * 8, 1) >= 0) {
829                 st->codec->channels = cfg.channels;
830                 st->codec->channel_layout = 0;
831                 if (cfg.ext_sample_rate)
832                     st->codec->sample_rate = cfg.ext_sample_rate;
833                 else
834                     st->codec->sample_rate = cfg.sample_rate;
835                 av_dlog(s, "mp4a config channels %d sample rate %d\n",
836                         st->codec->channels, st->codec->sample_rate);
837                 }
838             }
839
840             ret = AVERROR(EAGAIN);
841             goto leave;
842         }
843     }
844
845     /* skip empty data packets */
846     if (!size) {
847         ret = AVERROR(EAGAIN);
848         goto leave;
849     }
850
851     ret= av_get_packet(s->pb, pkt, size);
852     if (ret < 0)
853         return ret;
854     pkt->dts = dts;
855     pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
856     pkt->stream_index = st->index;
857     if (flv->new_extradata[stream_type]) {
858         uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
859                                                 flv->new_extradata_size[stream_type]);
860         if (side) {
861             memcpy(side, flv->new_extradata[stream_type],
862                    flv->new_extradata_size[stream_type]);
863             av_freep(&flv->new_extradata[stream_type]);
864             flv->new_extradata_size[stream_type] = 0;
865         }
866     }
867     if (stream_type == FLV_STREAM_TYPE_AUDIO && (sample_rate != flv->last_sample_rate ||
868                      channels != flv->last_channels)) {
869         flv->last_sample_rate = sample_rate;
870         flv->last_channels    = channels;
871         ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
872     }
873
874     if (    stream_type == FLV_STREAM_TYPE_AUDIO ||
875             ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
876             stream_type == FLV_STREAM_TYPE_DATA)
877         pkt->flags |= AV_PKT_FLAG_KEY;
878
879 leave:
880     avio_skip(s->pb, 4);
881     return ret;
882 }
883
884 static int flv_read_seek(AVFormatContext *s, int stream_index,
885     int64_t ts, int flags)
886 {
887     FLVContext *flv = s->priv_data;
888     flv->validate_count = 0;
889     return avio_seek_time(s->pb, stream_index, ts, flags);
890 }
891
892 #define OFFSET(x) offsetof(FLVContext, x)
893 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
894 static const AVOption options[] = {
895     { "flv_metadata", "Allocate streams according the onMetaData array",      OFFSET(trust_metadata), AV_OPT_TYPE_INT,    { .i64 = 0 }, 0, 1, VD},
896     { NULL }
897 };
898
899 static const AVClass class = {
900     .class_name = "flvdec",
901     .item_name  = av_default_item_name,
902     .option     = options,
903     .version    = LIBAVUTIL_VERSION_INT,
904 };
905
906 AVInputFormat ff_flv_demuxer = {
907     .name           = "flv",
908     .long_name      = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
909     .priv_data_size = sizeof(FLVContext),
910     .read_probe     = flv_probe,
911     .read_header    = flv_read_header,
912     .read_packet    = flv_read_packet,
913     .read_seek      = flv_read_seek,
914     .read_close     = flv_read_close,
915     .extensions     = "flv",
916     .priv_class     = &class,
917 };