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.

858 lines
29KB

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