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.

893 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. return acodec->sample_rate == 8000 &&
  107. acodec->codec_id == CODEC_ID_NELLYMOSER;
  108. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  109. return acodec->sample_rate == 16000 &&
  110. acodec->codec_id == CODEC_ID_NELLYMOSER;
  111. case FLV_CODECID_NELLYMOSER:
  112. return acodec->codec_id == CODEC_ID_NELLYMOSER;
  113. case FLV_CODECID_PCM_MULAW:
  114. return acodec->sample_rate == 8000 &&
  115. acodec->codec_id == CODEC_ID_PCM_MULAW;
  116. case FLV_CODECID_PCM_ALAW:
  117. return acodec->sample_rate = 8000 &&
  118. acodec->codec_id == CODEC_ID_PCM_ALAW;
  119. default:
  120. return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  121. }
  122. return 0;
  123. }
  124. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
  125. switch(flv_codecid) {
  126. //no distinction between S16 and S8 PCM codec flags
  127. case FLV_CODECID_PCM:
  128. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
  129. #if HAVE_BIGENDIAN
  130. CODEC_ID_PCM_S16BE;
  131. #else
  132. CODEC_ID_PCM_S16LE;
  133. #endif
  134. break;
  135. case FLV_CODECID_PCM_LE:
  136. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
  137. case FLV_CODECID_AAC : acodec->codec_id = CODEC_ID_AAC; break;
  138. case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break;
  139. case FLV_CODECID_SPEEX:
  140. acodec->codec_id = CODEC_ID_SPEEX;
  141. acodec->sample_rate = 16000;
  142. break;
  143. case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
  144. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  145. acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
  146. acodec->codec_id = CODEC_ID_NELLYMOSER;
  147. break;
  148. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  149. acodec->sample_rate = 16000;
  150. acodec->codec_id = CODEC_ID_NELLYMOSER;
  151. break;
  152. case FLV_CODECID_NELLYMOSER:
  153. acodec->codec_id = CODEC_ID_NELLYMOSER;
  154. break;
  155. case FLV_CODECID_PCM_MULAW:
  156. acodec->sample_rate = 8000;
  157. acodec->codec_id = CODEC_ID_PCM_MULAW;
  158. break;
  159. case FLV_CODECID_PCM_ALAW:
  160. acodec->sample_rate = 8000;
  161. acodec->codec_id = CODEC_ID_PCM_ALAW;
  162. break;
  163. default:
  164. av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  165. acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  166. }
  167. }
  168. static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
  169. {
  170. int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
  171. if (!vcodec->codec_id && !vcodec->codec_tag)
  172. return 1;
  173. switch (flv_codecid) {
  174. case FLV_CODECID_H263:
  175. return vcodec->codec_id == CODEC_ID_FLV1;
  176. case FLV_CODECID_SCREEN:
  177. return vcodec->codec_id == CODEC_ID_FLASHSV;
  178. case FLV_CODECID_SCREEN2:
  179. return vcodec->codec_id == CODEC_ID_FLASHSV2;
  180. case FLV_CODECID_VP6:
  181. return vcodec->codec_id == CODEC_ID_VP6F;
  182. case FLV_CODECID_VP6A:
  183. return vcodec->codec_id == CODEC_ID_VP6A;
  184. case FLV_CODECID_H264:
  185. return vcodec->codec_id == CODEC_ID_H264;
  186. default:
  187. return vcodec->codec_tag == flv_codecid;
  188. }
  189. return 0;
  190. }
  191. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
  192. AVCodecContext *vcodec = vstream->codec;
  193. switch(flv_codecid) {
  194. case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break;
  195. case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
  196. case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
  197. case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ;
  198. case FLV_CODECID_VP6A :
  199. if(flv_codecid == FLV_CODECID_VP6A)
  200. vcodec->codec_id = CODEC_ID_VP6A;
  201. if(vcodec->extradata_size != 1) {
  202. vcodec->extradata_size = 1;
  203. vcodec->extradata = av_malloc(1);
  204. }
  205. vcodec->extradata[0] = avio_r8(s->pb);
  206. return 1; // 1 byte body size adjustment for flv_read_packet()
  207. case FLV_CODECID_H264:
  208. vcodec->codec_id = CODEC_ID_H264;
  209. return 3; // not 4, reading packet type will consume one byte
  210. default:
  211. av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
  212. vcodec->codec_tag = flv_codecid;
  213. }
  214. return 0;
  215. }
  216. static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
  217. int length = avio_rb16(ioc);
  218. if(length >= buffsize) {
  219. avio_skip(ioc, length);
  220. return -1;
  221. }
  222. avio_read(ioc, buffer, length);
  223. buffer[length] = '\0';
  224. return length;
  225. }
  226. static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
  227. FLVContext *flv = s->priv_data;
  228. unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
  229. double num_val;
  230. char str_val[256];
  231. int64_t *times = NULL;
  232. int64_t *filepositions = NULL;
  233. int ret = AVERROR(ENOSYS);
  234. int64_t initial_pos = avio_tell(ioc);
  235. if (s->flags & AVFMT_FLAG_IGNIDX)
  236. return 0;
  237. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  238. int64_t* current_array;
  239. // Expect array object in context
  240. if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
  241. break;
  242. arraylen = avio_rb32(ioc);
  243. if (arraylen >> 28)
  244. break;
  245. /*
  246. * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
  247. * for indexing
  248. */
  249. if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
  250. if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
  251. ret = AVERROR(ENOMEM);
  252. goto finish;
  253. }
  254. timeslen = arraylen;
  255. current_array = times;
  256. } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
  257. if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
  258. ret = AVERROR(ENOMEM);
  259. goto finish;
  260. }
  261. fileposlen = arraylen;
  262. current_array = filepositions;
  263. } else // unexpected metatag inside keyframes, will not use such metadata for indexing
  264. break;
  265. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  266. if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
  267. goto finish;
  268. num_val = av_int2double(avio_rb64(ioc));
  269. current_array[i] = num_val;
  270. }
  271. if (times && filepositions) {
  272. // All done, exiting at a position allowing amf_parse_object
  273. // to finish parsing the object
  274. ret = 0;
  275. break;
  276. }
  277. }
  278. if (!ret && timeslen == fileposlen) {
  279. for (i = 0; i < fileposlen; i++) {
  280. av_add_index_entry(vstream, filepositions[i], times[i]*1000,
  281. 0, 0, AVINDEX_KEYFRAME);
  282. if (i < 2) {
  283. flv->validate_index[i].pos = filepositions[i];
  284. flv->validate_index[i].dts = times[i] * 1000;
  285. flv->validate_count = i + 1;
  286. }
  287. }
  288. } else
  289. av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
  290. finish:
  291. av_freep(&times);
  292. av_freep(&filepositions);
  293. // If we got unexpected data, but successfully reset back to
  294. // the start pos, the caller can continue parsing
  295. if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
  296. return 0;
  297. return ret;
  298. }
  299. static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
  300. AVCodecContext *acodec, *vcodec;
  301. FLVContext *flv = s->priv_data;
  302. AVIOContext *ioc;
  303. AMFDataType amf_type;
  304. char str_val[256];
  305. double num_val;
  306. num_val = 0;
  307. ioc = s->pb;
  308. amf_type = avio_r8(ioc);
  309. switch(amf_type) {
  310. case AMF_DATA_TYPE_NUMBER:
  311. num_val = av_int2double(avio_rb64(ioc)); break;
  312. case AMF_DATA_TYPE_BOOL:
  313. num_val = avio_r8(ioc); break;
  314. case AMF_DATA_TYPE_STRING:
  315. if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
  316. return -1;
  317. break;
  318. case AMF_DATA_TYPE_OBJECT:
  319. if ((vstream || astream) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
  320. if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
  321. max_pos) < 0)
  322. return -1;
  323. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  324. if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  325. return -1; //if we couldn't skip, bomb out.
  326. }
  327. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  328. return -1;
  329. break;
  330. case AMF_DATA_TYPE_NULL:
  331. case AMF_DATA_TYPE_UNDEFINED:
  332. case AMF_DATA_TYPE_UNSUPPORTED:
  333. break; //these take up no additional space
  334. case AMF_DATA_TYPE_MIXEDARRAY:
  335. avio_skip(ioc, 4); //skip 32-bit max array index
  336. while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  337. //this is the only case in which we would want a nested parse to not skip over the object
  338. if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  339. return -1;
  340. }
  341. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  342. return -1;
  343. break;
  344. case AMF_DATA_TYPE_ARRAY: {
  345. unsigned int arraylen, i;
  346. arraylen = avio_rb32(ioc);
  347. for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  348. if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
  349. return -1; //if we couldn't skip, bomb out.
  350. }
  351. }
  352. break;
  353. case AMF_DATA_TYPE_DATE:
  354. avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
  355. break;
  356. default: //unsupported type, we couldn't skip
  357. return -1;
  358. }
  359. if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
  360. acodec = astream ? astream->codec : NULL;
  361. vcodec = vstream ? vstream->codec : NULL;
  362. if (amf_type == AMF_DATA_TYPE_NUMBER) {
  363. if (!strcmp(key, "duration"))
  364. s->duration = num_val * AV_TIME_BASE;
  365. else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
  366. vcodec->bit_rate = num_val * 1024.0;
  367. else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
  368. acodec->bit_rate = num_val * 1024.0;
  369. else if (!strcmp(key, "datastream")) {
  370. AVStream *st = create_stream(s, 2, AVMEDIA_TYPE_DATA);
  371. if (!st)
  372. return AVERROR(ENOMEM);
  373. st->codec->codec_id = CODEC_ID_TEXT;
  374. } else if (flv->trust_metadata) {
  375. if (!strcmp(key, "videocodecid") && vcodec) {
  376. flv_set_video_codec(s, vstream, num_val);
  377. } else
  378. if (!strcmp(key, "audiocodecid") && acodec) {
  379. flv_set_audio_codec(s, astream, acodec, num_val);
  380. } else
  381. if (!strcmp(key, "audiosamplerate") && acodec) {
  382. acodec->sample_rate = num_val;
  383. } else
  384. if (!strcmp(key, "width") && vcodec) {
  385. vcodec->width = num_val;
  386. } else
  387. if (!strcmp(key, "height") && vcodec) {
  388. vcodec->height = num_val;
  389. }
  390. }
  391. }
  392. if (!strcmp(key, "duration") ||
  393. !strcmp(key, "filesize") ||
  394. !strcmp(key, "width") ||
  395. !strcmp(key, "height") ||
  396. !strcmp(key, "videodatarate") ||
  397. !strcmp(key, "framerate") ||
  398. !strcmp(key, "videocodecid") ||
  399. !strcmp(key, "audiodatarate") ||
  400. !strcmp(key, "audiosamplerate") ||
  401. !strcmp(key, "audiosamplesize") ||
  402. !strcmp(key, "stereo") ||
  403. !strcmp(key, "audiocodecid"))
  404. return 0;
  405. if(amf_type == AMF_DATA_TYPE_BOOL) {
  406. av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
  407. av_dict_set(&s->metadata, key, str_val, 0);
  408. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  409. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  410. av_dict_set(&s->metadata, key, str_val, 0);
  411. } else if (amf_type == AMF_DATA_TYPE_STRING)
  412. av_dict_set(&s->metadata, key, str_val, 0);
  413. }
  414. return 0;
  415. }
  416. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  417. AMFDataType type;
  418. AVStream *stream, *astream, *vstream;
  419. AVIOContext *ioc;
  420. int i;
  421. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  422. astream = NULL;
  423. vstream = NULL;
  424. ioc = s->pb;
  425. //first object needs to be "onMetaData" string
  426. type = avio_r8(ioc);
  427. if (type != AMF_DATA_TYPE_STRING ||
  428. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  429. return -1;
  430. if (!strcmp(buffer, "onTextData"))
  431. return 1;
  432. if (strcmp(buffer, "onMetaData"))
  433. return -1;
  434. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  435. for(i = 0; i < s->nb_streams; i++) {
  436. stream = s->streams[i];
  437. if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
  438. else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
  439. }
  440. //parse the second object (we want a mixed array)
  441. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  442. return -1;
  443. return 0;
  444. }
  445. static int flv_read_header(AVFormatContext *s)
  446. {
  447. int offset, flags;
  448. avio_skip(s->pb, 4);
  449. flags = avio_r8(s->pb);
  450. /* old flvtool cleared this field */
  451. /* FIXME: better fix needed */
  452. if (!flags) {
  453. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  454. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  455. }
  456. if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  457. != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  458. s->ctx_flags |= AVFMTCTX_NOHEADER;
  459. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  460. if(!create_stream(s, 0, AVMEDIA_TYPE_VIDEO))
  461. return AVERROR(ENOMEM);
  462. }
  463. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  464. if(!create_stream(s, 1, 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, 2, AVMEDIA_TYPE_DATA);
  551. if (!st)
  552. goto out;
  553. st->codec->codec_id = 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, is_audio,
  641. is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO);
  642. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  643. }
  644. av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
  645. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  646. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  647. || st->discard >= AVDISCARD_ALL
  648. ){
  649. avio_seek(s->pb, next, SEEK_SET);
  650. continue;
  651. }
  652. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  653. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  654. break;
  655. }
  656. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  657. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
  658. int size;
  659. const int64_t pos= avio_tell(s->pb);
  660. const int64_t fsize= avio_size(s->pb);
  661. avio_seek(s->pb, fsize-4, SEEK_SET);
  662. size= avio_rb32(s->pb);
  663. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  664. if(size == avio_rb24(s->pb) + 11){
  665. uint32_t ts = avio_rb24(s->pb);
  666. ts |= avio_r8(s->pb) << 24;
  667. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  668. }
  669. avio_seek(s->pb, pos, SEEK_SET);
  670. }
  671. if(is_audio){
  672. int bits_per_coded_sample;
  673. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  674. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  675. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  676. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  677. st->codec->channels = channels;
  678. st->codec->sample_rate = sample_rate;
  679. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  680. }
  681. if(!st->codec->codec_id){
  682. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  683. flv->last_sample_rate = sample_rate = st->codec->sample_rate;
  684. flv->last_channels = channels = st->codec->channels;
  685. } else {
  686. AVCodecContext ctx;
  687. ctx.sample_rate = sample_rate;
  688. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  689. sample_rate = ctx.sample_rate;
  690. }
  691. }else{
  692. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  693. }
  694. if (st->codec->codec_id == CODEC_ID_AAC ||
  695. st->codec->codec_id == CODEC_ID_H264) {
  696. int type = avio_r8(s->pb);
  697. size--;
  698. if (st->codec->codec_id == CODEC_ID_H264) {
  699. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  700. pts = dts + cts;
  701. if (cts < 0) { // dts are wrong
  702. flv->wrong_dts = 1;
  703. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  704. }
  705. if (flv->wrong_dts)
  706. dts = AV_NOPTS_VALUE;
  707. }
  708. if (type == 0) {
  709. if (st->codec->extradata) {
  710. if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
  711. return ret;
  712. ret = AVERROR(EAGAIN);
  713. goto leave;
  714. }
  715. if ((ret = flv_get_extradata(s, st, size)) < 0)
  716. return ret;
  717. if (st->codec->codec_id == CODEC_ID_AAC) {
  718. MPEG4AudioConfig cfg;
  719. avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  720. st->codec->extradata_size * 8, 1);
  721. st->codec->channels = cfg.channels;
  722. if (cfg.ext_sample_rate)
  723. st->codec->sample_rate = cfg.ext_sample_rate;
  724. else
  725. st->codec->sample_rate = cfg.sample_rate;
  726. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  727. st->codec->channels, st->codec->sample_rate);
  728. }
  729. ret = AVERROR(EAGAIN);
  730. goto leave;
  731. }
  732. }
  733. /* skip empty data packets */
  734. if (!size) {
  735. ret = AVERROR(EAGAIN);
  736. goto leave;
  737. }
  738. ret= av_get_packet(s->pb, pkt, size);
  739. if (ret < 0) {
  740. return AVERROR(EIO);
  741. }
  742. /* note: we need to modify the packet size here to handle the last
  743. packet */
  744. pkt->size = ret;
  745. pkt->dts = dts;
  746. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  747. pkt->stream_index = st->index;
  748. if (flv->new_extradata[is_audio]) {
  749. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  750. flv->new_extradata_size[is_audio]);
  751. if (side) {
  752. memcpy(side, flv->new_extradata[is_audio],
  753. flv->new_extradata_size[is_audio]);
  754. av_freep(&flv->new_extradata[is_audio]);
  755. flv->new_extradata_size[is_audio] = 0;
  756. }
  757. }
  758. if (is_audio && (sample_rate != flv->last_sample_rate ||
  759. channels != flv->last_channels)) {
  760. flv->last_sample_rate = sample_rate;
  761. flv->last_channels = channels;
  762. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  763. }
  764. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  765. pkt->flags |= AV_PKT_FLAG_KEY;
  766. leave:
  767. avio_skip(s->pb, 4);
  768. return ret;
  769. }
  770. static int flv_read_seek(AVFormatContext *s, int stream_index,
  771. int64_t ts, int flags)
  772. {
  773. FLVContext *flv = s->priv_data;
  774. flv->validate_count = 0;
  775. return avio_seek_time(s->pb, stream_index, ts, flags);
  776. }
  777. #define OFFSET(x) offsetof(FLVContext, x)
  778. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  779. static const AVOption options[] = {
  780. { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD},
  781. { NULL }
  782. };
  783. static const AVClass class = {
  784. .class_name = "flvdec",
  785. .item_name = av_default_item_name,
  786. .option = options,
  787. .version = LIBAVUTIL_VERSION_INT,
  788. };
  789. AVInputFormat ff_flv_demuxer = {
  790. .name = "flv",
  791. .long_name = NULL_IF_CONFIG_SMALL("FLV format"),
  792. .priv_data_size = sizeof(FLVContext),
  793. .read_probe = flv_probe,
  794. .read_header = flv_read_header,
  795. .read_packet = flv_read_packet,
  796. .read_seek = flv_read_seek,
  797. .read_close = flv_read_close,
  798. .extensions = "flv",
  799. .priv_class = &class,
  800. };