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.

487 lines
18KB

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