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.

918 lines
33KB

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