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