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.

1567 lines
53KB

  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/mathematics.h"
  23. #include "libavutil/bswap.h"
  24. #include "libavutil/opt.h"
  25. #include "libavutil/dict.h"
  26. #include "libavutil/avstring.h"
  27. #include "avformat.h"
  28. #include "internal.h"
  29. #include "avi.h"
  30. #include "dv.h"
  31. #include "riff.h"
  32. #undef NDEBUG
  33. #include <assert.h>
  34. typedef struct AVIStream {
  35. int64_t frame_offset; /* current frame (video) or byte (audio) counter
  36. (used to compute the pts) */
  37. int remaining;
  38. int packet_size;
  39. uint32_t scale;
  40. uint32_t rate;
  41. int sample_size; /* size of one sample (or packet) (in the rate/scale sense) in bytes */
  42. int64_t cum_len; /* temporary storage (used during seek) */
  43. int prefix; ///< normally 'd'<<8 + 'c' or 'w'<<8 + 'b'
  44. int prefix_count;
  45. uint32_t pal[256];
  46. int has_pal;
  47. int dshow_block_align; ///< block align variable used to emulate bugs in the MS dshow demuxer
  48. AVFormatContext *sub_ctx;
  49. AVPacket sub_pkt;
  50. uint8_t *sub_buffer;
  51. int64_t seek_pos;
  52. } AVIStream;
  53. typedef struct {
  54. const AVClass *class;
  55. int64_t riff_end;
  56. int64_t movi_end;
  57. int64_t fsize;
  58. int64_t movi_list;
  59. int64_t last_pkt_pos;
  60. int index_loaded;
  61. int is_odml;
  62. int non_interleaved;
  63. int stream_index;
  64. DVDemuxContext* dv_demux;
  65. int odml_depth;
  66. int use_odml;
  67. #define MAX_ODML_DEPTH 1000
  68. int64_t dts_max;
  69. } AVIContext;
  70. static const AVOption options[] = {
  71. { "use_odml", "use odml index", offsetof(AVIContext, use_odml), AV_OPT_TYPE_INT, {.dbl = 1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM},
  72. { NULL },
  73. };
  74. static const AVClass demuxer_class = {
  75. .class_name = "avi",
  76. .item_name = av_default_item_name,
  77. .option = options,
  78. .version = LIBAVUTIL_VERSION_INT,
  79. .category = AV_CLASS_CATEGORY_DEMUXER,
  80. };
  81. static const char avi_headers[][8] = {
  82. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', ' ' },
  83. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 'X' },
  84. { 'R', 'I', 'F', 'F', 'A', 'V', 'I', 0x19},
  85. { 'O', 'N', '2', ' ', 'O', 'N', '2', 'f' },
  86. { 'R', 'I', 'F', 'F', 'A', 'M', 'V', ' ' },
  87. { 0 }
  88. };
  89. static const AVMetadataConv avi_metadata_conv[] = {
  90. { "strn", "title" },
  91. { 0 },
  92. };
  93. static int avi_load_index(AVFormatContext *s);
  94. static int guess_ni_flag(AVFormatContext *s);
  95. #define print_tag(str, tag, size) \
  96. av_dlog(NULL, "%s: tag=%c%c%c%c size=0x%x\n", \
  97. str, tag & 0xff, \
  98. (tag >> 8) & 0xff, \
  99. (tag >> 16) & 0xff, \
  100. (tag >> 24) & 0xff, \
  101. size)
  102. static inline int get_duration(AVIStream *ast, int len){
  103. if(ast->sample_size){
  104. return len;
  105. }else if (ast->dshow_block_align){
  106. return (len + ast->dshow_block_align - 1)/ast->dshow_block_align;
  107. }else
  108. return 1;
  109. }
  110. static int get_riff(AVFormatContext *s, AVIOContext *pb)
  111. {
  112. AVIContext *avi = s->priv_data;
  113. char header[8];
  114. int i;
  115. /* check RIFF header */
  116. avio_read(pb, header, 4);
  117. avi->riff_end = avio_rl32(pb); /* RIFF chunk size */
  118. avi->riff_end += avio_tell(pb); /* RIFF chunk end */
  119. avio_read(pb, header+4, 4);
  120. for(i=0; avi_headers[i][0]; i++)
  121. if(!memcmp(header, avi_headers[i], 8))
  122. break;
  123. if(!avi_headers[i][0])
  124. return -1;
  125. if(header[7] == 0x19)
  126. av_log(s, AV_LOG_INFO, "This file has been generated by a totally broken muxer.\n");
  127. return 0;
  128. }
  129. static int read_braindead_odml_indx(AVFormatContext *s, int frame_num){
  130. AVIContext *avi = s->priv_data;
  131. AVIOContext *pb = s->pb;
  132. int longs_pre_entry= avio_rl16(pb);
  133. int index_sub_type = avio_r8(pb);
  134. int index_type = avio_r8(pb);
  135. int entries_in_use = avio_rl32(pb);
  136. int chunk_id = avio_rl32(pb);
  137. int64_t base = avio_rl64(pb);
  138. int stream_id= 10*((chunk_id&0xFF) - '0') + (((chunk_id>>8)&0xFF) - '0');
  139. AVStream *st;
  140. AVIStream *ast;
  141. int i;
  142. int64_t last_pos= -1;
  143. int64_t filesize= avi->fsize;
  144. av_dlog(s, "longs_pre_entry:%d index_type:%d entries_in_use:%d chunk_id:%X base:%16"PRIX64"\n",
  145. longs_pre_entry,index_type, entries_in_use, chunk_id, base);
  146. if(stream_id >= s->nb_streams || stream_id < 0)
  147. return -1;
  148. st= s->streams[stream_id];
  149. ast = st->priv_data;
  150. if(index_sub_type)
  151. return -1;
  152. avio_rl32(pb);
  153. if(index_type && longs_pre_entry != 2)
  154. return -1;
  155. if(index_type>1)
  156. return -1;
  157. if(filesize > 0 && base >= filesize){
  158. av_log(s, AV_LOG_ERROR, "ODML index invalid\n");
  159. if(base>>32 == (base & 0xFFFFFFFF) && (base & 0xFFFFFFFF) < filesize && filesize <= 0xFFFFFFFF)
  160. base &= 0xFFFFFFFF;
  161. else
  162. return -1;
  163. }
  164. for(i=0; i<entries_in_use; i++){
  165. if(index_type){
  166. int64_t pos= avio_rl32(pb) + base - 8;
  167. int len = avio_rl32(pb);
  168. int key= len >= 0;
  169. len &= 0x7FFFFFFF;
  170. #ifdef DEBUG_SEEK
  171. av_log(s, AV_LOG_ERROR, "pos:%"PRId64", len:%X\n", pos, len);
  172. #endif
  173. if(url_feof(pb))
  174. return -1;
  175. if(last_pos == pos || pos == base - 8)
  176. avi->non_interleaved= 1;
  177. if(last_pos != pos && (len || !ast->sample_size))
  178. av_add_index_entry(st, pos, ast->cum_len, len, 0, key ? AVINDEX_KEYFRAME : 0);
  179. ast->cum_len += get_duration(ast, len);
  180. last_pos= pos;
  181. }else{
  182. int64_t offset, pos;
  183. int duration;
  184. offset = avio_rl64(pb);
  185. avio_rl32(pb); /* size */
  186. duration = avio_rl32(pb);
  187. if(url_feof(pb))
  188. return -1;
  189. pos = avio_tell(pb);
  190. if(avi->odml_depth > MAX_ODML_DEPTH){
  191. av_log(s, AV_LOG_ERROR, "Too deeply nested ODML indexes\n");
  192. return -1;
  193. }
  194. if(avio_seek(pb, offset+8, SEEK_SET) < 0)
  195. return -1;
  196. avi->odml_depth++;
  197. read_braindead_odml_indx(s, frame_num);
  198. avi->odml_depth--;
  199. frame_num += duration;
  200. if(avio_seek(pb, pos, SEEK_SET) < 0) {
  201. av_log(s, AV_LOG_ERROR, "Failed to restore position after reading index");
  202. return -1;
  203. }
  204. }
  205. }
  206. avi->index_loaded=2;
  207. return 0;
  208. }
  209. static void clean_index(AVFormatContext *s){
  210. int i;
  211. int64_t j;
  212. for(i=0; i<s->nb_streams; i++){
  213. AVStream *st = s->streams[i];
  214. AVIStream *ast = st->priv_data;
  215. int n= st->nb_index_entries;
  216. int max= ast->sample_size;
  217. int64_t pos, size, ts;
  218. if(n != 1 || ast->sample_size==0)
  219. continue;
  220. while(max < 1024) max+=max;
  221. pos= st->index_entries[0].pos;
  222. size= st->index_entries[0].size;
  223. ts= st->index_entries[0].timestamp;
  224. for(j=0; j<size; j+=max){
  225. av_add_index_entry(st, pos+j, ts+j, FFMIN(max, size-j), 0, AVINDEX_KEYFRAME);
  226. }
  227. }
  228. }
  229. static int avi_read_tag(AVFormatContext *s, AVStream *st, uint32_t tag, uint32_t size)
  230. {
  231. AVIOContext *pb = s->pb;
  232. char key[5] = {0}, *value;
  233. size += (size & 1);
  234. if (size == UINT_MAX)
  235. return -1;
  236. value = av_malloc(size+1);
  237. if (!value)
  238. return -1;
  239. avio_read(pb, value, size);
  240. value[size]=0;
  241. AV_WL32(key, tag);
  242. return av_dict_set(st ? &st->metadata : &s->metadata, key, value,
  243. AV_DICT_DONT_STRDUP_VAL);
  244. }
  245. static const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  246. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  247. static void avi_metadata_creation_time(AVDictionary **metadata, char *date)
  248. {
  249. char month[4], time[9], buffer[64];
  250. int i, day, year;
  251. /* parse standard AVI date format (ie. "Mon Mar 10 15:04:43 2003") */
  252. if (sscanf(date, "%*3s%*[ ]%3s%*[ ]%2d%*[ ]%8s%*[ ]%4d",
  253. month, &day, time, &year) == 4) {
  254. for (i=0; i<12; i++)
  255. if (!av_strcasecmp(month, months[i])) {
  256. snprintf(buffer, sizeof(buffer), "%.4d-%.2d-%.2d %s",
  257. year, i+1, day, time);
  258. av_dict_set(metadata, "creation_time", buffer, 0);
  259. }
  260. } else if (date[4] == '/' && date[7] == '/') {
  261. date[4] = date[7] = '-';
  262. av_dict_set(metadata, "creation_time", date, 0);
  263. }
  264. }
  265. static void avi_read_nikon(AVFormatContext *s, uint64_t end)
  266. {
  267. while (avio_tell(s->pb) < end) {
  268. uint32_t tag = avio_rl32(s->pb);
  269. uint32_t size = avio_rl32(s->pb);
  270. switch (tag) {
  271. case MKTAG('n', 'c', 't', 'g'): { /* Nikon Tags */
  272. uint64_t tag_end = avio_tell(s->pb) + size;
  273. while (avio_tell(s->pb) < tag_end) {
  274. uint16_t tag = avio_rl16(s->pb);
  275. uint16_t size = avio_rl16(s->pb);
  276. const char *name = NULL;
  277. char buffer[64] = {0};
  278. size -= avio_read(s->pb, buffer,
  279. FFMIN(size, sizeof(buffer)-1));
  280. switch (tag) {
  281. case 0x03: name = "maker"; break;
  282. case 0x04: name = "model"; break;
  283. case 0x13: name = "creation_time";
  284. if (buffer[4] == ':' && buffer[7] == ':')
  285. buffer[4] = buffer[7] = '-';
  286. break;
  287. }
  288. if (name)
  289. av_dict_set(&s->metadata, name, buffer, 0);
  290. avio_skip(s->pb, size);
  291. }
  292. break;
  293. }
  294. default:
  295. avio_skip(s->pb, size);
  296. break;
  297. }
  298. }
  299. }
  300. static int avi_read_header(AVFormatContext *s)
  301. {
  302. AVIContext *avi = s->priv_data;
  303. AVIOContext *pb = s->pb;
  304. unsigned int tag, tag1, handler;
  305. int codec_type, stream_index, frame_period;
  306. unsigned int size;
  307. int i;
  308. AVStream *st;
  309. AVIStream *ast = NULL;
  310. int avih_width=0, avih_height=0;
  311. int amv_file_format=0;
  312. uint64_t list_end = 0;
  313. int ret;
  314. avi->stream_index= -1;
  315. if (get_riff(s, pb) < 0)
  316. return -1;
  317. av_log(avi, AV_LOG_DEBUG, "use odml:%d\n", avi->use_odml);
  318. avi->fsize = avio_size(pb);
  319. if(avi->fsize<=0 || avi->fsize < avi->riff_end)
  320. avi->fsize= avi->riff_end == 8 ? INT64_MAX : avi->riff_end;
  321. /* first list tag */
  322. stream_index = -1;
  323. codec_type = -1;
  324. frame_period = 0;
  325. for(;;) {
  326. if (url_feof(pb))
  327. goto fail;
  328. tag = avio_rl32(pb);
  329. size = avio_rl32(pb);
  330. print_tag("tag", tag, size);
  331. switch(tag) {
  332. case MKTAG('L', 'I', 'S', 'T'):
  333. list_end = avio_tell(pb) + size;
  334. /* Ignored, except at start of video packets. */
  335. tag1 = avio_rl32(pb);
  336. print_tag("list", tag1, 0);
  337. if (tag1 == MKTAG('m', 'o', 'v', 'i')) {
  338. avi->movi_list = avio_tell(pb) - 4;
  339. if(size) avi->movi_end = avi->movi_list + size + (size & 1);
  340. else avi->movi_end = avi->fsize;
  341. av_dlog(NULL, "movi end=%"PRIx64"\n", avi->movi_end);
  342. goto end_of_header;
  343. }
  344. else if (tag1 == MKTAG('I', 'N', 'F', 'O'))
  345. ff_read_riff_info(s, size - 4);
  346. else if (tag1 == MKTAG('n', 'c', 'd', 't'))
  347. avi_read_nikon(s, list_end);
  348. break;
  349. case MKTAG('I', 'D', 'I', 'T'): {
  350. unsigned char date[64] = {0};
  351. size += (size & 1);
  352. size -= avio_read(pb, date, FFMIN(size, sizeof(date)-1));
  353. avio_skip(pb, size);
  354. avi_metadata_creation_time(&s->metadata, date);
  355. break;
  356. }
  357. case MKTAG('d', 'm', 'l', 'h'):
  358. avi->is_odml = 1;
  359. avio_skip(pb, size + (size & 1));
  360. break;
  361. case MKTAG('a', 'm', 'v', 'h'):
  362. amv_file_format=1;
  363. case MKTAG('a', 'v', 'i', 'h'):
  364. /* AVI header */
  365. /* using frame_period is bad idea */
  366. frame_period = avio_rl32(pb);
  367. avio_rl32(pb); /* max. bytes per second */
  368. avio_rl32(pb);
  369. avi->non_interleaved |= avio_rl32(pb) & AVIF_MUSTUSEINDEX;
  370. avio_skip(pb, 2 * 4);
  371. avio_rl32(pb);
  372. avio_rl32(pb);
  373. avih_width=avio_rl32(pb);
  374. avih_height=avio_rl32(pb);
  375. avio_skip(pb, size - 10 * 4);
  376. break;
  377. case MKTAG('s', 't', 'r', 'h'):
  378. /* stream header */
  379. tag1 = avio_rl32(pb);
  380. handler = avio_rl32(pb); /* codec tag */
  381. if(tag1 == MKTAG('p', 'a', 'd', 's')){
  382. avio_skip(pb, size - 8);
  383. break;
  384. }else{
  385. stream_index++;
  386. st = avformat_new_stream(s, NULL);
  387. if (!st)
  388. goto fail;
  389. st->id = stream_index;
  390. ast = av_mallocz(sizeof(AVIStream));
  391. if (!ast)
  392. goto fail;
  393. st->priv_data = ast;
  394. }
  395. if(amv_file_format)
  396. tag1 = stream_index ? MKTAG('a','u','d','s') : MKTAG('v','i','d','s');
  397. print_tag("strh", tag1, -1);
  398. if(tag1 == MKTAG('i', 'a', 'v', 's') || tag1 == MKTAG('i', 'v', 'a', 's')){
  399. int64_t dv_dur;
  400. /*
  401. * After some consideration -- I don't think we
  402. * have to support anything but DV in type1 AVIs.
  403. */
  404. if (s->nb_streams != 1)
  405. goto fail;
  406. if (handler != MKTAG('d', 'v', 's', 'd') &&
  407. handler != MKTAG('d', 'v', 'h', 'd') &&
  408. handler != MKTAG('d', 'v', 's', 'l'))
  409. goto fail;
  410. ast = s->streams[0]->priv_data;
  411. av_freep(&s->streams[0]->codec->extradata);
  412. av_freep(&s->streams[0]->codec);
  413. av_freep(&s->streams[0]);
  414. s->nb_streams = 0;
  415. if (CONFIG_DV_DEMUXER) {
  416. avi->dv_demux = avpriv_dv_init_demux(s);
  417. if (!avi->dv_demux)
  418. goto fail;
  419. }
  420. s->streams[0]->priv_data = ast;
  421. avio_skip(pb, 3 * 4);
  422. ast->scale = avio_rl32(pb);
  423. ast->rate = avio_rl32(pb);
  424. avio_skip(pb, 4); /* start time */
  425. dv_dur = avio_rl32(pb);
  426. if (ast->scale > 0 && ast->rate > 0 && dv_dur > 0) {
  427. dv_dur *= AV_TIME_BASE;
  428. s->duration = av_rescale(dv_dur, ast->scale, ast->rate);
  429. }
  430. /*
  431. * else, leave duration alone; timing estimation in utils.c
  432. * will make a guess based on bitrate.
  433. */
  434. stream_index = s->nb_streams - 1;
  435. avio_skip(pb, size - 9*4);
  436. break;
  437. }
  438. assert(stream_index < s->nb_streams);
  439. st->codec->stream_codec_tag= handler;
  440. avio_rl32(pb); /* flags */
  441. avio_rl16(pb); /* priority */
  442. avio_rl16(pb); /* language */
  443. avio_rl32(pb); /* initial frame */
  444. ast->scale = avio_rl32(pb);
  445. ast->rate = avio_rl32(pb);
  446. if(!(ast->scale && ast->rate)){
  447. 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);
  448. if(frame_period){
  449. ast->rate = 1000000;
  450. ast->scale = frame_period;
  451. }else{
  452. ast->rate = 25;
  453. ast->scale = 1;
  454. }
  455. }
  456. avpriv_set_pts_info(st, 64, ast->scale, ast->rate);
  457. ast->cum_len=avio_rl32(pb); /* start */
  458. st->nb_frames = avio_rl32(pb);
  459. st->start_time = 0;
  460. avio_rl32(pb); /* buffer size */
  461. avio_rl32(pb); /* quality */
  462. if (ast->cum_len*ast->scale/ast->rate > 3600) {
  463. av_log(s, AV_LOG_ERROR, "crazy start time, iam scared, giving up\n");
  464. return AVERROR_INVALIDDATA;
  465. }
  466. ast->sample_size = avio_rl32(pb); /* sample ssize */
  467. ast->cum_len *= FFMAX(1, ast->sample_size);
  468. // av_log(s, AV_LOG_DEBUG, "%d %d %d %d\n", ast->rate, ast->scale, ast->start, ast->sample_size);
  469. switch(tag1) {
  470. case MKTAG('v', 'i', 'd', 's'):
  471. codec_type = AVMEDIA_TYPE_VIDEO;
  472. ast->sample_size = 0;
  473. break;
  474. case MKTAG('a', 'u', 'd', 's'):
  475. codec_type = AVMEDIA_TYPE_AUDIO;
  476. break;
  477. case MKTAG('t', 'x', 't', 's'):
  478. codec_type = AVMEDIA_TYPE_SUBTITLE;
  479. break;
  480. case MKTAG('d', 'a', 't', 's'):
  481. codec_type = AVMEDIA_TYPE_DATA;
  482. break;
  483. default:
  484. av_log(s, AV_LOG_INFO, "unknown stream type %X\n", tag1);
  485. }
  486. if(ast->sample_size == 0)
  487. st->duration = st->nb_frames;
  488. ast->frame_offset= ast->cum_len;
  489. avio_skip(pb, size - 12 * 4);
  490. break;
  491. case MKTAG('s', 't', 'r', 'f'):
  492. /* stream header */
  493. if (!size)
  494. break;
  495. if (stream_index >= (unsigned)s->nb_streams || avi->dv_demux) {
  496. avio_skip(pb, size);
  497. } else {
  498. uint64_t cur_pos = avio_tell(pb);
  499. unsigned esize;
  500. if (cur_pos < list_end)
  501. size = FFMIN(size, list_end - cur_pos);
  502. st = s->streams[stream_index];
  503. switch(codec_type) {
  504. case AVMEDIA_TYPE_VIDEO:
  505. if(amv_file_format){
  506. st->codec->width=avih_width;
  507. st->codec->height=avih_height;
  508. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  509. st->codec->codec_id = CODEC_ID_AMV;
  510. avio_skip(pb, size);
  511. break;
  512. }
  513. tag1 = ff_get_bmp_header(pb, st, &esize);
  514. if (tag1 == MKTAG('D', 'X', 'S', 'B') || tag1 == MKTAG('D','X','S','A')) {
  515. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  516. st->codec->codec_tag = tag1;
  517. st->codec->codec_id = CODEC_ID_XSUB;
  518. break;
  519. }
  520. if(size > 10*4 && size<(1<<30) && size < avi->fsize){
  521. if(esize == size-1 && (esize&1)) st->codec->extradata_size= esize - 10*4;
  522. else st->codec->extradata_size= size - 10*4;
  523. st->codec->extradata= av_malloc(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  524. if (!st->codec->extradata) {
  525. st->codec->extradata_size= 0;
  526. return AVERROR(ENOMEM);
  527. }
  528. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  529. }
  530. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  531. avio_r8(pb);
  532. /* Extract palette from extradata if bpp <= 8. */
  533. /* This code assumes that extradata contains only palette. */
  534. /* This is true for all paletted codecs implemented in FFmpeg. */
  535. if (st->codec->extradata_size && (st->codec->bits_per_coded_sample <= 8)) {
  536. int pal_size = (1 << st->codec->bits_per_coded_sample) << 2;
  537. const uint8_t *pal_src;
  538. pal_size = FFMIN(pal_size, st->codec->extradata_size);
  539. pal_src = st->codec->extradata + st->codec->extradata_size - pal_size;
  540. for (i = 0; i < pal_size/4; i++)
  541. ast->pal[i] = 0xFF<<24 | AV_RL32(pal_src+4*i);
  542. ast->has_pal = 1;
  543. }
  544. print_tag("video", tag1, 0);
  545. st->codec->codec_type = AVMEDIA_TYPE_VIDEO;
  546. st->codec->codec_tag = tag1;
  547. st->codec->codec_id = ff_codec_get_id(ff_codec_bmp_tags, tag1);
  548. st->need_parsing = AVSTREAM_PARSE_HEADERS; // This is needed to get the pict type which is necessary for generating correct pts.
  549. // Support "Resolution 1:1" for Avid AVI Codec
  550. if(tag1 == MKTAG('A', 'V', 'R', 'n') &&
  551. st->codec->extradata_size >= 31 &&
  552. !memcmp(&st->codec->extradata[28], "1:1", 3))
  553. st->codec->codec_id = CODEC_ID_RAWVIDEO;
  554. if(st->codec->codec_tag==0 && st->codec->height > 0 && st->codec->extradata_size < 1U<<30){
  555. st->codec->extradata_size+= 9;
  556. st->codec->extradata= av_realloc_f(st->codec->extradata, 1, st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  557. if(st->codec->extradata)
  558. memcpy(st->codec->extradata + st->codec->extradata_size - 9, "BottomUp", 9);
  559. }
  560. st->codec->height= FFABS(st->codec->height);
  561. // avio_skip(pb, size - 5 * 4);
  562. break;
  563. case AVMEDIA_TYPE_AUDIO:
  564. ret = ff_get_wav_header(pb, st->codec, size);
  565. if (ret < 0)
  566. return ret;
  567. ast->dshow_block_align= st->codec->block_align;
  568. if(ast->sample_size && st->codec->block_align && ast->sample_size != st->codec->block_align){
  569. av_log(s, AV_LOG_WARNING, "sample size (%d) != block align (%d)\n", ast->sample_size, st->codec->block_align);
  570. ast->sample_size= st->codec->block_align;
  571. }
  572. if (size&1) /* 2-aligned (fix for Stargate SG-1 - 3x18 - Shades of Grey.avi) */
  573. avio_skip(pb, 1);
  574. /* Force parsing as several audio frames can be in
  575. * one packet and timestamps refer to packet start. */
  576. st->need_parsing = AVSTREAM_PARSE_TIMESTAMPS;
  577. /* ADTS header is in extradata, AAC without header must be
  578. * stored as exact frames. Parser not needed and it will
  579. * fail. */
  580. if (st->codec->codec_id == CODEC_ID_AAC && st->codec->extradata_size)
  581. st->need_parsing = AVSTREAM_PARSE_NONE;
  582. /* AVI files with Xan DPCM audio (wrongly) declare PCM
  583. * audio in the header but have Axan as stream_code_tag. */
  584. if (st->codec->stream_codec_tag == AV_RL32("Axan")){
  585. st->codec->codec_id = CODEC_ID_XAN_DPCM;
  586. st->codec->codec_tag = 0;
  587. ast->dshow_block_align = 0;
  588. }
  589. if (amv_file_format){
  590. st->codec->codec_id = CODEC_ID_ADPCM_IMA_AMV;
  591. ast->dshow_block_align = 0;
  592. }
  593. break;
  594. case AVMEDIA_TYPE_SUBTITLE:
  595. st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE;
  596. st->request_probe= 1;
  597. break;
  598. default:
  599. st->codec->codec_type = AVMEDIA_TYPE_DATA;
  600. st->codec->codec_id= CODEC_ID_NONE;
  601. st->codec->codec_tag= 0;
  602. avio_skip(pb, size);
  603. break;
  604. }
  605. }
  606. break;
  607. case MKTAG('s', 't', 'r', 'd'):
  608. if (stream_index >= (unsigned)s->nb_streams || s->streams[stream_index]->codec->extradata_size) {
  609. avio_skip(pb, size);
  610. } else {
  611. uint64_t cur_pos = avio_tell(pb);
  612. if (cur_pos < list_end)
  613. size = FFMIN(size, list_end - cur_pos);
  614. st = s->streams[stream_index];
  615. if(size<(1<<30)){
  616. st->codec->extradata_size= size;
  617. st->codec->extradata= av_mallocz(st->codec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  618. if (!st->codec->extradata) {
  619. st->codec->extradata_size= 0;
  620. return AVERROR(ENOMEM);
  621. }
  622. avio_read(pb, st->codec->extradata, st->codec->extradata_size);
  623. }
  624. if(st->codec->extradata_size & 1) //FIXME check if the encoder really did this correctly
  625. avio_r8(pb);
  626. }
  627. break;
  628. case MKTAG('i', 'n', 'd', 'x'):
  629. i= avio_tell(pb);
  630. if(pb->seekable && !(s->flags & AVFMT_FLAG_IGNIDX) && avi->use_odml &&
  631. read_braindead_odml_indx(s, 0) < 0 && (s->error_recognition & AV_EF_EXPLODE))
  632. goto fail;
  633. avio_seek(pb, i+size, SEEK_SET);
  634. break;
  635. case MKTAG('v', 'p', 'r', 'p'):
  636. if(stream_index < (unsigned)s->nb_streams && size > 9*4){
  637. AVRational active, active_aspect;
  638. st = s->streams[stream_index];
  639. avio_rl32(pb);
  640. avio_rl32(pb);
  641. avio_rl32(pb);
  642. avio_rl32(pb);
  643. avio_rl32(pb);
  644. active_aspect.den= avio_rl16(pb);
  645. active_aspect.num= avio_rl16(pb);
  646. active.num = avio_rl32(pb);
  647. active.den = avio_rl32(pb);
  648. avio_rl32(pb); //nbFieldsPerFrame
  649. if(active_aspect.num && active_aspect.den && active.num && active.den){
  650. st->sample_aspect_ratio= av_div_q(active_aspect, active);
  651. //av_log(s, AV_LOG_ERROR, "vprp %d/%d %d/%d\n", active_aspect.num, active_aspect.den, active.num, active.den);
  652. }
  653. size -= 9*4;
  654. }
  655. avio_skip(pb, size);
  656. break;
  657. case MKTAG('s', 't', 'r', 'n'):
  658. if(s->nb_streams){
  659. avi_read_tag(s, s->streams[s->nb_streams-1], tag, size);
  660. break;
  661. }
  662. default:
  663. if(size > 1000000){
  664. av_log(s, AV_LOG_ERROR, "Something went wrong during header parsing, "
  665. "I will ignore it and try to continue anyway.\n");
  666. if (s->error_recognition & AV_EF_EXPLODE)
  667. goto fail;
  668. avi->movi_list = avio_tell(pb) - 4;
  669. avi->movi_end = avi->fsize;
  670. goto end_of_header;
  671. }
  672. /* skip tag */
  673. size += (size & 1);
  674. avio_skip(pb, size);
  675. break;
  676. }
  677. }
  678. end_of_header:
  679. /* check stream number */
  680. if (stream_index != s->nb_streams - 1) {
  681. fail:
  682. return -1;
  683. }
  684. if(!avi->index_loaded && pb->seekable)
  685. avi_load_index(s);
  686. avi->index_loaded |= 1;
  687. avi->non_interleaved |= guess_ni_flag(s) | (s->flags & AVFMT_FLAG_SORT_DTS);
  688. for(i=0; i<s->nb_streams; i++){
  689. AVStream *st = s->streams[i];
  690. if(st->nb_index_entries)
  691. break;
  692. }
  693. // DV-in-AVI cannot be non-interleaved, if set this must be
  694. // a mis-detection.
  695. if(avi->dv_demux)
  696. avi->non_interleaved=0;
  697. if(i==s->nb_streams && avi->non_interleaved) {
  698. av_log(s, AV_LOG_WARNING, "non-interleaved AVI without index, switching to interleaved\n");
  699. avi->non_interleaved=0;
  700. }
  701. if(avi->non_interleaved) {
  702. av_log(s, AV_LOG_INFO, "non-interleaved AVI\n");
  703. clean_index(s);
  704. }
  705. ff_metadata_conv_ctx(s, NULL, avi_metadata_conv);
  706. ff_metadata_conv_ctx(s, NULL, ff_riff_info_conv);
  707. return 0;
  708. }
  709. static int read_gab2_sub(AVStream *st, AVPacket *pkt) {
  710. if (!strcmp(pkt->data, "GAB2") && AV_RL16(pkt->data+5) == 2) {
  711. uint8_t desc[256];
  712. int score = AVPROBE_SCORE_MAX / 2, ret;
  713. AVIStream *ast = st->priv_data;
  714. AVInputFormat *sub_demuxer;
  715. AVRational time_base;
  716. AVIOContext *pb = avio_alloc_context( pkt->data + 7,
  717. pkt->size - 7,
  718. 0, NULL, NULL, NULL, NULL);
  719. AVProbeData pd;
  720. unsigned int desc_len = avio_rl32(pb);
  721. if (desc_len > pb->buf_end - pb->buf_ptr)
  722. goto error;
  723. ret = avio_get_str16le(pb, desc_len, desc, sizeof(desc));
  724. avio_skip(pb, desc_len - ret);
  725. if (*desc)
  726. av_dict_set(&st->metadata, "title", desc, 0);
  727. avio_rl16(pb); /* flags? */
  728. avio_rl32(pb); /* data size */
  729. pd = (AVProbeData) { .buf = pb->buf_ptr, .buf_size = pb->buf_end - pb->buf_ptr };
  730. if (!(sub_demuxer = av_probe_input_format2(&pd, 1, &score)))
  731. goto error;
  732. if (!(ast->sub_ctx = avformat_alloc_context()))
  733. goto error;
  734. ast->sub_ctx->pb = pb;
  735. if (!avformat_open_input(&ast->sub_ctx, "", sub_demuxer, NULL)) {
  736. ff_read_packet(ast->sub_ctx, &ast->sub_pkt);
  737. *st->codec = *ast->sub_ctx->streams[0]->codec;
  738. ast->sub_ctx->streams[0]->codec->extradata = NULL;
  739. time_base = ast->sub_ctx->streams[0]->time_base;
  740. avpriv_set_pts_info(st, 64, time_base.num, time_base.den);
  741. }
  742. ast->sub_buffer = pkt->data;
  743. memset(pkt, 0, sizeof(*pkt));
  744. return 1;
  745. error:
  746. av_freep(&pb);
  747. }
  748. return 0;
  749. }
  750. static AVStream *get_subtitle_pkt(AVFormatContext *s, AVStream *next_st,
  751. AVPacket *pkt)
  752. {
  753. AVIStream *ast, *next_ast = next_st->priv_data;
  754. int64_t ts, next_ts, ts_min = INT64_MAX;
  755. AVStream *st, *sub_st = NULL;
  756. int i;
  757. next_ts = av_rescale_q(next_ast->frame_offset, next_st->time_base,
  758. AV_TIME_BASE_Q);
  759. for (i=0; i<s->nb_streams; i++) {
  760. st = s->streams[i];
  761. ast = st->priv_data;
  762. if (st->discard < AVDISCARD_ALL && ast && ast->sub_pkt.data) {
  763. ts = av_rescale_q(ast->sub_pkt.dts, st->time_base, AV_TIME_BASE_Q);
  764. if (ts <= next_ts && ts < ts_min) {
  765. ts_min = ts;
  766. sub_st = st;
  767. }
  768. }
  769. }
  770. if (sub_st) {
  771. ast = sub_st->priv_data;
  772. *pkt = ast->sub_pkt;
  773. pkt->stream_index = sub_st->index;
  774. if (ff_read_packet(ast->sub_ctx, &ast->sub_pkt) < 0)
  775. ast->sub_pkt.data = NULL;
  776. }
  777. return sub_st;
  778. }
  779. static int get_stream_idx(int *d){
  780. if( d[0] >= '0' && d[0] <= '9'
  781. && d[1] >= '0' && d[1] <= '9'){
  782. return (d[0] - '0') * 10 + (d[1] - '0');
  783. }else{
  784. return 100; //invalid stream ID
  785. }
  786. }
  787. /**
  788. *
  789. * @param exit_early set to 1 to just gather packet position without making the changes needed to actually read & return the packet
  790. */
  791. static int avi_sync(AVFormatContext *s, int exit_early)
  792. {
  793. AVIContext *avi = s->priv_data;
  794. AVIOContext *pb = s->pb;
  795. int n;
  796. unsigned int d[8];
  797. unsigned int size;
  798. int64_t i, sync;
  799. start_sync:
  800. memset(d, -1, sizeof(d));
  801. for(i=sync=avio_tell(pb); !url_feof(pb); i++) {
  802. int j;
  803. for(j=0; j<7; j++)
  804. d[j]= d[j+1];
  805. d[7]= avio_r8(pb);
  806. size= d[4] + (d[5]<<8) + (d[6]<<16) + (d[7]<<24);
  807. n= get_stream_idx(d+2);
  808. //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);
  809. if(i + (uint64_t)size > avi->fsize || d[0] > 127)
  810. continue;
  811. //parse ix##
  812. if( (d[0] == 'i' && d[1] == 'x' && n < s->nb_streams)
  813. //parse JUNK
  814. ||(d[0] == 'J' && d[1] == 'U' && d[2] == 'N' && d[3] == 'K')
  815. ||(d[0] == 'i' && d[1] == 'd' && d[2] == 'x' && d[3] == '1')){
  816. avio_skip(pb, size);
  817. //av_log(s, AV_LOG_DEBUG, "SKIP\n");
  818. goto start_sync;
  819. }
  820. //parse stray LIST
  821. if(d[0] == 'L' && d[1] == 'I' && d[2] == 'S' && d[3] == 'T'){
  822. avio_skip(pb, 4);
  823. goto start_sync;
  824. }
  825. n= get_stream_idx(d);
  826. if(!((i-avi->last_pkt_pos)&1) && get_stream_idx(d+1) < s->nb_streams)
  827. continue;
  828. //detect ##ix chunk and skip
  829. if(d[2] == 'i' && d[3] == 'x' && n < s->nb_streams){
  830. avio_skip(pb, size);
  831. goto start_sync;
  832. }
  833. //parse ##dc/##wb
  834. if(n < s->nb_streams){
  835. AVStream *st;
  836. AVIStream *ast;
  837. st = s->streams[n];
  838. ast = st->priv_data;
  839. if (!ast) {
  840. av_log(s, AV_LOG_WARNING, "Skiping foreign stream %d packet\n", n);
  841. continue;
  842. }
  843. if(s->nb_streams>=2){
  844. AVStream *st1 = s->streams[1];
  845. AVIStream *ast1= st1->priv_data;
  846. //workaround for broken small-file-bug402.avi
  847. if( d[2] == 'w' && d[3] == 'b'
  848. && n==0
  849. && st ->codec->codec_type == AVMEDIA_TYPE_VIDEO
  850. && st1->codec->codec_type == AVMEDIA_TYPE_AUDIO
  851. && ast->prefix == 'd'*256+'c'
  852. && (d[2]*256+d[3] == ast1->prefix || !ast1->prefix_count)
  853. ){
  854. n=1;
  855. st = st1;
  856. ast = ast1;
  857. av_log(s, AV_LOG_WARNING, "Invalid stream + prefix combination, assuming audio.\n");
  858. }
  859. }
  860. if( (st->discard >= AVDISCARD_DEFAULT && size==0)
  861. /*|| (st->discard >= AVDISCARD_NONKEY && !(pkt->flags & AV_PKT_FLAG_KEY))*/ //FIXME needs a little reordering
  862. || st->discard >= AVDISCARD_ALL){
  863. if (!exit_early) {
  864. ast->frame_offset += get_duration(ast, size);
  865. }
  866. avio_skip(pb, size);
  867. goto start_sync;
  868. }
  869. if (d[2] == 'p' && d[3] == 'c' && size<=4*256+4) {
  870. int k = avio_r8(pb);
  871. int last = (k + avio_r8(pb) - 1) & 0xFF;
  872. avio_rl16(pb); //flags
  873. for (; k <= last; k++)
  874. ast->pal[k] = 0xFF<<24 | avio_rb32(pb)>>8;// b + (g << 8) + (r << 16);
  875. ast->has_pal= 1;
  876. goto start_sync;
  877. } else if( ((ast->prefix_count<5 || sync+9 > i) && d[2]<128 && d[3]<128) ||
  878. d[2]*256+d[3] == ast->prefix /*||
  879. (d[2] == 'd' && d[3] == 'c') ||
  880. (d[2] == 'w' && d[3] == 'b')*/) {
  881. if (exit_early)
  882. return 0;
  883. //av_log(s, AV_LOG_DEBUG, "OK\n");
  884. if(d[2]*256+d[3] == ast->prefix)
  885. ast->prefix_count++;
  886. else{
  887. ast->prefix= d[2]*256+d[3];
  888. ast->prefix_count= 0;
  889. }
  890. avi->stream_index= n;
  891. ast->packet_size= size + 8;
  892. ast->remaining= size;
  893. if(size || !ast->sample_size){
  894. uint64_t pos= avio_tell(pb) - 8;
  895. if(!st->index_entries || !st->nb_index_entries || st->index_entries[st->nb_index_entries - 1].pos < pos){
  896. av_add_index_entry(st, pos, ast->frame_offset, size, 0, AVINDEX_KEYFRAME);
  897. }
  898. }
  899. return 0;
  900. }
  901. }
  902. }
  903. if(pb->error)
  904. return pb->error;
  905. return AVERROR_EOF;
  906. }
  907. static int avi_read_packet(AVFormatContext *s, AVPacket *pkt)
  908. {
  909. AVIContext *avi = s->priv_data;
  910. AVIOContext *pb = s->pb;
  911. int err;
  912. void* dstr;
  913. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  914. int size = avpriv_dv_get_packet(avi->dv_demux, pkt);
  915. if (size >= 0)
  916. return size;
  917. }
  918. if(avi->non_interleaved){
  919. int best_stream_index = 0;
  920. AVStream *best_st= NULL;
  921. AVIStream *best_ast;
  922. int64_t best_ts= INT64_MAX;
  923. int i;
  924. for(i=0; i<s->nb_streams; i++){
  925. AVStream *st = s->streams[i];
  926. AVIStream *ast = st->priv_data;
  927. int64_t ts= ast->frame_offset;
  928. int64_t last_ts;
  929. if(!st->nb_index_entries)
  930. continue;
  931. last_ts = st->index_entries[st->nb_index_entries - 1].timestamp;
  932. if(!ast->remaining && ts > last_ts)
  933. continue;
  934. ts = av_rescale_q(ts, st->time_base, (AVRational){FFMAX(1, ast->sample_size), AV_TIME_BASE});
  935. // av_log(s, AV_LOG_DEBUG, "%"PRId64" %d/%d %"PRId64"\n", ts, st->time_base.num, st->time_base.den, ast->frame_offset);
  936. if(ts < best_ts){
  937. best_ts= ts;
  938. best_st= st;
  939. best_stream_index= i;
  940. }
  941. }
  942. if(!best_st)
  943. return AVERROR_EOF;
  944. best_ast = best_st->priv_data;
  945. best_ts = best_ast->frame_offset;
  946. if(best_ast->remaining)
  947. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY | AVSEEK_FLAG_BACKWARD);
  948. else{
  949. i= av_index_search_timestamp(best_st, best_ts, AVSEEK_FLAG_ANY);
  950. if(i>=0)
  951. best_ast->frame_offset= best_st->index_entries[i].timestamp;
  952. }
  953. // av_log(s, AV_LOG_DEBUG, "%d\n", i);
  954. if(i>=0){
  955. int64_t pos= best_st->index_entries[i].pos;
  956. pos += best_ast->packet_size - best_ast->remaining;
  957. if(avio_seek(s->pb, pos + 8, SEEK_SET) < 0)
  958. return AVERROR_EOF;
  959. // av_log(s, AV_LOG_DEBUG, "pos=%"PRId64"\n", pos);
  960. assert(best_ast->remaining <= best_ast->packet_size);
  961. avi->stream_index= best_stream_index;
  962. if(!best_ast->remaining)
  963. best_ast->packet_size=
  964. best_ast->remaining= best_st->index_entries[i].size;
  965. }
  966. else
  967. return AVERROR_EOF;
  968. }
  969. resync:
  970. if(avi->stream_index >= 0){
  971. AVStream *st= s->streams[ avi->stream_index ];
  972. AVIStream *ast= st->priv_data;
  973. int size, err;
  974. if(get_subtitle_pkt(s, st, pkt))
  975. return 0;
  976. if(ast->sample_size <= 1) // minorityreport.AVI block_align=1024 sample_size=1 IMA-ADPCM
  977. size= INT_MAX;
  978. else if(ast->sample_size < 32)
  979. // arbitrary multiplier to avoid tiny packets for raw PCM data
  980. size= 1024*ast->sample_size;
  981. else
  982. size= ast->sample_size;
  983. if(size > ast->remaining)
  984. size= ast->remaining;
  985. avi->last_pkt_pos= avio_tell(pb);
  986. err= av_get_packet(pb, pkt, size);
  987. if(err<0)
  988. return err;
  989. size = err;
  990. if(ast->has_pal && pkt->data && pkt->size<(unsigned)INT_MAX/2){
  991. uint8_t *pal;
  992. pal = av_packet_new_side_data(pkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE);
  993. if(!pal){
  994. av_log(s, AV_LOG_ERROR, "Failed to allocate data for palette\n");
  995. }else{
  996. memcpy(pal, ast->pal, AVPALETTE_SIZE);
  997. ast->has_pal = 0;
  998. }
  999. }
  1000. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1001. dstr = pkt->destruct;
  1002. size = avpriv_dv_produce_packet(avi->dv_demux, pkt,
  1003. pkt->data, pkt->size, pkt->pos);
  1004. pkt->destruct = dstr;
  1005. pkt->flags |= AV_PKT_FLAG_KEY;
  1006. if (size < 0)
  1007. av_free_packet(pkt);
  1008. } else if (st->codec->codec_type == AVMEDIA_TYPE_SUBTITLE
  1009. && !st->codec->codec_tag && read_gab2_sub(st, pkt)) {
  1010. ast->frame_offset++;
  1011. avi->stream_index = -1;
  1012. ast->remaining = 0;
  1013. goto resync;
  1014. } else {
  1015. /* XXX: How to handle B-frames in AVI? */
  1016. pkt->dts = ast->frame_offset;
  1017. // pkt->dts += ast->start;
  1018. if(ast->sample_size)
  1019. pkt->dts /= ast->sample_size;
  1020. //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);
  1021. pkt->stream_index = avi->stream_index;
  1022. if (st->codec->codec_type == AVMEDIA_TYPE_VIDEO) {
  1023. AVIndexEntry *e;
  1024. int index;
  1025. assert(st->index_entries);
  1026. index= av_index_search_timestamp(st, ast->frame_offset, 0);
  1027. e= &st->index_entries[index];
  1028. if(index >= 0 && e->timestamp == ast->frame_offset){
  1029. if (index == st->nb_index_entries-1){
  1030. int key=1;
  1031. int i;
  1032. uint32_t state=-1;
  1033. for(i=0; i<FFMIN(size,256); i++){
  1034. if(st->codec->codec_id == CODEC_ID_MPEG4){
  1035. if(state == 0x1B6){
  1036. key= !(pkt->data[i]&0xC0);
  1037. break;
  1038. }
  1039. }else
  1040. break;
  1041. state= (state<<8) + pkt->data[i];
  1042. }
  1043. if(!key)
  1044. e->flags &= ~AVINDEX_KEYFRAME;
  1045. }
  1046. if (e->flags & AVINDEX_KEYFRAME)
  1047. pkt->flags |= AV_PKT_FLAG_KEY;
  1048. }
  1049. } else {
  1050. pkt->flags |= AV_PKT_FLAG_KEY;
  1051. }
  1052. ast->frame_offset += get_duration(ast, pkt->size);
  1053. }
  1054. ast->remaining -= size;
  1055. if(!ast->remaining){
  1056. avi->stream_index= -1;
  1057. ast->packet_size= 0;
  1058. }
  1059. if(!avi->non_interleaved && pkt->pos >= 0 && ast->seek_pos > pkt->pos){
  1060. av_free_packet(pkt);
  1061. goto resync;
  1062. }
  1063. ast->seek_pos= 0;
  1064. if(!avi->non_interleaved && st->nb_index_entries>1 && avi->index_loaded>1){
  1065. int64_t dts= av_rescale_q(pkt->dts, st->time_base, AV_TIME_BASE_Q);
  1066. if(avi->dts_max - dts > 2*AV_TIME_BASE){
  1067. avi->non_interleaved= 1;
  1068. av_log(s, AV_LOG_INFO, "Switching to NI mode, due to poor interleaving\n");
  1069. }else if(avi->dts_max < dts)
  1070. avi->dts_max = dts;
  1071. }
  1072. return size;
  1073. }
  1074. if ((err = avi_sync(s, 0)) < 0)
  1075. return err;
  1076. goto resync;
  1077. }
  1078. /* XXX: We make the implicit supposition that the positions are sorted
  1079. for each stream. */
  1080. static int avi_read_idx1(AVFormatContext *s, int size)
  1081. {
  1082. AVIContext *avi = s->priv_data;
  1083. AVIOContext *pb = s->pb;
  1084. int nb_index_entries, i;
  1085. AVStream *st;
  1086. AVIStream *ast;
  1087. unsigned int index, tag, flags, pos, len, first_packet = 1;
  1088. unsigned last_pos= -1;
  1089. unsigned last_idx= -1;
  1090. int64_t idx1_pos, first_packet_pos = 0, data_offset = 0;
  1091. nb_index_entries = size / 16;
  1092. if (nb_index_entries <= 0)
  1093. return -1;
  1094. idx1_pos = avio_tell(pb);
  1095. avio_seek(pb, avi->movi_list+4, SEEK_SET);
  1096. if (avi_sync(s, 1) == 0) {
  1097. first_packet_pos = avio_tell(pb) - 8;
  1098. }
  1099. avi->stream_index = -1;
  1100. avio_seek(pb, idx1_pos, SEEK_SET);
  1101. /* Read the entries and sort them in each stream component. */
  1102. for(i = 0; i < nb_index_entries; i++) {
  1103. if(url_feof(pb))
  1104. return -1;
  1105. tag = avio_rl32(pb);
  1106. flags = avio_rl32(pb);
  1107. pos = avio_rl32(pb);
  1108. len = avio_rl32(pb);
  1109. av_dlog(s, "%d: tag=0x%x flags=0x%x pos=0x%x len=%d/",
  1110. i, tag, flags, pos, len);
  1111. index = ((tag & 0xff) - '0') * 10;
  1112. index += ((tag >> 8) & 0xff) - '0';
  1113. if (index >= s->nb_streams)
  1114. continue;
  1115. st = s->streams[index];
  1116. ast = st->priv_data;
  1117. if(first_packet && first_packet_pos && len) {
  1118. data_offset = first_packet_pos - pos;
  1119. first_packet = 0;
  1120. }
  1121. pos += data_offset;
  1122. av_dlog(s, "%d cum_len=%"PRId64"\n", len, ast->cum_len);
  1123. // even if we have only a single stream, we should
  1124. // switch to non-interleaved to get correct timestamps
  1125. if(last_pos == pos)
  1126. avi->non_interleaved= 1;
  1127. if(last_idx != pos && len) {
  1128. av_add_index_entry(st, pos, ast->cum_len, len, 0, (flags&AVIIF_INDEX) ? AVINDEX_KEYFRAME : 0);
  1129. last_idx= pos;
  1130. }
  1131. ast->cum_len += get_duration(ast, len);
  1132. last_pos= pos;
  1133. }
  1134. return 0;
  1135. }
  1136. static int guess_ni_flag(AVFormatContext *s){
  1137. int i;
  1138. int64_t last_start=0;
  1139. int64_t first_end= INT64_MAX;
  1140. int64_t oldpos= avio_tell(s->pb);
  1141. int *idx;
  1142. int64_t min_pos, pos;
  1143. for(i=0; i<s->nb_streams; i++){
  1144. AVStream *st = s->streams[i];
  1145. int n= st->nb_index_entries;
  1146. unsigned int size;
  1147. if(n <= 0)
  1148. continue;
  1149. if(n >= 2){
  1150. int64_t pos= st->index_entries[0].pos;
  1151. avio_seek(s->pb, pos + 4, SEEK_SET);
  1152. size= avio_rl32(s->pb);
  1153. if(pos + size > st->index_entries[1].pos)
  1154. last_start= INT64_MAX;
  1155. }
  1156. if(st->index_entries[0].pos > last_start)
  1157. last_start= st->index_entries[0].pos;
  1158. if(st->index_entries[n-1].pos < first_end)
  1159. first_end= st->index_entries[n-1].pos;
  1160. }
  1161. avio_seek(s->pb, oldpos, SEEK_SET);
  1162. if (last_start > first_end)
  1163. return 1;
  1164. idx= av_mallocz(sizeof(*idx) * s->nb_streams);
  1165. for (min_pos=pos=0; min_pos!=INT64_MAX; pos= min_pos+1) {
  1166. int64_t max_dts = INT64_MIN/2, min_dts= INT64_MAX/2;
  1167. min_pos = INT64_MAX;
  1168. for (i=0; i<s->nb_streams; i++) {
  1169. AVStream *st = s->streams[i];
  1170. int n= st->nb_index_entries;
  1171. while (idx[i]<n && st->index_entries[idx[i]].pos < pos)
  1172. idx[i]++;
  1173. if (idx[i] < n) {
  1174. min_dts = FFMIN(min_dts, av_rescale_q(st->index_entries[idx[i]].timestamp, st->time_base, AV_TIME_BASE_Q));
  1175. min_pos = FFMIN(min_pos, st->index_entries[idx[i]].pos);
  1176. }
  1177. if (idx[i])
  1178. max_dts = FFMAX(max_dts, av_rescale_q(st->index_entries[idx[i]-1].timestamp, st->time_base, AV_TIME_BASE_Q));
  1179. }
  1180. if(max_dts - min_dts > 2*AV_TIME_BASE) {
  1181. av_free(idx);
  1182. return 1;
  1183. }
  1184. }
  1185. av_free(idx);
  1186. return 0;
  1187. }
  1188. static int avi_load_index(AVFormatContext *s)
  1189. {
  1190. AVIContext *avi = s->priv_data;
  1191. AVIOContext *pb = s->pb;
  1192. uint32_t tag, size;
  1193. int64_t pos= avio_tell(pb);
  1194. int ret = -1;
  1195. if (avio_seek(pb, avi->movi_end, SEEK_SET) < 0)
  1196. goto the_end; // maybe truncated file
  1197. av_dlog(s, "movi_end=0x%"PRIx64"\n", avi->movi_end);
  1198. for(;;) {
  1199. if (url_feof(pb))
  1200. break;
  1201. tag = avio_rl32(pb);
  1202. size = avio_rl32(pb);
  1203. av_dlog(s, "tag=%c%c%c%c size=0x%x\n",
  1204. tag & 0xff,
  1205. (tag >> 8) & 0xff,
  1206. (tag >> 16) & 0xff,
  1207. (tag >> 24) & 0xff,
  1208. size);
  1209. if (tag == MKTAG('i', 'd', 'x', '1') &&
  1210. avi_read_idx1(s, size) >= 0) {
  1211. avi->index_loaded=2;
  1212. ret = 0;
  1213. break;
  1214. }
  1215. size += (size & 1);
  1216. if (avio_skip(pb, size) < 0)
  1217. break; // something is wrong here
  1218. }
  1219. the_end:
  1220. avio_seek(pb, pos, SEEK_SET);
  1221. return ret;
  1222. }
  1223. static void seek_subtitle(AVStream *st, AVStream *st2, int64_t timestamp)
  1224. {
  1225. AVIStream *ast2 = st2->priv_data;
  1226. int64_t ts2 = av_rescale_q(timestamp, st->time_base, st2->time_base);
  1227. av_free_packet(&ast2->sub_pkt);
  1228. if (avformat_seek_file(ast2->sub_ctx, 0, INT64_MIN, ts2, ts2, 0) >= 0 ||
  1229. avformat_seek_file(ast2->sub_ctx, 0, ts2, ts2, INT64_MAX, 0) >= 0)
  1230. ff_read_packet(ast2->sub_ctx, &ast2->sub_pkt);
  1231. }
  1232. static int avi_read_seek(AVFormatContext *s, int stream_index, int64_t timestamp, int flags)
  1233. {
  1234. AVIContext *avi = s->priv_data;
  1235. AVStream *st;
  1236. int i, index;
  1237. int64_t pos, pos_min;
  1238. AVIStream *ast;
  1239. if (!avi->index_loaded) {
  1240. /* we only load the index on demand */
  1241. avi_load_index(s);
  1242. avi->index_loaded |= 1;
  1243. }
  1244. assert(stream_index>= 0);
  1245. st = s->streams[stream_index];
  1246. ast= st->priv_data;
  1247. index= av_index_search_timestamp(st, timestamp * FFMAX(ast->sample_size, 1), flags);
  1248. if (index<0) {
  1249. if (st->nb_index_entries > 0)
  1250. av_log(s, AV_LOG_DEBUG, "Failed to find timestamp %"PRId64 " in index %"PRId64 " .. %"PRId64 "\n",
  1251. timestamp * FFMAX(ast->sample_size, 1),
  1252. st->index_entries[0].timestamp,
  1253. st->index_entries[st->nb_index_entries - 1].timestamp);
  1254. return -1;
  1255. }
  1256. /* find the position */
  1257. pos = st->index_entries[index].pos;
  1258. timestamp = st->index_entries[index].timestamp / FFMAX(ast->sample_size, 1);
  1259. // av_log(s, AV_LOG_DEBUG, "XX %"PRId64" %d %"PRId64"\n", timestamp, index, st->index_entries[index].timestamp);
  1260. if (CONFIG_DV_DEMUXER && avi->dv_demux) {
  1261. /* One and only one real stream for DV in AVI, and it has video */
  1262. /* offsets. Calling with other stream indexes should have failed */
  1263. /* the av_index_search_timestamp call above. */
  1264. assert(stream_index == 0);
  1265. if(avio_seek(s->pb, pos, SEEK_SET) < 0)
  1266. return -1;
  1267. /* Feed the DV video stream version of the timestamp to the */
  1268. /* DV demux so it can synthesize correct timestamps. */
  1269. ff_dv_offset_reset(avi->dv_demux, timestamp);
  1270. avi->stream_index= -1;
  1271. return 0;
  1272. }
  1273. pos_min= pos;
  1274. for(i = 0; i < s->nb_streams; i++) {
  1275. AVStream *st2 = s->streams[i];
  1276. AVIStream *ast2 = st2->priv_data;
  1277. ast2->packet_size=
  1278. ast2->remaining= 0;
  1279. if (ast2->sub_ctx) {
  1280. seek_subtitle(st, st2, timestamp);
  1281. continue;
  1282. }
  1283. if (st2->nb_index_entries <= 0)
  1284. continue;
  1285. // assert(st2->codec->block_align);
  1286. assert((int64_t)st2->time_base.num*ast2->rate == (int64_t)st2->time_base.den*ast2->scale);
  1287. index = av_index_search_timestamp(
  1288. st2,
  1289. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1290. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1291. if(index<0)
  1292. index=0;
  1293. ast2->seek_pos= st2->index_entries[index].pos;
  1294. pos_min= FFMIN(pos_min,ast2->seek_pos);
  1295. }
  1296. for(i = 0; i < s->nb_streams; i++) {
  1297. AVStream *st2 = s->streams[i];
  1298. AVIStream *ast2 = st2->priv_data;
  1299. if (ast2->sub_ctx || st2->nb_index_entries <= 0)
  1300. continue;
  1301. index = av_index_search_timestamp(
  1302. st2,
  1303. av_rescale_q(timestamp, st->time_base, st2->time_base) * FFMAX(ast2->sample_size, 1),
  1304. flags | AVSEEK_FLAG_BACKWARD | (st2->codec->codec_type != AVMEDIA_TYPE_VIDEO ? AVSEEK_FLAG_ANY : 0));
  1305. if(index<0)
  1306. index=0;
  1307. while(!avi->non_interleaved && index>0 && st2->index_entries[index-1].pos >= pos_min)
  1308. index--;
  1309. ast2->frame_offset = st2->index_entries[index].timestamp;
  1310. }
  1311. /* do the seek */
  1312. if (avio_seek(s->pb, pos_min, SEEK_SET) < 0) {
  1313. av_log(s, AV_LOG_ERROR, "Seek failed\n");
  1314. return -1;
  1315. }
  1316. avi->stream_index= -1;
  1317. avi->dts_max= INT_MIN;
  1318. return 0;
  1319. }
  1320. static int avi_read_close(AVFormatContext *s)
  1321. {
  1322. int i;
  1323. AVIContext *avi = s->priv_data;
  1324. for(i=0;i<s->nb_streams;i++) {
  1325. AVStream *st = s->streams[i];
  1326. AVIStream *ast = st->priv_data;
  1327. if (ast) {
  1328. if (ast->sub_ctx) {
  1329. av_freep(&ast->sub_ctx->pb);
  1330. avformat_close_input(&ast->sub_ctx);
  1331. }
  1332. av_free(ast->sub_buffer);
  1333. av_free_packet(&ast->sub_pkt);
  1334. }
  1335. }
  1336. av_free(avi->dv_demux);
  1337. return 0;
  1338. }
  1339. static int avi_probe(AVProbeData *p)
  1340. {
  1341. int i;
  1342. /* check file header */
  1343. for(i=0; avi_headers[i][0]; i++)
  1344. if(!memcmp(p->buf , avi_headers[i] , 4) &&
  1345. !memcmp(p->buf+8, avi_headers[i]+4, 4))
  1346. return AVPROBE_SCORE_MAX;
  1347. return 0;
  1348. }
  1349. AVInputFormat ff_avi_demuxer = {
  1350. .name = "avi",
  1351. .long_name = NULL_IF_CONFIG_SMALL("AVI format"),
  1352. .priv_data_size = sizeof(AVIContext),
  1353. .read_probe = avi_probe,
  1354. .read_header = avi_read_header,
  1355. .read_packet = avi_read_packet,
  1356. .read_close = avi_read_close,
  1357. .read_seek = avi_read_seek,
  1358. .priv_class = &demuxer_class,
  1359. };