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.

729 lines
26KB

  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 "libavutil/dict.h"
  28. #include "libavutil/intfloat.h"
  29. #include "libavutil/mathematics.h"
  30. #include "libavcodec/bytestream.h"
  31. #include "libavcodec/mpeg4audio.h"
  32. #include "avformat.h"
  33. #include "internal.h"
  34. #include "avio_internal.h"
  35. #include "flv.h"
  36. #define KEYFRAMES_TAG "keyframes"
  37. #define KEYFRAMES_TIMESTAMP_TAG "times"
  38. #define KEYFRAMES_BYTEOFFSET_TAG "filepositions"
  39. #define VALIDATE_INDEX_TS_THRESH 2500
  40. typedef struct {
  41. int wrong_dts; ///< wrong dts due to negative cts
  42. uint8_t *new_extradata[2];
  43. int new_extradata_size[2];
  44. int last_sample_rate;
  45. int last_channels;
  46. struct {
  47. int64_t dts;
  48. int64_t pos;
  49. } validate_index[2];
  50. int validate_next;
  51. int validate_count;
  52. } FLVContext;
  53. static int flv_probe(AVProbeData *p)
  54. {
  55. const uint8_t *d;
  56. d = p->buf;
  57. if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
  58. return AVPROBE_SCORE_MAX;
  59. }
  60. return 0;
  61. }
  62. static void flv_set_audio_codec(AVFormatContext *s, AVStream *astream, AVCodecContext *acodec, int flv_codecid) {
  63. switch(flv_codecid) {
  64. //no distinction between S16 and S8 PCM codec flags
  65. case FLV_CODECID_PCM:
  66. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 :
  67. #if HAVE_BIGENDIAN
  68. CODEC_ID_PCM_S16BE;
  69. #else
  70. CODEC_ID_PCM_S16LE;
  71. #endif
  72. break;
  73. case FLV_CODECID_PCM_LE:
  74. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? CODEC_ID_PCM_U8 : CODEC_ID_PCM_S16LE; break;
  75. case FLV_CODECID_AAC : acodec->codec_id = CODEC_ID_AAC; break;
  76. case FLV_CODECID_ADPCM: acodec->codec_id = CODEC_ID_ADPCM_SWF; break;
  77. case FLV_CODECID_SPEEX:
  78. acodec->codec_id = CODEC_ID_SPEEX;
  79. acodec->sample_rate = 16000;
  80. break;
  81. case FLV_CODECID_MP3 : acodec->codec_id = CODEC_ID_MP3 ; astream->need_parsing = AVSTREAM_PARSE_FULL; break;
  82. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  83. acodec->sample_rate = 8000; //in case metadata does not otherwise declare samplerate
  84. acodec->codec_id = CODEC_ID_NELLYMOSER;
  85. break;
  86. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  87. acodec->sample_rate = 16000;
  88. acodec->codec_id = CODEC_ID_NELLYMOSER;
  89. break;
  90. case FLV_CODECID_NELLYMOSER:
  91. acodec->codec_id = CODEC_ID_NELLYMOSER;
  92. break;
  93. default:
  94. av_log(s, AV_LOG_INFO, "Unsupported audio codec (%x)\n", flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  95. acodec->codec_tag = flv_codecid >> FLV_AUDIO_CODECID_OFFSET;
  96. }
  97. }
  98. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid) {
  99. AVCodecContext *vcodec = vstream->codec;
  100. switch(flv_codecid) {
  101. case FLV_CODECID_H263 : vcodec->codec_id = CODEC_ID_FLV1 ; break;
  102. case FLV_CODECID_SCREEN: vcodec->codec_id = CODEC_ID_FLASHSV; break;
  103. case FLV_CODECID_SCREEN2: vcodec->codec_id = CODEC_ID_FLASHSV2; break;
  104. case FLV_CODECID_VP6 : vcodec->codec_id = CODEC_ID_VP6F ;
  105. case FLV_CODECID_VP6A :
  106. if(flv_codecid == FLV_CODECID_VP6A)
  107. vcodec->codec_id = CODEC_ID_VP6A;
  108. if(vcodec->extradata_size != 1) {
  109. vcodec->extradata_size = 1;
  110. vcodec->extradata = av_malloc(1);
  111. }
  112. vcodec->extradata[0] = avio_r8(s->pb);
  113. return 1; // 1 byte body size adjustment for flv_read_packet()
  114. case FLV_CODECID_H264:
  115. vcodec->codec_id = CODEC_ID_H264;
  116. return 3; // not 4, reading packet type will consume one byte
  117. default:
  118. av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
  119. vcodec->codec_tag = flv_codecid;
  120. }
  121. return 0;
  122. }
  123. static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
  124. int length = avio_rb16(ioc);
  125. if(length >= buffsize) {
  126. avio_skip(ioc, length);
  127. return -1;
  128. }
  129. avio_read(ioc, buffer, length);
  130. buffer[length] = '\0';
  131. return length;
  132. }
  133. static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
  134. FLVContext *flv = s->priv_data;
  135. unsigned int arraylen = 0, timeslen = 0, fileposlen = 0, i;
  136. double num_val;
  137. char str_val[256];
  138. int64_t *times = NULL;
  139. int64_t *filepositions = NULL;
  140. int ret = AVERROR(ENOSYS);
  141. int64_t initial_pos = avio_tell(ioc);
  142. AVDictionaryEntry *creator = av_dict_get(s->metadata, "metadatacreator",
  143. NULL, 0);
  144. if (creator && !strcmp(creator->value, "MEGA")) {
  145. /* Files with this metadatacreator tag seem to have filepositions
  146. * pointing at the 4 trailer bytes of the previous packet,
  147. * which isn't the norm (nor what we expect here, nor what
  148. * jwplayer + lighttpd expect, nor what flvtool2 produces).
  149. * Just ignore the index in this case, instead of risking trying
  150. * to adjust it to something that might or might not work. */
  151. return 0;
  152. }
  153. if (s->flags & AVFMT_FLAG_IGNIDX)
  154. return 0;
  155. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  156. int64_t* current_array;
  157. // Expect array object in context
  158. if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
  159. break;
  160. arraylen = avio_rb32(ioc);
  161. if (arraylen >> 28)
  162. break;
  163. /*
  164. * Expect only 'times' or 'filepositions' sub-arrays in other case refuse to use such metadata
  165. * for indexing
  166. */
  167. if (!strcmp(KEYFRAMES_TIMESTAMP_TAG, str_val) && !times) {
  168. if (!(times = av_mallocz(sizeof(*times) * arraylen))) {
  169. ret = AVERROR(ENOMEM);
  170. goto finish;
  171. }
  172. timeslen = arraylen;
  173. current_array = times;
  174. } else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions) {
  175. if (!(filepositions = av_mallocz(sizeof(*filepositions) * arraylen))) {
  176. ret = AVERROR(ENOMEM);
  177. goto finish;
  178. }
  179. fileposlen = arraylen;
  180. current_array = filepositions;
  181. } else // unexpected metatag inside keyframes, will not use such metadata for indexing
  182. break;
  183. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  184. if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
  185. goto finish;
  186. num_val = av_int2double(avio_rb64(ioc));
  187. current_array[i] = num_val;
  188. }
  189. if (times && filepositions) {
  190. // All done, exiting at a position allowing amf_parse_object
  191. // to finish parsing the object
  192. ret = 0;
  193. break;
  194. }
  195. }
  196. if (!ret && timeslen == fileposlen) {
  197. for (i = 0; i < fileposlen; i++) {
  198. av_add_index_entry(vstream, filepositions[i], times[i]*1000,
  199. 0, 0, AVINDEX_KEYFRAME);
  200. if (i < 2) {
  201. flv->validate_index[i].pos = filepositions[i];
  202. flv->validate_index[i].dts = times[i] * 1000;
  203. flv->validate_count = i + 1;
  204. }
  205. }
  206. } else
  207. av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
  208. finish:
  209. av_freep(&times);
  210. av_freep(&filepositions);
  211. // If we got unexpected data, but successfully reset back to
  212. // the start pos, the caller can continue parsing
  213. if (ret < 0 && avio_seek(ioc, initial_pos, SEEK_SET) > 0)
  214. return 0;
  215. return ret;
  216. }
  217. static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
  218. AVCodecContext *acodec, *vcodec;
  219. AVIOContext *ioc;
  220. AMFDataType amf_type;
  221. char str_val[256];
  222. double num_val;
  223. num_val = 0;
  224. ioc = s->pb;
  225. amf_type = avio_r8(ioc);
  226. switch(amf_type) {
  227. case AMF_DATA_TYPE_NUMBER:
  228. num_val = av_int2double(avio_rb64(ioc)); break;
  229. case AMF_DATA_TYPE_BOOL:
  230. num_val = avio_r8(ioc); break;
  231. case AMF_DATA_TYPE_STRING:
  232. if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
  233. return -1;
  234. break;
  235. case AMF_DATA_TYPE_OBJECT:
  236. if ((vstream || astream) && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
  237. if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
  238. max_pos) < 0)
  239. return -1;
  240. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  241. if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  242. return -1; //if we couldn't skip, bomb out.
  243. }
  244. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  245. return -1;
  246. break;
  247. case AMF_DATA_TYPE_NULL:
  248. case AMF_DATA_TYPE_UNDEFINED:
  249. case AMF_DATA_TYPE_UNSUPPORTED:
  250. break; //these take up no additional space
  251. case AMF_DATA_TYPE_MIXEDARRAY:
  252. avio_skip(ioc, 4); //skip 32-bit max array index
  253. while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  254. //this is the only case in which we would want a nested parse to not skip over the object
  255. if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  256. return -1;
  257. }
  258. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  259. return -1;
  260. break;
  261. case AMF_DATA_TYPE_ARRAY: {
  262. unsigned int arraylen, i;
  263. arraylen = avio_rb32(ioc);
  264. for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  265. if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
  266. return -1; //if we couldn't skip, bomb out.
  267. }
  268. }
  269. break;
  270. case AMF_DATA_TYPE_DATE:
  271. avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
  272. break;
  273. default: //unsupported type, we couldn't skip
  274. return -1;
  275. }
  276. if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
  277. acodec = astream ? astream->codec : NULL;
  278. vcodec = vstream ? vstream->codec : NULL;
  279. if (amf_type == AMF_DATA_TYPE_NUMBER) {
  280. if (!strcmp(key, "duration"))
  281. s->duration = num_val * AV_TIME_BASE;
  282. else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
  283. vcodec->bit_rate = num_val * 1024.0;
  284. else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
  285. acodec->bit_rate = num_val * 1024.0;
  286. }
  287. if (!strcmp(key, "duration") ||
  288. !strcmp(key, "filesize") ||
  289. !strcmp(key, "width") ||
  290. !strcmp(key, "height") ||
  291. !strcmp(key, "videodatarate") ||
  292. !strcmp(key, "framerate") ||
  293. !strcmp(key, "videocodecid") ||
  294. !strcmp(key, "audiodatarate") ||
  295. !strcmp(key, "audiosamplerate") ||
  296. !strcmp(key, "audiosamplesize") ||
  297. !strcmp(key, "stereo") ||
  298. !strcmp(key, "audiocodecid"))
  299. return 0;
  300. if(amf_type == AMF_DATA_TYPE_BOOL) {
  301. av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
  302. av_dict_set(&s->metadata, key, str_val, 0);
  303. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  304. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  305. av_dict_set(&s->metadata, key, str_val, 0);
  306. } else if (amf_type == AMF_DATA_TYPE_STRING)
  307. av_dict_set(&s->metadata, key, str_val, 0);
  308. }
  309. return 0;
  310. }
  311. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  312. AMFDataType type;
  313. AVStream *stream, *astream, *vstream;
  314. AVIOContext *ioc;
  315. int i;
  316. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  317. astream = NULL;
  318. vstream = NULL;
  319. ioc = s->pb;
  320. //first object needs to be "onMetaData" string
  321. type = avio_r8(ioc);
  322. if(type != AMF_DATA_TYPE_STRING || amf_get_string(ioc, buffer, sizeof(buffer)) < 0 || strcmp(buffer, "onMetaData"))
  323. return -1;
  324. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  325. for(i = 0; i < s->nb_streams; i++) {
  326. stream = s->streams[i];
  327. if (stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
  328. else if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
  329. }
  330. //parse the second object (we want a mixed array)
  331. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  332. return -1;
  333. return 0;
  334. }
  335. static AVStream *create_stream(AVFormatContext *s, int is_audio){
  336. AVStream *st = avformat_new_stream(s, NULL);
  337. if (!st)
  338. return NULL;
  339. st->id = is_audio;
  340. st->codec->codec_type = is_audio ? AVMEDIA_TYPE_AUDIO : AVMEDIA_TYPE_VIDEO;
  341. avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  342. return st;
  343. }
  344. static int flv_read_header(AVFormatContext *s)
  345. {
  346. int offset, flags;
  347. avio_skip(s->pb, 4);
  348. flags = avio_r8(s->pb);
  349. /* old flvtool cleared this field */
  350. /* FIXME: better fix needed */
  351. if (!flags) {
  352. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  353. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  354. }
  355. if((flags & (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  356. != (FLV_HEADER_FLAG_HASVIDEO|FLV_HEADER_FLAG_HASAUDIO))
  357. s->ctx_flags |= AVFMTCTX_NOHEADER;
  358. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  359. if(!create_stream(s, 0))
  360. return AVERROR(ENOMEM);
  361. }
  362. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  363. if(!create_stream(s, 1))
  364. return AVERROR(ENOMEM);
  365. }
  366. offset = avio_rb32(s->pb);
  367. avio_seek(s->pb, offset, SEEK_SET);
  368. avio_skip(s->pb, 4);
  369. s->start_time = 0;
  370. return 0;
  371. }
  372. static int flv_read_close(AVFormatContext *s)
  373. {
  374. FLVContext *flv = s->priv_data;
  375. av_freep(&flv->new_extradata[0]);
  376. av_freep(&flv->new_extradata[1]);
  377. return 0;
  378. }
  379. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  380. {
  381. av_free(st->codec->extradata);
  382. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  383. if (!st->codec->extradata)
  384. return AVERROR(ENOMEM);
  385. st->codec->extradata_size = size;
  386. avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
  387. return 0;
  388. }
  389. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  390. int size)
  391. {
  392. av_free(flv->new_extradata[stream]);
  393. flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  394. if (!flv->new_extradata[stream])
  395. return AVERROR(ENOMEM);
  396. flv->new_extradata_size[stream] = size;
  397. avio_read(pb, flv->new_extradata[stream], size);
  398. return 0;
  399. }
  400. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  401. {
  402. int i, j, out;
  403. av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
  404. for (i = 0; i < s->nb_streams; i++) {
  405. AVStream *st = s->streams[i];
  406. /* Remove all index entries that point to >= pos */
  407. out = 0;
  408. for (j = 0; j < st->nb_index_entries; j++) {
  409. if (st->index_entries[j].pos < pos)
  410. st->index_entries[out++] = st->index_entries[j];
  411. }
  412. st->nb_index_entries = out;
  413. }
  414. }
  415. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  416. {
  417. FLVContext *flv = s->priv_data;
  418. int ret, i, type, size, flags, is_audio;
  419. int64_t next, pos;
  420. int64_t dts, pts = AV_NOPTS_VALUE;
  421. int sample_rate = 0, channels = 0;
  422. AVStream *st = NULL;
  423. for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
  424. pos = avio_tell(s->pb);
  425. type = avio_r8(s->pb);
  426. size = avio_rb24(s->pb);
  427. dts = avio_rb24(s->pb);
  428. dts |= avio_r8(s->pb) << 24;
  429. av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
  430. if (s->pb->eof_reached)
  431. return AVERROR_EOF;
  432. avio_skip(s->pb, 3); /* stream id, always 0 */
  433. flags = 0;
  434. if (flv->validate_next < flv->validate_count) {
  435. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  436. if (pos == validate_pos) {
  437. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  438. VALIDATE_INDEX_TS_THRESH) {
  439. flv->validate_next++;
  440. } else {
  441. clear_index_entries(s, validate_pos);
  442. flv->validate_count = 0;
  443. }
  444. } else if (pos > validate_pos) {
  445. clear_index_entries(s, validate_pos);
  446. flv->validate_count = 0;
  447. }
  448. }
  449. if(size == 0)
  450. continue;
  451. next= size + avio_tell(s->pb);
  452. if (type == FLV_TAG_TYPE_AUDIO) {
  453. is_audio=1;
  454. flags = avio_r8(s->pb);
  455. size--;
  456. } else if (type == FLV_TAG_TYPE_VIDEO) {
  457. is_audio=0;
  458. flags = avio_r8(s->pb);
  459. size--;
  460. if ((flags & 0xf0) == 0x50) /* video info / command frame */
  461. goto skip;
  462. } else {
  463. if (type == FLV_TAG_TYPE_META && size > 13+1+4)
  464. flv_read_metabody(s, next);
  465. else /* skip packet */
  466. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  467. skip:
  468. avio_seek(s->pb, next, SEEK_SET);
  469. continue;
  470. }
  471. /* skip empty data packets */
  472. if (!size)
  473. continue;
  474. /* now find stream */
  475. for(i=0;i<s->nb_streams;i++) {
  476. st = s->streams[i];
  477. if (st->id == is_audio)
  478. break;
  479. }
  480. if(i == s->nb_streams){
  481. av_log(s, AV_LOG_ERROR, "invalid stream\n");
  482. st= create_stream(s, is_audio);
  483. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  484. }
  485. av_dlog(s, "%d %X %d \n", is_audio, flags, st->discard);
  486. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || is_audio))
  487. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && !is_audio))
  488. || st->discard >= AVDISCARD_ALL
  489. ){
  490. avio_seek(s->pb, next, SEEK_SET);
  491. continue;
  492. }
  493. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY)
  494. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  495. break;
  496. }
  497. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  498. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE)){
  499. int size;
  500. const int64_t pos= avio_tell(s->pb);
  501. const int64_t fsize= avio_size(s->pb);
  502. avio_seek(s->pb, fsize-4, SEEK_SET);
  503. size= avio_rb32(s->pb);
  504. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  505. if(size == avio_rb24(s->pb) + 11){
  506. uint32_t ts = avio_rb24(s->pb);
  507. ts |= avio_r8(s->pb) << 24;
  508. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  509. }
  510. avio_seek(s->pb, pos, SEEK_SET);
  511. }
  512. if(is_audio){
  513. int bits_per_coded_sample;
  514. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  515. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  516. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  517. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  518. st->codec->channels = channels;
  519. st->codec->sample_rate = sample_rate;
  520. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  521. }
  522. if(!st->codec->codec_id){
  523. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  524. flv->last_sample_rate = st->codec->sample_rate;
  525. flv->last_channels = st->codec->channels;
  526. } else {
  527. AVCodecContext ctx;
  528. ctx.sample_rate = sample_rate;
  529. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  530. sample_rate = ctx.sample_rate;
  531. }
  532. }else{
  533. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK);
  534. }
  535. if (st->codec->codec_id == CODEC_ID_AAC ||
  536. st->codec->codec_id == CODEC_ID_H264) {
  537. int type = avio_r8(s->pb);
  538. size--;
  539. if (st->codec->codec_id == CODEC_ID_H264) {
  540. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  541. pts = dts + cts;
  542. if (cts < 0) { // dts are wrong
  543. flv->wrong_dts = 1;
  544. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  545. }
  546. if (flv->wrong_dts)
  547. dts = AV_NOPTS_VALUE;
  548. }
  549. if (type == 0) {
  550. if (st->codec->extradata) {
  551. if ((ret = flv_queue_extradata(flv, s->pb, is_audio, size)) < 0)
  552. return ret;
  553. ret = AVERROR(EAGAIN);
  554. goto leave;
  555. }
  556. if ((ret = flv_get_extradata(s, st, size)) < 0)
  557. return ret;
  558. if (st->codec->codec_id == CODEC_ID_AAC) {
  559. MPEG4AudioConfig cfg;
  560. avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  561. st->codec->extradata_size * 8, 1);
  562. st->codec->channels = cfg.channels;
  563. if (cfg.ext_sample_rate)
  564. st->codec->sample_rate = cfg.ext_sample_rate;
  565. else
  566. st->codec->sample_rate = cfg.sample_rate;
  567. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  568. st->codec->channels, st->codec->sample_rate);
  569. }
  570. ret = AVERROR(EAGAIN);
  571. goto leave;
  572. }
  573. }
  574. /* skip empty data packets */
  575. if (!size) {
  576. ret = AVERROR(EAGAIN);
  577. goto leave;
  578. }
  579. ret= av_get_packet(s->pb, pkt, size);
  580. if (ret < 0) {
  581. return AVERROR(EIO);
  582. }
  583. /* note: we need to modify the packet size here to handle the last
  584. packet */
  585. pkt->size = ret;
  586. pkt->dts = dts;
  587. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  588. pkt->stream_index = st->index;
  589. if (flv->new_extradata[is_audio]) {
  590. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  591. flv->new_extradata_size[is_audio]);
  592. if (side) {
  593. memcpy(side, flv->new_extradata[is_audio],
  594. flv->new_extradata_size[is_audio]);
  595. av_freep(&flv->new_extradata[is_audio]);
  596. flv->new_extradata_size[is_audio] = 0;
  597. }
  598. }
  599. if (is_audio && (sample_rate != flv->last_sample_rate ||
  600. channels != flv->last_channels)) {
  601. flv->last_sample_rate = sample_rate;
  602. flv->last_channels = channels;
  603. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  604. }
  605. if (is_audio || ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY))
  606. pkt->flags |= AV_PKT_FLAG_KEY;
  607. leave:
  608. avio_skip(s->pb, 4);
  609. return ret;
  610. }
  611. static int flv_read_seek(AVFormatContext *s, int stream_index,
  612. int64_t ts, int flags)
  613. {
  614. FLVContext *flv = s->priv_data;
  615. flv->validate_count = 0;
  616. return avio_seek_time(s->pb, stream_index, ts, flags);
  617. }
  618. #if 0 /* don't know enough to implement this */
  619. static int flv_read_seek2(AVFormatContext *s, int stream_index,
  620. int64_t min_ts, int64_t ts, int64_t max_ts, int flags)
  621. {
  622. int ret = AVERROR(ENOSYS);
  623. if (ts - min_ts > (uint64_t)(max_ts - ts)) flags |= AVSEEK_FLAG_BACKWARD;
  624. if (!s->pb->seekable) {
  625. if (stream_index < 0) {
  626. stream_index = av_find_default_stream_index(s);
  627. if (stream_index < 0)
  628. return -1;
  629. /* timestamp for default must be expressed in AV_TIME_BASE units */
  630. ts = av_rescale_rnd(ts, 1000, AV_TIME_BASE,
  631. flags & AVSEEK_FLAG_BACKWARD ? AV_ROUND_DOWN : AV_ROUND_UP);
  632. }
  633. ret = avio_seek_time(s->pb, stream_index, ts, flags);
  634. }
  635. if (ret == AVERROR(ENOSYS))
  636. ret = av_seek_frame(s, stream_index, ts, flags);
  637. return ret;
  638. }
  639. #endif
  640. AVInputFormat ff_flv_demuxer = {
  641. .name = "flv",
  642. .long_name = NULL_IF_CONFIG_SMALL("FLV format"),
  643. .priv_data_size = sizeof(FLVContext),
  644. .read_probe = flv_probe,
  645. .read_header = flv_read_header,
  646. .read_packet = flv_read_packet,
  647. .read_seek = flv_read_seek,
  648. #if 0
  649. .read_seek2 = flv_read_seek2,
  650. #endif
  651. .read_close = flv_read_close,
  652. .extensions = "flv",
  653. };