flvdec.c
Go to the documentation of this file.
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"
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;
49  int wrong_dts;
50  uint8_t *new_extradata[2];
51  int new_extradata_size[2];
54  struct {
55  int64_t dts;
56  int64_t pos;
57  } validate_index[2];
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' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
68  return AVPROBE_SCORE_MAX;
69  }
70  return 0;
71 }
72 
74 {
76  if (!st)
77  return NULL;
79  avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
80  return st;
81 }
82 static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
83 {
84  int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
85  int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
86  int codec_id;
87 
88  if (!acodec->codec_id && !acodec->codec_tag)
89  return 1;
90 
91  if (acodec->bits_per_coded_sample != bits_per_coded_sample)
92  return 0;
93 
94  switch(flv_codecid) {
95  //no distinction between S16 and S8 PCM codec flags
96  case FLV_CODECID_PCM:
97  codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
98 #if HAVE_BIGENDIAN
100 #else
102 #endif
103  return codec_id == acodec->codec_id;
104  case FLV_CODECID_PCM_LE:
105  codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;
106  return codec_id == acodec->codec_id;
107  case FLV_CODECID_AAC:
108  return acodec->codec_id == AV_CODEC_ID_AAC;
109  case FLV_CODECID_ADPCM:
110  return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
111  case FLV_CODECID_SPEEX:
112  return acodec->codec_id == AV_CODEC_ID_SPEEX;
113  case FLV_CODECID_MP3:
114  return acodec->codec_id == AV_CODEC_ID_MP3;
118  return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
120  return acodec->sample_rate == 8000 &&
121  acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
123  return acodec->sample_rate = 8000 &&
124  acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
125  default:
126  return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
127  }
128 
129  return 0;
130 }
131 
132 static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
133  switch(flv_codecid) {
134  //no distinction between S16 and S8 PCM codec flags
135  case FLV_CODECID_PCM:
136  acodec->codec_id = acodec->bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
137 #if HAVE_BIGENDIAN
139 #else
141 #endif
142  break;
143  case FLV_CODECID_PCM_LE:
145  case FLV_CODECID_AAC : acodec->codec_id = AV_CODEC_ID_AAC; break;
146  case FLV_CODECID_ADPCM: acodec->codec_id = AV_CODEC_ID_ADPCM_SWF; break;
147  case FLV_CODECID_SPEEX:
148  acodec->codec_id = AV_CODEC_ID_SPEEX;
149  acodec->sample_rate = 16000;
150  break;
151  case FLV_CODECID_MP3 : acodec->codec_id = AV_CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
153  acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
155  break;
157  acodec->sample_rate = 16000;
159  break;
162  break;
164  acodec->sample_rate = 8000;
166  break;
168  acodec->sample_rate = 8000;
169  acodec->codec_id = AV_CODEC_ID_PCM_ALAW;
170  break;
171  default:
172  av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
173  acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
174  }
175 }
176 
177 static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
178 {
179  int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
180 
181  if (!vcodec->codec_id && !vcodec->codec_tag)
182  return 1;
183 
184  switch (flv_codecid) {
185  case FLV_CODECID_H263:
186  return vcodec->codec_id == AV_CODEC_ID_FLV1;
187  case FLV_CODECID_SCREEN:
188  return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
189  case FLV_CODECID_SCREEN2:
190  return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
191  case FLV_CODECID_VP6:
192  return vcodec->codec_id == AV_CODEC_ID_VP6F;
193  case FLV_CODECID_VP6A:
194  return vcodec->codec_id == AV_CODEC_ID_VP6A;
195  case FLV_CODECID_H264:
196  return vcodec->codec_id == AV_CODEC_ID_H264;
197  default:
198  return vcodec->codec_tag == flv_codecid;
199  }
200 
201  return 0;
202 }
203 
204 static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid, int read) {
205  AVCodecContext *vcodec = vstream->codec;
206  switch(flv_codecid) {
207  case FLV_CODECID_H263 : vcodec->codec_id = AV_CODEC_ID_FLV1 ; break;
208  case FLV_CODECID_SCREEN: vcodec->codec_id = AV_CODEC_ID_FLASHSV; break;
209  case FLV_CODECID_SCREEN2: vcodec->codec_id = AV_CODEC_ID_FLASHSV2; break;
210  case FLV_CODECID_VP6 : vcodec->codec_id = AV_CODEC_ID_VP6F ;
211  case FLV_CODECID_VP6A :
212  if(flv_codecid == FLV_CODECID_VP6A)
213  vcodec->codec_id = AV_CODEC_ID_VP6A;
214  if (read) {
215  if (vcodec->extradata_size != 1) {
216  vcodec->extradata = av_malloc(1);
217  if (vcodec->extradata)
218  vcodec->extradata_size = 1;
219  }
220  if (vcodec->extradata)
221  vcodec->extradata[0] = avio_r8(s->pb);
222  else
223  avio_skip(s->pb, 1);
224  }
225  return 1; // 1 byte body size adjustment for flv_read_packet()
226  case FLV_CODECID_H264:
227  vcodec->codec_id = AV_CODEC_ID_H264;
228  return 3; // not 4, reading packet type will consume one byte
229  default:
230  av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
231  vcodec->codec_tag = flv_codecid;
232  }
233 
234  return 0;
235 }
236 
237 static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
238  int length = avio_rb16(ioc);
239  if(length >= buffsize) {
240  avio_skip(ioc, length);
241  return -1;
242  }
243 
244  avio_read(ioc, buffer, length);
245 
246  buffer[length] = '\0';
247 
248  return length;
249 }
250 
251 static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
252  FLVContext *flv = s->priv_data;
253  unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
254  double num_val;
255  char str_val[256];
256  int64_t *times = NULL;
257  int64_t *filepositions = NULL;
258  int ret = AVERROR(ENOSYS);
259  int64_t initial_pos = avio_tell(ioc);
260 
261  if (s->flags & AVFMT_FLAG_IGNIDX)
262  return 0;
263 
264  while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
265  int64_t* current_array;
266 
267  // Expect array object in context
268  if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
269  break;
270 
271  arraylen = avio_rb32(ioc);
272  if (arraylen >> 28)
273  break;
274 
275  /*
276  * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
277  * for indexing
278  */
279  if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
280  if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
281  ret = AVERROR(ENOMEM);
282  goto finish;
283  }
284  timeslen = arraylen;
285  current_array = times;
286  } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
287  if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
288  ret = AVERROR(ENOMEM);
289  goto finish;
290  }
291  fileposlen = arraylen;
292  current_array = filepositions;
293  } else // unexpected metatag inside keyframes, will not use such metadata for indexing
294  break;
295 
296  for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
297  if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
298  goto finish;
299  num_val = av_int2double(avio_rb64(ioc));
300  current_array[i] = num_val;
301  }
302  if (times && filepositions) {
303  // All done, exiting at a position allowing amf_parse_object
304  // to finish parsing the object
305  ret = 0;
306  break;
307  }
308  }
309 
310  if (!ret && timeslen == fileposlen) {
311  for (i = 0; i < fileposlen; i++) {
312  av_add_index_entry(vstream, filepositions[i], times[i]*1000,
313  0, 0, AVINDEX_KEYFRAME);
314  if (i < 2) {
315  flv->validate_index[i].pos = filepositions[i];
316  flv->validate_index[i].dts = times[i] * 1000;
317  flv->validate_count = i + 1;
318  }
319  }
320  } else
321  av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
322 
323 finish:
324  av_freep(&times);
325  av_freep(&filepositions);
326  // If we got unexpected data, but successfully reset back to
327  // the start pos, the caller can continue parsing
328  if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
329  return 0;
330  return ret;
331 }
332 
333 static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
334  AVCodecContext *acodec, *vcodec;
335  FLVContext *flv = s->priv_data;
336  AVIOContext *ioc;
337  AMFDataType amf_type;
338  char str_val[256];
339  double num_val;
340 
341  num_val = 0;
342  ioc = s->pb;
343 
344  amf_type = avio_r8(ioc);
345 
346  switch(amf_type) {
348  num_val = av_int2double(avio_rb64(ioc)); break;
349  case AMF_DATA_TYPE_BOOL:
350  num_val = avio_r8(ioc); break;
352  if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
353  return -1;
354  break;
356  if ((vstream || astream) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
357  if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
358  max_pos) < 0)
359  return -1;
360 
361  while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
362  if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
363  return -1; //if we couldn't skip, bomb out.
364  }
365  if(avio_r8(ioc) != AMF_END_OF_OBJECT)
366  return -1;
367  break;
368  case AMF_DATA_TYPE_NULL:
371  break; //these take up no additional space
373  avio_skip(ioc, 4); //skip 32-bit max array index
374  while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
375  //this is the only case in which we would want a nested parse to not skip over the object
376  if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
377  return -1;
378  }
379  if(avio_r8(ioc) != AMF_END_OF_OBJECT)
380  return -1;
381  break;
382  case AMF_DATA_TYPE_ARRAY: {
383  unsigned int arraylen, i;
384 
385  arraylen = avio_rb32(ioc);
386  for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
387  if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
388  return -1; //if we couldn't skip, bomb out.
389  }
390  }
391  break;
392  case AMF_DATA_TYPE_DATE:
393  avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
394  break;
395  default: //unsupported type, we couldn't skip
396  return -1;
397  }
398 
399  if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
400  acodec = astream ? astream->codec : NULL;
401  vcodec = vstream ? vstream->codec : NULL;
402 
403  if (amf_type == AMF_DATA_TYPE_NUMBER || amf_type == AMF_DATA_TYPE_BOOL) {
404  if (!strcmp(key, "duration"))
405  s->duration = num_val * AV_TIME_BASE;
406  else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
407  vcodec->bit_rate = num_val * 1024.0;
408  else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
409  acodec->bit_rate = num_val * 1024.0;
410  else if (!strcmp(key, "datastream")) {
412  if (!st)
413  return AVERROR(ENOMEM);
415  } else if (flv->trust_metadata) {
416  if (!strcmp(key, "videocodecid") && vcodec) {
417  flv_set_video_codec(s, vstream, num_val, 0);
418  } else
419  if (!strcmp(key, "audiocodecid") && acodec) {
420  int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
421  flv_set_audio_codec(s, astream, acodec, id);
422  } else
423  if (!strcmp(key, "audiosamplerate") && acodec) {
424  acodec->sample_rate = num_val;
425  } else if (!strcmp(key, "audiosamplesize") && acodec) {
426  acodec->bits_per_coded_sample = num_val;
427  } else if (!strcmp(key, "stereo") && acodec) {
428  acodec->channels = num_val + 1;
429  acodec->channel_layout = acodec->channels == 2 ?
432  } else
433  if (!strcmp(key, "width") && vcodec) {
434  vcodec->width = num_val;
435  } else
436  if (!strcmp(key, "height") && vcodec) {
437  vcodec->height = num_val;
438  }
439  }
440  }
441 
442  if (!strcmp(key, "duration") ||
443  !strcmp(key, "filesize") ||
444  !strcmp(key, "width") ||
445  !strcmp(key, "height") ||
446  !strcmp(key, "videodatarate") ||
447  !strcmp(key, "framerate") ||
448  !strcmp(key, "videocodecid") ||
449  !strcmp(key, "audiodatarate") ||
450  !strcmp(key, "audiosamplerate") ||
451  !strcmp(key, "audiosamplesize") ||
452  !strcmp(key, "stereo") ||
453  !strcmp(key, "audiocodecid"))
454  return 0;
455 
456  if(amf_type == AMF_DATA_TYPE_BOOL) {
457  av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
458  av_dict_set(&s->metadata, key, str_val, 0);
459  } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
460  snprintf(str_val, sizeof(str_val), "%.f", num_val);
461  av_dict_set(&s->metadata, key, str_val, 0);
462  } else if (amf_type == AMF_DATA_TYPE_STRING)
463  av_dict_set(&s->metadata, key, str_val, 0);
464  }
465 
466  return 0;
467 }
468 
469 static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
470  AMFDataType type;
471  AVStream *stream, *astream, *vstream;
472  AVIOContext *ioc;
473  int i;
474  char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
475 
476  astream = NULL;
477  vstream = NULL;
478  ioc = s->pb;
479 
480  //first object needs to be "onMetaData" string
481  type = avio_r8(ioc);
482  if (type != AMF_DATA_TYPE_STRING ||
483  amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
484  return -1;
485 
486  if (!strcmp(buffer, "onTextData"))
487  return 1;
488 
489  if (strcmp(buffer, "onMetaData"))
490  return -1;
491 
492  //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
493  for(i = 0; i < s->nb_streams; i++) {
494  stream = s->streams[i];
495  if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
496  else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
497  }
498 
499  //parse the second object (we want a mixed array)
500  if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
501  return -1;
502 
503  return 0;
504 }
505 
507 {
508  int offset, flags;
509 
510  avio_skip(s->pb, 4);
511  flags = avio_r8(s->pb);
512  /* old flvtool cleared this field */
513  /* FIXME: better fix needed */
514  if (!flags) {
516  av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
517  }
518 
520 
521  if(flags & FLV_HEADER_FLAG_HASVIDEO){
523  return AVERROR(ENOMEM);
524  }
525  if(flags & FLV_HEADER_FLAG_HASAUDIO){
527  return AVERROR(ENOMEM);
528  }
529 
530  offset = avio_rb32(s->pb);
531  avio_seek(s->pb, offset, SEEK_SET);
532  avio_skip(s->pb, 4);
533 
534  s->start_time = 0;
535 
536  return 0;
537 }
538 
540 {
541  FLVContext *flv = s->priv_data;
542  av_freep(&flv->new_extradata[0]);
543  av_freep(&flv->new_extradata[1]);
544  return 0;
545 }
546 
548 {
549  av_free(st->codec->extradata);
551  if (!st->codec->extradata)
552  return AVERROR(ENOMEM);
553  st->codec->extradata_size = size;
555  return 0;
556 }
557 
558 static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
559  int size)
560 {
561  av_free(flv->new_extradata[stream]);
563  if (!flv->new_extradata[stream])
564  return AVERROR(ENOMEM);
565  flv->new_extradata_size[stream] = size;
566  avio_read(pb, flv->new_extradata[stream], size);
567  return 0;
568 }
569 
570 static void clear_index_entries(AVFormatContext *s, int64_t pos)
571 {
572  int i, j, out;
573  av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
574  for (i = 0; i < s->nb_streams; i++) {
575  AVStream *st = s->streams[i];
576  /* Remove all index entries that point to >= pos */
577  out = 0;
578  for (j = 0; j < st->nb_index_entries; j++) {
579  if (st->index_entries[j].pos < pos)
580  st->index_entries[out++] = st->index_entries[j];
581  }
582  st->nb_index_entries = out;
583  }
584 }
585 
586 
588  int64_t dts, int64_t next)
589 {
590  int ret = AVERROR_INVALIDDATA, i;
591  AVIOContext *pb = s->pb;
592  AVStream *st = NULL;
593  AMFDataType type;
594  char buf[20];
595  int length;
596 
597  type = avio_r8(pb);
598  if (type == AMF_DATA_TYPE_MIXEDARRAY)
599  avio_seek(pb, 4, SEEK_CUR);
600  else if (type != AMF_DATA_TYPE_OBJECT)
601  goto out;
602 
603  amf_get_string(pb, buf, sizeof(buf));
604  if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
605  goto out;
606 
607  amf_get_string(pb, buf, sizeof(buf));
608  //FIXME parse it as codec_id
609  amf_get_string(pb, buf, sizeof(buf));
610  if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
611  goto out;
612 
613  length = avio_rb16(pb);
614  ret = av_get_packet(s->pb, pkt, length);
615  if (ret < 0) {
616  ret = AVERROR(EIO);
617  goto out;
618  }
619 
620  for (i = 0; i < s->nb_streams; i++) {
621  st = s->streams[i];
622  if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
623  break;
624  }
625 
626  if (i == s->nb_streams) {
628  if (!st)
629  goto out;
631  }
632 
633  pkt->dts = dts;
634  pkt->pts = dts;
635  pkt->size = ret;
636 
637  pkt->stream_index = st->index;
638  pkt->flags |= AV_PKT_FLAG_KEY;
639 
640  avio_seek(s->pb, next + 4, SEEK_SET);
641 out:
642  return ret;
643 }
644 
646 {
647  FLVContext *flv = s->priv_data;
648  int ret, i, type, size, flags, is_audio;
649  int64_t next, pos;
650  int64_t dts, pts = AV_NOPTS_VALUE;
651  int sample_rate = 0, channels = 0;
652  AVStream *st = NULL;
653 
654  for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
655  pos = avio_tell(s->pb);
656  type = avio_r8(s->pb);
657  size = avio_rb24(s->pb);
658  dts = avio_rb24(s->pb);
659  dts |= avio_r8(s->pb) << 24;
660  av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
661  if (s->pb->eof_reached)
662  return AVERROR_EOF;
663  avio_skip(s->pb, 3); /* stream id, always 0 */
664  flags = 0;
665 
666  if (flv->validate_next < flv->validate_count) {
667  int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
668  if (pos == validate_pos) {
669  if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
671  flv->validate_next++;
672  } else {
673  clear_index_entries(s, validate_pos);
674  flv->validate_count = 0;
675  }
676  } else if (pos > validate_pos) {
677  clear_index_entries(s, validate_pos);
678  flv->validate_count = 0;
679  }
680  }
681 
682  if(size == 0)
683  continue;
684 
685  next= size + avio_tell(s->pb);
686 
687  if (type == FLV_TAG_TYPE_AUDIO) {
688  is_audio=1;
689  flags = avio_r8(s->pb);
690  size--;
691  } else if (type == FLV_TAG_TYPE_VIDEO) {
692  is_audio=0;
693  flags = avio_r8(s->pb);
694  size--;
695  if ((flags & 0xf0) == 0x50) /* video info / command frame */
696  goto skip;
697  } else {
698  if (type == FLV_TAG_TYPE_META && size > 13+1+4)
699  if (flv_read_metabody(s, next) > 0) {
700  return flv_data_packet(s, pkt, dts, next);
701  }
702  else /* skip packet */
703  av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
704  skip:
705  avio_seek(s->pb, next, SEEK_SET);
706  continue;
707  }
708 
709  /* skip empty data packets */
710  if (!size)
711  continue;
712 
713  /* now find stream */
714  for(i=0;i<s->nb_streams;i++) {
715  st = s->streams[i];
716  if (is_audio && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
717  if (flv_same_audio_codec(st->codec, flags)) {
718  break;
719  }
720  } else
721  if (!is_audio && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
722  if (flv_same_video_codec(st->codec, flags)) {
723  break;
724  }
725  }
726  }
727  if(i == s->nb_streams){
728  st = create_stream(s,
730  }
731  av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
732  if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
733  ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
734  || st->discard >= AVDISCARD_ALL
735  ){
736  avio_seek(s->pb, next, SEEK_SET);
737  continue;
738  }
739  if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
740  av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
741  break;
742  }
743 
744  // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
745  if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
746  int size;
747  const int64_t pos= avio_tell(s->pb);
748  const int64_t fsize= avio_size(s->pb);
749  avio_seek(s->pb, fsize-4, SEEK_SET);
750  size= avio_rb32(s->pb);
751  avio_seek(s->pb, fsize-3-size, SEEK_SET);
752  if(size == avio_rb24(s->pb) + 11){
753  uint32_t ts = avio_rb24(s->pb);
754  ts |= avio_r8(s->pb) << 24;
755  s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
756  }
757  avio_seek(s->pb, pos, SEEK_SET);
758  }
759 
760  if(is_audio){
761  int bits_per_coded_sample;
762  channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
763  sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
764  bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
765  if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
766  st->codec->channels = channels;
767  st->codec->channel_layout = channels == 1 ? AV_CH_LAYOUT_MONO :
769  st->codec->sample_rate = sample_rate;
770  st->codec->bits_per_coded_sample = bits_per_coded_sample;
771  }
772  if(!st->codec->codec_id){
773  flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
774  flv->last_sample_rate = sample_rate = st->codec->sample_rate;
775  flv->last_channels = channels = st->codec->channels;
776  } else {
777  AVCodecContext ctx;
778  ctx.sample_rate = sample_rate;
779  flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
780  sample_rate = ctx.sample_rate;
781  }
782  }else{
783  size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
784  }
785 
786  if (st->codec->codec_id == AV_CODEC_ID_AAC ||
787  st->codec->codec_id == AV_CODEC_ID_H264) {
788  int type = avio_r8(s->pb);
789  size--;
790  if (st->codec->codec_id == AV_CODEC_ID_H264) {
791  int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
792  pts = dts + cts;
793  if (cts < 0) { // dts are wrong
794  flv->wrong_dts = 1;
795  av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
796  }
797  if (flv->wrong_dts)
798  dts = AV_NOPTS_VALUE;
799  }
800  if (type == 0) {
801  if (st->codec->extradata) {
802  if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
803  return ret;
804  ret = AVERROR(EAGAIN);
805  goto leave;
806  }
807  if ((ret = flv_get_extradata(s, st, size)) < 0)
808  return ret;
809  if (st->codec->codec_id == AV_CODEC_ID_AAC) {
810  MPEG4AudioConfig cfg;
812  st->codec->extradata_size * 8, 1);
813  st->codec->channels = cfg.channels;
814  st->codec->channel_layout = 0;
815  if (cfg.ext_sample_rate)
816  st->codec->sample_rate = cfg.ext_sample_rate;
817  else
818  st->codec->sample_rate = cfg.sample_rate;
819  av_dlog(s, "mp4a config channels %d sample rate %d\n",
820  st->codec->channels, st->codec->sample_rate);
821  }
822 
823  ret = AVERROR(EAGAIN);
824  goto leave;
825  }
826  }
827 
828  /* skip empty data packets */
829  if (!size) {
830  ret = AVERROR(EAGAIN);
831  goto leave;
832  }
833 
834  ret= av_get_packet(s->pb, pkt, size);
835  if (ret < 0) {
836  return AVERROR(EIO);
837  }
838  /* note: we need to modify the packet size here to handle the last
839  packet */
840  pkt->size = ret;
841  pkt->dts = dts;
842  pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
843  pkt->stream_index = st->index;
844  if (flv->new_extradata[is_audio]) {
846  flv->new_extradata_size[is_audio]);
847  if (side) {
848  memcpy(side, flv->new_extradata[is_audio],
849  flv->new_extradata_size[is_audio]);
850  av_freep(&flv->new_extradata[is_audio]);
851  flv->new_extradata_size[is_audio] = 0;
852  }
853  }
854  if (is_audio && (sample_rate != flv->last_sample_rate ||
855  channels != flv->last_channels)) {
856  flv->last_sample_rate = sample_rate;
857  flv->last_channels = channels;
858  ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
859  }
860 
861  if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
862  pkt->flags |= AV_PKT_FLAG_KEY;
863 
864 leave:
865  avio_skip(s->pb, 4);
866  return ret;
867 }
868 
869 static int flv_read_seek(AVFormatContext *s, int stream_index,
870  int64_t ts, int flags)
871 {
872  FLVContext *flv = s->priv_data;
873  flv->validate_count = 0;
874  return avio_seek_time(s->pb, stream_index, ts, flags);
875 }
876 
877 #define OFFSET(x) offsetof(FLVContext, x)
878 #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
879 static const AVOption options[] = {
880  { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD},
881  { NULL }
882 };
883 
884 static const AVClass class = {
885  .class_name = "flvdec",
886  .item_name = av_default_item_name,
887  .option = options,
889 };
890 
892  .name = "flv",
893  .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
894  .priv_data_size = sizeof(FLVContext),
900  .extensions = "flv",
901  .priv_class = &class,
902 };
void * av_malloc(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:61
discard all frames except keyframes
Definition: avcodec.h:535
Bytestream IO Context.
Definition: avio.h:68
int64_t avio_size(AVIOContext *s)
Get the filesize.
Definition: aviobuf.c:241
int size
AVOption.
Definition: opt.h:233
int av_add_index_entry(AVStream *st, int64_t pos, int64_t timestamp, int size, int distance, int flags)
Add an index entry into a sorted list.
Definition: utils.c:1393
static void clear_index_entries(AVFormatContext *s, int64_t pos)
Definition: flvdec.c:570
void avpriv_set_pts_info(AVStream *s, int pts_wrap_bits, unsigned int pts_num, unsigned int pts_den)
Set the time base and wrapping info for a given stream.
Definition: utils.c:3283
int64_t pos
Definition: avformat.h:583
static int read_seek(AVFormatContext *ctx, int stream_index, int64_t timestamp, int flags)
Definition: libcdio.c:153
int index
stream index in AVFormatContext
Definition: avformat.h:623
int size
Definition: avcodec.h:916
int64_t avio_seek(AVIOContext *s, int64_t offset, int whence)
fseek() equivalent for AVIOContext.
Definition: aviobuf.c:186
AVIndexEntry * index_entries
Only used if the format does not support seeking natively.
Definition: avformat.h:786
static int flv_data_packet(AVFormatContext *s, AVPacket *pkt, int64_t dts, int64_t next)
Definition: flvdec.c:587
enum AVMediaType codec_type
Definition: rtp.c:39
av_dlog(ac->avr,"%d samples - audio_convert: %s to %s (%s)\n", len, av_get_sample_fmt_name(ac->in_fmt), av_get_sample_fmt_name(ac->out_fmt), use_generic?ac->func_descr_generic:ac->func_descr)
discard all
Definition: avcodec.h:536
static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos)
Definition: flvdec.c:251
#define AV_CH_LAYOUT_STEREO
static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
Definition: flvdec.c:645
unsigned int avio_rb16(AVIOContext *s)
Definition: aviobuf.c:562
uint8_t * new_extradata[2]
Definition: flvdec.c:50
int ctx_flags
Format-specific flags, see AVFMTCTX_xx.
Definition: avformat.h:864
#define OFFSET(x)
Definition: flvdec.c:877
static int flv_read_seek(AVFormatContext *s, int stream_index, int64_t ts, int flags)
Definition: flvdec.c:869
void av_freep(void *arg)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc() and set the pointer ...
Definition: mem.c:151
Format I/O context.
Definition: avformat.h:828
const char * class_name
The name of the class; usually it is the same name as the context structure type to which the AVClass...
Definition: log.h:38
Public dictionary API.
static av_always_inline double av_int2double(uint64_t i)
Reinterpret a 64-bit integer as a double.
Definition: intfloat.h:60
uint8_t
int validate_next
Definition: flvdec.c:58
#define VD
Definition: flvdec.c:878
Opaque data information usually continuous.
Definition: avutil.h:181
AVOptions.
#define FLV_AUDIO_CODECID_MASK
Definition: flv.h:42
int64_t pos
Definition: flvdec.c:56
unsigned int avio_rb32(AVIOContext *s)
Definition: aviobuf.c:577
int wrong_dts
wrong dts due to negative cts
Definition: flvdec.c:49
#define AV_RB32
Definition: intreadwrite.h:130
enum AVStreamParseType need_parsing
Definition: avformat.h:775
static const AVOption options[]
Definition: flvdec.c:879
uint8_t * extradata
some codecs need / can use extradata like Huffman tables.
Definition: avcodec.h:1454
#define FLV_VIDEO_CODECID_MASK
Definition: flv.h:44
AVStream ** streams
Definition: avformat.h:876
#define VALIDATE_INDEX_TS_THRESH
Definition: flvdec.c:44
#define KEYFRAMES_BYTEOFFSET_TAG
Definition: flvdec.c:42
static int flags
Definition: log.c:42
#define FLV_AUDIO_SAMPLERATE_OFFSET
Definition: flv.h:33
static av_cold int read_close(AVFormatContext *ctx)
Definition: libcdio.c:145
int av_get_packet(AVIOContext *s, AVPacket *pkt, int size)
Allocate and read the payload of a packet and initialize its fields with default values.
Definition: utils.c:218
AMFDataType
Definition: flv.h:106
uint64_t avio_rb64(AVIOContext *s)
Definition: aviobuf.c:642
static av_always_inline int64_t avio_tell(AVIOContext *s)
ftell() equivalent for AVIOContext.
Definition: avio.h:219
int trust_metadata
configure streams according onMetaData
Definition: flvdec.c:48
int bits_per_coded_sample
bits per sample/pixel from the demuxer (needed for huffyuv).
Definition: avcodec.h:2704
int validate_count
Definition: flvdec.c:59
struct FLVContext FLVContext
#define FLV_AUDIO_SAMPLERATE_MASK
Definition: flv.h:41
int avio_read(AVIOContext *s, unsigned char *buf, int size)
Read size bytes from AVIOContext into buf.
Definition: aviobuf.c:446
AVDictionary * metadata
Definition: avformat.h:972
void av_free(void *ptr)
Free a memory block which has been allocated with av_malloc(z)() or av_realloc(). ...
Definition: mem.c:139
discard all bidirectional frames
Definition: avcodec.h:534
static int flv_read_close(AVFormatContext *s)
Definition: flvdec.c:539
#define NULL_IF_CONFIG_SMALL(x)
Return NULL if CONFIG_SMALL is true, otherwise the argument without modification. ...
Definition: internal.h:88
static int flv_read_header(AVFormatContext *s)
Definition: flvdec.c:506
preferred ID for decoding MPEG audio layer 1, 2 or 3
Definition: avcodec.h:348
int ff_add_param_change(AVPacket *pkt, int32_t channels, uint64_t channel_layout, int32_t sample_rate, int32_t width, int32_t height)
Add side data to a packet for changing parameters to the given values.
Definition: utils.c:3549
static AVStream * create_stream(AVFormatContext *s, int codec_type)
Definition: flvdec.c:73
void av_log(void *avcl, int level, const char *fmt,...)
Definition: log.c:146
AVStream * avformat_new_stream(AVFormatContext *s, AVCodec *c)
Add a new stream to a media file.
Definition: utils.c:2736
enum AVCodecID codec_id
Definition: mov_chan.c:432
size_t av_strlcpy(char *dst, const char *src, size_t size)
Copy the string src to dst, but no more than size - 1 bytes, and null-terminate dst.
Definition: avstring.c:67
static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid, int read)
Definition: flvdec.c:204
int flags
A combination of AV_PKT_FLAG values.
Definition: avcodec.h:921
uint64_t channel_layout
Audio channel layout.
Definition: avcodec.h:2165
int64_t dts
Definition: flvdec.c:55
int avio_r8(AVIOContext *s)
Definition: aviobuf.c:437
AVCodecContext * codec
Codec context associated with this stream.
Definition: avformat.h:641
unsigned char * buf
Buffer must have AVPROBE_PADDING_SIZE of extra allocated bytes filled with zero.
Definition: avformat.h:340
unsigned int nb_streams
A list of all streams in the file.
Definition: avformat.h:875
#define FLV_AUDIO_CODECID_OFFSET
Definition: flv.h:34
int seekable
A combination of AVIO_SEEKABLE_ flags or 0 when the stream is not seekable.
Definition: avio.h:117
int bit_rate
the average bitrate
Definition: avcodec.h:1404
audio channel layout utility functions
unsigned int avio_rb24(AVIOContext *s)
Definition: aviobuf.c:570
static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
Definition: flvdec.c:177
static int read_probe(AVProbeData *pd)
Definition: jvdec.c:54
int width
picture width / height.
Definition: avcodec.h:1508
static av_always_inline int64_t avio_skip(AVIOContext *s, int64_t offset)
Skip given number of bytes forward.
Definition: avio.h:210
int32_t
static char buffer[20]
Definition: seek-test.c:31
static int flv_probe(AVProbeData *p)
Definition: flvdec.c:62
static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid)
Definition: flvdec.c:132
LIBAVUTIL_VERSION_INT
Definition: eval.c:52
static int read_header(FFV1Context *f)
Definition: ffv1dec.c:536
static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
Definition: flvdec.c:82
Stream structure.
Definition: avformat.h:622
static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
Definition: flvdec.c:469
NULL
Definition: eval.c:52
FLV common header.
enum AVMediaType codec_type
Definition: avcodec.h:1347
enum AVCodecID codec_id
Definition: avcodec.h:1350
int sample_rate
samples per second
Definition: avcodec.h:2104
AVIOContext * pb
I/O context.
Definition: avformat.h:861
av_default_item_name
Definition: dnxhdenc.c:43
main external API structure.
Definition: avcodec.h:1339
int new_extradata_size[2]
Definition: flvdec.c:51
unsigned int codec_tag
fourcc (LSB first, so "ABCD" -> ('D'<<24) + ('C'<<16) + ('B'<<8) + 'A').
Definition: avcodec.h:1365
int extradata_size
Definition: avcodec.h:1455
static int read_packet(AVFormatContext *ctx, AVPacket *pkt)
Definition: libcdio.c:114
int av_dict_set(AVDictionary **pm, const char *key, const char *value, int flags)
Set the given entry in *pm, overwriting an existing entry.
Definition: dict.c:63
int last_sample_rate
Definition: flvdec.c:52
int nb_index_entries
Definition: avformat.h:788
Describe the class of an AVClass context structure.
Definition: log.h:33
int last_channels
Definition: flvdec.c:53
static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream, int size)
Definition: flvdec.c:558
This structure contains the data a format has to probe a file.
Definition: avformat.h:338
#define FLV_AUDIO_CHANNEL_MASK
Definition: flv.h:39
#define FLV_AUDIO_SAMPLESIZE_MASK
Definition: flv.h:40
#define AMF_END_OF_OBJECT
Definition: flv.h:47
int64_t start_time
Decoding: position of the first frame of the component, in AV_TIME_BASE fractional seconds...
Definition: avformat.h:885
full parsing and repack
Definition: avformat.h:576
Main libavformat public API header.
#define KEYFRAMES_TAG
Definition: flvdec.c:40
raw UTF-8 text
Definition: avcodec.h:416
#define FLV_VIDEO_FRAMETYPE_MASK
Definition: flv.h:45
static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
Definition: flvdec.c:237
static const int32_t max_pos[4]
Definition: g723_1_data.h:534
AVInputFormat ff_flv_demuxer
Definition: flvdec.c:891
int avpriv_mpeg4audio_get_config(MPEG4AudioConfig *c, const uint8_t *buf, int bit_size, int sync_extension)
Parse MPEG-4 systems extradata to retrieve audio configuration.
Definition: mpeg4audio.c:79
int64_t avio_seek_time(AVIOContext *h, int stream_index, int64_t timestamp, int flags)
Seek to a given timestamp relative to some component stream.
Definition: aviobuf.c:823
struct FLVContext::@87 validate_index[2]
int eof_reached
true if eof reached
Definition: avio.h:96
static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth)
Definition: flvdec.c:333
Definition: flv.h:62
int channels
number of audio channels
Definition: avcodec.h:2105
void * priv_data
Format private data.
Definition: avformat.h:848
#define KEYFRAMES_TIMESTAMP_TAG
Definition: flvdec.c:41
int64_t dts
Decompression timestamp in AVStream->time_base units; the time at which the packet is decompressed...
Definition: avcodec.h:914
static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
Definition: flvdec.c:547
int64_t duration
Decoding: duration of the stream, in AV_TIME_BASE fractional seconds.
Definition: avformat.h:893
const char * name
A comma separated list of short names for the format.
Definition: avformat.h:455
uint8_t * av_packet_new_side_data(AVPacket *pkt, enum AVPacketSideDataType type, int size)
Allocate new information of a packet.
Definition: avpacket.c:165
int stream_index
Definition: avcodec.h:917
#define AV_CH_LAYOUT_MONO
enum AVDiscard discard
Selects which packets can be discarded at will and do not need to be demuxed.
Definition: avformat.h:690
This structure stores compressed data.
Definition: avcodec.h:898
void * av_mallocz(size_t size)
Allocate a block of size bytes with alignment suitable for all memory accesses (including vectors if ...
Definition: mem.c:158
int64_t pts
Presentation timestamp in AVStream->time_base units; the time at which the decompressed packet will b...
Definition: avcodec.h:908