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.

1094 lines
37KB

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