avidec.c 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  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. //#define DEBUG
  22. //#define DEBUG_SEEK
  23. #include "libavutil/intreadwrite.h"
  24. #include "libavutil/bswap.h"
  25. #include "avformat.h"
  26. #include "avi.h"
  27. #include "dv.h"
  28. #include "riff.h"
  29. #undef NDEBUG
  30. #include <assert.h>
  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. dprintf(NULL, "%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 && (len || !ast->sample_size))
  148. av_add_index_entry(st, pos, ast->cum_len, 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, 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. char *value;
  196. size += (size & 1);
  197. if (size == UINT_MAX)
  198. return -1;
  199. value = av_malloc(size+1);
  200. if (!value)
  201. return -1;
  202. get_strz(pb, value, size);
  203. return av_metadata_set2(&s->metadata, key, value,
  204. AV_METADATA_DONT_STRDUP_VAL);
  205. }
  206. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  207. {
  208. AVIContext *avi = s->priv_data;
  209. ByteIOContext *pb = s->pb;
  210. unsigned int tag, tag1, handler;
  211. int codec_type, stream_index, frame_period, bit_rate;
  212. unsigned int size, nb_frames;
  213. int i;
  214. AVStream *st;
  215. AVIStream *ast = NULL;
  216. int avih_width=0, avih_height=0;
  217. int amv_file_format=0;
  218. uint64_t list_end = 0;
  219. avi->stream_index= -1;
  220. if (get_riff(s, pb) < 0)
  221. return -1;
  222. avi->fsize = url_fsize(pb);
  223. if(avi->fsize<=0)
  224. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  225. /* first list tag */
  226. stream_index = -1;
  227. codec_type = -1;
  228. frame_period = 0;
  229. for(;;) {
  230. if (url_feof(pb))
  231. goto fail;
  232. tag = get_le32(pb);
  233. size = get_le32(pb);
  234. #ifdef DEBUG
  235. print_tag("tag", tag, size);
  236. #endif
  237. switch(tag) {
  238. case MKTAG('L', 'I', 'S', 'T'):
  239. list_end = url_ftell(pb) + size;
  240. /* Ignored, except at start of video packets. */
  241. tag1 = get_le32(pb);
  242. #ifdef DEBUG
  243. print_tag("list", tag1, 0);
  244. #endif
  245. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  246. avi->movi_list = url_ftell(pb) - 4;
  247. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  248. else avi->movi_end = url_fsize(pb);
  249. dprintf(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  250. goto end_of_header;
  251. }
  252. break;
  253. case MKTAG('d', 'm', 'l', 'h'):
  254. avi->is_odml = 1;
  255. url_fskip(pb, size + (size & 1));
  256. break;
  257. case MKTAG('a', 'm', 'v', 'h'):
  258. amv_file_format=1;
  259. case MKTAG('a', 'v', 'i', 'h'):
  260. /* AVI header */
  261. /* using frame_period is bad idea */
  262. frame_period = get_le32(pb);
  263. bit_rate = get_le32(pb) * 8;
  264. get_le32(pb);
  265. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  266. url_fskip(pb, 2 * 4);
  267. get_le32(pb);
  268. get_le32(pb);
  269. avih_width=get_le32(pb);
  270. avih_height=get_le32(pb);
  271. url_fskip(pb, size - 10 * 4);
  272. break;
  273. case MKTAG('s', 't', 'r', 'h'):
  274. /* stream header */
  275. tag1 = get_le32(pb);
  276. handler = get_le32(pb); /* codec tag */
  277. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  278. url_fskip(pb, size - 8);
  279. break;
  280. }else{
  281. stream_index++;
  282. st = av_new_stream(s, stream_index);
  283. if (!st)
  284. goto fail;
  285. ast = av_mallocz(sizeof(AVIStream));
  286. if (!ast)
  287. goto fail;
  288. st->priv_data = ast;
  289. }
  290. if(amv_file_format)
  291. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  292. #ifdef DEBUG
  293. print_tag("strh", tag1, -1);
  294. #endif
  295. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  296. int64_t dv_dur;
  297. /*
  298. * After some consideration -- I don't think we
  299. * have to support anything but DV in type1 AVIs.
  300. */
  301. if (s->nb_streams != 1)
  302. goto fail;
  303. if (handler != MKTAG('d', 'v', 's', 'd') &&
  304. handler != MKTAG('d', 'v', 'h', 'd') &&
  305. handler != MKTAG('d', 'v', 's', 'l'))
  306. goto fail;
  307. ast = s->streams[0]->priv_data;
  308. av_freep(&s->streams[0]->codec->extradata);
  309. av_freep(&s->streams[0]);
  310. s->nb_streams = 0;
  311. if (CONFIG_DV_DEMUXER) {
  312. avi->dv_demux = dv_init_demux(s);
  313. if (!avi->dv_demux)
  314. goto fail;
  315. }
  316. s->streams[0]->priv_data = ast;
  317. url_fskip(pb, 3 * 4);
  318. ast->scale = get_le32(pb);
  319. ast->rate = get_le32(pb);
  320. url_fskip(pb, 4); /* start time */
  321. dv_dur = get_le32(pb);
  322. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  323. dv_dur *= AV_TIME_BASE;
  324. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  325. }
  326. /*
  327. * else, leave duration alone; timing estimation in utils.c
  328. * will make a guess based on bitrate.
  329. */
  330. stream_index = s->nb_streams - 1;
  331. url_fskip(pb, size - 9*4);
  332. break;
  333. }
  334. assert(stream_index < s->nb_streams);
  335. st->codec->stream_codec_tag= handler;
  336. get_le32(pb); /* flags */
  337. get_le16(pb); /* priority */
  338. get_le16(pb); /* language */
  339. get_le32(pb); /* initial frame */
  340. ast->scale = get_le32(pb);
  341. ast->rate = get_le32(pb);
  342. if(!(ast->scale && ast->rate)){
  343. 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);
  344. if(frame_period){
  345. ast->rate = 1000000;
  346. ast->scale = frame_period;
  347. }else{
  348. ast->rate = 25;
  349. ast->scale = 1;
  350. }
  351. }
  352. av_set_pts_info(st, 64, ast->scale, ast->rate);
  353. ast->cum_len=get_le32(pb); /* start */
  354. nb_frames = get_le32(pb);
  355. st->start_time = 0;
  356. st->duration = nb_frames;
  357. get_le32(pb); /* buffer size */
  358. get_le32(pb); /* quality */
  359. ast->sample_size = get_le32(pb); /* sample ssize */
  360. ast->cum_len *= FFMAX(1, ast->sample_size);
  361. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  362. switch(tag1) {
  363. case MKTAG('v', 'i', 'd', 's'):
  364. codec_type = CODEC_TYPE_VIDEO;
  365. ast->sample_size = 0;
  366. break;
  367. case MKTAG('a', 'u', 'd', 's'):
  368. codec_type = CODEC_TYPE_AUDIO;
  369. break;
  370. case MKTAG('t', 'x', 't', 's'):
  371. //FIXME
  372. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  373. break;
  374. case MKTAG('d', 'a', 't', 's'):
  375. codec_type = CODEC_TYPE_DATA;
  376. break;
  377. default:
  378. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  379. goto fail;
  380. }
  381. ast->frame_offset= ast->cum_len;
  382. url_fskip(pb, size - 12 * 4);
  383. break;
  384. case MKTAG('s', 't', 'r', 'f'):
  385. /* stream header */
  386. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  387. url_fskip(pb, size);
  388. } else {
  389. uint64_t cur_pos = url_ftell(pb);
  390. if (cur_pos < list_end)
  391. size = FFMIN(size, list_end - cur_pos);
  392. st = s->streams[stream_index];
  393. switch(codec_type) {
  394. case CODEC_TYPE_VIDEO:
  395. if(amv_file_format){
  396. st->codec->width=avih_width;
  397. st->codec->height=avih_height;
  398. st->codec->codec_type = CODEC_TYPE_VIDEO;
  399. st->codec->codec_id = CODEC_ID_AMV;
  400. url_fskip(pb, size);
  401. break;
  402. }
  403. get_le32(pb); /* size */
  404. st->codec->width = get_le32(pb);
  405. st->codec->height = (int32_t)get_le32(pb);
  406. get_le16(pb); /* panes */
  407. st->codec->bits_per_coded_sample= get_le16(pb); /* depth */
  408. tag1 = get_le32(pb);
  409. get_le32(pb); /* ImageSize */
  410. get_le32(pb); /* XPelsPerMeter */
  411. get_le32(pb); /* YPelsPerMeter */
  412. get_le32(pb); /* ClrUsed */
  413. get_le32(pb); /* ClrImportant */
  414. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  415. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  416. st->codec->codec_tag = tag1;
  417. st->codec->codec_id = CODEC_ID_XSUB;
  418. break;
  419. }
  420. if(size > 10*4 && size<(1<<30)){
  421. st->codec->extradata_size= size - 10*4;
  422. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  423. if (!st->codec->extradata) {
  424. st->codec->extradata_size= 0;
  425. return AVERROR(ENOMEM);
  426. }
  427. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  428. }
  429. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  430. get_byte(pb);
  431. /* Extract palette from extradata if bpp <= 8. */
  432. /* This code assumes that extradata contains only palette. */
  433. /* This is true for all paletted codecs implemented in FFmpeg. */
  434. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  435. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  436. #if HAVE_BIGENDIAN
  437. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  438. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  439. #else
  440. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  441. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  442. #endif
  443. st->codec->palctrl->palette_changed = 1;
  444. }
  445. #ifdef DEBUG
  446. print_tag("video", tag1, 0);
  447. #endif
  448. st->codec->codec_type = CODEC_TYPE_VIDEO;
  449. st->codec->codec_tag = tag1;
  450. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  451. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  452. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  453. st->codec->extradata_size+= 9;
  454. st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  455. if(st->codec->extradata)
  456. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  457. }
  458. st->codec->height= FFABS(st->codec->height);
  459. // url_fskip(pb, size - 5 * 4);
  460. break;
  461. case CODEC_TYPE_AUDIO:
  462. ff_get_wav_header(pb, st->codec, size);
  463. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  464. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  465. ast->sample_size= st->codec->block_align;
  466. }
  467. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  468. url_fskip(pb, 1);
  469. /* Force parsing as several audio frames can be in
  470. * one packet and timestamps refer to packet start. */
  471. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  472. /* ADTS header is in extradata, AAC without header must be
  473. * stored as exact frames. Parser not needed and it will
  474. * fail. */
  475. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  476. st->need_parsing = AVSTREAM_PARSE_NONE;
  477. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  478. * audio in the header but have Axan as stream_code_tag. */
  479. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  480. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  481. st->codec->codec_tag = 0;
  482. }
  483. if (amv_file_format)
  484. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  485. break;
  486. default:
  487. st->codec->codec_type = CODEC_TYPE_DATA;
  488. st->codec->codec_id= CODEC_ID_NONE;
  489. st->codec->codec_tag= 0;
  490. url_fskip(pb, size);
  491. break;
  492. }
  493. }
  494. break;
  495. case MKTAG('i', 'n', 'd', 'x'):
  496. i= url_ftell(pb);
  497. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  498. read_braindead_odml_indx(s, 0);
  499. }
  500. url_fseek(pb, i+size, SEEK_SET);
  501. break;
  502. case MKTAG('v', 'p', 'r', 'p'):
  503. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  504. AVRational active, active_aspect;
  505. st = s->streams[stream_index];
  506. get_le32(pb);
  507. get_le32(pb);
  508. get_le32(pb);
  509. get_le32(pb);
  510. get_le32(pb);
  511. active_aspect.den= get_le16(pb);
  512. active_aspect.num= get_le16(pb);
  513. active.num = get_le32(pb);
  514. active.den = get_le32(pb);
  515. get_le32(pb); //nbFieldsPerFrame
  516. if(active_aspect.num && active_aspect.den && active.num && active.den){
  517. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  518. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  519. }
  520. size -= 9*4;
  521. }
  522. url_fseek(pb, size, SEEK_CUR);
  523. break;
  524. case MKTAG('I', 'N', 'A', 'M'):
  525. avi_read_tag(s, "Title", size);
  526. break;
  527. case MKTAG('I', 'A', 'R', 'T'):
  528. avi_read_tag(s, "Artist", size);
  529. break;
  530. case MKTAG('I', 'C', 'O', 'P'):
  531. avi_read_tag(s, "Copyright", size);
  532. break;
  533. case MKTAG('I', 'C', 'M', 'T'):
  534. avi_read_tag(s, "Comment", size);
  535. break;
  536. case MKTAG('I', 'G', 'N', 'R'):
  537. avi_read_tag(s, "Genre", size);
  538. break;
  539. case MKTAG('I', 'P', 'R', 'D'):
  540. avi_read_tag(s, "Album", size);
  541. break;
  542. case MKTAG('I', 'P', 'R', 'T'):
  543. avi_read_tag(s, "Track", size);
  544. break;
  545. default:
  546. if(size > 1000000){
  547. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  548. "I will ignore it and try to continue anyway.\n");
  549. avi->movi_list = url_ftell(pb) - 4;
  550. avi->movi_end = url_fsize(pb);
  551. goto end_of_header;
  552. }
  553. /* skip tag */
  554. size += (size & 1);
  555. url_fskip(pb, size);
  556. break;
  557. }
  558. }
  559. end_of_header:
  560. /* check stream number */
  561. if (stream_index != s->nb_streams - 1) {
  562. fail:
  563. return -1;
  564. }
  565. if(!avi->index_loaded && !url_is_streamed(pb))
  566. avi_load_index(s);
  567. avi->index_loaded = 1;
  568. avi->non_interleaved |= guess_ni_flag(s);
  569. if(avi->non_interleaved) {
  570. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  571. clean_index(s);
  572. }
  573. return 0;
  574. }
  575. static int get_stream_idx(int *d){
  576. if( d[0] >= '0' && d[0] <= '9'
  577. && d[1] >= '0' && d[1] <= '9'){
  578. return (d[0] - '0') * 10 + (d[1] - '0');
  579. }else{
  580. return 100; //invalid stream ID
  581. }
  582. }
  583. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  584. {
  585. AVIContext *avi = s->priv_data;
  586. ByteIOContext *pb = s->pb;
  587. int n, d[8];
  588. unsigned int size;
  589. int64_t i, sync;
  590. void* dstr;
  591. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  592. int size = dv_get_packet(avi->dv_demux, pkt);
  593. if (size >= 0)
  594. return size;
  595. }
  596. if(avi->non_interleaved){
  597. int best_stream_index = 0;
  598. AVStream *best_st= NULL;
  599. AVIStream *best_ast;
  600. int64_t best_ts= INT64_MAX;
  601. int i;
  602. for(i=0; i<s->nb_streams; i++){
  603. AVStream *st = s->streams[i];
  604. AVIStream *ast = st->priv_data;
  605. int64_t ts= ast->frame_offset;
  606. int64_t last_ts;
  607. if(!st->nb_index_entries)
  608. continue;
  609. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  610. if(!ast->remaining && ts > last_ts)
  611. continue;
  612. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  613. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  614. if(ts < best_ts){
  615. best_ts= ts;
  616. best_st= st;
  617. best_stream_index= i;
  618. }
  619. }
  620. if(!best_st)
  621. return -1;
  622. best_ast = best_st->priv_data;
  623. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  624. if(best_ast->remaining)
  625. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  626. else{
  627. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  628. if(i>=0)
  629. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  630. }
  631. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  632. if(i>=0){
  633. int64_t pos= best_st->index_entries[i].pos;
  634. pos += best_ast->packet_size - best_ast->remaining;
  635. url_fseek(s->pb, pos + 8, SEEK_SET);
  636. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  637. assert(best_ast->remaining <= best_ast->packet_size);
  638. avi->stream_index= best_stream_index;
  639. if(!best_ast->remaining)
  640. best_ast->packet_size=
  641. best_ast->remaining= best_st->index_entries[i].size;
  642. }
  643. }
  644. resync:
  645. if(avi->stream_index >= 0){
  646. AVStream *st= s->streams[ avi->stream_index ];
  647. AVIStream *ast= st->priv_data;
  648. int size, err;
  649. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  650. size= INT_MAX;
  651. else if(ast->sample_size < 32)
  652. size= 64*ast->sample_size;
  653. else
  654. size= ast->sample_size;
  655. if(size > ast->remaining)
  656. size= ast->remaining;
  657. avi->last_pkt_pos= url_ftell(pb);
  658. err= av_get_packet(pb, pkt, size);
  659. if(err<0)
  660. return err;
  661. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  662. void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
  663. if(ptr){
  664. ast->has_pal=0;
  665. pkt->size += 4*256;
  666. pkt->data= ptr;
  667. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  668. }else
  669. av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
  670. }
  671. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  672. dstr = pkt->destruct;
  673. size = dv_produce_packet(avi->dv_demux, pkt,
  674. pkt->data, pkt->size);
  675. pkt->destruct = dstr;
  676. pkt->flags |= PKT_FLAG_KEY;
  677. } else {
  678. /* XXX: How to handle B-frames in AVI? */
  679. pkt->dts = ast->frame_offset;
  680. // pkt->dts += ast->start;
  681. if(ast->sample_size)
  682. pkt->dts /= ast->sample_size;
  683. //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);
  684. pkt->stream_index = avi->stream_index;
  685. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  686. AVIndexEntry *e;
  687. int index;
  688. assert(st->index_entries);
  689. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  690. e= &st->index_entries[index];
  691. if(index >= 0 && e->timestamp == ast->frame_offset){
  692. if (e->flags & AVINDEX_KEYFRAME)
  693. pkt->flags |= PKT_FLAG_KEY;
  694. }
  695. } else {
  696. pkt->flags |= PKT_FLAG_KEY;
  697. }
  698. if(ast->sample_size)
  699. ast->frame_offset += pkt->size;
  700. else
  701. ast->frame_offset++;
  702. }
  703. ast->remaining -= size;
  704. if(!ast->remaining){
  705. avi->stream_index= -1;
  706. ast->packet_size= 0;
  707. }
  708. return size;
  709. }
  710. memset(d, -1, sizeof(int)*8);
  711. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  712. int j;
  713. for(j=0; j<7; j++)
  714. d[j]= d[j+1];
  715. d[7]= get_byte(pb);
  716. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  717. n= get_stream_idx(d+2);
  718. //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);
  719. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  720. continue;
  721. //parse ix##
  722. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  723. //parse JUNK
  724. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  725. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  726. url_fskip(pb, size);
  727. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  728. goto resync;
  729. }
  730. //parse stray LIST
  731. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  732. url_fskip(pb, 4);
  733. goto resync;
  734. }
  735. n= get_stream_idx(d);
  736. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  737. continue;
  738. //detect ##ix chunk and skip
  739. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  740. url_fskip(pb, size);
  741. goto resync;
  742. }
  743. //parse ##dc/##wb
  744. if(n < s->nb_streams){
  745. AVStream *st;
  746. AVIStream *ast;
  747. st = s->streams[n];
  748. ast = st->priv_data;
  749. if(s->nb_streams>=2){
  750. AVStream *st1 = s->streams[1];
  751. AVIStream *ast1= st1->priv_data;
  752. //workaround for broken small-file-bug402.avi
  753. if( d[2] == 'w' && d[3] == 'b'
  754. && n==0
  755. && st ->codec->codec_type == CODEC_TYPE_VIDEO
  756. && st1->codec->codec_type == CODEC_TYPE_AUDIO
  757. && ast->prefix == 'd'*256+'c'
  758. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  759. ){
  760. n=1;
  761. st = st1;
  762. ast = ast1;
  763. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  764. }
  765. }
  766. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  767. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  768. || st->discard >= AVDISCARD_ALL){
  769. if(ast->sample_size) ast->frame_offset += pkt->size;
  770. else ast->frame_offset++;
  771. url_fskip(pb, size);
  772. goto resync;
  773. }
  774. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  775. int k = get_byte(pb);
  776. int last = (k + get_byte(pb) - 1) & 0xFF;
  777. get_le16(pb); //flags
  778. for (; k <= last; k++)
  779. ast->pal[k] = get_be32(pb)>>8;// b + (g << 8) + (r << 16);
  780. ast->has_pal= 1;
  781. goto resync;
  782. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  783. d[2]*256+d[3] == ast->prefix /*||
  784. (d[2] == 'd' && d[3] == 'c') ||
  785. (d[2] == 'w' && d[3] == 'b')*/) {
  786. //av_log(s, AV_LOG_DEBUG, "OK\n");
  787. if(d[2]*256+d[3] == ast->prefix)
  788. ast->prefix_count++;
  789. else{
  790. ast->prefix= d[2]*256+d[3];
  791. ast->prefix_count= 0;
  792. }
  793. avi->stream_index= n;
  794. ast->packet_size= size + 8;
  795. ast->remaining= size;
  796. if(size || !ast->sample_size){
  797. uint64_t pos= url_ftell(pb) - 8;
  798. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  799. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  800. }
  801. }
  802. goto resync;
  803. }
  804. }
  805. }
  806. return AVERROR_EOF;
  807. }
  808. /* XXX: We make the implicit supposition that the positions are sorted
  809. for each stream. */
  810. static int avi_read_idx1(AVFormatContext *s, int size)
  811. {
  812. AVIContext *avi = s->priv_data;
  813. ByteIOContext *pb = s->pb;
  814. int nb_index_entries, i;
  815. AVStream *st;
  816. AVIStream *ast;
  817. unsigned int index, tag, flags, pos, len;
  818. unsigned last_pos= -1;
  819. nb_index_entries = size / 16;
  820. if (nb_index_entries <= 0)
  821. return -1;
  822. /* Read the entries and sort them in each stream component. */
  823. for(i = 0; i < nb_index_entries; i++) {
  824. tag = get_le32(pb);
  825. flags = get_le32(pb);
  826. pos = get_le32(pb);
  827. len = get_le32(pb);
  828. #if defined(DEBUG_SEEK)
  829. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  830. i, tag, flags, pos, len);
  831. #endif
  832. if(i==0 && pos > avi->movi_list)
  833. avi->movi_list= 0; //FIXME better check
  834. pos += avi->movi_list;
  835. index = ((tag & 0xff) - '0') * 10;
  836. index += ((tag >> 8) & 0xff) - '0';
  837. if (index >= s->nb_streams)
  838. continue;
  839. st = s->streams[index];
  840. ast = st->priv_data;
  841. #if defined(DEBUG_SEEK)
  842. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  843. #endif
  844. if(url_feof(pb))
  845. return -1;
  846. if(last_pos == pos)
  847. avi->non_interleaved= 1;
  848. else if(len || !ast->sample_size)
  849. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  850. if(ast->sample_size)
  851. ast->cum_len += len;
  852. else
  853. ast->cum_len ++;
  854. last_pos= pos;
  855. }
  856. return 0;
  857. }
  858. static int guess_ni_flag(AVFormatContext *s){
  859. int i;
  860. int64_t last_start=0;
  861. int64_t first_end= INT64_MAX;
  862. int64_t oldpos= url_ftell(s->pb);
  863. for(i=0; i<s->nb_streams; i++){
  864. AVStream *st = s->streams[i];
  865. int n= st->nb_index_entries;
  866. unsigned int size;
  867. if(n <= 0)
  868. continue;
  869. if(n >= 2){
  870. int64_t pos= st->index_entries[0].pos;
  871. url_fseek(s->pb, pos + 4, SEEK_SET);
  872. size= get_le32(s->pb);
  873. if(pos + size > st->index_entries[1].pos)
  874. last_start= INT64_MAX;
  875. }
  876. if(st->index_entries[0].pos > last_start)
  877. last_start= st->index_entries[0].pos;
  878. if(st->index_entries[n-1].pos < first_end)
  879. first_end= st->index_entries[n-1].pos;
  880. }
  881. url_fseek(s->pb, oldpos, SEEK_SET);
  882. return last_start > first_end;
  883. }
  884. static int avi_load_index(AVFormatContext *s)
  885. {
  886. AVIContext *avi = s->priv_data;
  887. ByteIOContext *pb = s->pb;
  888. uint32_t tag, size;
  889. int64_t pos= url_ftell(pb);
  890. int ret = -1;
  891. if (url_fseek(pb, avi->movi_end, SEEK_SET) < 0)
  892. goto the_end; // maybe truncated file
  893. #ifdef DEBUG_SEEK
  894. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  895. #endif
  896. for(;;) {
  897. if (url_feof(pb))
  898. break;
  899. tag = get_le32(pb);
  900. size = get_le32(pb);
  901. #ifdef DEBUG_SEEK
  902. printf("tag=%c%c%c%c size=0x%x\n",
  903. tag & 0xff,
  904. (tag >> 8) & 0xff,
  905. (tag >> 16) & 0xff,
  906. (tag >> 24) & 0xff,
  907. size);
  908. #endif
  909. switch(tag) {
  910. case MKTAG('i', 'd', 'x', '1'):
  911. if (avi_read_idx1(s, size) < 0)
  912. goto skip;
  913. ret = 0;
  914. goto the_end;
  915. break;
  916. default:
  917. skip:
  918. size += (size & 1);
  919. if (url_fseek(pb, size, SEEK_CUR) < 0)
  920. goto the_end; // something is wrong here
  921. break;
  922. }
  923. }
  924. the_end:
  925. url_fseek(pb, pos, SEEK_SET);
  926. return ret;
  927. }
  928. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  929. {
  930. AVIContext *avi = s->priv_data;
  931. AVStream *st;
  932. int i, index;
  933. int64_t pos;
  934. AVIStream *ast;
  935. if (!avi->index_loaded) {
  936. /* we only load the index on demand */
  937. avi_load_index(s);
  938. avi->index_loaded = 1;
  939. }
  940. assert(stream_index>= 0);
  941. st = s->streams[stream_index];
  942. ast= st->priv_data;
  943. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  944. if(index<0)
  945. return -1;
  946. /* find the position */
  947. pos = st->index_entries[index].pos;
  948. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  949. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  950. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  951. /* One and only one real stream for DV in AVI, and it has video */
  952. /* offsets. Calling with other stream indexes should have failed */
  953. /* the av_index_search_timestamp call above. */
  954. assert(stream_index == 0);
  955. /* Feed the DV video stream version of the timestamp to the */
  956. /* DV demux so it can synthesize correct timestamps. */
  957. dv_offset_reset(avi->dv_demux, timestamp);
  958. url_fseek(s->pb, pos, SEEK_SET);
  959. avi->stream_index= -1;
  960. return 0;
  961. }
  962. for(i = 0; i < s->nb_streams; i++) {
  963. AVStream *st2 = s->streams[i];
  964. AVIStream *ast2 = st2->priv_data;
  965. ast2->packet_size=
  966. ast2->remaining= 0;
  967. if (st2->nb_index_entries <= 0)
  968. continue;
  969. // assert(st2->codec->block_align);
  970. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  971. index = av_index_search_timestamp(
  972. st2,
  973. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  974. flags | AVSEEK_FLAG_BACKWARD);
  975. if(index<0)
  976. index=0;
  977. if(!avi->non_interleaved){
  978. while(index>0 && st2->index_entries[index].pos > pos)
  979. index--;
  980. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  981. index++;
  982. }
  983. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  984. /* extract the current frame number */
  985. ast2->frame_offset = st2->index_entries[index].timestamp;
  986. }
  987. /* do the seek */
  988. url_fseek(s->pb, pos, SEEK_SET);
  989. avi->stream_index= -1;
  990. return 0;
  991. }
  992. static int avi_read_close(AVFormatContext *s)
  993. {
  994. int i;
  995. AVIContext *avi = s->priv_data;
  996. for(i=0;i<s->nb_streams;i++) {
  997. AVStream *st = s->streams[i];
  998. av_free(st->codec->palctrl);
  999. }
  1000. if (avi->dv_demux)
  1001. av_free(avi->dv_demux);
  1002. return 0;
  1003. }
  1004. static int avi_probe(AVProbeData *p)
  1005. {
  1006. int i;
  1007. /* check file header */
  1008. for(i=0; avi_headers[i][0]; i++)
  1009. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1010. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1011. return AVPROBE_SCORE_MAX;
  1012. return 0;
  1013. }
  1014. AVInputFormat avi_demuxer = {
  1015. "avi",
  1016. NULL_IF_CONFIG_SMALL("AVI format"),
  1017. sizeof(AVIContext),
  1018. avi_probe,
  1019. avi_read_header,
  1020. avi_read_packet,
  1021. avi_read_close,
  1022. avi_read_seek,
  1023. };