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.

906 lines
32KB

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