FFmpeg
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
flvdec.c
Go to the documentation of this file.
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"
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];
50  struct {
51  int64_t dts;
52  int64_t pos;
53  } validate_index[2];
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 
75 {
76  AVStream *st = avformat_new_stream(s, NULL);
77  if (!st)
78  return NULL;
80  if (s->nb_streams>=3 ||( s->nb_streams==2
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
106 #if HAVE_BIGENDIAN
108 #else
110 #endif
111  return codec_id == acodec->codec_id;
112  case FLV_CODECID_PCM_LE:
113  codec_id = bits_per_coded_sample == 8
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;
128  return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
130  return acodec->sample_rate == 8000 &&
131  acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
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 
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
148 #if HAVE_BIGENDIAN
150 #else
152 #endif
153  break;
154  case FLV_CODECID_PCM_LE:
155  acodec->codec_id = acodec->bits_per_coded_sample == 8
158  break;
159  case FLV_CODECID_AAC:
160  acodec->codec_id = AV_CODEC_ID_AAC;
161  break;
162  case FLV_CODECID_ADPCM:
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;
172  break;
174  // in case metadata does not otherwise declare samplerate
175  acodec->sample_rate = 8000;
177  break;
179  acodec->sample_rate = 16000;
181  break;
184  break;
186  acodec->sample_rate = 8000;
188  break;
190  acodec->sample_rate = 8000;
191  acodec->codec_id = AV_CODEC_ID_PCM_ALAW;
192  break;
193  default:
194  avpriv_request_sample(s, "Audio codec (%x)",
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 
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;
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  ff_alloc_extradata(vcodec, 1);
250  }
251  if (vcodec->extradata)
252  vcodec->extradata[0] = avio_r8(s->pb);
253  else
254  avio_skip(s->pb, 1);
255  }
256  return 1; // 1 byte body size adjustment for flv_read_packet()
257  case FLV_CODECID_H264:
258  vcodec->codec_id = AV_CODEC_ID_H264;
259  return 3; // not 4, reading packet type will consume one byte
260  case FLV_CODECID_MPEG4:
261  vcodec->codec_id = AV_CODEC_ID_MPEG4;
262  return 3;
263  default:
264  avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
265  vcodec->codec_tag = flv_codecid;
266  }
267 
268  return 0;
269 }
270 
271 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
272 {
273  int length = avio_rb16(ioc);
274  if (length >= buffsize) {
275  avio_skip(ioc, length);
276  return -1;
277  }
278 
279  avio_read(ioc, buffer, length);
280 
281  buffer[length] = '\0';
282 
283  return length;
284 }
285 
287  AVStream *vstream, int64_t max_pos)
288 {
289  FLVContext *flv = s->priv_data;
290  unsigned int timeslen = 0, fileposlen = 0, i;
291  char str_val[256];
292  int64_t *times = NULL;
293  int64_t *filepositions = NULL;
294  int ret = AVERROR(ENOSYS);
295  int64_t initial_pos = avio_tell(ioc);
296 
297  if (vstream->nb_index_entries>0) {
298  av_log(s, AV_LOG_WARNING, "Skiping duplicate index\n");
299  return 0;
300  }
301 
302  if (s->flags & AVFMT_FLAG_IGNIDX)
303  return 0;
304 
305  while (avio_tell(ioc) < max_pos - 2 &&
306  amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
307  int64_t **current_array;
308  unsigned int arraylen;
309 
310  // Expect array object in context
311  if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
312  break;
313 
314  arraylen = avio_rb32(ioc);
315  if (arraylen>>28)
316  break;
317 
318  if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
319  current_array = &times;
320  timeslen = arraylen;
321  } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
322  !filepositions) {
323  current_array = &filepositions;
324  fileposlen = arraylen;
325  } else
326  // unexpected metatag inside keyframes, will not use such
327  // metadata for indexing
328  break;
329 
330  if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
331  ret = AVERROR(ENOMEM);
332  goto finish;
333  }
334 
335  for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
336  if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
337  goto invalid;
338  current_array[0][i] = av_int2double(avio_rb64(ioc));
339  }
340  if (times && filepositions) {
341  // All done, exiting at a position allowing amf_parse_object
342  // to finish parsing the object
343  ret = 0;
344  break;
345  }
346  }
347 
348  if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
349  for (i = 0; i < fileposlen; i++) {
350  av_add_index_entry(vstream, filepositions[i], times[i] * 1000,
351  0, 0, AVINDEX_KEYFRAME);
352  if (i < 2) {
353  flv->validate_index[i].pos = filepositions[i];
354  flv->validate_index[i].dts = times[i] * 1000;
355  flv->validate_count = i + 1;
356  }
357  }
358  } else {
359 invalid:
360  av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
361  }
362 
363 finish:
364  av_freep(&times);
365  av_freep(&filepositions);
366  avio_seek(ioc, initial_pos, SEEK_SET);
367  return ret;
368 }
369 
371  AVStream *vstream, const char *key,
372  int64_t max_pos, int depth)
373 {
374  AVCodecContext *acodec, *vcodec;
375  FLVContext *flv = s->priv_data;
376  AVIOContext *ioc;
377  AMFDataType amf_type;
378  char str_val[256];
379  double num_val;
380 
381  num_val = 0;
382  ioc = s->pb;
383  amf_type = avio_r8(ioc);
384 
385  switch (amf_type) {
387  num_val = av_int2double(avio_rb64(ioc));
388  break;
389  case AMF_DATA_TYPE_BOOL:
390  num_val = avio_r8(ioc);
391  break;
393  if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
394  return -1;
395  break;
397  if ((vstream || astream) && key &&
398  ioc->seekable &&
399  !strcmp(KEYFRAMES_TAG, key) && depth == 1)
400  if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
401  max_pos) < 0)
402  av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
403 
404  while (avio_tell(ioc) < max_pos - 2 &&
405  amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
406  if (amf_parse_object(s, astream, vstream, str_val, max_pos,
407  depth + 1) < 0)
408  return -1; // if we couldn't skip, bomb out.
409  if (avio_r8(ioc) != AMF_END_OF_OBJECT)
410  return -1;
411  break;
412  case AMF_DATA_TYPE_NULL:
415  break; // these take up no additional space
417  avio_skip(ioc, 4); // skip 32-bit max array index
418  while (avio_tell(ioc) < max_pos - 2 &&
419  amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
420  // this is the only case in which we would want a nested
421  // parse to not skip over the object
422  if (amf_parse_object(s, astream, vstream, str_val, max_pos,
423  depth + 1) < 0)
424  return -1;
425  if (avio_r8(ioc) != AMF_END_OF_OBJECT)
426  return -1;
427  break;
428  case AMF_DATA_TYPE_ARRAY:
429  {
430  unsigned int arraylen, i;
431 
432  arraylen = avio_rb32(ioc);
433  for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
434  if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
435  depth + 1) < 0)
436  return -1; // if we couldn't skip, bomb out.
437  }
438  break;
439  case AMF_DATA_TYPE_DATE:
440  avio_skip(ioc, 8 + 2); // timestamp (double) and UTC offset (int16)
441  break;
442  default: // unsupported type, we couldn't skip
443  return -1;
444  }
445 
446  // only look for metadata values when we are not nested and key != NULL
447  if (depth == 1 && key) {
448  acodec = astream ? astream->codec : NULL;
449  vcodec = vstream ? vstream->codec : NULL;
450 
451  if (amf_type == AMF_DATA_TYPE_NUMBER ||
452  amf_type == AMF_DATA_TYPE_BOOL) {
453  if (!strcmp(key, "duration"))
454  s->duration = num_val * AV_TIME_BASE;
455  else if (!strcmp(key, "videodatarate") && vcodec &&
456  0 <= (int)(num_val * 1024.0))
457  vcodec->bit_rate = num_val * 1024.0;
458  else if (!strcmp(key, "audiodatarate") && acodec &&
459  0 <= (int)(num_val * 1024.0))
460  acodec->bit_rate = num_val * 1024.0;
461  else if (!strcmp(key, "datastream")) {
463  if (!st)
464  return AVERROR(ENOMEM);
466  } else if (flv->trust_metadata) {
467  if (!strcmp(key, "videocodecid") && vcodec) {
468  flv_set_video_codec(s, vstream, num_val, 0);
469  } else if (!strcmp(key, "audiocodecid") && acodec) {
470  int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
471  flv_set_audio_codec(s, astream, acodec, id);
472  } else if (!strcmp(key, "audiosamplerate") && acodec) {
473  acodec->sample_rate = num_val;
474  } else if (!strcmp(key, "audiosamplesize") && acodec) {
475  acodec->bits_per_coded_sample = num_val;
476  } else if (!strcmp(key, "stereo") && acodec) {
477  acodec->channels = num_val + 1;
478  acodec->channel_layout = acodec->channels == 2 ?
481  } else if (!strcmp(key, "width") && vcodec) {
482  vcodec->width = num_val;
483  } else if (!strcmp(key, "height") && vcodec) {
484  vcodec->height = num_val;
485  }
486  }
487  }
488 
489  if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
490  ((!acodec && !strcmp(key, "audiocodecid")) ||
491  (!vcodec && !strcmp(key, "videocodecid"))))
492  s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
493 
494  if (!strcmp(key, "duration") ||
495  !strcmp(key, "filesize") ||
496  !strcmp(key, "width") ||
497  !strcmp(key, "height") ||
498  !strcmp(key, "videodatarate") ||
499  !strcmp(key, "framerate") ||
500  !strcmp(key, "videocodecid") ||
501  !strcmp(key, "audiodatarate") ||
502  !strcmp(key, "audiosamplerate") ||
503  !strcmp(key, "audiosamplesize") ||
504  !strcmp(key, "stereo") ||
505  !strcmp(key, "audiocodecid") ||
506  !strcmp(key, "datastream"))
507  return 0;
508 
509  if (amf_type == AMF_DATA_TYPE_BOOL) {
510  av_strlcpy(str_val, num_val > 0 ? "true" : "false",
511  sizeof(str_val));
512  av_dict_set(&s->metadata, key, str_val, 0);
513  } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
514  snprintf(str_val, sizeof(str_val), "%.f", num_val);
515  av_dict_set(&s->metadata, key, str_val, 0);
516  } else if (amf_type == AMF_DATA_TYPE_STRING)
517  av_dict_set(&s->metadata, key, str_val, 0);
518  }
519 
520  return 0;
521 }
522 
523 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
524 {
526  AVStream *stream, *astream, *vstream;
527  AVStream av_unused *dstream;
528  AVIOContext *ioc;
529  int i;
530  // only needs to hold the string "onMetaData".
531  // Anything longer is something we don't want.
532  char buffer[11];
533 
534  astream = NULL;
535  vstream = NULL;
536  dstream = NULL;
537  ioc = s->pb;
538 
539  // first object needs to be "onMetaData" string
540  type = avio_r8(ioc);
541  if (type != AMF_DATA_TYPE_STRING ||
542  amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
543  return -1;
544 
545  if (!strcmp(buffer, "onTextData"))
546  return 1;
547 
548  if (strcmp(buffer, "onMetaData"))
549  return -1;
550 
551  // find the streams now so that amf_parse_object doesn't need to do
552  // the lookup every time it is called.
553  for (i = 0; i < s->nb_streams; i++) {
554  stream = s->streams[i];
555  if (stream->codec->codec_type == AVMEDIA_TYPE_VIDEO)
556  vstream = stream;
557  else if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO)
558  astream = stream;
559  else if (stream->codec->codec_type == AVMEDIA_TYPE_DATA)
560  dstream = stream;
561  }
562 
563  // parse the second object (we want a mixed array)
564  if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
565  return -1;
566 
567  return 0;
568 }
569 
571 {
572  int offset, flags;
573 
574  avio_skip(s->pb, 4);
575  flags = avio_r8(s->pb);
576  /* old flvtool cleared this field */
577  /* FIXME: better fix needed */
578  if (!flags) {
581  "Broken FLV file, which says no streams present, "
582  "this might fail\n");
583  }
584 
586 
587  if (flags & FLV_HEADER_FLAG_HASVIDEO)
589  return AVERROR(ENOMEM);
590  if (flags & FLV_HEADER_FLAG_HASAUDIO)
592  return AVERROR(ENOMEM);
593  // Flag doesn't indicate whether or not there is script-data present. Must
594  // create that stream if it's encountered.
595 
596  offset = avio_rb32(s->pb);
597  avio_seek(s->pb, offset, SEEK_SET);
598  avio_skip(s->pb, 4);
599 
600  s->start_time = 0;
601 
602  return 0;
603 }
604 
606 {
607  int i;
608  FLVContext *flv = s->priv_data;
609  for (i=0; i<FLV_STREAM_TYPE_NB; i++)
610  av_freep(&flv->new_extradata[i]);
611  return 0;
612 }
613 
615 {
616  av_free(st->codec->extradata);
617  if (ff_alloc_extradata(st->codec, size))
618  return AVERROR(ENOMEM);
620  return 0;
621 }
622 
623 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
624  int size)
625 {
626  av_free(flv->new_extradata[stream]);
627  flv->new_extradata[stream] = av_mallocz(size +
629  if (!flv->new_extradata[stream])
630  return AVERROR(ENOMEM);
631  flv->new_extradata_size[stream] = size;
632  avio_read(pb, flv->new_extradata[stream], size);
633  return 0;
634 }
635 
636 static void clear_index_entries(AVFormatContext *s, int64_t pos)
637 {
638  int i, j, out;
640  "Found invalid index entries, clearing the index.\n");
641  for (i = 0; i < s->nb_streams; i++) {
642  AVStream *st = s->streams[i];
643  /* Remove all index entries that point to >= pos */
644  out = 0;
645  for (j = 0; j < st->nb_index_entries; j++)
646  if (st->index_entries[j].pos < pos)
647  st->index_entries[out++] = st->index_entries[j];
648  st->nb_index_entries = out;
649  }
650 }
651 
652 static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
653 {
654  int nb = -1, ret, parse_name = 1;
655 
656  switch (type) {
658  avio_skip(pb, 8);
659  break;
660  case AMF_DATA_TYPE_BOOL:
661  avio_skip(pb, 1);
662  break;
664  avio_skip(pb, avio_rb16(pb));
665  break;
666  case AMF_DATA_TYPE_ARRAY:
667  parse_name = 0;
669  nb = avio_rb32(pb);
671  while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
672  if (parse_name) {
673  int size = avio_rb16(pb);
674  if (!size) {
675  avio_skip(pb, 1);
676  break;
677  }
678  avio_skip(pb, size);
679  }
680  if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
681  return ret;
682  }
683  break;
684  case AMF_DATA_TYPE_NULL:
686  break;
687  default:
688  return AVERROR_INVALIDDATA;
689  }
690  return 0;
691 }
692 
694  int64_t dts, int64_t next)
695 {
696  AVIOContext *pb = s->pb;
697  AVStream *st = NULL;
698  char buf[20];
699  int ret = AVERROR_INVALIDDATA;
700  int i, length = -1;
701 
702  switch (avio_r8(pb)) {
704  avio_seek(pb, 4, SEEK_CUR);
706  break;
707  default:
708  goto skip;
709  }
710 
711  while ((ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
712  AMFDataType type = avio_r8(pb);
713  if (type == AMF_DATA_TYPE_STRING && !strcmp(buf, "text")) {
714  length = avio_rb16(pb);
715  ret = av_get_packet(pb, pkt, length);
716  if (ret < 0)
717  goto skip;
718  else
719  break;
720  } else {
721  if ((ret = amf_skip_tag(pb, type)) < 0)
722  goto skip;
723  }
724  }
725 
726  if (length < 0) {
727  ret = AVERROR_INVALIDDATA;
728  goto skip;
729  }
730 
731  for (i = 0; i < s->nb_streams; i++) {
732  st = s->streams[i];
733  if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
734  break;
735  }
736 
737  if (i == s->nb_streams) {
739  if (!st)
740  return AVERROR_INVALIDDATA;
742  }
743 
744  pkt->dts = dts;
745  pkt->pts = dts;
746  pkt->size = ret;
747 
748  pkt->stream_index = st->index;
749  pkt->flags |= AV_PKT_FLAG_KEY;
750 
751 skip:
752  avio_seek(s->pb, next + 4, SEEK_SET);
753 
754  return ret;
755 }
756 
758 {
759  FLVContext *flv = s->priv_data;
760  int ret, i, type, size, flags;
761  int stream_type=-1;
762  int64_t next, pos, meta_pos;
763  int64_t dts, pts = AV_NOPTS_VALUE;
764  int av_uninit(channels);
765  int av_uninit(sample_rate);
766  AVStream *st = NULL;
767 
768  /* pkt size is repeated at end. skip it */
769  for (;; avio_skip(s->pb, 4)) {
770  pos = avio_tell(s->pb);
771  type = avio_r8(s->pb);
772  size = avio_rb24(s->pb);
773  dts = avio_rb24(s->pb);
774  dts |= avio_r8(s->pb) << 24;
775  av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
776  if (url_feof(s->pb))
777  return AVERROR_EOF;
778  avio_skip(s->pb, 3); /* stream id, always 0 */
779  flags = 0;
780 
781  if (flv->validate_next < flv->validate_count) {
782  int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
783  if (pos == validate_pos) {
784  if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
786  flv->validate_next++;
787  } else {
788  clear_index_entries(s, validate_pos);
789  flv->validate_count = 0;
790  }
791  } else if (pos > validate_pos) {
792  clear_index_entries(s, validate_pos);
793  flv->validate_count = 0;
794  }
795  }
796 
797  if (size == 0)
798  continue;
799 
800  next = size + avio_tell(s->pb);
801 
802  if (type == FLV_TAG_TYPE_AUDIO) {
803  stream_type = FLV_STREAM_TYPE_AUDIO;
804  flags = avio_r8(s->pb);
805  size--;
806  } else if (type == FLV_TAG_TYPE_VIDEO) {
807  stream_type = FLV_STREAM_TYPE_VIDEO;
808  flags = avio_r8(s->pb);
809  size--;
811  goto skip;
812  } else if (type == FLV_TAG_TYPE_META) {
813  stream_type=FLV_STREAM_TYPE_DATA;
814  if (size > 13 + 1 + 4 && dts == 0) { // Header-type metadata stuff
815  meta_pos = avio_tell(s->pb);
816  if (flv_read_metabody(s, next) == 0) {
817  goto skip;
818  }
819  avio_seek(s->pb, meta_pos, SEEK_SET);
820  }
821  } else {
822  av_log(s, AV_LOG_DEBUG,
823  "skipping flv packet: type %d, size %d, flags %d\n",
824  type, size, flags);
825 skip:
826  avio_seek(s->pb, next, SEEK_SET);
827  continue;
828  }
829 
830  /* skip empty data packets */
831  if (!size)
832  continue;
833 
834  /* now find stream */
835  for (i = 0; i < s->nb_streams; i++) {
836  st = s->streams[i];
837  if (stream_type == FLV_STREAM_TYPE_AUDIO) {
838  if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
839  (s->audio_codec_id || flv_same_audio_codec(st->codec, flags)))
840  break;
841  } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
842  if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
843  (s->video_codec_id || flv_same_video_codec(st->codec, flags)))
844  break;
845  } else if (stream_type == FLV_STREAM_TYPE_DATA) {
846  if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
847  break;
848  }
849  }
850  if (i == s->nb_streams) {
851  static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
852  av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
853  st = create_stream(s, stream_types[stream_type]);
854  if (!st)
855  return AVERROR(ENOMEM);
856 
857  }
858  av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
859  if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
860  ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
861  || st->discard >= AVDISCARD_ALL
862  ) {
863  avio_seek(s->pb, next, SEEK_SET);
864  continue;
865  }
866  if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)
867  av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
868  break;
869  }
870 
871  // if not streamed and no duration from metadata then seek to end to find
872  // the duration from the timestamps
873  if (s->pb->seekable && (!s->duration || s->duration == AV_NOPTS_VALUE) && !flv->searched_for_end) {
874  int size;
875  const int64_t pos = avio_tell(s->pb);
876  int64_t fsize = avio_size(s->pb);
877 retry_duration:
878  avio_seek(s->pb, fsize - 4, SEEK_SET);
879  size = avio_rb32(s->pb);
880  avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
881  if (size == avio_rb24(s->pb) + 11) {
882  uint32_t ts = avio_rb24(s->pb);
883  ts |= avio_r8(s->pb) << 24;
884  if (ts)
885  s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
886  else if (fsize >= 8 && fsize - 8 >= size) {
887  fsize -= size+4;
888  goto retry_duration;
889  }
890  }
891 
892  avio_seek(s->pb, pos, SEEK_SET);
893  flv->searched_for_end = 1;
894  }
895 
896  if (stream_type == FLV_STREAM_TYPE_AUDIO) {
897  int bits_per_coded_sample;
898  channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
899  sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
901  bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
902  if (!st->codec->channels || !st->codec->sample_rate ||
904  st->codec->channels = channels;
905  st->codec->channel_layout = channels == 1
909  st->codec->bits_per_coded_sample = bits_per_coded_sample;
910  }
911  if (!st->codec->codec_id) {
912  flv_set_audio_codec(s, st, st->codec,
913  flags & FLV_AUDIO_CODECID_MASK);
914  flv->last_sample_rate =
916  flv->last_channels =
917  channels = st->codec->channels;
918  } else {
919  AVCodecContext ctx = {0};
920  ctx.sample_rate = sample_rate;
921  flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
922  sample_rate = ctx.sample_rate;
923  }
924  } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
925  size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
926  }
927 
928  if (st->codec->codec_id == AV_CODEC_ID_AAC ||
929  st->codec->codec_id == AV_CODEC_ID_H264 ||
930  st->codec->codec_id == AV_CODEC_ID_MPEG4) {
931  int type = avio_r8(s->pb);
932  size--;
934  // sign extension
935  int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
936  pts = dts + cts;
937  if (cts < 0) { // dts are wrong
938  flv->wrong_dts = 1;
940  "negative cts, previous timestamps might be wrong\n");
941  }
942  if (flv->wrong_dts)
943  dts = AV_NOPTS_VALUE;
944  }
945  if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
946  if (st->codec->extradata) {
947  if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
948  return ret;
949  ret = AVERROR(EAGAIN);
950  goto leave;
951  }
952  if ((ret = flv_get_extradata(s, st, size)) < 0)
953  return ret;
954  if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
955  MPEG4AudioConfig cfg;
957  st->codec->extradata_size * 8, 1) >= 0) {
958  st->codec->channels = cfg.channels;
959  st->codec->channel_layout = 0;
960  if (cfg.ext_sample_rate)
961  st->codec->sample_rate = cfg.ext_sample_rate;
962  else
963  st->codec->sample_rate = cfg.sample_rate;
964  av_dlog(s, "mp4a config channels %d sample rate %d\n",
965  st->codec->channels, st->codec->sample_rate);
966  }
967  }
968 
969  ret = AVERROR(EAGAIN);
970  goto leave;
971  }
972  }
973 
974  /* skip empty data packets */
975  if (!size) {
976  ret = AVERROR(EAGAIN);
977  goto leave;
978  }
979 
980  ret = av_get_packet(s->pb, pkt, size);
981  if (ret < 0)
982  return ret;
983  pkt->dts = dts;
984  pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
985  pkt->stream_index = st->index;
986  if (flv->new_extradata[stream_type]) {
988  flv->new_extradata_size[stream_type]);
989  if (side) {
990  memcpy(side, flv->new_extradata[stream_type],
991  flv->new_extradata_size[stream_type]);
992  av_freep(&flv->new_extradata[stream_type]);
993  flv->new_extradata_size[stream_type] = 0;
994  }
995  }
996  if (stream_type == FLV_STREAM_TYPE_AUDIO &&
997  (sample_rate != flv->last_sample_rate ||
998  channels != flv->last_channels)) {
1000  flv->last_channels = channels;
1001  ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
1002  }
1003 
1004  if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
1005  ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
1006  stream_type == FLV_STREAM_TYPE_DATA)
1007  pkt->flags |= AV_PKT_FLAG_KEY;
1008 
1009 leave:
1010  avio_skip(s->pb, 4);
1011  return ret;
1012 }
1013 
1014 static int flv_read_seek(AVFormatContext *s, int stream_index,
1015  int64_t ts, int flags)
1016 {
1017  FLVContext *flv = s->priv_data;
1018  flv->validate_count = 0;
1019  return avio_seek_time(s->pb, stream_index, ts, flags);
1020 }
1021 
1022 #define OFFSET(x) offsetof(FLVContext, x)
1023 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
1024 static const AVOption options[] = {
1025  { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD },
1026  { NULL }
1027 };
1028 
1029 static const AVClass flv_class = {
1030  .class_name = "flvdec",
1031  .item_name = av_default_item_name,
1032  .option = options,
1033  .version = LIBAVUTIL_VERSION_INT,
1034 };
1035 
1037  .name = "flv",
1038  .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
1039  .priv_data_size = sizeof(FLVContext),
1040  .read_probe = flv_probe,
1045  .extensions = "flv",
1046  .priv_class = &flv_class,
1047 };