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.

793 lines
27KB

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