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.

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