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.

1427 lines
49KB

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