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.

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