flvdec.c 18 KB

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