You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1400 lines
47KB

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