avidec.c 46 KB

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