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.

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