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.

1410 lines
48KB

  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 4 bits: difference between encoded width and visible width
  8. * - lower 4 bits: 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 "libavutil/time_internal.h"
  33. #include "libavcodec/bytestream.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. #define RESYNC_BUFFER_SIZE (1<<20)
  40. typedef struct FLVContext {
  41. const AVClass *class; ///< Class for private options.
  42. int trust_metadata; ///< configure streams according onMetaData
  43. int trust_datasize; ///< trust data size of FLVTag
  44. int dump_full_metadata; ///< Dump full metadata of the onMetadata
  45. int wrong_dts; ///< wrong dts due to negative cts
  46. uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
  47. int new_extradata_size[FLV_STREAM_TYPE_NB];
  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. uint8_t resync_buffer[2*RESYNC_BUFFER_SIZE];
  58. int broken_sizes;
  59. int sum_flv_tag_size;
  60. int last_keyframe_stream_index;
  61. int keyframe_count;
  62. int64_t video_bit_rate;
  63. int64_t audio_bit_rate;
  64. int64_t *keyframe_times;
  65. int64_t *keyframe_filepositions;
  66. int missing_streams;
  67. AVRational framerate;
  68. int64_t last_ts;
  69. int64_t time_offset;
  70. int64_t time_pos;
  71. } FLVContext;
  72. /* AMF date type */
  73. typedef struct amf_date {
  74. double milliseconds;
  75. int16_t timezone;
  76. } amf_date;
  77. static int probe(const AVProbeData *p, int live)
  78. {
  79. const uint8_t *d = p->buf;
  80. unsigned offset = AV_RB32(d + 5);
  81. if (d[0] == 'F' &&
  82. d[1] == 'L' &&
  83. d[2] == 'V' &&
  84. d[3] < 5 && d[5] == 0 &&
  85. offset + 100 < p->buf_size &&
  86. offset > 8) {
  87. int is_live = !memcmp(d + offset + 40, "NGINX RTMP", 10);
  88. if (live == is_live)
  89. return AVPROBE_SCORE_MAX;
  90. }
  91. return 0;
  92. }
  93. static int flv_probe(const AVProbeData *p)
  94. {
  95. return probe(p, 0);
  96. }
  97. static int live_flv_probe(const AVProbeData *p)
  98. {
  99. return probe(p, 1);
  100. }
  101. static int kux_probe(const AVProbeData *p)
  102. {
  103. const uint8_t *d = p->buf;
  104. if (d[0] == 'K' &&
  105. d[1] == 'D' &&
  106. d[2] == 'K' &&
  107. d[3] == 0 &&
  108. d[4] == 0) {
  109. return AVPROBE_SCORE_EXTENSION + 1;
  110. }
  111. return 0;
  112. }
  113. static void add_keyframes_index(AVFormatContext *s)
  114. {
  115. FLVContext *flv = s->priv_data;
  116. AVStream *stream = NULL;
  117. unsigned int i = 0;
  118. if (flv->last_keyframe_stream_index < 0) {
  119. av_log(s, AV_LOG_DEBUG, "keyframe stream hasn't been created\n");
  120. return;
  121. }
  122. av_assert0(flv->last_keyframe_stream_index <= s->nb_streams);
  123. stream = s->streams[flv->last_keyframe_stream_index];
  124. if (stream->nb_index_entries == 0) {
  125. for (i = 0; i < flv->keyframe_count; i++) {
  126. av_log(s, AV_LOG_TRACE, "keyframe filepositions = %"PRId64" times = %"PRId64"\n",
  127. flv->keyframe_filepositions[i], flv->keyframe_times[i] * 1000);
  128. av_add_index_entry(stream, flv->keyframe_filepositions[i],
  129. flv->keyframe_times[i] * 1000, 0, 0, AVINDEX_KEYFRAME);
  130. }
  131. } else
  132. av_log(s, AV_LOG_WARNING, "Skipping duplicate index\n");
  133. if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  134. av_freep(&flv->keyframe_times);
  135. av_freep(&flv->keyframe_filepositions);
  136. flv->keyframe_count = 0;
  137. }
  138. }
  139. static AVStream *create_stream(AVFormatContext *s, int codec_type)
  140. {
  141. FLVContext *flv = s->priv_data;
  142. AVStream *st = avformat_new_stream(s, NULL);
  143. if (!st)
  144. return NULL;
  145. st->codecpar->codec_type = codec_type;
  146. if (s->nb_streams>=3 ||( s->nb_streams==2
  147. && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
  148. && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_SUBTITLE
  149. && s->streams[0]->codecpar->codec_type != AVMEDIA_TYPE_DATA
  150. && s->streams[1]->codecpar->codec_type != AVMEDIA_TYPE_DATA))
  151. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  152. if (codec_type == AVMEDIA_TYPE_AUDIO) {
  153. st->codecpar->bit_rate = flv->audio_bit_rate;
  154. flv->missing_streams &= ~FLV_HEADER_FLAG_HASAUDIO;
  155. }
  156. if (codec_type == AVMEDIA_TYPE_VIDEO) {
  157. st->codecpar->bit_rate = flv->video_bit_rate;
  158. flv->missing_streams &= ~FLV_HEADER_FLAG_HASVIDEO;
  159. st->avg_frame_rate = flv->framerate;
  160. }
  161. avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  162. flv->last_keyframe_stream_index = s->nb_streams - 1;
  163. add_keyframes_index(s);
  164. return st;
  165. }
  166. static int flv_same_audio_codec(AVCodecParameters *apar, int flags)
  167. {
  168. int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  169. int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
  170. int codec_id;
  171. if (!apar->codec_id && !apar->codec_tag)
  172. return 1;
  173. if (apar->bits_per_coded_sample != bits_per_coded_sample)
  174. return 0;
  175. switch (flv_codecid) {
  176. // no distinction between S16 and S8 PCM codec flags
  177. case FLV_CODECID_PCM:
  178. codec_id = bits_per_coded_sample == 8
  179. ? AV_CODEC_ID_PCM_U8
  180. #if HAVE_BIGENDIAN
  181. : AV_CODEC_ID_PCM_S16BE;
  182. #else
  183. : AV_CODEC_ID_PCM_S16LE;
  184. #endif
  185. return codec_id == apar->codec_id;
  186. case FLV_CODECID_PCM_LE:
  187. codec_id = bits_per_coded_sample == 8
  188. ? AV_CODEC_ID_PCM_U8
  189. : AV_CODEC_ID_PCM_S16LE;
  190. return codec_id == apar->codec_id;
  191. case FLV_CODECID_AAC:
  192. return apar->codec_id == AV_CODEC_ID_AAC;
  193. case FLV_CODECID_ADPCM:
  194. return apar->codec_id == AV_CODEC_ID_ADPCM_SWF;
  195. case FLV_CODECID_SPEEX:
  196. return apar->codec_id == AV_CODEC_ID_SPEEX;
  197. case FLV_CODECID_MP3:
  198. return apar->codec_id == AV_CODEC_ID_MP3;
  199. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  200. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  201. case FLV_CODECID_NELLYMOSER:
  202. return apar->codec_id == AV_CODEC_ID_NELLYMOSER;
  203. case FLV_CODECID_PCM_MULAW:
  204. return apar->sample_rate == 8000 &&
  205. apar->codec_id == AV_CODEC_ID_PCM_MULAW;
  206. case FLV_CODECID_PCM_ALAW:
  207. return apar->sample_rate == 8000 &&
  208. apar->codec_id == AV_CODEC_ID_PCM_ALAW;
  209. default:
  210. return apar->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  211. }
  212. }
  213. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream,
  214. AVCodecParameters *apar, int flv_codecid)
  215. {
  216. switch (flv_codecid) {
  217. // no distinction between S16 and S8 PCM codec flags
  218. case FLV_CODECID_PCM:
  219. apar->codec_id = apar->bits_per_coded_sample == 8
  220. ? AV_CODEC_ID_PCM_U8
  221. #if HAVE_BIGENDIAN
  222. : AV_CODEC_ID_PCM_S16BE;
  223. #else
  224. : AV_CODEC_ID_PCM_S16LE;
  225. #endif
  226. break;
  227. case FLV_CODECID_PCM_LE:
  228. apar->codec_id = apar->bits_per_coded_sample == 8
  229. ? AV_CODEC_ID_PCM_U8
  230. : AV_CODEC_ID_PCM_S16LE;
  231. break;
  232. case FLV_CODECID_AAC:
  233. apar->codec_id = AV_CODEC_ID_AAC;
  234. break;
  235. case FLV_CODECID_ADPCM:
  236. apar->codec_id = AV_CODEC_ID_ADPCM_SWF;
  237. break;
  238. case FLV_CODECID_SPEEX:
  239. apar->codec_id = AV_CODEC_ID_SPEEX;
  240. apar->sample_rate = 16000;
  241. break;
  242. case FLV_CODECID_MP3:
  243. apar->codec_id = AV_CODEC_ID_MP3;
  244. astream->need_parsing = AVSTREAM_PARSE_FULL;
  245. break;
  246. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  247. // in case metadata does not otherwise declare samplerate
  248. apar->sample_rate = 8000;
  249. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  250. break;
  251. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  252. apar->sample_rate = 16000;
  253. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  254. break;
  255. case FLV_CODECID_NELLYMOSER:
  256. apar->codec_id = AV_CODEC_ID_NELLYMOSER;
  257. break;
  258. case FLV_CODECID_PCM_MULAW:
  259. apar->sample_rate = 8000;
  260. apar->codec_id = AV_CODEC_ID_PCM_MULAW;
  261. break;
  262. case FLV_CODECID_PCM_ALAW:
  263. apar->sample_rate = 8000;
  264. apar->codec_id = AV_CODEC_ID_PCM_ALAW;
  265. break;
  266. default:
  267. avpriv_request_sample(s, "Audio codec (%x)",
  268. flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  269. apar->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  270. }
  271. }
  272. static int flv_same_video_codec(AVCodecParameters *vpar, int flags)
  273. {
  274. int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
  275. if (!vpar->codec_id && !vpar->codec_tag)
  276. return 1;
  277. switch (flv_codecid) {
  278. case FLV_CODECID_H263:
  279. return vpar->codec_id == AV_CODEC_ID_FLV1;
  280. case FLV_CODECID_SCREEN:
  281. return vpar->codec_id == AV_CODEC_ID_FLASHSV;
  282. case FLV_CODECID_SCREEN2:
  283. return vpar->codec_id == AV_CODEC_ID_FLASHSV2;
  284. case FLV_CODECID_VP6:
  285. return vpar->codec_id == AV_CODEC_ID_VP6F;
  286. case FLV_CODECID_VP6A:
  287. return vpar->codec_id == AV_CODEC_ID_VP6A;
  288. case FLV_CODECID_H264:
  289. return vpar->codec_id == AV_CODEC_ID_H264;
  290. default:
  291. return vpar->codec_tag == flv_codecid;
  292. }
  293. }
  294. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream,
  295. int flv_codecid, int read)
  296. {
  297. int ret = 0;
  298. AVCodecParameters *par = vstream->codecpar;
  299. enum AVCodecID old_codec_id = vstream->codecpar->codec_id;
  300. switch (flv_codecid) {
  301. case FLV_CODECID_H263:
  302. par->codec_id = AV_CODEC_ID_FLV1;
  303. break;
  304. case FLV_CODECID_REALH263:
  305. par->codec_id = AV_CODEC_ID_H263;
  306. break; // Really mean it this time
  307. case FLV_CODECID_SCREEN:
  308. par->codec_id = AV_CODEC_ID_FLASHSV;
  309. break;
  310. case FLV_CODECID_SCREEN2:
  311. par->codec_id = AV_CODEC_ID_FLASHSV2;
  312. break;
  313. case FLV_CODECID_VP6:
  314. par->codec_id = AV_CODEC_ID_VP6F;
  315. case FLV_CODECID_VP6A:
  316. if (flv_codecid == FLV_CODECID_VP6A)
  317. par->codec_id = AV_CODEC_ID_VP6A;
  318. if (read) {
  319. if (par->extradata_size != 1) {
  320. ff_alloc_extradata(par, 1);
  321. }
  322. if (par->extradata)
  323. par->extradata[0] = avio_r8(s->pb);
  324. else
  325. avio_skip(s->pb, 1);
  326. }
  327. ret = 1; // 1 byte body size adjustment for flv_read_packet()
  328. break;
  329. case FLV_CODECID_H264:
  330. par->codec_id = AV_CODEC_ID_H264;
  331. vstream->need_parsing = AVSTREAM_PARSE_HEADERS;
  332. ret = 3; // not 4, reading packet type will consume one byte
  333. break;
  334. case FLV_CODECID_MPEG4:
  335. par->codec_id = AV_CODEC_ID_MPEG4;
  336. ret = 3;
  337. break;
  338. default:
  339. avpriv_request_sample(s, "Video codec (%x)", flv_codecid);
  340. par->codec_tag = flv_codecid;
  341. }
  342. if (!vstream->internal->need_context_update && par->codec_id != old_codec_id) {
  343. avpriv_request_sample(s, "Changing the codec id midstream");
  344. return AVERROR_PATCHWELCOME;
  345. }
  346. return ret;
  347. }
  348. static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize)
  349. {
  350. int length = avio_rb16(ioc);
  351. if (length >= buffsize) {
  352. avio_skip(ioc, length);
  353. return -1;
  354. }
  355. avio_read(ioc, buffer, length);
  356. buffer[length] = '\0';
  357. return length;
  358. }
  359. static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, int64_t max_pos)
  360. {
  361. FLVContext *flv = s->priv_data;
  362. unsigned int timeslen = 0, fileposlen = 0, i;
  363. char str_val[256];
  364. int64_t *times = NULL;
  365. int64_t *filepositions = NULL;
  366. int ret = AVERROR(ENOSYS);
  367. int64_t initial_pos = avio_tell(ioc);
  368. if (flv->keyframe_count > 0) {
  369. av_log(s, AV_LOG_DEBUG, "keyframes have been parsed\n");
  370. return 0;
  371. }
  372. av_assert0(!flv->keyframe_times);
  373. av_assert0(!flv->keyframe_filepositions);
  374. if (s->flags & AVFMT_FLAG_IGNIDX)
  375. return 0;
  376. while (avio_tell(ioc) < max_pos - 2 &&
  377. amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  378. int64_t **current_array;
  379. unsigned int arraylen;
  380. // Expect array object in context
  381. if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
  382. break;
  383. arraylen = avio_rb32(ioc);
  384. if (arraylen>>28)
  385. break;
  386. if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times) {
  387. current_array = &times;
  388. timeslen = arraylen;
  389. } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) &&
  390. !filepositions) {
  391. current_array = &filepositions;
  392. fileposlen = arraylen;
  393. } else
  394. // unexpected metatag inside keyframes, will not use such
  395. // metadata for indexing
  396. break;
  397. if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
  398. ret = AVERROR(ENOMEM);
  399. goto finish;
  400. }
  401. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  402. if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
  403. goto invalid;
  404. current_array[0][i] = av_int2double(avio_rb64(ioc));
  405. }
  406. if (times && filepositions) {
  407. // All done, exiting at a position allowing amf_parse_object
  408. // to finish parsing the object
  409. ret = 0;
  410. break;
  411. }
  412. }
  413. if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
  414. for (i = 0; i < FFMIN(2,fileposlen); i++) {
  415. flv->validate_index[i].pos = filepositions[i];
  416. flv->validate_index[i].dts = times[i] * 1000;
  417. flv->validate_count = i + 1;
  418. }
  419. flv->keyframe_times = times;
  420. flv->keyframe_filepositions = filepositions;
  421. flv->keyframe_count = timeslen;
  422. times = NULL;
  423. filepositions = NULL;
  424. } else {
  425. invalid:
  426. av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
  427. }
  428. finish:
  429. av_freep(&times);
  430. av_freep(&filepositions);
  431. avio_seek(ioc, initial_pos, SEEK_SET);
  432. return ret;
  433. }
  434. static int amf_parse_object(AVFormatContext *s, AVStream *astream,
  435. AVStream *vstream, const char *key,
  436. int64_t max_pos, int depth)
  437. {
  438. AVCodecParameters *apar, *vpar;
  439. FLVContext *flv = s->priv_data;
  440. AVIOContext *ioc;
  441. AMFDataType amf_type;
  442. char str_val[1024];
  443. double num_val;
  444. amf_date date;
  445. num_val = 0;
  446. ioc = s->pb;
  447. amf_type = avio_r8(ioc);
  448. switch (amf_type) {
  449. case AMF_DATA_TYPE_NUMBER:
  450. num_val = av_int2double(avio_rb64(ioc));
  451. break;
  452. case AMF_DATA_TYPE_BOOL:
  453. num_val = avio_r8(ioc);
  454. break;
  455. case AMF_DATA_TYPE_STRING:
  456. if (amf_get_string(ioc, str_val, sizeof(str_val)) < 0) {
  457. av_log(s, AV_LOG_ERROR, "AMF_DATA_TYPE_STRING parsing failed\n");
  458. return -1;
  459. }
  460. break;
  461. case AMF_DATA_TYPE_OBJECT:
  462. if (key &&
  463. (ioc->seekable & AVIO_SEEKABLE_NORMAL) &&
  464. !strcmp(KEYFRAMES_TAG, key) && depth == 1)
  465. if (parse_keyframes_index(s, ioc,
  466. max_pos) < 0)
  467. av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
  468. else
  469. add_keyframes_index(s);
  470. while (avio_tell(ioc) < max_pos - 2 &&
  471. amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
  472. if (amf_parse_object(s, astream, vstream, str_val, max_pos,
  473. depth + 1) < 0)
  474. return -1; // if we couldn't skip, bomb out.
  475. if (avio_r8(ioc) != AMF_END_OF_OBJECT) {
  476. av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_OBJECT\n");
  477. return -1;
  478. }
  479. break;
  480. case AMF_DATA_TYPE_NULL:
  481. case AMF_DATA_TYPE_UNDEFINED:
  482. case AMF_DATA_TYPE_UNSUPPORTED:
  483. break; // these take up no additional space
  484. case AMF_DATA_TYPE_MIXEDARRAY:
  485. {
  486. unsigned v;
  487. avio_skip(ioc, 4); // skip 32-bit max array index
  488. while (avio_tell(ioc) < max_pos - 2 &&
  489. amf_get_string(ioc, str_val, sizeof(str_val)) > 0)
  490. // this is the only case in which we would want a nested
  491. // parse to not skip over the object
  492. if (amf_parse_object(s, astream, vstream, str_val, max_pos,
  493. depth + 1) < 0)
  494. return -1;
  495. v = avio_r8(ioc);
  496. if (v != AMF_END_OF_OBJECT) {
  497. av_log(s, AV_LOG_ERROR, "Missing AMF_END_OF_OBJECT in AMF_DATA_TYPE_MIXEDARRAY, found %d\n", v);
  498. return -1;
  499. }
  500. break;
  501. }
  502. case AMF_DATA_TYPE_ARRAY:
  503. {
  504. unsigned int arraylen, i;
  505. arraylen = avio_rb32(ioc);
  506. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++)
  507. if (amf_parse_object(s, NULL, NULL, NULL, max_pos,
  508. depth + 1) < 0)
  509. return -1; // if we couldn't skip, bomb out.
  510. }
  511. break;
  512. case AMF_DATA_TYPE_DATE:
  513. // timestamp (double) and UTC offset (int16)
  514. date.milliseconds = av_int2double(avio_rb64(ioc));
  515. date.timezone = avio_rb16(ioc);
  516. break;
  517. default: // unsupported type, we couldn't skip
  518. av_log(s, AV_LOG_ERROR, "unsupported amf type %d\n", amf_type);
  519. return -1;
  520. }
  521. if (key) {
  522. apar = astream ? astream->codecpar : NULL;
  523. vpar = vstream ? vstream->codecpar : NULL;
  524. // stream info doesn't live any deeper than the first object
  525. if (depth == 1) {
  526. if (amf_type == AMF_DATA_TYPE_NUMBER ||
  527. amf_type == AMF_DATA_TYPE_BOOL) {
  528. if (!strcmp(key, "duration"))
  529. s->duration = num_val * AV_TIME_BASE;
  530. else if (!strcmp(key, "videodatarate") &&
  531. 0 <= (int)(num_val * 1024.0))
  532. flv->video_bit_rate = num_val * 1024.0;
  533. else if (!strcmp(key, "audiodatarate") &&
  534. 0 <= (int)(num_val * 1024.0))
  535. flv->audio_bit_rate = num_val * 1024.0;
  536. else if (!strcmp(key, "datastream")) {
  537. AVStream *st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
  538. if (!st)
  539. return AVERROR(ENOMEM);
  540. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  541. } else if (!strcmp(key, "framerate")) {
  542. flv->framerate = av_d2q(num_val, 1000);
  543. if (vstream)
  544. vstream->avg_frame_rate = flv->framerate;
  545. } else if (flv->trust_metadata) {
  546. if (!strcmp(key, "videocodecid") && vpar) {
  547. int ret = flv_set_video_codec(s, vstream, num_val, 0);
  548. if (ret < 0)
  549. return ret;
  550. } else if (!strcmp(key, "audiocodecid") && apar) {
  551. int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
  552. flv_set_audio_codec(s, astream, apar, id);
  553. } else if (!strcmp(key, "audiosamplerate") && apar) {
  554. apar->sample_rate = num_val;
  555. } else if (!strcmp(key, "audiosamplesize") && apar) {
  556. apar->bits_per_coded_sample = num_val;
  557. } else if (!strcmp(key, "stereo") && apar) {
  558. apar->channels = num_val + 1;
  559. apar->channel_layout = apar->channels == 2 ?
  560. AV_CH_LAYOUT_STEREO :
  561. AV_CH_LAYOUT_MONO;
  562. } else if (!strcmp(key, "width") && vpar) {
  563. vpar->width = num_val;
  564. } else if (!strcmp(key, "height") && vpar) {
  565. vpar->height = num_val;
  566. }
  567. }
  568. }
  569. if (amf_type == AMF_DATA_TYPE_STRING) {
  570. if (!strcmp(key, "encoder")) {
  571. int version = -1;
  572. if (1 == sscanf(str_val, "Open Broadcaster Software v0.%d", &version)) {
  573. if (version > 0 && version <= 655)
  574. flv->broken_sizes = 1;
  575. }
  576. } else if (!strcmp(key, "metadatacreator")) {
  577. if ( !strcmp (str_val, "MEGA")
  578. || !strncmp(str_val, "FlixEngine", 10))
  579. flv->broken_sizes = 1;
  580. }
  581. }
  582. }
  583. if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
  584. ((!apar && !strcmp(key, "audiocodecid")) ||
  585. (!vpar && !strcmp(key, "videocodecid"))))
  586. s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
  587. if ((!strcmp(key, "duration") ||
  588. !strcmp(key, "filesize") ||
  589. !strcmp(key, "width") ||
  590. !strcmp(key, "height") ||
  591. !strcmp(key, "videodatarate") ||
  592. !strcmp(key, "framerate") ||
  593. !strcmp(key, "videocodecid") ||
  594. !strcmp(key, "audiodatarate") ||
  595. !strcmp(key, "audiosamplerate") ||
  596. !strcmp(key, "audiosamplesize") ||
  597. !strcmp(key, "stereo") ||
  598. !strcmp(key, "audiocodecid") ||
  599. !strcmp(key, "datastream")) && !flv->dump_full_metadata)
  600. return 0;
  601. s->event_flags |= AVFMT_EVENT_FLAG_METADATA_UPDATED;
  602. if (amf_type == AMF_DATA_TYPE_BOOL) {
  603. av_strlcpy(str_val, num_val > 0 ? "true" : "false",
  604. sizeof(str_val));
  605. av_dict_set(&s->metadata, key, str_val, 0);
  606. } else if (amf_type == AMF_DATA_TYPE_NUMBER) {
  607. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  608. av_dict_set(&s->metadata, key, str_val, 0);
  609. } else if (amf_type == AMF_DATA_TYPE_STRING) {
  610. av_dict_set(&s->metadata, key, str_val, 0);
  611. } else if (amf_type == AMF_DATA_TYPE_DATE) {
  612. time_t time;
  613. struct tm t;
  614. char datestr[128];
  615. time = date.milliseconds / 1000; // to seconds
  616. localtime_r(&time, &t);
  617. strftime(datestr, sizeof(datestr), "%a, %d %b %Y %H:%M:%S %z", &t);
  618. av_dict_set(&s->metadata, key, datestr, 0);
  619. }
  620. }
  621. return 0;
  622. }
  623. #define TYPE_ONTEXTDATA 1
  624. #define TYPE_ONCAPTION 2
  625. #define TYPE_ONCAPTIONINFO 3
  626. #define TYPE_UNKNOWN 9
  627. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos)
  628. {
  629. FLVContext *flv = s->priv_data;
  630. AMFDataType type;
  631. AVStream *stream, *astream, *vstream;
  632. AVStream av_unused *dstream;
  633. AVIOContext *ioc;
  634. int i;
  635. char buffer[32];
  636. astream = NULL;
  637. vstream = NULL;
  638. dstream = NULL;
  639. ioc = s->pb;
  640. // first object needs to be "onMetaData" string
  641. type = avio_r8(ioc);
  642. if (type != AMF_DATA_TYPE_STRING ||
  643. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  644. return TYPE_UNKNOWN;
  645. if (!strcmp(buffer, "onTextData"))
  646. return TYPE_ONTEXTDATA;
  647. if (!strcmp(buffer, "onCaption"))
  648. return TYPE_ONCAPTION;
  649. if (!strcmp(buffer, "onCaptionInfo"))
  650. return TYPE_ONCAPTIONINFO;
  651. if (strcmp(buffer, "onMetaData") && strcmp(buffer, "onCuePoint")) {
  652. av_log(s, AV_LOG_DEBUG, "Unknown type %s\n", buffer);
  653. return TYPE_UNKNOWN;
  654. }
  655. // find the streams now so that amf_parse_object doesn't need to do
  656. // the lookup every time it is called.
  657. for (i = 0; i < s->nb_streams; i++) {
  658. stream = s->streams[i];
  659. if (stream->codecpar->codec_type == AVMEDIA_TYPE_VIDEO) {
  660. vstream = stream;
  661. flv->last_keyframe_stream_index = i;
  662. } else if (stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) {
  663. astream = stream;
  664. if (flv->last_keyframe_stream_index == -1)
  665. flv->last_keyframe_stream_index = i;
  666. }
  667. else if (stream->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  668. dstream = stream;
  669. }
  670. // parse the second object (we want a mixed array)
  671. if (amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  672. return -1;
  673. return 0;
  674. }
  675. static int flv_read_header(AVFormatContext *s)
  676. {
  677. int flags;
  678. FLVContext *flv = s->priv_data;
  679. int offset;
  680. int pre_tag_size = 0;
  681. /* Actual FLV data at 0xe40000 in KUX file */
  682. if(!strcmp(s->iformat->name, "kux"))
  683. avio_skip(s->pb, 0xe40000);
  684. avio_skip(s->pb, 4);
  685. flags = avio_r8(s->pb);
  686. flv->missing_streams = flags & (FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO);
  687. s->ctx_flags |= AVFMTCTX_NOHEADER;
  688. offset = avio_rb32(s->pb);
  689. avio_seek(s->pb, offset, SEEK_SET);
  690. /* Annex E. The FLV File Format
  691. * E.3 TheFLVFileBody
  692. * Field Type Comment
  693. * PreviousTagSize0 UI32 Always 0
  694. * */
  695. pre_tag_size = avio_rb32(s->pb);
  696. if (pre_tag_size) {
  697. av_log(s, AV_LOG_WARNING, "Read FLV header error, input file is not a standard flv format, first PreviousTagSize0 always is 0\n");
  698. }
  699. s->start_time = 0;
  700. flv->sum_flv_tag_size = 0;
  701. flv->last_keyframe_stream_index = -1;
  702. return 0;
  703. }
  704. static int flv_read_close(AVFormatContext *s)
  705. {
  706. int i;
  707. FLVContext *flv = s->priv_data;
  708. for (i=0; i<FLV_STREAM_TYPE_NB; i++)
  709. av_freep(&flv->new_extradata[i]);
  710. av_freep(&flv->keyframe_times);
  711. av_freep(&flv->keyframe_filepositions);
  712. return 0;
  713. }
  714. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  715. {
  716. if (!size)
  717. return 0;
  718. av_freep(&st->codecpar->extradata);
  719. if (ff_get_extradata(s, st->codecpar, s->pb, size) < 0)
  720. return AVERROR(ENOMEM);
  721. st->internal->need_context_update = 1;
  722. return 0;
  723. }
  724. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  725. int size)
  726. {
  727. if (!size)
  728. return 0;
  729. av_free(flv->new_extradata[stream]);
  730. flv->new_extradata[stream] = av_mallocz(size +
  731. AV_INPUT_BUFFER_PADDING_SIZE);
  732. if (!flv->new_extradata[stream])
  733. return AVERROR(ENOMEM);
  734. flv->new_extradata_size[stream] = size;
  735. avio_read(pb, flv->new_extradata[stream], size);
  736. return 0;
  737. }
  738. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  739. {
  740. int i, j, out;
  741. av_log(s, AV_LOG_WARNING,
  742. "Found invalid index entries, clearing the index.\n");
  743. for (i = 0; i < s->nb_streams; i++) {
  744. AVStream *st = s->streams[i];
  745. /* Remove all index entries that point to >= pos */
  746. out = 0;
  747. for (j = 0; j < st->nb_index_entries; j++)
  748. if (st->index_entries[j].pos < pos)
  749. st->index_entries[out++] = st->index_entries[j];
  750. st->nb_index_entries = out;
  751. }
  752. }
  753. static int amf_skip_tag(AVIOContext *pb, AMFDataType type)
  754. {
  755. int nb = -1, ret, parse_name = 1;
  756. switch (type) {
  757. case AMF_DATA_TYPE_NUMBER:
  758. avio_skip(pb, 8);
  759. break;
  760. case AMF_DATA_TYPE_BOOL:
  761. avio_skip(pb, 1);
  762. break;
  763. case AMF_DATA_TYPE_STRING:
  764. avio_skip(pb, avio_rb16(pb));
  765. break;
  766. case AMF_DATA_TYPE_ARRAY:
  767. parse_name = 0;
  768. case AMF_DATA_TYPE_MIXEDARRAY:
  769. nb = avio_rb32(pb);
  770. case AMF_DATA_TYPE_OBJECT:
  771. while(!pb->eof_reached && (nb-- > 0 || type != AMF_DATA_TYPE_ARRAY)) {
  772. if (parse_name) {
  773. int size = avio_rb16(pb);
  774. if (!size) {
  775. avio_skip(pb, 1);
  776. break;
  777. }
  778. avio_skip(pb, size);
  779. }
  780. if ((ret = amf_skip_tag(pb, avio_r8(pb))) < 0)
  781. return ret;
  782. }
  783. break;
  784. case AMF_DATA_TYPE_NULL:
  785. case AMF_DATA_TYPE_OBJECT_END:
  786. break;
  787. default:
  788. return AVERROR_INVALIDDATA;
  789. }
  790. return 0;
  791. }
  792. static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
  793. int64_t dts, int64_t next)
  794. {
  795. AVIOContext *pb = s->pb;
  796. AVStream *st = NULL;
  797. char buf[20];
  798. int ret = AVERROR_INVALIDDATA;
  799. int i, length = -1;
  800. int array = 0;
  801. switch (avio_r8(pb)) {
  802. case AMF_DATA_TYPE_ARRAY:
  803. array = 1;
  804. case AMF_DATA_TYPE_MIXEDARRAY:
  805. avio_seek(pb, 4, SEEK_CUR);
  806. case AMF_DATA_TYPE_OBJECT:
  807. break;
  808. default:
  809. goto skip;
  810. }
  811. while (array || (ret = amf_get_string(pb, buf, sizeof(buf))) > 0) {
  812. AMFDataType type = avio_r8(pb);
  813. if (type == AMF_DATA_TYPE_STRING && (array || !strcmp(buf, "text"))) {
  814. length = avio_rb16(pb);
  815. ret = av_get_packet(pb, pkt, length);
  816. if (ret < 0)
  817. goto skip;
  818. else
  819. break;
  820. } else {
  821. if ((ret = amf_skip_tag(pb, type)) < 0)
  822. goto skip;
  823. }
  824. }
  825. if (length < 0) {
  826. ret = AVERROR_INVALIDDATA;
  827. goto skip;
  828. }
  829. for (i = 0; i < s->nb_streams; i++) {
  830. st = s->streams[i];
  831. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  832. break;
  833. }
  834. if (i == s->nb_streams) {
  835. st = create_stream(s, AVMEDIA_TYPE_SUBTITLE);
  836. if (!st)
  837. return AVERROR(ENOMEM);
  838. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  839. }
  840. pkt->dts = dts;
  841. pkt->pts = dts;
  842. pkt->size = ret;
  843. pkt->stream_index = st->index;
  844. pkt->flags |= AV_PKT_FLAG_KEY;
  845. skip:
  846. avio_seek(s->pb, next + 4, SEEK_SET);
  847. return ret;
  848. }
  849. static int resync(AVFormatContext *s)
  850. {
  851. FLVContext *flv = s->priv_data;
  852. int64_t i;
  853. int64_t pos = avio_tell(s->pb);
  854. for (i=0; !avio_feof(s->pb); i++) {
  855. int j = i & (RESYNC_BUFFER_SIZE-1);
  856. int j1 = j + RESYNC_BUFFER_SIZE;
  857. flv->resync_buffer[j ] =
  858. flv->resync_buffer[j1] = avio_r8(s->pb);
  859. if (i >= 8 && pos) {
  860. uint8_t *d = flv->resync_buffer + j1 - 8;
  861. if (d[0] == 'F' &&
  862. d[1] == 'L' &&
  863. d[2] == 'V' &&
  864. d[3] < 5 && d[5] == 0) {
  865. av_log(s, AV_LOG_WARNING, "Concatenated FLV detected, might fail to demux, decode and seek %"PRId64"\n", flv->last_ts);
  866. flv->time_offset = flv->last_ts + 1;
  867. flv->time_pos = avio_tell(s->pb);
  868. }
  869. }
  870. if (i > 22) {
  871. unsigned lsize2 = AV_RB32(flv->resync_buffer + j1 - 4);
  872. if (lsize2 >= 11 && lsize2 + 8LL < FFMIN(i, RESYNC_BUFFER_SIZE)) {
  873. unsigned size2 = AV_RB24(flv->resync_buffer + j1 - lsize2 + 1 - 4);
  874. unsigned lsize1 = AV_RB32(flv->resync_buffer + j1 - lsize2 - 8);
  875. if (lsize1 >= 11 && lsize1 + 8LL + lsize2 < FFMIN(i, RESYNC_BUFFER_SIZE)) {
  876. unsigned size1 = AV_RB24(flv->resync_buffer + j1 - lsize1 + 1 - lsize2 - 8);
  877. if (size1 == lsize1 - 11 && size2 == lsize2 - 11) {
  878. avio_seek(s->pb, pos + i - lsize1 - lsize2 - 8, SEEK_SET);
  879. return 1;
  880. }
  881. }
  882. }
  883. }
  884. }
  885. return AVERROR_EOF;
  886. }
  887. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  888. {
  889. FLVContext *flv = s->priv_data;
  890. int ret, i, size, flags;
  891. enum FlvTagType type;
  892. int stream_type=-1;
  893. int64_t next, pos, meta_pos;
  894. int64_t dts, pts = AV_NOPTS_VALUE;
  895. int av_uninit(channels);
  896. int av_uninit(sample_rate);
  897. AVStream *st = NULL;
  898. int last = -1;
  899. int orig_size;
  900. retry:
  901. /* pkt size is repeated at end. skip it */
  902. pos = avio_tell(s->pb);
  903. type = (avio_r8(s->pb) & 0x1F);
  904. orig_size =
  905. size = avio_rb24(s->pb);
  906. flv->sum_flv_tag_size += size + 11;
  907. dts = avio_rb24(s->pb);
  908. dts |= (unsigned)avio_r8(s->pb) << 24;
  909. av_log(s, AV_LOG_TRACE, "type:%d, size:%d, last:%d, dts:%"PRId64" pos:%"PRId64"\n", type, size, last, dts, avio_tell(s->pb));
  910. if (avio_feof(s->pb))
  911. return AVERROR_EOF;
  912. avio_skip(s->pb, 3); /* stream id, always 0 */
  913. flags = 0;
  914. if (flv->validate_next < flv->validate_count) {
  915. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  916. if (pos == validate_pos) {
  917. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  918. VALIDATE_INDEX_TS_THRESH) {
  919. flv->validate_next++;
  920. } else {
  921. clear_index_entries(s, validate_pos);
  922. flv->validate_count = 0;
  923. }
  924. } else if (pos > validate_pos) {
  925. clear_index_entries(s, validate_pos);
  926. flv->validate_count = 0;
  927. }
  928. }
  929. if (size == 0) {
  930. ret = FFERROR_REDO;
  931. goto leave;
  932. }
  933. next = size + avio_tell(s->pb);
  934. if (type == FLV_TAG_TYPE_AUDIO) {
  935. stream_type = FLV_STREAM_TYPE_AUDIO;
  936. flags = avio_r8(s->pb);
  937. size--;
  938. } else if (type == FLV_TAG_TYPE_VIDEO) {
  939. stream_type = FLV_STREAM_TYPE_VIDEO;
  940. flags = avio_r8(s->pb);
  941. size--;
  942. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
  943. goto skip;
  944. } else if (type == FLV_TAG_TYPE_META) {
  945. stream_type=FLV_STREAM_TYPE_SUBTITLE;
  946. if (size > 13 + 1 + 4) { // Header-type metadata stuff
  947. int type;
  948. meta_pos = avio_tell(s->pb);
  949. type = flv_read_metabody(s, next);
  950. if (type == 0 && dts == 0 || type < 0) {
  951. if (type < 0 && flv->validate_count &&
  952. flv->validate_index[0].pos > next &&
  953. flv->validate_index[0].pos - 4 < next
  954. ) {
  955. av_log(s, AV_LOG_WARNING, "Adjusting next position due to index mismatch\n");
  956. next = flv->validate_index[0].pos - 4;
  957. }
  958. goto skip;
  959. } else if (type == TYPE_ONTEXTDATA) {
  960. avpriv_request_sample(s, "OnTextData packet");
  961. return flv_data_packet(s, pkt, dts, next);
  962. } else if (type == TYPE_ONCAPTION) {
  963. return flv_data_packet(s, pkt, dts, next);
  964. } else if (type == TYPE_UNKNOWN) {
  965. stream_type = FLV_STREAM_TYPE_DATA;
  966. }
  967. avio_seek(s->pb, meta_pos, SEEK_SET);
  968. }
  969. } else {
  970. av_log(s, AV_LOG_DEBUG,
  971. "Skipping flv packet: type %d, size %d, flags %d.\n",
  972. type, size, flags);
  973. skip:
  974. if (avio_seek(s->pb, next, SEEK_SET) != next) {
  975. // This can happen if flv_read_metabody above read past
  976. // next, on a non-seekable input, and the preceding data has
  977. // been flushed out from the IO buffer.
  978. av_log(s, AV_LOG_ERROR, "Unable to seek to the next packet\n");
  979. return AVERROR_INVALIDDATA;
  980. }
  981. ret = FFERROR_REDO;
  982. goto leave;
  983. }
  984. /* skip empty data packets */
  985. if (!size) {
  986. ret = FFERROR_REDO;
  987. goto leave;
  988. }
  989. /* now find stream */
  990. for (i = 0; i < s->nb_streams; i++) {
  991. st = s->streams[i];
  992. if (stream_type == FLV_STREAM_TYPE_AUDIO) {
  993. if (st->codecpar->codec_type == AVMEDIA_TYPE_AUDIO &&
  994. (s->audio_codec_id || flv_same_audio_codec(st->codecpar, flags)))
  995. break;
  996. } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
  997. if (st->codecpar->codec_type == AVMEDIA_TYPE_VIDEO &&
  998. (s->video_codec_id || flv_same_video_codec(st->codecpar, flags)))
  999. break;
  1000. } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
  1001. if (st->codecpar->codec_type == AVMEDIA_TYPE_SUBTITLE)
  1002. break;
  1003. } else if (stream_type == FLV_STREAM_TYPE_DATA) {
  1004. if (st->codecpar->codec_type == AVMEDIA_TYPE_DATA)
  1005. break;
  1006. }
  1007. }
  1008. if (i == s->nb_streams) {
  1009. static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_SUBTITLE, AVMEDIA_TYPE_DATA};
  1010. st = create_stream(s, stream_types[stream_type]);
  1011. if (!st)
  1012. return AVERROR(ENOMEM);
  1013. }
  1014. av_log(s, AV_LOG_TRACE, "%d %X %d \n", stream_type, flags, st->discard);
  1015. if (flv->time_pos <= pos) {
  1016. dts += flv->time_offset;
  1017. }
  1018. if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  1019. ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY ||
  1020. stream_type == FLV_STREAM_TYPE_AUDIO))
  1021. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  1022. if ( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
  1023. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
  1024. || st->discard >= AVDISCARD_ALL
  1025. ) {
  1026. avio_seek(s->pb, next, SEEK_SET);
  1027. ret = FFERROR_REDO;
  1028. goto leave;
  1029. }
  1030. // if not streamed and no duration from metadata then seek to end to find
  1031. // the duration from the timestamps
  1032. if ((s->pb->seekable & AVIO_SEEKABLE_NORMAL) &&
  1033. (!s->duration || s->duration == AV_NOPTS_VALUE) &&
  1034. !flv->searched_for_end) {
  1035. int size;
  1036. const int64_t pos = avio_tell(s->pb);
  1037. // Read the last 4 bytes of the file, this should be the size of the
  1038. // previous FLV tag. Use the timestamp of its payload as duration.
  1039. int64_t fsize = avio_size(s->pb);
  1040. retry_duration:
  1041. avio_seek(s->pb, fsize - 4, SEEK_SET);
  1042. size = avio_rb32(s->pb);
  1043. if (size > 0 && size < fsize) {
  1044. // Seek to the start of the last FLV tag at position (fsize - 4 - size)
  1045. // but skip the byte indicating the type.
  1046. avio_seek(s->pb, fsize - 3 - size, SEEK_SET);
  1047. if (size == avio_rb24(s->pb) + 11) {
  1048. uint32_t ts = avio_rb24(s->pb);
  1049. ts |= avio_r8(s->pb) << 24;
  1050. if (ts)
  1051. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  1052. else if (fsize >= 8 && fsize - 8 >= size) {
  1053. fsize -= size+4;
  1054. goto retry_duration;
  1055. }
  1056. }
  1057. }
  1058. avio_seek(s->pb, pos, SEEK_SET);
  1059. flv->searched_for_end = 1;
  1060. }
  1061. if (stream_type == FLV_STREAM_TYPE_AUDIO) {
  1062. int bits_per_coded_sample;
  1063. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  1064. sample_rate = 44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >>
  1065. FLV_AUDIO_SAMPLERATE_OFFSET) >> 3;
  1066. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  1067. if (!st->codecpar->channels || !st->codecpar->sample_rate ||
  1068. !st->codecpar->bits_per_coded_sample) {
  1069. st->codecpar->channels = channels;
  1070. st->codecpar->channel_layout = channels == 1
  1071. ? AV_CH_LAYOUT_MONO
  1072. : AV_CH_LAYOUT_STEREO;
  1073. st->codecpar->sample_rate = sample_rate;
  1074. st->codecpar->bits_per_coded_sample = bits_per_coded_sample;
  1075. }
  1076. if (!st->codecpar->codec_id) {
  1077. flv_set_audio_codec(s, st, st->codecpar,
  1078. flags & FLV_AUDIO_CODECID_MASK);
  1079. flv->last_sample_rate =
  1080. sample_rate = st->codecpar->sample_rate;
  1081. flv->last_channels =
  1082. channels = st->codecpar->channels;
  1083. } else {
  1084. AVCodecParameters *par = avcodec_parameters_alloc();
  1085. if (!par) {
  1086. ret = AVERROR(ENOMEM);
  1087. goto leave;
  1088. }
  1089. par->sample_rate = sample_rate;
  1090. par->bits_per_coded_sample = bits_per_coded_sample;
  1091. flv_set_audio_codec(s, st, par, flags & FLV_AUDIO_CODECID_MASK);
  1092. sample_rate = par->sample_rate;
  1093. avcodec_parameters_free(&par);
  1094. }
  1095. } else if (stream_type == FLV_STREAM_TYPE_VIDEO) {
  1096. int ret = flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
  1097. if (ret < 0)
  1098. return ret;
  1099. size -= ret;
  1100. } else if (stream_type == FLV_STREAM_TYPE_SUBTITLE) {
  1101. st->codecpar->codec_id = AV_CODEC_ID_TEXT;
  1102. } else if (stream_type == FLV_STREAM_TYPE_DATA) {
  1103. st->codecpar->codec_id = AV_CODEC_ID_NONE; // Opaque AMF data
  1104. }
  1105. if (st->codecpar->codec_id == AV_CODEC_ID_AAC ||
  1106. st->codecpar->codec_id == AV_CODEC_ID_H264 ||
  1107. st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
  1108. int type = avio_r8(s->pb);
  1109. size--;
  1110. if (size < 0) {
  1111. ret = AVERROR_INVALIDDATA;
  1112. goto leave;
  1113. }
  1114. if (st->codecpar->codec_id == AV_CODEC_ID_H264 || st->codecpar->codec_id == AV_CODEC_ID_MPEG4) {
  1115. // sign extension
  1116. int32_t cts = (avio_rb24(s->pb) + 0xff800000) ^ 0xff800000;
  1117. pts = dts + cts;
  1118. if (cts < 0) { // dts might be wrong
  1119. if (!flv->wrong_dts)
  1120. av_log(s, AV_LOG_WARNING,
  1121. "Negative cts, previous timestamps might be wrong.\n");
  1122. flv->wrong_dts = 1;
  1123. } else if (FFABS(dts - pts) > 1000*60*15) {
  1124. av_log(s, AV_LOG_WARNING,
  1125. "invalid timestamps %"PRId64" %"PRId64"\n", dts, pts);
  1126. dts = pts = AV_NOPTS_VALUE;
  1127. }
  1128. }
  1129. if (type == 0 && (!st->codecpar->extradata || st->codecpar->codec_id == AV_CODEC_ID_AAC ||
  1130. st->codecpar->codec_id == AV_CODEC_ID_H264)) {
  1131. AVDictionaryEntry *t;
  1132. if (st->codecpar->extradata) {
  1133. if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
  1134. return ret;
  1135. ret = FFERROR_REDO;
  1136. goto leave;
  1137. }
  1138. if ((ret = flv_get_extradata(s, st, size)) < 0)
  1139. return ret;
  1140. /* Workaround for buggy Omnia A/XE encoder */
  1141. t = av_dict_get(s->metadata, "Encoder", NULL, 0);
  1142. if (st->codecpar->codec_id == AV_CODEC_ID_AAC && t && !strcmp(t->value, "Omnia A/XE"))
  1143. st->codecpar->extradata_size = 2;
  1144. ret = FFERROR_REDO;
  1145. goto leave;
  1146. }
  1147. }
  1148. /* skip empty data packets */
  1149. if (!size) {
  1150. ret = FFERROR_REDO;
  1151. goto leave;
  1152. }
  1153. ret = av_get_packet(s->pb, pkt, size);
  1154. if (ret < 0)
  1155. return ret;
  1156. pkt->dts = dts;
  1157. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  1158. pkt->stream_index = st->index;
  1159. pkt->pos = pos;
  1160. if (flv->new_extradata[stream_type]) {
  1161. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  1162. flv->new_extradata_size[stream_type]);
  1163. if (side) {
  1164. memcpy(side, flv->new_extradata[stream_type],
  1165. flv->new_extradata_size[stream_type]);
  1166. av_freep(&flv->new_extradata[stream_type]);
  1167. flv->new_extradata_size[stream_type] = 0;
  1168. }
  1169. }
  1170. if (stream_type == FLV_STREAM_TYPE_AUDIO &&
  1171. (sample_rate != flv->last_sample_rate ||
  1172. channels != flv->last_channels)) {
  1173. flv->last_sample_rate = sample_rate;
  1174. flv->last_channels = channels;
  1175. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  1176. }
  1177. if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
  1178. ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
  1179. stream_type == FLV_STREAM_TYPE_SUBTITLE ||
  1180. stream_type == FLV_STREAM_TYPE_DATA)
  1181. pkt->flags |= AV_PKT_FLAG_KEY;
  1182. leave:
  1183. last = avio_rb32(s->pb);
  1184. if (!flv->trust_datasize) {
  1185. if (last != orig_size + 11 && last != orig_size + 10 &&
  1186. !avio_feof(s->pb) &&
  1187. (last != orig_size || !last) && last != flv->sum_flv_tag_size &&
  1188. !flv->broken_sizes) {
  1189. av_log(s, AV_LOG_ERROR, "Packet mismatch %d %d %d\n", last, orig_size + 11, flv->sum_flv_tag_size);
  1190. avio_seek(s->pb, pos + 1, SEEK_SET);
  1191. ret = resync(s);
  1192. av_packet_unref(pkt);
  1193. if (ret >= 0) {
  1194. goto retry;
  1195. }
  1196. }
  1197. }
  1198. if (ret >= 0)
  1199. flv->last_ts = pkt->dts;
  1200. return ret;
  1201. }
  1202. static int flv_read_seek(AVFormatContext *s, int stream_index,
  1203. int64_t ts, int flags)
  1204. {
  1205. FLVContext *flv = s->priv_data;
  1206. flv->validate_count = 0;
  1207. return avio_seek_time(s->pb, stream_index, ts, flags);
  1208. }
  1209. #define OFFSET(x) offsetof(FLVContext, x)
  1210. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  1211. static const AVOption options[] = {
  1212. { "flv_metadata", "Allocate streams according to the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1213. { "flv_full_metadata", "Dump full metadata of the onMetadata", OFFSET(dump_full_metadata), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1214. { "flv_ignore_prevtag", "Ignore the Size of previous tag", OFFSET(trust_datasize), AV_OPT_TYPE_BOOL, { .i64 = 0 }, 0, 1, VD },
  1215. { "missing_streams", "", OFFSET(missing_streams), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0xFF, VD | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY },
  1216. { NULL }
  1217. };
  1218. static const AVClass flv_class = {
  1219. .class_name = "flvdec",
  1220. .item_name = av_default_item_name,
  1221. .option = options,
  1222. .version = LIBAVUTIL_VERSION_INT,
  1223. };
  1224. AVInputFormat ff_flv_demuxer = {
  1225. .name = "flv",
  1226. .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
  1227. .priv_data_size = sizeof(FLVContext),
  1228. .read_probe = flv_probe,
  1229. .read_header = flv_read_header,
  1230. .read_packet = flv_read_packet,
  1231. .read_seek = flv_read_seek,
  1232. .read_close = flv_read_close,
  1233. .extensions = "flv",
  1234. .priv_class = &flv_class,
  1235. };
  1236. static const AVClass live_flv_class = {
  1237. .class_name = "live_flvdec",
  1238. .item_name = av_default_item_name,
  1239. .option = options,
  1240. .version = LIBAVUTIL_VERSION_INT,
  1241. };
  1242. AVInputFormat ff_live_flv_demuxer = {
  1243. .name = "live_flv",
  1244. .long_name = NULL_IF_CONFIG_SMALL("live RTMP FLV (Flash Video)"),
  1245. .priv_data_size = sizeof(FLVContext),
  1246. .read_probe = live_flv_probe,
  1247. .read_header = flv_read_header,
  1248. .read_packet = flv_read_packet,
  1249. .read_seek = flv_read_seek,
  1250. .read_close = flv_read_close,
  1251. .extensions = "flv",
  1252. .priv_class = &live_flv_class,
  1253. .flags = AVFMT_TS_DISCONT
  1254. };
  1255. static const AVClass kux_class = {
  1256. .class_name = "kuxdec",
  1257. .item_name = av_default_item_name,
  1258. .option = options,
  1259. .version = LIBAVUTIL_VERSION_INT,
  1260. };
  1261. AVInputFormat ff_kux_demuxer = {
  1262. .name = "kux",
  1263. .long_name = NULL_IF_CONFIG_SMALL("KUX (YouKu)"),
  1264. .priv_data_size = sizeof(FLVContext),
  1265. .read_probe = kux_probe,
  1266. .read_header = flv_read_header,
  1267. .read_packet = flv_read_packet,
  1268. .read_seek = flv_read_seek,
  1269. .read_close = flv_read_close,
  1270. .extensions = "kux",
  1271. .priv_class = &kux_class,
  1272. };