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.

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