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.

1393 lines
46KB

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