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.

803 lines
28KB

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