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.

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