avidec.c 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134
  1. /*
  2. * AVI demuxer
  3. * Copyright (c) 2001 Fabrice Bellard
  4. *
  5. * This file is part of FFmpeg.
  6. *
  7. * FFmpeg is free software; you can redistribute it and/or
  8. * modify it under the terms of the GNU Lesser General Public
  9. * License as published by the Free Software Foundation; either
  10. * version 2.1 of the License, or (at your option) any later version.
  11. *
  12. * FFmpeg is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  15. * Lesser General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU Lesser General Public
  18. * License along with FFmpeg; if not, write to the Free Software
  19. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  20. */
  21. #include "libavutil/intreadwrite.h"
  22. #include "libavutil/bswap.h"
  23. #include "avformat.h"
  24. #include "avi.h"
  25. #include "dv.h"
  26. #include "riff.h"
  27. #undef NDEBUG
  28. #include <assert.h>
  29. //#define DEBUG
  30. //#define DEBUG_SEEK
  31. typedef struct AVIStream {
  32. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  33. (used to compute the pts) */
  34. int remaining;
  35. int packet_size;
  36. int scale;
  37. int rate;
  38. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  39. int64_t cum_len; /* temporary storage (used during seek) */
  40. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  41. int prefix_count;
  42. uint32_t pal[256];
  43. int has_pal;
  44. } AVIStream;
  45. typedef struct {
  46. int64_t riff_end;
  47. int64_t movi_end;
  48. int64_t fsize;
  49. int64_t movi_list;
  50. int64_t last_pkt_pos;
  51. int index_loaded;
  52. int is_odml;
  53. int non_interleaved;
  54. int stream_index;
  55. DVDemuxContext* dv_demux;
  56. } AVIContext;
  57. static const char avi_headers[][8] = {
  58. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  59. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  60. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  61. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  62. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  63. { 0 }
  64. };
  65. static int avi_load_index(AVFormatContext *s);
  66. static int guess_ni_flag(AVFormatContext *s);
  67. #ifdef DEBUG
  68. static void print_tag(const char *str, unsigned int tag, int size)
  69. {
  70. printf("%s: tag=%c%c%c%c size=0x%x\n",
  71. str, tag & 0xff,
  72. (tag >> 8) & 0xff,
  73. (tag >> 16) & 0xff,
  74. (tag >> 24) & 0xff,
  75. size);
  76. }
  77. #endif
  78. static int get_riff(AVFormatContext *s, ByteIOContext *pb)
  79. {
  80. AVIContext *avi = s->priv_data;
  81. char header[8];
  82. int i;
  83. /* check RIFF header */
  84. get_buffer(pb, header, 4);
  85. avi->riff_end = get_le32(pb); /* RIFF chunk size */
  86. avi->riff_end += url_ftell(pb); /* RIFF chunk end */
  87. get_buffer(pb, header+4, 4);
  88. for(i=0; avi_headers[i][0]; i++)
  89. if(!memcmp(header, avi_headers[i], 8))
  90. break;
  91. if(!avi_headers[i][0])
  92. return -1;
  93. if(header[7] == 0x19)
  94. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  95. return 0;
  96. }
  97. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  98. AVIContext *avi = s->priv_data;
  99. ByteIOContext *pb = s->pb;
  100. int longs_pre_entry= get_le16(pb);
  101. int index_sub_type = get_byte(pb);
  102. int index_type = get_byte(pb);
  103. int entries_in_use = get_le32(pb);
  104. int chunk_id = get_le32(pb);
  105. int64_t base = get_le64(pb);
  106. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  107. AVStream *st;
  108. AVIStream *ast;
  109. int i;
  110. int64_t last_pos= -1;
  111. int64_t filesize= url_fsize(s->pb);
  112. #ifdef DEBUG_SEEK
  113. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  114. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  115. #endif
  116. if(stream_id > s->nb_streams || stream_id < 0)
  117. return -1;
  118. st= s->streams[stream_id];
  119. ast = st->priv_data;
  120. if(index_sub_type)
  121. return -1;
  122. get_le32(pb);
  123. if(index_type && longs_pre_entry != 2)
  124. return -1;
  125. if(index_type>1)
  126. return -1;
  127. if(filesize > 0 && base >= filesize){
  128. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  129. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  130. base &= 0xFFFFFFFF;
  131. else
  132. return -1;
  133. }
  134. for(i=0; i<entries_in_use; i++){
  135. if(index_type){
  136. int64_t pos= get_le32(pb) + base - 8;
  137. int len = get_le32(pb);
  138. int key= len >= 0;
  139. len &= 0x7FFFFFFF;
  140. #ifdef DEBUG_SEEK
  141. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  142. #endif
  143. if(url_feof(pb))
  144. return -1;
  145. if(last_pos == pos || pos == base - 8)
  146. avi->non_interleaved= 1;
  147. if(last_pos != pos)
  148. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
  149. if(ast->sample_size)
  150. ast->cum_len += len;
  151. else
  152. ast->cum_len ++;
  153. last_pos= pos;
  154. }else{
  155. int64_t offset, pos;
  156. int duration;
  157. offset = get_le64(pb);
  158. get_le32(pb); /* size */
  159. duration = get_le32(pb);
  160. if(url_feof(pb))
  161. return -1;
  162. pos = url_ftell(pb);
  163. url_fseek(pb, offset+8, SEEK_SET);
  164. read_braindead_odml_indx(s, frame_num);
  165. frame_num += duration;
  166. url_fseek(pb, pos, SEEK_SET);
  167. }
  168. }
  169. avi->index_loaded=1;
  170. return 0;
  171. }
  172. static void clean_index(AVFormatContext *s){
  173. int i;
  174. int64_t j;
  175. for(i=0; i<s->nb_streams; i++){
  176. AVStream *st = s->streams[i];
  177. AVIStream *ast = st->priv_data;
  178. int n= st->nb_index_entries;
  179. int max= ast->sample_size;
  180. int64_t pos, size, ts;
  181. if(n != 1 || ast->sample_size==0)
  182. continue;
  183. while(max < 1024) max+=max;
  184. pos= st->index_entries[0].pos;
  185. size= st->index_entries[0].size;
  186. ts= st->index_entries[0].timestamp;
  187. for(j=0; j<size; j+=max){
  188. av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  189. }
  190. }
  191. }
  192. static int avi_read_tag(AVFormatContext *s, const char *key, unsigned int size)
  193. {
  194. ByteIOContext *pb = s->pb;
  195. uint8_t value[1024];
  196. int64_t i = url_ftell(pb);
  197. size += (size & 1);
  198. get_strz(pb, value, sizeof(value));
  199. url_fseek(pb, i+size, SEEK_SET);
  200. return av_metadata_set(&s->metadata, key, value);
  201. }
  202. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  203. {
  204. AVIContext *avi = s->priv_data;
  205. ByteIOContext *pb = s->pb;
  206. unsigned int tag, tag1, handler;
  207. int codec_type, stream_index, frame_period, bit_rate;
  208. unsigned int size, nb_frames;
  209. int i;
  210. AVStream *st;
  211. AVIStream *ast = NULL;
  212. int avih_width=0, avih_height=0;
  213. int amv_file_format=0;
  214. avi->stream_index= -1;
  215. if (get_riff(s, pb) < 0)
  216. return -1;
  217. avi->fsize = url_fsize(pb);
  218. if(avi->fsize<=0)
  219. avi->fsize= avi->riff_end;
  220. /* first list tag */
  221. stream_index = -1;
  222. codec_type = -1;
  223. frame_period = 0;
  224. for(;;) {
  225. if (url_feof(pb))
  226. goto fail;
  227. tag = get_le32(pb);
  228. size = get_le32(pb);
  229. #ifdef DEBUG
  230. print_tag("tag", tag, size);
  231. #endif
  232. switch(tag) {
  233. case MKTAG('L', 'I', 'S', 'T'):
  234. /* Ignored, except at start of video packets. */
  235. tag1 = get_le32(pb);
  236. #ifdef DEBUG
  237. print_tag("list", tag1, 0);
  238. #endif
  239. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  240. avi->movi_list = url_ftell(pb) - 4;
  241. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  242. else avi->movi_end = url_fsize(pb);
  243. #ifdef DEBUG
  244. printf("movi end=%"PRIx64"\n", avi->movi_end);
  245. #endif
  246. goto end_of_header;
  247. }
  248. break;
  249. case MKTAG('d', 'm', 'l', 'h'):
  250. avi->is_odml = 1;
  251. url_fskip(pb, size + (size & 1));
  252. break;
  253. case MKTAG('a', 'm', 'v', 'h'):
  254. amv_file_format=1;
  255. case MKTAG('a', 'v', 'i', 'h'):
  256. /* AVI header */
  257. /* using frame_period is bad idea */
  258. frame_period = get_le32(pb);
  259. bit_rate = get_le32(pb) * 8;
  260. get_le32(pb);
  261. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  262. url_fskip(pb, 2 * 4);
  263. get_le32(pb);
  264. get_le32(pb);
  265. avih_width=get_le32(pb);
  266. avih_height=get_le32(pb);
  267. url_fskip(pb, size - 10 * 4);
  268. break;
  269. case MKTAG('s', 't', 'r', 'h'):
  270. /* stream header */
  271. tag1 = get_le32(pb);
  272. handler = get_le32(pb); /* codec tag */
  273. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  274. url_fskip(pb, size - 8);
  275. break;
  276. }else{
  277. stream_index++;
  278. st = av_new_stream(s, stream_index);
  279. if (!st)
  280. goto fail;
  281. ast = av_mallocz(sizeof(AVIStream));
  282. if (!ast)
  283. goto fail;
  284. st->priv_data = ast;
  285. }
  286. if(amv_file_format)
  287. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  288. #ifdef DEBUG
  289. print_tag("strh", tag1, -1);
  290. #endif
  291. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  292. int64_t dv_dur;
  293. /*
  294. * After some consideration -- I don't think we
  295. * have to support anything but DV in type1 AVIs.
  296. */
  297. if (s->nb_streams != 1)
  298. goto fail;
  299. if (handler != MKTAG('d', 'v', 's', 'd') &&
  300. handler != MKTAG('d', 'v', 'h', 'd') &&
  301. handler != MKTAG('d', 'v', 's', 'l'))
  302. goto fail;
  303. ast = s->streams[0]->priv_data;
  304. av_freep(&s->streams[0]->codec->extradata);
  305. av_freep(&s->streams[0]);
  306. s->nb_streams = 0;
  307. if (CONFIG_DV_DEMUXER) {
  308. avi->dv_demux = dv_init_demux(s);
  309. if (!avi->dv_demux)
  310. goto fail;
  311. }
  312. s->streams[0]->priv_data = ast;
  313. url_fskip(pb, 3 * 4);
  314. ast->scale = get_le32(pb);
  315. ast->rate = get_le32(pb);
  316. url_fskip(pb, 4); /* start time */
  317. dv_dur = get_le32(pb);
  318. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  319. dv_dur *= AV_TIME_BASE;
  320. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  321. }
  322. /*
  323. * else, leave duration alone; timing estimation in utils.c
  324. * will make a guess based on bitrate.
  325. */
  326. stream_index = s->nb_streams - 1;
  327. url_fskip(pb, size - 9*4);
  328. break;
  329. }
  330. assert(stream_index < s->nb_streams);
  331. st->codec->stream_codec_tag= handler;
  332. get_le32(pb); /* flags */
  333. get_le16(pb); /* priority */
  334. get_le16(pb); /* language */
  335. get_le32(pb); /* initial frame */
  336. ast->scale = get_le32(pb);
  337. ast->rate = get_le32(pb);
  338. if(!(ast->scale && ast->rate)){
  339. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  340. if(frame_period){
  341. ast->rate = 1000000;
  342. ast->scale = frame_period;
  343. }else{
  344. ast->rate = 25;
  345. ast->scale = 1;
  346. }
  347. }
  348. av_set_pts_info(st, 64, ast->scale, ast->rate);
  349. ast->cum_len=get_le32(pb); /* start */
  350. nb_frames = get_le32(pb);
  351. st->start_time = 0;
  352. st->duration = nb_frames;
  353. get_le32(pb); /* buffer size */
  354. get_le32(pb); /* quality */
  355. ast->sample_size = get_le32(pb); /* sample ssize */
  356. ast->cum_len *= FFMAX(1, ast->sample_size);
  357. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  358. switch(tag1) {
  359. case MKTAG('v', 'i', 'd', 's'):
  360. codec_type = CODEC_TYPE_VIDEO;
  361. ast->sample_size = 0;
  362. break;
  363. case MKTAG('a', 'u', 'd', 's'):
  364. codec_type = CODEC_TYPE_AUDIO;
  365. break;
  366. case MKTAG('t', 'x', 't', 's'):
  367. //FIXME
  368. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  369. break;
  370. case MKTAG('d', 'a', 't', 's'):
  371. codec_type = CODEC_TYPE_DATA;
  372. break;
  373. default:
  374. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  375. goto fail;
  376. }
  377. ast->frame_offset= ast->cum_len;
  378. url_fskip(pb, size - 12 * 4);
  379. break;
  380. case MKTAG('s', 't', 'r', 'f'):
  381. /* stream header */
  382. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  383. url_fskip(pb, size);
  384. } else {
  385. st = s->streams[stream_index];
  386. switch(codec_type) {
  387. case CODEC_TYPE_VIDEO:
  388. if(amv_file_format){
  389. st->codec->width=avih_width;
  390. st->codec->height=avih_height;
  391. st->codec->codec_type = CODEC_TYPE_VIDEO;
  392. st->codec->codec_id = CODEC_ID_AMV;
  393. url_fskip(pb, size);
  394. break;
  395. }
  396. get_le32(pb); /* size */
  397. st->codec->width = get_le32(pb);
  398. st->codec->height = (int32_t)get_le32(pb);
  399. get_le16(pb); /* panes */
  400. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  401. tag1 = get_le32(pb);
  402. get_le32(pb); /* ImageSize */
  403. get_le32(pb); /* XPelsPerMeter */
  404. get_le32(pb); /* YPelsPerMeter */
  405. get_le32(pb); /* ClrUsed */
  406. get_le32(pb); /* ClrImportant */
  407. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  408. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  409. st->codec->codec_tag = tag1;
  410. st->codec->codec_id = CODEC_ID_XSUB;
  411. break;
  412. }
  413. if(size > 10*4 && size<(1<<30)){
  414. st->codec->extradata_size= size - 10*4;
  415. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  416. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  417. }
  418. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  419. get_byte(pb);
  420. /* Extract palette from extradata if bpp <= 8. */
  421. /* This code assumes that extradata contains only palette. */
  422. /* This is true for all paletted codecs implemented in FFmpeg. */
  423. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  424. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  425. #ifdef WORDS_BIGENDIAN
  426. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  427. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  428. #else
  429. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  430. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  431. #endif
  432. st->codec->palctrl->palette_changed = 1;
  433. }
  434. #ifdef DEBUG
  435. print_tag("video", tag1, 0);
  436. #endif
  437. st->codec->codec_type = CODEC_TYPE_VIDEO;
  438. st->codec->codec_tag = tag1;
  439. st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
  440. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  441. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  442. st->codec->extradata_size+= 9;
  443. st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  444. if(st->codec->extradata)
  445. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  446. }
  447. st->codec->height= FFABS(st->codec->height);
  448. // url_fskip(pb, size - 5 * 4);
  449. break;
  450. case CODEC_TYPE_AUDIO:
  451. get_wav_header(pb, st->codec, size);
  452. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  453. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  454. ast->sample_size= st->codec->block_align;
  455. }
  456. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  457. url_fskip(pb, 1);
  458. /* Force parsing as several audio frames can be in
  459. * one packet and timestamps refer to packet start. */
  460. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  461. /* ADTS header is in extradata, AAC without header must be
  462. * stored as exact frames. Parser not needed and it will
  463. * fail. */
  464. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  465. st->need_parsing = AVSTREAM_PARSE_NONE;
  466. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  467. * audio in the header but have Axan as stream_code_tag. */
  468. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  469. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  470. st->codec->codec_tag = 0;
  471. }
  472. if (amv_file_format)
  473. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  474. break;
  475. default:
  476. st->codec->codec_type = CODEC_TYPE_DATA;
  477. st->codec->codec_id= CODEC_ID_NONE;
  478. st->codec->codec_tag= 0;
  479. url_fskip(pb, size);
  480. break;
  481. }
  482. }
  483. break;
  484. case MKTAG('i', 'n', 'd', 'x'):
  485. i= url_ftell(pb);
  486. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  487. read_braindead_odml_indx(s, 0);
  488. }
  489. url_fseek(pb, i+size, SEEK_SET);
  490. break;
  491. case MKTAG('v', 'p', 'r', 'p'):
  492. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  493. AVRational active, active_aspect;
  494. st = s->streams[stream_index];
  495. get_le32(pb);
  496. get_le32(pb);
  497. get_le32(pb);
  498. get_le32(pb);
  499. get_le32(pb);
  500. active_aspect.den= get_le16(pb);
  501. active_aspect.num= get_le16(pb);
  502. active.num = get_le32(pb);
  503. active.den = get_le32(pb);
  504. get_le32(pb); //nbFieldsPerFrame
  505. if(active_aspect.num && active_aspect.den && active.num && active.den){
  506. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  507. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  508. }
  509. size -= 9*4;
  510. }
  511. url_fseek(pb, size, SEEK_CUR);
  512. break;
  513. case MKTAG('I', 'N', 'A', 'M'):
  514. avi_read_tag(s, "Title", size);
  515. break;
  516. case MKTAG('I', 'A', 'R', 'T'):
  517. avi_read_tag(s, "Artist", size);
  518. break;
  519. case MKTAG('I', 'C', 'O', 'P'):
  520. avi_read_tag(s, "Copyright", size);
  521. break;
  522. case MKTAG('I', 'C', 'M', 'T'):
  523. avi_read_tag(s, "Comment", size);
  524. break;
  525. case MKTAG('I', 'G', 'N', 'R'):
  526. avi_read_tag(s, "Genre", size);
  527. break;
  528. case MKTAG('I', 'P', 'R', 'D'):
  529. avi_read_tag(s, "Album", size);
  530. break;
  531. case MKTAG('I', 'P', 'R', 'T'):
  532. avi_read_tag(s, "Track", size);
  533. break;
  534. default:
  535. if(size > 1000000){
  536. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  537. "I will ignore it and try to continue anyway.\n");
  538. avi->movi_list = url_ftell(pb) - 4;
  539. avi->movi_end = url_fsize(pb);
  540. goto end_of_header;
  541. }
  542. /* skip tag */
  543. size += (size & 1);
  544. url_fskip(pb, size);
  545. break;
  546. }
  547. }
  548. end_of_header:
  549. /* check stream number */
  550. if (stream_index != s->nb_streams - 1) {
  551. fail:
  552. return -1;
  553. }
  554. if(!avi->index_loaded && !url_is_streamed(pb))
  555. avi_load_index(s);
  556. avi->index_loaded = 1;
  557. avi->non_interleaved |= guess_ni_flag(s);
  558. if(avi->non_interleaved) {
  559. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  560. clean_index(s);
  561. }
  562. return 0;
  563. }
  564. static int get_stream_idx(int *d){
  565. if( d[0] >= '0' && d[0] <= '9'
  566. && d[1] >= '0' && d[1] <= '9'){
  567. return (d[0] - '0') * 10 + (d[1] - '0');
  568. }else{
  569. return 100; //invalid stream ID
  570. }
  571. }
  572. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  573. {
  574. AVIContext *avi = s->priv_data;
  575. ByteIOContext *pb = s->pb;
  576. int n, d[8];
  577. unsigned int size;
  578. int64_t i, sync;
  579. void* dstr;
  580. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  581. int size = dv_get_packet(avi->dv_demux, pkt);
  582. if (size >= 0)
  583. return size;
  584. }
  585. if(avi->non_interleaved){
  586. int best_stream_index = 0;
  587. AVStream *best_st= NULL;
  588. AVIStream *best_ast;
  589. int64_t best_ts= INT64_MAX;
  590. int i;
  591. for(i=0; i<s->nb_streams; i++){
  592. AVStream *st = s->streams[i];
  593. AVIStream *ast = st->priv_data;
  594. int64_t ts= ast->frame_offset;
  595. if(ast->sample_size)
  596. ts /= ast->sample_size;
  597. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  598. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  599. if(ts < best_ts && st->nb_index_entries){
  600. best_ts= ts;
  601. best_st= st;
  602. best_stream_index= i;
  603. }
  604. }
  605. if(!best_st)
  606. return -1;
  607. best_ast = best_st->priv_data;
  608. best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
  609. if(best_ast->remaining)
  610. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  611. else{
  612. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  613. if(i>=0)
  614. best_ast->frame_offset= best_st->index_entries[i].timestamp
  615. * FFMAX(1, best_ast->sample_size);
  616. }
  617. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  618. if(i>=0){
  619. int64_t pos= best_st->index_entries[i].pos;
  620. pos += best_ast->packet_size - best_ast->remaining;
  621. url_fseek(s->pb, pos + 8, SEEK_SET);
  622. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  623. assert(best_ast->remaining <= best_ast->packet_size);
  624. avi->stream_index= best_stream_index;
  625. if(!best_ast->remaining)
  626. best_ast->packet_size=
  627. best_ast->remaining= best_st->index_entries[i].size;
  628. }
  629. }
  630. resync:
  631. if(avi->stream_index >= 0){
  632. AVStream *st= s->streams[ avi->stream_index ];
  633. AVIStream *ast= st->priv_data;
  634. int size, err;
  635. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  636. size= INT_MAX;
  637. else if(ast->sample_size < 32)
  638. size= 64*ast->sample_size;
  639. else
  640. size= ast->sample_size;
  641. if(size > ast->remaining)
  642. size= ast->remaining;
  643. avi->last_pkt_pos= url_ftell(pb);
  644. err= av_get_packet(pb, pkt, size);
  645. if(err<0)
  646. return err;
  647. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  648. void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
  649. if(ptr){
  650. ast->has_pal=0;
  651. pkt->size += 4*256;
  652. pkt->data= ptr;
  653. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  654. }else
  655. av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
  656. }
  657. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  658. dstr = pkt->destruct;
  659. size = dv_produce_packet(avi->dv_demux, pkt,
  660. pkt->data, pkt->size);
  661. pkt->destruct = dstr;
  662. pkt->flags |= PKT_FLAG_KEY;
  663. } else {
  664. /* XXX: How to handle B-frames in AVI? */
  665. pkt->dts = ast->frame_offset;
  666. // pkt->dts += ast->start;
  667. if(ast->sample_size)
  668. pkt->dts /= ast->sample_size;
  669. //av_log(s, AV_LOG_DEBUG, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n", pkt->dts, ast->frame_offset, ast->scale, ast->rate, ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  670. pkt->stream_index = avi->stream_index;
  671. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  672. AVIndexEntry *e;
  673. int index;
  674. assert(st->index_entries);
  675. index= av_index_search_timestamp(st, pkt->dts, 0);
  676. e= &st->index_entries[index];
  677. if(index >= 0 && e->timestamp == ast->frame_offset){
  678. if (e->flags & AVINDEX_KEYFRAME)
  679. pkt->flags |= PKT_FLAG_KEY;
  680. }
  681. } else {
  682. pkt->flags |= PKT_FLAG_KEY;
  683. }
  684. if(ast->sample_size)
  685. ast->frame_offset += pkt->size;
  686. else
  687. ast->frame_offset++;
  688. }
  689. ast->remaining -= err;
  690. if(!ast->remaining){
  691. avi->stream_index= -1;
  692. ast->packet_size= 0;
  693. }
  694. return 0;
  695. }
  696. memset(d, -1, sizeof(int)*8);
  697. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  698. int j;
  699. for(j=0; j<7; j++)
  700. d[j]= d[j+1];
  701. d[7]= get_byte(pb);
  702. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  703. n= get_stream_idx(d+2);
  704. //av_log(s, AV_LOG_DEBUG, "%X %X %X %X %X %X %X %X %"PRId64" %d %d\n", d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  705. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  706. continue;
  707. //parse ix##
  708. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  709. //parse JUNK
  710. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  711. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  712. url_fskip(pb, size);
  713. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  714. goto resync;
  715. }
  716. n= get_stream_idx(d);
  717. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  718. continue;
  719. //parse ##dc/##wb
  720. if(n < s->nb_streams){
  721. AVStream *st;
  722. AVIStream *ast;
  723. st = s->streams[n];
  724. ast = st->priv_data;
  725. if(s->nb_streams>=2){
  726. AVStream *st1 = s->streams[1];
  727. AVIStream *ast1= st1->priv_data;
  728. //workaround for broken small-file-bug402.avi
  729. if( d[2] == 'w' && d[3] == 'b'
  730. && n==0
  731. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  732. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  733. && ast->prefix == 'd'*256+'c'
  734. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  735. ){
  736. n=1;
  737. st = st1;
  738. ast = ast1;
  739. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  740. }
  741. }
  742. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  743. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  744. || st->discard >= AVDISCARD_ALL){
  745. if(ast->sample_size) ast->frame_offset += pkt->size;
  746. else ast->frame_offset++;
  747. url_fskip(pb, size);
  748. goto resync;
  749. }
  750. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  751. int k = get_byte(pb);
  752. int last = (k + get_byte(pb) - 1) & 0xFF;
  753. get_le16(pb); //flags
  754. for (; k <= last; k++)
  755. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  756. ast->has_pal= 1;
  757. goto resync;
  758. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  759. d[2]*256+d[3] == ast->prefix /*||
  760. (d[2] == 'd' && d[3] == 'c') ||
  761. (d[2] == 'w' && d[3] == 'b')*/) {
  762. //av_log(s, AV_LOG_DEBUG, "OK\n");
  763. if(d[2]*256+d[3] == ast->prefix)
  764. ast->prefix_count++;
  765. else{
  766. ast->prefix= d[2]*256+d[3];
  767. ast->prefix_count= 0;
  768. }
  769. avi->stream_index= n;
  770. ast->packet_size= size + 8;
  771. ast->remaining= size;
  772. {
  773. uint64_t pos= url_ftell(pb) - 8;
  774. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  775. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  776. }
  777. }
  778. goto resync;
  779. }
  780. }
  781. }
  782. return AVERROR_EOF;
  783. }
  784. /* XXX: We make the implicit supposition that the positions are sorted
  785. for each stream. */
  786. static int avi_read_idx1(AVFormatContext *s, int size)
  787. {
  788. AVIContext *avi = s->priv_data;
  789. ByteIOContext *pb = s->pb;
  790. int nb_index_entries, i;
  791. AVStream *st;
  792. AVIStream *ast;
  793. unsigned int index, tag, flags, pos, len;
  794. unsigned last_pos= -1;
  795. nb_index_entries = size / 16;
  796. if (nb_index_entries <= 0)
  797. return -1;
  798. /* Read the entries and sort them in each stream component. */
  799. for(i = 0; i < nb_index_entries; i++) {
  800. tag = get_le32(pb);
  801. flags = get_le32(pb);
  802. pos = get_le32(pb);
  803. len = get_le32(pb);
  804. #if defined(DEBUG_SEEK)
  805. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  806. i, tag, flags, pos, len);
  807. #endif
  808. if(i==0 && pos > avi->movi_list)
  809. avi->movi_list= 0; //FIXME better check
  810. pos += avi->movi_list;
  811. index = ((tag & 0xff) - '0') * 10;
  812. index += ((tag >> 8) & 0xff) - '0';
  813. if (index >= s->nb_streams)
  814. continue;
  815. st = s->streams[index];
  816. ast = st->priv_data;
  817. #if defined(DEBUG_SEEK)
  818. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  819. #endif
  820. if(url_feof(pb))
  821. return -1;
  822. if(last_pos == pos)
  823. avi->non_interleaved= 1;
  824. else
  825. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  826. if(ast->sample_size)
  827. ast->cum_len += len;
  828. else
  829. ast->cum_len ++;
  830. last_pos= pos;
  831. }
  832. return 0;
  833. }
  834. static int guess_ni_flag(AVFormatContext *s){
  835. int i;
  836. int64_t last_start=0;
  837. int64_t first_end= INT64_MAX;
  838. for(i=0; i<s->nb_streams; i++){
  839. AVStream *st = s->streams[i];
  840. int n= st->nb_index_entries;
  841. if(n <= 0)
  842. continue;
  843. if(st->index_entries[0].pos > last_start)
  844. last_start= st->index_entries[0].pos;
  845. if(st->index_entries[n-1].pos < first_end)
  846. first_end= st->index_entries[n-1].pos;
  847. }
  848. return last_start > first_end;
  849. }
  850. static int avi_load_index(AVFormatContext *s)
  851. {
  852. AVIContext *avi = s->priv_data;
  853. ByteIOContext *pb = s->pb;
  854. uint32_t tag, size;
  855. int64_t pos= url_ftell(pb);
  856. url_fseek(pb, avi->movi_end, SEEK_SET);
  857. #ifdef DEBUG_SEEK
  858. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  859. #endif
  860. for(;;) {
  861. if (url_feof(pb))
  862. break;
  863. tag = get_le32(pb);
  864. size = get_le32(pb);
  865. #ifdef DEBUG_SEEK
  866. printf("tag=%c%c%c%c size=0x%x\n",
  867. tag & 0xff,
  868. (tag >> 8) & 0xff,
  869. (tag >> 16) & 0xff,
  870. (tag >> 24) & 0xff,
  871. size);
  872. #endif
  873. switch(tag) {
  874. case MKTAG('i', 'd', 'x', '1'):
  875. if (avi_read_idx1(s, size) < 0)
  876. goto skip;
  877. else
  878. goto the_end;
  879. break;
  880. default:
  881. skip:
  882. size += (size & 1);
  883. url_fskip(pb, size);
  884. break;
  885. }
  886. }
  887. the_end:
  888. url_fseek(pb, pos, SEEK_SET);
  889. return 0;
  890. }
  891. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  892. {
  893. AVIContext *avi = s->priv_data;
  894. AVStream *st;
  895. int i, index;
  896. int64_t pos;
  897. if (!avi->index_loaded) {
  898. /* we only load the index on demand */
  899. avi_load_index(s);
  900. avi->index_loaded = 1;
  901. }
  902. assert(stream_index>= 0);
  903. st = s->streams[stream_index];
  904. index= av_index_search_timestamp(st, timestamp, flags);
  905. if(index<0)
  906. return -1;
  907. /* find the position */
  908. pos = st->index_entries[index].pos;
  909. timestamp = st->index_entries[index].timestamp;
  910. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  911. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  912. /* One and only one real stream for DV in AVI, and it has video */
  913. /* offsets. Calling with other stream indexes should have failed */
  914. /* the av_index_search_timestamp call above. */
  915. assert(stream_index == 0);
  916. /* Feed the DV video stream version of the timestamp to the */
  917. /* DV demux so it can synthesize correct timestamps. */
  918. dv_offset_reset(avi->dv_demux, timestamp);
  919. url_fseek(s->pb, pos, SEEK_SET);
  920. avi->stream_index= -1;
  921. return 0;
  922. }
  923. for(i = 0; i < s->nb_streams; i++) {
  924. AVStream *st2 = s->streams[i];
  925. AVIStream *ast2 = st2->priv_data;
  926. ast2->packet_size=
  927. ast2->remaining= 0;
  928. if (st2->nb_index_entries <= 0)
  929. continue;
  930. // assert(st2->codec->block_align);
  931. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  932. index = av_index_search_timestamp(
  933. st2,
  934. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  935. flags | AVSEEK_FLAG_BACKWARD);
  936. if(index<0)
  937. index=0;
  938. if(!avi->non_interleaved){
  939. while(index>0 && st2->index_entries[index].pos > pos)
  940. index--;
  941. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  942. index++;
  943. }
  944. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  945. /* extract the current frame number */
  946. ast2->frame_offset = st2->index_entries[index].timestamp;
  947. if(ast2->sample_size)
  948. ast2->frame_offset *=ast2->sample_size;
  949. }
  950. /* do the seek */
  951. url_fseek(s->pb, pos, SEEK_SET);
  952. avi->stream_index= -1;
  953. return 0;
  954. }
  955. static int avi_read_close(AVFormatContext *s)
  956. {
  957. int i;
  958. AVIContext *avi = s->priv_data;
  959. for(i=0;i<s->nb_streams;i++) {
  960. AVStream *st = s->streams[i];
  961. av_free(st->codec->palctrl);
  962. }
  963. if (avi->dv_demux)
  964. av_free(avi->dv_demux);
  965. return 0;
  966. }
  967. static int avi_probe(AVProbeData *p)
  968. {
  969. int i;
  970. /* check file header */
  971. for(i=0; avi_headers[i][0]; i++)
  972. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  973. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  974. return AVPROBE_SCORE_MAX;
  975. return 0;
  976. }
  977. AVInputFormat avi_demuxer = {
  978. "avi",
  979. NULL_IF_CONFIG_SMALL("AVI format"),
  980. sizeof(AVIContext),
  981. avi_probe,
  982. avi_read_header,
  983. avi_read_packet,
  984. avi_read_close,
  985. avi_read_seek,
  986. };