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