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.

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