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.

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