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.

1420 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 "internal.h"
  28. #include "avi.h"
  29. #include "dv.h"
  30. #include "riff.h"
  31. #undef NDEBUG
  32. #include <assert.h>
  33. typedef struct AVIStream {
  34. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  35. (used to compute the pts) */
  36. int remaining;
  37. int packet_size;
  38. uint32_t scale;
  39. uint32_t rate;
  40. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  41. int64_t cum_len; /* temporary storage (used during seek) */
  42. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  43. int prefix_count;
  44. uint32_t pal[256];
  45. int has_pal;
  46. int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
  47. AVFormatContext *sub_ctx;
  48. AVPacket sub_pkt;
  49. uint8_t *sub_buffer;
  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 const AVMetadataConv avi_metadata_conv[] = {
  74. { "strn", "title" },
  75. { 0 },
  76. };
  77. static int avi_load_index(AVFormatContext *s);
  78. static int guess_ni_flag(AVFormatContext *s);
  79. #define print_tag(str, tag, size) \
  80. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  81. str, tag & 0xff, \
  82. (tag >> 8) & 0xff, \
  83. (tag >> 16) & 0xff, \
  84. (tag >> 24) & 0xff, \
  85. size)
  86. static inline int get_duration(AVIStream *ast, int len){
  87. if(ast->sample_size){
  88. return len;
  89. }else if (ast->dshow_block_align){
  90. return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
  91. }else
  92. return 1;
  93. }
  94. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  95. {
  96. AVIContext *avi = s->priv_data;
  97. char header[8];
  98. int i;
  99. /* check RIFF header */
  100. avio_read(pb, header, 4);
  101. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  102. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  103. avio_read(pb, header+4, 4);
  104. for(i=0; avi_headers[i][0]; i++)
  105. if(!memcmp(header, avi_headers[i], 8))
  106. break;
  107. if(!avi_headers[i][0])
  108. return AVERROR_INVALIDDATA;
  109. if(header[7] == 0x19)
  110. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  111. return 0;
  112. }
  113. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  114. AVIContext *avi = s->priv_data;
  115. AVIOContext *pb = s->pb;
  116. int longs_pre_entry= avio_rl16(pb);
  117. int index_sub_type = avio_r8(pb);
  118. int index_type = avio_r8(pb);
  119. int entries_in_use = avio_rl32(pb);
  120. int chunk_id = avio_rl32(pb);
  121. int64_t base = avio_rl64(pb);
  122. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  123. AVStream *st;
  124. AVIStream *ast;
  125. int i;
  126. int64_t last_pos= -1;
  127. int64_t filesize= avio_size(s->pb);
  128. av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  129. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  130. if(stream_id >= s->nb_streams || stream_id < 0)
  131. return AVERROR_INVALIDDATA;
  132. st= s->streams[stream_id];
  133. ast = st->priv_data;
  134. if(index_sub_type)
  135. return AVERROR_INVALIDDATA;
  136. avio_rl32(pb);
  137. if(index_type && longs_pre_entry != 2)
  138. return AVERROR_INVALIDDATA;
  139. if(index_type>1)
  140. return AVERROR_INVALIDDATA;
  141. if(filesize > 0 && base >= filesize){
  142. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  143. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  144. base &= 0xFFFFFFFF;
  145. else
  146. return AVERROR_INVALIDDATA;
  147. }
  148. for(i=0; i<entries_in_use; i++){
  149. if(index_type){
  150. int64_t pos= avio_rl32(pb) + base - 8;
  151. int len = avio_rl32(pb);
  152. int key= len >= 0;
  153. len &= 0x7FFFFFFF;
  154. av_dlog(s, "pos:%"PRId64", len:%X\n", pos, len);
  155. if(pb->eof_reached)
  156. return AVERROR_INVALIDDATA;
  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(pb->eof_reached)
  170. return AVERROR_INVALIDDATA;
  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 AVERROR_INVALIDDATA;
  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 AVERROR(EINVAL);
  214. value = av_malloc(size+1);
  215. if (!value)
  216. return AVERROR(ENOMEM);
  217. avio_read(pb, value, size);
  218. value[size]=0;
  219. AV_WL32(key, tag);
  220. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  221. AV_DICT_DONT_STRDUP_VAL);
  222. }
  223. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  224. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  225. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  226. {
  227. char month[4], time[9], buffer[64];
  228. int i, day, year;
  229. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  230. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  231. month, &day, time, &year) == 4) {
  232. for (i=0; i<12; i++)
  233. if (!av_strcasecmp(month, months[i])) {
  234. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  235. year, i+1, day, time);
  236. av_dict_set(metadata, "creation_time", buffer, 0);
  237. }
  238. } else if (date[4] == '/' && date[7] == '/') {
  239. date[4] = date[7] = '-';
  240. av_dict_set(metadata, "creation_time", date, 0);
  241. }
  242. }
  243. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  244. {
  245. while (avio_tell(s->pb) < end) {
  246. uint32_t tag = avio_rl32(s->pb);
  247. uint32_t size = avio_rl32(s->pb);
  248. switch (tag) {
  249. case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
  250. uint64_t tag_end = avio_tell(s->pb) + size;
  251. while (avio_tell(s->pb) < tag_end) {
  252. uint16_t tag = avio_rl16(s->pb);
  253. uint16_t size = avio_rl16(s->pb);
  254. const char *name = NULL;
  255. char buffer[64] = {0};
  256. size -= avio_read(s->pb, buffer,
  257. FFMIN(size, sizeof(buffer)-1));
  258. switch (tag) {
  259. case 0x03: name = "maker"; break;
  260. case 0x04: name = "model"; break;
  261. case 0x13: name = "creation_time";
  262. if (buffer[4] == ':' && buffer[7] == ':')
  263. buffer[4] = buffer[7] = '-';
  264. break;
  265. }
  266. if (name)
  267. av_dict_set(&s->metadata, name, buffer, 0);
  268. avio_skip(s->pb, size);
  269. }
  270. break;
  271. }
  272. default:
  273. avio_skip(s->pb, size);
  274. break;
  275. }
  276. }
  277. }
  278. static int avi_read_header(AVFormatContext *s)
  279. {
  280. AVIContext *avi = s->priv_data;
  281. AVIOContext *pb = s->pb;
  282. unsigned int tag, tag1, handler;
  283. int codec_type, stream_index, frame_period;
  284. unsigned int size;
  285. int i;
  286. AVStream *st;
  287. AVIStream *ast = NULL;
  288. int avih_width=0, avih_height=0;
  289. int amv_file_format=0;
  290. uint64_t list_end = 0;
  291. int ret;
  292. avi->stream_index= -1;
  293. ret = get_riff(s, pb);
  294. if (ret < 0)
  295. return ret;
  296. avi->fsize = avio_size(pb);
  297. if(avi->fsize<=0)
  298. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  299. /* first list tag */
  300. stream_index = -1;
  301. codec_type = -1;
  302. frame_period = 0;
  303. for(;;) {
  304. if (pb->eof_reached)
  305. goto fail;
  306. tag = avio_rl32(pb);
  307. size = avio_rl32(pb);
  308. print_tag("tag", tag, size);
  309. switch(tag) {
  310. case MKTAG('L', 'I', 'S', 'T'):
  311. list_end = avio_tell(pb) + size;
  312. /* Ignored, except at start of video packets. */
  313. tag1 = avio_rl32(pb);
  314. print_tag("list", tag1, 0);
  315. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  316. avi->movi_list = avio_tell(pb) - 4;
  317. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  318. else avi->movi_end = avio_size(pb);
  319. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  320. goto end_of_header;
  321. }
  322. else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  323. ff_read_riff_info(s, size - 4);
  324. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  325. avi_read_nikon(s, list_end);
  326. break;
  327. case MKTAG('I', 'D', 'I', 'T'): {
  328. unsigned char date[64] = {0};
  329. size += (size & 1);
  330. size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
  331. avio_skip(pb, size);
  332. avi_metadata_creation_time(&s->metadata, date);
  333. break;
  334. }
  335. case MKTAG('d', 'm', 'l', 'h'):
  336. avi->is_odml = 1;
  337. avio_skip(pb, size + (size & 1));
  338. break;
  339. case MKTAG('a', 'm', 'v', 'h'):
  340. amv_file_format=1;
  341. case MKTAG('a', 'v', 'i', 'h'):
  342. /* AVI header */
  343. /* using frame_period is bad idea */
  344. frame_period = avio_rl32(pb);
  345. avio_skip(pb, 4);
  346. avio_rl32(pb);
  347. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  348. avio_skip(pb, 2 * 4);
  349. avio_rl32(pb);
  350. avio_rl32(pb);
  351. avih_width=avio_rl32(pb);
  352. avih_height=avio_rl32(pb);
  353. avio_skip(pb, size - 10 * 4);
  354. break;
  355. case MKTAG('s', 't', 'r', 'h'):
  356. /* stream header */
  357. tag1 = avio_rl32(pb);
  358. handler = avio_rl32(pb); /* codec tag */
  359. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  360. avio_skip(pb, size - 8);
  361. break;
  362. }else{
  363. stream_index++;
  364. st = avformat_new_stream(s, NULL);
  365. if (!st)
  366. goto fail;
  367. st->id = stream_index;
  368. ast = av_mallocz(sizeof(AVIStream));
  369. if (!ast)
  370. goto fail;
  371. st->priv_data = ast;
  372. }
  373. if(amv_file_format)
  374. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  375. print_tag("strh", tag1, -1);
  376. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  377. int64_t dv_dur;
  378. /*
  379. * After some consideration -- I don't think we
  380. * have to support anything but DV in type1 AVIs.
  381. */
  382. if (s->nb_streams != 1)
  383. goto fail;
  384. if (handler != MKTAG('d', 'v', 's', 'd') &&
  385. handler != MKTAG('d', 'v', 'h', 'd') &&
  386. handler != MKTAG('d', 'v', 's', 'l'))
  387. goto fail;
  388. ast = s->streams[0]->priv_data;
  389. av_freep(&s->streams[0]->codec->extradata);
  390. av_freep(&s->streams[0]->codec);
  391. av_freep(&s->streams[0]);
  392. s->nb_streams = 0;
  393. if (CONFIG_DV_DEMUXER) {
  394. avi->dv_demux = avpriv_dv_init_demux(s);
  395. if (!avi->dv_demux)
  396. goto fail;
  397. }
  398. s->streams[0]->priv_data = ast;
  399. avio_skip(pb, 3 * 4);
  400. ast->scale = avio_rl32(pb);
  401. ast->rate = avio_rl32(pb);
  402. avio_skip(pb, 4); /* start time */
  403. dv_dur = avio_rl32(pb);
  404. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  405. dv_dur *= AV_TIME_BASE;
  406. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  407. }
  408. /*
  409. * else, leave duration alone; timing estimation in utils.c
  410. * will make a guess based on bitrate.
  411. */
  412. stream_index = s->nb_streams - 1;
  413. avio_skip(pb, size - 9*4);
  414. break;
  415. }
  416. assert(stream_index < s->nb_streams);
  417. st->codec->stream_codec_tag= handler;
  418. avio_rl32(pb); /* flags */
  419. avio_rl16(pb); /* priority */
  420. avio_rl16(pb); /* language */
  421. avio_rl32(pb); /* initial frame */
  422. ast->scale = avio_rl32(pb);
  423. ast->rate = avio_rl32(pb);
  424. if(!(ast->scale && ast->rate)){
  425. av_log(s, AV_LOG_WARNING, "scale/rate is %u/%u which is invalid. (This file has been generated by broken software.)\n", ast->scale, ast->rate);
  426. if(frame_period){
  427. ast->rate = 1000000;
  428. ast->scale = frame_period;
  429. }else{
  430. ast->rate = 25;
  431. ast->scale = 1;
  432. }
  433. }
  434. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  435. ast->cum_len=avio_rl32(pb); /* start */
  436. st->nb_frames = avio_rl32(pb);
  437. st->start_time = 0;
  438. avio_rl32(pb); /* buffer size */
  439. avio_rl32(pb); /* quality */
  440. ast->sample_size = avio_rl32(pb); /* sample ssize */
  441. ast->cum_len *= FFMAX(1, ast->sample_size);
  442. av_dlog(s, "%"PRIu32" %"PRIu32" %d\n",
  443. ast->rate, ast->scale, 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 = AV_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 = AV_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 = AV_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 == AV_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 = AV_CODEC_ID_XAN_DPCM;
  562. st->codec->codec_tag = 0;
  563. }
  564. if (amv_file_format){
  565. st->codec->codec_id = AV_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 = AV_CODEC_ID_PROBE;
  572. break;
  573. default:
  574. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  575. st->codec->codec_id= AV_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) < 0 &&
  586. (s->error_recognition & AV_EF_EXPLODE))
  587. goto fail;
  588. avio_seek(pb, i+size, SEEK_SET);
  589. break;
  590. case MKTAG('v', 'p', 'r', 'p'):
  591. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  592. AVRational active, active_aspect;
  593. st = s->streams[stream_index];
  594. avio_rl32(pb);
  595. avio_rl32(pb);
  596. avio_rl32(pb);
  597. avio_rl32(pb);
  598. avio_rl32(pb);
  599. active_aspect.den= avio_rl16(pb);
  600. active_aspect.num= avio_rl16(pb);
  601. active.num = avio_rl32(pb);
  602. active.den = avio_rl32(pb);
  603. avio_rl32(pb); //nbFieldsPerFrame
  604. if(active_aspect.num && active_aspect.den && active.num && active.den){
  605. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  606. av_dlog(s, "vprp %d/%d %d/%d\n",
  607. active_aspect.num, active_aspect.den,
  608. active.num, active.den);
  609. }
  610. size -= 9*4;
  611. }
  612. avio_skip(pb, size);
  613. break;
  614. case MKTAG('s', 't', 'r', 'n'):
  615. if(s->nb_streams){
  616. ret = avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
  617. if (ret < 0)
  618. return ret;
  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. if (s->error_recognition & AV_EF_EXPLODE)
  626. goto fail;
  627. avi->movi_list = avio_tell(pb) - 4;
  628. avi->movi_end = avio_size(pb);
  629. goto end_of_header;
  630. }
  631. /* skip tag */
  632. size += (size & 1);
  633. avio_skip(pb, size);
  634. break;
  635. }
  636. }
  637. end_of_header:
  638. /* check stream number */
  639. if (stream_index != s->nb_streams - 1) {
  640. fail:
  641. return AVERROR_INVALIDDATA;
  642. }
  643. if(!avi->index_loaded && pb->seekable)
  644. avi_load_index(s);
  645. avi->index_loaded = 1;
  646. avi->non_interleaved |= guess_ni_flag(s);
  647. for(i=0; i<s->nb_streams; i++){
  648. AVStream *st = s->streams[i];
  649. if(st->nb_index_entries)
  650. break;
  651. }
  652. if(i==s->nb_streams && avi->non_interleaved) {
  653. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  654. avi->non_interleaved=0;
  655. }
  656. if(avi->non_interleaved) {
  657. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  658. clean_index(s);
  659. }
  660. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  661. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  662. return 0;
  663. }
  664. static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
  665. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
  666. uint8_t desc[256];
  667. int score = AVPROBE_SCORE_MAX / 2, ret;
  668. AVIStream *ast = st->priv_data;
  669. AVInputFormat *sub_demuxer;
  670. AVRational time_base;
  671. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  672. pkt->size - 7,
  673. 0, NULL, NULL, NULL, NULL);
  674. AVProbeData pd;
  675. unsigned int desc_len = avio_rl32(pb);
  676. if (desc_len > pb->buf_end - pb->buf_ptr)
  677. goto error;
  678. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  679. avio_skip(pb, desc_len - ret);
  680. if (*desc)
  681. av_dict_set(&st->metadata, "title", desc, 0);
  682. avio_rl16(pb); /* flags? */
  683. avio_rl32(pb); /* data size */
  684. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  685. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  686. goto error;
  687. if (!(ast->sub_ctx = avformat_alloc_context()))
  688. goto error;
  689. ast->sub_ctx->pb = pb;
  690. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  691. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  692. *st->codec = *ast->sub_ctx->streams[0]->codec;
  693. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  694. time_base = ast->sub_ctx->streams[0]->time_base;
  695. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  696. }
  697. ast->sub_buffer = pkt->data;
  698. memset(pkt, 0, sizeof(*pkt));
  699. return 1;
  700. error:
  701. av_freep(&pb);
  702. }
  703. return 0;
  704. }
  705. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  706. AVPacket *pkt)
  707. {
  708. AVIStream *ast, *next_ast = next_st->priv_data;
  709. int64_t ts, next_ts, ts_min = INT64_MAX;
  710. AVStream *st, *sub_st = NULL;
  711. int i;
  712. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  713. AV_TIME_BASE_Q);
  714. for (i=0; i<s->nb_streams; i++) {
  715. st = s->streams[i];
  716. ast = st->priv_data;
  717. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  718. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  719. if (ts <= next_ts && ts < ts_min) {
  720. ts_min = ts;
  721. sub_st = st;
  722. }
  723. }
  724. }
  725. if (sub_st) {
  726. ast = sub_st->priv_data;
  727. *pkt = ast->sub_pkt;
  728. pkt->stream_index = sub_st->index;
  729. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  730. ast->sub_pkt.data = NULL;
  731. }
  732. return sub_st;
  733. }
  734. static int get_stream_idx(int *d){
  735. if( d[0] >= '0' && d[0] <= '9'
  736. && d[1] >= '0' && d[1] <= '9'){
  737. return (d[0] - '0') * 10 + (d[1] - '0');
  738. }else{
  739. return 100; //invalid stream ID
  740. }
  741. }
  742. static int avi_sync(AVFormatContext *s, int exit_early)
  743. {
  744. AVIContext *avi = s->priv_data;
  745. AVIOContext *pb = s->pb;
  746. int n;
  747. unsigned int d[8];
  748. unsigned int size;
  749. int64_t i, sync;
  750. start_sync:
  751. memset(d, -1, sizeof(d));
  752. for(i=sync=avio_tell(pb); !pb->eof_reached; i++) {
  753. int j;
  754. for(j=0; j<7; j++)
  755. d[j]= d[j+1];
  756. d[7]= avio_r8(pb);
  757. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  758. n= get_stream_idx(d+2);
  759. av_dlog(s, "%X %X %X %X %X %X %X %X %"PRId64" %u %d\n",
  760. d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], i, size, n);
  761. if(i + (uint64_t)size > avi->fsize || d[0] > 127)
  762. continue;
  763. //parse ix##
  764. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  765. //parse JUNK
  766. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  767. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  768. avio_skip(pb, size);
  769. goto start_sync;
  770. }
  771. //parse stray LIST
  772. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  773. avio_skip(pb, 4);
  774. goto start_sync;
  775. }
  776. n= get_stream_idx(d);
  777. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  778. continue;
  779. //detect ##ix chunk and skip
  780. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  781. avio_skip(pb, size);
  782. goto start_sync;
  783. }
  784. //parse ##dc/##wb
  785. if(n < s->nb_streams){
  786. AVStream *st;
  787. AVIStream *ast;
  788. st = s->streams[n];
  789. ast = st->priv_data;
  790. if(s->nb_streams>=2){
  791. AVStream *st1 = s->streams[1];
  792. AVIStream *ast1= st1->priv_data;
  793. //workaround for broken small-file-bug402.avi
  794. if( d[2] == 'w' && d[3] == 'b'
  795. && n==0
  796. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  797. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  798. && ast->prefix == 'd'*256+'c'
  799. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  800. ){
  801. n=1;
  802. st = st1;
  803. ast = ast1;
  804. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  805. }
  806. }
  807. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  808. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  809. || st->discard >= AVDISCARD_ALL){
  810. if (!exit_early) {
  811. ast->frame_offset += get_duration(ast, size);
  812. }
  813. avio_skip(pb, size);
  814. goto start_sync;
  815. }
  816. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  817. int k = avio_r8(pb);
  818. int last = (k + avio_r8(pb) - 1) & 0xFF;
  819. avio_rl16(pb); //flags
  820. for (; k <= last; k++)
  821. ast->pal[k] = avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  822. ast->has_pal= 1;
  823. goto start_sync;
  824. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  825. d[2]*256+d[3] == ast->prefix /*||
  826. (d[2] == 'd' && d[3] == 'c') ||
  827. (d[2] == 'w' && d[3] == 'b')*/) {
  828. if (exit_early)
  829. return 0;
  830. if(d[2]*256+d[3] == ast->prefix)
  831. ast->prefix_count++;
  832. else{
  833. ast->prefix= d[2]*256+d[3];
  834. ast->prefix_count= 0;
  835. }
  836. avi->stream_index= n;
  837. ast->packet_size= size + 8;
  838. ast->remaining= size;
  839. if(size || !ast->sample_size){
  840. uint64_t pos= avio_tell(pb) - 8;
  841. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  842. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  843. }
  844. }
  845. return 0;
  846. }
  847. }
  848. }
  849. return AVERROR_EOF;
  850. }
  851. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  852. {
  853. AVIContext *avi = s->priv_data;
  854. AVIOContext *pb = s->pb;
  855. int err;
  856. #if FF_API_DESTRUCT_PACKET
  857. void* dstr;
  858. #endif
  859. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  860. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  861. if (size >= 0)
  862. return size;
  863. }
  864. if(avi->non_interleaved){
  865. int best_stream_index = 0;
  866. AVStream *best_st= NULL;
  867. AVIStream *best_ast;
  868. int64_t best_ts= INT64_MAX;
  869. int i;
  870. for(i=0; i<s->nb_streams; i++){
  871. AVStream *st = s->streams[i];
  872. AVIStream *ast = st->priv_data;
  873. int64_t ts= ast->frame_offset;
  874. int64_t last_ts;
  875. if(!st->nb_index_entries)
  876. continue;
  877. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  878. if(!ast->remaining && ts > last_ts)
  879. continue;
  880. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  881. av_dlog(s, "%"PRId64" %d/%d %"PRId64"\n", ts,
  882. st->time_base.num, st->time_base.den, ast->frame_offset);
  883. if(ts < best_ts){
  884. best_ts= ts;
  885. best_st= st;
  886. best_stream_index= i;
  887. }
  888. }
  889. if(!best_st)
  890. return AVERROR_EOF;
  891. best_ast = best_st->priv_data;
  892. best_ts = av_rescale_q(best_ts, (AVRational){FFMAX(1, best_ast->sample_size), AV_TIME_BASE}, best_st->time_base);
  893. if(best_ast->remaining)
  894. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  895. else{
  896. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  897. if(i>=0)
  898. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  899. }
  900. if(i>=0){
  901. int64_t pos= best_st->index_entries[i].pos;
  902. pos += best_ast->packet_size - best_ast->remaining;
  903. avio_seek(s->pb, pos + 8, SEEK_SET);
  904. assert(best_ast->remaining <= best_ast->packet_size);
  905. avi->stream_index= best_stream_index;
  906. if(!best_ast->remaining)
  907. best_ast->packet_size=
  908. best_ast->remaining= best_st->index_entries[i].size;
  909. }
  910. }
  911. resync:
  912. if(avi->stream_index >= 0){
  913. AVStream *st= s->streams[ avi->stream_index ];
  914. AVIStream *ast= st->priv_data;
  915. int size, err;
  916. if(get_subtitle_pkt(s, st, pkt))
  917. return 0;
  918. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  919. size= INT_MAX;
  920. else if(ast->sample_size < 32)
  921. // arbitrary multiplier to avoid tiny packets for raw PCM data
  922. size= 1024*ast->sample_size;
  923. else
  924. size= ast->sample_size;
  925. if(size > ast->remaining)
  926. size= ast->remaining;
  927. avi->last_pkt_pos= avio_tell(pb);
  928. err= av_get_packet(pb, pkt, size);
  929. if(err<0)
  930. return err;
  931. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  932. uint8_t *pal;
  933. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  934. if(!pal){
  935. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  936. }else{
  937. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  938. ast->has_pal = 0;
  939. }
  940. }
  941. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  942. AVBufferRef *avbuf = pkt->buf;
  943. #if FF_API_DESTRUCT_PACKET
  944. dstr = pkt->destruct;
  945. #endif
  946. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  947. pkt->data, pkt->size);
  948. #if FF_API_DESTRUCT_PACKET
  949. pkt->destruct = dstr;
  950. #endif
  951. pkt->buf = avbuf;
  952. pkt->flags |= AV_PKT_FLAG_KEY;
  953. if (size < 0)
  954. av_free_packet(pkt);
  955. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  956. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  957. ast->frame_offset++;
  958. avi->stream_index = -1;
  959. ast->remaining = 0;
  960. goto resync;
  961. } else {
  962. /* XXX: How to handle B-frames in AVI? */
  963. pkt->dts = ast->frame_offset;
  964. // pkt->dts += ast->start;
  965. if(ast->sample_size)
  966. pkt->dts /= ast->sample_size;
  967. av_dlog(s, "dts:%"PRId64" offset:%"PRId64" %d/%d smpl_siz:%d base:%d st:%d size:%d\n",
  968. pkt->dts, ast->frame_offset, ast->scale, ast->rate,
  969. ast->sample_size, AV_TIME_BASE, avi->stream_index, size);
  970. pkt->stream_index = avi->stream_index;
  971. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  972. AVIndexEntry *e;
  973. int index;
  974. assert(st->index_entries);
  975. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  976. e= &st->index_entries[index];
  977. if(index >= 0 && e->timestamp == ast->frame_offset){
  978. if (e->flags & AVINDEX_KEYFRAME)
  979. pkt->flags |= AV_PKT_FLAG_KEY;
  980. }
  981. } else {
  982. pkt->flags |= AV_PKT_FLAG_KEY;
  983. }
  984. ast->frame_offset += get_duration(ast, pkt->size);
  985. }
  986. ast->remaining -= err;
  987. if(!ast->remaining){
  988. avi->stream_index= -1;
  989. ast->packet_size= 0;
  990. }
  991. return 0;
  992. }
  993. if ((err = avi_sync(s, 0)) < 0)
  994. return err;
  995. goto resync;
  996. }
  997. /* XXX: We make the implicit supposition that the positions are sorted
  998. for each stream. */
  999. static int avi_read_idx1(AVFormatContext *s, int size)
  1000. {
  1001. AVIContext *avi = s->priv_data;
  1002. AVIOContext *pb = s->pb;
  1003. int nb_index_entries, i;
  1004. AVStream *st;
  1005. AVIStream *ast;
  1006. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1007. unsigned last_pos= -1;
  1008. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1009. nb_index_entries = size / 16;
  1010. if (nb_index_entries <= 0)
  1011. return AVERROR_INVALIDDATA;
  1012. idx1_pos = avio_tell(pb);
  1013. avio_seek(pb, avi->movi_list+4, SEEK_SET);
  1014. if (avi_sync(s, 1) == 0) {
  1015. first_packet_pos = avio_tell(pb) - 8;
  1016. }
  1017. avi->stream_index = -1;
  1018. avio_seek(pb, idx1_pos, SEEK_SET);
  1019. /* Read the entries and sort them in each stream component. */
  1020. for(i = 0; i < nb_index_entries; i++) {
  1021. tag = avio_rl32(pb);
  1022. flags = avio_rl32(pb);
  1023. pos = avio_rl32(pb);
  1024. len = avio_rl32(pb);
  1025. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1026. i, tag, flags, pos, len);
  1027. index = ((tag & 0xff) - '0') * 10;
  1028. index += ((tag >> 8) & 0xff) - '0';
  1029. if (index >= s->nb_streams)
  1030. continue;
  1031. st = s->streams[index];
  1032. ast = st->priv_data;
  1033. if(first_packet && first_packet_pos && len) {
  1034. data_offset = first_packet_pos - pos;
  1035. first_packet = 0;
  1036. }
  1037. pos += data_offset;
  1038. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1039. if(pb->eof_reached)
  1040. return AVERROR_INVALIDDATA;
  1041. if(last_pos == pos)
  1042. avi->non_interleaved= 1;
  1043. else if(len || !ast->sample_size)
  1044. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1045. ast->cum_len += get_duration(ast, len);
  1046. last_pos= pos;
  1047. }
  1048. return 0;
  1049. }
  1050. static int guess_ni_flag(AVFormatContext *s){
  1051. int i;
  1052. int64_t last_start=0;
  1053. int64_t first_end= INT64_MAX;
  1054. int64_t oldpos= avio_tell(s->pb);
  1055. for(i=0; i<s->nb_streams; i++){
  1056. AVStream *st = s->streams[i];
  1057. int n= st->nb_index_entries;
  1058. unsigned int size;
  1059. if(n <= 0)
  1060. continue;
  1061. if(n >= 2){
  1062. int64_t pos= st->index_entries[0].pos;
  1063. avio_seek(s->pb, pos + 4, SEEK_SET);
  1064. size= avio_rl32(s->pb);
  1065. if(pos + size > st->index_entries[1].pos)
  1066. last_start= INT64_MAX;
  1067. }
  1068. if(st->index_entries[0].pos > last_start)
  1069. last_start= st->index_entries[0].pos;
  1070. if(st->index_entries[n-1].pos < first_end)
  1071. first_end= st->index_entries[n-1].pos;
  1072. }
  1073. avio_seek(s->pb, oldpos, SEEK_SET);
  1074. return last_start > first_end;
  1075. }
  1076. static int avi_load_index(AVFormatContext *s)
  1077. {
  1078. AVIContext *avi = s->priv_data;
  1079. AVIOContext *pb = s->pb;
  1080. uint32_t tag, size;
  1081. int64_t pos= avio_tell(pb);
  1082. int ret = -1;
  1083. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1084. goto the_end; // maybe truncated file
  1085. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1086. for(;;) {
  1087. if (pb->eof_reached)
  1088. break;
  1089. tag = avio_rl32(pb);
  1090. size = avio_rl32(pb);
  1091. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1092. tag & 0xff,
  1093. (tag >> 8) & 0xff,
  1094. (tag >> 16) & 0xff,
  1095. (tag >> 24) & 0xff,
  1096. size);
  1097. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1098. avi_read_idx1(s, size) >= 0) {
  1099. ret = 0;
  1100. break;
  1101. }
  1102. size += (size & 1);
  1103. if (avio_skip(pb, size) < 0)
  1104. break; // something is wrong here
  1105. }
  1106. the_end:
  1107. avio_seek(pb, pos, SEEK_SET);
  1108. return ret;
  1109. }
  1110. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1111. {
  1112. AVIStream *ast2 = st2->priv_data;
  1113. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1114. av_free_packet(&ast2->sub_pkt);
  1115. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1116. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1117. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1118. }
  1119. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1120. {
  1121. AVIContext *avi = s->priv_data;
  1122. AVStream *st;
  1123. int i, index;
  1124. int64_t pos;
  1125. AVIStream *ast;
  1126. if (!avi->index_loaded) {
  1127. /* we only load the index on demand */
  1128. avi_load_index(s);
  1129. avi->index_loaded = 1;
  1130. }
  1131. assert(stream_index>= 0);
  1132. st = s->streams[stream_index];
  1133. ast= st->priv_data;
  1134. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1135. if(index<0)
  1136. return AVERROR_INVALIDDATA;
  1137. /* find the position */
  1138. pos = st->index_entries[index].pos;
  1139. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1140. av_dlog(s, "XX %"PRId64" %d %"PRId64"\n",
  1141. timestamp, index, st->index_entries[index].timestamp);
  1142. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1143. /* One and only one real stream for DV in AVI, and it has video */
  1144. /* offsets. Calling with other stream indexes should have failed */
  1145. /* the av_index_search_timestamp call above. */
  1146. assert(stream_index == 0);
  1147. /* Feed the DV video stream version of the timestamp to the */
  1148. /* DV demux so it can synthesize correct timestamps. */
  1149. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1150. avio_seek(s->pb, pos, SEEK_SET);
  1151. avi->stream_index= -1;
  1152. return 0;
  1153. }
  1154. for(i = 0; i < s->nb_streams; i++) {
  1155. AVStream *st2 = s->streams[i];
  1156. AVIStream *ast2 = st2->priv_data;
  1157. ast2->packet_size=
  1158. ast2->remaining= 0;
  1159. if (ast2->sub_ctx) {
  1160. seek_subtitle(st, st2, timestamp);
  1161. continue;
  1162. }
  1163. if (st2->nb_index_entries <= 0)
  1164. continue;
  1165. // assert(st2->codec->block_align);
  1166. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1167. index = av_index_search_timestamp(
  1168. st2,
  1169. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1170. flags | AVSEEK_FLAG_BACKWARD);
  1171. if(index<0)
  1172. index=0;
  1173. if(!avi->non_interleaved){
  1174. while(index>0 && st2->index_entries[index].pos > pos)
  1175. index--;
  1176. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  1177. index++;
  1178. }
  1179. av_dlog(s, "%"PRId64" %d %"PRId64"\n",
  1180. timestamp, index, st2->index_entries[index].timestamp);
  1181. /* extract the current frame number */
  1182. ast2->frame_offset = st2->index_entries[index].timestamp;
  1183. }
  1184. /* do the seek */
  1185. avio_seek(s->pb, pos, SEEK_SET);
  1186. avi->stream_index= -1;
  1187. return 0;
  1188. }
  1189. static int avi_read_close(AVFormatContext *s)
  1190. {
  1191. int i;
  1192. AVIContext *avi = s->priv_data;
  1193. for(i=0;i<s->nb_streams;i++) {
  1194. AVStream *st = s->streams[i];
  1195. AVIStream *ast = st->priv_data;
  1196. if (ast) {
  1197. if (ast->sub_ctx) {
  1198. av_freep(&ast->sub_ctx->pb);
  1199. avformat_close_input(&ast->sub_ctx);
  1200. }
  1201. av_free(ast->sub_buffer);
  1202. av_free_packet(&ast->sub_pkt);
  1203. }
  1204. }
  1205. av_free(avi->dv_demux);
  1206. return 0;
  1207. }
  1208. static int avi_probe(AVProbeData *p)
  1209. {
  1210. int i;
  1211. /* check file header */
  1212. for(i=0; avi_headers[i][0]; i++)
  1213. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1214. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1215. return AVPROBE_SCORE_MAX;
  1216. return 0;
  1217. }
  1218. AVInputFormat ff_avi_demuxer = {
  1219. .name = "avi",
  1220. .long_name = NULL_IF_CONFIG_SMALL("AVI (Audio Video Interleaved)"),
  1221. .priv_data_size = sizeof(AVIContext),
  1222. .read_probe = avi_probe,
  1223. .read_header = avi_read_header,
  1224. .read_packet = avi_read_packet,
  1225. .read_close = avi_read_close,
  1226. .read_seek = avi_read_seek,
  1227. };