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.

871 lines
31KB

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