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.

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