-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRunLengthCodec.java
More file actions
451 lines (419 loc) · 16.9 KB
/
RunLengthCodec.java
File metadata and controls
451 lines (419 loc) · 16.9 KB
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
/*
* @(#)RunLengthCodec.java
*
* Copyright © 2011 Werner Randelshofer, Immensee, Switzerland.
* All rights reserved.
*
* You may not use, copy or modify this file, except in compliance with the
* license agreement you entered into with Werner Randelshofer.
* For details see accompanying license terms.
*/
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.WritableRaster;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteOrder;
import static java.lang.Math.*;
/**
* {@code RunLengthCodec} encodes a BufferedImage as a byte[] array.
* <p>
* This codec only works with the AVI file format. Other formats, such as
* QuickTime, use a different encoding for run-length compressed video.
* <p>
* This codec currently only supports encoding from a {@code BufferedImage} into
* the file format. Decoding support may be added in the future.
* <p>
* Supported input formats:
* <ul>
* {@code Format} with {@code BufferedImage.class}, any width, any height,
* depth=8.
* </ul>
* Supported output formats:
* <ul>
* {@code Format} with {@code byte[].class}, same width and height as input
* format, depth=8.
* </ul>
* The codec supports lossless delta- and key-frame encoding of images with 8
* bits per pixel.
* <p>
* The codec does not encode the color palette of an image. This must be done
* separately.
* <p>
* A frame is compressed line by line from bottom to top.
* <p>
* Each line of a frame is compressed individually. A line consists of two-byte
* op-codes optionally followed by data. The end of the line is marked with
* the EOL op-code.
* <p>
* The following op-codes are supported:
* <ul>
* <li>{@code 0x00 0x00}
* <br>Marks the end of a line.</li>
*
* <li>{@code 0x00 0x01}
* <br>Marks the end of the bitmap.</li>
*
* <li>{@code 0x00 0x02 x y}
* <br> Marks a delta (skip). {@code x} and {@code y}
* indicate the horizontal and vertical offset from the current position.
* {@code x} and {@code y} are unsigned 8-bit values.</li>
*
* <li>{@code 0x00 n data{n} 0x00?}
* <br> Marks a literal run. {@code n}
* gives the number of data bytes that follow. {@code n} must be between 3 and
* 255. If n is odd, a pad byte with the value 0x00 must be added.
* </li>
* <li>{@code n data}
* <br> Marks a repetition. {@code n}
* gives the number of times the data byte is repeated. {@code n} must be
* between 1 and 255.
* </li>
* </ul>
* Example:
* <pre>
* Compressed data Expanded data
*
* 03 04 04 04 04
* 05 06 06 06 06 06 06
* 00 03 45 56 67 00 45 56 67
* 02 78 78 78
* 00 02 05 01 Move 5 right and 1 down
* 02 78 78 78
* 00 00 End of line
* 09 1E 1E 1E 1E 1E 1E 1E 1E 1E 1E
* 00 01 End of RLE bitmap
* </pre>
*
* References:<br/>
* <a href="http://wiki.multimedia.cx/index.php?title=Microsoft_RLE">http://wiki.multimedia.cx/index.php?title=Microsoft_RLE</a><br>
*
*
* @author Werner Randelshofer
* @version $Id: RunLengthCodec.java 186 2012-03-28 11:18:42Z werner $
*/
public class RunLengthCodec extends AbstractVideoCodec {
private byte[] previousPixels;
private int frameCounter;
public RunLengthCodec() {
super(new Format[]{
new Format(VideoFormatKeys.MediaTypeKey, FormatKeys.MediaType.VIDEO, VideoFormatKeys.MimeTypeKey, VideoFormatKeys.MIME_JAVA,
VideoFormatKeys.EncodingKey, VideoFormatKeys.ENCODING_BUFFERED_IMAGE, VideoFormatKeys.FixedFrameRateKey, true), //
},
new Format[]{
new Format(VideoFormatKeys.MediaTypeKey, FormatKeys.MediaType.VIDEO, VideoFormatKeys.MimeTypeKey, VideoFormatKeys.MIME_AVI,
VideoFormatKeys.EncodingKey, VideoFormatKeys.ENCODING_AVI_RLE, VideoFormatKeys.DataClassKey, byte[].class,
VideoFormatKeys.FixedFrameRateKey, true, VideoFormatKeys.DepthKey,8), //
});
}
@Override
public void reset() {
frameCounter = 0;
}
@Override
public int process(Buffer in, Buffer out) {
if (outputFormat==null) return CODEC_FAILED;
if (outputFormat.get(VideoFormatKeys.EncodingKey).equals(VideoFormatKeys.ENCODING_AVI_RLE)) {
return encode(in, out);
} else {
return decode(in, out);
}
}
private int encode(Buffer in, Buffer out) {
out.setMetaTo(in);
out.format=outputFormat;
if (in.isFlag(BufferFlag.DISCARD)) {
return CODEC_OK;
}
ByteArrayImageOutputStream tmp;
if (out.data instanceof byte[]) {
tmp = new ByteArrayImageOutputStream((byte[]) out.data);
} else {
tmp = new ByteArrayImageOutputStream();
}
// Handle sub-image
Rectangle r;
int scanlineStride;
if (in.data instanceof BufferedImage) {
BufferedImage image = (BufferedImage) in.data;
WritableRaster raster = image.getRaster();
scanlineStride = raster.getSampleModel().getWidth();
r = raster.getBounds();
r.x -= raster.getSampleModelTranslateX();
r.y -= raster.getSampleModelTranslateY();
out.header = image.getColorModel();
} else {
r = new Rectangle(0, 0, outputFormat.get(VideoFormatKeys.WidthKey), outputFormat.get(VideoFormatKeys.HeightKey));
scanlineStride = outputFormat.get(VideoFormatKeys.WidthKey);
out.header = null;
}
int offset = r.x + r.y * scanlineStride;
boolean isKeyframe = frameCounter== 0
|| frameCounter % outputFormat.get(VideoFormatKeys.KeyFrameIntervalKey,outputFormat.get(VideoFormatKeys.FrameRateKey).intValue()) == 0;
frameCounter++;
try {
byte[] pixels = getIndexed8(in);
if (pixels == null) {
return CODEC_FAILED;
}
if (isKeyframe) {
writeKey8(tmp, pixels, r.width, r.height, offset, scanlineStride);
out.setFlag(BufferFlag.KEYFRAME);
} else {
writeDelta8(tmp, pixels, previousPixels, r.width, r.height, offset, scanlineStride);
out.clearFlag(BufferFlag.KEYFRAME);
}
out.data = tmp.getBuffer();
out.offset = 0;
out.length = (int) tmp.getStreamPosition();
//
if (previousPixels == null) {
previousPixels = pixels.clone();
} else {
System.arraycopy(pixels, 0, previousPixels, 0, pixels.length);
}
return CODEC_OK;
} catch (IOException ex) {
ex.printStackTrace();
out.setFlag(BufferFlag.DISCARD);
return CODEC_FAILED;
}
}
private int decode(Buffer in, Buffer out) {
return CODEC_FAILED;
}
/** Encodes an 8-bit key frame.
*
* @param out The output stream.
* @param data The image data.
* @param offset The offset to the first pixel in the data array.
* @param width The width of the image in data elements.
* @param scanlineStride The number to append to offset to get to the next scanline.
*/
public void writeKey8(OutputStream out, byte[] data, int width, int height, int offset, int scanlineStride) throws IOException {
ByteArrayImageOutputStream buf = new ByteArrayImageOutputStream(data.length);
writeKey8(buf, data, width, height, offset, scanlineStride);
buf.toOutputStream(out);
}
/** Encodes an 8-bit key frame.
*
* @param out The output stream.
* @param data The image data.
* @param offset The offset to the first pixel in the data array.
* @param width The width of the image in data elements.
* @param scanlineStride The number to append to offset to get to the next scanline.
*/
public void writeKey8(ImageOutputStream out, byte[] data, int width, int height, int offset, int scanlineStride)
throws IOException {
out.setByteOrder(ByteOrder.LITTLE_ENDIAN);
int ymax = offset + height * scanlineStride;
int upsideDown = ymax - scanlineStride + offset;
// Encode each scanline separately
for (int y = offset; y < ymax; y += scanlineStride) {
int xy = upsideDown - y;
int xymax = xy + width;
int literalCount = 0;
int repeatCount = 0;
for (; xy < xymax; ++xy) {
// determine repeat count
byte v = data[xy];
for (repeatCount = 0; xy < xymax && repeatCount < 255; ++xy, ++repeatCount) {
if (data[xy] != v) {
break;
}
}
xy -= repeatCount;
if (repeatCount < 3) {
literalCount++;
if (literalCount == 254) {
out.write(0);
out.write(literalCount); // Literal OP-code
out.write(data, xy - literalCount + 1, literalCount);
literalCount = 0;
}
} else {
if (literalCount > 0) {
if (literalCount < 3) {
for (; literalCount > 0; --literalCount) {
out.write(1); // Repeat OP-code
out.write(data[xy - literalCount]);
}
} else {
out.write(0);
out.write(literalCount); // Literal OP-code
out.write(data, xy - literalCount, literalCount);
if (literalCount % 2 == 1) {
out.write(0); // pad byte
}
literalCount = 0;
}
}
out.write(repeatCount); // Repeat OP-code
out.write(v);
xy += repeatCount - 1;
}
}
// flush literal run
if (literalCount > 0) {
if (literalCount < 3) {
for (; literalCount > 0; --literalCount) {
out.write(1); // Repeat OP-code
out.write(data[xy - literalCount]);
}
} else {
out.write(0);
out.write(literalCount);
out.write(data, xy - literalCount, literalCount);
if (literalCount % 2 == 1) {
out.write(0); // pad byte
}
}
literalCount = 0;
}
out.write(0);
out.write(0x0000);// End of line
}
out.write(0);
out.write(0x0001);// End of bitmap
}
/** Encodes an 8-bit key frame.
*
* @param out The output stream.
* @param data The image data.
* @param offset The offset to the first pixel in the data array.
* @param width The width of the image in data elements.
* @param scanlineStride The number to append to offset to get to the next scanline.
*/
public void writeDelta8(OutputStream out, byte[] data, byte[] prev, int width, int height, int offset, int scanlineStride) throws IOException {
ByteArrayImageOutputStream buf = new ByteArrayImageOutputStream(data.length);
writeDelta8(buf, data, prev, width, height, offset, scanlineStride);
buf.toOutputStream(out);
}
/** Encodes an 8-bit delta frame.
*
* @param out The output stream.
* @param data The image data.
* @param prev The image data of the previous frame.
* @param offset The offset to the first pixel in the data array.
* @param width The width of the image in data elements.
* @param scanlineStride The number to append to offset to get to the next scanline.
*/
public void writeDelta8(ImageOutputStream out, byte[] data, byte[] prev, int width, int height, int offset, int scanlineStride)
throws IOException {
out.setByteOrder(ByteOrder.LITTLE_ENDIAN);
int ymax = offset + height * scanlineStride;
int upsideDown = ymax - scanlineStride + offset;
// Encode each scanline
int verticalOffset = 0;
for (int y = offset; y < ymax; y += scanlineStride) {
int xy = upsideDown - y;
int xymax = xy + width;
// determine skip count
int skipCount = 0;
for (; xy < xymax; ++xy, ++skipCount) {
if (data[xy] != prev[xy]) {
break;
}
}
if (skipCount == width) {
// => the entire line can be skipped
++verticalOffset;
continue;
}
while (verticalOffset > 0 || skipCount > 0) {
if (verticalOffset == 1 && skipCount == 0) {
out.write(0x00);
out.write(0x00); // End of line OP-code
verticalOffset = 0;
} else {
out.write(0x00);
out.write(0x02); // Skip OP-code
out.write(min(255, skipCount)); // horizontal offset
out.write(min(255, verticalOffset)); // vertical offset
skipCount -= min(255, skipCount);
verticalOffset -= min(255, verticalOffset);
}
}
int literalCount = 0;
int repeatCount = 0;
for (; xy < xymax; ++xy) {
// determine skip count
for (skipCount = 0; xy < xymax; ++xy, ++skipCount) {
if (data[xy] != prev[xy]) {
break;
}
}
xy -= skipCount;
// determine repeat count
byte v = data[xy];
for (repeatCount = 0; xy < xymax && repeatCount < 255; ++xy, ++repeatCount) {
if (data[xy] != v) {
break;
}
}
xy -= repeatCount;
if (skipCount < 4 && xy + skipCount < xymax && repeatCount < 3) {
literalCount++;
} else {
while (literalCount > 0) {
if (literalCount < 3) {
out.write(1); // Repeat OP-code
out.write(data[xy - literalCount]);
literalCount--;
} else {
int literalRun = min(254, literalCount);
out.write(0);
out.write(literalRun); // Literal OP-code
out.write(data, xy - literalCount, literalRun);
if (literalRun % 2 == 1) {
out.write(0); // pad byte
}
literalCount -= literalRun;
}
}
if (xy + skipCount == xymax) {
// => we can skip until the end of the line without
// having to write an op-code
xy += skipCount - 1;
} else if (skipCount >= repeatCount) {
while (skipCount > 0) {
out.write(0);
out.write(0x0002); // Skip OP-code
out.write(min(255, skipCount));
out.write(0);
xy += min(255, skipCount);
skipCount -= min(255, skipCount);
}
xy -= 1;
} else {
out.write(repeatCount); // Repeat OP-code
out.write(v);
xy += repeatCount - 1;
}
}
}
// flush literal run
while (literalCount > 0) {
if (literalCount < 3) {
out.write(1); // Repeat OP-code
out.write(data[xy - literalCount]);
literalCount--;
} else {
int literalRun = min(254, literalCount);
out.write(0);
out.write(literalRun); // Literal OP-code
out.write(data, xy - literalCount, literalRun);
if (literalRun % 2 == 1) {
out.write(0); // pad byte
}
literalCount -= literalRun;
}
}
out.write(0);
out.write(0x0000); // End of line OP-code
}
out.write(0);
out.write(0x0001);// End of bitmap
}
}