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.

1101 lines
36KB

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