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.

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