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.

895 lines
31KB

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