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.

899 lines
31KB

  1. /*
  2. * FLV demuxer
  3. * Copyright (c) 2003 The Libav Project
  4. *
  5. * This demuxer will generate a 1 byte extradata for VP6F content.
  6. * It is composed of:
  7. * - upper 4bits: difference between encoded width and visible width
  8. * - lower 4bits: difference between encoded height and visible height
  9. *
  10. * This file is part of Libav.
  11. *
  12. * Libav is free software; you can redistribute it and/or
  13. * modify it under the terms of the GNU Lesser General Public
  14. * License as published by the Free Software Foundation; either
  15. * version 2.1 of the License, or (at your option) any later version.
  16. *
  17. * Libav is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  20. * Lesser General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU Lesser General Public
  23. * License along with Libav; if not, write to the Free Software
  24. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  25. */
  26. #include "libavutil/avstring.h"
  27. #include "libavutil/channel_layout.h"
  28. #include "libavutil/dict.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/intfloat.h"
  31. #include "libavutil/mathematics.h"
  32. #include "libavcodec/bytestream.h"
  33. #include "libavcodec/mpeg4audio.h"
  34. #include "avformat.h"
  35. #include "internal.h"
  36. #include "avio_internal.h"
  37. #include "flv.h"
  38. #define KEYFRAMES_TAG "keyframes"
  39. #define KEYFRAMES_TIMESTAMP_TAG "times"
  40. #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
  41. #define VALIDATE_INDEX_TS_THRESH 2500
  42. typedef struct {
  43. const AVClass *class; ///< Class for private options.
  44. int trust_metadata; ///< configure streams according onMetaData
  45. int wrong_dts; ///< wrong dts due to negative cts
  46. uint8_t *new_extradata[2];
  47. int new_extradata_size[2];
  48. int last_sample_rate;
  49. int last_channels;
  50. struct {
  51. int64_t dts;
  52. int64_t pos;
  53. } validate_index[2];
  54. int validate_next;
  55. int validate_count;
  56. } FLVContext;
  57. static int flv_probe(AVProbeData *p)
  58. {
  59. const uint8_t *d;
  60. d = p->buf;
  61. if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
  62. return AVPROBE_SCORE_MAX;
  63. }
  64. return 0;
  65. }
  66. static AVStream *create_stream(AVFormatContext *s, int codec_type)
  67. {
  68. AVStream *st = avformat_new_stream(s, NULL);
  69. if (!st)
  70. return NULL;
  71. st->codec->codec_type = codec_type;
  72. avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  73. return st;
  74. }
  75. static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
  76. {
  77. int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  78. int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
  79. int codec_id;
  80. if (!acodec->codec_id && !acodec->codec_tag)
  81. return 1;
  82. if (acodec->bits_per_coded_sample != bits_per_coded_sample)
  83. return 0;
  84. switch(flv_codecid) {
  85. //no distinction between S16 and S8 PCM codec flags
  86. case FLV_CODECID_PCM:
  87. codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
  88. #if HAVE_BIGENDIAN
  89. AV_CODEC_ID_PCM_S16BE;
  90. #else
  91. AV_CODEC_ID_PCM_S16LE;
  92. #endif
  93. return codec_id == acodec->codec_id;
  94. case FLV_CODECID_PCM_LE:
  95. codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;
  96. return codec_id == acodec->codec_id;
  97. case FLV_CODECID_AAC:
  98. return acodec->codec_id == AV_CODEC_ID_AAC;
  99. case FLV_CODECID_ADPCM:
  100. return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
  101. case FLV_CODECID_SPEEX:
  102. return acodec->codec_id == AV_CODEC_ID_SPEEX;
  103. case FLV_CODECID_MP3:
  104. return acodec->codec_id == AV_CODEC_ID_MP3;
  105. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  106. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  107. case FLV_CODECID_NELLYMOSER:
  108. return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
  109. case FLV_CODECID_PCM_MULAW:
  110. return acodec->sample_rate == 8000 &&
  111. acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
  112. case FLV_CODECID_PCM_ALAW:
  113. return acodec->sample_rate = 8000 &&
  114. acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
  115. default:
  116. return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  117. }
  118. }
  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. }
  185. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid, int read) {
  186. AVCodecContext *vcodec = vstream->codec;
  187. switch(flv_codecid) {
  188. case FLV_CODECID_H263 : vcodec->codec_id = AV_CODEC_ID_FLV1 ; break;
  189. case FLV_CODECID_SCREEN: vcodec->codec_id = AV_CODEC_ID_FLASHSV; break;
  190. case FLV_CODECID_SCREEN2: vcodec->codec_id = AV_CODEC_ID_FLASHSV2; break;
  191. case FLV_CODECID_VP6 : vcodec->codec_id = AV_CODEC_ID_VP6F ;
  192. case FLV_CODECID_VP6A :
  193. if(flv_codecid == FLV_CODECID_VP6A)
  194. vcodec->codec_id = AV_CODEC_ID_VP6A;
  195. if (read) {
  196. if (vcodec->extradata_size != 1) {
  197. vcodec->extradata = av_malloc(1);
  198. if (vcodec->extradata)
  199. vcodec->extradata_size = 1;
  200. }
  201. if (vcodec->extradata)
  202. vcodec->extradata[0] = avio_r8(s->pb);
  203. else
  204. avio_skip(s->pb, 1);
  205. }
  206. return 1; // 1 byte body size adjustment for flv_read_packet()
  207. case FLV_CODECID_H264:
  208. vcodec->codec_id = AV_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 || amf_type == AMF_DATA_TYPE_BOOL) {
  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, AVMEDIA_TYPE_DATA);
  371. if (!st)
  372. return AVERROR(ENOMEM);
  373. st->codec->codec_id = AV_CODEC_ID_TEXT;
  374. } else if (flv->trust_metadata) {
  375. if (!strcmp(key, "videocodecid") && vcodec) {
  376. flv_set_video_codec(s, vstream, num_val, 0);
  377. } else
  378. if (!strcmp(key, "audiocodecid") && acodec) {
  379. int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
  380. flv_set_audio_codec(s, astream, acodec, id);
  381. } else
  382. if (!strcmp(key, "audiosamplerate") && acodec) {
  383. acodec->sample_rate = num_val;
  384. } else if (!strcmp(key, "audiosamplesize") && acodec) {
  385. acodec->bits_per_coded_sample = num_val;
  386. } else if (!strcmp(key, "stereo") && acodec) {
  387. acodec->channels = num_val + 1;
  388. acodec->channel_layout = acodec->channels == 2 ?
  389. AV_CH_LAYOUT_STEREO :
  390. AV_CH_LAYOUT_MONO;
  391. } else
  392. if (!strcmp(key, "width") && vcodec) {
  393. vcodec->width = num_val;
  394. } else
  395. if (!strcmp(key, "height") && vcodec) {
  396. vcodec->height = num_val;
  397. }
  398. }
  399. }
  400. if (!strcmp(key, "duration") ||
  401. !strcmp(key, "filesize") ||
  402. !strcmp(key, "width") ||
  403. !strcmp(key, "height") ||
  404. !strcmp(key, "videodatarate") ||
  405. !strcmp(key, "framerate") ||
  406. !strcmp(key, "videocodecid") ||
  407. !strcmp(key, "audiodatarate") ||
  408. !strcmp(key, "audiosamplerate") ||
  409. !strcmp(key, "audiosamplesize") ||
  410. !strcmp(key, "stereo") ||
  411. !strcmp(key, "audiocodecid"))
  412. return 0;
  413. if(amf_type == AMF_DATA_TYPE_BOOL) {
  414. av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
  415. av_dict_set(&s->metadata, key, str_val, 0);
  416. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  417. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  418. av_dict_set(&s->metadata, key, str_val, 0);
  419. } else if (amf_type == AMF_DATA_TYPE_STRING)
  420. av_dict_set(&s->metadata, key, str_val, 0);
  421. }
  422. return 0;
  423. }
  424. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  425. AMFDataType type;
  426. AVStream *stream, *astream, *vstream;
  427. AVIOContext *ioc;
  428. int i;
  429. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  430. astream = NULL;
  431. vstream = NULL;
  432. ioc = s->pb;
  433. //first object needs to be "onMetaData" string
  434. type = avio_r8(ioc);
  435. if (type != AMF_DATA_TYPE_STRING ||
  436. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  437. return -1;
  438. if (!strcmp(buffer, "onTextData"))
  439. return 1;
  440. if (strcmp(buffer, "onMetaData"))
  441. return -1;
  442. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  443. for(i = 0; i < s->nb_streams; i++) {
  444. stream = s->streams[i];
  445. if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
  446. else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
  447. }
  448. //parse the second object (we want a mixed array)
  449. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  450. return -1;
  451. return 0;
  452. }
  453. static int flv_read_header(AVFormatContext *s)
  454. {
  455. int offset, flags;
  456. avio_skip(s->pb, 4);
  457. flags = avio_r8(s->pb);
  458. /* old flvtool cleared this field */
  459. /* FIXME: better fix needed */
  460. if (!flags) {
  461. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  462. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  463. }
  464. s->ctx_flags |= AVFMTCTX_NOHEADER;
  465. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  466. if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
  467. return AVERROR(ENOMEM);
  468. }
  469. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  470. if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
  471. return AVERROR(ENOMEM);
  472. }
  473. offset = avio_rb32(s->pb);
  474. avio_seek(s->pb, offset, SEEK_SET);
  475. avio_skip(s->pb, 4);
  476. s->start_time = 0;
  477. return 0;
  478. }
  479. static int flv_read_close(AVFormatContext *s)
  480. {
  481. FLVContext *flv = s->priv_data;
  482. av_freep(&flv->new_extradata[0]);
  483. av_freep(&flv->new_extradata[1]);
  484. return 0;
  485. }
  486. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  487. {
  488. av_free(st->codec->extradata);
  489. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  490. if (!st->codec->extradata)
  491. return AVERROR(ENOMEM);
  492. st->codec->extradata_size = size;
  493. avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
  494. return 0;
  495. }
  496. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  497. int size)
  498. {
  499. av_free(flv->new_extradata[stream]);
  500. flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  501. if (!flv->new_extradata[stream])
  502. return AVERROR(ENOMEM);
  503. flv->new_extradata_size[stream] = size;
  504. avio_read(pb, flv->new_extradata[stream], size);
  505. return 0;
  506. }
  507. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  508. {
  509. int i, j, out;
  510. av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
  511. for (i = 0; i < s->nb_streams; i++) {
  512. AVStream *st = s->streams[i];
  513. /* Remove all index entries that point to >= pos */
  514. out = 0;
  515. for (j = 0; j < st->nb_index_entries; j++) {
  516. if (st->index_entries[j].pos < pos)
  517. st->index_entries[out++] = st->index_entries[j];
  518. }
  519. st->nb_index_entries = out;
  520. }
  521. }
  522. static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
  523. int64_t dts, int64_t next)
  524. {
  525. int ret = AVERROR_INVALIDDATA, i;
  526. AVIOContext *pb = s->pb;
  527. AVStream *st = NULL;
  528. AMFDataType type;
  529. char buf[20];
  530. int length;
  531. type = avio_r8(pb);
  532. if (type == AMF_DATA_TYPE_MIXEDARRAY)
  533. avio_seek(pb, 4, SEEK_CUR);
  534. else if (type != AMF_DATA_TYPE_OBJECT)
  535. goto out;
  536. amf_get_string(pb, buf, sizeof(buf));
  537. if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  538. goto out;
  539. amf_get_string(pb, buf, sizeof(buf));
  540. //FIXME parse it as codec_id
  541. amf_get_string(pb, buf, sizeof(buf));
  542. if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  543. goto out;
  544. length = avio_rb16(pb);
  545. ret = av_get_packet(s->pb, pkt, length);
  546. if (ret < 0) {
  547. ret = AVERROR(EIO);
  548. goto out;
  549. }
  550. for (i = 0; i < s->nb_streams; i++) {
  551. st = s->streams[i];
  552. if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
  553. break;
  554. }
  555. if (i == s->nb_streams) {
  556. st = create_stream(s, AVMEDIA_TYPE_DATA);
  557. if (!st)
  558. goto out;
  559. st->codec->codec_id = AV_CODEC_ID_TEXT;
  560. }
  561. pkt->dts = dts;
  562. pkt->pts = dts;
  563. pkt->size = ret;
  564. pkt->stream_index = st->index;
  565. pkt->flags |= AV_PKT_FLAG_KEY;
  566. avio_seek(s->pb, next + 4, SEEK_SET);
  567. out:
  568. return ret;
  569. }
  570. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  571. {
  572. FLVContext *flv = s->priv_data;
  573. int ret, i, type, size, flags, is_audio;
  574. int64_t next, pos;
  575. int64_t dts, pts = AV_NOPTS_VALUE;
  576. int sample_rate = 0, channels = 0;
  577. AVStream *st = NULL;
  578. for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
  579. pos = avio_tell(s->pb);
  580. type = avio_r8(s->pb);
  581. size = avio_rb24(s->pb);
  582. dts = avio_rb24(s->pb);
  583. dts |= avio_r8(s->pb) << 24;
  584. av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
  585. if (s->pb->eof_reached)
  586. return AVERROR_EOF;
  587. avio_skip(s->pb, 3); /* stream id, always 0 */
  588. flags = 0;
  589. if (flv->validate_next < flv->validate_count) {
  590. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  591. if (pos == validate_pos) {
  592. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  593. VALIDATE_INDEX_TS_THRESH) {
  594. flv->validate_next++;
  595. } else {
  596. clear_index_entries(s, validate_pos);
  597. flv->validate_count = 0;
  598. }
  599. } else if (pos > validate_pos) {
  600. clear_index_entries(s, validate_pos);
  601. flv->validate_count = 0;
  602. }
  603. }
  604. if(size == 0)
  605. continue;
  606. next= size + avio_tell(s->pb);
  607. if (type == FLV_TAG_TYPE_AUDIO) {
  608. is_audio=1;
  609. flags = avio_r8(s->pb);
  610. size--;
  611. } else if (type == FLV_TAG_TYPE_VIDEO) {
  612. is_audio=0;
  613. flags = avio_r8(s->pb);
  614. size--;
  615. if ((flags & 0xf0) == 0x50) /* video info / command frame */
  616. goto skip;
  617. } else {
  618. if (type == FLV_TAG_TYPE_META && size > 13+1+4)
  619. if (flv_read_metabody(s, next) > 0) {
  620. return flv_data_packet(s, pkt, dts, next);
  621. }
  622. else /* skip packet */
  623. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  624. skip:
  625. avio_seek(s->pb, next, SEEK_SET);
  626. continue;
  627. }
  628. /* skip empty data packets */
  629. if (!size)
  630. continue;
  631. /* now find stream */
  632. for(i=0;i<s->nb_streams;i++) {
  633. st = s->streams[i];
  634. if (is_audio && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  635. if (flv_same_audio_codec(st->codec, flags)) {
  636. break;
  637. }
  638. } else
  639. if (!is_audio && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  640. if (flv_same_video_codec(st->codec, flags)) {
  641. break;
  642. }
  643. }
  644. }
  645. if(i == s->nb_streams){
  646. st = create_stream(s,
  647. is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO);
  648. }
  649. av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
  650. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  651. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  652. || st->discard >= AVDISCARD_ALL
  653. ){
  654. avio_seek(s->pb, next, SEEK_SET);
  655. continue;
  656. }
  657. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  658. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  659. break;
  660. }
  661. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  662. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
  663. int size;
  664. const int64_t pos= avio_tell(s->pb);
  665. const int64_t fsize= avio_size(s->pb);
  666. avio_seek(s->pb, fsize-4, SEEK_SET);
  667. size= avio_rb32(s->pb);
  668. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  669. if(size == avio_rb24(s->pb) + 11){
  670. uint32_t ts = avio_rb24(s->pb);
  671. ts |= avio_r8(s->pb) << 24;
  672. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  673. }
  674. avio_seek(s->pb, pos, SEEK_SET);
  675. }
  676. if(is_audio){
  677. int bits_per_coded_sample;
  678. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  679. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  680. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  681. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  682. st->codec->channels = channels;
  683. st->codec->channel_layout = channels == 1 ? AV_CH_LAYOUT_MONO :
  684. AV_CH_LAYOUT_STEREO;
  685. st->codec->sample_rate = sample_rate;
  686. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  687. }
  688. if(!st->codec->codec_id){
  689. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  690. flv->last_sample_rate = sample_rate = st->codec->sample_rate;
  691. flv->last_channels = channels = st->codec->channels;
  692. } else {
  693. AVCodecContext ctx;
  694. ctx.sample_rate = sample_rate;
  695. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  696. sample_rate = ctx.sample_rate;
  697. }
  698. }else{
  699. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
  700. }
  701. if (st->codec->codec_id == AV_CODEC_ID_AAC ||
  702. st->codec->codec_id == AV_CODEC_ID_H264) {
  703. int type = avio_r8(s->pb);
  704. size--;
  705. if (st->codec->codec_id == AV_CODEC_ID_H264) {
  706. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  707. pts = dts + cts;
  708. if (cts < 0) { // dts are wrong
  709. flv->wrong_dts = 1;
  710. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  711. }
  712. if (flv->wrong_dts)
  713. dts = AV_NOPTS_VALUE;
  714. }
  715. if (type == 0) {
  716. if (st->codec->extradata) {
  717. if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
  718. return ret;
  719. ret = AVERROR(EAGAIN);
  720. goto leave;
  721. }
  722. if ((ret = flv_get_extradata(s, st, size)) < 0)
  723. return ret;
  724. if (st->codec->codec_id == AV_CODEC_ID_AAC) {
  725. MPEG4AudioConfig cfg;
  726. avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  727. st->codec->extradata_size * 8, 1);
  728. st->codec->channels = cfg.channels;
  729. st->codec->channel_layout = 0;
  730. if (cfg.ext_sample_rate)
  731. st->codec->sample_rate = cfg.ext_sample_rate;
  732. else
  733. st->codec->sample_rate = cfg.sample_rate;
  734. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  735. st->codec->channels, st->codec->sample_rate);
  736. }
  737. ret = AVERROR(EAGAIN);
  738. goto leave;
  739. }
  740. }
  741. /* skip empty data packets */
  742. if (!size) {
  743. ret = AVERROR(EAGAIN);
  744. goto leave;
  745. }
  746. ret= av_get_packet(s->pb, pkt, size);
  747. if (ret < 0) {
  748. return AVERROR(EIO);
  749. }
  750. /* note: we need to modify the packet size here to handle the last
  751. packet */
  752. pkt->size = ret;
  753. pkt->dts = dts;
  754. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  755. pkt->stream_index = st->index;
  756. if (flv->new_extradata[is_audio]) {
  757. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  758. flv->new_extradata_size[is_audio]);
  759. if (side) {
  760. memcpy(side, flv->new_extradata[is_audio],
  761. flv->new_extradata_size[is_audio]);
  762. av_freep(&flv->new_extradata[is_audio]);
  763. flv->new_extradata_size[is_audio] = 0;
  764. }
  765. }
  766. if (is_audio && (sample_rate != flv->last_sample_rate ||
  767. channels != flv->last_channels)) {
  768. flv->last_sample_rate = sample_rate;
  769. flv->last_channels = channels;
  770. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  771. }
  772. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  773. pkt->flags |= AV_PKT_FLAG_KEY;
  774. leave:
  775. avio_skip(s->pb, 4);
  776. return ret;
  777. }
  778. static int flv_read_seek(AVFormatContext *s, int stream_index,
  779. int64_t ts, int flags)
  780. {
  781. FLVContext *flv = s->priv_data;
  782. flv->validate_count = 0;
  783. return avio_seek_time(s->pb, stream_index, ts, flags);
  784. }
  785. #define OFFSET(x) offsetof(FLVContext, x)
  786. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  787. static const AVOption options[] = {
  788. { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD},
  789. { NULL }
  790. };
  791. static const AVClass class = {
  792. .class_name = "flvdec",
  793. .item_name = av_default_item_name,
  794. .option = options,
  795. .version = LIBAVUTIL_VERSION_INT,
  796. };
  797. AVInputFormat ff_flv_demuxer = {
  798. .name = "flv",
  799. .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
  800. .priv_data_size = sizeof(FLVContext),
  801. .read_probe = flv_probe,
  802. .read_header = flv_read_header,
  803. .read_packet = flv_read_packet,
  804. .read_seek = flv_read_seek,
  805. .read_close = flv_read_close,
  806. .extensions = "flv",
  807. .priv_class = &class,
  808. };