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.

902 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. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  107. case FLV_CODECID_NELLYMOSER:
  108. return acodec->codec_id == CODEC_ID_NELLYMOSER;
  109. case FLV_CODECID_PCM_MULAW:
  110. return acodec->sample_rate == 8000 &&
  111. acodec->codec_id == CODEC_ID_PCM_MULAW;
  112. case FLV_CODECID_PCM_ALAW:
  113. return acodec->sample_rate = 8000 &&
  114. acodec->codec_id == CODEC_ID_PCM_ALAW;
  115. default:
  116. return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  117. }
  118. return 0;
  119. }
  120. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
  121. switch(flv_codecid) {
  122. //no distinction between S16 and S8 PCM codec flags
  123. case FLV_CODECID_PCM:
  124. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
  125. #if HAVE_BIGENDIAN
  126. CODEC_ID_PCM_S16BE;
  127. #else
  128. CODEC_ID_PCM_S16LE;
  129. #endif
  130. break;
  131. case FLV_CODECID_PCM_LE:
  132. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
  133. case FLV_CODECID_AAC : acodec->codec_id = CODEC_ID_AAC; break;
  134. case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break;
  135. case FLV_CODECID_SPEEX:
  136. acodec->codec_id = CODEC_ID_SPEEX;
  137. acodec->sample_rate = 16000;
  138. break;
  139. case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
  140. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  141. acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
  142. acodec->codec_id = CODEC_ID_NELLYMOSER;
  143. break;
  144. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  145. acodec->sample_rate = 16000;
  146. acodec->codec_id = CODEC_ID_NELLYMOSER;
  147. break;
  148. case FLV_CODECID_NELLYMOSER:
  149. acodec->codec_id = CODEC_ID_NELLYMOSER;
  150. break;
  151. case FLV_CODECID_PCM_MULAW:
  152. acodec->sample_rate = 8000;
  153. acodec->codec_id = CODEC_ID_PCM_MULAW;
  154. break;
  155. case FLV_CODECID_PCM_ALAW:
  156. acodec->sample_rate = 8000;
  157. acodec->codec_id = CODEC_ID_PCM_ALAW;
  158. break;
  159. default:
  160. av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  161. acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  162. }
  163. }
  164. static int flv_same_video_codec(AVCodecContext *vcodec, int flags)
  165. {
  166. int flv_codecid = flags & FLV_VIDEO_CODECID_MASK;
  167. if (!vcodec->codec_id && !vcodec->codec_tag)
  168. return 1;
  169. switch (flv_codecid) {
  170. case FLV_CODECID_H263:
  171. return vcodec->codec_id == CODEC_ID_FLV1;
  172. case FLV_CODECID_SCREEN:
  173. return vcodec->codec_id == CODEC_ID_FLASHSV;
  174. case FLV_CODECID_SCREEN2:
  175. return vcodec->codec_id == CODEC_ID_FLASHSV2;
  176. case FLV_CODECID_VP6:
  177. return vcodec->codec_id == CODEC_ID_VP6F;
  178. case FLV_CODECID_VP6A:
  179. return vcodec->codec_id == CODEC_ID_VP6A;
  180. case FLV_CODECID_H264:
  181. return vcodec->codec_id == CODEC_ID_H264;
  182. default:
  183. return vcodec->codec_tag == flv_codecid;
  184. }
  185. return 0;
  186. }
  187. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
  188. AVCodecContext *vcodec = vstream->codec;
  189. switch(flv_codecid) {
  190. case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break;
  191. case FLV_CODECID_REALH263: vcodec->codec_id = CODEC_ID_H263 ; break; // Really mean it this time
  192. case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
  193. case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
  194. case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ;
  195. case FLV_CODECID_VP6A :
  196. if(flv_codecid == FLV_CODECID_VP6A)
  197. vcodec->codec_id = 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 = CODEC_ID_H264;
  206. return 3; // not 4, reading packet type will consume one byte
  207. case FLV_CODECID_MPEG4:
  208. vcodec->codec_id = 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, 2, AVMEDIA_TYPE_DATA);
  365. if (!st)
  366. return AVERROR(ENOMEM);
  367. st->codec->codec_id = 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, 0, AVMEDIA_TYPE_VIDEO))
  457. return AVERROR(ENOMEM);
  458. }
  459. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  460. if(!create_stream(s, 1, 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, 2, AVMEDIA_TYPE_DATA);
  550. if (!st)
  551. goto out;
  552. st->codec->codec_id = 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 && st->codec->codec_type == AVMEDIA_TYPE_AUDIO) {
  634. if (flv_same_audio_codec(st->codec, flags)) {
  635. break;
  636. }
  637. } else
  638. if (stream_type == FLV_STREAM_TYPE_VIDEO && st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  639. if (flv_same_video_codec(st->codec, flags)) {
  640. break;
  641. }
  642. } else if (st->id == stream_type) {
  643. break;
  644. }
  645. }
  646. if(i == s->nb_streams){
  647. av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
  648. st = create_stream(s, stream_type,
  649. (int[]){AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA}[stream_type]);
  650. }
  651. av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
  652. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
  653. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
  654. || st->discard >= AVDISCARD_ALL
  655. ){
  656. avio_seek(s->pb, next, SEEK_SET);
  657. continue;
  658. }
  659. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  660. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  661. break;
  662. }
  663. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  664. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
  665. int size;
  666. const int64_t pos= avio_tell(s->pb);
  667. const int64_t fsize= avio_size(s->pb);
  668. avio_seek(s->pb, fsize-4, SEEK_SET);
  669. size= avio_rb32(s->pb);
  670. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  671. if(size == avio_rb24(s->pb) + 11){
  672. uint32_t ts = avio_rb24(s->pb);
  673. ts |= avio_r8(s->pb) << 24;
  674. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  675. }
  676. avio_seek(s->pb, pos, SEEK_SET);
  677. }
  678. if(stream_type == FLV_STREAM_TYPE_AUDIO){
  679. int bits_per_coded_sample;
  680. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  681. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  682. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  683. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  684. st->codec->channels = channels;
  685. st->codec->sample_rate = sample_rate;
  686. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  687. }
  688. if(!st->codec->codec_id){
  689. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  690. flv->last_sample_rate = sample_rate = st->codec->sample_rate;
  691. flv->last_channels = channels = st->codec->channels;
  692. } else {
  693. AVCodecContext ctx;
  694. ctx.sample_rate = sample_rate;
  695. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  696. sample_rate = ctx.sample_rate;
  697. }
  698. } else if(stream_type == FLV_STREAM_TYPE_VIDEO) {
  699. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  700. }
  701. if (st->codec->codec_id == CODEC_ID_AAC ||
  702. st->codec->codec_id == CODEC_ID_H264 ||
  703. st->codec->codec_id == CODEC_ID_MPEG4) {
  704. int type = avio_r8(s->pb);
  705. size--;
  706. if (st->codec->codec_id == CODEC_ID_H264 || st->codec->codec_id == CODEC_ID_MPEG4) {
  707. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  708. pts = dts + cts;
  709. if (cts < 0) { // dts are wrong
  710. flv->wrong_dts = 1;
  711. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  712. }
  713. if (flv->wrong_dts)
  714. dts = AV_NOPTS_VALUE;
  715. }
  716. if (type == 0 && (!st->codec->extradata || st->codec->codec_id == CODEC_ID_AAC)) {
  717. if (st->codec->extradata) {
  718. if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
  719. return ret;
  720. ret = AVERROR(EAGAIN);
  721. goto leave;
  722. }
  723. if ((ret = flv_get_extradata(s, st, size)) < 0)
  724. return ret;
  725. if (st->codec->codec_id == CODEC_ID_AAC) {
  726. MPEG4AudioConfig cfg;
  727. if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  728. st->codec->extradata_size * 8, 1) >= 0) {
  729. st->codec->channels = cfg.channels;
  730. if (cfg.ext_sample_rate)
  731. st->codec->sample_rate = cfg.ext_sample_rate;
  732. else
  733. st->codec->sample_rate = cfg.sample_rate;
  734. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  735. st->codec->channels, st->codec->sample_rate);
  736. }
  737. }
  738. ret = AVERROR(EAGAIN);
  739. goto leave;
  740. }
  741. }
  742. /* skip empty data packets */
  743. if (!size) {
  744. ret = AVERROR(EAGAIN);
  745. goto leave;
  746. }
  747. ret= av_get_packet(s->pb, pkt, size);
  748. if (ret < 0)
  749. return ret;
  750. pkt->dts = dts;
  751. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  752. pkt->stream_index = st->index;
  753. if (flv->new_extradata[stream_type]) {
  754. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  755. flv->new_extradata_size[stream_type]);
  756. if (side) {
  757. memcpy(side, flv->new_extradata[stream_type],
  758. flv->new_extradata_size[stream_type]);
  759. av_freep(&flv->new_extradata[stream_type]);
  760. flv->new_extradata_size[stream_type] = 0;
  761. }
  762. }
  763. if (stream_type == FLV_STREAM_TYPE_AUDIO && (sample_rate != flv->last_sample_rate ||
  764. channels != flv->last_channels)) {
  765. flv->last_sample_rate = sample_rate;
  766. flv->last_channels = channels;
  767. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  768. }
  769. if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
  770. ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
  771. stream_type == FLV_STREAM_TYPE_DATA)
  772. pkt->flags |= AV_PKT_FLAG_KEY;
  773. leave:
  774. avio_skip(s->pb, 4);
  775. return ret;
  776. }
  777. static int flv_read_seek(AVFormatContext *s, int stream_index,
  778. int64_t ts, int flags)
  779. {
  780. FLVContext *flv = s->priv_data;
  781. flv->validate_count = 0;
  782. return avio_seek_time(s->pb, stream_index, ts, flags);
  783. }
  784. #define OFFSET(x) offsetof(FLVContext, x)
  785. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  786. static const AVOption options[] = {
  787. { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { 0 }, 0, 1, VD},
  788. { NULL }
  789. };
  790. static const AVClass class = {
  791. .class_name = "flvdec",
  792. .item_name = av_default_item_name,
  793. .option = options,
  794. .version = LIBAVUTIL_VERSION_INT,
  795. };
  796. AVInputFormat ff_flv_demuxer = {
  797. .name = "flv",
  798. .long_name = NULL_IF_CONFIG_SMALL("FLV format"),
  799. .priv_data_size = sizeof(FLVContext),
  800. .read_probe = flv_probe,
  801. .read_header = flv_read_header,
  802. .read_packet = flv_read_packet,
  803. .read_seek = flv_read_seek,
  804. .read_close = flv_read_close,
  805. .extensions = "flv",
  806. .priv_class = &class,
  807. };