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.

888 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. if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  452. != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  453. s->ctx_flags |= AVFMTCTX_NOHEADER;
  454. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  455. if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
  456. return AVERROR(ENOMEM);
  457. }
  458. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  459. if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
  460. return AVERROR(ENOMEM);
  461. }
  462. offset = avio_rb32(s->pb);
  463. avio_seek(s->pb, offset, SEEK_SET);
  464. avio_skip(s->pb, 4);
  465. s->start_time = 0;
  466. return 0;
  467. }
  468. static int flv_read_close(AVFormatContext *s)
  469. {
  470. FLVContext *flv = s->priv_data;
  471. av_freep(&flv->new_extradata[0]);
  472. av_freep(&flv->new_extradata[1]);
  473. return 0;
  474. }
  475. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  476. {
  477. av_free(st->codec->extradata);
  478. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  479. if (!st->codec->extradata)
  480. return AVERROR(ENOMEM);
  481. st->codec->extradata_size = size;
  482. avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
  483. return 0;
  484. }
  485. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  486. int size)
  487. {
  488. av_free(flv->new_extradata[stream]);
  489. flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  490. if (!flv->new_extradata[stream])
  491. return AVERROR(ENOMEM);
  492. flv->new_extradata_size[stream] = size;
  493. avio_read(pb, flv->new_extradata[stream], size);
  494. return 0;
  495. }
  496. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  497. {
  498. int i, j, out;
  499. av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
  500. for (i = 0; i < s->nb_streams; i++) {
  501. AVStream *st = s->streams[i];
  502. /* Remove all index entries that point to >= pos */
  503. out = 0;
  504. for (j = 0; j < st->nb_index_entries; j++) {
  505. if (st->index_entries[j].pos < pos)
  506. st->index_entries[out++] = st->index_entries[j];
  507. }
  508. st->nb_index_entries = out;
  509. }
  510. }
  511. static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
  512. int64_t dts, int64_t next)
  513. {
  514. int ret = AVERROR_INVALIDDATA, i;
  515. AVIOContext *pb = s->pb;
  516. AVStream *st = NULL;
  517. AMFDataType type;
  518. char buf[20];
  519. int length;
  520. type = avio_r8(pb);
  521. if (type == AMF_DATA_TYPE_MIXEDARRAY)
  522. avio_seek(pb, 4, SEEK_CUR);
  523. else if (type != AMF_DATA_TYPE_OBJECT)
  524. goto out;
  525. amf_get_string(pb, buf, sizeof(buf));
  526. if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  527. goto out;
  528. amf_get_string(pb, buf, sizeof(buf));
  529. //FIXME parse it as codec_id
  530. amf_get_string(pb, buf, sizeof(buf));
  531. if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  532. goto out;
  533. length = avio_rb16(pb);
  534. ret = av_get_packet(s->pb, pkt, length);
  535. if (ret < 0) {
  536. ret = AVERROR(EIO);
  537. goto out;
  538. }
  539. for (i = 0; i < s->nb_streams; i++) {
  540. st = s->streams[i];
  541. if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
  542. break;
  543. }
  544. if (i == s->nb_streams) {
  545. st = create_stream(s, AVMEDIA_TYPE_DATA);
  546. if (!st)
  547. goto out;
  548. st->codec->codec_id = AV_CODEC_ID_TEXT;
  549. }
  550. pkt->dts = dts;
  551. pkt->pts = dts;
  552. pkt->size = ret;
  553. pkt->stream_index = st->index;
  554. pkt->flags |= AV_PKT_FLAG_KEY;
  555. avio_seek(s->pb, next + 4, SEEK_SET);
  556. out:
  557. return ret;
  558. }
  559. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  560. {
  561. FLVContext *flv = s->priv_data;
  562. int ret, i, type, size, flags, is_audio;
  563. int64_t next, pos;
  564. int64_t dts, pts = AV_NOPTS_VALUE;
  565. int sample_rate = 0, channels = 0;
  566. AVStream *st = NULL;
  567. for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
  568. pos = avio_tell(s->pb);
  569. type = avio_r8(s->pb);
  570. size = avio_rb24(s->pb);
  571. dts = avio_rb24(s->pb);
  572. dts |= avio_r8(s->pb) << 24;
  573. av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
  574. if (s->pb->eof_reached)
  575. return AVERROR_EOF;
  576. avio_skip(s->pb, 3); /* stream id, always 0 */
  577. flags = 0;
  578. if (flv->validate_next < flv->validate_count) {
  579. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  580. if (pos == validate_pos) {
  581. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  582. VALIDATE_INDEX_TS_THRESH) {
  583. flv->validate_next++;
  584. } else {
  585. clear_index_entries(s, validate_pos);
  586. flv->validate_count = 0;
  587. }
  588. } else if (pos > validate_pos) {
  589. clear_index_entries(s, validate_pos);
  590. flv->validate_count = 0;
  591. }
  592. }
  593. if(size == 0)
  594. continue;
  595. next= size + avio_tell(s->pb);
  596. if (type == FLV_TAG_TYPE_AUDIO) {
  597. is_audio=1;
  598. flags = avio_r8(s->pb);
  599. size--;
  600. } else if (type == FLV_TAG_TYPE_VIDEO) {
  601. is_audio=0;
  602. flags = avio_r8(s->pb);
  603. size--;
  604. if ((flags & 0xf0) == 0x50) /* video info / command frame */
  605. goto skip;
  606. } else {
  607. if (type == FLV_TAG_TYPE_META && size > 13+1+4)
  608. if (flv_read_metabody(s, next) > 0) {
  609. return flv_data_packet(s, pkt, dts, next);
  610. }
  611. else /* skip packet */
  612. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  613. skip:
  614. avio_seek(s->pb, next, SEEK_SET);
  615. continue;
  616. }
  617. /* skip empty data packets */
  618. if (!size)
  619. continue;
  620. /* now find stream */
  621. for(i=0;i<s->nb_streams;i++) {
  622. st = s->streams[i];
  623. if (is_audio && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  624. if (flv_same_audio_codec(st->codec, flags)) {
  625. break;
  626. }
  627. } else
  628. if (!is_audio && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  629. if (flv_same_video_codec(st->codec, flags)) {
  630. break;
  631. }
  632. }
  633. }
  634. if(i == s->nb_streams){
  635. st = create_stream(s,
  636. is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO);
  637. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  638. }
  639. av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
  640. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  641. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  642. || st->discard >= AVDISCARD_ALL
  643. ){
  644. avio_seek(s->pb, next, SEEK_SET);
  645. continue;
  646. }
  647. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  648. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  649. break;
  650. }
  651. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  652. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
  653. int size;
  654. const int64_t pos= avio_tell(s->pb);
  655. const int64_t fsize= avio_size(s->pb);
  656. avio_seek(s->pb, fsize-4, SEEK_SET);
  657. size= avio_rb32(s->pb);
  658. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  659. if(size == avio_rb24(s->pb) + 11){
  660. uint32_t ts = avio_rb24(s->pb);
  661. ts |= avio_r8(s->pb) << 24;
  662. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  663. }
  664. avio_seek(s->pb, pos, SEEK_SET);
  665. }
  666. if(is_audio){
  667. int bits_per_coded_sample;
  668. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  669. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  670. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  671. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  672. st->codec->channels = channels;
  673. st->codec->sample_rate = sample_rate;
  674. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  675. }
  676. if(!st->codec->codec_id){
  677. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  678. flv->last_sample_rate = sample_rate = st->codec->sample_rate;
  679. flv->last_channels = channels = st->codec->channels;
  680. } else {
  681. AVCodecContext ctx;
  682. ctx.sample_rate = sample_rate;
  683. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  684. sample_rate = ctx.sample_rate;
  685. }
  686. }else{
  687. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  688. }
  689. if (st->codec->codec_id == AV_CODEC_ID_AAC ||
  690. st->codec->codec_id == AV_CODEC_ID_H264) {
  691. int type = avio_r8(s->pb);
  692. size--;
  693. if (st->codec->codec_id == AV_CODEC_ID_H264) {
  694. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  695. pts = dts + cts;
  696. if (cts < 0) { // dts are wrong
  697. flv->wrong_dts = 1;
  698. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  699. }
  700. if (flv->wrong_dts)
  701. dts = AV_NOPTS_VALUE;
  702. }
  703. if (type == 0) {
  704. if (st->codec->extradata) {
  705. if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
  706. return ret;
  707. ret = AVERROR(EAGAIN);
  708. goto leave;
  709. }
  710. if ((ret = flv_get_extradata(s, st, size)) < 0)
  711. return ret;
  712. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  713. MPEG4AudioConfig cfg;
  714. avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  715. st->codec->extradata_size * 8, 1);
  716. st->codec->channels = cfg.channels;
  717. if (cfg.ext_sample_rate)
  718. st->codec->sample_rate = cfg.ext_sample_rate;
  719. else
  720. st->codec->sample_rate = cfg.sample_rate;
  721. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  722. st->codec->channels, st->codec->sample_rate);
  723. }
  724. ret = AVERROR(EAGAIN);
  725. goto leave;
  726. }
  727. }
  728. /* skip empty data packets */
  729. if (!size) {
  730. ret = AVERROR(EAGAIN);
  731. goto leave;
  732. }
  733. ret= av_get_packet(s->pb, pkt, size);
  734. if (ret < 0) {
  735. return AVERROR(EIO);
  736. }
  737. /* note: we need to modify the packet size here to handle the last
  738. packet */
  739. pkt->size = ret;
  740. pkt->dts = dts;
  741. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  742. pkt->stream_index = st->index;
  743. if (flv->new_extradata[is_audio]) {
  744. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  745. flv->new_extradata_size[is_audio]);
  746. if (side) {
  747. memcpy(side, flv->new_extradata[is_audio],
  748. flv->new_extradata_size[is_audio]);
  749. av_freep(&flv->new_extradata[is_audio]);
  750. flv->new_extradata_size[is_audio] = 0;
  751. }
  752. }
  753. if (is_audio && (sample_rate != flv->last_sample_rate ||
  754. channels != flv->last_channels)) {
  755. flv->last_sample_rate = sample_rate;
  756. flv->last_channels = channels;
  757. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  758. }
  759. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  760. pkt->flags |= AV_PKT_FLAG_KEY;
  761. leave:
  762. avio_skip(s->pb, 4);
  763. return ret;
  764. }
  765. static int flv_read_seek(AVFormatContext *s, int stream_index,
  766. int64_t ts, int flags)
  767. {
  768. FLVContext *flv = s->priv_data;
  769. flv->validate_count = 0;
  770. return avio_seek_time(s->pb, stream_index, ts, flags);
  771. }
  772. #define OFFSET(x) offsetof(FLVContext, x)
  773. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  774. static const AVOption options[] = {
  775. { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD},
  776. { NULL }
  777. };
  778. static const AVClass class = {
  779. .class_name = "flvdec",
  780. .item_name = av_default_item_name,
  781. .option = options,
  782. .version = LIBAVUTIL_VERSION_INT,
  783. };
  784. AVInputFormat ff_flv_demuxer = {
  785. .name = "flv",
  786. .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
  787. .priv_data_size = sizeof(FLVContext),
  788. .read_probe = flv_probe,
  789. .read_header = flv_read_header,
  790. .read_packet = flv_read_packet,
  791. .read_seek = flv_read_seek,
  792. .read_close = flv_read_close,
  793. .extensions = "flv",
  794. .priv_class = &class,
  795. };