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.

506 lines
19KB

  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 "libavcodec/bytestream.h"
  27. #include "libavcodec/mpeg4audio.h"
  28. #include "avformat.h"
  29. #include "flv.h"
  30. typedef struct {
  31. int wrong_dts; ///< wrong dts due to negative cts
  32. } FLVContext;
  33. static int flv_probe(AVProbeData *p)
  34. {
  35. const uint8_t *d;
  36. d = p->buf;
  37. if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0) {
  38. return AVPROBE_SCORE_MAX;
  39. }
  40. return 0;
  41. }
  42. /**
  43. * Builds a Speex header.
  44. * This is not needed for the libavcodec libspeex decoder, but is needed for
  45. * stream copy and for decoders which require a header.
  46. */
  47. static void flv_build_speex_header(uint8_t *extradata)
  48. {
  49. memset(extradata, 0, 80);
  50. bytestream_put_buffer(&extradata, "Speex ", 8); // speex_string
  51. bytestream_put_buffer(&extradata, "1.2rc1", 6); // speex_version
  52. extradata += 14; // speex_version padding
  53. bytestream_put_le32(&extradata, 1); // speex_version_id
  54. bytestream_put_le32(&extradata, 80); // header_size
  55. bytestream_put_le32(&extradata, 16000); // rate
  56. bytestream_put_le32(&extradata, 1); // mode
  57. bytestream_put_le32(&extradata, 4); // mode_bitstream_version
  58. bytestream_put_le32(&extradata, 1); // nb_channels
  59. bytestream_put_le32(&extradata, -1); // bitrate
  60. bytestream_put_le32(&extradata, 320); // frame_size
  61. // vbr = 0
  62. // frames_per_packet = 0
  63. // extra_headers = 0
  64. // reserved1 = 0
  65. // reserved2 = 0
  66. }
  67. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, int flv_codecid) {
  68. AVCodecContext *acodec = astream->codec;
  69. switch(flv_codecid) {
  70. //no distinction between S16 and S8 PCM codec flags
  71. case FLV_CODECID_PCM:
  72. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_S8 :
  73. #ifdef WORDS_BIGENDIAN
  74. CODEC_ID_PCM_S16BE;
  75. #else
  76. CODEC_ID_PCM_S16LE;
  77. #endif
  78. break;
  79. case FLV_CODECID_PCM_LE:
  80. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_S8 : CODEC_ID_PCM_S16LE; break;
  81. case FLV_CODECID_AAC : acodec->codec_id = CODEC_ID_AAC; break;
  82. case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break;
  83. case FLV_CODECID_SPEEX:
  84. acodec->codec_id = CODEC_ID_SPEEX;
  85. acodec->sample_rate = 16000;
  86. acodec->extradata = av_mallocz(80 + FF_INPUT_BUFFER_PADDING_SIZE);
  87. if (acodec->extradata) {
  88. acodec->extradata_size = 80;
  89. flv_build_speex_header(acodec->extradata);
  90. } else {
  91. av_log(s, AV_LOG_WARNING, "Unable to create Speex extradata\n");
  92. }
  93. break;
  94. case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
  95. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  96. acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
  97. case FLV_CODECID_NELLYMOSER:
  98. acodec->codec_id = CODEC_ID_NELLYMOSER;
  99. break;
  100. default:
  101. av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  102. acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  103. }
  104. }
  105. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
  106. AVCodecContext *vcodec = vstream->codec;
  107. switch(flv_codecid) {
  108. case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break;
  109. case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
  110. case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ;
  111. case FLV_CODECID_VP6A :
  112. if(flv_codecid == FLV_CODECID_VP6A)
  113. vcodec->codec_id = CODEC_ID_VP6A;
  114. if(vcodec->extradata_size != 1) {
  115. vcodec->extradata_size = 1;
  116. vcodec->extradata = av_malloc(1);
  117. }
  118. vcodec->extradata[0] = get_byte(s->pb);
  119. return 1; // 1 byte body size adjustment for flv_read_packet()
  120. case FLV_CODECID_H264:
  121. vcodec->codec_id = CODEC_ID_H264;
  122. return 3; // not 4, reading packet type will consume one byte
  123. default:
  124. av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
  125. vcodec->codec_tag = flv_codecid;
  126. }
  127. return 0;
  128. }
  129. static int amf_get_string(ByteIOContext *ioc, char *buffer, int buffsize) {
  130. int length = get_be16(ioc);
  131. if(length >= buffsize) {
  132. url_fskip(ioc, length);
  133. return -1;
  134. }
  135. get_buffer(ioc, buffer, length);
  136. buffer[length] = '\0';
  137. return length;
  138. }
  139. static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
  140. AVCodecContext *acodec, *vcodec;
  141. ByteIOContext *ioc;
  142. AMFDataType amf_type;
  143. char str_val[256];
  144. double num_val;
  145. num_val = 0;
  146. ioc = s->pb;
  147. amf_type = get_byte(ioc);
  148. switch(amf_type) {
  149. case AMF_DATA_TYPE_NUMBER:
  150. num_val = av_int2dbl(get_be64(ioc)); break;
  151. case AMF_DATA_TYPE_BOOL:
  152. num_val = get_byte(ioc); break;
  153. case AMF_DATA_TYPE_STRING:
  154. if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
  155. return -1;
  156. break;
  157. case AMF_DATA_TYPE_OBJECT: {
  158. unsigned int keylen;
  159. while(url_ftell(ioc) < max_pos - 2 && (keylen = get_be16(ioc))) {
  160. url_fskip(ioc, keylen); //skip key string
  161. if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
  162. return -1; //if we couldn't skip, bomb out.
  163. }
  164. if(get_byte(ioc) != AMF_END_OF_OBJECT)
  165. return -1;
  166. }
  167. break;
  168. case AMF_DATA_TYPE_NULL:
  169. case AMF_DATA_TYPE_UNDEFINED:
  170. case AMF_DATA_TYPE_UNSUPPORTED:
  171. break; //these take up no additional space
  172. case AMF_DATA_TYPE_MIXEDARRAY:
  173. url_fskip(ioc, 4); //skip 32-bit max array index
  174. while(url_ftell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  175. //this is the only case in which we would want a nested parse to not skip over the object
  176. if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  177. return -1;
  178. }
  179. if(get_byte(ioc) != AMF_END_OF_OBJECT)
  180. return -1;
  181. break;
  182. case AMF_DATA_TYPE_ARRAY: {
  183. unsigned int arraylen, i;
  184. arraylen = get_be32(ioc);
  185. for(i = 0; i < arraylen && url_ftell(ioc) < max_pos - 1; i++) {
  186. if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
  187. return -1; //if we couldn't skip, bomb out.
  188. }
  189. }
  190. break;
  191. case AMF_DATA_TYPE_DATE:
  192. url_fskip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
  193. break;
  194. default: //unsupported type, we couldn't skip
  195. return -1;
  196. }
  197. if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
  198. acodec = astream ? astream->codec : NULL;
  199. vcodec = vstream ? vstream->codec : NULL;
  200. if(amf_type == AMF_DATA_TYPE_BOOL) {
  201. if(!strcmp(key, "stereo") && acodec) acodec->channels = num_val > 0 ? 2 : 1;
  202. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  203. if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
  204. // else if(!strcmp(key, "width") && vcodec && num_val > 0) vcodec->width = num_val;
  205. // else if(!strcmp(key, "height") && vcodec && num_val > 0) vcodec->height = num_val;
  206. else if(!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
  207. vcodec->bit_rate = num_val * 1024.0;
  208. else if(!strcmp(key, "audiocodecid") && acodec && 0 <= (int)num_val)
  209. flv_set_audio_codec(s, astream, (int)num_val << FLV_AUDIO_CODECID_OFFSET);
  210. else if(!strcmp(key, "videocodecid") && vcodec && 0 <= (int)num_val)
  211. flv_set_video_codec(s, vstream, (int)num_val);
  212. else if(!strcmp(key, "audiosamplesize") && acodec && 0 < (int)num_val) {
  213. acodec->bits_per_coded_sample = num_val;
  214. //we may have to rewrite a previously read codecid because FLV only marks PCM endianness.
  215. if(num_val == 8 && (acodec->codec_id == CODEC_ID_PCM_S16BE || acodec->codec_id == CODEC_ID_PCM_S16LE))
  216. acodec->codec_id = CODEC_ID_PCM_S8;
  217. }
  218. else if(!strcmp(key, "audiosamplerate") && acodec && num_val >= 0) {
  219. //some tools, like FLVTool2, write consistently approximate metadata sample rates
  220. if (!acodec->sample_rate) {
  221. switch((int)num_val) {
  222. case 44000: acodec->sample_rate = 44100 ; break;
  223. case 22000: acodec->sample_rate = 22050 ; break;
  224. case 11000: acodec->sample_rate = 11025 ; break;
  225. case 5000 : acodec->sample_rate = 5512 ; break;
  226. default : acodec->sample_rate = num_val;
  227. }
  228. }
  229. }
  230. }
  231. }
  232. return 0;
  233. }
  234. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  235. AMFDataType type;
  236. AVStream *stream, *astream, *vstream;
  237. ByteIOContext *ioc;
  238. int i;
  239. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  240. astream = NULL;
  241. vstream = NULL;
  242. ioc = s->pb;
  243. //first object needs to be "onMetaData" string
  244. type = get_byte(ioc);
  245. if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
  246. return -1;
  247. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  248. for(i = 0; i < s->nb_streams; i++) {
  249. stream = s->streams[i];
  250. if (stream->codec->codec_type == CODEC_TYPE_AUDIO) astream = stream;
  251. else if(stream->codec->codec_type == CODEC_TYPE_VIDEO) vstream = stream;
  252. }
  253. //parse the second object (we want a mixed array)
  254. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  255. return -1;
  256. return 0;
  257. }
  258. static AVStream *create_stream(AVFormatContext *s, int is_audio){
  259. AVStream *st = av_new_stream(s, is_audio);
  260. if (!st)
  261. return NULL;
  262. st->codec->codec_type = is_audio ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
  263. av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  264. return st;
  265. }
  266. static int flv_read_header(AVFormatContext *s,
  267. AVFormatParameters *ap)
  268. {
  269. int offset, flags;
  270. url_fskip(s->pb, 4);
  271. flags = get_byte(s->pb);
  272. /* old flvtool cleared this field */
  273. /* FIXME: better fix needed */
  274. if (!flags) {
  275. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  276. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  277. }
  278. if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  279. != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  280. s->ctx_flags |= AVFMTCTX_NOHEADER;
  281. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  282. if(!create_stream(s, 0))
  283. return AVERROR(ENOMEM);
  284. }
  285. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  286. if(!create_stream(s, 1))
  287. return AVERROR(ENOMEM);
  288. }
  289. offset = get_be32(s->pb);
  290. url_fseek(s->pb, offset, SEEK_SET);
  291. s->start_time = 0;
  292. return 0;
  293. }
  294. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  295. {
  296. av_free(st->codec->extradata);
  297. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  298. if (!st->codec->extradata)
  299. return AVERROR(ENOMEM);
  300. st->codec->extradata_size = size;
  301. get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
  302. return 0;
  303. }
  304. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  305. {
  306. FLVContext *flv = s->priv_data;
  307. int ret, i, type, size, flags, is_audio;
  308. int64_t next, pos;
  309. int64_t dts, pts = AV_NOPTS_VALUE;
  310. AVStream *st = NULL;
  311. for(;;){
  312. pos = url_ftell(s->pb);
  313. url_fskip(s->pb, 4); /* size of previous packet */
  314. type = get_byte(s->pb);
  315. size = get_be24(s->pb);
  316. dts = get_be24(s->pb);
  317. dts |= get_byte(s->pb) << 24;
  318. // av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
  319. if (url_feof(s->pb))
  320. return AVERROR_EOF;
  321. url_fskip(s->pb, 3); /* stream id, always 0 */
  322. flags = 0;
  323. if(size == 0)
  324. continue;
  325. next= size + url_ftell(s->pb);
  326. if (type == FLV_TAG_TYPE_AUDIO) {
  327. is_audio=1;
  328. flags = get_byte(s->pb);
  329. size--;
  330. } else if (type == FLV_TAG_TYPE_VIDEO) {
  331. is_audio=0;
  332. flags = get_byte(s->pb);
  333. size--;
  334. if ((flags & 0xf0) == 0x50) /* video info / command frame */
  335. goto skip;
  336. } else {
  337. if (type == FLV_TAG_TYPE_META && size > 13+1+4 && 0)
  338. flv_read_metabody(s, next);
  339. else /* skip packet */
  340. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  341. skip:
  342. url_fseek(s->pb, next, SEEK_SET);
  343. continue;
  344. }
  345. /* skip empty data packets */
  346. if (!size)
  347. continue;
  348. /* now find stream */
  349. for(i=0;i<s->nb_streams;i++) {
  350. st = s->streams[i];
  351. if (st->id == is_audio)
  352. break;
  353. }
  354. if(i == s->nb_streams){
  355. av_log(s, AV_LOG_ERROR, "invalid stream\n");
  356. st= create_stream(s, is_audio);
  357. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  358. }
  359. // av_log(s, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
  360. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  361. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  362. || st->discard >= AVDISCARD_ALL
  363. ){
  364. url_fseek(s->pb, next, SEEK_SET);
  365. continue;
  366. }
  367. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  368. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  369. break;
  370. }
  371. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  372. if(!url_is_streamed(s->pb) && s->duration==AV_NOPTS_VALUE){
  373. int size;
  374. const int64_t pos= url_ftell(s->pb);
  375. const int64_t fsize= url_fsize(s->pb);
  376. url_fseek(s->pb, fsize-4, SEEK_SET);
  377. size= get_be32(s->pb);
  378. url_fseek(s->pb, fsize-3-size, SEEK_SET);
  379. if(size == get_be24(s->pb) + 11){
  380. s->duration= get_be24(s->pb) * (int64_t)AV_TIME_BASE / 1000;
  381. }
  382. url_fseek(s->pb, pos, SEEK_SET);
  383. }
  384. if(is_audio){
  385. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  386. st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  387. st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  388. st->codec->bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  389. }
  390. if(!st->codec->codec_id){
  391. flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
  392. }
  393. }else{
  394. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  395. }
  396. if (st->codec->codec_id == CODEC_ID_AAC ||
  397. st->codec->codec_id == CODEC_ID_H264) {
  398. int type = get_byte(s->pb);
  399. size--;
  400. if (st->codec->codec_id == CODEC_ID_H264) {
  401. int32_t cts = (get_be24(s->pb)+0xff800000)^0xff800000; // sign extension
  402. pts = dts + cts;
  403. if (cts < 0) { // dts are wrong
  404. flv->wrong_dts = 1;
  405. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  406. }
  407. if (flv->wrong_dts)
  408. dts = AV_NOPTS_VALUE;
  409. }
  410. if (type == 0) {
  411. if ((ret = flv_get_extradata(s, st, size)) < 0)
  412. return ret;
  413. if (st->codec->codec_id == CODEC_ID_AAC) {
  414. MPEG4AudioConfig cfg;
  415. ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
  416. st->codec->extradata_size);
  417. if (cfg.chan_config > 7)
  418. return -1;
  419. st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
  420. st->codec->sample_rate = cfg.sample_rate;
  421. dprintf(s, "mp4a config channels %d sample rate %d\n",
  422. st->codec->channels, st->codec->sample_rate);
  423. }
  424. return AVERROR(EAGAIN);
  425. }
  426. }
  427. /* skip empty data packets */
  428. if (!size)
  429. return AVERROR(EAGAIN);
  430. ret= av_get_packet(s->pb, pkt, size);
  431. if (ret < 0) {
  432. return AVERROR(EIO);
  433. }
  434. /* note: we need to modify the packet size here to handle the last
  435. packet */
  436. pkt->size = ret;
  437. pkt->dts = dts;
  438. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  439. pkt->stream_index = st->index;
  440. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  441. pkt->flags |= PKT_FLAG_KEY;
  442. return ret;
  443. }
  444. AVInputFormat flv_demuxer = {
  445. "flv",
  446. NULL_IF_CONFIG_SMALL("FLV format"),
  447. sizeof(FLVContext),
  448. flv_probe,
  449. flv_read_header,
  450. flv_read_packet,
  451. .extensions = "flv",
  452. .value = CODEC_ID_FLV1,
  453. };