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.

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