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.

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