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.

1328 lines
46KB

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