You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1060 lines
36KB

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