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.

903 lines
32KB

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