avidec.c 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378
  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 <strings.h>
  24. #include "libavutil/intreadwrite.h"
  25. #include "libavutil/bswap.h"
  26. #include "avformat.h"
  27. #include "avi.h"
  28. #include "dv.h"
  29. #include "riff.h"
  30. #undef NDEBUG
  31. #include <assert.h>
  32. typedef struct AVIStream {
  33. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  34. (used to compute the pts) */
  35. int remaining;
  36. int packet_size;
  37. int scale;
  38. int rate;
  39. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  40. int64_t cum_len; /* temporary storage (used during seek) */
  41. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  42. int prefix_count;
  43. uint32_t pal[256];
  44. int has_pal;
  45. int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
  46. AVFormatContext *sub_ctx;
  47. AVPacket sub_pkt;
  48. uint8_t *sub_buffer;
  49. } AVIStream;
  50. typedef struct {
  51. int64_t riff_end;
  52. int64_t movi_end;
  53. int64_t fsize;
  54. int64_t movi_list;
  55. int64_t last_pkt_pos;
  56. int index_loaded;
  57. int is_odml;
  58. int non_interleaved;
  59. int stream_index;
  60. DVDemuxContext* dv_demux;
  61. int odml_depth;
  62. #define MAX_ODML_DEPTH 1000
  63. } AVIContext;
  64. static const char avi_headers[][8] = {
  65. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  66. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  67. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  68. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  69. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  70. { 0 }
  71. };
  72. static int avi_load_index(AVFormatContext *s);
  73. static int guess_ni_flag(AVFormatContext *s);
  74. #define print_tag(str, tag, size) \
  75. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  76. str, tag & 0xff, \
  77. (tag >> 8) & 0xff, \
  78. (tag >> 16) & 0xff, \
  79. (tag >> 24) & 0xff, \
  80. size)
  81. static inline int get_duration(AVIStream *ast, int len){
  82. if(ast->sample_size){
  83. return len;
  84. }else if (ast->dshow_block_align){
  85. return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
  86. }else
  87. return 1;
  88. }
  89. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  90. {
  91. AVIContext *avi = s->priv_data;
  92. char header[8];
  93. int i;
  94. /* check RIFF header */
  95. avio_read(pb, header, 4);
  96. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  97. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  98. avio_read(pb, header+4, 4);
  99. for(i=0; avi_headers[i][0]; i++)
  100. if(!memcmp(header, avi_headers[i], 8))
  101. break;
  102. if(!avi_headers[i][0])
  103. return -1;
  104. if(header[7] == 0x19)
  105. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  106. return 0;
  107. }
  108. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  109. AVIContext *avi = s->priv_data;
  110. AVIOContext *pb = s->pb;
  111. int longs_pre_entry= avio_rl16(pb);
  112. int index_sub_type = avio_r8(pb);
  113. int index_type = avio_r8(pb);
  114. int entries_in_use = avio_rl32(pb);
  115. int chunk_id = avio_rl32(pb);
  116. int64_t base = avio_rl64(pb);
  117. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  118. AVStream *st;
  119. AVIStream *ast;
  120. int i;
  121. int64_t last_pos= -1;
  122. int64_t filesize= avio_size(s->pb);
  123. #ifdef DEBUG_SEEK
  124. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  125. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  126. #endif
  127. if(stream_id >= s->nb_streams || stream_id < 0)
  128. return -1;
  129. st= s->streams[stream_id];
  130. ast = st->priv_data;
  131. if(index_sub_type)
  132. return -1;
  133. avio_rl32(pb);
  134. if(index_type && longs_pre_entry != 2)
  135. return -1;
  136. if(index_type>1)
  137. return -1;
  138. if(filesize > 0 && base >= filesize){
  139. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  140. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  141. base &= 0xFFFFFFFF;
  142. else
  143. return -1;
  144. }
  145. for(i=0; i<entries_in_use; i++){
  146. if(index_type){
  147. int64_t pos= avio_rl32(pb) + base - 8;
  148. int len = avio_rl32(pb);
  149. int key= len >= 0;
  150. len &= 0x7FFFFFFF;
  151. #ifdef DEBUG_SEEK
  152. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  153. #endif
  154. if(url_feof(pb))
  155. return -1;
  156. if(last_pos == pos || pos == base - 8)
  157. avi->non_interleaved= 1;
  158. if(last_pos != pos && (len || !ast->sample_size))
  159. av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
  160. ast->cum_len += get_duration(ast, len);
  161. last_pos= pos;
  162. }else{
  163. int64_t offset, pos;
  164. int duration;
  165. offset = avio_rl64(pb);
  166. avio_rl32(pb); /* size */
  167. duration = avio_rl32(pb);
  168. if(url_feof(pb))
  169. return -1;
  170. pos = avio_tell(pb);
  171. if(avi->odml_depth > MAX_ODML_DEPTH){
  172. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  173. return -1;
  174. }
  175. avio_seek(pb, offset+8, SEEK_SET);
  176. avi->odml_depth++;
  177. read_braindead_odml_indx(s, frame_num);
  178. avi->odml_depth--;
  179. frame_num += duration;
  180. avio_seek(pb, pos, SEEK_SET);
  181. }
  182. }
  183. avi->index_loaded=1;
  184. return 0;
  185. }
  186. static void clean_index(AVFormatContext *s){
  187. int i;
  188. int64_t j;
  189. for(i=0; i<s->nb_streams; i++){
  190. AVStream *st = s->streams[i];
  191. AVIStream *ast = st->priv_data;
  192. int n= st->nb_index_entries;
  193. int max= ast->sample_size;
  194. int64_t pos, size, ts;
  195. if(n != 1 || ast->sample_size==0)
  196. continue;
  197. while(max < 1024) max+=max;
  198. pos= st->index_entries[0].pos;
  199. size= st->index_entries[0].size;
  200. ts= st->index_entries[0].timestamp;
  201. for(j=0; j<size; j+=max){
  202. av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  203. }
  204. }
  205. }
  206. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
  207. {
  208. AVIOContext *pb = s->pb;
  209. char key[5] = {0}, *value;
  210. size += (size & 1);
  211. if (size == UINT_MAX)
  212. return -1;
  213. value = av_malloc(size+1);
  214. if (!value)
  215. return -1;
  216. avio_read(pb, value, size);
  217. value[size]=0;
  218. AV_WL32(key, tag);
  219. return av_metadata_set2(st ? &st->metadata : &s->metadata, key, value,
  220. AV_METADATA_DONT_STRDUP_VAL);
  221. }
  222. static void avi_read_info(AVFormatContext *s, uint64_t end)
  223. {
  224. while (avio_tell(s->pb) < end) {
  225. uint32_t tag = avio_rl32(s->pb);
  226. uint32_t size = avio_rl32(s->pb);
  227. avi_read_tag(s, NULL, tag, size);
  228. }
  229. }
  230. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  231. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  232. static void avi_metadata_creation_time(AVMetadata **metadata, char *date)
  233. {
  234. char month[4], time[9], buffer[64];
  235. int i, day, year;
  236. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  237. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  238. month, &day, time, &year) == 4) {
  239. for (i=0; i<12; i++)
  240. if (!strcasecmp(month, months[i])) {
  241. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  242. year, i+1, day, time);
  243. av_metadata_set2(metadata, "creation_time", buffer, 0);
  244. }
  245. } else if (date[4] == '/' && date[7] == '/') {
  246. date[4] = date[7] = '-';
  247. av_metadata_set2(metadata, "creation_time", date, 0);
  248. }
  249. }
  250. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  251. {
  252. while (avio_tell(s->pb) < end) {
  253. uint32_t tag = avio_rl32(s->pb);
  254. uint32_t size = avio_rl32(s->pb);
  255. switch (tag) {
  256. case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
  257. uint64_t tag_end = avio_tell(s->pb) + size;
  258. while (avio_tell(s->pb) < tag_end) {
  259. uint16_t tag = avio_rl16(s->pb);
  260. uint16_t size = avio_rl16(s->pb);
  261. const char *name = NULL;
  262. char buffer[64] = {0};
  263. size -= avio_read(s->pb, buffer,
  264. FFMIN(size, sizeof(buffer)-1));
  265. switch (tag) {
  266. case 0x03: name = "maker"; break;
  267. case 0x04: name = "model"; break;
  268. case 0x13: name = "creation_time";
  269. if (buffer[4] == ':' && buffer[7] == ':')
  270. buffer[4] = buffer[7] = '-';
  271. break;
  272. }
  273. if (name)
  274. av_metadata_set2(&s->metadata, name, buffer, 0);
  275. avio_seek(s->pb, size, SEEK_CUR);
  276. }
  277. break;
  278. }
  279. default:
  280. avio_seek(s->pb, size, SEEK_CUR);
  281. break;
  282. }
  283. }
  284. }
  285. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  286. {
  287. AVIContext *avi = s->priv_data;
  288. AVIOContext *pb = s->pb;
  289. unsigned int tag, tag1, handler;
  290. int codec_type, stream_index, frame_period, bit_rate;
  291. unsigned int size;
  292. int i;
  293. AVStream *st;
  294. AVIStream *ast = NULL;
  295. int avih_width=0, avih_height=0;
  296. int amv_file_format=0;
  297. uint64_t list_end = 0;
  298. avi->stream_index= -1;
  299. if (get_riff(s, pb) < 0)
  300. return -1;
  301. avi->fsize = avio_size(pb);
  302. if(avi->fsize<=0)
  303. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  304. /* first list tag */
  305. stream_index = -1;
  306. codec_type = -1;
  307. frame_period = 0;
  308. for(;;) {
  309. if (url_feof(pb))
  310. goto fail;
  311. tag = avio_rl32(pb);
  312. size = avio_rl32(pb);
  313. print_tag("tag", tag, size);
  314. switch(tag) {
  315. case MKTAG('L', 'I', 'S', 'T'):
  316. list_end = avio_tell(pb) + size;
  317. /* Ignored, except at start of video packets. */
  318. tag1 = avio_rl32(pb);
  319. print_tag("list", tag1, 0);
  320. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  321. avi->movi_list = avio_tell(pb) - 4;
  322. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  323. else avi->movi_end = avio_size(pb);
  324. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  325. goto end_of_header;
  326. }
  327. else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  328. avi_read_info(s, list_end);
  329. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  330. avi_read_nikon(s, list_end);
  331. break;
  332. case MKTAG('I', 'D', 'I', 'T'): {
  333. unsigned char date[64] = {0};
  334. size += (size & 1);
  335. size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
  336. avio_seek(pb, size, SEEK_CUR);
  337. avi_metadata_creation_time(&s->metadata, date);
  338. break;
  339. }
  340. case MKTAG('d', 'm', 'l', 'h'):
  341. avi->is_odml = 1;
  342. avio_seek(pb, size + (size & 1), SEEK_CUR);
  343. break;
  344. case MKTAG('a', 'm', 'v', 'h'):
  345. amv_file_format=1;
  346. case MKTAG('a', 'v', 'i', 'h'):
  347. /* AVI header */
  348. /* using frame_period is bad idea */
  349. frame_period = avio_rl32(pb);
  350. bit_rate = avio_rl32(pb) * 8;
  351. avio_rl32(pb);
  352. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  353. avio_seek(pb, 2 * 4, SEEK_CUR);
  354. avio_rl32(pb);
  355. avio_rl32(pb);
  356. avih_width=avio_rl32(pb);
  357. avih_height=avio_rl32(pb);
  358. avio_seek(pb, size - 10 * 4, SEEK_CUR);
  359. break;
  360. case MKTAG('s', 't', 'r', 'h'):
  361. /* stream header */
  362. tag1 = avio_rl32(pb);
  363. handler = avio_rl32(pb); /* codec tag */
  364. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  365. avio_seek(pb, size - 8, SEEK_CUR);
  366. break;
  367. }else{
  368. stream_index++;
  369. st = av_new_stream(s, stream_index);
  370. if (!st)
  371. goto fail;
  372. ast = av_mallocz(sizeof(AVIStream));
  373. if (!ast)
  374. goto fail;
  375. st->priv_data = ast;
  376. }
  377. if(amv_file_format)
  378. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  379. print_tag("strh", tag1, -1);
  380. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  381. int64_t dv_dur;
  382. /*
  383. * After some consideration -- I don't think we
  384. * have to support anything but DV in type1 AVIs.
  385. */
  386. if (s->nb_streams != 1)
  387. goto fail;
  388. if (handler != MKTAG('d', 'v', 's', 'd') &&
  389. handler != MKTAG('d', 'v', 'h', 'd') &&
  390. handler != MKTAG('d', 'v', 's', 'l'))
  391. goto fail;
  392. ast = s->streams[0]->priv_data;
  393. av_freep(&s->streams[0]->codec->extradata);
  394. av_freep(&s->streams[0]->codec);
  395. av_freep(&s->streams[0]);
  396. s->nb_streams = 0;
  397. if (CONFIG_DV_DEMUXER) {
  398. avi->dv_demux = dv_init_demux(s);
  399. if (!avi->dv_demux)
  400. goto fail;
  401. }
  402. s->streams[0]->priv_data = ast;
  403. avio_seek(pb, 3 * 4, SEEK_CUR);
  404. ast->scale = avio_rl32(pb);
  405. ast->rate = avio_rl32(pb);
  406. avio_seek(pb, 4, SEEK_CUR); /* start time */
  407. dv_dur = avio_rl32(pb);
  408. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  409. dv_dur *= AV_TIME_BASE;
  410. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  411. }
  412. /*
  413. * else, leave duration alone; timing estimation in utils.c
  414. * will make a guess based on bitrate.
  415. */
  416. stream_index = s->nb_streams - 1;
  417. avio_seek(pb, size - 9*4, SEEK_CUR);
  418. break;
  419. }
  420. assert(stream_index < s->nb_streams);
  421. st->codec->stream_codec_tag= handler;
  422. avio_rl32(pb); /* flags */
  423. avio_rl16(pb); /* priority */
  424. avio_rl16(pb); /* language */
  425. avio_rl32(pb); /* initial frame */
  426. ast->scale = avio_rl32(pb);
  427. ast->rate = avio_rl32(pb);
  428. if(!(ast->scale && ast->rate)){
  429. 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);
  430. if(frame_period){
  431. ast->rate = 1000000;
  432. ast->scale = frame_period;
  433. }else{
  434. ast->rate = 25;
  435. ast->scale = 1;
  436. }
  437. }
  438. av_set_pts_info(st, 64, ast->scale, ast->rate);
  439. ast->cum_len=avio_rl32(pb); /* start */
  440. st->nb_frames = avio_rl32(pb);
  441. st->start_time = 0;
  442. avio_rl32(pb); /* buffer size */
  443. avio_rl32(pb); /* quality */
  444. ast->sample_size = avio_rl32(pb); /* sample ssize */
  445. ast->cum_len *= FFMAX(1, ast->sample_size);
  446. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  447. switch(tag1) {
  448. case MKTAG('v', 'i', 'd', 's'):
  449. codec_type = AVMEDIA_TYPE_VIDEO;
  450. ast->sample_size = 0;
  451. break;
  452. case MKTAG('a', 'u', 'd', 's'):
  453. codec_type = AVMEDIA_TYPE_AUDIO;
  454. break;
  455. case MKTAG('t', 'x', 't', 's'):
  456. codec_type = AVMEDIA_TYPE_SUBTITLE;
  457. break;
  458. case MKTAG('d', 'a', 't', 's'):
  459. codec_type = AVMEDIA_TYPE_DATA;
  460. break;
  461. default:
  462. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  463. goto fail;
  464. }
  465. if(ast->sample_size == 0)
  466. st->duration = st->nb_frames;
  467. ast->frame_offset= ast->cum_len;
  468. avio_seek(pb, size - 12 * 4, SEEK_CUR);
  469. break;
  470. case MKTAG('s', 't', 'r', 'f'):
  471. /* stream header */
  472. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  473. avio_seek(pb, size, SEEK_CUR);
  474. } else {
  475. uint64_t cur_pos = avio_tell(pb);
  476. if (cur_pos < list_end)
  477. size = FFMIN(size, list_end - cur_pos);
  478. st = s->streams[stream_index];
  479. switch(codec_type) {
  480. case AVMEDIA_TYPE_VIDEO:
  481. if(amv_file_format){
  482. st->codec->width=avih_width;
  483. st->codec->height=avih_height;
  484. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  485. st->codec->codec_id = CODEC_ID_AMV;
  486. avio_seek(pb, size, SEEK_CUR);
  487. break;
  488. }
  489. tag1 = ff_get_bmp_header(pb, st);
  490. if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
  491. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  492. st->codec->codec_tag = tag1;
  493. st->codec->codec_id = CODEC_ID_XSUB;
  494. break;
  495. }
  496. if(size > 10*4 && size<(1<<30)){
  497. st->codec->extradata_size= size - 10*4;
  498. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  499. if (!st->codec->extradata) {
  500. st->codec->extradata_size= 0;
  501. return AVERROR(ENOMEM);
  502. }
  503. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  504. }
  505. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  506. avio_r8(pb);
  507. /* Extract palette from extradata if bpp <= 8. */
  508. /* This code assumes that extradata contains only palette. */
  509. /* This is true for all paletted codecs implemented in FFmpeg. */
  510. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  511. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  512. #if HAVE_BIGENDIAN
  513. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  514. st->codec->palctrl->palette[i] = av_bswap32(((uint32_t*)st->codec->extradata)[i]);
  515. #else
  516. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  517. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  518. #endif
  519. st->codec->palctrl->palette_changed = 1;
  520. }
  521. print_tag("video", tag1, 0);
  522. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  523. st->codec->codec_tag = tag1;
  524. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  525. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  526. // Support "Resolution 1:1" for Avid AVI Codec
  527. if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
  528. st->codec->extradata_size >= 31 &&
  529. !memcmp(&st->codec->extradata[28], "1:1", 3))
  530. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  531. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  532. st->codec->extradata_size+= 9;
  533. st->codec->extradata= av_realloc(st->codec->extradata, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  534. if(st->codec->extradata)
  535. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  536. }
  537. st->codec->height= FFABS(st->codec->height);
  538. // avio_seek(pb, size - 5 * 4, SEEK_CUR);
  539. break;
  540. case AVMEDIA_TYPE_AUDIO:
  541. ff_get_wav_header(pb, st->codec, size);
  542. ast->dshow_block_align= st->codec->block_align;
  543. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  544. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  545. ast->sample_size= st->codec->block_align;
  546. }
  547. if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  548. avio_seek(pb, 1, SEEK_CUR);
  549. /* Force parsing as several audio frames can be in
  550. * one packet and timestamps refer to packet start. */
  551. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  552. /* ADTS header is in extradata, AAC without header must be
  553. * stored as exact frames. Parser not needed and it will
  554. * fail. */
  555. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  556. st->need_parsing = AVSTREAM_PARSE_NONE;
  557. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  558. * audio in the header but have Axan as stream_code_tag. */
  559. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  560. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  561. st->codec->codec_tag = 0;
  562. }
  563. if (amv_file_format){
  564. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  565. ast->dshow_block_align = 0;
  566. }
  567. break;
  568. case AVMEDIA_TYPE_SUBTITLE:
  569. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  570. st->codec->codec_id = CODEC_ID_PROBE;
  571. break;
  572. default:
  573. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  574. st->codec->codec_id= CODEC_ID_NONE;
  575. st->codec->codec_tag= 0;
  576. avio_seek(pb, size, SEEK_CUR);
  577. break;
  578. }
  579. }
  580. break;
  581. case MKTAG('i', 'n', 'd', 'x'):
  582. i= avio_tell(pb);
  583. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  584. read_braindead_odml_indx(s, 0);
  585. }
  586. avio_seek(pb, i+size, SEEK_SET);
  587. break;
  588. case MKTAG('v', 'p', 'r', 'p'):
  589. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  590. AVRational active, active_aspect;
  591. st = s->streams[stream_index];
  592. avio_rl32(pb);
  593. avio_rl32(pb);
  594. avio_rl32(pb);
  595. avio_rl32(pb);
  596. avio_rl32(pb);
  597. active_aspect.den= avio_rl16(pb);
  598. active_aspect.num= avio_rl16(pb);
  599. active.num = avio_rl32(pb);
  600. active.den = avio_rl32(pb);
  601. avio_rl32(pb); //nbFieldsPerFrame
  602. if(active_aspect.num && active_aspect.den && active.num && active.den){
  603. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  604. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  605. }
  606. size -= 9*4;
  607. }
  608. avio_seek(pb, size, SEEK_CUR);
  609. break;
  610. case MKTAG('s', 't', 'r', 'n'):
  611. if(s->nb_streams){
  612. avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
  613. break;
  614. }
  615. default:
  616. if(size > 1000000){
  617. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  618. "I will ignore it and try to continue anyway.\n");
  619. avi->movi_list = avio_tell(pb) - 4;
  620. avi->movi_end = avio_size(pb);
  621. goto end_of_header;
  622. }
  623. /* skip tag */
  624. size += (size & 1);
  625. avio_seek(pb, size, SEEK_CUR);
  626. break;
  627. }
  628. }
  629. end_of_header:
  630. /* check stream number */
  631. if (stream_index != s->nb_streams - 1) {
  632. fail:
  633. return -1;
  634. }
  635. if(!avi->index_loaded && !url_is_streamed(pb))
  636. avi_load_index(s);
  637. avi->index_loaded = 1;
  638. avi->non_interleaved |= guess_ni_flag(s);
  639. for(i=0; i<s->nb_streams; i++){
  640. AVStream *st = s->streams[i];
  641. if(st->nb_index_entries)
  642. break;
  643. }
  644. if(i==s->nb_streams && avi->non_interleaved) {
  645. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  646. avi->non_interleaved=0;
  647. }
  648. if(avi->non_interleaved) {
  649. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  650. clean_index(s);
  651. }
  652. ff_metadata_conv_ctx(s, NULL, ff_avi_metadata_conv);
  653. return 0;
  654. }
  655. static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
  656. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
  657. uint8_t desc[256];
  658. int score = AVPROBE_SCORE_MAX / 2, ret;
  659. AVIStream *ast = st->priv_data;
  660. AVInputFormat *sub_demuxer;
  661. AVRational time_base;
  662. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  663. pkt->size - 7,
  664. 0, NULL, NULL, NULL, NULL);
  665. AVProbeData pd;
  666. unsigned int desc_len = avio_rl32(pb);
  667. if (desc_len > pb->buf_end - pb->buf_ptr)
  668. goto error;
  669. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  670. avio_seek(pb, desc_len - ret, SEEK_CUR);
  671. if (*desc)
  672. av_metadata_set2(&st->metadata, "title", desc, 0);
  673. avio_rl16(pb); /* flags? */
  674. avio_rl32(pb); /* data size */
  675. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  676. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  677. goto error;
  678. if (!av_open_input_stream(&ast->sub_ctx, pb, "", sub_demuxer, NULL)) {
  679. av_read_packet(ast->sub_ctx, &ast->sub_pkt);
  680. *st->codec = *ast->sub_ctx->streams[0]->codec;
  681. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  682. time_base = ast->sub_ctx->streams[0]->time_base;
  683. av_set_pts_info(st, 64, time_base.num, time_base.den);
  684. }
  685. ast->sub_buffer = pkt->data;
  686. memset(pkt, 0, sizeof(*pkt));
  687. return 1;
  688. error:
  689. av_freep(&pb);
  690. }
  691. return 0;
  692. }
  693. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  694. AVPacket *pkt)
  695. {
  696. AVIStream *ast, *next_ast = next_st->priv_data;
  697. int64_t ts, next_ts, ts_min = INT64_MAX;
  698. AVStream *st, *sub_st = NULL;
  699. int i;
  700. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  701. AV_TIME_BASE_Q);
  702. for (i=0; i<s->nb_streams; i++) {
  703. st = s->streams[i];
  704. ast = st->priv_data;
  705. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  706. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  707. if (ts <= next_ts && ts < ts_min) {
  708. ts_min = ts;
  709. sub_st = st;
  710. }
  711. }
  712. }
  713. if (sub_st) {
  714. ast = sub_st->priv_data;
  715. *pkt = ast->sub_pkt;
  716. pkt->stream_index = sub_st->index;
  717. if (av_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  718. ast->sub_pkt.data = NULL;
  719. }
  720. return sub_st;
  721. }
  722. static int get_stream_idx(int *d){
  723. if( d[0] >= '0' && d[0] <= '9'
  724. && d[1] >= '0' && d[1] <= '9'){
  725. return (d[0] - '0') * 10 + (d[1] - '0');
  726. }else{
  727. return 100; //invalid stream ID
  728. }
  729. }
  730. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  731. {
  732. AVIContext *avi = s->priv_data;
  733. AVIOContext *pb = s->pb;
  734. int n, d[8];
  735. unsigned int size;
  736. int64_t i, sync;
  737. void* dstr;
  738. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  739. int size = dv_get_packet(avi->dv_demux, pkt);
  740. if (size >= 0)
  741. return size;
  742. }
  743. if(avi->non_interleaved){
  744. int best_stream_index = 0;
  745. AVStream *best_st= NULL;
  746. AVIStream *best_ast;
  747. int64_t best_ts= INT64_MAX;
  748. int i;
  749. for(i=0; i<s->nb_streams; i++){
  750. AVStream *st = s->streams[i];
  751. AVIStream *ast = st->priv_data;
  752. int64_t ts= ast->frame_offset;
  753. int64_t last_ts;
  754. if(!st->nb_index_entries)
  755. continue;
  756. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  757. if(!ast->remaining && ts > last_ts)
  758. continue;
  759. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  760. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  761. if(ts < best_ts){
  762. best_ts= ts;
  763. best_st= st;
  764. best_stream_index= i;
  765. }
  766. }
  767. if(!best_st)
  768. return -1;
  769. best_ast = best_st->priv_data;
  770. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  771. if(best_ast->remaining)
  772. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  773. else{
  774. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  775. if(i>=0)
  776. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  777. }
  778. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  779. if(i>=0){
  780. int64_t pos= best_st->index_entries[i].pos;
  781. pos += best_ast->packet_size - best_ast->remaining;
  782. avio_seek(s->pb, pos + 8, SEEK_SET);
  783. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  784. assert(best_ast->remaining <= best_ast->packet_size);
  785. avi->stream_index= best_stream_index;
  786. if(!best_ast->remaining)
  787. best_ast->packet_size=
  788. best_ast->remaining= best_st->index_entries[i].size;
  789. }
  790. }
  791. resync:
  792. if(avi->stream_index >= 0){
  793. AVStream *st= s->streams[ avi->stream_index ];
  794. AVIStream *ast= st->priv_data;
  795. int size, err;
  796. if(get_subtitle_pkt(s, st, pkt))
  797. return 0;
  798. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  799. size= INT_MAX;
  800. else if(ast->sample_size < 32)
  801. // arbitrary multiplier to avoid tiny packets for raw PCM data
  802. size= 1024*ast->sample_size;
  803. else
  804. size= ast->sample_size;
  805. if(size > ast->remaining)
  806. size= ast->remaining;
  807. avi->last_pkt_pos= avio_tell(pb);
  808. err= av_get_packet(pb, pkt, size);
  809. if(err<0)
  810. return err;
  811. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  812. void *ptr= av_realloc(pkt->data, pkt->size + 4*256 + FF_INPUT_BUFFER_PADDING_SIZE);
  813. if(ptr){
  814. ast->has_pal=0;
  815. pkt->size += 4*256;
  816. pkt->data= ptr;
  817. memcpy(pkt->data + pkt->size - 4*256, ast->pal, 4*256);
  818. }else
  819. av_log(s, AV_LOG_ERROR, "Failed to append palette\n");
  820. }
  821. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  822. dstr = pkt->destruct;
  823. size = dv_produce_packet(avi->dv_demux, pkt,
  824. pkt->data, pkt->size);
  825. pkt->destruct = dstr;
  826. pkt->flags |= AV_PKT_FLAG_KEY;
  827. if (size < 0)
  828. av_free_packet(pkt);
  829. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  830. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  831. ast->frame_offset++;
  832. avi->stream_index = -1;
  833. ast->remaining = 0;
  834. goto resync;
  835. } else {
  836. /* XXX: How to handle B-frames in AVI? */
  837. pkt->dts = ast->frame_offset;
  838. // pkt->dts += ast->start;
  839. if(ast->sample_size)
  840. pkt->dts /= ast->sample_size;
  841. //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);
  842. pkt->stream_index = avi->stream_index;
  843. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  844. AVIndexEntry *e;
  845. int index;
  846. assert(st->index_entries);
  847. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  848. e= &st->index_entries[index];
  849. if(index >= 0 && e->timestamp == ast->frame_offset){
  850. if (e->flags & AVINDEX_KEYFRAME)
  851. pkt->flags |= AV_PKT_FLAG_KEY;
  852. }
  853. } else {
  854. pkt->flags |= AV_PKT_FLAG_KEY;
  855. }
  856. ast->frame_offset += get_duration(ast, pkt->size);
  857. }
  858. ast->remaining -= size;
  859. if(!ast->remaining){
  860. avi->stream_index= -1;
  861. ast->packet_size= 0;
  862. }
  863. return size;
  864. }
  865. memset(d, -1, sizeof(int)*8);
  866. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  867. int j;
  868. for(j=0; j<7; j++)
  869. d[j]= d[j+1];
  870. d[7]= avio_r8(pb);
  871. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  872. n= get_stream_idx(d+2);
  873. //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);
  874. if(i + (uint64_t)size > avi->fsize || d[0]<0)
  875. continue;
  876. //parse ix##
  877. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  878. //parse JUNK
  879. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  880. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  881. avio_seek(pb, size, SEEK_CUR);
  882. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  883. goto resync;
  884. }
  885. //parse stray LIST
  886. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  887. avio_seek(pb, 4, SEEK_CUR);
  888. goto resync;
  889. }
  890. n= get_stream_idx(d);
  891. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  892. continue;
  893. //detect ##ix chunk and skip
  894. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  895. avio_seek(pb, size, SEEK_CUR);
  896. goto resync;
  897. }
  898. //parse ##dc/##wb
  899. if(n < s->nb_streams){
  900. AVStream *st;
  901. AVIStream *ast;
  902. st = s->streams[n];
  903. ast = st->priv_data;
  904. if(s->nb_streams>=2){
  905. AVStream *st1 = s->streams[1];
  906. AVIStream *ast1= st1->priv_data;
  907. //workaround for broken small-file-bug402.avi
  908. if( d[2] == 'w' && d[3] == 'b'
  909. && n==0
  910. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  911. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  912. && ast->prefix == 'd'*256+'c'
  913. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  914. ){
  915. n=1;
  916. st = st1;
  917. ast = ast1;
  918. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  919. }
  920. }
  921. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  922. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  923. || st->discard >= AVDISCARD_ALL){
  924. ast->frame_offset += get_duration(ast, size);
  925. avio_seek(pb, size, SEEK_CUR);
  926. goto resync;
  927. }
  928. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  929. int k = avio_r8(pb);
  930. int last = (k + avio_r8(pb) - 1) & 0xFF;
  931. avio_rl16(pb); //flags
  932. for (; k <= last; k++)
  933. ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  934. ast->has_pal= 1;
  935. goto resync;
  936. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  937. d[2]*256+d[3] == ast->prefix /*||
  938. (d[2] == 'd' && d[3] == 'c') ||
  939. (d[2] == 'w' && d[3] == 'b')*/) {
  940. //av_log(s, AV_LOG_DEBUG, "OK\n");
  941. if(d[2]*256+d[3] == ast->prefix)
  942. ast->prefix_count++;
  943. else{
  944. ast->prefix= d[2]*256+d[3];
  945. ast->prefix_count= 0;
  946. }
  947. avi->stream_index= n;
  948. ast->packet_size= size + 8;
  949. ast->remaining= size;
  950. if(size || !ast->sample_size){
  951. uint64_t pos= avio_tell(pb) - 8;
  952. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  953. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  954. }
  955. }
  956. goto resync;
  957. }
  958. }
  959. }
  960. return AVERROR_EOF;
  961. }
  962. /* XXX: We make the implicit supposition that the positions are sorted
  963. for each stream. */
  964. static int avi_read_idx1(AVFormatContext *s, int size)
  965. {
  966. AVIContext *avi = s->priv_data;
  967. AVIOContext *pb = s->pb;
  968. int nb_index_entries, i;
  969. AVStream *st;
  970. AVIStream *ast;
  971. unsigned int index, tag, flags, pos, len;
  972. unsigned last_pos= -1;
  973. nb_index_entries = size / 16;
  974. if (nb_index_entries <= 0)
  975. return -1;
  976. /* Read the entries and sort them in each stream component. */
  977. for(i = 0; i < nb_index_entries; i++) {
  978. tag = avio_rl32(pb);
  979. flags = avio_rl32(pb);
  980. pos = avio_rl32(pb);
  981. len = avio_rl32(pb);
  982. #if defined(DEBUG_SEEK)
  983. av_log(s, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  984. i, tag, flags, pos, len);
  985. #endif
  986. if(i==0 && pos > avi->movi_list)
  987. avi->movi_list= 0; //FIXME better check
  988. pos += avi->movi_list;
  989. index = ((tag & 0xff) - '0') * 10;
  990. index += ((tag >> 8) & 0xff) - '0';
  991. if (index >= s->nb_streams)
  992. continue;
  993. st = s->streams[index];
  994. ast = st->priv_data;
  995. #if defined(DEBUG_SEEK)
  996. av_log(s, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  997. #endif
  998. if(url_feof(pb))
  999. return -1;
  1000. if(last_pos == pos)
  1001. avi->non_interleaved= 1;
  1002. else if(len || !ast->sample_size)
  1003. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1004. ast->cum_len += get_duration(ast, len);
  1005. last_pos= pos;
  1006. }
  1007. return 0;
  1008. }
  1009. static int guess_ni_flag(AVFormatContext *s){
  1010. int i;
  1011. int64_t last_start=0;
  1012. int64_t first_end= INT64_MAX;
  1013. int64_t oldpos= avio_tell(s->pb);
  1014. for(i=0; i<s->nb_streams; i++){
  1015. AVStream *st = s->streams[i];
  1016. int n= st->nb_index_entries;
  1017. unsigned int size;
  1018. if(n <= 0)
  1019. continue;
  1020. if(n >= 2){
  1021. int64_t pos= st->index_entries[0].pos;
  1022. avio_seek(s->pb, pos + 4, SEEK_SET);
  1023. size= avio_rl32(s->pb);
  1024. if(pos + size > st->index_entries[1].pos)
  1025. last_start= INT64_MAX;
  1026. }
  1027. if(st->index_entries[0].pos > last_start)
  1028. last_start= st->index_entries[0].pos;
  1029. if(st->index_entries[n-1].pos < first_end)
  1030. first_end= st->index_entries[n-1].pos;
  1031. }
  1032. avio_seek(s->pb, oldpos, SEEK_SET);
  1033. return last_start > first_end;
  1034. }
  1035. static int avi_load_index(AVFormatContext *s)
  1036. {
  1037. AVIContext *avi = s->priv_data;
  1038. AVIOContext *pb = s->pb;
  1039. uint32_t tag, size;
  1040. int64_t pos= avio_tell(pb);
  1041. int ret = -1;
  1042. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1043. goto the_end; // maybe truncated file
  1044. #ifdef DEBUG_SEEK
  1045. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  1046. #endif
  1047. for(;;) {
  1048. if (url_feof(pb))
  1049. break;
  1050. tag = avio_rl32(pb);
  1051. size = avio_rl32(pb);
  1052. #ifdef DEBUG_SEEK
  1053. printf("tag=%c%c%c%c size=0x%x\n",
  1054. tag & 0xff,
  1055. (tag >> 8) & 0xff,
  1056. (tag >> 16) & 0xff,
  1057. (tag >> 24) & 0xff,
  1058. size);
  1059. #endif
  1060. switch(tag) {
  1061. case MKTAG('i', 'd', 'x', '1'):
  1062. if (avi_read_idx1(s, size) < 0)
  1063. goto skip;
  1064. ret = 0;
  1065. goto the_end;
  1066. break;
  1067. default:
  1068. skip:
  1069. size += (size & 1);
  1070. if (avio_seek(pb, size, SEEK_CUR) < 0)
  1071. goto the_end; // something is wrong here
  1072. break;
  1073. }
  1074. }
  1075. the_end:
  1076. avio_seek(pb, pos, SEEK_SET);
  1077. return ret;
  1078. }
  1079. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1080. {
  1081. AVIStream *ast2 = st2->priv_data;
  1082. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1083. av_free_packet(&ast2->sub_pkt);
  1084. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1085. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1086. av_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1087. }
  1088. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1089. {
  1090. AVIContext *avi = s->priv_data;
  1091. AVStream *st;
  1092. int i, index;
  1093. int64_t pos;
  1094. AVIStream *ast;
  1095. if (!avi->index_loaded) {
  1096. /* we only load the index on demand */
  1097. avi_load_index(s);
  1098. avi->index_loaded = 1;
  1099. }
  1100. assert(stream_index>= 0);
  1101. st = s->streams[stream_index];
  1102. ast= st->priv_data;
  1103. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1104. if(index<0)
  1105. return -1;
  1106. /* find the position */
  1107. pos = st->index_entries[index].pos;
  1108. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1109. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1110. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1111. /* One and only one real stream for DV in AVI, and it has video */
  1112. /* offsets. Calling with other stream indexes should have failed */
  1113. /* the av_index_search_timestamp call above. */
  1114. assert(stream_index == 0);
  1115. /* Feed the DV video stream version of the timestamp to the */
  1116. /* DV demux so it can synthesize correct timestamps. */
  1117. dv_offset_reset(avi->dv_demux, timestamp);
  1118. avio_seek(s->pb, pos, SEEK_SET);
  1119. avi->stream_index= -1;
  1120. return 0;
  1121. }
  1122. for(i = 0; i < s->nb_streams; i++) {
  1123. AVStream *st2 = s->streams[i];
  1124. AVIStream *ast2 = st2->priv_data;
  1125. ast2->packet_size=
  1126. ast2->remaining= 0;
  1127. if (ast2->sub_ctx) {
  1128. seek_subtitle(st, st2, timestamp);
  1129. continue;
  1130. }
  1131. if (st2->nb_index_entries <= 0)
  1132. continue;
  1133. // assert(st2->codec->block_align);
  1134. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1135. index = av_index_search_timestamp(
  1136. st2,
  1137. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1138. flags | AVSEEK_FLAG_BACKWARD);
  1139. if(index<0)
  1140. index=0;
  1141. if(!avi->non_interleaved){
  1142. while(index>0 && st2->index_entries[index].pos > pos)
  1143. index--;
  1144. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  1145. index++;
  1146. }
  1147. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  1148. /* extract the current frame number */
  1149. ast2->frame_offset = st2->index_entries[index].timestamp;
  1150. }
  1151. /* do the seek */
  1152. avio_seek(s->pb, pos, SEEK_SET);
  1153. avi->stream_index= -1;
  1154. return 0;
  1155. }
  1156. static int avi_read_close(AVFormatContext *s)
  1157. {
  1158. int i;
  1159. AVIContext *avi = s->priv_data;
  1160. for(i=0;i<s->nb_streams;i++) {
  1161. AVStream *st = s->streams[i];
  1162. AVIStream *ast = st->priv_data;
  1163. av_free(st->codec->palctrl);
  1164. if (ast) {
  1165. if (ast->sub_ctx) {
  1166. av_freep(&ast->sub_ctx->pb);
  1167. av_close_input_stream(ast->sub_ctx);
  1168. }
  1169. av_free(ast->sub_buffer);
  1170. av_free_packet(&ast->sub_pkt);
  1171. }
  1172. }
  1173. av_free(avi->dv_demux);
  1174. return 0;
  1175. }
  1176. static int avi_probe(AVProbeData *p)
  1177. {
  1178. int i;
  1179. /* check file header */
  1180. for(i=0; avi_headers[i][0]; i++)
  1181. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1182. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1183. return AVPROBE_SCORE_MAX;
  1184. return 0;
  1185. }
  1186. AVInputFormat ff_avi_demuxer = {
  1187. "avi",
  1188. NULL_IF_CONFIG_SMALL("AVI format"),
  1189. sizeof(AVIContext),
  1190. avi_probe,
  1191. avi_read_header,
  1192. avi_read_packet,
  1193. avi_read_close,
  1194. avi_read_seek,
  1195. };