Source file gIF.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
exception Error of string
type version = GIF87a | GIF89a
type info = {
version : version;
screen_width : int;
screen_height : int;
global_color_table : ColorTable.t option;
global_color_table_sort : bool;
global_color_table_size : int;
original_color_res : int;
original_aspect_ratio : int;
background_color_index : int;
}
type image_descriptor = {
image_left_pos : int;
image_top_pos : int;
image_width : int;
image_height : int;
local_color_table : ColorTable.t option;
local_color_table_sort : bool;
local_color_table_size : int;
interlace_flag : bool;
}
type graphic_control_ext = {
disposal_method : int;
user_input : bool;
transparent_color : int option;
delay_time : int;
}
type image_block = {
image_descriptor : image_descriptor;
image_control : graphic_control_ext option;
image_data : Bytes.t;
image_lzw_code_size : int;
}
type app_ext = {
app_identifier : string;
app_auth_code : string;
app_data : string;
}
type block =
| ImageBlock of image_block
| UnknownExtBlock of string
| AppExtBlock of app_ext
| Trailer
type t = { stream_descriptor : info; blocks : block list }
let default_info =
{
version = GIF89a;
screen_width = 0;
screen_height = 0;
global_color_table = None;
global_color_table_sort = false;
global_color_table_size = 0;
original_color_res = 0;
original_aspect_ratio = 0;
background_color_index = 0;
}
let read_uint16 inp =
let b1 = input_byte inp in
let b2 = input_byte inp in
b1 + (256 * b2)
let write_uint16 f n =
output_byte f n;
output_byte f (n lsr 8)
let int_of_option = function Some _ -> 1 | None -> 0
let int_of_bool = function true -> 1 | false -> 0
let input_string inp n =
let buf = Bytes.create n in
really_input inp buf 0 n;
String.of_bytes buf
let unpack_fields byte lengths =
let sum = List.fold_left ( + ) 0 and byte = byte in
let rec unpack = function
| [] -> []
| x :: xs -> ((byte lsr sum xs) land ((1 lsl x) - 1)) :: unpack xs
in
unpack lengths
let pack_fields values lengths =
let rec pack vs ls offset =
match (vs, ls) with
| v :: vs, l :: ls ->
((v land ((1 lsl l) - 1)) lsl (offset - l)) + pack vs ls (offset - l)
| [], [] -> 0
| _, _ -> failwith "pack_fields"
in
pack values lengths 8
let info inp =
let buf = Bytes.create 6 in
really_input inp buf 0 6;
match String.of_bytes buf with
| "GIF87a" -> { info with version = GIF87a }
| "GIF89a" -> { info with version = GIF89a }
| _ -> raise (Error "Unsupported format")
let read_logical_screen_descriptor info inp =
let w = read_uint16 inp in
let h = read_uint16 inp in
let gct, cres, gct_sort, gct_size =
match unpack_fields (input_byte inp) [ 1; 3; 1; 3 ] with
| [ v1; v2; v3; v4 ] -> (v1, v2, v3, v4)
| _ -> failwith "read_logical_screen_descriptor"
in
let bgc = input_byte inp in
let ratio = input_byte inp in
{
info with
screen_width = w;
screen_height = h;
global_color_table = (if gct = 1 then Some (ColorTable.create 0) else None);
global_color_table_sort = gct_sort = 1;
global_color_table_size = gct_size;
original_color_res = cres;
original_aspect_ratio = ratio;
background_color_index = bgc;
}
let read_color_table n inp =
let tbl = ColorTable.create n in
for i = 0 to n - 1 do
let r = input_byte inp in
let g = input_byte inp in
let b = input_byte inp in
ColorTable.set tbl i (r, g, b)
done;
tbl
let read_global_color_table info s =
let n = 2 lsl info.global_color_table_size in
{ info with global_color_table = Some (read_color_table n s) }
let read_info s =
let hd_info = read_header default_info s in
let desc = read_logical_screen_descriptor hd_info s in
if desc.global_color_table != None then read_global_color_table desc s
else desc
let read_image_descriptor inp =
let l = read_uint16 inp in
let t = read_uint16 inp in
let w = read_uint16 inp in
let h = read_uint16 inp in
let lct, il, lct_sort, lct_size =
match unpack_fields (input_byte inp) [ 1; 1; 1; 2; 3 ] with
| [ v1; v2; v3; _; v4 ] -> (v1, v2, v3, v4)
| _ -> failwith "read_image_descriptor"
in
{
image_left_pos = l;
image_top_pos = t;
image_width = w;
image_height = h;
local_color_table = (if lct = 1 then Some (ColorTable.create 0) else None);
local_color_table_sort = lct_sort = 1;
local_color_table_size = lct_size;
interlace_flag = il = 1;
}
let read_data_subblocks inp =
let buf = Buffer.create 255 in
let rec read () =
match input_byte inp with
| 0x00 -> ()
| size ->
let data = input_string inp size in
Buffer.add_string buf data;
read ()
in
try
read ();
Buffer.contents buf
with End_of_file -> failwith "dupa"
let read_image_block inp =
let desc =
let desc = read_image_descriptor inp in
if desc.local_color_table != None then
let n = 2 lsl desc.local_color_table_size in
{ desc with local_color_table = Some (read_color_table n inp) }
else desc
in
let lzw_cs = input_byte inp in
let data = read_data_subblocks inp in
ImageBlock
{
image_descriptor = desc;
image_control = None;
image_data = String.to_bytes data;
image_lzw_code_size = lzw_cs;
}
let read_graphic_control_ext inp =
ignore (input_byte inp);
let dm, ui, tc =
match unpack_fields (input_byte inp) [ 3; 3; 1; 1 ] with
| [ _; v1; v2; v3 ] -> (v1, v2, v3)
| _ -> failwith "read_graphic_control_ext"
in
let delay = read_uint16 inp in
let col_idx = input_byte inp in
ignore (input_byte inp);
{
disposal_method = dm;
user_input = ui = 1;
transparent_color = (if tc = 1 then Some col_idx else None);
delay_time = delay;
}
let read_app_ext inp =
ignore (input_byte inp);
let app_id = input_string inp 8 in
let app_code = input_string inp 3 in
let data = read_data_subblocks inp in
AppExtBlock
{ app_identifier = app_id; app_auth_code = app_code; app_data = data }
let inp = CommentBlock (read_data_subblocks inp)
let read_unknown_ext inp = UnknownExtBlock (read_data_subblocks inp)
let rec read_block inp =
match input_byte inp with
| 0x2C -> read_image_block inp
| 0x21 -> (
match input_byte inp with
| 0xF9 -> (
let ctl = read_graphic_control_ext inp in
match read_block inp with
| ImageBlock im -> ImageBlock { im with image_control = Some ctl }
| b -> b)
| 0xFF -> read_app_ext inp
| 0xFE -> read_comment_ext inp
| _ -> read_unknown_ext inp)
| 0x3B -> Trailer
| 0x00 -> read_block inp
| _ -> raise (Error "Unrecognized data")
let from_file file_name =
let file = open_in_bin file_name in
let info = read_info file in
let rec read_blocks () =
match read_block file with Trailer -> [] | b -> b :: read_blocks ()
in
let gif = { stream_descriptor = info; blocks = read_blocks () } in
close_in file;
gif
let info out =
match info.version with
| GIF87a -> output_string out "GIF87a"
| GIF89a -> output_string out "GIF89a"
let write_logical_screen_descriptor info out =
write_uint16 out info.screen_width;
write_uint16 out info.screen_height;
output_byte out
(pack_fields
[
int_of_option info.global_color_table;
info.original_color_res;
int_of_bool info.global_color_table_sort;
info.global_color_table_size;
]
[ 1; 3; 1; 3 ]);
output_byte out info.background_color_index;
output_byte out info.original_aspect_ratio
let write_color_table tbl out =
for i = 0 to Array.length tbl - 1 do
let r, g, b = tbl.(i) in
output_byte out r;
output_byte out g;
output_byte out b
done
let write_info info out =
write_header info out;
write_logical_screen_descriptor info out;
match info.global_color_table with
| Some gct -> write_color_table gct out
| None -> ()
let write_data_subblocks data out =
let len = String.length data in
let rec write from =
if from < len - 255 then (
output_byte out 255;
output_string out (String.sub data from 255);
write (from + 255))
else if from = len - 1 then output_byte out 0x00
else (
output_byte out (len - from);
output_string out (String.sub data from (len - from));
output_byte out 0x00)
in
write 0
let write_data_subblocks_from_list data out =
let n = ref 0 and buf = Bytes.create 255 in
let rec fn data =
if !n = 255 then (
output_byte out 0xFF;
output_string out (String.of_bytes buf);
n := 0;
fn data)
else if Bytes.length data == 0 then (
output_byte out !n;
output_string out (String.sub (String.of_bytes buf) 0 !n);
if !n > 0 then output_byte out 0x00)
else
let head = Bytes.get data 0 in
let tail = Bytes.sub data 1 (Bytes.length data - 1) in
Bytes.set buf !n head;
incr n;
fn tail
in
fn data
let write_image_block img out =
output_byte out 0x2C;
write_uint16 out img.image_descriptor.image_left_pos;
write_uint16 out img.image_descriptor.image_top_pos;
write_uint16 out img.image_descriptor.image_width;
write_uint16 out img.image_descriptor.image_height;
output_byte out
(pack_fields
[
int_of_option img.image_descriptor.local_color_table;
int_of_bool img.image_descriptor.interlace_flag;
int_of_bool img.image_descriptor.local_color_table_sort;
0;
img.image_descriptor.local_color_table_size;
]
[ 1; 1; 1; 2; 3 ]);
(match img.image_descriptor.local_color_table with
| Some lct -> write_color_table lct out
| None -> ());
output_byte out img.image_lzw_code_size;
write_data_subblocks_from_list img.image_data out
let write_graphic_control_ext ctl out =
output_byte out 0x21;
output_byte out 0xF9;
output_byte out 0x04;
output_byte out
(pack_fields
[
0;
ctl.disposal_method;
int_of_bool ctl.user_input;
int_of_option ctl.transparent_color;
]
[ 3; 3; 1; 1 ]);
write_uint16 out ctl.delay_time;
output_byte out (match ctl.transparent_color with Some c -> c | None -> 0);
output_byte out 0x00
let write_block out block =
match block with
| ImageBlock img ->
(match img.image_control with
| Some ctl -> write_graphic_control_ext ctl out
| None -> ());
write_image_block img out
| CommentBlock data ->
output_byte out 0x21;
output_byte out 0xFE;
write_data_subblocks data out
| UnknownExtBlock _data -> ()
| AppExtBlock app_ext ->
output_byte out 0x21;
output_byte out 0xFF;
output_byte out 0x0B;
output_string out app_ext.app_identifier;
output_string out app_ext.app_auth_code;
write_data_subblocks app_ext.app_data out
| Trailer -> output_byte out 0x3B
let to_file gif file =
let out = open_out_bin file in
write_info gif.stream_descriptor out;
List.iter (write_block out) gif.blocks;
write_block out Trailer;
close_out out
let get_frames gif =
let flt = function ImageBlock _ -> true | _ -> false
and get_img = function ImageBlock b -> b | _ -> failwith "" in
List.map get_img (List.filter flt gif.blocks)
let image_count gif = List.length (get_frames gif)
let get_image gif n =
let img =
try List.nth (get_frames gif) n
with Failure _ -> raise (Error "get_image: frame not found")
in
let w = img.image_descriptor.image_width
and h = img.image_descriptor.image_height in
let ct =
match img.image_descriptor.local_color_table with
| Some ct -> ct
| None -> (
match gif.stream_descriptor.global_color_table with
| Some ct -> ct
| None -> raise (Error "No color table"))
in
Image.v
~offset:
(img.image_descriptor.image_left_pos, img.image_descriptor.image_top_pos)
~transparent:
(match img.image_control with
| None -> None
| Some x -> x.transparent_color)
~delay_time:
(match img.image_control with
| None -> None
| Some x -> Some x.delay_time)
(w, h) ct img.image_data img.image_lzw_code_size
img.image_descriptor.interlace_flag
let _find_color_fn palette =
let colors =
Bigarray.Array3.create Bigarray.int Bigarray.c_layout 256 256 256
in
Array.iteri (fun i (r, g, b) -> colors.{r, g, b} <- i) palette;
function r, g, b -> Bigarray.Array3.get colors r g b
let compute_color_table (palette : ColorTable.t) : int * int * ColorTable.t =
let n = Array.length palette in
let ct_size =
if n <= 2 then 0
else if n <= 4 then 1
else if n <= 8 then 2
else if n <= 16 then 3
else if n <= 32 then 4
else if n <= 64 then 5
else if n <= 128 then 6
else if n <= 256 then 7
else raise (Error "too many colors in palette")
in
let code_size = if ct_size < 2 then 2 else ct_size + 1 in
let table =
let p = ColorTable.create (1 lsl (ct_size + 1)) in
Array.iteri (fun i c -> ColorTable.set p i c) palette;
p
in
(ct_size, code_size, table)
let block_of_image ~w ~h ~code_size (img : Image.t) : block =
let ctl =
{
disposal_method = 0;
user_input = false;
transparent_color = Image.transparent img;
delay_time = (match Image.delay_time img with Some d -> d | None -> 0);
}
in
let desc =
{
image_left_pos = 0;
image_top_pos = 0;
image_width = w;
image_height = h;
local_color_table = None;
local_color_table_sort = false;
local_color_table_size = 0;
interlace_flag = false;
}
in
ImageBlock
{
image_descriptor = desc;
image_control = Some ctl;
image_data = Image.compressed_image_data img;
image_lzw_code_size = code_size;
}
let from_images (images : Image.t list) : t =
match images with
| [] -> raise (Error "from_images: empty image list")
| img0 :: _ ->
let w, h = Image.dimensions img0 in
List.iter
(fun img ->
let w', h' = Image.dimensions img in
if w <> w' || h <> h' then
raise (Error "from_images: inconsistent image dimensions");
let n_colors = Array.length (Image.palette img) in
if n_colors > 256 then
raise (Error "from_images: too many colors in an image"))
images;
let palette = Image.palette img0 in
let ct_size, code_size, global_ct = compute_color_table palette in
let info =
{
default_info with
screen_width = w;
screen_height = h;
global_color_table = Some global_ct;
global_color_table_size = ct_size;
}
in
let blocks =
List.map (fun img -> block_of_image img ~w ~h ~code_size) images
in
{ stream_descriptor = info; blocks }
let from_image img = from_images [ img ]
let dimensions i =
(i.stream_descriptor.screen_width, i.stream_descriptor.screen_height)