avidec.c 47 KB

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