flvdec.c 32 KB

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