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.

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