Debian Codegraph @

src/uk/me/parabola/imgfmt/app/dem/DEMTile.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2017.
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 3 or
6 * version 2 as published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * General Public License for more details.
12 */
13 package uk.me.parabola.imgfmt.app.dem;
14
15 import java.io.ByteArrayOutputStream;
16
17 import uk.me.parabola.imgfmt.MapFailedException;
18 import uk.me.parabola.imgfmt.app.ImgFileWriter;
19 import uk.me.parabola.mkgmap.reader.hgt.HGTReader;
20
21 /**
22 * This keeps the bit stream data and header info for a single DEM tile.
23 * A tile contains the height values for a number of points organised in a width * height matrix.
24 * The values of the matrix are not stored directly. Instead, a compression algorithm is used to reduce
25 * the size of the needed bit stream. The algorithm uses different methods, mainly a delta encoding, run length encoding
26 * and a variable number of bits and encoding methods to store the actual value.
27 * The actually used methods are not stored, instead they are predicted from previously stored values (if any) and header data.
28 * Both the encoder and decoder have to implement exactly the same prediction algorithm.
29 * As of 2017-12-13 only a subset of the algorithms used by Garmin is understood, but it seems to be enough to store valid data.
30 *
31 * This code is based on the program and documentation created by Frank Stinner.
32 *
33 * @author Gerd Petermann
34 *
35 */
36 public class DEMTile {
37 private ByteArrayOutputStream bits;
38 private int[] heights;
39 private final int height;
40 private final int width;
41 private int offset; // offset from section.dataOffset2
42 private final int baseHeight; // base or minimum height in this tile
43 private final int maxDeltaHeight; // delta between max height and base height
44 private final int encodingType; // determines how the highest values are displayed
45 private final boolean hasData; // not all voids
46
47 private int bitPos;
48 private byte currByte;
49 private int currPlateauTablePos; // current position in plateau tables
50 private CalcType currCalcType;
51
52 private final static boolean DEBUG = false;
53 private StringBuilder bs;
54
55
56 // fields used for debugging
57 private final int tileNumberLat;
58 private final int tileNumberLon;
59
60 private enum EncType {
61 HYBRID, LEN
62 }
63
64 private enum WrapType {
65 WRAP_0, WRAP_1, WRAP_2
66 }
67
68 private enum CalcType {
69 CALC_P_LEN, CALC_STD, CALC_PLATEAU_ZERO, CALC_PLATEAU_NON_ZERO
70 }
71
72 static final int[] plateauUnit = { 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 8, 8, 8, 8, 16, 16, 32, 32, 64, 64, 128 };
73 static final int[] plateauBinBits = { 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6, 6, 7, 8 };
74
75 public DEMTile (int col, int row, int width, int height, short[] realHeights) {
76 this.width = width;
77 this.height = height;
78 this.tileNumberLon = col;
79 this.tileNumberLat = row;
80
81 // check values in matrix
82 int min = Integer.MAX_VALUE;
83 int max = Integer.MIN_VALUE;
84 int countInvalid = 0;
85 for (int h : realHeights) {
86 if (h == HGTReader.UNDEF)
87 ++countInvalid;
88 else {
89 if (h > max)
90 max = h;
91 if (h < min)
92 min = h;
93 }
94 }
95 if (min == Integer.MAX_VALUE) {
96 // all values are invalid
97 hasData = false;
98 encodingType = 2;
99 min = 0;
100 max = 0;
101 } else if (countInvalid > 0) {
102 // some values are invalid
103 hasData = true;
104 encodingType = 2; // don't display highest value
105 max++;
106 } else {
107 // all height values are valid
108 hasData = true;
109 encodingType = 0;
110 }
111
112 this.baseHeight = min;
113 this.maxDeltaHeight = max - min;
114 if (min == max) {
115 return; // all heights equal
116 }
117 createBitStream(realHeights);
118 }
119
120 public boolean hasValidHeights() {
121 return hasData;
122 }
123
124 public int getBaseHeight() {
125 return baseHeight;
126 }
127
128 public int getMaxHeight() {
129 return baseHeight + maxDeltaHeight - (encodingType == 0 ? 0 : 1);
130 }
131
132 private void createBitStream(short[] realHeights) {
133 bits = new ByteArrayOutputStream(1024);
134 heights = new int[realHeights.length];
135 // normalise the height matrix
136 for (int i = 0; i < realHeights.length; i++) {
137 if (realHeights[i] == HGTReader.UNDEF)
138 heights[i] = maxDeltaHeight;
139 else
140 heights[i] = (realHeights[i] - baseHeight);
141 }
142 // all values in heights are now expected to be between 0 .. maxDeltaHeight
143 if (DEBUG) {
144 bs = new StringBuilder();
145 }
146 encodeDeltas();
147 // cleanup
148 bs = null;
149 heights = null;
150 }
151
152 private void addBit(boolean bit) {
153 if (DEBUG) {
154 bs.append(bit ? '1':'0');
155 }
156 if (bit) {
157 currByte |= 1 << (7-bitPos);
158 }
159 bitPos++;
160 if (bitPos > 7) {
161 bitPos = 0;
162 bits.write(currByte);
163 currByte = 0;
164 }
165 }
166
167 /**
168 * The main loop to calculate the bit stream data.
169 */
170 private void encodeDeltas() {
171 int pos = 0;
172 currCalcType = null;
173 ValPredicter encStandard = new ValPredicter(CalcType.CALC_STD, maxDeltaHeight);
174 ValPredicter encPlateauF0 = new ValPredicter(CalcType.CALC_PLATEAU_ZERO, maxDeltaHeight);
175 ValPredicter encPlateauF1 = new ValPredicter(CalcType.CALC_PLATEAU_NON_ZERO, maxDeltaHeight);
176 ValPredicter encoder = null;
177 boolean writeFollower = false;
178 while (pos < heights.length) {
179 if (DEBUG) {
180 bs.setLength(0);
181 }
182 int n = pos % width;
183 int m = pos / width;
184 int hUpper = getHeight(n, m - 1);
185 int hLeft = getHeight(n - 1, m);
186 int dDiff = hUpper - hLeft;
187 if (writeFollower) {
188 encoder = (dDiff == 0) ? encPlateauF0 : encPlateauF1;
189 writeFollower = false;
190 } else if (dDiff == 0) {
191 currCalcType = CalcType.CALC_P_LEN;
192 int pLen = calcPlateauLen(n, m);
193 writePlateauLen(pLen, n);
194 pos += pLen;
195 writeFollower = (pos % width != 0 || pLen == 0);
196 continue;
197 } else {
198 encoder = encStandard;
199 }
200 currCalcType = encoder.type;
201 encoder.setDDiff(dDiff);
202 int v;
203 int h = getHeight(n, m);
204 if (currCalcType == CalcType.CALC_STD) {
205 int predict;
206 int hUpLeft = getHeight(n-1, m-1);
207 int hdiffUp = hUpper- hUpLeft;
208 if (hdiffUp >= maxDeltaHeight - hLeft) {
209 predict = -1;
210 } else if (hdiffUp <= -hLeft) {
211 predict = 0;
212 } else {
213 predict = hLeft + hdiffUp;
214 }
215 if (dDiff > 0)
216 v = -h + predict;
217 else
218 v = h -predict;
219
220 } else {
221 // plateau follower: predicted value is upper height
222 v = h - hUpper;
223 }
224 if (DEBUG) {
225 bs.setLength(0);
226 }
227 encoder.write(v);
228 pos++;
229 }
230 if (bitPos > 0)
231 bits.write(currByte);
232 }
233
234 /**
235 * Add the bits for a given plateau length using the current value of lastTablePos
236 * @param pLen
237 */
238 private void writePlateauLen(int pLen, int col) {
239 int len = pLen;
240 int x = col;
241
242 if (col + len >= width) {
243 // this is not really needed but sometimes produces fewer bits
244 // compared to the loop in the else branch
245 while (x < width) {
246 int unit = plateauUnit[currPlateauTablePos++];
247 len -= unit;
248 x += unit;
249 addBit(true);
250 }
251 if (x != width) {
252 currPlateauTablePos--;
253 }
254 } else {
255 while (true) {
256 int unit = plateauUnit[currPlateauTablePos];
257 if (len < unit)
258 break;
259 currPlateauTablePos++;
260 len -= unit;
261 addBit(true);
262 x += unit;
263 if (x > width)
264 currPlateauTablePos--;
265 if (x >= width) {
266 return;
267 }
268 }
269 if (currPlateauTablePos > 0)
270 currPlateauTablePos--;
271
272 addBit(false); // separator bit
273 int binBits = plateauBinBits[currPlateauTablePos];
274 if (binBits > 0) {
275 writeValAsBin(Math.abs(len), binBits);
276 }
277 }
278
279 }
280
281 /**
282 * Write an unsigned binary value with the given number of bits, MSB first.
283 * @param val
284 * @param numBits
285 */
286 private void writeValAsBin(int val, int numBits) {
287 if (numBits == 0 && val == 0)
288 return;
289
290 int t = 1 << (numBits - 1);
291 if (val >= t << 1)
292 throw new MapFailedException("Number too big for binary encoding with " + numBits + " bits:" + val);
293 while (t > 0) {
294 addBit((val & t) != 0);
295 t >>= 1;
296 }
297 }
298
299 /**
300 * Write a length encoded value as a sequence of 0-bits followed by a 1-bit.
301 * @param val
302 */
303 private void writeNumberOfZeroBits(int val) {
304 for (int i = 0; i < val; i++)
305 addBit(false);
306 addBit(true); // terminating 1-bit
307 }
308
309 /**
310 * Write an unsigned binary value with the given number of bits, MSB first.
311 * @param val
312 * @param hunit
313 * @param maxZeroBits
314 * @return
315 */
316 private boolean writeValHybrid(int val, int hunit, int maxZeroBits) {
317 assert hunit > 0;
318 assert Integer.bitCount(hunit) == 1;
319 int numBits = Integer.numberOfTrailingZeros(hunit);
320 int binPart;
321 int lenPart;
322 if (val > 0) {
323 binPart = (val - 1) % hunit;
324 lenPart = (val - 1 - binPart) / hunit;
325 } else {
326 binPart = -val % hunit;
327 lenPart = (-val - binPart) / hunit;
328 }
329 if (lenPart <= maxZeroBits) {
330 writeNumberOfZeroBits(lenPart); // write length encoded part
331 writeValAsBin(binPart, numBits); // write binary encoded part
332 addBit(val > 0); // sign bit, 1 means positive
333 return true;
334 }
335 return false;
336 }
337
338 /**
339 * Write a signed binary value with the given number of bits, MSB first, sign bit last
340 * @param val
341 * @param numZeroBits number of zero bits that is considered valid
342 */
343 private void writeValBigBin (int val, int numZeroBits) {
344 // signal big bin by writing an invalid number of zero bits
345 writeNumberOfZeroBits(numZeroBits + 1);
346 int bits = getBigBinBits(maxDeltaHeight);
347 if (val < 0)
348 writeValAsBin(-val - 1, bits - 1);
349 else
350 writeValAsBin(val - 1, bits - 1);
351 addBit(val <= 0); // sign bit, 0 means positive
352 }
353
354 /**
355 * A plateau is a sequence of equal delta values. Calculate the length.
356 * @param col current column
357 * @param row current row
358 * @return the length of the plateau, which might be zero.
359 */
360 private int calcPlateauLen(int col, int row) {
361 int len = 0;
362 int v = getHeight(col-1, row);
363 while (col + len < width) {
364 if (v == getHeight(col + len, row)) {
365 ++len;
366 } else
367 break;
368
369 }
370 return len;
371 }
372
373 private int getHeight(int col, int row) {
374 if (heights == null)
375 return 0;
376 if (row < 0) {
377 // virtual 1st row
378 return 0;
379 }
380 if (col < 0) {
381 return row == 0 ? 0 : heights[(row - 1) * width];
382 }
383 return heights[col + row * width];
384 }
385
386 /**
387 * Write tile header with the given field sizes
388 * @param writer
389 * @param recordDesc gives the field sizes
390 */
391 public void writeHeader(ImgFileWriter writer, int recordDesc) {
392 if (maxDeltaHeight == 0)
393 offset = 0;
394 int offsetSize = (recordDesc & 0x3) + 1;
395 int baseSize = ((recordDesc & 0x4) >> 2) + 1;
396 int deltaSize = ((recordDesc & 0x8) >> 3) + 1;
397 boolean hasExtra = (recordDesc & 0x10) != 0;
398 writer.putNu(offsetSize, offset);
399 if (baseSize == 1)
400 writer.put1s(baseHeight);
401 else
402 writer.put2s(baseHeight);
403 writer.putNu(deltaSize, maxDeltaHeight);
404 if (hasExtra)
405 writer.put1u(encodingType);
406 }
407
408 public void writeBitStreamData(ImgFileWriter writer) {
409 if (bits != null) {
410 writer.put(bits.toByteArray());
411 }
412 }
413
414 private static int evaluateData(int oldsum, int elemcount, int newdata, int region) {
415 switch (region) {
416 case 0:
417 return -1 - oldsum - elemcount;
418 case 1:
419 return 2 * (newdata + elemcount) + 3;
420 case 2:
421 return 2 * newdata - 1;
422 case 3:
423 return 2 * (newdata - elemcount) - 5;
424 default:
425 return 1 - oldsum + elemcount;
426 }
427 }
428
429 private static int getEvaluateDataRegion(int oldsum, int elemcount, int newdata) {
430 if (elemcount < 63) {
431 if (newdata < -2 - ((oldsum + 3 * elemcount) >> 1)) {
432 return 0;
433 } else if (newdata < -((oldsum + elemcount) >> 1)) {
434 return 1;
435 } else if (newdata < 2 - ((oldsum - elemcount) >> 1)) {
436 return 2;
437 } else if (newdata < 4 - ((oldsum - 3 * elemcount) >> 1)) {
438 return 3;
439 } else {
440 return 4;
441 }
442 } else {
443 if (newdata < -2 - ((oldsum + 3 * elemcount) >> 1)) {
444 return 0;
445 } else if (newdata < -((oldsum + elemcount) >> 1) - 1) {
446 // special case in if !
447 return 1;
448 } else if (newdata < 2 - ((oldsum - elemcount) >> 1)) {
449 return 2;
450 } else if (newdata < 4 - ((oldsum - 3 * elemcount) >> 1)) {
451 return 3;
452 } else {
453 return 4;
454 }
455 }
456 }
457
458 /**
459 * This class keeps statistics about the previously encoded values and tries to predict the next value.
460 * It also calculates the encoding method to use.
461 * Based on findings of Frank Stinner.
462 */
463 private class ValPredicter {
464 private EncType encType;
465 private WrapType wrapType;
466 private int sumH;
467 private int sumL;
468 private int elemCount;
469 private int hunit;
470 private final CalcType type;
471 private final int unitDelta;
472 private int dDiff;
473 private final int maxZeroBits;
474 final int l0WrapUp, l0WrapDown, l1WrapUp, l1WrapDown, l2WrapUp, l2WrapDown,hWrapUp, hWrapDown;
475
476 public ValPredicter(CalcType type, int maxHeight) {
477 super();
478 this.type = type;
479 int numZeroBits = getMaxLengthZeroBits(maxHeight);
480 if (type == CalcType.CALC_PLATEAU_NON_ZERO || type == CalcType.CALC_PLATEAU_ZERO)
481 --numZeroBits;
482 maxZeroBits = numZeroBits;
483
484 unitDelta = Math.max(0, maxHeight - 0x5f) / 0x40; // TODO what does it mean?
485 encType = EncType.HYBRID;
486 wrapType = WrapType.WRAP_0;
487 hunit = getStartHUnit(maxHeight);
488
489 // calculate threshold values for wrapping
490 if (maxHeight % 2 == 0) {
491 l0WrapDown = maxHeight / 2;
492 l0WrapUp = -maxHeight / 2;
493 l1WrapDown = (maxHeight + 2) / 2;
494 l1WrapUp = -maxHeight / 2;
495 l2WrapDown = maxHeight / 2;
496 l2WrapUp = -maxHeight / 2;
497 } else {
498 l0WrapDown = (maxHeight + 1) / 2;
499 l0WrapUp = -(maxHeight - 1) / 2;
500 l1WrapDown = (maxHeight + 1) / 2;
501 l1WrapUp = -(maxHeight - 1) / 2;
502 l2WrapDown = (maxHeight - 1) / 2;
503 l2WrapUp = -(maxHeight + 1) / 2;
504 }
505
506 hWrapDown = (maxHeight + 1) / 2;
507 hWrapUp = -(maxHeight - 1) / 2;
508 }
509
510 /**
511 * This
512 * @param data
513 * @return
514 */
515 private int wrap(int data) {
516 int v = data;
517 int down,up;
518 if (encType == EncType.HYBRID) {
519 down = hWrapDown;
520 up = hWrapUp;
521 } else {
522 if (wrapType == WrapType.WRAP_0) {
523 down = l0WrapDown;
524 up = l0WrapUp;
525 } else if (wrapType == WrapType.WRAP_1) {
526 down = l1WrapDown;
527 up = l1WrapUp;
528 } else {
529 down = l2WrapDown;
530 up = l2WrapUp;
531 }
532 }
533
534 if (v > down)
535 v = v - (maxDeltaHeight + 1);
536 if (v < up)
537 v = v + maxDeltaHeight + 1;
538 return v;
539 }
540
541 public void write(int val) {
542
543 int wrapped = wrap(val);
544 int delta1 = wrapped;
545 if (type == CalcType.CALC_PLATEAU_ZERO) {
546 if (delta1 <= 0)
547 delta1++;
548 } else if (type == CalcType.CALC_PLATEAU_NON_ZERO) {
549 if (dDiff > 0) {
550 delta1 = -delta1;
551 }
552 }
553 int delta2;
554 if (wrapType == WrapType.WRAP_0)
555 delta2 = delta1;
556 else if (wrapType == WrapType.WRAP_1)
557 delta2 = 1 - delta1;
558 else delta2 = -delta1;
559 boolean written = false;
560 if (encType == EncType.HYBRID) {
561 written = writeValHybrid(delta2, hunit, getCurrentMaxZeroBits());
562 } else {
563 // EncType.LEN
564 // 2 * Math.Abs(data) - (Math.Sign(data) + 1) / 2
565 int n0;
566 if (delta2 < 0) {
567 n0 = -delta2 * 2;
568 } else if (delta2 > 0){
569 n0 = (delta2 -1) * 2 + 1;
570 } else {
571 n0 = 0;
572 }
573 if (n0 <= getCurrentMaxZeroBits()) {
574 writeNumberOfZeroBits(n0);
575 written = true;
576 }
577 }
578 if (!written)
579 writeValBigBin(delta2, getCurrentMaxZeroBits());
580 processVal(delta1);
581 }
582
583 /**
584 * This looks wrong but seems to be needed. For a plateau follower we reduce the max value.
585 * The effect seems to be that a Big Bin is written although it would fit in the normal number.
586 * Maybe a BigBin signals that a flag should be reset or currPlateauTablePos is too high?
587 * @return number of 0 bits that are considered okay.
588 */
589 int getCurrentMaxZeroBits() {
590 if (currCalcType == CalcType.CALC_PLATEAU_NON_ZERO || currCalcType == CalcType.CALC_PLATEAU_ZERO)
591 return maxZeroBits - plateauBinBits[currPlateauTablePos];
592 return maxZeroBits;
593 }
594
595 private void processVal(int delta1) {
596 if (type == CalcType.CALC_STD) {
597 // calculate threshold sum hybrid
598 sumH += delta1 > 0 ? delta1 : -delta1;
599 if (sumH + unitDelta + 1 >= 0xffff)
600 sumH -= 0x10000;
601
602 // calculate threshold sum for length encoding
603 int evalRegion = -1;
604 int workData = delta1;
605 if (elemCount == 63) {
606 evalRegion = getEvaluateDataRegion(sumL, elemCount, delta1);
607 boolean datagerade = delta1 % 2 == 0;
608 boolean sumL1 = (sumL - 1) % 4 == 0;
609
610 switch (evalRegion) {
611 case 0:
612 case 2:
613 case 4:
614 if ((sumL1 && !datagerade) || (!sumL1 && datagerade)) {
615 workData++;
616 }
617 break;
618 case 1:
619 workData++;
620 if ((sumL1 && !datagerade) || (!sumL1 && datagerade)) {
621 workData++;
622 }
623 break;
624 case 3:
625 if ((sumL1 && datagerade) || (!sumL1 && !datagerade)) {
626 workData--;
627 }
628 break;
629 }
630 }
631 if (evalRegion < 0)
632 evalRegion = getEvaluateDataRegion(sumL, elemCount, workData);
633 int eval = evaluateData(sumL, elemCount, workData, evalRegion);
634 sumL += eval;
635
636 // now update elem counter
637 elemCount++;
638
639 if (elemCount == 64) {
640 elemCount = 32;
641 sumH = ((sumH - unitDelta) >> 1) - 1;
642
643 sumL /= 2;
644 }
645
646 // calculate new hunit
647 hunit = normalizeHUnit((unitDelta + sumH + 1) / (elemCount + 1));
648
649 // finally determine encode type for next value
650 wrapType = WrapType.WRAP_0;
651 if (hunit > 0) {
652 encType = EncType.HYBRID;
653 } else {
654 encType = EncType.LEN;
655 if (sumL > 0)
656 wrapType = WrapType.WRAP_1;
657 }
658 } else if (type == CalcType.CALC_PLATEAU_ZERO) {
659 // calculate threshold sum hybrid
660 sumH += delta1 > 0 ? delta1 : 1 - delta1; // different to standard
661 if (sumH + unitDelta + 1 >= 0xffff)
662 sumH -= 0x10000;
663
664 // calculate threshold sum for length encoding
665 sumL += delta1 <= 0 ? -1 : 1;
666 elemCount++;
667
668 if (elemCount == 64) {
669 elemCount = 32;
670 sumH = ((sumH - unitDelta) >> 1) - 1;
671 sumL /= 2;
672 if (sumL % 2 != 0) {
673 sumL++;
674 }
675 }
676
677 // calculate new hunit
678 hunit = normalizeHUnit((unitDelta + sumH + 1 - elemCount / 2) / (elemCount + 1));
679 // finally determine encode type for next value
680 wrapType = WrapType.WRAP_0;
681 if (hunit > 0) {
682 encType = EncType.HYBRID;
683 } else {
684 encType = EncType.LEN;
685 if (sumL >= 0)
686 wrapType = WrapType.WRAP_1;
687 }
688 } else {
689 assert type == CalcType.CALC_PLATEAU_NON_ZERO;
690 // calculate threshold sum hybrid
691 sumH += delta1 < 0 ? -delta1 : delta1; // simple absolute sum
692 if (sumH + unitDelta + 1 >= 0xffff)
693 sumH -= 0x10000;
694
695 // calculate threshold sum for length encoding
696 sumL += delta1 <= 0 ? -1 : 1;
697 elemCount++;
698
699 if (elemCount == 64) {
700 elemCount = 32;
701 sumH = ((sumH - unitDelta) >> 1) - 1;
702 sumL /= 2;
703 if (sumL % 2 != 0) {
704 sumL--; // different to CALC_PLATEAU_ZERO !
705 }
706 }
707
708 // calculate new hunit
709 hunit = normalizeHUnit((unitDelta + sumH + 1) / (elemCount + 1));
710 // finally determine encode type for next value
711 wrapType = WrapType.WRAP_0;
712 if (hunit > 0) {
713 encType = EncType.HYBRID;
714 } else {
715 encType = EncType.LEN;
716 if (sumL <= 0)
717 wrapType = WrapType.WRAP_2;
718 }
719 }
720 }
721
722 public void setDDiff(int dDiff) {
723 this.dDiff = dDiff;
724 }
725 }
726
727 /**
728 * Calculate the longest sequence of zero bits that is considered as a valid number.
729 * The number depends on the field maxDeltaHeight in the header structure.
730 * @param maxHeight
731 * @return the number of bits
732 */
733 private static int getMaxLengthZeroBits(int maxHeight) {
734 if (maxHeight < 2)
735 return 15;
736 if (maxHeight < 4)
737 return 16;
738 if (maxHeight < 8)
739 return 17;
740 if (maxHeight < 16)
741 return 18;
742 if (maxHeight < 32)
743 return 19;
744 if (maxHeight < 64)
745 return 20;
746 if (maxHeight < 128)
747 return 21;
748 if (maxHeight < 256)
749 return 22;
750 if (maxHeight < 512)
751 return 25;
752 if (maxHeight < 1024)
753 return 28;
754 if (maxHeight < 2048)
755 return 31;
756 if (maxHeight < 4096)
757 return 34;
758 if (maxHeight < 8192)
759 return 37;
760 if (maxHeight < 16384)
761 return 40;
762 return 43;
763 }
764
765 /**
766 * Calculate the start hunit value.
767 * The number depends on the field maxDeltaHeight in the header structure.
768 * @param maxHeight
769 * @return the hunit value
770 */
771 private static int getStartHUnit(int maxHeight) {
772 if (maxHeight < 0x9f)
773 return 1;
774 else if (maxHeight < 0x11f)
775 return 2;
776 else if (maxHeight < 0x21f)
777 return 4;
778 else if (maxHeight < 0x41f)
779 return 8;
780 else if (maxHeight < 0x81f)
781 return 16;
782 else if (maxHeight < 0x101f)
783 return 32;
784 else if (maxHeight < 0x201f)
785 return 64;
786 else if (maxHeight < 0x401f)
787 return 128;
788 return 256;
789 }
790
791 static int getBigBinBits(int maxHeight) {
792 int bits;
793 if (maxHeight <16384) {
794 int n = Integer.highestOneBit(maxHeight);
795 bits = Integer.numberOfTrailingZeros(n) + 1;
796 } else
797 bits = 15;
798 return bits;
799 // if (maxHeight < 2)
800 // return 1;
801 // else if (maxHeight < 4)
802 // return 2;
803 // else if (maxHeight < 8)
804 // return 3;
805 // else if (maxHeight < 16)
806 // return 4;
807 // else if (maxHeight < 32)
808 // return 5;
809 // else if (maxHeight < 64)
810 // return 6;
811 // else if (maxHeight < 128)
812 // return 7;
813 // else if (maxHeight < 256)
814 // return 8;
815 // else if (maxHeight < 512)
816 // return 9;
817 // else if (maxHeight < 1024)
818 // return 10;
819 // else if (maxHeight < 2048)
820 // return 11;
821 // else if (maxHeight < 4096)
822 // return 12;
823 // else if (maxHeight < 8192)
824 // return 13;
825 // else if (maxHeight < 16384)
826 // return 14;
827 // else
828 // return 15;
829 }
830
831 /**
832 * The hunit value must be a positive multiple of 2 (including 0).
833 * @param hu the result of a division to calculate the new hunit
834 * @return the normalised value
835 */
836 private static int normalizeHUnit(int hu) {
837 if (hu > 0) {
838 return Integer.highestOneBit(hu);
839 }
840 return 0;
841 }
842
843 public int getBitStreamLen() {
844 if (bits == null)
845 return 0;
846 else
847 return bits.size();
848 }
849
850 public void setOffset(int off) {
851 this.offset = off;
852 }
853
854 @Override
855 public String toString() {
856 return tileNumberLat + " " + tileNumberLon + " w=" + width + " h=" + height;
857 }
858
859 public int getMaxDeltaHeight() {
860 return maxDeltaHeight;
861 }
862
863 public int getEncodingType() {
864 return encodingType;
865 }
866
867 public byte[] getBitStream() {
868 return bits.toByteArray();
869 }
870 }