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.

1004 lines
35KB

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