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.

933 lines
34KB

  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/channel_layout.h"
  28. #include "libavutil/dict.h"
  29. #include "libavutil/opt.h"
  30. #include "libavutil/intfloat.h"
  31. #include "libavutil/mathematics.h"
  32. #include "libavcodec/bytestream.h"
  33. #include "libavcodec/mpeg4audio.h"
  34. #include "avformat.h"
  35. #include "internal.h"
  36. #include "avio_internal.h"
  37. #include "flv.h"
  38. #define VALIDATE_INDEX_TS_THRESH 2500
  39. typedef struct {
  40. const AVClass *class; ///< Class for private options.
  41. int trust_metadata; ///< configure streams according onMetaData
  42. int wrong_dts; ///< wrong dts due to negative cts
  43. uint8_t *new_extradata[FLV_STREAM_TYPE_NB];
  44. int new_extradata_size[FLV_STREAM_TYPE_NB];
  45. int last_sample_rate;
  46. int last_channels;
  47. struct {
  48. int64_t dts;
  49. int64_t pos;
  50. } validate_index[2];
  51. int validate_next;
  52. int validate_count;
  53. int searched_for_end;
  54. } FLVContext;
  55. static int flv_probe(AVProbeData *p)
  56. {
  57. const uint8_t *d;
  58. d = p->buf;
  59. if (d[0] == 'F' && d[1] == 'L' && d[2] == 'V' && d[3] < 5 && d[5]==0 && AV_RB32(d+5)>8) {
  60. return AVPROBE_SCORE_MAX;
  61. }
  62. return 0;
  63. }
  64. static AVStream *create_stream(AVFormatContext *s, int codec_type)
  65. {
  66. AVStream *st = avformat_new_stream(s, NULL);
  67. if (!st)
  68. return NULL;
  69. st->codec->codec_type = codec_type;
  70. if(s->nb_streams>=3 ||( s->nb_streams==2
  71. && s->streams[0]->codec->codec_type != AVMEDIA_TYPE_DATA
  72. && s->streams[1]->codec->codec_type != AVMEDIA_TYPE_DATA))
  73. s->ctx_flags &= ~AVFMTCTX_NOHEADER;
  74. avpriv_set_pts_info(st, 32, 1, 1000); /* 32 bit pts in ms */
  75. return st;
  76. }
  77. static int flv_same_audio_codec(AVCodecContext *acodec, int flags)
  78. {
  79. int bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  80. int flv_codecid = flags & FLV_AUDIO_CODECID_MASK;
  81. int codec_id;
  82. if (!acodec->codec_id && !acodec->codec_tag)
  83. return 1;
  84. if (acodec->bits_per_coded_sample != bits_per_coded_sample)
  85. return 0;
  86. switch(flv_codecid) {
  87. //no distinction between S16 and S8 PCM codec flags
  88. case FLV_CODECID_PCM:
  89. codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 :
  90. #if HAVE_BIGENDIAN
  91. AV_CODEC_ID_PCM_S16BE;
  92. #else
  93. AV_CODEC_ID_PCM_S16LE;
  94. #endif
  95. return codec_id == acodec->codec_id;
  96. case FLV_CODECID_PCM_LE:
  97. codec_id = bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE;
  98. return codec_id == acodec->codec_id;
  99. case FLV_CODECID_AAC:
  100. return acodec->codec_id == AV_CODEC_ID_AAC;
  101. case FLV_CODECID_ADPCM:
  102. return acodec->codec_id == AV_CODEC_ID_ADPCM_SWF;
  103. case FLV_CODECID_SPEEX:
  104. return acodec->codec_id == AV_CODEC_ID_SPEEX;
  105. case FLV_CODECID_MP3:
  106. return acodec->codec_id == AV_CODEC_ID_MP3;
  107. case FLV_CODECID_NELLYMOSER_8KHZ_MONO:
  108. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  109. case FLV_CODECID_NELLYMOSER:
  110. return acodec->codec_id == AV_CODEC_ID_NELLYMOSER;
  111. case FLV_CODECID_PCM_MULAW:
  112. return acodec->sample_rate == 8000 &&
  113. acodec->codec_id == AV_CODEC_ID_PCM_MULAW;
  114. case FLV_CODECID_PCM_ALAW:
  115. return acodec->sample_rate = 8000 &&
  116. acodec->codec_id == AV_CODEC_ID_PCM_ALAW;
  117. default:
  118. return acodec->codec_tag == (flv_codecid >> FLV_AUDIO_CODECID_OFFSET);
  119. }
  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 ? AV_CODEC_ID_PCM_U8 :
  126. #if HAVE_BIGENDIAN
  127. AV_CODEC_ID_PCM_S16BE;
  128. #else
  129. AV_CODEC_ID_PCM_S16LE;
  130. #endif
  131. break;
  132. case FLV_CODECID_PCM_LE:
  133. acodec->codec_id = acodec->bits_per_coded_sample == 8 ? AV_CODEC_ID_PCM_U8 : AV_CODEC_ID_PCM_S16LE; break;
  134. case FLV_CODECID_AAC : acodec->codec_id = AV_CODEC_ID_AAC; break;
  135. case FLV_CODECID_ADPCM: acodec->codec_id = AV_CODEC_ID_ADPCM_SWF; break;
  136. case FLV_CODECID_SPEEX:
  137. acodec->codec_id = AV_CODEC_ID_SPEEX;
  138. acodec->sample_rate = 16000;
  139. break;
  140. case FLV_CODECID_MP3 : acodec->codec_id = AV_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 = AV_CODEC_ID_NELLYMOSER;
  144. break;
  145. case FLV_CODECID_NELLYMOSER_16KHZ_MONO:
  146. acodec->sample_rate = 16000;
  147. acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
  148. break;
  149. case FLV_CODECID_NELLYMOSER:
  150. acodec->codec_id = AV_CODEC_ID_NELLYMOSER;
  151. break;
  152. case FLV_CODECID_PCM_MULAW:
  153. acodec->sample_rate = 8000;
  154. acodec->codec_id = AV_CODEC_ID_PCM_MULAW;
  155. break;
  156. case FLV_CODECID_PCM_ALAW:
  157. acodec->sample_rate = 8000;
  158. acodec->codec_id = AV_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 == AV_CODEC_ID_FLV1;
  173. case FLV_CODECID_SCREEN:
  174. return vcodec->codec_id == AV_CODEC_ID_FLASHSV;
  175. case FLV_CODECID_SCREEN2:
  176. return vcodec->codec_id == AV_CODEC_ID_FLASHSV2;
  177. case FLV_CODECID_VP6:
  178. return vcodec->codec_id == AV_CODEC_ID_VP6F;
  179. case FLV_CODECID_VP6A:
  180. return vcodec->codec_id == AV_CODEC_ID_VP6A;
  181. case FLV_CODECID_H264:
  182. return vcodec->codec_id == AV_CODEC_ID_H264;
  183. default:
  184. return vcodec->codec_tag == flv_codecid;
  185. }
  186. }
  187. static int flv_set_video_codec(AVFormatContext *s, AVStream *vstream, int flv_codecid, int read) {
  188. AVCodecContext *vcodec = vstream->codec;
  189. switch(flv_codecid) {
  190. case FLV_CODECID_H263 : vcodec->codec_id = AV_CODEC_ID_FLV1 ; break;
  191. case FLV_CODECID_REALH263: vcodec->codec_id = AV_CODEC_ID_H263 ; break; // Really mean it this time
  192. case FLV_CODECID_SCREEN: vcodec->codec_id = AV_CODEC_ID_FLASHSV; break;
  193. case FLV_CODECID_SCREEN2: vcodec->codec_id = AV_CODEC_ID_FLASHSV2; break;
  194. case FLV_CODECID_VP6 : vcodec->codec_id = AV_CODEC_ID_VP6F ;
  195. case FLV_CODECID_VP6A :
  196. if(flv_codecid == FLV_CODECID_VP6A)
  197. vcodec->codec_id = AV_CODEC_ID_VP6A;
  198. if (read) {
  199. if (vcodec->extradata_size != 1) {
  200. vcodec->extradata = av_malloc(1 + FF_INPUT_BUFFER_PADDING_SIZE);
  201. if (vcodec->extradata)
  202. vcodec->extradata_size = 1;
  203. }
  204. if (vcodec->extradata)
  205. vcodec->extradata[0] = avio_r8(s->pb);
  206. else
  207. avio_skip(s->pb, 1);
  208. }
  209. return 1; // 1 byte body size adjustment for flv_read_packet()
  210. case FLV_CODECID_H264:
  211. vcodec->codec_id = AV_CODEC_ID_H264;
  212. return 3; // not 4, reading packet type will consume one byte
  213. case FLV_CODECID_MPEG4:
  214. vcodec->codec_id = AV_CODEC_ID_MPEG4;
  215. return 3;
  216. default:
  217. av_log(s, AV_LOG_INFO, "Unsupported video codec (%x)\n", flv_codecid);
  218. vcodec->codec_tag = flv_codecid;
  219. }
  220. return 0;
  221. }
  222. static int amf_get_string(AVIOContext *ioc, char *buffer, int buffsize) {
  223. int length = avio_rb16(ioc);
  224. if(length >= buffsize) {
  225. avio_skip(ioc, length);
  226. return -1;
  227. }
  228. avio_read(ioc, buffer, length);
  229. buffer[length] = '\0';
  230. return length;
  231. }
  232. static int parse_keyframes_index(AVFormatContext *s, AVIOContext *ioc, AVStream *vstream, int64_t max_pos) {
  233. FLVContext *flv = s->priv_data;
  234. unsigned int timeslen = 0, fileposlen = 0, i;
  235. char str_val[256];
  236. int64_t *times = NULL;
  237. int64_t *filepositions = NULL;
  238. int ret = AVERROR(ENOSYS);
  239. int64_t initial_pos = avio_tell(ioc);
  240. if(vstream->nb_index_entries>0){
  241. av_log(s, AV_LOG_WARNING, "Skiping duplicate index\n");
  242. return 0;
  243. }
  244. if (s->flags & AVFMT_FLAG_IGNIDX)
  245. return 0;
  246. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  247. int64_t** current_array;
  248. unsigned int arraylen;
  249. // Expect array object in context
  250. if (avio_r8(ioc) != AMF_DATA_TYPE_ARRAY)
  251. break;
  252. arraylen = avio_rb32(ioc);
  253. if(arraylen>>28)
  254. break;
  255. if (!strcmp(KEYFRAMES_TIMESTAMP_TAG , str_val) && !times){
  256. current_array= &times;
  257. timeslen= arraylen;
  258. }else if (!strcmp(KEYFRAMES_BYTEOFFSET_TAG, str_val) && !filepositions){
  259. current_array= &filepositions;
  260. fileposlen= arraylen;
  261. }else // unexpected metatag inside keyframes, will not use such metadata for indexing
  262. break;
  263. if (!(*current_array = av_mallocz(sizeof(**current_array) * arraylen))) {
  264. ret = AVERROR(ENOMEM);
  265. goto finish;
  266. }
  267. for (i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  268. if (avio_r8(ioc) != AMF_DATA_TYPE_NUMBER)
  269. goto invalid;
  270. current_array[0][i] = av_int2double(avio_rb64(ioc));
  271. }
  272. if (times && filepositions) {
  273. // All done, exiting at a position allowing amf_parse_object
  274. // to finish parsing the object
  275. ret = 0;
  276. break;
  277. }
  278. }
  279. if (timeslen == fileposlen && fileposlen>1 && max_pos <= filepositions[0]) {
  280. for (i = 0; i < fileposlen; i++) {
  281. av_add_index_entry(vstream, filepositions[i], times[i]*1000,
  282. 0, 0, AVINDEX_KEYFRAME);
  283. if (i < 2) {
  284. flv->validate_index[i].pos = filepositions[i];
  285. flv->validate_index[i].dts = times[i] * 1000;
  286. flv->validate_count = i + 1;
  287. }
  288. }
  289. } else {
  290. invalid:
  291. av_log(s, AV_LOG_WARNING, "Invalid keyframes object, skipping.\n");
  292. }
  293. finish:
  294. av_freep(&times);
  295. av_freep(&filepositions);
  296. avio_seek(ioc, initial_pos, SEEK_SET);
  297. return ret;
  298. }
  299. static int amf_parse_object(AVFormatContext *s, AVStream *astream, AVStream *vstream, const char *key, int64_t max_pos, int depth) {
  300. AVCodecContext *acodec, *vcodec;
  301. FLVContext *flv = s->priv_data;
  302. AVIOContext *ioc;
  303. AMFDataType amf_type;
  304. char str_val[256];
  305. double num_val;
  306. num_val = 0;
  307. ioc = s->pb;
  308. amf_type = avio_r8(ioc);
  309. switch(amf_type) {
  310. case AMF_DATA_TYPE_NUMBER:
  311. num_val = av_int2double(avio_rb64(ioc)); break;
  312. case AMF_DATA_TYPE_BOOL:
  313. num_val = avio_r8(ioc); break;
  314. case AMF_DATA_TYPE_STRING:
  315. if(amf_get_string(ioc, str_val, sizeof(str_val)) < 0)
  316. return -1;
  317. break;
  318. case AMF_DATA_TYPE_OBJECT:
  319. if ((vstream || astream) && ioc->seekable && key && !strcmp(KEYFRAMES_TAG, key) && depth == 1)
  320. if (parse_keyframes_index(s, ioc, vstream ? vstream : astream,
  321. max_pos) < 0)
  322. av_log(s, AV_LOG_ERROR, "Keyframe index parsing failed\n");
  323. while (avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  324. if (amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  325. return -1; //if we couldn't skip, bomb out.
  326. }
  327. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  328. return -1;
  329. break;
  330. case AMF_DATA_TYPE_NULL:
  331. case AMF_DATA_TYPE_UNDEFINED:
  332. case AMF_DATA_TYPE_UNSUPPORTED:
  333. break; //these take up no additional space
  334. case AMF_DATA_TYPE_MIXEDARRAY:
  335. avio_skip(ioc, 4); //skip 32-bit max array index
  336. while(avio_tell(ioc) < max_pos - 2 && amf_get_string(ioc, str_val, sizeof(str_val)) > 0) {
  337. //this is the only case in which we would want a nested parse to not skip over the object
  338. if(amf_parse_object(s, astream, vstream, str_val, max_pos, depth + 1) < 0)
  339. return -1;
  340. }
  341. if(avio_r8(ioc) != AMF_END_OF_OBJECT)
  342. return -1;
  343. break;
  344. case AMF_DATA_TYPE_ARRAY: {
  345. unsigned int arraylen, i;
  346. arraylen = avio_rb32(ioc);
  347. for(i = 0; i < arraylen && avio_tell(ioc) < max_pos - 1; i++) {
  348. if(amf_parse_object(s, NULL, NULL, NULL, max_pos, depth + 1) < 0)
  349. return -1; //if we couldn't skip, bomb out.
  350. }
  351. }
  352. break;
  353. case AMF_DATA_TYPE_DATE:
  354. avio_skip(ioc, 8 + 2); //timestamp (double) and UTC offset (int16)
  355. break;
  356. default: //unsupported type, we couldn't skip
  357. return -1;
  358. }
  359. if(depth == 1 && key) { //only look for metadata values when we are not nested and key != NULL
  360. acodec = astream ? astream->codec : NULL;
  361. vcodec = vstream ? vstream->codec : NULL;
  362. if (amf_type == AMF_DATA_TYPE_NUMBER || amf_type == AMF_DATA_TYPE_BOOL) {
  363. if (!strcmp(key, "duration"))
  364. s->duration = num_val * AV_TIME_BASE;
  365. else if (!strcmp(key, "videodatarate") && vcodec && 0 <= (int)(num_val * 1024.0))
  366. vcodec->bit_rate = num_val * 1024.0;
  367. else if (!strcmp(key, "audiodatarate") && acodec && 0 <= (int)(num_val * 1024.0))
  368. acodec->bit_rate = num_val * 1024.0;
  369. else if (!strcmp(key, "datastream")) {
  370. AVStream *st = create_stream(s, AVMEDIA_TYPE_DATA);
  371. if (!st)
  372. return AVERROR(ENOMEM);
  373. st->codec->codec_id = AV_CODEC_ID_TEXT;
  374. } else if (flv->trust_metadata) {
  375. if (!strcmp(key, "videocodecid") && vcodec) {
  376. flv_set_video_codec(s, vstream, num_val, 0);
  377. } else
  378. if (!strcmp(key, "audiocodecid") && acodec) {
  379. int id = ((int)num_val) << FLV_AUDIO_CODECID_OFFSET;
  380. flv_set_audio_codec(s, astream, acodec, id);
  381. } else
  382. if (!strcmp(key, "audiosamplerate") && acodec) {
  383. acodec->sample_rate = num_val;
  384. } else if (!strcmp(key, "audiosamplesize") && acodec) {
  385. acodec->bits_per_coded_sample = num_val;
  386. } else if (!strcmp(key, "stereo") && acodec) {
  387. acodec->channels = num_val + 1;
  388. acodec->channel_layout = acodec->channels == 2 ?
  389. AV_CH_LAYOUT_STEREO :
  390. AV_CH_LAYOUT_MONO;
  391. } else
  392. if (!strcmp(key, "width") && vcodec) {
  393. vcodec->width = num_val;
  394. } else
  395. if (!strcmp(key, "height") && vcodec) {
  396. vcodec->height = num_val;
  397. }
  398. }
  399. }
  400. if (amf_type == AMF_DATA_TYPE_OBJECT && s->nb_streams == 1 &&
  401. ((!acodec && !strcmp(key, "audiocodecid")) ||
  402. (!vcodec && !strcmp(key, "videocodecid"))))
  403. s->ctx_flags &= ~AVFMTCTX_NOHEADER; //If there is either audio/video missing, codecid will be an empty object
  404. if (!strcmp(key, "duration") ||
  405. !strcmp(key, "filesize") ||
  406. !strcmp(key, "width") ||
  407. !strcmp(key, "height") ||
  408. !strcmp(key, "videodatarate") ||
  409. !strcmp(key, "framerate") ||
  410. !strcmp(key, "videocodecid") ||
  411. !strcmp(key, "audiodatarate") ||
  412. !strcmp(key, "audiosamplerate") ||
  413. !strcmp(key, "audiosamplesize") ||
  414. !strcmp(key, "stereo") ||
  415. !strcmp(key, "audiocodecid"))
  416. return 0;
  417. if(amf_type == AMF_DATA_TYPE_BOOL) {
  418. av_strlcpy(str_val, num_val > 0 ? "true" : "false", sizeof(str_val));
  419. av_dict_set(&s->metadata, key, str_val, 0);
  420. } else if(amf_type == AMF_DATA_TYPE_NUMBER) {
  421. snprintf(str_val, sizeof(str_val), "%.f", num_val);
  422. av_dict_set(&s->metadata, key, str_val, 0);
  423. } else if (amf_type == AMF_DATA_TYPE_STRING)
  424. av_dict_set(&s->metadata, key, str_val, 0);
  425. }
  426. return 0;
  427. }
  428. static int flv_read_metabody(AVFormatContext *s, int64_t next_pos) {
  429. AMFDataType type;
  430. AVStream *stream, *astream, *vstream, *dstream;
  431. AVIOContext *ioc;
  432. int i;
  433. char buffer[11]; //only needs to hold the string "onMetaData". Anything longer is something we don't want.
  434. vstream = astream = dstream = NULL;
  435. ioc = s->pb;
  436. //first object needs to be "onMetaData" string
  437. type = avio_r8(ioc);
  438. if (type != AMF_DATA_TYPE_STRING ||
  439. amf_get_string(ioc, buffer, sizeof(buffer)) < 0)
  440. return -1;
  441. if (!strcmp(buffer, "onTextData"))
  442. return 1;
  443. if (strcmp(buffer, "onMetaData"))
  444. return -1;
  445. //find the streams now so that amf_parse_object doesn't need to do the lookup every time it is called.
  446. for(i = 0; i < s->nb_streams; i++) {
  447. stream = s->streams[i];
  448. if(stream->codec->codec_type == AVMEDIA_TYPE_VIDEO) vstream = stream;
  449. else if(stream->codec->codec_type == AVMEDIA_TYPE_AUDIO) astream = stream;
  450. else if(stream->codec->codec_type == AVMEDIA_TYPE_DATA) dstream = stream;
  451. }
  452. //parse the second object (we want a mixed array)
  453. if(amf_parse_object(s, astream, vstream, buffer, next_pos, 0) < 0)
  454. return -1;
  455. return 0;
  456. }
  457. static int flv_read_header(AVFormatContext *s)
  458. {
  459. int offset, flags;
  460. avio_skip(s->pb, 4);
  461. flags = avio_r8(s->pb);
  462. /* old flvtool cleared this field */
  463. /* FIXME: better fix needed */
  464. if (!flags) {
  465. flags = FLV_HEADER_FLAG_HASVIDEO | FLV_HEADER_FLAG_HASAUDIO;
  466. av_log(s, AV_LOG_WARNING, "Broken FLV file, which says no streams present, this might fail\n");
  467. }
  468. s->ctx_flags |= AVFMTCTX_NOHEADER;
  469. if(flags & FLV_HEADER_FLAG_HASVIDEO){
  470. if(!create_stream(s, AVMEDIA_TYPE_VIDEO))
  471. return AVERROR(ENOMEM);
  472. }
  473. if(flags & FLV_HEADER_FLAG_HASAUDIO){
  474. if(!create_stream(s, AVMEDIA_TYPE_AUDIO))
  475. return AVERROR(ENOMEM);
  476. }
  477. // Flag doesn't indicate whether or not there is script-data present. Must
  478. // create that stream if it's encountered.
  479. offset = avio_rb32(s->pb);
  480. avio_seek(s->pb, offset, SEEK_SET);
  481. avio_skip(s->pb, 4);
  482. s->start_time = 0;
  483. return 0;
  484. }
  485. static int flv_read_close(AVFormatContext *s)
  486. {
  487. int i;
  488. FLVContext *flv = s->priv_data;
  489. for(i=0; i<FLV_STREAM_TYPE_NB; i++)
  490. av_freep(&flv->new_extradata[i]);
  491. return 0;
  492. }
  493. static int flv_get_extradata(AVFormatContext *s, AVStream *st, int size)
  494. {
  495. av_free(st->codec->extradata);
  496. st->codec->extradata = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  497. if (!st->codec->extradata)
  498. return AVERROR(ENOMEM);
  499. st->codec->extradata_size = size;
  500. avio_read(s->pb, st->codec->extradata, st->codec->extradata_size);
  501. return 0;
  502. }
  503. static int flv_queue_extradata(FLVContext *flv, AVIOContext *pb, int stream,
  504. int size)
  505. {
  506. av_free(flv->new_extradata[stream]);
  507. flv->new_extradata[stream] = av_mallocz(size + FF_INPUT_BUFFER_PADDING_SIZE);
  508. if (!flv->new_extradata[stream])
  509. return AVERROR(ENOMEM);
  510. flv->new_extradata_size[stream] = size;
  511. avio_read(pb, flv->new_extradata[stream], size);
  512. return 0;
  513. }
  514. static void clear_index_entries(AVFormatContext *s, int64_t pos)
  515. {
  516. int i, j, out;
  517. av_log(s, AV_LOG_WARNING, "Found invalid index entries, clearing the index.\n");
  518. for (i = 0; i < s->nb_streams; i++) {
  519. AVStream *st = s->streams[i];
  520. /* Remove all index entries that point to >= pos */
  521. out = 0;
  522. for (j = 0; j < st->nb_index_entries; j++) {
  523. if (st->index_entries[j].pos < pos)
  524. st->index_entries[out++] = st->index_entries[j];
  525. }
  526. st->nb_index_entries = out;
  527. }
  528. }
  529. static int flv_data_packet(AVFormatContext *s, AVPacket *pkt,
  530. int64_t dts, int64_t next)
  531. {
  532. int ret = AVERROR_INVALIDDATA, i;
  533. AVIOContext *pb = s->pb;
  534. AVStream *st = NULL;
  535. AMFDataType type;
  536. char buf[20];
  537. int length;
  538. type = avio_r8(pb);
  539. if (type == AMF_DATA_TYPE_MIXEDARRAY)
  540. avio_seek(pb, 4, SEEK_CUR);
  541. else if (type != AMF_DATA_TYPE_OBJECT)
  542. goto out;
  543. amf_get_string(pb, buf, sizeof(buf));
  544. if (strcmp(buf, "type") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  545. goto out;
  546. amf_get_string(pb, buf, sizeof(buf));
  547. //FIXME parse it as codec_id
  548. amf_get_string(pb, buf, sizeof(buf));
  549. if (strcmp(buf, "text") || avio_r8(pb) != AMF_DATA_TYPE_STRING)
  550. goto out;
  551. length = avio_rb16(pb);
  552. ret = av_get_packet(s->pb, pkt, length);
  553. if (ret < 0) {
  554. ret = AVERROR(EIO);
  555. goto out;
  556. }
  557. for (i = 0; i < s->nb_streams; i++) {
  558. st = s->streams[i];
  559. if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
  560. break;
  561. }
  562. if (i == s->nb_streams) {
  563. st = create_stream(s, AVMEDIA_TYPE_DATA);
  564. if (!st)
  565. goto out;
  566. st->codec->codec_id = AV_CODEC_ID_TEXT;
  567. }
  568. pkt->dts = dts;
  569. pkt->pts = dts;
  570. pkt->size = ret;
  571. pkt->stream_index = st->index;
  572. pkt->flags |= AV_PKT_FLAG_KEY;
  573. avio_seek(s->pb, next + 4, SEEK_SET);
  574. out:
  575. return ret;
  576. }
  577. static int flv_read_packet(AVFormatContext *s, AVPacket *pkt)
  578. {
  579. FLVContext *flv = s->priv_data;
  580. int ret, i, type, size, flags;
  581. int stream_type=-1;
  582. int64_t next, pos, meta_pos;
  583. int64_t dts, pts = AV_NOPTS_VALUE;
  584. int av_uninit(channels);
  585. int av_uninit(sample_rate);
  586. AVStream *st = NULL;
  587. for(;;avio_skip(s->pb, 4)){ /* pkt size is repeated at end. skip it */
  588. pos = avio_tell(s->pb);
  589. type = avio_r8(s->pb);
  590. size = avio_rb24(s->pb);
  591. dts = avio_rb24(s->pb);
  592. dts |= avio_r8(s->pb) << 24;
  593. av_dlog(s, "type:%d, size:%d, dts:%"PRId64"\n", type, size, dts);
  594. if (url_feof(s->pb))
  595. return AVERROR_EOF;
  596. avio_skip(s->pb, 3); /* stream id, always 0 */
  597. flags = 0;
  598. if (flv->validate_next < flv->validate_count) {
  599. int64_t validate_pos = flv->validate_index[flv->validate_next].pos;
  600. if (pos == validate_pos) {
  601. if (FFABS(dts - flv->validate_index[flv->validate_next].dts) <=
  602. VALIDATE_INDEX_TS_THRESH) {
  603. flv->validate_next++;
  604. } else {
  605. clear_index_entries(s, validate_pos);
  606. flv->validate_count = 0;
  607. }
  608. } else if (pos > validate_pos) {
  609. clear_index_entries(s, validate_pos);
  610. flv->validate_count = 0;
  611. }
  612. }
  613. if(size == 0)
  614. continue;
  615. next= size + avio_tell(s->pb);
  616. if (type == FLV_TAG_TYPE_AUDIO) {
  617. stream_type=FLV_STREAM_TYPE_AUDIO;
  618. flags = avio_r8(s->pb);
  619. size--;
  620. } else if (type == FLV_TAG_TYPE_VIDEO) {
  621. stream_type=FLV_STREAM_TYPE_VIDEO;
  622. flags = avio_r8(s->pb);
  623. size--;
  624. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_VIDEO_INFO_CMD)
  625. goto skip;
  626. } else if (type == FLV_TAG_TYPE_META) {
  627. stream_type=FLV_STREAM_TYPE_DATA;
  628. if (size > 13+1+4 && dts == 0) { // Header-type metadata stuff
  629. meta_pos = avio_tell(s->pb);
  630. if (flv_read_metabody(s, next) == 0){
  631. goto skip;
  632. }
  633. avio_seek(s->pb, meta_pos, SEEK_SET);
  634. }
  635. } else {
  636. av_log(s, AV_LOG_DEBUG, "skipping flv packet: type %d, size %d, flags %d\n", type, size, flags);
  637. skip:
  638. avio_seek(s->pb, next, SEEK_SET);
  639. continue;
  640. }
  641. /* skip empty data packets */
  642. if (!size)
  643. continue;
  644. /* now find stream */
  645. for(i=0;i<s->nb_streams;i++) {
  646. st = s->streams[i];
  647. if (stream_type == FLV_STREAM_TYPE_AUDIO) {
  648. if (st->codec->codec_type == AVMEDIA_TYPE_AUDIO &&
  649. (s->audio_codec_id || flv_same_audio_codec(st->codec, flags))) {
  650. break;
  651. }
  652. } else
  653. if (stream_type == FLV_STREAM_TYPE_VIDEO) {
  654. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO &&
  655. (s->video_codec_id || flv_same_video_codec(st->codec, flags))) {
  656. break;
  657. }
  658. } else if (stream_type == FLV_STREAM_TYPE_DATA) {
  659. if (st->codec->codec_type == AVMEDIA_TYPE_DATA)
  660. break;
  661. }
  662. }
  663. if(i == s->nb_streams){
  664. static const enum AVMediaType stream_types[] = {AVMEDIA_TYPE_VIDEO, AVMEDIA_TYPE_AUDIO, AVMEDIA_TYPE_DATA};
  665. av_log(s, AV_LOG_WARNING, "Stream discovered after head already parsed\n");
  666. st = create_stream(s,
  667. stream_types[stream_type]);
  668. if (!st)
  669. return AVERROR(ENOMEM);
  670. }
  671. av_dlog(s, "%d %X %d \n", stream_type, flags, st->discard);
  672. if( (st->discard >= AVDISCARD_NONKEY && !((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || (stream_type == FLV_STREAM_TYPE_AUDIO)))
  673. ||(st->discard >= AVDISCARD_BIDIR && ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_DISP_INTER && (stream_type == FLV_STREAM_TYPE_VIDEO)))
  674. || st->discard >= AVDISCARD_ALL
  675. ){
  676. avio_seek(s->pb, next, SEEK_SET);
  677. continue;
  678. }
  679. if ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY || stream_type == FLV_STREAM_TYPE_AUDIO)
  680. av_add_index_entry(st, pos, dts, size, 0, AVINDEX_KEYFRAME);
  681. break;
  682. }
  683. // if not streamed and no duration from metadata then seek to end to find the duration from the timestamps
  684. if(s->pb->seekable && (!s->duration || s->duration==AV_NOPTS_VALUE) && !flv->searched_for_end){
  685. int size;
  686. const int64_t pos= avio_tell(s->pb);
  687. int64_t fsize= avio_size(s->pb);
  688. retry_duration:
  689. avio_seek(s->pb, fsize-4, SEEK_SET);
  690. size= avio_rb32(s->pb);
  691. avio_seek(s->pb, fsize-3-size, SEEK_SET);
  692. if(size == avio_rb24(s->pb) + 11){
  693. uint32_t ts = avio_rb24(s->pb);
  694. ts |= avio_r8(s->pb) << 24;
  695. if(ts)
  696. s->duration = ts * (int64_t)AV_TIME_BASE / 1000;
  697. else if (fsize >= 8 && fsize - 8 >= size){
  698. fsize -= size+4;
  699. goto retry_duration;
  700. }
  701. }
  702. avio_seek(s->pb, pos, SEEK_SET);
  703. flv->searched_for_end = 1;
  704. }
  705. if(stream_type == FLV_STREAM_TYPE_AUDIO){
  706. int bits_per_coded_sample;
  707. channels = (flags & FLV_AUDIO_CHANNEL_MASK) == FLV_STEREO ? 2 : 1;
  708. sample_rate = (44100 << ((flags & FLV_AUDIO_SAMPLERATE_MASK) >> FLV_AUDIO_SAMPLERATE_OFFSET) >> 3);
  709. bits_per_coded_sample = (flags & FLV_AUDIO_SAMPLESIZE_MASK) ? 16 : 8;
  710. if(!st->codec->channels || !st->codec->sample_rate || !st->codec->bits_per_coded_sample) {
  711. st->codec->channels = channels;
  712. st->codec->channel_layout = channels == 1 ? AV_CH_LAYOUT_MONO :
  713. AV_CH_LAYOUT_STEREO;
  714. st->codec->sample_rate = sample_rate;
  715. st->codec->bits_per_coded_sample = bits_per_coded_sample;
  716. }
  717. if(!st->codec->codec_id){
  718. flv_set_audio_codec(s, st, st->codec, flags & FLV_AUDIO_CODECID_MASK);
  719. flv->last_sample_rate = sample_rate = st->codec->sample_rate;
  720. flv->last_channels = channels = st->codec->channels;
  721. } else {
  722. AVCodecContext ctx;
  723. ctx.sample_rate = sample_rate;
  724. flv_set_audio_codec(s, st, &ctx, flags & FLV_AUDIO_CODECID_MASK);
  725. sample_rate = ctx.sample_rate;
  726. }
  727. } else if(stream_type == FLV_STREAM_TYPE_VIDEO) {
  728. size -= flv_set_video_codec(s, st, flags & FLV_VIDEO_CODECID_MASK, 1);
  729. }
  730. if (st->codec->codec_id == AV_CODEC_ID_AAC ||
  731. st->codec->codec_id == AV_CODEC_ID_H264 ||
  732. st->codec->codec_id == AV_CODEC_ID_MPEG4) {
  733. int type = avio_r8(s->pb);
  734. size--;
  735. if (st->codec->codec_id == AV_CODEC_ID_H264 || st->codec->codec_id == AV_CODEC_ID_MPEG4) {
  736. int32_t cts = (avio_rb24(s->pb)+0xff800000)^0xff800000; // sign extension
  737. pts = dts + cts;
  738. if (cts < 0) { // dts are wrong
  739. flv->wrong_dts = 1;
  740. av_log(s, AV_LOG_WARNING, "negative cts, previous timestamps might be wrong\n");
  741. }
  742. if (flv->wrong_dts)
  743. dts = AV_NOPTS_VALUE;
  744. }
  745. if (type == 0 && (!st->codec->extradata || st->codec->codec_id == AV_CODEC_ID_AAC)) {
  746. if (st->codec->extradata) {
  747. if ((ret = flv_queue_extradata(flv, s->pb, stream_type, size)) < 0)
  748. return ret;
  749. ret = AVERROR(EAGAIN);
  750. goto leave;
  751. }
  752. if ((ret = flv_get_extradata(s, st, size)) < 0)
  753. return ret;
  754. if (st->codec->codec_id == AV_CODEC_ID_AAC && 0) {
  755. MPEG4AudioConfig cfg;
  756. if (avpriv_mpeg4audio_get_config(&cfg, st->codec->extradata,
  757. st->codec->extradata_size * 8, 1) >= 0) {
  758. st->codec->channels = cfg.channels;
  759. st->codec->channel_layout = 0;
  760. if (cfg.ext_sample_rate)
  761. st->codec->sample_rate = cfg.ext_sample_rate;
  762. else
  763. st->codec->sample_rate = cfg.sample_rate;
  764. av_dlog(s, "mp4a config channels %d sample rate %d\n",
  765. st->codec->channels, st->codec->sample_rate);
  766. }
  767. }
  768. ret = AVERROR(EAGAIN);
  769. goto leave;
  770. }
  771. }
  772. /* skip empty data packets */
  773. if (!size) {
  774. ret = AVERROR(EAGAIN);
  775. goto leave;
  776. }
  777. ret= av_get_packet(s->pb, pkt, size);
  778. if (ret < 0)
  779. return ret;
  780. pkt->dts = dts;
  781. pkt->pts = pts == AV_NOPTS_VALUE ? dts : pts;
  782. pkt->stream_index = st->index;
  783. if (flv->new_extradata[stream_type]) {
  784. uint8_t *side = av_packet_new_side_data(pkt, AV_PKT_DATA_NEW_EXTRADATA,
  785. flv->new_extradata_size[stream_type]);
  786. if (side) {
  787. memcpy(side, flv->new_extradata[stream_type],
  788. flv->new_extradata_size[stream_type]);
  789. av_freep(&flv->new_extradata[stream_type]);
  790. flv->new_extradata_size[stream_type] = 0;
  791. }
  792. }
  793. if (stream_type == FLV_STREAM_TYPE_AUDIO && (sample_rate != flv->last_sample_rate ||
  794. channels != flv->last_channels)) {
  795. flv->last_sample_rate = sample_rate;
  796. flv->last_channels = channels;
  797. ff_add_param_change(pkt, channels, 0, sample_rate, 0, 0);
  798. }
  799. if ( stream_type == FLV_STREAM_TYPE_AUDIO ||
  800. ((flags & FLV_VIDEO_FRAMETYPE_MASK) == FLV_FRAME_KEY) ||
  801. stream_type == FLV_STREAM_TYPE_DATA)
  802. pkt->flags |= AV_PKT_FLAG_KEY;
  803. leave:
  804. avio_skip(s->pb, 4);
  805. return ret;
  806. }
  807. static int flv_read_seek(AVFormatContext *s, int stream_index,
  808. int64_t ts, int flags)
  809. {
  810. FLVContext *flv = s->priv_data;
  811. flv->validate_count = 0;
  812. return avio_seek_time(s->pb, stream_index, ts, flags);
  813. }
  814. #define OFFSET(x) offsetof(FLVContext, x)
  815. #define VD AV_OPT_FLAG_VIDEO_PARAM | AV_OPT_FLAG_DECODING_PARAM
  816. static const AVOption options[] = {
  817. { "flv_metadata", "Allocate streams according the onMetaData array", OFFSET(trust_metadata), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, VD},
  818. { NULL }
  819. };
  820. static const AVClass flv_class = {
  821. .class_name = "flvdec",
  822. .item_name = av_default_item_name,
  823. .option = options,
  824. .version = LIBAVUTIL_VERSION_INT,
  825. };
  826. AVInputFormat ff_flv_demuxer = {
  827. .name = "flv",
  828. .long_name = NULL_IF_CONFIG_SMALL("FLV (Flash Video)"),
  829. .priv_data_size = sizeof(FLVContext),
  830. .read_probe = flv_probe,
  831. .read_header = flv_read_header,
  832. .read_packet = flv_read_packet,
  833. .read_seek = flv_read_seek,
  834. .read_close = flv_read_close,
  835. .extensions = "flv",
  836. .priv_class = &flv_class,
  837. };