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.

1389 lines
46KB

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