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.

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