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.

1018 lines
34KB

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