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.

1079 lines
35KB

  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. #include "avformat.h"
  22. #include "avi.h"
  23. #include "dv.h"
  24. #include "riff.h"
  25. #undef NDEBUG
  26. #include <assert.h>
  27. //#define DEBUG
  28. //#define DEBUG_SEEK
  29. typedef struct AVIStream {
  30. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  31. (used to compute the pts) */
  32. int remaining;
  33. int packet_size;
  34. int scale;
  35. int rate;
  36. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  37. int64_t cum_len; /* temporary storage (used during seek) */
  38. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  39. int prefix_count;
  40. } AVIStream;
  41. typedef struct {
  42. int64_t riff_end;
  43. int64_t movi_end;
  44. int64_t fsize;
  45. offset_t movi_list;
  46. int index_loaded;
  47. int is_odml;
  48. int non_interleaved;
  49. int stream_index;
  50. DVDemuxContext* dv_demux;
  51. } AVIContext;
  52. static const char avi_headers[][8] = {
  53. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  54. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  55. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  56. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  57. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  58. { 0 }
  59. };
  60. static int avi_load_index(AVFormatContext *s);
  61. static int guess_ni_flag(AVFormatContext *s);
  62. #ifdef DEBUG
  63. static void print_tag(const char *str, unsigned int tag, int size)
  64. {
  65. printf("%s: tag=%c%c%c%c size=0x%x\n",
  66. str, tag & 0xff,
  67. (tag >> 8) & 0xff,
  68. (tag >> 16) & 0xff,
  69. (tag >> 24) & 0xff,
  70. size);
  71. }
  72. #endif
  73. static int get_riff(AVIContext *avi, ByteIOContext *pb)
  74. {
  75. char header[8];
  76. int i;
  77. /* check RIFF header */
  78. get_buffer(pb, header, 4);
  79. avi->riff_end = get_le32(pb); /* RIFF chunk size */
  80. avi->riff_end += url_ftell(pb); /* RIFF chunk end */
  81. get_buffer(pb, header+4, 4);
  82. for(i=0; avi_headers[i][0]; i++)
  83. if(!memcmp(header, avi_headers[i], 8))
  84. break;
  85. if(!avi_headers[i][0])
  86. return -1;
  87. if(header[7] == 0x19)
  88. av_log(NULL, AV_LOG_INFO, "file has been generated with a totally broken muxer\n");
  89. return 0;
  90. }
  91. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  92. AVIContext *avi = s->priv_data;
  93. ByteIOContext *pb = s->pb;
  94. int longs_pre_entry= get_le16(pb);
  95. int index_sub_type = get_byte(pb);
  96. int index_type = get_byte(pb);
  97. int entries_in_use = get_le32(pb);
  98. int chunk_id = get_le32(pb);
  99. int64_t base = get_le64(pb);
  100. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  101. AVStream *st;
  102. AVIStream *ast;
  103. int i;
  104. int64_t last_pos= -1;
  105. int64_t filesize= url_fsize(s->pb);
  106. #ifdef DEBUG_SEEK
  107. av_log(s, AV_LOG_ERROR, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  108. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  109. #endif
  110. if(stream_id > s->nb_streams || stream_id < 0)
  111. return -1;
  112. st= s->streams[stream_id];
  113. ast = st->priv_data;
  114. if(index_sub_type)
  115. return -1;
  116. get_le32(pb);
  117. if(index_type && longs_pre_entry != 2)
  118. return -1;
  119. if(index_type>1)
  120. return -1;
  121. if(filesize > 0 && base >= filesize){
  122. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  123. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  124. base &= 0xFFFFFFFF;
  125. else
  126. return -1;
  127. }
  128. for(i=0; i<entries_in_use; i++){
  129. if(index_type){
  130. int64_t pos= get_le32(pb) + base - 8;
  131. int len = get_le32(pb);
  132. int key= len >= 0;
  133. len &= 0x7FFFFFFF;
  134. #ifdef DEBUG_SEEK
  135. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  136. #endif
  137. if(last_pos == pos || pos == base - 8)
  138. avi->non_interleaved= 1;
  139. else
  140. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, key ? AVINDEX_KEYFRAME : 0);
  141. if(ast->sample_size)
  142. ast->cum_len += len;
  143. else
  144. ast->cum_len ++;
  145. last_pos= pos;
  146. }else{
  147. int64_t offset, pos;
  148. int duration;
  149. offset = get_le64(pb);
  150. get_le32(pb); /* size */
  151. duration = get_le32(pb);
  152. pos = url_ftell(pb);
  153. url_fseek(pb, offset+8, SEEK_SET);
  154. read_braindead_odml_indx(s, frame_num);
  155. frame_num += duration;
  156. url_fseek(pb, pos, SEEK_SET);
  157. }
  158. }
  159. avi->index_loaded=1;
  160. return 0;
  161. }
  162. static void clean_index(AVFormatContext *s){
  163. int i;
  164. int64_t j;
  165. for(i=0; i<s->nb_streams; i++){
  166. AVStream *st = s->streams[i];
  167. AVIStream *ast = st->priv_data;
  168. int n= st->nb_index_entries;
  169. int max= ast->sample_size;
  170. int64_t pos, size, ts;
  171. if(n != 1 || ast->sample_size==0)
  172. continue;
  173. while(max < 1024) max+=max;
  174. pos= st->index_entries[0].pos;
  175. size= st->index_entries[0].size;
  176. ts= st->index_entries[0].timestamp;
  177. for(j=0; j<size; j+=max){
  178. av_add_index_entry(st, pos+j, ts + j/ast->sample_size, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  179. }
  180. }
  181. }
  182. static int avi_read_tag(ByteIOContext *pb, char *buf, int maxlen, unsigned int size)
  183. {
  184. offset_t i = url_ftell(pb);
  185. size += (size & 1);
  186. get_strz(pb, buf, maxlen);
  187. url_fseek(pb, i+size, SEEK_SET);
  188. return 0;
  189. }
  190. static int avi_read_header(AVFormatContext *s, AVFormatParameters *ap)
  191. {
  192. AVIContext *avi = s->priv_data;
  193. ByteIOContext *pb = s->pb;
  194. uint32_t tag, tag1, handler;
  195. int codec_type, stream_index, frame_period, bit_rate;
  196. unsigned int size, nb_frames;
  197. int i;
  198. AVStream *st;
  199. AVIStream *ast = NULL;
  200. char str_track[4];
  201. int avih_width=0, avih_height=0;
  202. int amv_file_format=0;
  203. avi->stream_index= -1;
  204. if (get_riff(avi, pb) < 0)
  205. return -1;
  206. avi->fsize = url_fsize(pb);
  207. if(avi->fsize<=0)
  208. avi->fsize= avi->riff_end;
  209. /* first list tag */
  210. stream_index = -1;
  211. codec_type = -1;
  212. frame_period = 0;
  213. for(;;) {
  214. if (url_feof(pb))
  215. goto fail;
  216. tag = get_le32(pb);
  217. size = get_le32(pb);
  218. #ifdef DEBUG
  219. print_tag("tag", tag, size);
  220. #endif
  221. switch(tag) {
  222. case MKTAG('L', 'I', 'S', 'T'):
  223. /* ignored, except when start of video packets */
  224. tag1 = get_le32(pb);
  225. #ifdef DEBUG
  226. print_tag("list", tag1, 0);
  227. #endif
  228. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  229. avi->movi_list = url_ftell(pb) - 4;
  230. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  231. else avi->movi_end = url_fsize(pb);
  232. #ifdef DEBUG
  233. printf("movi end=%"PRIx64"\n", avi->movi_end);
  234. #endif
  235. goto end_of_header;
  236. }
  237. break;
  238. case MKTAG('d', 'm', 'l', 'h'):
  239. avi->is_odml = 1;
  240. url_fskip(pb, size + (size & 1));
  241. break;
  242. case MKTAG('a', 'm', 'v', 'h'):
  243. amv_file_format=1;
  244. case MKTAG('a', 'v', 'i', 'h'):
  245. /* avi header */
  246. /* using frame_period is bad idea */
  247. frame_period = get_le32(pb);
  248. bit_rate = get_le32(pb) * 8;
  249. get_le32(pb);
  250. avi->non_interleaved |= get_le32(pb) & AVIF_MUSTUSEINDEX;
  251. url_fskip(pb, 2 * 4);
  252. get_le32(pb);
  253. get_le32(pb);
  254. avih_width=get_le32(pb);
  255. avih_height=get_le32(pb);
  256. url_fskip(pb, size - 10 * 4);
  257. break;
  258. case MKTAG('s', 't', 'r', 'h'):
  259. /* stream header */
  260. tag1 = get_le32(pb);
  261. handler = get_le32(pb); /* codec tag */
  262. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  263. url_fskip(pb, size - 8);
  264. break;
  265. }else{
  266. stream_index++;
  267. st = av_new_stream(s, stream_index);
  268. if (!st)
  269. goto fail;
  270. ast = av_mallocz(sizeof(AVIStream));
  271. if (!ast)
  272. goto fail;
  273. st->priv_data = ast;
  274. }
  275. if(amv_file_format)
  276. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  277. #ifdef DEBUG
  278. print_tag("strh", tag1, -1);
  279. #endif
  280. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  281. int64_t dv_dur;
  282. /*
  283. * After some consideration -- I don't think we
  284. * have to support anything but DV in a type1 AVIs.
  285. */
  286. if (s->nb_streams != 1)
  287. goto fail;
  288. if (handler != MKTAG('d', 'v', 's', 'd') &&
  289. handler != MKTAG('d', 'v', 'h', 'd') &&
  290. handler != MKTAG('d', 'v', 's', 'l'))
  291. goto fail;
  292. ast = s->streams[0]->priv_data;
  293. av_freep(&s->streams[0]->codec->extradata);
  294. av_freep(&s->streams[0]);
  295. s->nb_streams = 0;
  296. if (ENABLE_DV_DEMUXER) {
  297. avi->dv_demux = dv_init_demux(s);
  298. if (!avi->dv_demux)
  299. goto fail;
  300. }
  301. s->streams[0]->priv_data = ast;
  302. url_fskip(pb, 3 * 4);
  303. ast->scale = get_le32(pb);
  304. ast->rate = get_le32(pb);
  305. url_fskip(pb, 4); /* start time */
  306. dv_dur = get_le32(pb);
  307. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  308. dv_dur *= AV_TIME_BASE;
  309. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  310. }
  311. /*
  312. * else, leave duration alone; timing estimation in utils.c
  313. * will make a guess based on bit rate.
  314. */
  315. stream_index = s->nb_streams - 1;
  316. url_fskip(pb, size - 9*4);
  317. break;
  318. }
  319. assert(stream_index < s->nb_streams);
  320. st->codec->stream_codec_tag= handler;
  321. get_le32(pb); /* flags */
  322. get_le16(pb); /* priority */
  323. get_le16(pb); /* language */
  324. get_le32(pb); /* initial frame */
  325. ast->scale = get_le32(pb);
  326. ast->rate = get_le32(pb);
  327. if(ast->scale && ast->rate){
  328. }else if(frame_period){
  329. ast->rate = 1000000;
  330. ast->scale = frame_period;
  331. }else{
  332. ast->rate = 25;
  333. ast->scale = 1;
  334. }
  335. av_set_pts_info(st, 64, ast->scale, ast->rate);
  336. ast->cum_len=get_le32(pb); /* start */
  337. nb_frames = get_le32(pb);
  338. st->start_time = 0;
  339. st->duration = nb_frames;
  340. get_le32(pb); /* buffer size */
  341. get_le32(pb); /* quality */
  342. ast->sample_size = get_le32(pb); /* sample ssize */
  343. ast->cum_len *= FFMAX(1, ast->sample_size);
  344. // av_log(NULL, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  345. switch(tag1) {
  346. case MKTAG('v', 'i', 'd', 's'):
  347. codec_type = CODEC_TYPE_VIDEO;
  348. ast->sample_size = 0;
  349. break;
  350. case MKTAG('a', 'u', 'd', 's'):
  351. codec_type = CODEC_TYPE_AUDIO;
  352. break;
  353. case MKTAG('t', 'x', 't', 's'):
  354. //FIXME
  355. codec_type = CODEC_TYPE_DATA; //CODEC_TYPE_SUB ? FIXME
  356. break;
  357. default:
  358. av_log(s, AV_LOG_ERROR, "unknown stream type %X\n", tag1);
  359. goto fail;
  360. }
  361. ast->frame_offset= ast->cum_len;
  362. url_fskip(pb, size - 12 * 4);
  363. break;
  364. case MKTAG('s', 't', 'r', 'f'):
  365. /* stream header */
  366. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  367. url_fskip(pb, size);
  368. } else {
  369. st = s->streams[stream_index];
  370. switch(codec_type) {
  371. case CODEC_TYPE_VIDEO:
  372. if(amv_file_format){
  373. st->codec->width=avih_width;
  374. st->codec->height=avih_height;
  375. st->codec->codec_type = CODEC_TYPE_VIDEO;
  376. st->codec->codec_id = CODEC_ID_AMV;
  377. url_fskip(pb, size);
  378. break;
  379. }
  380. get_le32(pb); /* size */
  381. st->codec->width = get_le32(pb);
  382. st->codec->height = get_le32(pb);
  383. get_le16(pb); /* panes */
  384. st->codec->bits_per_sample= get_le16(pb); /* depth */
  385. tag1 = get_le32(pb);
  386. get_le32(pb); /* ImageSize */
  387. get_le32(pb); /* XPelsPerMeter */
  388. get_le32(pb); /* YPelsPerMeter */
  389. get_le32(pb); /* ClrUsed */
  390. get_le32(pb); /* ClrImportant */
  391. if (tag1 == MKTAG('D', 'X', 'S', 'B')) {
  392. st->codec->codec_type = CODEC_TYPE_SUBTITLE;
  393. st->codec->codec_tag = tag1;
  394. st->codec->codec_id = CODEC_ID_XSUB;
  395. break;
  396. }
  397. if(size > 10*4 && size<(1<<30)){
  398. st->codec->extradata_size= size - 10*4;
  399. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  400. get_buffer(pb, st->codec->extradata, st->codec->extradata_size);
  401. }
  402. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  403. get_byte(pb);
  404. /* Extract palette from extradata if bpp <= 8 */
  405. /* This code assumes that extradata contains only palette */
  406. /* This is true for all paletted codecs implemented in ffmpeg */
  407. if (st->codec->extradata_size && (st->codec->bits_per_sample <= 8)) {
  408. st->codec->palctrl = av_mallocz(sizeof(AVPaletteControl));
  409. #ifdef WORDS_BIGENDIAN
  410. for (i = 0; i < FFMIN(st->codec->extradata_size, AVPALETTE_SIZE)/4; i++)
  411. st->codec->palctrl->palette[i] = bswap_32(((uint32_t*)st->codec->extradata)[i]);
  412. #else
  413. memcpy(st->codec->palctrl->palette, st->codec->extradata,
  414. FFMIN(st->codec->extradata_size, AVPALETTE_SIZE));
  415. #endif
  416. st->codec->palctrl->palette_changed = 1;
  417. }
  418. #ifdef DEBUG
  419. print_tag("video", tag1, 0);
  420. #endif
  421. st->codec->codec_type = CODEC_TYPE_VIDEO;
  422. st->codec->codec_tag = tag1;
  423. st->codec->codec_id = codec_get_id(codec_bmp_tags, tag1);
  424. st->need_parsing = AVSTREAM_PARSE_HEADERS; // this is needed to get the pict type which is needed for generating correct pts
  425. // url_fskip(pb, size - 5 * 4);
  426. break;
  427. case CODEC_TYPE_AUDIO:
  428. get_wav_header(pb, st->codec, size);
  429. if(ast->sample_size && st->codec->block_align && ast->sample_size % st->codec->block_align)
  430. av_log(s, AV_LOG_DEBUG, "invalid sample size or block align detected\n");
  431. if (size%2) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  432. url_fskip(pb, 1);
  433. /* Force parsing as several audio frames can be in
  434. * one packet and timestamps refer to packet start*/
  435. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  436. /* ADTS header is in extradata, AAC without header must be stored as exact frames, parser not needed and it will fail */
  437. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  438. st->need_parsing = AVSTREAM_PARSE_NONE;
  439. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  440. * audio in the header but have Axan as stream_code_tag. */
  441. if (st->codec->stream_codec_tag == ff_get_fourcc("Axan")){
  442. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  443. st->codec->codec_tag = 0;
  444. }
  445. if (amv_file_format)
  446. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  447. break;
  448. default:
  449. st->codec->codec_type = CODEC_TYPE_DATA;
  450. st->codec->codec_id= CODEC_ID_NONE;
  451. st->codec->codec_tag= 0;
  452. url_fskip(pb, size);
  453. break;
  454. }
  455. }
  456. break;
  457. case MKTAG('i', 'n', 'd', 'x'):
  458. i= url_ftell(pb);
  459. if(!url_is_streamed(pb) && !(s->flags & AVFMT_FLAG_IGNIDX)){
  460. read_braindead_odml_indx(s, 0);
  461. }
  462. url_fseek(pb, i+size, SEEK_SET);
  463. break;
  464. case MKTAG('v', 'p', 'r', 'p'):
  465. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  466. AVRational active, active_aspect;
  467. st = s->streams[stream_index];
  468. get_le32(pb);
  469. get_le32(pb);
  470. get_le32(pb);
  471. get_le32(pb);
  472. get_le32(pb);
  473. active_aspect.num= get_le16(pb);
  474. active_aspect.den= get_le16(pb);
  475. active.num = get_le32(pb);
  476. active.den = get_le32(pb);
  477. get_le32(pb); //nbFieldsPerFrame
  478. if(active_aspect.num && active_aspect.den && active.num && active.den){
  479. st->codec->sample_aspect_ratio= av_div_q(active_aspect, active);
  480. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  481. }
  482. size -= 9*4;
  483. }
  484. url_fseek(pb, size, SEEK_CUR);
  485. break;
  486. case MKTAG('I', 'N', 'A', 'M'):
  487. avi_read_tag(pb, s->title, sizeof(s->title), size);
  488. break;
  489. case MKTAG('I', 'A', 'R', 'T'):
  490. avi_read_tag(pb, s->author, sizeof(s->author), size);
  491. break;
  492. case MKTAG('I', 'C', 'O', 'P'):
  493. avi_read_tag(pb, s->copyright, sizeof(s->copyright), size);
  494. break;
  495. case MKTAG('I', 'C', 'M', 'T'):
  496. avi_read_tag(pb, s->comment, sizeof(s->comment), size);
  497. break;
  498. case MKTAG('I', 'G', 'N', 'R'):
  499. avi_read_tag(pb, s->genre, sizeof(s->genre), size);
  500. break;
  501. case MKTAG('I', 'P', 'R', 'D'):
  502. avi_read_tag(pb, s->album, sizeof(s->album), size);
  503. break;
  504. case MKTAG('I', 'P', 'R', 'T'):
  505. avi_read_tag(pb, str_track, sizeof(str_track), size);
  506. sscanf(str_track, "%d", &s->track);
  507. break;
  508. default:
  509. if(size > 1000000){
  510. av_log(s, AV_LOG_ERROR, "well something went wrong during header parsing, "
  511. "ill ignore it and try to continue anyway\n");
  512. avi->movi_list = url_ftell(pb) - 4;
  513. avi->movi_end = url_fsize(pb);
  514. goto end_of_header;
  515. }
  516. /* skip tag */
  517. size += (size & 1);
  518. url_fskip(pb, size);
  519. break;
  520. }
  521. }
  522. end_of_header:
  523. /* check stream number */
  524. if (stream_index != s->nb_streams - 1) {
  525. fail:
  526. for(i=0;i<s->nb_streams;i++) {
  527. av_freep(&s->streams[i]->codec->extradata);
  528. av_freep(&s->streams[i]);
  529. }
  530. return -1;
  531. }
  532. if(!avi->index_loaded && !url_is_streamed(pb))
  533. avi_load_index(s);
  534. avi->index_loaded = 1;
  535. avi->non_interleaved |= guess_ni_flag(s);
  536. if(avi->non_interleaved)
  537. clean_index(s);
  538. return 0;
  539. }
  540. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  541. {
  542. AVIContext *avi = s->priv_data;
  543. ByteIOContext *pb = s->pb;
  544. int n, d[8], size;
  545. offset_t i, sync;
  546. void* dstr;
  547. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  548. size = dv_get_packet(avi->dv_demux, pkt);
  549. if (size >= 0)
  550. return size;
  551. }
  552. if(avi->non_interleaved){
  553. int best_stream_index = 0;
  554. AVStream *best_st= NULL;
  555. AVIStream *best_ast;
  556. int64_t best_ts= INT64_MAX;
  557. int i;
  558. for(i=0; i<s->nb_streams; i++){
  559. AVStream *st = s->streams[i];
  560. AVIStream *ast = st->priv_data;
  561. int64_t ts= ast->frame_offset;
  562. if(ast->sample_size)
  563. ts /= ast->sample_size;
  564. ts= av_rescale(ts, AV_TIME_BASE * (int64_t)st->time_base.num, st->time_base.den);
  565. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  566. if(ts < best_ts){
  567. best_ts= ts;
  568. best_st= st;
  569. best_stream_index= i;
  570. }
  571. }
  572. best_ast = best_st->priv_data;
  573. best_ts= av_rescale(best_ts, best_st->time_base.den, AV_TIME_BASE * (int64_t)best_st->time_base.num); //FIXME a little ugly
  574. if(best_ast->remaining)
  575. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  576. else
  577. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  578. // av_log(NULL, AV_LOG_DEBUG, "%d\n", i);
  579. if(i>=0){
  580. int64_t pos= best_st->index_entries[i].pos;
  581. pos += best_ast->packet_size - best_ast->remaining;
  582. url_fseek(s->pb, pos + 8, SEEK_SET);
  583. // av_log(NULL, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  584. assert(best_ast->remaining <= best_ast->packet_size);
  585. avi->stream_index= best_stream_index;
  586. if(!best_ast->remaining)
  587. best_ast->packet_size=
  588. best_ast->remaining= best_st->index_entries[i].size;
  589. }
  590. }
  591. resync:
  592. if(avi->stream_index >= 0){
  593. AVStream *st= s->streams[ avi->stream_index ];
  594. AVIStream *ast= st->priv_data;
  595. int size;
  596. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  597. size= INT_MAX;
  598. else if(ast->sample_size < 32)
  599. size= 64*ast->sample_size;
  600. else
  601. size= ast->sample_size;
  602. if(size > ast->remaining)
  603. size= ast->remaining;
  604. av_get_packet(pb, pkt, size);
  605. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  606. dstr = pkt->destruct;
  607. size = dv_produce_packet(avi->dv_demux, pkt,
  608. pkt->data, pkt->size);
  609. pkt->destruct = dstr;
  610. pkt->flags |= PKT_FLAG_KEY;
  611. } else {
  612. /* XXX: how to handle B frames in avi ? */
  613. pkt->dts = ast->frame_offset;
  614. // pkt->dts += ast->start;
  615. if(ast->sample_size)
  616. pkt->dts /= ast->sample_size;
  617. //av_log(NULL, 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);
  618. pkt->stream_index = avi->stream_index;
  619. if (st->codec->codec_type == CODEC_TYPE_VIDEO) {
  620. AVIndexEntry *e;
  621. int index;
  622. assert(st->index_entries);
  623. index= av_index_search_timestamp(st, pkt->dts, 0);
  624. e= &st->index_entries[index];
  625. if(index >= 0 && e->timestamp == ast->frame_offset){
  626. if (e->flags & AVINDEX_KEYFRAME)
  627. pkt->flags |= PKT_FLAG_KEY;
  628. }
  629. } else {
  630. pkt->flags |= PKT_FLAG_KEY;
  631. }
  632. if(ast->sample_size)
  633. ast->frame_offset += pkt->size;
  634. else
  635. ast->frame_offset++;
  636. }
  637. ast->remaining -= size;
  638. if(!ast->remaining){
  639. avi->stream_index= -1;
  640. ast->packet_size= 0;
  641. }
  642. return size;
  643. }
  644. memset(d, -1, sizeof(int)*8);
  645. for(i=sync=url_ftell(pb); !url_feof(pb); i++) {
  646. int j;
  647. for(j=0; j<7; j++)
  648. d[j]= d[j+1];
  649. d[7]= get_byte(pb);
  650. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  651. if( d[2] >= '0' && d[2] <= '9'
  652. && d[3] >= '0' && d[3] <= '9'){
  653. n= (d[2] - '0') * 10 + (d[3] - '0');
  654. }else{
  655. n= 100; //invalid stream id
  656. }
  657. //av_log(NULL, 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);
  658. if(i + size > avi->fsize || d[0]<0)
  659. continue;
  660. //parse ix##
  661. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  662. //parse JUNK
  663. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  664. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  665. url_fskip(pb, size);
  666. //av_log(NULL, AV_LOG_DEBUG, "SKIP\n");
  667. goto resync;
  668. }
  669. if( d[0] >= '0' && d[0] <= '9'
  670. && d[1] >= '0' && d[1] <= '9'){
  671. n= (d[0] - '0') * 10 + (d[1] - '0');
  672. }else{
  673. n= 100; //invalid stream id
  674. }
  675. //parse ##dc/##wb
  676. if(n < s->nb_streams){
  677. AVStream *st;
  678. AVIStream *ast;
  679. st = s->streams[n];
  680. ast = st->priv_data;
  681. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  682. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  683. || st->discard >= AVDISCARD_ALL){
  684. if(ast->sample_size) ast->frame_offset += pkt->size;
  685. else ast->frame_offset++;
  686. url_fskip(pb, size);
  687. goto resync;
  688. }
  689. if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  690. d[2]*256+d[3] == ast->prefix /*||
  691. (d[2] == 'd' && d[3] == 'c') ||
  692. (d[2] == 'w' && d[3] == 'b')*/) {
  693. //av_log(NULL, AV_LOG_DEBUG, "OK\n");
  694. if(d[2]*256+d[3] == ast->prefix)
  695. ast->prefix_count++;
  696. else{
  697. ast->prefix= d[2]*256+d[3];
  698. ast->prefix_count= 0;
  699. }
  700. avi->stream_index= n;
  701. ast->packet_size= size + 8;
  702. ast->remaining= size;
  703. {
  704. uint64_t pos= url_ftell(pb) - 8;
  705. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  706. av_add_index_entry(st, pos, ast->frame_offset / FFMAX(1, ast->sample_size), size, 0, AVINDEX_KEYFRAME);
  707. }
  708. }
  709. goto resync;
  710. }
  711. }
  712. /* palette changed chunk */
  713. if ( d[0] >= '0' && d[0] <= '9'
  714. && d[1] >= '0' && d[1] <= '9'
  715. && ((d[2] == 'p' && d[3] == 'c'))
  716. && n < s->nb_streams && i + size <= avi->fsize) {
  717. AVStream *st;
  718. int first, clr, flags, k, p;
  719. st = s->streams[n];
  720. first = get_byte(pb);
  721. clr = get_byte(pb);
  722. if(!clr) /* all 256 colors used */
  723. clr = 256;
  724. flags = get_le16(pb);
  725. p = 4;
  726. for (k = first; k < clr + first; k++) {
  727. int r, g, b;
  728. r = get_byte(pb);
  729. g = get_byte(pb);
  730. b = get_byte(pb);
  731. get_byte(pb);
  732. st->codec->palctrl->palette[k] = b + (g << 8) + (r << 16);
  733. }
  734. st->codec->palctrl->palette_changed = 1;
  735. goto resync;
  736. }
  737. }
  738. return -1;
  739. }
  740. /* XXX: we make the implicit supposition that the position are sorted
  741. for each stream */
  742. static int avi_read_idx1(AVFormatContext *s, int size)
  743. {
  744. AVIContext *avi = s->priv_data;
  745. ByteIOContext *pb = s->pb;
  746. int nb_index_entries, i;
  747. AVStream *st;
  748. AVIStream *ast;
  749. unsigned int index, tag, flags, pos, len;
  750. unsigned last_pos= -1;
  751. nb_index_entries = size / 16;
  752. if (nb_index_entries <= 0)
  753. return -1;
  754. /* read the entries and sort them in each stream component */
  755. for(i = 0; i < nb_index_entries; i++) {
  756. tag = get_le32(pb);
  757. flags = get_le32(pb);
  758. pos = get_le32(pb);
  759. len = get_le32(pb);
  760. #if defined(DEBUG_SEEK)
  761. av_log(NULL, AV_LOG_DEBUG, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  762. i, tag, flags, pos, len);
  763. #endif
  764. if(i==0 && pos > avi->movi_list)
  765. avi->movi_list= 0; //FIXME better check
  766. pos += avi->movi_list;
  767. index = ((tag & 0xff) - '0') * 10;
  768. index += ((tag >> 8) & 0xff) - '0';
  769. if (index >= s->nb_streams)
  770. continue;
  771. st = s->streams[index];
  772. ast = st->priv_data;
  773. #if defined(DEBUG_SEEK)
  774. av_log(NULL, AV_LOG_DEBUG, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  775. #endif
  776. if(last_pos == pos)
  777. avi->non_interleaved= 1;
  778. else
  779. av_add_index_entry(st, pos, ast->cum_len / FFMAX(1, ast->sample_size), len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  780. if(ast->sample_size)
  781. ast->cum_len += len;
  782. else
  783. ast->cum_len ++;
  784. last_pos= pos;
  785. }
  786. return 0;
  787. }
  788. static int guess_ni_flag(AVFormatContext *s){
  789. int i;
  790. int64_t last_start=0;
  791. int64_t first_end= INT64_MAX;
  792. for(i=0; i<s->nb_streams; i++){
  793. AVStream *st = s->streams[i];
  794. int n= st->nb_index_entries;
  795. if(n <= 0)
  796. continue;
  797. if(st->index_entries[0].pos > last_start)
  798. last_start= st->index_entries[0].pos;
  799. if(st->index_entries[n-1].pos < first_end)
  800. first_end= st->index_entries[n-1].pos;
  801. }
  802. return last_start > first_end;
  803. }
  804. static int avi_load_index(AVFormatContext *s)
  805. {
  806. AVIContext *avi = s->priv_data;
  807. ByteIOContext *pb = s->pb;
  808. uint32_t tag, size;
  809. offset_t pos= url_ftell(pb);
  810. url_fseek(pb, avi->movi_end, SEEK_SET);
  811. #ifdef DEBUG_SEEK
  812. printf("movi_end=0x%"PRIx64"\n", avi->movi_end);
  813. #endif
  814. for(;;) {
  815. if (url_feof(pb))
  816. break;
  817. tag = get_le32(pb);
  818. size = get_le32(pb);
  819. #ifdef DEBUG_SEEK
  820. printf("tag=%c%c%c%c size=0x%x\n",
  821. tag & 0xff,
  822. (tag >> 8) & 0xff,
  823. (tag >> 16) & 0xff,
  824. (tag >> 24) & 0xff,
  825. size);
  826. #endif
  827. switch(tag) {
  828. case MKTAG('i', 'd', 'x', '1'):
  829. if (avi_read_idx1(s, size) < 0)
  830. goto skip;
  831. else
  832. goto the_end;
  833. break;
  834. default:
  835. skip:
  836. size += (size & 1);
  837. url_fskip(pb, size);
  838. break;
  839. }
  840. }
  841. the_end:
  842. url_fseek(pb, pos, SEEK_SET);
  843. return 0;
  844. }
  845. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  846. {
  847. AVIContext *avi = s->priv_data;
  848. AVStream *st;
  849. int i, index;
  850. int64_t pos;
  851. if (!avi->index_loaded) {
  852. /* we only load the index on demand */
  853. avi_load_index(s);
  854. avi->index_loaded = 1;
  855. }
  856. assert(stream_index>= 0);
  857. st = s->streams[stream_index];
  858. index= av_index_search_timestamp(st, timestamp, flags);
  859. if(index<0)
  860. return -1;
  861. /* find the position */
  862. pos = st->index_entries[index].pos;
  863. timestamp = st->index_entries[index].timestamp;
  864. // av_log(NULL, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  865. if (ENABLE_DV_DEMUXER && avi->dv_demux) {
  866. /* One and only one real stream for DV in AVI, and it has video */
  867. /* offsets. Calling with other stream indices should have failed */
  868. /* the av_index_search_timestamp call above. */
  869. assert(stream_index == 0);
  870. /* Feed the DV video stream version of the timestamp to the */
  871. /* DV demux so it can synth correct timestamps */
  872. dv_offset_reset(avi->dv_demux, timestamp);
  873. url_fseek(s->pb, pos, SEEK_SET);
  874. avi->stream_index= -1;
  875. return 0;
  876. }
  877. for(i = 0; i < s->nb_streams; i++) {
  878. AVStream *st2 = s->streams[i];
  879. AVIStream *ast2 = st2->priv_data;
  880. ast2->packet_size=
  881. ast2->remaining= 0;
  882. if (st2->nb_index_entries <= 0)
  883. continue;
  884. // assert(st2->codec->block_align);
  885. assert(st2->time_base.den == ast2->rate);
  886. assert(st2->time_base.num == ast2->scale);
  887. index = av_index_search_timestamp(
  888. st2,
  889. av_rescale(timestamp, st2->time_base.den*(int64_t)st->time_base.num, st->time_base.den * (int64_t)st2->time_base.num),
  890. flags | AVSEEK_FLAG_BACKWARD);
  891. if(index<0)
  892. index=0;
  893. if(!avi->non_interleaved){
  894. while(index>0 && st2->index_entries[index].pos > pos)
  895. index--;
  896. while(index+1 < st2->nb_index_entries && st2->index_entries[index].pos < pos)
  897. index++;
  898. }
  899. // av_log(NULL, AV_LOG_DEBUG, "%"PRId64" %d %"PRId64"\n", timestamp, index, st2->index_entries[index].timestamp);
  900. /* extract the current frame number */
  901. ast2->frame_offset = st2->index_entries[index].timestamp;
  902. if(ast2->sample_size)
  903. ast2->frame_offset *=ast2->sample_size;
  904. }
  905. /* do the seek */
  906. url_fseek(s->pb, pos, SEEK_SET);
  907. avi->stream_index= -1;
  908. return 0;
  909. }
  910. static int avi_read_close(AVFormatContext *s)
  911. {
  912. int i;
  913. AVIContext *avi = s->priv_data;
  914. for(i=0;i<s->nb_streams;i++) {
  915. AVStream *st = s->streams[i];
  916. AVIStream *ast = st->priv_data;
  917. av_free(ast);
  918. av_free(st->codec->palctrl);
  919. }
  920. if (avi->dv_demux)
  921. av_free(avi->dv_demux);
  922. return 0;
  923. }
  924. static int avi_probe(AVProbeData *p)
  925. {
  926. int i;
  927. /* check file header */
  928. for(i=0; avi_headers[i][0]; i++)
  929. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  930. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  931. return AVPROBE_SCORE_MAX;
  932. return 0;
  933. }
  934. AVInputFormat avi_demuxer = {
  935. "avi",
  936. "avi format",
  937. sizeof(AVIContext),
  938. avi_probe,
  939. avi_read_header,
  940. avi_read_packet,
  941. avi_read_close,
  942. avi_read_seek,
  943. };