Debian Codegraph @

src/djvu/iff.c

raw
1 /*
2 * iff.c - read/write IFF files (DjVu files are IFF)
3 */
4
5 #include "../base/mdjvucfg.h"
6 #include <minidjvu/minidjvu.h>
7 #include <stdlib.h>
8 #include <stdio.h>
9
10
11 static void read_align(FILE *f)
12 {
13 long pos = ftell(f);
14 if (pos & 1) fgetc(f);
15 }
16
17 static void write_align(FILE *f)
18 {
19 long pos = ftell(f);
20 if (pos & 1) fputc(0, f);
21 }
22
23
24 typedef struct
25 {
26 int32 id;
27 uint32 start;
28 uint32 length;
29 int write;
30 } Chunk;
31
32 MDJVU_IMPLEMENT int32 mdjvu_iff_get_id(mdjvu_iff_t iff)
33 {
34 return ((Chunk *) iff) -> id;
35 }
36
37 MDJVU_IMPLEMENT int32 mdjvu_iff_get_length(mdjvu_iff_t iff)
38 {
39 return ((Chunk *) iff) -> length;
40 }
41
42 MDJVU_IMPLEMENT mdjvu_iff_t mdjvu_iff_read_chunk(mdjvu_file_t file)
43 {
44 FILE *f = (FILE *) file;
45 Chunk *chunk = (Chunk *) malloc(sizeof(Chunk));
46 read_align(f);
47 chunk->id = mdjvu_read_big_endian_int32(file);
48 chunk->length = mdjvu_read_big_endian_int32(file);
49 chunk->start = ftell(f);
50 chunk->write = 0;
51
52 return (mdjvu_iff_t) chunk;
53 }
54
55 MDJVU_IMPLEMENT mdjvu_iff_t mdjvu_iff_write_chunk(int32 id, mdjvu_file_t file)
56 {
57 FILE *f = (FILE *) file;
58 Chunk *chunk = (Chunk *) malloc(sizeof(Chunk));
59 write_align(f);
60 mdjvu_write_big_endian_int32(id, file);
61 mdjvu_write_big_endian_int32(0, file); /* will be length */
62
63 chunk->id = id;
64 chunk->start = ftell(f);
65 chunk->length = 0;
66 chunk->write = 1;
67
68 return (mdjvu_iff_t) chunk;
69 }
70
71 MDJVU_IMPLEMENT void mdjvu_iff_close_chunk(mdjvu_iff_t iff, mdjvu_file_t file)
72 {
73 FILE *f = (FILE *) file;
74 Chunk *chunk = (Chunk *) iff;
75
76 if (chunk->write)
77 {
78 long pos = ftell(f);
79 uint32 length = pos - chunk->start;
80 fseek(f, chunk->start - 4, SEEK_SET);
81 mdjvu_write_big_endian_int32(length, file);
82 fseek(f, pos, SEEK_SET);
83 }
84 else
85 {
86 fseek(f, chunk->start + chunk->length, SEEK_SET);
87 }
88
89 free(chunk);
90 }