flvdec.c 16 KB

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