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.

481 lines
17KB

  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. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  202. if(!strcmp(key, "duration")) s->duration = num_val * AV_TIME_BASE;
  203. else if(!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
  204. vcodec->bit_rate = num_val * 1024.0;
  205. }
  206. }
  207. return 0;
  208. }
  209. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  210. AMFDataType type;
  211. AVStream *stream, *astream, *vstream;
  212. ByteIOContext *ioc;
  213. int i;
  214. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  215. astream = NULL;
  216. vstream = NULL;
  217. ioc = s->pb;
  218. //first object needs to be "onMetaData" string
  219. type = get_byte(ioc);
  220. if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
  221. return -1;
  222. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  223. for(i = 0; i < s->nb_streams; i++) {
  224. stream = s->streams[i];
  225. if (stream->codec->codec_type == CODEC_TYPE_AUDIO) astream = stream;
  226. else if(stream->codec->codec_type == CODEC_TYPE_VIDEO) vstream = stream;
  227. }
  228. //parse the second object (we want a mixed array)
  229. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  230. return -1;
  231. return 0;
  232. }
  233. static AVStream *create_stream(AVFormatContext *s, int is_audio){
  234. AVStream *st = av_new_stream(s, is_audio);
  235. if (!st)
  236. return NULL;
  237. st->codec->codec_type = is_audio ? CODEC_TYPE_AUDIO : CODEC_TYPE_VIDEO;
  238. av_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  239. return st;
  240. }
  241. static int flv_read_header(AVFormatContext *s,
  242. AVFormatParameters *ap)
  243. {
  244. int offset, flags;
  245. url_fskip(s->pb, 4);
  246. flags = get_byte(s->pb);
  247. /* old flvtool cleared this field */
  248. /* FIXME: better fix needed */
  249. if (!flags) {
  250. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  251. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  252. }
  253. if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  254. != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  255. s->ctx_flags |= AVFMTCTX_NOHEADER;
  256. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  257. if(!create_stream(s, 0))
  258. return AVERROR(ENOMEM);
  259. }
  260. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  261. if(!create_stream(s, 1))
  262. return AVERROR(ENOMEM);
  263. }
  264. offset = get_be32(s->pb);
  265. url_fseek(s->pb, offset, SEEK_SET);
  266. s->start_time = 0;
  267. return 0;
  268. }
  269. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  270. {
  271. av_free(st->codec->extradata);
  272. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  273. if (!st->codec->extradata)
  274. return AVERROR(ENOMEM);
  275. st->codec->extradata_size = size;
  276. get_buffer(s->pb, st->codec->extradata, st->codec->extradata_size);
  277. return 0;
  278. }
  279. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  280. {
  281. FLVContext *flv = s->priv_data;
  282. int ret, i, type, size, flags, is_audio;
  283. int64_t next, pos;
  284. int64_t dts, pts = AV_NOPTS_VALUE;
  285. AVStream *st = NULL;
  286. for(;;){
  287. pos = url_ftell(s->pb);
  288. url_fskip(s->pb, 4); /* size of previous packet */
  289. type = get_byte(s->pb);
  290. size = get_be24(s->pb);
  291. dts = get_be24(s->pb);
  292. dts |= get_byte(s->pb) << 24;
  293. // av_log(s, AV_LOG_DEBUG, "type:%d, size:%d, dts:%d\n", type, size, dts);
  294. if (url_feof(s->pb))
  295. return AVERROR_EOF;
  296. url_fskip(s->pb, 3); /* stream id, always 0 */
  297. flags = 0;
  298. if(size == 0)
  299. continue;
  300. next= size + url_ftell(s->pb);
  301. if (type == FLV_TAG_TYPE_AUDIO) {
  302. is_audio=1;
  303. flags = get_byte(s->pb);
  304. size--;
  305. } else if (type == FLV_TAG_TYPE_VIDEO) {
  306. is_audio=0;
  307. flags = get_byte(s->pb);
  308. size--;
  309. if ((flags & 0xf0) == 0x50) /* video info / command frame */
  310. goto skip;
  311. } else {
  312. if (type == FLV_TAG_TYPE_META && size > 13+1+4)
  313. flv_read_metabody(s, next);
  314. else /* skip packet */
  315. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  316. skip:
  317. url_fseek(s->pb, next, SEEK_SET);
  318. continue;
  319. }
  320. /* skip empty data packets */
  321. if (!size)
  322. continue;
  323. /* now find stream */
  324. for(i=0;i<s->nb_streams;i++) {
  325. st = s->streams[i];
  326. if (st->id == is_audio)
  327. break;
  328. }
  329. if(i == s->nb_streams){
  330. av_log(s, AV_LOG_ERROR, "invalid stream\n");
  331. st= create_stream(s, is_audio);
  332. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  333. }
  334. // av_log(s, AV_LOG_DEBUG, "%d %X %d \n", is_audio, flags, st->discard);
  335. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  336. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  337. || st->discard >= AVDISCARD_ALL
  338. ){
  339. url_fseek(s->pb, next, SEEK_SET);
  340. continue;
  341. }
  342. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  343. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  344. break;
  345. }
  346. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  347. if(!url_is_streamed(s->pb) && s->duration==AV_NOPTS_VALUE){
  348. int size;
  349. const int64_t pos= url_ftell(s->pb);
  350. const int64_t fsize= url_fsize(s->pb);
  351. url_fseek(s->pb, fsize-4, SEEK_SET);
  352. size= get_be32(s->pb);
  353. url_fseek(s->pb, fsize-3-size, SEEK_SET);
  354. if(size == get_be24(s->pb) + 11){
  355. s->duration= get_be24(s->pb) * (int64_t)AV_TIME_BASE / 1000;
  356. }
  357. url_fseek(s->pb, pos, SEEK_SET);
  358. }
  359. if(is_audio){
  360. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  361. st->codec->channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  362. st->codec->sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  363. st->codec->bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  364. }
  365. if(!st->codec->codec_id){
  366. flv_set_audio_codec(s, st, flags & FLV_AUDIO_CODECID_MASK);
  367. }
  368. }else{
  369. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  370. }
  371. if (st->codec->codec_id == CODEC_ID_AAC ||
  372. st->codec->codec_id == CODEC_ID_H264) {
  373. int type = get_byte(s->pb);
  374. size--;
  375. if (st->codec->codec_id == CODEC_ID_H264) {
  376. int32_t cts = (get_be24(s->pb)+0xff800000)^0xff800000; // sign extension
  377. pts = dts + cts;
  378. if (cts < 0) { // dts are wrong
  379. flv->wrong_dts = 1;
  380. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  381. }
  382. if (flv->wrong_dts)
  383. dts = AV_NOPTS_VALUE;
  384. }
  385. if (type == 0) {
  386. if ((ret = flv_get_extradata(s, st, size)) < 0)
  387. return ret;
  388. if (st->codec->codec_id == CODEC_ID_AAC) {
  389. MPEG4AudioConfig cfg;
  390. ff_mpeg4audio_get_config(&cfg, st->codec->extradata,
  391. st->codec->extradata_size);
  392. if (cfg.chan_config > 7)
  393. return -1;
  394. st->codec->channels = ff_mpeg4audio_channels[cfg.chan_config];
  395. st->codec->sample_rate = cfg.sample_rate;
  396. dprintf(s, "mp4a config channels %d sample rate %d\n",
  397. st->codec->channels, st->codec->sample_rate);
  398. }
  399. return AVERROR(EAGAIN);
  400. }
  401. }
  402. /* skip empty data packets */
  403. if (!size)
  404. return AVERROR(EAGAIN);
  405. ret= av_get_packet(s->pb, pkt, size);
  406. if (ret < 0) {
  407. return AVERROR(EIO);
  408. }
  409. /* note: we need to modify the packet size here to handle the last
  410. packet */
  411. pkt->size = ret;
  412. pkt->dts = dts;
  413. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  414. pkt->stream_index = st->index;
  415. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  416. pkt->flags |= PKT_FLAG_KEY;
  417. return ret;
  418. }
  419. AVInputFormat flv_demuxer = {
  420. "flv",
  421. NULL_IF_CONFIG_SMALL("FLV format"),
  422. sizeof(FLVContext),
  423. flv_probe,
  424. flv_read_header,
  425. flv_read_packet,
  426. .extensions = "flv",
  427. .value = CODEC_ID_FLV1,
  428. };