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.

1382 lines
46KB

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