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.

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