Check-in [e37ff9dab2]
Not logged in

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:update openjpeg to version 2.4.0
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: e37ff9dab2b47bfc3151cc43b25451427588a151
User & Date: chw 2022-04-24 13:43:23.567
Context
2022-04-24
13:56
various fixes in build and configure scripts check-in: 1b5345fc88 user: chw tags: trunk
13:43
update openjpeg to version 2.4.0 check-in: e37ff9dab2 user: chw tags: trunk
2022-04-23
14:00
add new "const" minor command to topcua check-in: 0d5a5293f2 user: chw tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
Changes to jni/openjpeg/CHANGELOG.md.
1
2























































































3
4
5
6
7
8
9
# Changelog
























































































## [v2.3.1](https://github.com/uclouvain/openjpeg/releases/v2.3.1) (2019-04-02)
[Full Changelog](https://github.com/uclouvain/openjpeg/compare/v2.3.0...v2.3.1)

**Closed issues:**

- v2.2.0 regression for decoding images where TNsot == 0 [\#1120](https://github.com/uclouvain/openjpeg/issues/1120)
- Int overflow in jp3d [\#1162](https://github.com/uclouvain/openjpeg/issues/1162)


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
# Changelog

## [v2.4.0](https://github.com/uclouvain/openjpeg/releases/v2.4.0) (2020-12-28)

[Full Changelog](https://github.com/uclouvain/openjpeg/compare/v2.3.1...v2.4.0)

**Closed issues:**

- OPENJPEG\_INSTALL\_DOC\_DIR does not control a destination directory where HTML docs would be installed. [\#1309](https://github.com/uclouvain/openjpeg/issues/1309)
- Heap-buffer-overflow in lib/openjp2/pi.c:312 [\#1302](https://github.com/uclouvain/openjpeg/issues/1302)
- Heap-buffer-overflow in lib/openjp2/t2.c:973 [\#1299](https://github.com/uclouvain/openjpeg/issues/1299)
- Heap-buffer-overflow in lib/openjp2/pi.c:623 [\#1293](https://github.com/uclouvain/openjpeg/issues/1293)
- Global-buffer-overflow in lib/openjp2/dwt.c:1980 [\#1286](https://github.com/uclouvain/openjpeg/issues/1286)
- Heap-buffer-overflow in lib/openjp2/tcd.c:2417 [\#1284](https://github.com/uclouvain/openjpeg/issues/1284)
- Heap-buffer-overflow in lib/openjp2/mqc.c:499 [\#1283](https://github.com/uclouvain/openjpeg/issues/1283)
- Openjpeg could not encode 32bit RGB float image [\#1281](https://github.com/uclouvain/openjpeg/issues/1281)
- Openjpeg could not encode 32bit RGB float image [\#1280](https://github.com/uclouvain/openjpeg/issues/1280)
- ISO/IEC 15444-1:2019 \(E\) compared with 'cio.h' [\#1277](https://github.com/uclouvain/openjpeg/issues/1277)
- Test-suite failure due to hash mismatch [\#1264](https://github.com/uclouvain/openjpeg/issues/1264)
- Heap use-after-free [\#1261](https://github.com/uclouvain/openjpeg/issues/1261)
- Memory leak when failing to allocate object... [\#1259](https://github.com/uclouvain/openjpeg/issues/1259)
- Memory leak of Tier 1 handle when OpenJPEG fails to set it as TLS... [\#1257](https://github.com/uclouvain/openjpeg/issues/1257)
- Any plan to build release for CVE-2020-8112/CVE-2020-6851 [\#1247](https://github.com/uclouvain/openjpeg/issues/1247)
- failing to convert 16-bit file: opj\_t2\_encode\_packet\(\): only 5251 bytes remaining in output buffer. 5621 needed. [\#1243](https://github.com/uclouvain/openjpeg/issues/1243)
- CMake+VS2017 Compile OK, thirdparty Compile OK, but thirdparty not install [\#1239](https://github.com/uclouvain/openjpeg/issues/1239)
- New release to solve CVE-2019-6988 ? [\#1238](https://github.com/uclouvain/openjpeg/issues/1238)
- Many tests fail to pass after the update of libtiff to version 4.1.0 [\#1233](https://github.com/uclouvain/openjpeg/issues/1233)
- Another heap buffer overflow in libopenjp2 [\#1231](https://github.com/uclouvain/openjpeg/issues/1231)
- Heap buffer overflow in libopenjp2 [\#1228](https://github.com/uclouvain/openjpeg/issues/1228)
- Endianness of binary volume \(JP3D\) [\#1224](https://github.com/uclouvain/openjpeg/issues/1224)
- New release to resolve CVE-2019-12973 [\#1222](https://github.com/uclouvain/openjpeg/issues/1222)
- how to set the block size,like 128,256 ? [\#1216](https://github.com/uclouvain/openjpeg/issues/1216)
- compress YUV files to motion jpeg2000 standard [\#1213](https://github.com/uclouvain/openjpeg/issues/1213)
- Repair/update Java wrapper, and include in release [\#1208](https://github.com/uclouvain/openjpeg/issues/1208)
- abc [\#1206](https://github.com/uclouvain/openjpeg/issues/1206)
- Slow decoding [\#1202](https://github.com/uclouvain/openjpeg/issues/1202)
- Installation question [\#1201](https://github.com/uclouvain/openjpeg/issues/1201)
- Typo in test\_decode\_area - \*ptilew is assigned instead of \*ptileh [\#1195](https://github.com/uclouvain/openjpeg/issues/1195)
- Creating a J2K file with one POC is broken [\#1191](https://github.com/uclouvain/openjpeg/issues/1191)
- Make fails on Arch Linux [\#1174](https://github.com/uclouvain/openjpeg/issues/1174)
- Heap buffer overflow in opj\_t1\_clbl\_decode\_processor\(\) triggered with Ghostscript [\#1158](https://github.com/uclouvain/openjpeg/issues/1158)
- opj\_stream\_get\_number\_byte\_left: Assertion `p\_stream-\>m\_byte\_offset \>= 0' failed. [\#1151](https://github.com/uclouvain/openjpeg/issues/1151)
- The fuzzer ignores too many inputs [\#1079](https://github.com/uclouvain/openjpeg/issues/1079)
- out of bounds read [\#1068](https://github.com/uclouvain/openjpeg/issues/1068)

**Merged pull requests:**

- Change defined WIN32 [\#1310](https://github.com/uclouvain/openjpeg/pull/1310) ([Jamaika1](https://github.com/Jamaika1))
- docs: fix simple typo, producted -\> produced [\#1308](https://github.com/uclouvain/openjpeg/pull/1308) ([timgates42](https://github.com/timgates42))
- Set ${OPENJPEG\_INSTALL\_DOC\_DIR} to DESTINATION of HTMLs [\#1307](https://github.com/uclouvain/openjpeg/pull/1307) ([lemniscati](https://github.com/lemniscati))
- Use INC\_DIR for OPENJPEG\_INCLUDE\_DIRS \(fixes uclouvain\#1174\) [\#1306](https://github.com/uclouvain/openjpeg/pull/1306) ([matthew-sharp](https://github.com/matthew-sharp))
- pi.c: avoid out of bounds access with POC \(fixes \#1302\) [\#1304](https://github.com/uclouvain/openjpeg/pull/1304) ([rouault](https://github.com/rouault))
- Encoder: grow again buffer size [\#1303](https://github.com/uclouvain/openjpeg/pull/1303) ([zodf0055980](https://github.com/zodf0055980))
- opj\_j2k\_write\_sod\(\): avoid potential heap buffer overflow \(fixes \#1299\) \(probably master only\) [\#1301](https://github.com/uclouvain/openjpeg/pull/1301) ([rouault](https://github.com/rouault))
- pi.c: avoid out of bounds access with POC \(refs https://github.com/uclouvain/openjpeg/issues/1293\#issuecomment-737122836\) [\#1300](https://github.com/uclouvain/openjpeg/pull/1300) ([rouault](https://github.com/rouault))
- opj\_t2\_encode\_packet\(\): avoid out of bound access of \#1297, but likely not the proper fix [\#1298](https://github.com/uclouvain/openjpeg/pull/1298) ([rouault](https://github.com/rouault))
- opj\_t2\_encode\_packet\(\): avoid out of bound access of \#1294, but likely not the proper fix [\#1296](https://github.com/uclouvain/openjpeg/pull/1296) ([rouault](https://github.com/rouault))
- opj\_j2k\_setup\_encoder\(\): validate POC compno0 and compno1 \(fixes \#1293\) [\#1295](https://github.com/uclouvain/openjpeg/pull/1295) ([rouault](https://github.com/rouault))
- Encoder: avoid global buffer overflow on irreversible conversion when… [\#1292](https://github.com/uclouvain/openjpeg/pull/1292) ([rouault](https://github.com/rouault))
- Decoding: deal with some SPOT6 images that have tiles with a single tile-part with TPsot == 0 and TNsot == 0, and with missing EOC [\#1291](https://github.com/uclouvain/openjpeg/pull/1291) ([rouault](https://github.com/rouault))
- Free p\_tcd\_marker\_info to avoid memory leak [\#1288](https://github.com/uclouvain/openjpeg/pull/1288) ([zodf0055980](https://github.com/zodf0055980))
- Encoder: grow again buffer size [\#1287](https://github.com/uclouvain/openjpeg/pull/1287) ([zodf0055980](https://github.com/zodf0055980))
- Encoder: avoid uint32 overflow when allocating memory for codestream buffer \(fixes \#1243\) [\#1276](https://github.com/uclouvain/openjpeg/pull/1276) ([rouault](https://github.com/rouault))
- Java compatibility from 1.5 to 1.6 [\#1263](https://github.com/uclouvain/openjpeg/pull/1263) ([jiapei100](https://github.com/jiapei100))
- opj\_decompress: fix double-free on input directory with mix of valid and invalid images [\#1262](https://github.com/uclouvain/openjpeg/pull/1262) ([rouault](https://github.com/rouault))
- openjp2: Plug image leak when failing to allocate codestream index. [\#1260](https://github.com/uclouvain/openjpeg/pull/1260) ([sebras](https://github.com/sebras))
- openjp2: Plug memory leak when setting data as TLS fails. [\#1258](https://github.com/uclouvain/openjpeg/pull/1258) ([sebras](https://github.com/sebras))
- openjp2: Error out if failing to create Tier 1 handle. [\#1256](https://github.com/uclouvain/openjpeg/pull/1256) ([sebras](https://github.com/sebras))
- Testing for invalid values of width, height, numcomps [\#1254](https://github.com/uclouvain/openjpeg/pull/1254) ([szukw000](https://github.com/szukw000))
- Single-threaded performance improvements in forward DWT for 5-3 and 9-7 \(and other improvements\) [\#1253](https://github.com/uclouvain/openjpeg/pull/1253) ([rouault](https://github.com/rouault))
- Add support for multithreading in encoder [\#1248](https://github.com/uclouvain/openjpeg/pull/1248) ([rouault](https://github.com/rouault))
- Add support for generation of PLT markers in encoder [\#1246](https://github.com/uclouvain/openjpeg/pull/1246) ([rouault](https://github.com/rouault))
- Fix warnings about signed/unsigned casts in pi.c [\#1244](https://github.com/uclouvain/openjpeg/pull/1244) ([rouault](https://github.com/rouault))
- opj\_decompress: add sanity checks to avoid segfault in case of decoding error [\#1240](https://github.com/uclouvain/openjpeg/pull/1240) ([rouault](https://github.com/rouault))
- ignore wrong icc [\#1236](https://github.com/uclouvain/openjpeg/pull/1236) ([szukw000](https://github.com/szukw000))
- Implement writing of IMF profiles [\#1235](https://github.com/uclouvain/openjpeg/pull/1235) ([rouault](https://github.com/rouault))
- tests: add alternate checksums for libtiff 4.1 [\#1234](https://github.com/uclouvain/openjpeg/pull/1234) ([rouault](https://github.com/rouault))
- opj\_tcd\_init\_tile\(\): avoid integer overflow [\#1232](https://github.com/uclouvain/openjpeg/pull/1232) ([rouault](https://github.com/rouault))
- tests/fuzzers: link fuzz binaries using $LIB\_FUZZING\_ENGINE. [\#1230](https://github.com/uclouvain/openjpeg/pull/1230) ([Dor1s](https://github.com/Dor1s))
- opj\_j2k\_update\_image\_dimensions\(\): reject images whose coordinates are beyond INT\_MAX \(fixes \#1228\) [\#1229](https://github.com/uclouvain/openjpeg/pull/1229) ([rouault](https://github.com/rouault))
- Fix resource leaks [\#1226](https://github.com/uclouvain/openjpeg/pull/1226) ([dodys](https://github.com/dodys))
- abi-check.sh: fix false postive ABI error, and display output error log [\#1218](https://github.com/uclouvain/openjpeg/pull/1218) ([rouault](https://github.com/rouault))
- pi.c: avoid integer overflow, resulting in later invalid access to memory in opj\_t2\_decode\_packets\(\) [\#1217](https://github.com/uclouvain/openjpeg/pull/1217) ([rouault](https://github.com/rouault))
- Add check to validate SGcod/SPcoc/SPcod parameter values. [\#1211](https://github.com/uclouvain/openjpeg/pull/1211) ([sebras](https://github.com/sebras))
- Fix buffer overflow reading an image file less than four characters [\#1196](https://github.com/uclouvain/openjpeg/pull/1196) ([robert-ancell](https://github.com/robert-ancell))
- compression: emit POC marker when only one single POC is requested \(f… [\#1192](https://github.com/uclouvain/openjpeg/pull/1192) ([rouault](https://github.com/rouault))
- Fix several potential vulnerabilities  [\#1185](https://github.com/uclouvain/openjpeg/pull/1185) ([Young-X](https://github.com/Young-X))
- openjp2/j2k: Report error if all wanted components are not decoded. [\#1164](https://github.com/uclouvain/openjpeg/pull/1164) ([sebras](https://github.com/sebras))

## [v2.3.1](https://github.com/uclouvain/openjpeg/releases/v2.3.1) (2019-04-02)
[Full Changelog](https://github.com/uclouvain/openjpeg/compare/v2.3.0...v2.3.1)

**Closed issues:**

- v2.2.0 regression for decoding images where TNsot == 0 [\#1120](https://github.com/uclouvain/openjpeg/issues/1120)
- Int overflow in jp3d [\#1162](https://github.com/uclouvain/openjpeg/issues/1162)
Changes to jni/openjpeg/CMakeLists.txt.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# Do full dependency headers.
include_regular_expression("^.*$")

#-----------------------------------------------------------------------------
# OPENJPEG version number, useful for packaging and doxygen doc:
set(OPENJPEG_VERSION_MAJOR 2)
set(OPENJPEG_VERSION_MINOR 3)
set(OPENJPEG_VERSION_BUILD 1)
set(OPENJPEG_VERSION
  "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")
set(PACKAGE_VERSION
  "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")

# Because autotools does not support X.Y notation for SOVERSION, we have to use
# two numbering, one for the openjpeg version and one for openjpeg soversion







|
|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

# Do full dependency headers.
include_regular_expression("^.*$")

#-----------------------------------------------------------------------------
# OPENJPEG version number, useful for packaging and doxygen doc:
set(OPENJPEG_VERSION_MAJOR 2)
set(OPENJPEG_VERSION_MINOR 4)
set(OPENJPEG_VERSION_BUILD 0)
set(OPENJPEG_VERSION
  "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")
set(PACKAGE_VERSION
  "${OPENJPEG_VERSION_MAJOR}.${OPENJPEG_VERSION_MINOR}.${OPENJPEG_VERSION_BUILD}")

# Because autotools does not support X.Y notation for SOVERSION, we have to use
# two numbering, one for the openjpeg version and one for openjpeg soversion
53
54
55
56
57
58
59

60
61
62
63
64
65
66
#   2.0.1 |  6
#   2.1   |  7
#   2.1.1 |  7
#   2.1.2 |  7
#   2.2.0 |  7
#   2.3.0 |  7
#   2.3.1 |  7

# above is the recommendation by the OPJ team. If you really need to override this default,
# you can specify your own OPENJPEG_SOVERSION at cmake configuration time:
# cmake -DOPENJPEG_SOVERSION:STRING=42 /path/to/openjpeg
if(NOT OPENJPEG_SOVERSION)
  set(OPENJPEG_SOVERSION 7)
endif(NOT OPENJPEG_SOVERSION)
set(OPENJPEG_LIBRARY_PROPERTIES







>







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#   2.0.1 |  6
#   2.1   |  7
#   2.1.1 |  7
#   2.1.2 |  7
#   2.2.0 |  7
#   2.3.0 |  7
#   2.3.1 |  7
#   2.4.0 |  7
# above is the recommendation by the OPJ team. If you really need to override this default,
# you can specify your own OPENJPEG_SOVERSION at cmake configuration time:
# cmake -DOPENJPEG_SOVERSION:STRING=42 /path/to/openjpeg
if(NOT OPENJPEG_SOVERSION)
  set(OPENJPEG_SOVERSION 7)
endif(NOT OPENJPEG_SOVERSION)
set(OPENJPEG_LIBRARY_PROPERTIES
252
253
254
255
256
257
258

259

260
261
262
263
264
265
266
  find_package(Threads REQUIRED)
  if(NOT CMAKE_USE_PTHREADS_INIT)
    message(FATAL_ERROR "Only pthread are supported")
  endif()
endif()
add_subdirectory(src/lib)
option(BUILD_LUTS_GENERATOR "Build utility to generate t1_luts.h" OFF)

option(BUILD_UNIT_TESTS "Build unit tests (bench_dwt, test_sparse_array, etc..)" OFF)


#-----------------------------------------------------------------------------
# Build Applications
option(BUILD_CODEC "Build the CODEC executables" ON)
option(BUILD_MJ2 "Build the MJ2 executables." OFF)
option(BUILD_JPWL "Build the JPWL library and executables" OFF)
option(BUILD_JPIP "Build the JPIP library and executables." OFF)







>

>







253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
  find_package(Threads REQUIRED)
  if(NOT CMAKE_USE_PTHREADS_INIT)
    message(FATAL_ERROR "Only pthread are supported")
  endif()
endif()
add_subdirectory(src/lib)
option(BUILD_LUTS_GENERATOR "Build utility to generate t1_luts.h" OFF)
if(UNIX)
option(BUILD_UNIT_TESTS "Build unit tests (bench_dwt, test_sparse_array, etc..)" OFF)
endif()

#-----------------------------------------------------------------------------
# Build Applications
option(BUILD_CODEC "Build the CODEC executables" ON)
option(BUILD_MJ2 "Build the MJ2 executables." OFF)
option(BUILD_JPWL "Build the JPWL library and executables" OFF)
option(BUILD_JPIP "Build the JPIP library and executables." OFF)
Changes to jni/openjpeg/NEWS.md.
1
2
3
4










5
6
7
8
9
10
11
# OpenJPEG NEWS

More details in the [CHANGELOG](https://github.com/uclouvain/openjpeg/blob/master/CHANGELOG.md)











## OpenJPEG 2.3.1 (April 2019)

No API/ABI break compared to v2.3.0

* Many bug fixes (including security fixes)

## OpenJPEG 2.3.0 (October 2017)




>
>
>
>
>
>
>
>
>
>







1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# OpenJPEG NEWS

More details in the [CHANGELOG](https://github.com/uclouvain/openjpeg/blob/master/CHANGELOG.md)

## OpenJPEG 2.4.0 (December 2021)

No API/ABI break compared to v2.3.1, but additional symbols for subset of components decoding (hence the MINOR version bump).

* Encoder: add support for multithreading [\#1248](https://github.com/uclouvain/openjpeg/pull/1248)
* Encoder: add support for generation of PLT markers [\#1246](https://github.com/uclouvain/openjpeg/pull/1246)
* Encoder: single-threaded performance improvements in forward DWT for 5-3 and 9-7 (and other improvements) [\#1253](https://github.com/uclouvain/openjpeg/pull/1253)
* Encoder: support IMF profiles [\#1235](https://github.com/uclouvain/openjpeg/pull/1235)
* Many bug fixes (including security fixes)

## OpenJPEG 2.3.1 (April 2019)

No API/ABI break compared to v2.3.0

* Many bug fixes (including security fixes)

## OpenJPEG 2.3.0 (October 2017)
Changes to jni/openjpeg/android/opj_config.h.
1
2
3
4
5
6
7
8
9
10
/* create opj_config.h for CMake */
#define OPJ_HAVE_STDINT_H 		1

/*--------------------------------------------------------------------------*/
/* OpenJPEG Versioning                                                      */

/* Version number. */
#define OPJ_VERSION_MAJOR 2
#define OPJ_VERSION_MINOR 3
#define OPJ_VERSION_BUILD 1








|
|
1
2
3
4
5
6
7
8
9
10
/* create opj_config.h for CMake */
#define OPJ_HAVE_STDINT_H 		1

/*--------------------------------------------------------------------------*/
/* OpenJPEG Versioning                                                      */

/* Version number. */
#define OPJ_VERSION_MAJOR 2
#define OPJ_VERSION_MINOR 4
#define OPJ_VERSION_BUILD 0
Changes to jni/openjpeg/android/opj_config_private.h.
1
2
3
4
5
6
7
8
9
10
11
/* create opj_config_private.h for CMake */
#define OPJ_HAVE_INTTYPES_H 	1

#define OPJ_PACKAGE_VERSION "2.3.1"

/* Not used by openjp2*/
/*#define HAVE_MEMORY_H 1*/
/*#define HAVE_STDLIB_H 1*/
/*#define HAVE_STRINGS_H 1*/
/*#define HAVE_STRING_H 1*/
/*#define HAVE_SYS_STAT_H 1*/



|







1
2
3
4
5
6
7
8
9
10
11
/* create opj_config_private.h for CMake */
#define OPJ_HAVE_INTTYPES_H 	1

#define OPJ_PACKAGE_VERSION "2.4.0"

/* Not used by openjp2*/
/*#define HAVE_MEMORY_H 1*/
/*#define HAVE_STDLIB_H 1*/
/*#define HAVE_STRINGS_H 1*/
/*#define HAVE_STRING_H 1*/
/*#define HAVE_SYS_STAT_H 1*/
Changes to jni/openjpeg/appveyor.yml.
1
2
3
4
5
6
7
8
version: 2.3.1.{build}
branches:
  except:
  - coverity_scan
skip_tags: false
clone_depth: 50
environment:
  matrix:
|







1
2
3
4
5
6
7
8
version: 2.4.0.{build}
branches:
  except:
  - coverity_scan
skip_tags: false
clone_depth: 50
environment:
  matrix:
Changes to jni/openjpeg/cmake/OpenJPEGConfig.cmake.in.
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
set(OPENJPEG_USE_FILE "@OPENJPEG_USE_FILE_CONFIG@")

get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
if(EXISTS ${SELF_DIR}/OpenJPEGTargets.cmake)
  # This is an install tree
  include(${SELF_DIR}/OpenJPEGTargets.cmake)

  # We find a relative path from the PKG directory to header files.
  set(PKG_DIR "@CMAKE_INSTALL_PREFIX@/@OPENJPEG_INSTALL_PACKAGE_DIR@")
  set(INC_DIR "@CMAKE_INSTALL_PREFIX@/@OPENJPEG_INSTALL_INCLUDE_DIR@")
  file(RELATIVE_PATH PKG_TO_INC_RPATH "${PKG_DIR}" "${INC_DIR}")

  get_filename_component(OPENJPEG_INCLUDE_DIRS "${SELF_DIR}/${PKG_TO_INC_RPATH}" ABSOLUTE)

else()
  if(EXISTS ${SELF_DIR}/OpenJPEGExports.cmake)
    # This is a build tree
    set( OPENJPEG_INCLUDE_DIRS @OPENJPEG_INCLUDE_PATH@)

    include(${SELF_DIR}/OpenJPEGExports.cmake)







<
<

<
<
|







23
24
25
26
27
28
29


30


31
32
33
34
35
36
37
38
set(OPENJPEG_USE_FILE "@OPENJPEG_USE_FILE_CONFIG@")

get_filename_component(SELF_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
if(EXISTS ${SELF_DIR}/OpenJPEGTargets.cmake)
  # This is an install tree
  include(${SELF_DIR}/OpenJPEGTargets.cmake)



  set(INC_DIR "@CMAKE_INSTALL_PREFIX@/@OPENJPEG_INSTALL_INCLUDE_DIR@")


  get_filename_component(OPENJPEG_INCLUDE_DIRS "${INC_DIR}" ABSOLUTE)

else()
  if(EXISTS ${SELF_DIR}/OpenJPEGExports.cmake)
    # This is a build tree
    set( OPENJPEG_INCLUDE_DIRS @OPENJPEG_INCLUDE_PATH@)

    include(${SELF_DIR}/OpenJPEGExports.cmake)
Changes to jni/openjpeg/doc/CMakeLists.txt.
40
41
42
43
44
45
46
47
48
49
50
51
52
  add_custom_target(doc ALL
    DEPENDS ${CMAKE_BINARY_DIR}/doc/html/index.html
    COMMENT "Building doxygen documentation"
  )

  # install HTML documentation (install png files too):
  install(DIRECTORY ${CMAKE_BINARY_DIR}/doc/html
    DESTINATION share/doc
    PATTERN ".svn" EXCLUDE
  )
else()
  message(STATUS "Doxygen not found, we cannot generate the documentation")
endif()







|





40
41
42
43
44
45
46
47
48
49
50
51
52
  add_custom_target(doc ALL
    DEPENDS ${CMAKE_BINARY_DIR}/doc/html/index.html
    COMMENT "Building doxygen documentation"
  )

  # install HTML documentation (install png files too):
  install(DIRECTORY ${CMAKE_BINARY_DIR}/doc/html
    DESTINATION ${OPENJPEG_INSTALL_DOC_DIR}
    PATTERN ".svn" EXCLUDE
  )
else()
  message(STATUS "Doxygen not found, we cannot generate the documentation")
endif()
Changes to jni/openjpeg/src/bin/common/color.c.
484
485
486
487
488
489
490




491
492
493
494
495
496
497
    max_w = image->comps[0].w;
    max_h = image->comps[0].h;
    prec = (int)image->comps[0].prec;

    if (out_space == cmsSigRgbData) { /* enumCS 16 */
        unsigned int i, nr_comp = image->numcomps;





        if (nr_comp > 4) {
            nr_comp = 4;
        }
        for (i = 1; i < nr_comp; ++i) { /* AFL test */
            if (image->comps[0].dx != image->comps[i].dx) {
                break;
            }







>
>
>
>







484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
    max_w = image->comps[0].w;
    max_h = image->comps[0].h;
    prec = (int)image->comps[0].prec;

    if (out_space == cmsSigRgbData) { /* enumCS 16 */
        unsigned int i, nr_comp = image->numcomps;

        if (nr_comp < 3) { /* GRAY or GRAYA, not RGB or RGBA */
            cmsCloseProfile(in_prof);
            return;
        }
        if (nr_comp > 4) {
            nr_comp = 4;
        }
        for (i = 1; i < nr_comp; ++i) { /* AFL test */
            if (image->comps[0].dx != image->comps[i].dx) {
                break;
            }
525
526
527
528
529
530
531




532
533
534
535
536
537
538
        new_space = OPJ_CLRSPC_SRGB;
    } else if (out_space == cmsSigGrayData) { /* enumCS 17 */
        in_type = TYPE_GRAY_8;
        out_type = TYPE_RGB_8;
        out_prof = cmsCreate_sRGBProfile();
        new_space = OPJ_CLRSPC_SRGB;
    } else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */




        in_type = TYPE_YCbCr_16;
        out_type = TYPE_RGB_16;
        out_prof = cmsCreate_sRGBProfile();
        new_space = OPJ_CLRSPC_SRGB;
    } else {
#ifdef DEBUG_PROFILE
        fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "







>
>
>
>







529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
        new_space = OPJ_CLRSPC_SRGB;
    } else if (out_space == cmsSigGrayData) { /* enumCS 17 */
        in_type = TYPE_GRAY_8;
        out_type = TYPE_RGB_8;
        out_prof = cmsCreate_sRGBProfile();
        new_space = OPJ_CLRSPC_SRGB;
    } else if (out_space == cmsSigYCbCrData) { /* enumCS 18 */
        if (image->numcomps < 3) {
            cmsCloseProfile(in_prof);
            return;
        }
        in_type = TYPE_YCbCr_16;
        out_type = TYPE_RGB_16;
        out_prof = cmsCreate_sRGBProfile();
        new_space = OPJ_CLRSPC_SRGB;
    } else {
#ifdef DEBUG_PROFILE
        fprintf(stderr, "%s:%d: color_apply_icc_profile\n\tICC Profile has unknown "
Changes to jni/openjpeg/src/bin/jp2/convert.c.
2063
2064
2065
2066
2067
2068
2069







2070
2071
2072
2073









2074
2075
2076
2077
2078
2079
2080
        triple = (ncomp > 2);
        wr = (int)image->comps[0].w;
        hr = (int)image->comps[0].h;
        max = (1 << prec) - 1;
        has_alpha = (ncomp == 4 || ncomp == 2);

        red = image->comps[0].data;








        if (triple) {
            green = image->comps[1].data;
            blue = image->comps[2].data;









        } else {
            green = blue = NULL;
        }

        if (has_alpha) {
            const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");








>
>
>
>
>
>
>




>
>
>
>
>
>
>
>
>







2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
        triple = (ncomp > 2);
        wr = (int)image->comps[0].w;
        hr = (int)image->comps[0].h;
        max = (1 << prec) - 1;
        has_alpha = (ncomp == 4 || ncomp == 2);

        red = image->comps[0].data;
        if (red == NULL) {
            fprintf(stderr,
                    "imagetopnm: planes[%d] == NULL.\n", 0);
            fprintf(stderr, "\tAborting\n");
            fclose(fdest);
            return fails;
        }

        if (triple) {
            green = image->comps[1].data;
            blue = image->comps[2].data;
            for (i = 1; i <= 2; i++) {
                if (image->comps[i].data == NULL) {
                    fprintf(stderr,
                            "imagetopnm: planes[%d] == NULL.\n", i);
                    fprintf(stderr, "\tAborting\n");
                    fclose(fdest);
                    return fails;
                }
            }
        } else {
            green = blue = NULL;
        }

        if (has_alpha) {
            const char *tt = (triple ? "RGB_ALPHA" : "GRAYSCALE_ALPHA");

Changes to jni/openjpeg/src/bin/jp2/convertbmp.c.
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640






641
642
643
644

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659



660
661



662
663
664
665
666
667
668
669
670





671
672
673

674
675
676



677
678
679
680




681
682
683
684
685
686
687

    return OPJ_TRUE;
}

static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
                                   OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
    OPJ_UINT32 x, y;
    OPJ_UINT8 *pix;
    const OPJ_UINT8 *beyond;

    beyond = pData + stride * height;
    pix = pData;
    x = y = 0U;
    while (y < height) {
        int c = getc(IN);
        if (c == EOF) {
            break;
        }

        if (c) { /* encoded mode */
            int j;
            OPJ_UINT8 c1 = (OPJ_UINT8)getc(IN);







            for (j = 0; (j < c) && (x < width) &&
                    ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));

            }
        } else { /* absolute mode */
            c = getc(IN);
            if (c == EOF) {
                break;
            }

            if (c == 0x00) { /* EOL */
                x = 0;
                y++;
                pix = pData + y * stride;
            } else if (c == 0x01) { /* EOP */
                break;
            } else if (c == 0x02) { /* MOVE by dxdy */
                c = getc(IN);



                x += (OPJ_UINT32)c;
                c = getc(IN);



                y += (OPJ_UINT32)c;
                pix = pData + y * stride + x;
            } else { /* 03 .. 255 : absolute mode */
                int j;
                OPJ_UINT8 c1 = 0U;

                for (j = 0; (j < c) && (x < width) &&
                        ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                    if ((j & 1) == 0) {





                        c1 = (OPJ_UINT8)getc(IN);
                    }
                    *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));

                }
                if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
                    getc(IN);



                }
            }
        }
    }  /* while(y < height) */




    return OPJ_TRUE;
}

opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
{
    opj_image_cmptparm_t cmptparm[4];   /* maximum of 4 components */
    OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256];







|





|



|



|
|
>
>
>
>
>
>




>




|










>
>
>


>
>
>









>
>
>
>
>
|


>


|
>
>
>




>
>
>
>







618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713

    return OPJ_TRUE;
}

static OPJ_BOOL bmp_read_rle4_data(FILE* IN, OPJ_UINT8* pData,
                                   OPJ_UINT32 stride, OPJ_UINT32 width, OPJ_UINT32 height)
{
    OPJ_UINT32 x, y, written;
    OPJ_UINT8 *pix;
    const OPJ_UINT8 *beyond;

    beyond = pData + stride * height;
    pix = pData;
    x = y = written = 0U;
    while (y < height) {
        int c = getc(IN);
        if (c == EOF) {
            return OPJ_FALSE;
        }

        if (c) { /* encoded mode */
            int j, c1_int;
            OPJ_UINT8 c1;

            c1_int = getc(IN);
            if (c1_int == EOF) {
                return OPJ_FALSE;
            }
            c1 = (OPJ_UINT8)c1_int;

            for (j = 0; (j < c) && (x < width) &&
                    ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
                written++;
            }
        } else { /* absolute mode */
            c = getc(IN);
            if (c == EOF) {
                return OPJ_FALSE;
            }

            if (c == 0x00) { /* EOL */
                x = 0;
                y++;
                pix = pData + y * stride;
            } else if (c == 0x01) { /* EOP */
                break;
            } else if (c == 0x02) { /* MOVE by dxdy */
                c = getc(IN);
                if (c == EOF) {
                    return OPJ_FALSE;
                }
                x += (OPJ_UINT32)c;
                c = getc(IN);
                if (c == EOF) {
                    return OPJ_FALSE;
                }
                y += (OPJ_UINT32)c;
                pix = pData + y * stride + x;
            } else { /* 03 .. 255 : absolute mode */
                int j;
                OPJ_UINT8 c1 = 0U;

                for (j = 0; (j < c) && (x < width) &&
                        ((OPJ_SIZE_T)pix < (OPJ_SIZE_T)beyond); j++, x++, pix++) {
                    if ((j & 1) == 0) {
                        int c1_int;
                        c1_int = getc(IN);
                        if (c1_int == EOF) {
                            return OPJ_FALSE;
                        }
                        c1 = (OPJ_UINT8)c1_int;
                    }
                    *pix = (OPJ_UINT8)((j & 1) ? (c1 & 0x0fU) : ((c1 >> 4) & 0x0fU));
                    written++;
                }
                if (((c & 3) == 1) || ((c & 3) == 2)) { /* skip padding byte */
                    c = getc(IN);
                    if (c == EOF) {
                        return OPJ_FALSE;
                    }
                }
            }
        }
    }  /* while(y < height) */
    if (written != width * height) {
        fprintf(stderr, "warning, image's actual size does not match advertized one\n");
        return OPJ_FALSE;
    }
    return OPJ_TRUE;
}

opj_image_t* bmptoimage(const char *filename, opj_cparameters_t *parameters)
{
    opj_image_cmptparm_t cmptparm[4];   /* maximum of 4 components */
    OPJ_UINT8 lut_R[256], lut_G[256], lut_B[256];
Changes to jni/openjpeg/src/bin/jp2/convertpng.c.
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                             (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY);
    if (image == NULL) {
        goto fin;
    }
    image->x0 = (OPJ_UINT32)params->image_offset_x0;
    image->y0 = (OPJ_UINT32)params->image_offset_y0;
    image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)
                             params->subsampling_dx + 1 + image->x0);
    image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)
                             params->subsampling_dy + 1 + image->y0);

    row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32));
    if (row32s == NULL) {
        goto fin;
    }

    /* Set alpha channel */







|

|







219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
                             (nr_comp > 2U) ? OPJ_CLRSPC_SRGB : OPJ_CLRSPC_GRAY);
    if (image == NULL) {
        goto fin;
    }
    image->x0 = (OPJ_UINT32)params->image_offset_x0;
    image->y0 = (OPJ_UINT32)params->image_offset_y0;
    image->x1 = (OPJ_UINT32)(image->x0 + (width  - 1) * (OPJ_UINT32)
                             params->subsampling_dx + 1);
    image->y1 = (OPJ_UINT32)(image->y0 + (height - 1) * (OPJ_UINT32)
                             params->subsampling_dy + 1);

    row32s = (OPJ_INT32 *)malloc((size_t)width * nr_comp * sizeof(OPJ_INT32));
    if (row32s == NULL) {
        goto fin;
    }

    /* Set alpha channel */
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
    OPJ_INT32* volatile buffer32s = NULL;

    volatile int fails = 1;

    memset(&sig_bit, 0, sizeof(sig_bit));
    prec = (int)image->comps[0].prec;
    planes[0] = image->comps[0].data;






    nr_comp = (int)image->numcomps;

    if (nr_comp > 4) {
        nr_comp = 4;
    }
    for (i = 1; i < nr_comp; ++i) {
        if (image->comps[0].dx != image->comps[i].dx) {
            break;
        }
        if (image->comps[0].dy != image->comps[i].dy) {
            break;
        }
        if (image->comps[0].prec != image->comps[i].prec) {
            break;
        }
        if (image->comps[0].sgnd != image->comps[i].sgnd) {
            break;
        }
        planes[i] = image->comps[i].data;






    }
    if (i != nr_comp) {
        fprintf(stderr,
                "imagetopng: All components shall have the same subsampling, same bit depth, same sign.\n");
        fprintf(stderr, "\tAborting\n");
        return 1;
    }







>
>
>
>
>
>



















>
>
>
>
>
>







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
    OPJ_INT32* volatile buffer32s = NULL;

    volatile int fails = 1;

    memset(&sig_bit, 0, sizeof(sig_bit));
    prec = (int)image->comps[0].prec;
    planes[0] = image->comps[0].data;
    if (planes[0] == NULL) {
        fprintf(stderr,
                "imagetopng: planes[%d] == NULL.\n", 0);
        fprintf(stderr, "\tAborting\n");
        return 1;
    }
    nr_comp = (int)image->numcomps;

    if (nr_comp > 4) {
        nr_comp = 4;
    }
    for (i = 1; i < nr_comp; ++i) {
        if (image->comps[0].dx != image->comps[i].dx) {
            break;
        }
        if (image->comps[0].dy != image->comps[i].dy) {
            break;
        }
        if (image->comps[0].prec != image->comps[i].prec) {
            break;
        }
        if (image->comps[0].sgnd != image->comps[i].sgnd) {
            break;
        }
        planes[i] = image->comps[i].data;
        if (planes[i] == NULL) {
            fprintf(stderr,
                    "imagetopng: planes[%d] == NULL.\n", i);
            fprintf(stderr, "\tAborting\n");
            return 1;
        }
    }
    if (i != nr_comp) {
        fprintf(stderr,
                "imagetopng: All components shall have the same subsampling, same bit depth, same sign.\n");
        fprintf(stderr, "\tAborting\n");
        return 1;
    }
Changes to jni/openjpeg/src/bin/jp2/converttif.c.
612
613
614
615
616
617
618






619
620
621
622
623
624
625
        if (image->comps[0].prec != image->comps[i].prec) {
            break;
        }
        if (image->comps[0].sgnd != image->comps[i].sgnd) {
            break;
        }
        planes[i] = image->comps[i].data;






    }
    if (i != numcomps) {
        fprintf(stderr,
                "imagetotif: All components shall have the same subsampling, same bit depth.\n");
        fprintf(stderr, "\tAborting\n");
        return 1;
    }







>
>
>
>
>
>







612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
        if (image->comps[0].prec != image->comps[i].prec) {
            break;
        }
        if (image->comps[0].sgnd != image->comps[i].sgnd) {
            break;
        }
        planes[i] = image->comps[i].data;
        if (planes[i] == NULL) {
            fprintf(stderr,
                    "imagetotif: planes[%d] == NULL.\n", i);
            fprintf(stderr, "\tAborting\n");
            return 1;
        }
    }
    if (i != numcomps) {
        fprintf(stderr,
                "imagetotif: All components shall have the same subsampling, same bit depth.\n");
        fprintf(stderr, "\tAborting\n");
        return 1;
    }
Changes to jni/openjpeg/src/bin/jp2/opj_compress.c.
225
226
227
228
229
230
231


232
233
234
235
236
237
238
    fprintf(stdout,
            "    T<tile>=<resStart>,<compStart>,<layerEnd>,<resEnd>,<compEnd>,<progOrder>\n");
    fprintf(stdout, "      Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\n");
    fprintf(stdout, "-SOP\n");
    fprintf(stdout, "    Write SOP marker before each packet.\n");
    fprintf(stdout, "-EPH\n");
    fprintf(stdout, "    Write EPH marker after each header packet.\n");


    fprintf(stdout, "-M <key value>\n");
    fprintf(stdout, "    Mode switch.\n");
    fprintf(stdout, "    [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
    fprintf(stdout, "    8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
    fprintf(stdout, "    Indicate multiple modes by adding their values.\n");
    fprintf(stdout,
            "      Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");







>
>







225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    fprintf(stdout,
            "    T<tile>=<resStart>,<compStart>,<layerEnd>,<resEnd>,<compEnd>,<progOrder>\n");
    fprintf(stdout, "      Example: -POC T1=0,0,1,5,3,CPRL/T1=5,0,1,6,3,CPRL\n");
    fprintf(stdout, "-SOP\n");
    fprintf(stdout, "    Write SOP marker before each packet.\n");
    fprintf(stdout, "-EPH\n");
    fprintf(stdout, "    Write EPH marker after each header packet.\n");
    fprintf(stdout, "-PLT\n");
    fprintf(stdout, "    Write PLT marker in tile-part header.\n");
    fprintf(stdout, "-M <key value>\n");
    fprintf(stdout, "    Mode switch.\n");
    fprintf(stdout, "    [1=BYPASS(LAZY) 2=RESET 4=RESTART(TERMALL)\n");
    fprintf(stdout, "    8=VSC 16=ERTERM(SEGTERM) 32=SEGMARK(SEGSYM)]\n");
    fprintf(stdout, "    Indicate multiple modes by adding their values.\n");
    fprintf(stdout,
            "      Example: RESTART(4) + RESET(2) + SEGMARK(32) => -M 38\n");
283
284
285
286
287
288
289







290
291
292
293
294




295
296
297
298
299
300
301
    fprintf(stdout, "    Digital Cinema 2K profile compliant codestream.\n");
    fprintf(stdout,
            "	Need to specify the frames per second for a 2K resolution.\n");
    fprintf(stdout, "    Only 24 or 48 fps are currently allowed.\n");
    fprintf(stdout, "-cinema4K\n");
    fprintf(stdout, "    Digital Cinema 4K profile compliant codestream.\n");
    fprintf(stdout, "	Frames per second not required. Default value is 24fps.\n");







    fprintf(stdout, "-jpip\n");
    fprintf(stdout, "    Write jpip codestream index box in JP2 output file.\n");
    fprintf(stdout, "    Currently supports only RPCL order.\n");
    fprintf(stdout, "-C <comment>\n");
    fprintf(stdout, "    Add <comment> in the comment marker segment.\n");




    /* UniPG>> */
#ifdef USE_JPWL
    fprintf(stdout, "-W <params>\n");
    fprintf(stdout, "    Adoption of JPWL (Part 11) capabilities (-W params)\n");
    fprintf(stdout,
            "    The <params> field can be written and repeated in any order:\n");
    fprintf(stdout, "    [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");







>
>
>
>
>
>
>





>
>
>
>







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
    fprintf(stdout, "    Digital Cinema 2K profile compliant codestream.\n");
    fprintf(stdout,
            "	Need to specify the frames per second for a 2K resolution.\n");
    fprintf(stdout, "    Only 24 or 48 fps are currently allowed.\n");
    fprintf(stdout, "-cinema4K\n");
    fprintf(stdout, "    Digital Cinema 4K profile compliant codestream.\n");
    fprintf(stdout, "	Frames per second not required. Default value is 24fps.\n");
    fprintf(stdout, "-IMF <PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS]\n");
    fprintf(stdout, "    Interoperable Master Format compliant codestream.\n");
    fprintf(stdout, "    <PROFILE>=2K, 4K, 8K, 2K_R, 4K_R or 8K_R.\n");
    fprintf(stdout, "    X >= 0 and X <= 11.\n");
    fprintf(stdout, "    Y >= 0 and Y <= 9.\n");
    fprintf(stdout,
            "    framerate > 0 may be specified to enhance checks and set maximum bit rate when Y > 0.\n");
    fprintf(stdout, "-jpip\n");
    fprintf(stdout, "    Write jpip codestream index box in JP2 output file.\n");
    fprintf(stdout, "    Currently supports only RPCL order.\n");
    fprintf(stdout, "-C <comment>\n");
    fprintf(stdout, "    Add <comment> in the comment marker segment.\n");
    if (opj_has_thread_support()) {
        fprintf(stdout, "  -threads <num_threads|ALL_CPUS>\n"
                "    Number of threads to use for encoding or ALL_CPUS for all available cores.\n");
    }
    /* UniPG>> */
#ifdef USE_JPWL
    fprintf(stdout, "-W <params>\n");
    fprintf(stdout, "    Adoption of JPWL (Part 11) capabilities (-W params)\n");
    fprintf(stdout,
            "    The <params> field can be written and repeated in any order:\n");
    fprintf(stdout, "    [h<tilepart><=type>,s<tilepart><=method>,a=<addr>,...\n");
564
565
566
567
568
569
570
571



572
573
574
575
576
577
578
579
580
581
582
583
584
585
586



587
588
589
590
591
592
593
}

/* ------------------------------------------------------------------------------------ */

static int parse_cmdline_encoder(int argc, char **argv,
                                 opj_cparameters_t *parameters,
                                 img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename,
                                 size_t indexfilename_size)



{
    OPJ_UINT32 i, j;
    int totlen, c;
    opj_option_t long_option[] = {
        {"cinema2K", REQ_ARG, NULL, 'w'},
        {"cinema4K", NO_ARG, NULL, 'y'},
        {"ImgDir", REQ_ARG, NULL, 'z'},
        {"TP", REQ_ARG, NULL, 'u'},
        {"SOP", NO_ARG, NULL, 'S'},
        {"EPH", NO_ARG, NULL, 'E'},
        {"OutFor", REQ_ARG, NULL, 'O'},
        {"POC", REQ_ARG, NULL, 'P'},
        {"ROI", REQ_ARG, NULL, 'R'},
        {"jpip", NO_ARG, NULL, 'J'},
        {"mct", REQ_ARG, NULL, 'Y'}



    };

    /* parse the command line */
    const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
#ifdef USE_JPWL
                           "W:"
#endif /* USE_JPWL */







|
>
>
>














|
>
>
>







577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
}

/* ------------------------------------------------------------------------------------ */

static int parse_cmdline_encoder(int argc, char **argv,
                                 opj_cparameters_t *parameters,
                                 img_fol_t *img_fol, raw_cparameters_t *raw_cp, char *indexfilename,
                                 size_t indexfilename_size,
                                 int* pOutFramerate,
                                 OPJ_BOOL* pOutPLT,
                                 int* pOutNumThreads)
{
    OPJ_UINT32 i, j;
    int totlen, c;
    opj_option_t long_option[] = {
        {"cinema2K", REQ_ARG, NULL, 'w'},
        {"cinema4K", NO_ARG, NULL, 'y'},
        {"ImgDir", REQ_ARG, NULL, 'z'},
        {"TP", REQ_ARG, NULL, 'u'},
        {"SOP", NO_ARG, NULL, 'S'},
        {"EPH", NO_ARG, NULL, 'E'},
        {"OutFor", REQ_ARG, NULL, 'O'},
        {"POC", REQ_ARG, NULL, 'P'},
        {"ROI", REQ_ARG, NULL, 'R'},
        {"jpip", NO_ARG, NULL, 'J'},
        {"mct", REQ_ARG, NULL, 'Y'},
        {"IMF", REQ_ARG, NULL, 'Z'},
        {"PLT", NO_ARG, NULL, 'A'},
        {"threads",   REQ_ARG, NULL, 'B'}
    };

    /* parse the command line */
    const char optlist[] = "i:o:r:q:n:b:c:t:p:s:SEM:x:R:d:T:If:P:C:F:u:JY:"
#ifdef USE_JPWL
                           "W:"
#endif /* USE_JPWL */
1125
1126
1127
1128
1129
1130
1131




























































































1132
1133
1134
1135
1136
1137
1138
            fprintf(stdout, "CINEMA 4K profile activated\n"
                    "Other options specified could be overridden\n");
        }
        break;

        /* ------------------------------------------------------ */





























































































        case 'Y': {         /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
            int mct_mode = 0;
            sscanf(opj_optarg, "%d", &mct_mode);
            if (mct_mode < 0 || mct_mode > 2) {
                fprintf(stderr,
                        "MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
                return 1;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
            fprintf(stdout, "CINEMA 4K profile activated\n"
                    "Other options specified could be overridden\n");
        }
        break;

        /* ------------------------------------------------------ */

        case 'Z': {         /* IMF profile*/
            int mainlevel = 0;
            int sublevel = 0;
            int profile = 0;
            int framerate = 0;
            const char* msg =
                "Wrong value for -IMF. Should be "
                "<PROFILE>[,mainlevel=X][,sublevel=Y][,framerate=FPS] where <PROFILE> is one "
                "of 2K/4K/8K/2K_R/4K_R/8K_R.\n";
            char* comma;

            comma = strstr(opj_optarg, ",mainlevel=");
            if (comma && sscanf(comma + 1, "mainlevel=%d", &mainlevel) != 1) {
                fprintf(stderr, "%s", msg);
                return 1;
            }

            comma = strstr(opj_optarg, ",sublevel=");
            if (comma && sscanf(comma + 1, "sublevel=%d", &sublevel) != 1) {
                fprintf(stderr, "%s", msg);
                return 1;
            }

            comma = strstr(opj_optarg, ",framerate=");
            if (comma && sscanf(comma + 1, "framerate=%d", &framerate) != 1) {
                fprintf(stderr, "%s", msg);
                return 1;
            }

            comma = strchr(opj_optarg, ',');
            if (comma != NULL) {
                *comma = 0;
            }

            if (strcmp(opj_optarg, "2K") == 0) {
                profile = OPJ_PROFILE_IMF_2K;
            } else if (strcmp(opj_optarg, "4K") == 0) {
                profile = OPJ_PROFILE_IMF_4K;
            } else if (strcmp(opj_optarg, "8K") == 0) {
                profile = OPJ_PROFILE_IMF_8K;
            } else if (strcmp(opj_optarg, "2K_R") == 0) {
                profile = OPJ_PROFILE_IMF_2K_R;
            } else if (strcmp(opj_optarg, "4K_R") == 0) {
                profile = OPJ_PROFILE_IMF_4K_R;
            } else if (strcmp(opj_optarg, "8K_R") == 0) {
                profile = OPJ_PROFILE_IMF_8K_R;
            } else {
                fprintf(stderr, "%s", msg);
                return 1;
            }

            if (!(mainlevel >= 0 && mainlevel <= 15)) {
                /* Voluntarily rough validation. More fine grained done in library */
                fprintf(stderr, "Invalid mainlevel value.\n");
                return 1;
            }
            if (!(sublevel >= 0 && sublevel <= 15)) {
                /* Voluntarily rough validation. More fine grained done in library */
                fprintf(stderr, "Invalid sublevel value.\n");
                return 1;
            }
            parameters->rsiz = (OPJ_UINT16)(profile | (sublevel << 4) | mainlevel);

            fprintf(stdout, "IMF profile activated\n"
                    "Other options specified could be overridden\n");

            if (pOutFramerate) {
                *pOutFramerate = framerate;
            }
            if (framerate > 0 && sublevel > 0 && sublevel <= 9) {
                const int limitMBitsSec[] = {
                    0,
                    OPJ_IMF_SUBLEVEL_1_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_2_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_3_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_4_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_5_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_6_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_7_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_8_MBITSSEC,
                    OPJ_IMF_SUBLEVEL_9_MBITSSEC
                };
                parameters->max_cs_size = limitMBitsSec[sublevel] * (1000 * 1000 / 8) /
                                          framerate;
                fprintf(stdout, "Setting max codestream size to %d bytes.\n",
                        parameters->max_cs_size);
            }
        }
        break;

        /* ------------------------------------------------------ */

        case 'Y': {         /* Shall we do an MCT ? 0:no_mct;1:rgb->ycc;2:custom mct (-m option required)*/
            int mct_mode = 0;
            sscanf(opj_optarg, "%d", &mct_mode);
            if (mct_mode < 0 || mct_mode > 2) {
                fprintf(stderr,
                        "MCT incorrect value!! Current accepted values are 0, 1 or 2.\n");
                return 1;
1565
1566
1567
1568
1569
1570
1571




















1572
1573
1574
1575
1576
1577
1578

        case 'J': {         /* jpip on */
            parameters->jpip_on = OPJ_TRUE;
        }
        break;
        /* ------------------------------------------------------ */






















        default:
            fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
            break;
        }
    } while (c != -1);








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709

        case 'J': {         /* jpip on */
            parameters->jpip_on = OPJ_TRUE;
        }
        break;
        /* ------------------------------------------------------ */

        case 'A': {         /* PLT markers */
            *pOutPLT = OPJ_TRUE;
        }
        break;

        /* ----------------------------------------------------- */
        case 'B': { /* Number of threads */
            if (strcmp(opj_optarg, "ALL_CPUS") == 0) {
                *pOutNumThreads = opj_get_num_cpus();
                if (*pOutNumThreads == 1) {
                    *pOutNumThreads = 0;
                }
            } else {
                sscanf(opj_optarg, "%d", pOutNumThreads);
            }
        }
        break;

        /* ------------------------------------------------------ */


        default:
            fprintf(stderr, "[WARNING] An invalid option has been ignored\n");
            break;
        }
    } while (c != -1);

1740
1741
1742
1743
1744
1745
1746

1747



1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
    dircnt_t *dirptr = NULL;

    int ret = 0;

    OPJ_BOOL bSuccess;
    OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
    OPJ_UINT32 l_nb_tiles = 4;

    OPJ_FLOAT64 t = opj_clock();




    /* set encoding parameters to default values */
    opj_set_default_encoder_parameters(&parameters);

    /* Initialize indexfilename and img_fol */
    *indexfilename = 0;
    memset(&img_fol, 0, sizeof(img_fol_t));

    /* raw_cp initialization */
    raw_cp.rawBitDepth = 0;
    raw_cp.rawComp = 0;
    raw_cp.rawComps = 0;
    raw_cp.rawHeight = 0;
    raw_cp.rawSigned = 0;
    raw_cp.rawWidth = 0;

    /* parse input and get user encoding parameters */
    parameters.tcp_mct = (char)
                         255; /* This will be set later according to the input image or the provided option */
    if (parse_cmdline_encoder(argc, argv, &parameters, &img_fol, &raw_cp,
                              indexfilename, sizeof(indexfilename)) == 1) {
        ret = 1;
        goto fin;
    }

    /* Read directory if necessary */
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);







>

>
>
>




















|







1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
    dircnt_t *dirptr = NULL;

    int ret = 0;

    OPJ_BOOL bSuccess;
    OPJ_BOOL bUseTiles = OPJ_FALSE; /* OPJ_TRUE */
    OPJ_UINT32 l_nb_tiles = 4;
    int framerate = 0;
    OPJ_FLOAT64 t = opj_clock();

    OPJ_BOOL PLT = OPJ_FALSE;
    int num_threads = 0;

    /* set encoding parameters to default values */
    opj_set_default_encoder_parameters(&parameters);

    /* Initialize indexfilename and img_fol */
    *indexfilename = 0;
    memset(&img_fol, 0, sizeof(img_fol_t));

    /* raw_cp initialization */
    raw_cp.rawBitDepth = 0;
    raw_cp.rawComp = 0;
    raw_cp.rawComps = 0;
    raw_cp.rawHeight = 0;
    raw_cp.rawSigned = 0;
    raw_cp.rawWidth = 0;

    /* parse input and get user encoding parameters */
    parameters.tcp_mct = (char)
                         255; /* This will be set later according to the input image or the provided option */
    if (parse_cmdline_encoder(argc, argv, &parameters, &img_fol, &raw_cp,
                              indexfilename, sizeof(indexfilename), &framerate, &PLT, &num_threads) == 1) {
        ret = 1;
        goto fin;
    }

    /* Read directory if necessary */
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);
1935
1936
1937
1938
1939
1940
1941



































1942
1943
1944
1945
1946
1947
1948
            if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {
                fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
                fprintf(stderr, "has been provided. Aborting.\n");
                ret = 1;
                goto fin;
            }
        }




































        /* encode the destination image */
        /* ---------------------------- */

        switch (parameters.cod_format) {
        case J2K_CFMT: { /* JPEG-2000 codestream */
            /* Get a decoder handle */







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
            if ((parameters.tcp_mct == 2) && (!parameters.mct_data)) {
                fprintf(stderr, "Custom MCT has been set but no array-based MCT\n");
                fprintf(stderr, "has been provided. Aborting.\n");
                ret = 1;
                goto fin;
            }
        }

        if (OPJ_IS_IMF(parameters.rsiz) && framerate > 0) {
            const int mainlevel = OPJ_GET_IMF_MAINLEVEL(parameters.rsiz);
            if (mainlevel > 0 && mainlevel <= OPJ_IMF_MAINLEVEL_MAX) {
                const int limitMSamplesSec[] = {
                    0,
                    OPJ_IMF_MAINLEVEL_1_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_2_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_3_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_4_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_5_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_6_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_7_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_8_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_9_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_10_MSAMPLESEC,
                    OPJ_IMF_MAINLEVEL_11_MSAMPLESEC
                };
                OPJ_UINT32 avgcomponents = image->numcomps;
                double msamplespersec;
                if (image->numcomps == 3 &&
                        image->comps[1].dx == 2 &&
                        image->comps[1].dy == 2) {
                    avgcomponents = 2;
                }
                msamplespersec = (double)image->x1 * image->y1 * avgcomponents * framerate /
                                 1e6;
                if (msamplespersec > limitMSamplesSec[mainlevel]) {
                    fprintf(stderr,
                            "Warning: MSamples/sec is %f, whereas limit is %d.\n",
                            msamplespersec,
                            limitMSamplesSec[mainlevel]);
                }
            }
        }

        /* encode the destination image */
        /* ---------------------------- */

        switch (parameters.cod_format) {
        case J2K_CFMT: { /* JPEG-2000 codestream */
            /* Get a decoder handle */
1975
1976
1977
1978
1979
1980
1981




















1982
1983
1984
1985
1986
1987
1988
        if (! opj_setup_encoder(l_codec, &parameters, image)) {
            fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            ret = 1;
            goto fin;
        }





















        /* open a byte stream for writing and allocate memory for all tiles */
        l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);
        if (! l_stream) {
            ret = 1;
            goto fin;
        }







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
        if (! opj_setup_encoder(l_codec, &parameters, image)) {
            fprintf(stderr, "failed to encode image: opj_setup_encoder\n");
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            ret = 1;
            goto fin;
        }

        if (PLT) {
            const char* const options[] = { "PLT=YES", NULL };
            if (!opj_encoder_set_extra_options(l_codec, options)) {
                fprintf(stderr, "failed to encode image: opj_encoder_set_extra_options\n");
                opj_destroy_codec(l_codec);
                opj_image_destroy(image);
                ret = 1;
                goto fin;
            }
        }

        if (num_threads >= 1 &&
                !opj_codec_set_threads(l_codec, num_threads)) {
            fprintf(stderr, "failed to set number of threads\n");
            opj_destroy_codec(l_codec);
            opj_image_destroy(image);
            ret = 1;
            goto fin;
        }

        /* open a byte stream for writing and allocate memory for all tiles */
        l_stream = opj_stream_create_default_file_stream(parameters.outfile, OPJ_FALSE);
        if (! l_stream) {
            ret = 1;
            goto fin;
        }
Changes to jni/openjpeg/src/bin/jp2/opj_decompress.c.
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
/**
 * OPJ_DECOMPRESS MAIN
 */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
    opj_decompress_parameters parameters;           /* decompression parameters */
    opj_image_t* image = NULL;
    opj_stream_t *l_stream = NULL;              /* Stream */
    opj_codec_t* l_codec = NULL;                /* Handle to a decompressor */
    opj_codestream_index_t* cstr_index = NULL;

    OPJ_INT32 num_images, imageno;
    img_fol_t img_fol;
    dircnt_t *dirptr = NULL;
    int failed = 0;
    OPJ_FLOAT64 t, tCumulative = 0;
    OPJ_UINT32 numDecompressedImages = 0;







<
<
<
<







1312
1313
1314
1315
1316
1317
1318




1319
1320
1321
1322
1323
1324
1325
/**
 * OPJ_DECOMPRESS MAIN
 */
/* -------------------------------------------------------------------------- */
int main(int argc, char **argv)
{
    opj_decompress_parameters parameters;           /* decompression parameters */





    OPJ_INT32 num_images, imageno;
    img_fol_t img_fol;
    dircnt_t *dirptr = NULL;
    int failed = 0;
    OPJ_FLOAT64 t, tCumulative = 0;
    OPJ_UINT32 numDecompressedImages = 0;
1389
1390
1391
1392
1393
1394
1395




1396
1397
1398
1399
1400
1401
1402
        }
    } else {
        num_images = 1;
    }

    /*Decoding image one by one*/
    for (imageno = 0; imageno < num_images ; imageno++)  {





        if (!parameters.quiet) {
            fprintf(stderr, "\n");
        }

        if (img_fol.set_imgdir == 1) {
            if (get_next_file(imageno, dirptr, &img_fol, &parameters)) {







>
>
>
>







1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
        }
    } else {
        num_images = 1;
    }

    /*Decoding image one by one*/
    for (imageno = 0; imageno < num_images ; imageno++)  {
        opj_image_t* image = NULL;
        opj_stream_t *l_stream = NULL;              /* Stream */
        opj_codec_t* l_codec = NULL;                /* Handle to a decompressor */
        opj_codestream_index_t* cstr_index = NULL;

        if (!parameters.quiet) {
            fprintf(stderr, "\n");
        }

        if (img_fol.set_imgdir == 1) {
            if (get_next_file(imageno, dirptr, &img_fol, &parameters)) {
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
                goto fin;
            }
            if (!(parameters.quiet)) {
                fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
            }
        }

        /* FIXME? Shouldn't that situation be considered as an error of */
        /* opj_decode() / opj_get_decoded_tile() ? */
        if (image->comps[0].data == NULL) {
            fprintf(stderr, "ERROR -> opj_decompress: no image data!\n");
            opj_destroy_codec(l_codec);
            opj_stream_destroy(l_stream);
            opj_image_destroy(image);
            failed = 1;
            goto fin;
        }

        tCumulative += opj_clock() - t;
        numDecompressedImages++;

        /* Close the byte stream */
        opj_stream_destroy(l_stream);

        if (image->color_space != OPJ_CLRSPC_SYCC







<
<
<
<
<
<
<
<
<
<
<







1567
1568
1569
1570
1571
1572
1573











1574
1575
1576
1577
1578
1579
1580
                goto fin;
            }
            if (!(parameters.quiet)) {
                fprintf(stdout, "tile %d is decoded!\n\n", parameters.tile_index);
            }
        }












        tCumulative += opj_clock() - t;
        numDecompressedImages++;

        /* Close the byte stream */
        opj_stream_destroy(l_stream);

        if (image->color_space != OPJ_CLRSPC_SYCC
Changes to jni/openjpeg/src/bin/jp3d/convert.c.
276
277
278
279
280
281
282

283
284
285
286
287
288
289
        }

    }/* else if pattern*.pgx */

    if (!sliceno) {
        fprintf(stdout,
                "[ERROR] No slices with this pattern founded !! Please check input volume name\n");

        return NULL;
    }
    /*if ( maxslice != sliceno) {
        fprintf(stdout,"[ERROR] Slices are not sequentially numbered !! Please rename them accordingly\n");
        return NULL;
    }*/








>







276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
        }

    }/* else if pattern*.pgx */

    if (!sliceno) {
        fprintf(stdout,
                "[ERROR] No slices with this pattern founded !! Please check input volume name\n");
        closedir(dirp);
        return NULL;
    }
    /*if ( maxslice != sliceno) {
        fprintf(stdout,"[ERROR] Slices are not sequentially numbered !! Please rename them accordingly\n");
        return NULL;
    }*/

313
314
315
316
317
318
319

320
321
322
323
324
325
326
        if (endian1 == 'M' && endian2 == 'L') {
            cmptparm.bigendian = 1;
        } else if (endian2 == 'M' && endian1 == 'L') {
            cmptparm.bigendian = 0;
        } else {
            fprintf(stdout, "[ERROR] Bad pgx header, please check input file\n");
            fclose(f);

            return NULL;
        }

        if (s == 0) {
            /* initialize volume component */

            cmptparm.x0 = parameters->volume_offset_x0;







>







314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
        if (endian1 == 'M' && endian2 == 'L') {
            cmptparm.bigendian = 1;
        } else if (endian2 == 'M' && endian1 == 'L') {
            cmptparm.bigendian = 0;
        } else {
            fprintf(stdout, "[ERROR] Bad pgx header, please check input file\n");
            fclose(f);
            closedir(dirp);
            return NULL;
        }

        if (s == 0) {
            /* initialize volume component */

            cmptparm.x0 = parameters->volume_offset_x0;
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
            }
            comp->data[i + offset] = v;

        }
        fclose(f);
    } /* for s --> sliceno*/
    comp->bpp = int_floorlog2(maxvalue) + 1;
    if (sliceno != 1) {
        closedir(dirp);
    }
    /*dump_volume(stdout, volume);*/
    return volume;
}


int volumetopgx(opj_volume_t * volume, char *outfile)
{







<
|
<







394
395
396
397
398
399
400

401

402
403
404
405
406
407
408
            }
            comp->data[i + offset] = v;

        }
        fclose(f);
    } /* for s --> sliceno*/
    comp->bpp = int_floorlog2(maxvalue) + 1;

    closedir(dirp);

    /*dump_volume(stdout, volume);*/
    return volume;
}


int volumetopgx(opj_volume_t * volume, char *outfile)
{
577
578
579
580
581
582
583

584
585
586
587
588
589
590
    volume->y1 = parameters->volume_offset_y0 + (h - 1) *   subsampling_dy + 1;
    volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;

    /* set volume data */
    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stdout, "[ERROR] Failed to open %s for reading !!\n", filename);

        return 0;
    }

    /* BINARY */
    for (compno = 0; compno < volume->numcomps; compno++) {
        int whl = w * h * l;
        /* set volume data */







>







577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
    volume->y1 = parameters->volume_offset_y0 + (h - 1) *   subsampling_dy + 1;
    volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;

    /* set volume data */
    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stdout, "[ERROR] Failed to open %s for reading !!\n", filename);
        opj_free(volume);
        return 0;
    }

    /* BINARY */
    for (compno = 0; compno < volume->numcomps; compno++) {
        int whl = w * h * l;
        /* set volume data */
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
    volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;

    max = 0;
    /* set volume data */
    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "[ERROR] Failed to open %s for reading !!\n", filename);
        fclose(f);
        return 0;
    }

    /* BINARY */
    for (compno = 0; compno < volume->numcomps; compno++) {
        int whl = w * h * l;
        /* set volume data */







|







915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
    volume->z1 = parameters->volume_offset_z0 + (l - 1) *   subsampling_dz + 1;

    max = 0;
    /* set volume data */
    f = fopen(filename, "rb");
    if (!f) {
        fprintf(stderr, "[ERROR] Failed to open %s for reading !!\n", filename);
        opj_free(volume);
        return 0;
    }

    /* BINARY */
    for (compno = 0; compno < volume->numcomps; compno++) {
        int whl = w * h * l;
        /* set volume data */
Changes to jni/openjpeg/src/bin/jpip/CMakeLists.txt.
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  install(TARGETS ${exe}
    EXPORT OpenJPEGTargets
    DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
    )
endforeach()

# Build the two java clients:
find_package(Java 1.5 COMPONENTS Development) # javac, jar

# User can override this:
if(NOT DEFINED JAVA_SOURCE_VERSION)
  set(JAVA_SOURCE_VERSION 1.5)
endif()
if(NOT DEFINED JAVA_TARGET_VERSION)
  set(JAVA_TARGET_VERSION 1.5)
endif()

# Only build the java viewer if dev is found:
if(Java_Development_FOUND AND Java_JAVAC_EXECUTABLE)
  set(jflags $ENV{JFLAGS})
  # search for package org.apache.xerces.parsers
  find_file(APACHE_XERCES_JAR







|



|


|







53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  install(TARGETS ${exe}
    EXPORT OpenJPEGTargets
    DESTINATION ${OPENJPEG_INSTALL_BIN_DIR} COMPONENT Applications
    )
endforeach()

# Build the two java clients:
find_package(Java 1.6 COMPONENTS Development) # javac, jar

# User can override this:
if(NOT DEFINED JAVA_SOURCE_VERSION)
  set(JAVA_SOURCE_VERSION 1.6)
endif()
if(NOT DEFINED JAVA_TARGET_VERSION)
  set(JAVA_TARGET_VERSION 1.6)
endif()

# Only build the java viewer if dev is found:
if(Java_Development_FOUND AND Java_JAVAC_EXECUTABLE)
  set(jflags $ENV{JFLAGS})
  # search for package org.apache.xerces.parsers
  find_file(APACHE_XERCES_JAR
Changes to jni/openjpeg/src/bin/jpip/opj_jpip_transcode.c.
45
46
47
48
49
50
51

52
53
54
55
56
57

58
59
60
61
62
63
64
static int jpip_to_jp2(char *argv[])
{
    jpip_dec_param_t *dec;

    dec = init_jpipdecoder(OPJ_TRUE);

    if (!(fread_jpip(argv[1], dec))) {

        return 1;
    }

    decode_jpip(dec);

    if (!(fwrite_jp2k(argv[2], dec))) {

        return 1;
    }

    /* output_log( OPJ_TRUE, OPJ_FALSE, OPJ_TRUE, dec); */

    destroy_jpipdecoder(&dec);








>






>







45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
static int jpip_to_jp2(char *argv[])
{
    jpip_dec_param_t *dec;

    dec = init_jpipdecoder(OPJ_TRUE);

    if (!(fread_jpip(argv[1], dec))) {
        destroy_jpipdecoder(&dec);
        return 1;
    }

    decode_jpip(dec);

    if (!(fwrite_jp2k(argv[2], dec))) {
        destroy_jpipdecoder(&dec);
        return 1;
    }

    /* output_log( OPJ_TRUE, OPJ_FALSE, OPJ_TRUE, dec); */

    destroy_jpipdecoder(&dec);

79
80
81
82
83
84
85

86
87
88
89
90
91

92
93
94
95
96
97
98
static int jpip_to_j2k(char *argv[])
{
    jpip_dec_param_t *dec;

    dec = init_jpipdecoder(OPJ_FALSE);

    if (!(fread_jpip(argv[1], dec))) {

        return 1;
    }

    decode_jpip(dec);

    if (!(fwrite_jp2k(argv[2], dec))) {

        return 1;
    }

    /*  output_log( OPJ_TRUE, OPJ_FALSE, OPJ_FALSE, dec); */

    destroy_jpipdecoder(&dec);








>






>







81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
static int jpip_to_j2k(char *argv[])
{
    jpip_dec_param_t *dec;

    dec = init_jpipdecoder(OPJ_FALSE);

    if (!(fread_jpip(argv[1], dec))) {
        destroy_jpipdecoder(&dec);
        return 1;
    }

    decode_jpip(dec);

    if (!(fwrite_jp2k(argv[2], dec))) {
        destroy_jpipdecoder(&dec);
        return 1;
    }

    /*  output_log( OPJ_TRUE, OPJ_FALSE, OPJ_FALSE, dec); */

    destroy_jpipdecoder(&dec);

Changes to jni/openjpeg/src/bin/jpwl/convert.c.
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

    for (i = 0; i < image->numcomps - 1; i++) {
        if ((image->comps[0].dx != image->comps[i + 1].dx)
                || (image->comps[0].dy != image->comps[i + 1].dy)
                || (image->comps[0].prec != image->comps[i + 1].prec)) {
            fprintf(stderr,
                    "Unable to create a tga file with such J2K image charateristics.");

            return 1;
        }
    }

    width = image->comps[0].w;
    height = image->comps[0].h;

    /* Mono with alpha, or RGB with alpha. */
    write_alpha = (image->numcomps == 2) || (image->numcomps == 4);

    /* Write TGA header  */
    bpp = write_alpha ? 32 : 24;
    if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {

        return 1;
    }

    alpha_channel = image->numcomps - 1;

    scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);








>













>







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

    for (i = 0; i < image->numcomps - 1; i++) {
        if ((image->comps[0].dx != image->comps[i + 1].dx)
                || (image->comps[0].dy != image->comps[i + 1].dy)
                || (image->comps[0].prec != image->comps[i + 1].prec)) {
            fprintf(stderr,
                    "Unable to create a tga file with such J2K image charateristics.");
            fclose(fdest);
            return 1;
        }
    }

    width = image->comps[0].w;
    height = image->comps[0].h;

    /* Mono with alpha, or RGB with alpha. */
    write_alpha = (image->numcomps == 2) || (image->numcomps == 4);

    /* Write TGA header  */
    bpp = write_alpha ? 32 : 24;
    if (!tga_writeheader(fdest, bpp, width, height, OPJ_TRUE)) {
        fclose(fdest);
        return 1;
    }

    alpha_channel = image->numcomps - 1;

    scale = 255.0f / (float)((1 << image->comps[0].prec) - 1);

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
            }

            /* TGA format writes BGR ... */
            value = (unsigned char)(b * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);

                return 1;
            }

            value = (unsigned char)(g * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);

                return 1;
            }

            value = (unsigned char)(r * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);

                return 1;
            }

            if (write_alpha) {
                a = (float)(image->comps[alpha_channel].data[index]);
                value = (unsigned char)(a * scale);
                res = fwrite(&value, 1, 1, fdest);
                if (res < 1) {
                    fprintf(stderr, "failed to write 1 byte for %s\n", outfile);

                    return 1;
                }
            }
        }
    }



    return 0;
}

/* -->> -->> -->> -->>

  BMP IMAGE FORMAT







>







>







>









>





>
>







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
            }

            /* TGA format writes BGR ... */
            value = (unsigned char)(b * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
                fclose(fdest);
                return 1;
            }

            value = (unsigned char)(g * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
                fclose(fdest);
                return 1;
            }

            value = (unsigned char)(r * scale);
            res = fwrite(&value, 1, 1, fdest);
            if (res < 1) {
                fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
                fclose(fdest);
                return 1;
            }

            if (write_alpha) {
                a = (float)(image->comps[alpha_channel].data[index]);
                value = (unsigned char)(a * scale);
                res = fwrite(&value, 1, 1, fdest);
                if (res < 1) {
                    fprintf(stderr, "failed to write 1 byte for %s\n", outfile);
                    fclose(fdest);
                    return 1;
                }
            }
        }
    }

    fclose(fdest);

    return 0;
}

/* -->> -->> -->> -->>

  BMP IMAGE FORMAT
828
829
830
831
832
833
834

835
836
837
838
839
840
841
                    (h - 1) * subsampling_dy + 1;

        /* set image data */

        RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));

        if (fread(RGB, sizeof(unsigned char), W * H, IN) != W * H) {

            free(table_R);
            free(table_G);
            free(table_B);
            free(RGB);
            opj_image_destroy(image);
            fprintf(stderr,
                    "\nError: fread return a number of element different from the expected.\n");







>







836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
                    (h - 1) * subsampling_dy + 1;

        /* set image data */

        RGB = (unsigned char *) malloc(W * H * sizeof(unsigned char));

        if (fread(RGB, sizeof(unsigned char), W * H, IN) != W * H) {
            fclose(IN);
            free(table_R);
            free(table_G);
            free(table_B);
            free(RGB);
            opj_image_destroy(image);
            fprintf(stderr,
                    "\nError: fread return a number of element different from the expected.\n");
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507

1508
1509
1510
1511
1512
1513
1514
        char bname[256]; /* buffer for name */
        char *name = bname; /* pointer */
        int nbytes = 0;
        size_t res;
        const size_t olen = strlen(outfile);
        const size_t dotpos = olen - 4;
        const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
        if (outfile[dotpos] != '.') {
            /* `pgx` was recognized but there is no dot at expected position */
            fprintf(stderr, "ERROR -> Impossible happen.");
            return 1;
        }
        if (total > 256) {
            name = (char*)malloc(total + 1);
        }
        strncpy(name, outfile, dotpos);
        /*if (image->numcomps > 1) {*/
        sprintf(name + dotpos, "_%d.pgx", compno);
        /*} else {
            strcpy(name+dotpos, ".pgx");
        }*/
        fdest = fopen(name, "wb");
        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);

            return 1;
        }
        /* don't need name anymore */
        if (total > 256) {
            free(name);
        }








|
















>







1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
        char bname[256]; /* buffer for name */
        char *name = bname; /* pointer */
        int nbytes = 0;
        size_t res;
        const size_t olen = strlen(outfile);
        const size_t dotpos = olen - 4;
        const size_t total = dotpos + 1 + 1 + 4; /* '-' + '[1-3]' + '.pgx' */
        if (olen < 4 || outfile[dotpos] != '.') {
            /* `pgx` was recognized but there is no dot at expected position */
            fprintf(stderr, "ERROR -> Impossible happen.");
            return 1;
        }
        if (total > 256) {
            name = (char*)malloc(total + 1);
        }
        strncpy(name, outfile, dotpos);
        /*if (image->numcomps > 1) {*/
        sprintf(name + dotpos, "_%d.pgx", compno);
        /*} else {
            strcpy(name+dotpos, ".pgx");
        }*/
        fdest = fopen(name, "wb");
        if (!fdest) {
            fprintf(stderr, "ERROR -> failed to open %s for writing\n", name);
            free(name);
            return 1;
        }
        /* don't need name anymore */
        if (total > 256) {
            free(name);
        }

Changes to jni/openjpeg/src/bin/jpwl/opj_jpwl_compress.c.
1677
1678
1679
1680
1681
1682
1683





1684
1685


1686
1687
1688
1689
1690
1691
1692


1693
1694
1695


1696
1697
1698
1699
1700
1701
1702
    /* Read directory if necessary */
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);
        dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
        if (dirptr) {
            dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
                    char)); /* Stores at max 10 image file names*/





            dirptr->filename = (char**) malloc(num_images * sizeof(char*));
            if (!dirptr->filename_buf) {


                return 0;
            }
            for (i = 0; i < num_images; i++) {
                dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
            }
        }
        if (load_images(dirptr, img_fol.imgdirpath) == 1) {


            return 0;
        }
        if (num_images == 0) {


            fprintf(stdout, "Folder is empty\n");
            return 0;
        }
    } else {
        num_images = 1;
    }
    /*Encoding image one by one*/







>
>
>
>
>

|
>
>







>
>



>
>







1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
    /* Read directory if necessary */
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);
        dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
        if (dirptr) {
            dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
                    char)); /* Stores at max 10 image file names*/
            if (!dirptr->filename_buf) {
                free(parameters.cp_comment);
                free(dirptr);
                return 0;
            }
            dirptr->filename = (char**) malloc(num_images * sizeof(char*));
            if (!dirptr->filename) {
                free(parameters.cp_comment);
                free(dirptr);
                return 0;
            }
            for (i = 0; i < num_images; i++) {
                dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
            }
        }
        if (load_images(dirptr, img_fol.imgdirpath) == 1) {
            free(parameters.cp_comment);
            free(dirptr);
            return 0;
        }
        if (num_images == 0) {
            free(parameters.cp_comment);
            free(dirptr);
            fprintf(stdout, "Folder is empty\n");
            return 0;
        }
    } else {
        num_images = 1;
    }
    /*Encoding image one by one*/
1846
1847
1848
1849
1850
1851
1852

1853
1854
1855
1856
1857
1858
1859
                fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
                return 1;
            }
            res = fwrite(cio->buffer, 1, codestream_length, f);
            if (res < (size_t)codestream_length) {  /* FIXME */
                fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
                        parameters.outfile);

                return 1;
            }
            fclose(f);

            fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
            /* close and free the byte stream */
            opj_cio_close(cio);







>







1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
                fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
                return 1;
            }
            res = fwrite(cio->buffer, 1, codestream_length, f);
            if (res < (size_t)codestream_length) {  /* FIXME */
                fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
                        parameters.outfile);
                fclose(f);
                return 1;
            }
            fclose(f);

            fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
            /* close and free the byte stream */
            opj_cio_close(cio);
1910
1911
1912
1913
1914
1915
1916

1917
1918
1919
1920
1921
1922
1923
                fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
                return 1;
            }
            res = fwrite(cio->buffer, 1, codestream_length, f);
            if (res < (size_t)codestream_length) {  /* FIXME */
                fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
                        parameters.outfile);

                return 1;
            }
            fclose(f);
            fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
            /* close and free the byte stream */
            opj_cio_close(cio);








>







1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
                fprintf(stderr, "failed to open %s for writing\n", parameters.outfile);
                return 1;
            }
            res = fwrite(cio->buffer, 1, codestream_length, f);
            if (res < (size_t)codestream_length) {  /* FIXME */
                fprintf(stderr, "failed to write %d (%s)\n", codestream_length,
                        parameters.outfile);
                fclose(f);
                return 1;
            }
            fclose(f);
            fprintf(stderr, "Generated outfile %s\n", parameters.outfile);
            /* close and free the byte stream */
            opj_cio_close(cio);

Changes to jni/openjpeg/src/bin/jpwl/opj_jpwl_decompress.c.
593
594
595
596
597
598
599
600


601

602

603
604

605
606
607
608
609
610
611
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);

        dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
        if (dirptr) {
            dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
                    char)); /* Stores at max 10 image file names*/
            dirptr->filename = (char**) malloc(num_images * sizeof(char*));




            if (!dirptr->filename_buf) {

                return 1;
            }

            for (i = 0; i < num_images; i++) {
                dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
            }
        }
        if (load_images(dirptr, img_fol.imgdirpath) == 1) {
            return 1;
        }







|
>
>
|
>
|
>


>







593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    if (img_fol.set_imgdir == 1) {
        num_images = get_num_images(img_fol.imgdirpath);

        dirptr = (dircnt_t*)malloc(sizeof(dircnt_t));
        if (dirptr) {
            dirptr->filename_buf = (char*)malloc(num_images * OPJ_PATH_LEN * sizeof(
                    char)); /* Stores at max 10 image file names*/
            if (!dirptr->filename_buf) {
                free(dirptr);
                return 1;
            }
            dirptr->filename = (char**) malloc(num_images * sizeof(char*));
            if (!dirptr->filename) {
                free(dirptr);
                return 1;
            }

            for (i = 0; i < num_images; i++) {
                dirptr->filename[i] = dirptr->filename_buf + i * OPJ_PATH_LEN;
            }
        }
        if (load_images(dirptr, img_fol.imgdirpath) == 1) {
            return 1;
        }
Changes to jni/openjpeg/src/bin/mj2/mj2_to_metadata.c.
300
301
302
303
304
305
306

307
308
309
310
311
312
313
        outfile++; /* There may be a leading blank if user put space after -o */
    }

    // Checking output file
    xmlout = fopen(outfile, "w"); /* was: argv[2] */
    if (!xmlout) {
        fprintf(stderr, "Failed to open %s for writing.\n", outfile); /* was: argv[2] */

        return 1;
    }
    // Leave it open

    /*
    configure the event callbacks (not required)
    setting of each callback is optional







>







300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        outfile++; /* There may be a leading blank if user put space after -o */
    }

    // Checking output file
    xmlout = fopen(outfile, "w"); /* was: argv[2] */
    if (!xmlout) {
        fprintf(stderr, "Failed to open %s for writing.\n", outfile); /* was: argv[2] */
        fclose(file);
        return 1;
    }
    // Leave it open

    /*
    configure the event callbacks (not required)
    setting of each callback is optional
Changes to jni/openjpeg/src/bin/mj2/opj_mj2_compress.c.
704
705
706
707
708
709
710

711
712
713
714
715
716
717
    /* setup encoder parameters */
    mj2_setup_encoder(movie, &mj2_parameters);

    movie->tk[0].num_samples =
        yuv_num_frames(&movie->tk[0], mj2_parameters.infile);

    if (movie->tk[0].num_samples == 0) {

        return 1;
    }

    /* One sample per chunk*/
    movie->tk[0].chunk = (mj2_chunk_t*)
                         malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));
    movie->tk[0].sample = (mj2_sample_t*)







>







704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
    /* setup encoder parameters */
    mj2_setup_encoder(movie, &mj2_parameters);

    movie->tk[0].num_samples =
        yuv_num_frames(&movie->tk[0], mj2_parameters.infile);

    if (movie->tk[0].num_samples == 0) {
        fclose(mj2file);
        return 1;
    }

    /* One sample per chunk*/
    movie->tk[0].chunk = (mj2_chunk_t*)
                         malloc(movie->tk[0].num_samples * sizeof(mj2_chunk_t));
    movie->tk[0].sample = (mj2_sample_t*)
Changes to jni/openjpeg/src/bin/mj2/opj_mj2_decompress.c.
95
96
97
98
99
100
101
102
103

104
105
106
107
108
109
110
    if (!file) {
        fprintf(stderr, "failed to open %s for reading\n", argv[1]);
        return 1;
    }

    /* Checking output file */
    outfile = fopen(argv[2], "w");
    if (!file) {
        fprintf(stderr, "failed to open %s for writing\n", argv[2]);

        return 1;
    }
    fclose(outfile);

    /*
    configure the event callbacks (not required)
    setting of each callback is optional







|

>







95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    if (!file) {
        fprintf(stderr, "failed to open %s for reading\n", argv[1]);
        return 1;
    }

    /* Checking output file */
    outfile = fopen(argv[2], "w");
    if (!outfile) {
        fprintf(stderr, "failed to open %s for writing\n", argv[2]);
        fclose(file);
        return 1;
    }
    fclose(outfile);

    /*
    configure the event callbacks (not required)
    setting of each callback is optional
165
166
167
168
169
170
171

172
173
174
175
176
177
178

        sample = &track->sample[snum];
        if (sample->sample_size - 8 > max_codstrm_size) {
            max_codstrm_size =  sample->sample_size - 8;
            if ((frame_codestream = (unsigned char*)
                                    realloc(frame_codestream, max_codstrm_size)) == NULL) {
                printf("Error reallocation memory\n");

                return 1;
            };
        }
        fseek(file, sample->offset + 8, SEEK_SET);
        fread(frame_codestream, sample->sample_size - 8, 1,
              file); /* Assuming that jp and ftyp markers size do */








>







166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

        sample = &track->sample[snum];
        if (sample->sample_size - 8 > max_codstrm_size) {
            max_codstrm_size =  sample->sample_size - 8;
            if ((frame_codestream = (unsigned char*)
                                    realloc(frame_codestream, max_codstrm_size)) == NULL) {
                printf("Error reallocation memory\n");
                free(frame_codestream);
                return 1;
            };
        }
        fseek(file, sample->offset + 8, SEEK_SET);
        fread(frame_codestream, sample->sample_size - 8, 1,
              file); /* Assuming that jp and ftyp markers size do */

Changes to jni/openjpeg/src/lib/openjp2/CMakeLists.txt.
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
  message(FATAL_ERROR "No thread library found and thread/mutex support is required by OPJ_USE_THREAD option")
endif(OPJ_USE_THREAD AND NOT Threads_FOUND)

if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
   TARGET_LINK_LIBRARIES(${OPENJPEG_LIBRARY_NAME} ${CMAKE_THREAD_LIBS_INIT})
endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)

if(BUILD_UNIT_TESTS)
    add_executable(bench_dwt bench_dwt.c)
    if(UNIX)
        target_link_libraries(bench_dwt m ${OPENJPEG_LIBRARY_NAME})
    endif()
    if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
        target_link_libraries(bench_dwt ${CMAKE_THREAD_LIBS_INIT})
    endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)

    add_executable(test_sparse_array test_sparse_array.c)
    if(UNIX)
        target_link_libraries(test_sparse_array m ${OPENJPEG_LIBRARY_NAME})
    endif()
    if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
        target_link_libraries(test_sparse_array ${CMAKE_THREAD_LIBS_INIT})
    endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
endif(BUILD_UNIT_TESTS)







|















|
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
  message(FATAL_ERROR "No thread library found and thread/mutex support is required by OPJ_USE_THREAD option")
endif(OPJ_USE_THREAD AND NOT Threads_FOUND)

if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
   TARGET_LINK_LIBRARIES(${OPENJPEG_LIBRARY_NAME} ${CMAKE_THREAD_LIBS_INIT})
endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)

if(BUILD_UNIT_TESTS AND UNIX)
    add_executable(bench_dwt bench_dwt.c)
    if(UNIX)
        target_link_libraries(bench_dwt m ${OPENJPEG_LIBRARY_NAME})
    endif()
    if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
        target_link_libraries(bench_dwt ${CMAKE_THREAD_LIBS_INIT})
    endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)

    add_executable(test_sparse_array test_sparse_array.c)
    if(UNIX)
        target_link_libraries(test_sparse_array m ${OPENJPEG_LIBRARY_NAME})
    endif()
    if(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
        target_link_libraries(test_sparse_array ${CMAKE_THREAD_LIBS_INIT})
    endif(OPJ_USE_THREAD AND Threads_FOUND AND CMAKE_USE_PTHREADS_INIT)
endif(BUILD_UNIT_TESTS AND UNIX)
Changes to jni/openjpeg/src/lib/openjp2/bench_dwt.c.
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
}

void init_tilec(opj_tcd_tilecomp_t * l_tilec,
                OPJ_INT32 x0,
                OPJ_INT32 y0,
                OPJ_INT32 x1,
                OPJ_INT32 y1,
                OPJ_UINT32 numresolutions)

{
    opj_tcd_resolution_t* l_res;
    OPJ_UINT32 resno, l_level_no;
    size_t i, nValues;

    memset(l_tilec, 0, sizeof(*l_tilec));
    l_tilec->x0 = x0;
    l_tilec->y0 = y0;
    l_tilec->x1 = x1;
    l_tilec->y1 = y1;
    nValues = (size_t)(l_tilec->x1 - l_tilec->x0) *
              (size_t)(l_tilec->y1 - l_tilec->y0);
    l_tilec->data = (OPJ_INT32*) opj_malloc(sizeof(OPJ_INT32) * nValues);
    for (i = 0; i < nValues; i++) {





        l_tilec->data[i] = getValue((OPJ_UINT32)i);
    }

    l_tilec->numresolutions = numresolutions;

    l_tilec->resolutions = (opj_tcd_resolution_t*) opj_calloc(
                               l_tilec->numresolutions,
                               sizeof(opj_tcd_resolution_t));

    l_level_no = l_tilec->numresolutions;
    l_res = l_tilec->resolutions;








|
>














>
>
>
>
>
|
|
>

>







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
}

void init_tilec(opj_tcd_tilecomp_t * l_tilec,
                OPJ_INT32 x0,
                OPJ_INT32 y0,
                OPJ_INT32 x1,
                OPJ_INT32 y1,
                OPJ_UINT32 numresolutions,
                OPJ_BOOL irreversible)
{
    opj_tcd_resolution_t* l_res;
    OPJ_UINT32 resno, l_level_no;
    size_t i, nValues;

    memset(l_tilec, 0, sizeof(*l_tilec));
    l_tilec->x0 = x0;
    l_tilec->y0 = y0;
    l_tilec->x1 = x1;
    l_tilec->y1 = y1;
    nValues = (size_t)(l_tilec->x1 - l_tilec->x0) *
              (size_t)(l_tilec->y1 - l_tilec->y0);
    l_tilec->data = (OPJ_INT32*) opj_malloc(sizeof(OPJ_INT32) * nValues);
    for (i = 0; i < nValues; i++) {
        OPJ_INT32 val = getValue((OPJ_UINT32)i);
        if (irreversible) {
            OPJ_FLOAT32 fVal = (OPJ_FLOAT32)val;
            memcpy(&l_tilec->data[i], &fVal, sizeof(OPJ_FLOAT32));
        } else {
            l_tilec->data[i] = val;
        }
    }
    l_tilec->numresolutions = numresolutions;
    l_tilec->minimum_num_resolutions = numresolutions;
    l_tilec->resolutions = (opj_tcd_resolution_t*) opj_calloc(
                               l_tilec->numresolutions,
                               sizeof(opj_tcd_resolution_t));

    l_level_no = l_tilec->numresolutions;
    l_res = l_tilec->resolutions;

94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
    opj_free(l_tilec->data);
    opj_free(l_tilec->resolutions);
}

void usage(void)
{
    printf(
        "bench_dwt [-size value] [-check] [-display] [-num_resolutions val]\n");
    printf(
        "          [-offset x y] [-num_threads val]\n");
    exit(1);
}


OPJ_FLOAT64 opj_clock(void)
{
#ifdef _WIN32







|

|







102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    opj_free(l_tilec->data);
    opj_free(l_tilec->resolutions);
}

void usage(void)
{
    printf(
        "bench_dwt [-decode|encode] [-I] [-size value] [-check] [-display]\n");
    printf(
        "          [-num_resolutions val] [-offset x y] [-num_threads val]\n");
    exit(1);
}


OPJ_FLOAT64 opj_clock(void)
{
#ifdef _WIN32
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
    /* (2a) Get the seconds */
    procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
    /* (2b) More precisely! Get the microseconds part ! */
    return (procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) *
            1e-6) ;
#endif
}












int main(int argc, char** argv)
{
    int num_threads = 0;
    opj_tcd_t tcd;
    opj_tcd_image_t tcd_image;
    opj_tcd_tile_t tcd_tile;
    opj_tcd_tilecomp_t tilec;
    opj_image_t image;
    opj_image_comp_t image_comp;
    opj_thread_pool_t* tp;
    OPJ_INT32 i, j, k;
    OPJ_BOOL display = OPJ_FALSE;
    OPJ_BOOL check = OPJ_FALSE;
    OPJ_INT32 size = 16384 - 1;
    OPJ_FLOAT64 start, stop;

    OPJ_UINT32 offset_x = ((OPJ_UINT32)size + 1) / 2 - 1;
    OPJ_UINT32 offset_y = ((OPJ_UINT32)size + 1) / 2 - 1;
    OPJ_UINT32 num_resolutions = 6;



    for (i = 1; i < argc; i++) {




        if (strcmp(argv[i], "-display") == 0) {
            display = OPJ_TRUE;

            check = OPJ_TRUE;
        } else if (strcmp(argv[i], "-check") == 0) {
            check = OPJ_TRUE;
        } else if (strcmp(argv[i], "-size") == 0 && i + 1 < argc) {
            size = atoi(argv[i + 1]);
            i ++;
        } else if (strcmp(argv[i], "-num_threads") == 0 && i + 1 < argc) {
            num_threads = atoi(argv[i + 1]);
            i ++;
        } else if (strcmp(argv[i], "-num_resolutions") == 0 && i + 1 < argc) {







>
>
>
>
>
>
>
>
>
>
>
















>



>
>


>
>
>
>
|

>

|
|







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
    /* (2a) Get the seconds */
    procTime = (OPJ_FLOAT64)(t.ru_utime.tv_sec + t.ru_stime.tv_sec);
    /* (2b) More precisely! Get the microseconds part ! */
    return (procTime + (OPJ_FLOAT64)(t.ru_utime.tv_usec + t.ru_stime.tv_usec) *
            1e-6) ;
#endif
}

static OPJ_FLOAT64 opj_wallclock(void)
{
#ifdef _WIN32
    return opj_clock();
#else
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (OPJ_FLOAT64)tv.tv_sec + 1e-6 * (OPJ_FLOAT64)tv.tv_usec;
#endif
}

int main(int argc, char** argv)
{
    int num_threads = 0;
    opj_tcd_t tcd;
    opj_tcd_image_t tcd_image;
    opj_tcd_tile_t tcd_tile;
    opj_tcd_tilecomp_t tilec;
    opj_image_t image;
    opj_image_comp_t image_comp;
    opj_thread_pool_t* tp;
    OPJ_INT32 i, j, k;
    OPJ_BOOL display = OPJ_FALSE;
    OPJ_BOOL check = OPJ_FALSE;
    OPJ_INT32 size = 16384 - 1;
    OPJ_FLOAT64 start, stop;
    OPJ_FLOAT64 start_wc, stop_wc;
    OPJ_UINT32 offset_x = ((OPJ_UINT32)size + 1) / 2 - 1;
    OPJ_UINT32 offset_y = ((OPJ_UINT32)size + 1) / 2 - 1;
    OPJ_UINT32 num_resolutions = 6;
    OPJ_BOOL bench_decode = OPJ_TRUE;
    OPJ_BOOL irreversible = OPJ_FALSE;

    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-encode") == 0) {
            bench_decode = OPJ_FALSE;
        } else if (strcmp(argv[i], "-decode") == 0) {
            bench_decode = OPJ_TRUE;
        } else if (strcmp(argv[i], "-display") == 0) {
            display = OPJ_TRUE;
        } else if (strcmp(argv[i], "-check") == 0) {
            check = OPJ_TRUE;
        } else if (strcmp(argv[i], "-I") == 0) {
            irreversible = OPJ_TRUE;
        } else if (strcmp(argv[i], "-size") == 0 && i + 1 < argc) {
            size = atoi(argv[i + 1]);
            i ++;
        } else if (strcmp(argv[i], "-num_threads") == 0 && i + 1 < argc) {
            num_threads = atoi(argv[i + 1]);
            i ++;
        } else if (strcmp(argv[i], "-num_resolutions") == 0 && i + 1 < argc) {
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
            offset_x = (OPJ_UINT32)atoi(argv[i + 1]);
            offset_y = (OPJ_UINT32)atoi(argv[i + 2]);
            i += 2;
        } else {
            usage();
        }
    }








    tp = opj_thread_pool_create(num_threads);

    init_tilec(&tilec, (OPJ_INT32)offset_x, (OPJ_INT32)offset_y,
               (OPJ_INT32)offset_x + size, (OPJ_INT32)offset_y + size,
               num_resolutions);

    if (display) {
        printf("Before\n");
        k = 0;
        for (j = 0; j < tilec.y1 - tilec.y0; j++) {
            for (i = 0; i < tilec.x1 - tilec.x0; i++) {



                printf("%d ", tilec.data[k]);

                k ++;
            }
            printf("\n");
        }
    }

    memset(&tcd, 0, sizeof(tcd));







>
>
>
>
>
>
>





|






>
>
>
|
>







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
            offset_x = (OPJ_UINT32)atoi(argv[i + 1]);
            offset_y = (OPJ_UINT32)atoi(argv[i + 2]);
            i += 2;
        } else {
            usage();
        }
    }

    if (irreversible && check) {
        /* Due to irreversible inverse DWT not being symetric of forward */
        /* See BUG_WEIRD_TWO_INVK in dwt.c */
        printf("-I and -check aren't compatible\n");
        exit(1);
    }

    tp = opj_thread_pool_create(num_threads);

    init_tilec(&tilec, (OPJ_INT32)offset_x, (OPJ_INT32)offset_y,
               (OPJ_INT32)offset_x + size, (OPJ_INT32)offset_y + size,
               num_resolutions, irreversible);

    if (display) {
        printf("Before\n");
        k = 0;
        for (j = 0; j < tilec.y1 - tilec.y0; j++) {
            for (i = 0; i < tilec.x1 - tilec.x0; i++) {
                if (irreversible) {
                    printf("%f ", ((OPJ_FLOAT32*)tilec.data)[k]);
                } else {
                    printf("%d ", tilec.data[k]);
                }
                k ++;
            }
            printf("\n");
        }
    }

    memset(&tcd, 0, sizeof(tcd));
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
    image.numcomps = 1;
    image.comps = &image_comp;
    memset(&image_comp, 0, sizeof(image_comp));
    image_comp.dx = 1;
    image_comp.dy = 1;

    start = opj_clock();





    opj_dwt_decode(&tcd, &tilec, tilec.numresolutions);








    stop = opj_clock();



    printf("time for dwt_decode: %.03f s\n", stop - start);


    if (display || check) {
        if (display) {
            printf("After IDWT\n");



            k = 0;
            for (j = 0; j < tilec.y1 - tilec.y0; j++) {
                for (i = 0; i < tilec.x1 - tilec.x0; i++) {



                    printf("%d ", tilec.data[k]);

                    k ++;
                }
                printf("\n");
            }
        }




        opj_dwt_encode(&tilec);





        if (display) {

            printf("After FDWT\n");



            k = 0;
            for (j = 0; j < tilec.y1 - tilec.y0; j++) {
                for (i = 0; i < tilec.x1 - tilec.x0; i++) {



                    printf("%d ", tilec.data[k]);

                    k ++;
                }
                printf("\n");
            }
        }



        if (check) {

            size_t idx;
            size_t nValues = (size_t)(tilec.x1 - tilec.x0) *
                             (size_t)(tilec.y1 - tilec.y0);
            for (idx = 0; idx < nValues; idx++) {
                if (tilec.data[idx] != getValue((OPJ_UINT32)idx)) {
                    printf("Difference found at idx = %u\n", (OPJ_UINT32)idx);
                    exit(1);
                }
            }
        }
    }

    free_tilec(&tilec);

    opj_thread_pool_destroy(tp);
    return 0;
}







>
>
>
>
>
|
>
>
>
>
>
>
>
>

>
>
>
|
>

|
|

>
>
>
|
|
|
>
>
>

>
|
|
|
|
|

>
>
>
|
>
>
>
>
>
|
>
|
>
>
>



>
>
>
|
>






>
>
|
>
|
|
|
|
|
|
|
<









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
    image.numcomps = 1;
    image.comps = &image_comp;
    memset(&image_comp, 0, sizeof(image_comp));
    image_comp.dx = 1;
    image_comp.dy = 1;

    start = opj_clock();
    start_wc = opj_wallclock();
    if (bench_decode) {
        if (irreversible)  {
            opj_dwt_decode_real(&tcd, &tilec, tilec.numresolutions);
        } else {
            opj_dwt_decode(&tcd, &tilec, tilec.numresolutions);
        }
    } else {
        if (irreversible)  {
            opj_dwt_encode_real(&tcd, &tilec);
        } else {
            opj_dwt_encode(&tcd, &tilec);
        }
    }
    stop = opj_clock();
    stop_wc = opj_wallclock();
    printf("time for %s: total = %.03f s, wallclock = %.03f s\n",
           bench_decode ? "dwt_decode" : "dwt_encode",
           stop - start,
           stop_wc - start_wc);

    if (display) {
        if (bench_decode) {
            printf("After IDWT\n");
        } else {
            printf("After FDWT\n");
        }
        k = 0;
        for (j = 0; j < tilec.y1 - tilec.y0; j++) {
            for (i = 0; i < tilec.x1 - tilec.x0; i++) {
                if (irreversible) {
                    printf("%f ", ((OPJ_FLOAT32*)tilec.data)[k]);
                } else {
                    printf("%d ", tilec.data[k]);
                }
                k ++;
            }
            printf("\n");
        }
    }

    if ((display || check) && !irreversible) {

        if (bench_decode) {
            opj_dwt_encode(&tcd, &tilec);
        } else {
            opj_dwt_decode(&tcd, &tilec, tilec.numresolutions);
        }


        if (display && !irreversible) {
            if (bench_decode) {
                printf("After FDWT\n");
            } else {
                printf("After IDWT\n");
            }
            k = 0;
            for (j = 0; j < tilec.y1 - tilec.y0; j++) {
                for (i = 0; i < tilec.x1 - tilec.x0; i++) {
                    if (irreversible) {
                        printf("%f ", ((OPJ_FLOAT32*)tilec.data)[k]);
                    } else {
                        printf("%d ", tilec.data[k]);
                    }
                    k ++;
                }
                printf("\n");
            }
        }

    }

    if (check) {

        size_t idx;
        size_t nValues = (size_t)(tilec.x1 - tilec.x0) *
                         (size_t)(tilec.y1 - tilec.y0);
        for (idx = 0; idx < nValues; idx++) {
            if (tilec.data[idx] != getValue((OPJ_UINT32)idx)) {
                printf("Difference found at idx = %u\n", (OPJ_UINT32)idx);
                exit(1);

            }
        }
    }

    free_tilec(&tilec);

    opj_thread_pool_destroy(tp);
    return 0;
}
Changes to jni/openjpeg/src/lib/openjp2/dwt.c.
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
typedef struct dwt_local {
    OPJ_INT32* mem;
    OPJ_INT32 dn;   /* number of elements in high pass band */
    OPJ_INT32 sn;   /* number of elements in low pass band */
    OPJ_INT32 cas;  /* 0 = start on even coord, 1 = start on odd coord */
} opj_dwt_t;



typedef union {
    OPJ_FLOAT32 f[4];
} opj_v4_t;

typedef struct v4dwt_local {
    opj_v4_t*   wavelet ;
    OPJ_INT32       dn ;  /* number of elements in high pass band */
    OPJ_INT32       sn ;  /* number of elements in low pass band */
    OPJ_INT32       cas ; /* 0 = start on even coord, 1 = start on odd coord */
    OPJ_UINT32      win_l_x0; /* start coord in low pass band */
    OPJ_UINT32      win_l_x1; /* end coord in low pass band */
    OPJ_UINT32      win_h_x0; /* start coord in high pass band */
    OPJ_UINT32      win_h_x1; /* end coord in high pass band */
} opj_v4dwt_t ;


static const OPJ_FLOAT32 opj_dwt_alpha =  1.586134342f; /*  12994 */
static const OPJ_FLOAT32 opj_dwt_beta  =  0.052980118f; /*    434 */
static const OPJ_FLOAT32 opj_dwt_gamma = -0.882911075f; /*  -7233 */
static const OPJ_FLOAT32 opj_dwt_delta = -0.443506852f; /*  -3633 */

static const OPJ_FLOAT32 opj_K      = 1.230174105f; /*  10078 */
static const OPJ_FLOAT32 opj_c13318 = 1.625732422f;

/*@}*/

/**
Virtual function type for wavelet transform in 1-D
*/
typedef void (*DWT1DFN)(const opj_dwt_t* v);

/** @name Local static functions */
/*@{*/

/**
Forward lazy transform (horizontal)
*/
static void opj_dwt_deinterleave_h(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,

                                   OPJ_INT32 sn, OPJ_INT32 cas);
/**
Forward lazy transform (vertical)
*/
static void opj_dwt_deinterleave_v(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
                                   OPJ_INT32 sn, OPJ_INT32 x, OPJ_INT32 cas);
/**
Forward 5-3 wavelet transform in 1-D
*/
static void opj_dwt_encode_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                             OPJ_INT32 cas);
/**
Forward 9-7 wavelet transform in 1-D
*/
static void opj_dwt_encode_1_real(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                                  OPJ_INT32 cas);
/**
Explicit calculation of the Quantization Stepsizes
*/
static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
                                    opj_stepsize_t *bandno_stepsize);
/**
Inverse wavelet transform in 2-D.
*/
static OPJ_BOOL opj_dwt_decode_tile(opj_thread_pool_t* tp,
                                    opj_tcd_tilecomp_t* tilec, OPJ_UINT32 i);

static OPJ_BOOL opj_dwt_decode_partial_tile(
    opj_tcd_tilecomp_t* tilec,
    OPJ_UINT32 numres);



















static OPJ_BOOL opj_dwt_encode_procedure(opj_tcd_tilecomp_t * tilec,
        void (*p_function)(OPJ_INT32 *, OPJ_INT32, OPJ_INT32, OPJ_INT32));





static OPJ_UINT32 opj_dwt_max_resolution(opj_tcd_resolution_t* OPJ_RESTRICT r,
        OPJ_UINT32 i);

/* <summary>                             */
/* Inverse 9-7 wavelet transform in 1-D. */
/* </summary>                            */
static void opj_v4dwt_decode(opj_v4dwt_t* OPJ_RESTRICT dwt);

static void opj_v4dwt_interleave_h(opj_v4dwt_t* OPJ_RESTRICT dwt,
                                   OPJ_FLOAT32* OPJ_RESTRICT a,
                                   OPJ_UINT32 width,
                                   OPJ_UINT32 remaining_height);

static void opj_v4dwt_interleave_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
                                   OPJ_FLOAT32* OPJ_RESTRICT a,
                                   OPJ_UINT32 width,
                                   OPJ_UINT32 nb_elts_read);

#ifdef __SSE__
static void opj_v4dwt_decode_step1_sse(opj_v4_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       const __m128 c);

static void opj_v4dwt_decode_step2_sse(opj_v4_t* l, opj_v4_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       OPJ_UINT32 m, __m128 c);

#else
static void opj_v4dwt_decode_step1(opj_v4_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   const OPJ_FLOAT32 c);

static void opj_v4dwt_decode_step2(opj_v4_t* l, opj_v4_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   OPJ_UINT32 m,
                                   OPJ_FLOAT32 c);

#endif

/*@}*/

/*@}*/

#define OPJ_S(i) a[(i)*2]
#define OPJ_D(i) a[(1+(i)*2)]







>
>

|
|

|
|







|

>
|
|
|
|

|
|



<
<
<
<
<






|
>
|
<
<
<
<
|
|
<
<
<
<



|
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
<
>
>
>
>







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







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
typedef struct dwt_local {
    OPJ_INT32* mem;
    OPJ_INT32 dn;   /* number of elements in high pass band */
    OPJ_INT32 sn;   /* number of elements in low pass band */
    OPJ_INT32 cas;  /* 0 = start on even coord, 1 = start on odd coord */
} opj_dwt_t;

#define NB_ELTS_V8  8

typedef union {
    OPJ_FLOAT32 f[NB_ELTS_V8];
} opj_v8_t;

typedef struct v8dwt_local {
    opj_v8_t*   wavelet ;
    OPJ_INT32       dn ;  /* number of elements in high pass band */
    OPJ_INT32       sn ;  /* number of elements in low pass band */
    OPJ_INT32       cas ; /* 0 = start on even coord, 1 = start on odd coord */
    OPJ_UINT32      win_l_x0; /* start coord in low pass band */
    OPJ_UINT32      win_l_x1; /* end coord in low pass band */
    OPJ_UINT32      win_h_x0; /* start coord in high pass band */
    OPJ_UINT32      win_h_x1; /* end coord in high pass band */
} opj_v8dwt_t ;

/* From table F.4 from the standard */
static const OPJ_FLOAT32 opj_dwt_alpha =  -1.586134342f;
static const OPJ_FLOAT32 opj_dwt_beta  =  -0.052980118f;
static const OPJ_FLOAT32 opj_dwt_gamma = 0.882911075f;
static const OPJ_FLOAT32 opj_dwt_delta = 0.443506852f;

static const OPJ_FLOAT32 opj_K      = 1.230174105f;
static const OPJ_FLOAT32 opj_invK   = (OPJ_FLOAT32)(1.0 / 1.230174105);

/*@}*/






/** @name Local static functions */
/*@{*/

/**
Forward lazy transform (horizontal)
*/
static void opj_dwt_deinterleave_h(const OPJ_INT32 * OPJ_RESTRICT a,
                                   OPJ_INT32 * OPJ_RESTRICT b,
                                   OPJ_INT32 dn,




                                   OPJ_INT32 sn, OPJ_INT32 cas);





/**
Forward 9-7 wavelet transform in 1-D
*/
static void opj_dwt_encode_1_real(void *a, OPJ_INT32 dn, OPJ_INT32 sn,
                                  OPJ_INT32 cas);
/**
Explicit calculation of the Quantization Stepsizes
*/
static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
                                    opj_stepsize_t *bandno_stepsize);
/**
Inverse wavelet transform in 2-D.
*/
static OPJ_BOOL opj_dwt_decode_tile(opj_thread_pool_t* tp,
                                    opj_tcd_tilecomp_t* tilec, OPJ_UINT32 i);

static OPJ_BOOL opj_dwt_decode_partial_tile(
    opj_tcd_tilecomp_t* tilec,
    OPJ_UINT32 numres);

/* Forward transform, for the vertical pass, processing cols columns */
/* where cols <= NB_ELTS_V8 */
/* Where void* is a OPJ_INT32* for 5x3 and OPJ_FLOAT32* for 9x7 */
typedef void (*opj_encode_and_deinterleave_v_fnptr_type)(
    void *array,
    void *tmp,
    OPJ_UINT32 height,
    OPJ_BOOL even,
    OPJ_UINT32 stride_width,
    OPJ_UINT32 cols);

/* Where void* is a OPJ_INT32* for 5x3 and OPJ_FLOAT32* for 9x7 */
typedef void (*opj_encode_and_deinterleave_h_one_row_fnptr_type)(
    void *row,
    void *tmp,
    OPJ_UINT32 width,
    OPJ_BOOL even);

static OPJ_BOOL opj_dwt_encode_procedure(opj_thread_pool_t* tp,

        opj_tcd_tilecomp_t * tilec,
        opj_encode_and_deinterleave_v_fnptr_type p_encode_and_deinterleave_v,
        opj_encode_and_deinterleave_h_one_row_fnptr_type
        p_encode_and_deinterleave_h_one_row);

static OPJ_UINT32 opj_dwt_max_resolution(opj_tcd_resolution_t* OPJ_RESTRICT r,
        OPJ_UINT32 i);

/* <summary>                             */
/* Inverse 9-7 wavelet transform in 1-D. */
/* </summary>                            */





































/*@}*/

/*@}*/

#define OPJ_S(i) a[(i)*2]
#define OPJ_D(i) a[(1+(i)*2)]
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
   local functions
==========================================================
*/

/* <summary>                             */
/* Forward lazy transform (horizontal).  */
/* </summary>                            */
static void opj_dwt_deinterleave_h(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,


                                   OPJ_INT32 sn, OPJ_INT32 cas)
{
    OPJ_INT32 i;
    OPJ_INT32 * l_dest = b;
    OPJ_INT32 * l_src = a + cas;

    for (i = 0; i < sn; ++i) {
        *l_dest++ = *l_src;
        l_src += 2;
    }

    l_dest = b + sn;
    l_src = a + 1 - cas;

    for (i = 0; i < dn; ++i)  {
        *l_dest++ = *l_src;
        l_src += 2;
    }
}

/* <summary>                             */
/* Forward lazy transform (vertical).    */
/* </summary>                            */
static void opj_dwt_deinterleave_v(OPJ_INT32 *a, OPJ_INT32 *b, OPJ_INT32 dn,
                                   OPJ_INT32 sn, OPJ_INT32 x, OPJ_INT32 cas)
{
    OPJ_INT32 i = sn;
    OPJ_INT32 * l_dest = b;
    OPJ_INT32 * l_src = a + cas;

    while (i--) {
        *l_dest = *l_src;
        l_dest += x;
        l_src += 2;
    } /* b[i*x]=a[2*i+cas]; */

    l_dest = b + (OPJ_SIZE_T)sn * (OPJ_SIZE_T)x;
    l_src = a + 1 - cas;

    i = dn;
    while (i--) {
        *l_dest = *l_src;
        l_dest += x;
        l_src += 2;
    } /*b[(sn+i)*x]=a[(2*i+1-cas)];*/
}

#ifdef STANDARD_SLOW_VERSION
/* <summary>                             */
/* Inverse lazy transform (horizontal).  */
/* </summary>                            */
static void opj_dwt_interleave_h(const opj_dwt_t* h, OPJ_INT32 *a)
{
    OPJ_INT32 *ai = a;
    OPJ_INT32 *bi = h->mem + h->cas;
    OPJ_INT32  i    = h->sn;
    while (i--) {
        *bi = *(ai++);
        bi += 2;
    }
    ai  = a + h->sn;
    bi  = h->mem + 1 - h->cas;
    i   = h->dn ;
    while (i--) {
        *bi = *(ai++);
        bi += 2;
    }
}

/* <summary>                             */
/* Inverse lazy transform (vertical).    */
/* </summary>                            */
static void opj_dwt_interleave_v(const opj_dwt_t* v, OPJ_INT32 *a, OPJ_INT32 x)
{
    OPJ_INT32 *ai = a;
    OPJ_INT32 *bi = v->mem + v->cas;
    OPJ_INT32  i = v->sn;
    while (i--) {
        *bi = *ai;
        bi += 2;
        ai += x;
    }
    ai = a + (v->sn * (OPJ_SIZE_T)x);
    bi = v->mem + 1 - v->cas;
    i = v->dn ;
    while (i--) {
        *bi = *ai;
        bi += 2;
        ai += x;
    }
}

#endif /* STANDARD_SLOW_VERSION */

/* <summary>                            */
/* Forward 5-3 wavelet transform in 1-D. */
/* </summary>                           */
static void opj_dwt_encode_1(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                             OPJ_INT32 cas)
{
    OPJ_INT32 i;

    if (!cas) {
        if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
            for (i = 0; i < dn; i++) {
                OPJ_D(i) -= (OPJ_S_(i) + OPJ_S_(i + 1)) >> 1;
            }
            for (i = 0; i < sn; i++) {
                OPJ_S(i) += (OPJ_D_(i - 1) + OPJ_D_(i) + 2) >> 2;
            }
        }
    } else {
        if (!sn && dn == 1) {       /* NEW :  CASE ONE ELEMENT */
            OPJ_S(0) *= 2;
        } else {
            for (i = 0; i < dn; i++) {
                OPJ_S(i) -= (OPJ_DD_(i) + OPJ_DD_(i - 1)) >> 1;
            }
            for (i = 0; i < sn; i++) {
                OPJ_D(i) += (OPJ_SS_(i) + OPJ_SS_(i + 1) + 2) >> 2;
            }
        }
    }
}

#ifdef STANDARD_SLOW_VERSION
/* <summary>                            */
/* Inverse 5-3 wavelet transform in 1-D. */
/* </summary>                           */
static void opj_dwt_decode_1_(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                              OPJ_INT32 cas)
{







|
>
>



|
|















<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<






|




















|



















<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







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
   local functions
==========================================================
*/

/* <summary>                             */
/* Forward lazy transform (horizontal).  */
/* </summary>                            */
static void opj_dwt_deinterleave_h(const OPJ_INT32 * OPJ_RESTRICT a,
                                   OPJ_INT32 * OPJ_RESTRICT b,
                                   OPJ_INT32 dn,
                                   OPJ_INT32 sn, OPJ_INT32 cas)
{
    OPJ_INT32 i;
    OPJ_INT32 * OPJ_RESTRICT l_dest = b;
    const OPJ_INT32 * OPJ_RESTRICT l_src = a + cas;

    for (i = 0; i < sn; ++i) {
        *l_dest++ = *l_src;
        l_src += 2;
    }

    l_dest = b + sn;
    l_src = a + 1 - cas;

    for (i = 0; i < dn; ++i)  {
        *l_dest++ = *l_src;
        l_src += 2;
    }
}




























#ifdef STANDARD_SLOW_VERSION
/* <summary>                             */
/* Inverse lazy transform (horizontal).  */
/* </summary>                            */
static void opj_dwt_interleave_h(const opj_dwt_t* h, OPJ_INT32 *a)
{
    const OPJ_INT32 *ai = a;
    OPJ_INT32 *bi = h->mem + h->cas;
    OPJ_INT32  i    = h->sn;
    while (i--) {
        *bi = *(ai++);
        bi += 2;
    }
    ai  = a + h->sn;
    bi  = h->mem + 1 - h->cas;
    i   = h->dn ;
    while (i--) {
        *bi = *(ai++);
        bi += 2;
    }
}

/* <summary>                             */
/* Inverse lazy transform (vertical).    */
/* </summary>                            */
static void opj_dwt_interleave_v(const opj_dwt_t* v, OPJ_INT32 *a, OPJ_INT32 x)
{
    const OPJ_INT32 *ai = a;
    OPJ_INT32 *bi = v->mem + v->cas;
    OPJ_INT32  i = v->sn;
    while (i--) {
        *bi = *ai;
        bi += 2;
        ai += x;
    }
    ai = a + (v->sn * (OPJ_SIZE_T)x);
    bi = v->mem + 1 - v->cas;
    i = v->dn ;
    while (i--) {
        *bi = *ai;
        bi += 2;
        ai += x;
    }
}

#endif /* STANDARD_SLOW_VERSION */
































#ifdef STANDARD_SLOW_VERSION
/* <summary>                            */
/* Inverse 5-3 wavelet transform in 1-D. */
/* </summary>                           */
static void opj_dwt_decode_1_(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                              OPJ_INT32 cas)
{
1029
1030
1031
1032
1033
1034
1035




1036













































1037

1038




























1039
1040
1041
1042

1043

1044
1045
1046
1047

1048

1049
1050
1051

1052
1053
1054


1055
1056
1057


1058










1059
1060

1061



1062
1063
1064

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086

1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
































































































































































































































































































































































































































































































































































































































1105
1106
1107
1108
1109
1110



1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123


1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147




1148

1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163



1164













1165




1166

1167
1168

1169


1170





1171



1172


1173










1174



1175
1176
1177


1178
1179






1180

1181
1182

1183


1184




























1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198

1199
1200


1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250

1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
            }
            return;
        }
    }
#endif
}



















































/* <summary>                             */

/* Forward 9-7 wavelet transform in 1-D. */




























/* </summary>                            */
static void opj_dwt_encode_1_real(OPJ_INT32 *a, OPJ_INT32 dn, OPJ_INT32 sn,
                                  OPJ_INT32 cas)
{

    OPJ_INT32 i;

    if (!cas) {
        if ((dn > 0) || (sn > 1)) { /* NEW :  CASE ONE ELEMENT */
            for (i = 0; i < dn; i++) {
                OPJ_D(i) -= opj_int_fix_mul(OPJ_S_(i) + OPJ_S_(i + 1), 12993);

            }

            for (i = 0; i < sn; i++) {
                OPJ_S(i) -= opj_int_fix_mul(OPJ_D_(i - 1) + OPJ_D_(i), 434);
            }

            for (i = 0; i < dn; i++) {
                OPJ_D(i) += opj_int_fix_mul(OPJ_S_(i) + OPJ_S_(i + 1), 7233);
            }


            for (i = 0; i < sn; i++) {
                OPJ_S(i) += opj_int_fix_mul(OPJ_D_(i - 1) + OPJ_D_(i), 3633);
            }


            for (i = 0; i < dn; i++) {










                OPJ_D(i) = opj_int_fix_mul(OPJ_D(i), 5038);    /*5038 */
            }

            for (i = 0; i < sn; i++) {



                OPJ_S(i) = opj_int_fix_mul(OPJ_S(i), 6659);    /*6660 */
            }
        }

    } else {
        if ((sn > 0) || (dn > 1)) { /* NEW :  CASE ONE ELEMENT */
            for (i = 0; i < dn; i++) {
                OPJ_S(i) -= opj_int_fix_mul(OPJ_DD_(i) + OPJ_DD_(i - 1), 12993);
            }
            for (i = 0; i < sn; i++) {
                OPJ_D(i) -= opj_int_fix_mul(OPJ_SS_(i) + OPJ_SS_(i + 1), 434);
            }
            for (i = 0; i < dn; i++) {
                OPJ_S(i) += opj_int_fix_mul(OPJ_DD_(i) + OPJ_DD_(i - 1), 7233);
            }
            for (i = 0; i < sn; i++) {
                OPJ_D(i) += opj_int_fix_mul(OPJ_SS_(i) + OPJ_SS_(i + 1), 3633);
            }
            for (i = 0; i < dn; i++) {
                OPJ_S(i) = opj_int_fix_mul(OPJ_S(i), 5038);    /*5038 */
            }
            for (i = 0; i < sn; i++) {
                OPJ_D(i) = opj_int_fix_mul(OPJ_D(i), 6659);    /*6660 */
            }
        }
    }

}

static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
                                    opj_stepsize_t *bandno_stepsize)
{
    OPJ_INT32 p, n;
    p = opj_int_floorlog2(stepsize) - 13;
    n = 11 - opj_int_floorlog2(stepsize);
    bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
    bandno_stepsize->expn = numbps - p;
}

/*
==========================================================
   DWT interface
==========================================================
*/


































































































































































































































































































































































































































































































































































































































/* <summary>                            */
/* Forward 5-3 wavelet transform in 2-D. */
/* </summary>                           */
static INLINE OPJ_BOOL opj_dwt_encode_procedure(opj_tcd_tilecomp_t * tilec,
        void (*p_function)(OPJ_INT32 *, OPJ_INT32, OPJ_INT32, OPJ_INT32))



{
    OPJ_INT32 i, j, k;
    OPJ_INT32 *a = 00;
    OPJ_INT32 *aj = 00;
    OPJ_INT32 *bj = 00;
    OPJ_INT32 w, l;

    OPJ_INT32 rw;           /* width of the resolution level computed   */
    OPJ_INT32 rh;           /* height of the resolution level computed  */
    OPJ_SIZE_T l_data_size;

    opj_tcd_resolution_t * l_cur_res = 0;
    opj_tcd_resolution_t * l_last_res = 0;



    w = tilec->x1 - tilec->x0;
    l = (OPJ_INT32)tilec->numresolutions - 1;
    a = tilec->data;

    l_cur_res = tilec->resolutions + l;
    l_last_res = l_cur_res - 1;

    l_data_size = opj_dwt_max_resolution(tilec->resolutions, tilec->numresolutions);
    /* overflow check */
    if (l_data_size > (SIZE_MAX / sizeof(OPJ_INT32))) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    l_data_size *= sizeof(OPJ_INT32);
    bj = (OPJ_INT32*)opj_malloc(l_data_size);
    /* l_data_size is equal to 0 when numresolutions == 1 but bj is not used */
    /* in that case, so do not error out */
    if (l_data_size != 0 && ! bj) {
        return OPJ_FALSE;
    }
    i = l;

    while (i--) {




        OPJ_INT32 rw1;      /* width of the resolution level once lower than computed one                                       */

        OPJ_INT32 rh1;      /* height of the resolution level once lower than computed one                                      */
        OPJ_INT32 cas_col;  /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
        OPJ_INT32 cas_row;  /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
        OPJ_INT32 dn, sn;

        rw  = l_cur_res->x1 - l_cur_res->x0;
        rh  = l_cur_res->y1 - l_cur_res->y0;
        rw1 = l_last_res->x1 - l_last_res->x0;
        rh1 = l_last_res->y1 - l_last_res->y0;

        cas_row = l_cur_res->x0 & 1;
        cas_col = l_cur_res->y0 & 1;

        sn = rh1;
        dn = rh - rh1;



        for (j = 0; j < rw; ++j) {













            aj = a + j;




            for (k = 0; k < rh; ++k) {

                bj[k] = aj[k * w];
            }




            (*p_function)(bj, dn, sn, cas_col);









            opj_dwt_deinterleave_v(bj, aj, dn, sn, w, cas_col);


        }














        sn = rw1;
        dn = rw - rw1;



        for (j = 0; j < rh; j++) {
            aj = a + j * w;






            for (k = 0; k < rw; k++) {

                bj[k] = aj[k];
            }

            (*p_function)(bj, dn, sn, cas_row);


            opj_dwt_deinterleave_h(bj, aj, dn, sn, cas_row);




























        }

        l_cur_res = l_last_res;

        --l_last_res;
    }

    opj_free(bj);
    return OPJ_TRUE;
}

/* Forward 5-3 wavelet transform in 2-D. */
/* </summary>                           */
OPJ_BOOL opj_dwt_encode(opj_tcd_tilecomp_t * tilec)

{
    return opj_dwt_encode_procedure(tilec, opj_dwt_encode_1);


}

/* <summary>                            */
/* Inverse 5-3 wavelet transform in 2-D. */
/* </summary>                           */
OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd, opj_tcd_tilecomp_t* tilec,
                        OPJ_UINT32 numres)
{
    if (p_tcd->whole_tile_decoding) {
        return opj_dwt_decode_tile(p_tcd->thread_pool, tilec, numres);
    } else {
        return opj_dwt_decode_partial_tile(tilec, numres);
    }
}


/* <summary>                          */
/* Get gain of 5-3 wavelet transform. */
/* </summary>                         */
OPJ_UINT32 opj_dwt_getgain(OPJ_UINT32 orient)
{
    if (orient == 0) {
        return 0;
    }
    if (orient == 1 || orient == 2) {
        return 1;
    }
    return 2;
}

/* <summary>                */
/* Get norm of 5-3 wavelet. */
/* </summary>               */
OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient)
{
    /* FIXME ! This is just a band-aid to avoid a buffer overflow */
    /* but the array should really be extended up to 33 resolution levels */
    /* See https://github.com/uclouvain/openjpeg/issues/493 */
    if (orient == 0 && level >= 10) {
        level = 9;
    } else if (orient > 0 && level >= 9) {
        level = 8;
    }
    return opj_dwt_norms[orient][level];
}

/* <summary>                             */
/* Forward 9-7 wavelet transform in 2-D. */
/* </summary>                            */
OPJ_BOOL opj_dwt_encode_real(opj_tcd_tilecomp_t * tilec)

{
    return opj_dwt_encode_procedure(tilec, opj_dwt_encode_1_real);
}

/* <summary>                          */
/* Get gain of 9-7 wavelet transform. */
/* </summary>                         */
OPJ_UINT32 opj_dwt_getgain_real(OPJ_UINT32 orient)
{
    (void)orient;
    return 0;
}

/* <summary>                */
/* Get norm of 9-7 wavelet. */
/* </summary>               */
OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient)
{







>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|


>
|
>
|
<
|
<
>
|
>
|
<
|
>
|
|
<
>
>
|
|
<
>
>
|
>
>
>
>
>
>
>
>
>
>
|
<
>
|
>
>
>
|
<
<
>

|
<
|
<
<
|
<
<
<
<
<
<
<
<
|
<
<
|
|
<
<
>


















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|
>
>
>

|
|
|
|
<

<
<




>
>

|

<






|



|
|








>
>
>
>
|
>
|




|
|
|
|




|
|
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
|
>
|

>

>
>
|
>
>
>
>
>
|
>
>
>
|
>
>
|
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
|

>
>
|
|
>
>
>
>
>
>
|
>
|

>
|
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







|





|
>

|
>
>















<
<
<
<
<
<
<
<
<
<
<
<
<
<
<



















|
>

|
<
|
<
<
<
|
<
<
<







949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044

1045

1046
1047
1048
1049

1050
1051
1052
1053

1054
1055
1056
1057

1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071

1072
1073
1074
1075
1076
1077


1078
1079
1080

1081


1082








1083


1084
1085


1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726

1727


1728
1729
1730
1731
1732
1733
1734
1735
1736

1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919















1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942

1943



1944



1945
1946
1947
1948
1949
1950
1951
            }
            return;
        }
    }
#endif
}

#if 0
static void opj_dwt_encode_step1(OPJ_FLOAT32* fw,
                                 OPJ_UINT32 end,
                                 const OPJ_FLOAT32 c)
{
    OPJ_UINT32 i = 0;
    for (; i < end; ++i) {
        fw[0] *= c;
        fw += 2;
    }
}
#else
static void opj_dwt_encode_step1_combined(OPJ_FLOAT32* fw,
        OPJ_UINT32 iters_c1,
        OPJ_UINT32 iters_c2,
        const OPJ_FLOAT32 c1,
        const OPJ_FLOAT32 c2)
{
    OPJ_UINT32 i = 0;
    const OPJ_UINT32 iters_common =  opj_uint_min(iters_c1, iters_c2);
    assert((((OPJ_SIZE_T)fw) & 0xf) == 0);
    assert(opj_int_abs((OPJ_INT32)iters_c1 - (OPJ_INT32)iters_c2) <= 1);
    for (; i + 3 < iters_common; i += 4) {
#ifdef __SSE__
        const __m128 vcst = _mm_set_ps(c2, c1, c2, c1);
        *(__m128*)fw = _mm_mul_ps(*(__m128*)fw, vcst);
        *(__m128*)(fw + 4) = _mm_mul_ps(*(__m128*)(fw + 4), vcst);
#else
        fw[0] *= c1;
        fw[1] *= c2;
        fw[2] *= c1;
        fw[3] *= c2;
        fw[4] *= c1;
        fw[5] *= c2;
        fw[6] *= c1;
        fw[7] *= c2;
#endif
        fw += 8;
    }
    for (; i < iters_common; i++) {
        fw[0] *= c1;
        fw[1] *= c2;
        fw += 2;
    }
    if (i < iters_c1) {
        fw[0] *= c1;
    } else if (i < iters_c2) {
        fw[1] *= c2;
    }
}

#endif

static void opj_dwt_encode_step2(OPJ_FLOAT32* fl, OPJ_FLOAT32* fw,
                                 OPJ_UINT32 end,
                                 OPJ_UINT32 m,
                                 OPJ_FLOAT32 c)
{
    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);
    if (imax > 0) {
        fw[-1] += (fl[0] + fw[0]) * c;
        fw += 2;
        i = 1;
        for (; i + 3 < imax; i += 4) {
            fw[-1] += (fw[-2] + fw[0]) * c;
            fw[1] += (fw[0] + fw[2]) * c;
            fw[3] += (fw[2] + fw[4]) * c;
            fw[5] += (fw[4] + fw[6]) * c;
            fw += 8;
        }
        for (; i < imax; ++i) {
            fw[-1] += (fw[-2] + fw[0]) * c;
            fw += 2;
        }
    }
    if (m < end) {
        assert(m + 1 == end);
        fw[-1] += (2 * fw[-2]) * c;
    }
}

static void opj_dwt_encode_1_real(void *aIn, OPJ_INT32 dn, OPJ_INT32 sn,
                                  OPJ_INT32 cas)
{
    OPJ_FLOAT32* w = (OPJ_FLOAT32*)aIn;
    OPJ_INT32 a, b;
    assert(dn + sn > 1);
    if (cas == 0) {

        a = 0;

        b = 1;
    } else {
        a = 1;
        b = 0;

    }
    opj_dwt_encode_step2(w + a, w + b + 1,
                         (OPJ_UINT32)dn,
                         (OPJ_UINT32)opj_int_min(dn, sn - b),

                         opj_dwt_alpha);
    opj_dwt_encode_step2(w + b, w + a + 1,
                         (OPJ_UINT32)sn,
                         (OPJ_UINT32)opj_int_min(sn, dn - a),

                         opj_dwt_beta);
    opj_dwt_encode_step2(w + a, w + b + 1,
                         (OPJ_UINT32)dn,
                         (OPJ_UINT32)opj_int_min(dn, sn - b),
                         opj_dwt_gamma);
    opj_dwt_encode_step2(w + b, w + a + 1,
                         (OPJ_UINT32)sn,
                         (OPJ_UINT32)opj_int_min(sn, dn - a),
                         opj_dwt_delta);
#if 0
    opj_dwt_encode_step1(w + b, (OPJ_UINT32)dn,
                         opj_K);
    opj_dwt_encode_step1(w + a, (OPJ_UINT32)sn,
                         opj_invK);

#else
    if (a == 0) {
        opj_dwt_encode_step1_combined(w,
                                      (OPJ_UINT32)sn,
                                      (OPJ_UINT32)dn,
                                      opj_invK,


                                      opj_K);
    } else {
        opj_dwt_encode_step1_combined(w,

                                      (OPJ_UINT32)dn,


                                      (OPJ_UINT32)sn,








                                      opj_K,


                                      opj_invK);
    }


#endif
}

static void opj_dwt_encode_stepsize(OPJ_INT32 stepsize, OPJ_INT32 numbps,
                                    opj_stepsize_t *bandno_stepsize)
{
    OPJ_INT32 p, n;
    p = opj_int_floorlog2(stepsize) - 13;
    n = 11 - opj_int_floorlog2(stepsize);
    bandno_stepsize->mant = (n < 0 ? stepsize >> -n : stepsize << n) & 0x7ff;
    bandno_stepsize->expn = numbps - p;
}

/*
==========================================================
   DWT interface
==========================================================
*/

/** Process one line for the horizontal pass of the 5x3 forward transform */
static
void opj_dwt_encode_and_deinterleave_h_one_row(void* rowIn,
        void* tmpIn,
        OPJ_UINT32 width,
        OPJ_BOOL even)
{
    OPJ_INT32* OPJ_RESTRICT row = (OPJ_INT32*)rowIn;
    OPJ_INT32* OPJ_RESTRICT tmp = (OPJ_INT32*)tmpIn;
    const OPJ_INT32 sn = (OPJ_INT32)((width + (even ? 1 : 0)) >> 1);
    const OPJ_INT32 dn = (OPJ_INT32)(width - (OPJ_UINT32)sn);

    if (even) {
        if (width > 1) {
            OPJ_INT32 i;
            for (i = 0; i < sn - 1; i++) {
                tmp[sn + i] = row[2 * i + 1] - ((row[(i) * 2] + row[(i + 1) * 2]) >> 1);
            }
            if ((width % 2) == 0) {
                tmp[sn + i] = row[2 * i + 1] - row[(i) * 2];
            }
            row[0] += (tmp[sn] + tmp[sn] + 2) >> 2;
            for (i = 1; i < dn; i++) {
                row[i] = row[2 * i] + ((tmp[sn + (i - 1)] + tmp[sn + i] + 2) >> 2);
            }
            if ((width % 2) == 1) {
                row[i] = row[2 * i] + ((tmp[sn + (i - 1)] + tmp[sn + (i - 1)] + 2) >> 2);
            }
            memcpy(row + sn, tmp + sn, (OPJ_SIZE_T)dn * sizeof(OPJ_INT32));
        }
    } else {
        if (width == 1) {
            row[0] *= 2;
        } else {
            OPJ_INT32 i;
            tmp[sn + 0] = row[0] - row[1];
            for (i = 1; i < sn; i++) {
                tmp[sn + i] = row[2 * i] - ((row[2 * i + 1] + row[2 * (i - 1) + 1]) >> 1);
            }
            if ((width % 2) == 1) {
                tmp[sn + i] = row[2 * i] - row[2 * (i - 1) + 1];
            }

            for (i = 0; i < dn - 1; i++) {
                row[i] = row[2 * i + 1] + ((tmp[sn + i] + tmp[sn + i + 1] + 2) >> 2);
            }
            if ((width % 2) == 0) {
                row[i] = row[2 * i + 1] + ((tmp[sn + i] + tmp[sn + i] + 2) >> 2);
            }
            memcpy(row + sn, tmp + sn, (OPJ_SIZE_T)dn * sizeof(OPJ_INT32));
        }
    }
}

/** Process one line for the horizontal pass of the 9x7 forward transform */
static
void opj_dwt_encode_and_deinterleave_h_one_row_real(void* rowIn,
        void* tmpIn,
        OPJ_UINT32 width,
        OPJ_BOOL even)
{
    OPJ_FLOAT32* OPJ_RESTRICT row = (OPJ_FLOAT32*)rowIn;
    OPJ_FLOAT32* OPJ_RESTRICT tmp = (OPJ_FLOAT32*)tmpIn;
    const OPJ_INT32 sn = (OPJ_INT32)((width + (even ? 1 : 0)) >> 1);
    const OPJ_INT32 dn = (OPJ_INT32)(width - (OPJ_UINT32)sn);
    if (width == 1) {
        return;
    }
    memcpy(tmp, row, width * sizeof(OPJ_FLOAT32));
    opj_dwt_encode_1_real(tmp, dn, sn, even ? 0 : 1);
    opj_dwt_deinterleave_h((OPJ_INT32 * OPJ_RESTRICT)tmp,
                           (OPJ_INT32 * OPJ_RESTRICT)row,
                           dn, sn, even ? 0 : 1);
}

typedef struct {
    opj_dwt_t h;
    OPJ_UINT32 rw; /* Width of the resolution to process */
    OPJ_UINT32 w; /* Width of tiledp */
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
    opj_encode_and_deinterleave_h_one_row_fnptr_type p_function;
} opj_dwt_encode_h_job_t;

static void opj_dwt_encode_h_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt_encode_h_job_t* job;
    (void)tls;

    job = (opj_dwt_encode_h_job_t*)user_data;
    for (j = job->min_j; j < job->max_j; j++) {
        OPJ_INT32* OPJ_RESTRICT aj = job->tiledp + j * job->w;
        (*job->p_function)(aj, job->h.mem, job->rw,
                           job->h.cas == 0 ? OPJ_TRUE : OPJ_FALSE);
    }

    opj_aligned_free(job->h.mem);
    opj_free(job);
}

typedef struct {
    opj_dwt_t v;
    OPJ_UINT32 rh;
    OPJ_UINT32 w;
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
    opj_encode_and_deinterleave_v_fnptr_type p_encode_and_deinterleave_v;
} opj_dwt_encode_v_job_t;

static void opj_dwt_encode_v_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt_encode_v_job_t* job;
    (void)tls;

    job = (opj_dwt_encode_v_job_t*)user_data;
    for (j = job->min_j; j + NB_ELTS_V8 - 1 < job->max_j; j += NB_ELTS_V8) {
        (*job->p_encode_and_deinterleave_v)(job->tiledp + j,
                                            job->v.mem,
                                            job->rh,
                                            job->v.cas == 0,
                                            job->w,
                                            NB_ELTS_V8);
    }
    if (j < job->max_j) {
        (*job->p_encode_and_deinterleave_v)(job->tiledp + j,
                                            job->v.mem,
                                            job->rh,
                                            job->v.cas == 0,
                                            job->w,
                                            job->max_j - j);
    }

    opj_aligned_free(job->v.mem);
    opj_free(job);
}

/** Fetch up to cols <= NB_ELTS_V8 for each line, and put them in tmpOut */
/* that has a NB_ELTS_V8 interleave factor. */
static void opj_dwt_fetch_cols_vertical_pass(const void *arrayIn,
        void *tmpOut,
        OPJ_UINT32 height,
        OPJ_UINT32 stride_width,
        OPJ_UINT32 cols)
{
    const OPJ_INT32* OPJ_RESTRICT array = (const OPJ_INT32 * OPJ_RESTRICT)arrayIn;
    OPJ_INT32* OPJ_RESTRICT tmp = (OPJ_INT32 * OPJ_RESTRICT)tmpOut;
    if (cols == NB_ELTS_V8) {
        OPJ_UINT32 k;
        for (k = 0; k < height; ++k) {
            memcpy(tmp + NB_ELTS_V8 * k,
                   array + k * stride_width,
                   NB_ELTS_V8 * sizeof(OPJ_INT32));
        }
    } else {
        OPJ_UINT32 k;
        for (k = 0; k < height; ++k) {
            OPJ_UINT32 c;
            for (c = 0; c < cols; c++) {
                tmp[NB_ELTS_V8 * k + c] = array[c + k * stride_width];
            }
            for (; c < NB_ELTS_V8; c++) {
                tmp[NB_ELTS_V8 * k + c] = 0;
            }
        }
    }
}

/* Deinterleave result of forward transform, where cols <= NB_ELTS_V8 */
/* and src contains NB_ELTS_V8 consecutive values for up to NB_ELTS_V8 */
/* columns. */
static INLINE void opj_dwt_deinterleave_v_cols(
    const OPJ_INT32 * OPJ_RESTRICT src,
    OPJ_INT32 * OPJ_RESTRICT dst,
    OPJ_INT32 dn,
    OPJ_INT32 sn,
    OPJ_UINT32 stride_width,
    OPJ_INT32 cas,
    OPJ_UINT32 cols)
{
    OPJ_INT32 k;
    OPJ_INT32 i = sn;
    OPJ_INT32 * OPJ_RESTRICT l_dest = dst;
    const OPJ_INT32 * OPJ_RESTRICT l_src = src + cas * NB_ELTS_V8;
    OPJ_UINT32 c;

    for (k = 0; k < 2; k++) {
        while (i--) {
            if (cols == NB_ELTS_V8) {
                memcpy(l_dest, l_src, NB_ELTS_V8 * sizeof(OPJ_INT32));
            } else {
                c = 0;
                switch (cols) {
                case 7:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                case 6:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                case 5:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                case 4:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                case 3:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                case 2:
                    l_dest[c] = l_src[c];
                    c++; /* fallthru */
                default:
                    l_dest[c] = l_src[c];
                    break;
                }
            }
            l_dest += stride_width;
            l_src += 2 * NB_ELTS_V8;
        }

        l_dest = dst + (OPJ_SIZE_T)sn * (OPJ_SIZE_T)stride_width;
        l_src = src + (1 - cas) * NB_ELTS_V8;
        i = dn;
    }
}


/* Forward 5-3 transform, for the vertical pass, processing cols columns */
/* where cols <= NB_ELTS_V8 */
static void opj_dwt_encode_and_deinterleave_v(
    void *arrayIn,
    void *tmpIn,
    OPJ_UINT32 height,
    OPJ_BOOL even,
    OPJ_UINT32 stride_width,
    OPJ_UINT32 cols)
{
    OPJ_INT32* OPJ_RESTRICT array = (OPJ_INT32 * OPJ_RESTRICT)arrayIn;
    OPJ_INT32* OPJ_RESTRICT tmp = (OPJ_INT32 * OPJ_RESTRICT)tmpIn;
    const OPJ_UINT32 sn = (height + (even ? 1 : 0)) >> 1;
    const OPJ_UINT32 dn = height - sn;

    opj_dwt_fetch_cols_vertical_pass(arrayIn, tmpIn, height, stride_width, cols);

#define OPJ_Sc(i) tmp[(i)*2* NB_ELTS_V8 + c]
#define OPJ_Dc(i) tmp[((1+(i)*2))* NB_ELTS_V8 + c]

#ifdef __SSE2__
    if (height == 1) {
        if (!even) {
            OPJ_UINT32 c;
            for (c = 0; c < NB_ELTS_V8; c++) {
                tmp[c] *= 2;
            }
        }
    } else if (even) {
        OPJ_UINT32 c;
        OPJ_UINT32 i;
        i = 0;
        if (i + 1 < sn) {
            __m128i xmm_Si_0 = *(const __m128i*)(tmp + 4 * 0);
            __m128i xmm_Si_1 = *(const __m128i*)(tmp + 4 * 1);
            for (; i + 1 < sn; i++) {
                __m128i xmm_Sip1_0 = *(const __m128i*)(tmp +
                                                       (i + 1) * 2 * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Sip1_1 = *(const __m128i*)(tmp +
                                                       (i + 1) * 2 * NB_ELTS_V8 + 4 * 1);
                __m128i xmm_Di_0 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Di_1 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 1);
                xmm_Di_0 = _mm_sub_epi32(xmm_Di_0,
                                         _mm_srai_epi32(_mm_add_epi32(xmm_Si_0, xmm_Sip1_0), 1));
                xmm_Di_1 = _mm_sub_epi32(xmm_Di_1,
                                         _mm_srai_epi32(_mm_add_epi32(xmm_Si_1, xmm_Sip1_1), 1));
                *(__m128i*)(tmp + (1 + i * 2) * NB_ELTS_V8 + 4 * 0) =  xmm_Di_0;
                *(__m128i*)(tmp + (1 + i * 2) * NB_ELTS_V8 + 4 * 1) =  xmm_Di_1;
                xmm_Si_0 = xmm_Sip1_0;
                xmm_Si_1 = xmm_Sip1_1;
            }
        }
        if (((height) % 2) == 0) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Dc(i) -= OPJ_Sc(i);
            }
        }
        for (c = 0; c < NB_ELTS_V8; c++) {
            OPJ_Sc(0) += (OPJ_Dc(0) + OPJ_Dc(0) + 2) >> 2;
        }
        i = 1;
        if (i < dn) {
            __m128i xmm_Dim1_0 = *(const __m128i*)(tmp + (1 +
                                                   (i - 1) * 2) * NB_ELTS_V8 + 4 * 0);
            __m128i xmm_Dim1_1 = *(const __m128i*)(tmp + (1 +
                                                   (i - 1) * 2) * NB_ELTS_V8 + 4 * 1);
            const __m128i xmm_two = _mm_set1_epi32(2);
            for (; i < dn; i++) {
                __m128i xmm_Di_0 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Di_1 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 1);
                __m128i xmm_Si_0 = *(const __m128i*)(tmp +
                                                     (i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Si_1 = *(const __m128i*)(tmp +
                                                     (i * 2) * NB_ELTS_V8 + 4 * 1);
                xmm_Si_0 = _mm_add_epi32(xmm_Si_0,
                                         _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(xmm_Dim1_0, xmm_Di_0), xmm_two), 2));
                xmm_Si_1 = _mm_add_epi32(xmm_Si_1,
                                         _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(xmm_Dim1_1, xmm_Di_1), xmm_two), 2));
                *(__m128i*)(tmp + (i * 2) * NB_ELTS_V8 + 4 * 0) = xmm_Si_0;
                *(__m128i*)(tmp + (i * 2) * NB_ELTS_V8 + 4 * 1) = xmm_Si_1;
                xmm_Dim1_0 = xmm_Di_0;
                xmm_Dim1_1 = xmm_Di_1;
            }
        }
        if (((height) % 2) == 1) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Sc(i) += (OPJ_Dc(i - 1) + OPJ_Dc(i - 1) + 2) >> 2;
            }
        }
    } else {
        OPJ_UINT32 c;
        OPJ_UINT32 i;
        for (c = 0; c < NB_ELTS_V8; c++) {
            OPJ_Sc(0) -= OPJ_Dc(0);
        }
        i = 1;
        if (i < sn) {
            __m128i xmm_Dim1_0 = *(const __m128i*)(tmp + (1 +
                                                   (i - 1) * 2) * NB_ELTS_V8 + 4 * 0);
            __m128i xmm_Dim1_1 = *(const __m128i*)(tmp + (1 +
                                                   (i - 1) * 2) * NB_ELTS_V8 + 4 * 1);
            for (; i < sn; i++) {
                __m128i xmm_Di_0 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Di_1 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 1);
                __m128i xmm_Si_0 = *(const __m128i*)(tmp +
                                                     (i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Si_1 = *(const __m128i*)(tmp +
                                                     (i * 2) * NB_ELTS_V8 + 4 * 1);
                xmm_Si_0 = _mm_sub_epi32(xmm_Si_0,
                                         _mm_srai_epi32(_mm_add_epi32(xmm_Di_0, xmm_Dim1_0), 1));
                xmm_Si_1 = _mm_sub_epi32(xmm_Si_1,
                                         _mm_srai_epi32(_mm_add_epi32(xmm_Di_1, xmm_Dim1_1), 1));
                *(__m128i*)(tmp + (i * 2) * NB_ELTS_V8 + 4 * 0) = xmm_Si_0;
                *(__m128i*)(tmp + (i * 2) * NB_ELTS_V8 + 4 * 1) = xmm_Si_1;
                xmm_Dim1_0 = xmm_Di_0;
                xmm_Dim1_1 = xmm_Di_1;
            }
        }
        if (((height) % 2) == 1) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Sc(i) -= OPJ_Dc(i - 1);
            }
        }
        i = 0;
        if (i + 1 < dn) {
            __m128i xmm_Si_0 = *((const __m128i*)(tmp + 4 * 0));
            __m128i xmm_Si_1 = *((const __m128i*)(tmp + 4 * 1));
            const __m128i xmm_two = _mm_set1_epi32(2);
            for (; i + 1 < dn; i++) {
                __m128i xmm_Sip1_0 = *(const __m128i*)(tmp +
                                                       (i + 1) * 2 * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Sip1_1 = *(const __m128i*)(tmp +
                                                       (i + 1) * 2 * NB_ELTS_V8 + 4 * 1);
                __m128i xmm_Di_0 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 0);
                __m128i xmm_Di_1 = *(const __m128i*)(tmp +
                                                     (1 + i * 2) * NB_ELTS_V8 + 4 * 1);
                xmm_Di_0 = _mm_add_epi32(xmm_Di_0,
                                         _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(xmm_Si_0, xmm_Sip1_0), xmm_two), 2));
                xmm_Di_1 = _mm_add_epi32(xmm_Di_1,
                                         _mm_srai_epi32(_mm_add_epi32(_mm_add_epi32(xmm_Si_1, xmm_Sip1_1), xmm_two), 2));
                *(__m128i*)(tmp + (1 + i * 2) * NB_ELTS_V8 + 4 * 0) = xmm_Di_0;
                *(__m128i*)(tmp + (1 + i * 2) * NB_ELTS_V8 + 4 * 1) = xmm_Di_1;
                xmm_Si_0 = xmm_Sip1_0;
                xmm_Si_1 = xmm_Sip1_1;
            }
        }
        if (((height) % 2) == 0) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Dc(i) += (OPJ_Sc(i) + OPJ_Sc(i) + 2) >> 2;
            }
        }
    }
#else
    if (even) {
        OPJ_UINT32 c;
        if (height > 1) {
            OPJ_UINT32 i;
            for (i = 0; i + 1 < sn; i++) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Dc(i) -= (OPJ_Sc(i) + OPJ_Sc(i + 1)) >> 1;
                }
            }
            if (((height) % 2) == 0) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Dc(i) -= OPJ_Sc(i);
                }
            }
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Sc(0) += (OPJ_Dc(0) + OPJ_Dc(0) + 2) >> 2;
            }
            for (i = 1; i < dn; i++) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Sc(i) += (OPJ_Dc(i - 1) + OPJ_Dc(i) + 2) >> 2;
                }
            }
            if (((height) % 2) == 1) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Sc(i) += (OPJ_Dc(i - 1) + OPJ_Dc(i - 1) + 2) >> 2;
                }
            }
        }
    } else {
        OPJ_UINT32 c;
        if (height == 1) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Sc(0) *= 2;
            }
        } else {
            OPJ_UINT32 i;
            for (c = 0; c < NB_ELTS_V8; c++) {
                OPJ_Sc(0) -= OPJ_Dc(0);
            }
            for (i = 1; i < sn; i++) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Sc(i) -= (OPJ_Dc(i) + OPJ_Dc(i - 1)) >> 1;
                }
            }
            if (((height) % 2) == 1) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Sc(i) -= OPJ_Dc(i - 1);
                }
            }
            for (i = 0; i + 1 < dn; i++) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Dc(i) += (OPJ_Sc(i) + OPJ_Sc(i + 1) + 2) >> 2;
                }
            }
            if (((height) % 2) == 0) {
                for (c = 0; c < NB_ELTS_V8; c++) {
                    OPJ_Dc(i) += (OPJ_Sc(i) + OPJ_Sc(i) + 2) >> 2;
                }
            }
        }
    }
#endif

    if (cols == NB_ELTS_V8) {
        opj_dwt_deinterleave_v_cols(tmp, array, (OPJ_INT32)dn, (OPJ_INT32)sn,
                                    stride_width, even ? 0 : 1, NB_ELTS_V8);
    } else {
        opj_dwt_deinterleave_v_cols(tmp, array, (OPJ_INT32)dn, (OPJ_INT32)sn,
                                    stride_width, even ? 0 : 1, cols);
    }
}

static void opj_v8dwt_encode_step1(OPJ_FLOAT32* fw,
                                   OPJ_UINT32 end,
                                   const OPJ_FLOAT32 cst)
{
    OPJ_UINT32 i;
#ifdef __SSE__
    __m128* vw = (__m128*) fw;
    const __m128 vcst = _mm_set1_ps(cst);
    for (i = 0; i < end; ++i) {
        vw[0] = _mm_mul_ps(vw[0], vcst);
        vw[1] = _mm_mul_ps(vw[1], vcst);
        vw += 2 * (NB_ELTS_V8 * sizeof(OPJ_FLOAT32) / sizeof(__m128));
    }
#else
    OPJ_UINT32 c;
    for (i = 0; i < end; ++i) {
        for (c = 0; c < NB_ELTS_V8; c++) {
            fw[i * 2 * NB_ELTS_V8 + c] *= cst;
        }
    }
#endif
}

static void opj_v8dwt_encode_step2(OPJ_FLOAT32* fl, OPJ_FLOAT32* fw,
                                   OPJ_UINT32 end,
                                   OPJ_UINT32 m,
                                   OPJ_FLOAT32 cst)
{
    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);
#ifdef __SSE__
    __m128* vw = (__m128*) fw;
    __m128 vcst = _mm_set1_ps(cst);
    if (imax > 0) {
        __m128* vl = (__m128*) fl;
        vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(_mm_add_ps(vl[0], vw[0]), vcst));
        vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(_mm_add_ps(vl[1], vw[1]), vcst));
        vw += 2 * (NB_ELTS_V8 * sizeof(OPJ_FLOAT32) / sizeof(__m128));
        i = 1;

        for (; i < imax; ++i) {
            vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(_mm_add_ps(vw[-4], vw[0]), vcst));
            vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(_mm_add_ps(vw[-3], vw[1]), vcst));
            vw += 2 * (NB_ELTS_V8 * sizeof(OPJ_FLOAT32) / sizeof(__m128));
        }
    }
    if (m < end) {
        assert(m + 1 == end);
        vcst = _mm_add_ps(vcst, vcst);
        vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(vw[-4], vcst));
        vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(vw[-3], vcst));
    }
#else
    OPJ_INT32 c;
    if (imax > 0) {
        for (c = 0; c < NB_ELTS_V8; c++) {
            fw[-1 * NB_ELTS_V8 + c] += (fl[0 * NB_ELTS_V8 + c] + fw[0 * NB_ELTS_V8 + c]) *
                                       cst;
        }
        fw += 2 * NB_ELTS_V8;
        i = 1;
        for (; i < imax; ++i) {
            for (c = 0; c < NB_ELTS_V8; c++) {
                fw[-1 * NB_ELTS_V8 + c] += (fw[-2 * NB_ELTS_V8 + c] + fw[0 * NB_ELTS_V8 + c]) *
                                           cst;
            }
            fw += 2 * NB_ELTS_V8;
        }
    }
    if (m < end) {
        assert(m + 1 == end);
        for (c = 0; c < NB_ELTS_V8; c++) {
            fw[-1 * NB_ELTS_V8 + c] += (2 * fw[-2 * NB_ELTS_V8 + c]) * cst;
        }
    }
#endif
}

/* Forward 9-7 transform, for the vertical pass, processing cols columns */
/* where cols <= NB_ELTS_V8 */
static void opj_dwt_encode_and_deinterleave_v_real(
    void *arrayIn,
    void *tmpIn,
    OPJ_UINT32 height,
    OPJ_BOOL even,
    OPJ_UINT32 stride_width,
    OPJ_UINT32 cols)
{
    OPJ_FLOAT32* OPJ_RESTRICT array = (OPJ_FLOAT32 * OPJ_RESTRICT)arrayIn;
    OPJ_FLOAT32* OPJ_RESTRICT tmp = (OPJ_FLOAT32 * OPJ_RESTRICT)tmpIn;
    const OPJ_INT32 sn = (OPJ_INT32)((height + (even ? 1 : 0)) >> 1);
    const OPJ_INT32 dn = (OPJ_INT32)(height - (OPJ_UINT32)sn);
    OPJ_INT32 a, b;

    if (height == 1) {
        return;
    }

    opj_dwt_fetch_cols_vertical_pass(arrayIn, tmpIn, height, stride_width, cols);

    if (even) {
        a = 0;
        b = 1;
    } else {
        a = 1;
        b = 0;
    }
    opj_v8dwt_encode_step2(tmp + a * NB_ELTS_V8,
                           tmp + (b + 1) * NB_ELTS_V8,
                           (OPJ_UINT32)dn,
                           (OPJ_UINT32)opj_int_min(dn, sn - b),
                           opj_dwt_alpha);
    opj_v8dwt_encode_step2(tmp + b * NB_ELTS_V8,
                           tmp + (a + 1) * NB_ELTS_V8,
                           (OPJ_UINT32)sn,
                           (OPJ_UINT32)opj_int_min(sn, dn - a),
                           opj_dwt_beta);
    opj_v8dwt_encode_step2(tmp + a * NB_ELTS_V8,
                           tmp + (b + 1) * NB_ELTS_V8,
                           (OPJ_UINT32)dn,
                           (OPJ_UINT32)opj_int_min(dn, sn - b),
                           opj_dwt_gamma);
    opj_v8dwt_encode_step2(tmp + b * NB_ELTS_V8,
                           tmp + (a + 1) * NB_ELTS_V8,
                           (OPJ_UINT32)sn,
                           (OPJ_UINT32)opj_int_min(sn, dn - a),
                           opj_dwt_delta);
    opj_v8dwt_encode_step1(tmp + b * NB_ELTS_V8, (OPJ_UINT32)dn,
                           opj_K);
    opj_v8dwt_encode_step1(tmp + a * NB_ELTS_V8, (OPJ_UINT32)sn,
                           opj_invK);


    if (cols == NB_ELTS_V8) {
        opj_dwt_deinterleave_v_cols((OPJ_INT32*)tmp,
                                    (OPJ_INT32*)array,
                                    (OPJ_INT32)dn, (OPJ_INT32)sn,
                                    stride_width, even ? 0 : 1, NB_ELTS_V8);
    } else {
        opj_dwt_deinterleave_v_cols((OPJ_INT32*)tmp,
                                    (OPJ_INT32*)array,
                                    (OPJ_INT32)dn, (OPJ_INT32)sn,
                                    stride_width, even ? 0 : 1, cols);
    }
}


/* <summary>                            */
/* Forward 5-3 wavelet transform in 2-D. */
/* </summary>                           */
static INLINE OPJ_BOOL opj_dwt_encode_procedure(opj_thread_pool_t* tp,
        opj_tcd_tilecomp_t * tilec,
        opj_encode_and_deinterleave_v_fnptr_type p_encode_and_deinterleave_v,
        opj_encode_and_deinterleave_h_one_row_fnptr_type
        p_encode_and_deinterleave_h_one_row)
{
    OPJ_INT32 i;
    OPJ_INT32 *bj = 00;
    OPJ_UINT32 w;
    OPJ_INT32 l;




    OPJ_SIZE_T l_data_size;

    opj_tcd_resolution_t * l_cur_res = 0;
    opj_tcd_resolution_t * l_last_res = 0;
    const int num_threads = opj_thread_pool_get_thread_count(tp);
    OPJ_INT32 * OPJ_RESTRICT tiledp = tilec->data;

    w = (OPJ_UINT32)(tilec->x1 - tilec->x0);
    l = (OPJ_INT32)tilec->numresolutions - 1;


    l_cur_res = tilec->resolutions + l;
    l_last_res = l_cur_res - 1;

    l_data_size = opj_dwt_max_resolution(tilec->resolutions, tilec->numresolutions);
    /* overflow check */
    if (l_data_size > (SIZE_MAX / (NB_ELTS_V8 * sizeof(OPJ_INT32)))) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    l_data_size *= NB_ELTS_V8 * sizeof(OPJ_INT32);
    bj = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
    /* l_data_size is equal to 0 when numresolutions == 1 but bj is not used */
    /* in that case, so do not error out */
    if (l_data_size != 0 && ! bj) {
        return OPJ_FALSE;
    }
    i = l;

    while (i--) {
        OPJ_UINT32 j;
        OPJ_UINT32 rw;           /* width of the resolution level computed   */
        OPJ_UINT32 rh;           /* height of the resolution level computed  */
        OPJ_UINT32
        rw1;      /* width of the resolution level once lower than computed one                                       */
        OPJ_UINT32
        rh1;      /* height of the resolution level once lower than computed one                                      */
        OPJ_INT32 cas_col;  /* 0 = non inversion on horizontal filtering 1 = inversion between low-pass and high-pass filtering */
        OPJ_INT32 cas_row;  /* 0 = non inversion on vertical filtering 1 = inversion between low-pass and high-pass filtering   */
        OPJ_INT32 dn, sn;

        rw  = (OPJ_UINT32)(l_cur_res->x1 - l_cur_res->x0);
        rh  = (OPJ_UINT32)(l_cur_res->y1 - l_cur_res->y0);
        rw1 = (OPJ_UINT32)(l_last_res->x1 - l_last_res->x0);
        rh1 = (OPJ_UINT32)(l_last_res->y1 - l_last_res->y0);

        cas_row = l_cur_res->x0 & 1;
        cas_col = l_cur_res->y0 & 1;

        sn = (OPJ_INT32)rh1;
        dn = (OPJ_INT32)(rh - rh1);

        /* Perform vertical pass */
        if (num_threads <= 1 || rw < 2 * NB_ELTS_V8) {
            for (j = 0; j + NB_ELTS_V8 - 1 < rw; j += NB_ELTS_V8) {
                p_encode_and_deinterleave_v(tiledp + j,
                                            bj,
                                            rh,
                                            cas_col == 0,
                                            w,
                                            NB_ELTS_V8);
            }
            if (j < rw) {
                p_encode_and_deinterleave_v(tiledp + j,
                                            bj,
                                            rh,
                                            cas_col == 0,
                                            w,
                                            rw - j);
            }
        }  else {
            OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
            OPJ_UINT32 step_j;

            if (rw < num_jobs) {
                num_jobs = rw;
            }
            step_j = ((rw / num_jobs) / NB_ELTS_V8) * NB_ELTS_V8;

            for (j = 0; j < num_jobs; j++) {
                opj_dwt_encode_v_job_t* job;

                job = (opj_dwt_encode_v_job_t*) opj_malloc(sizeof(opj_dwt_encode_v_job_t));
                if (!job) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(bj);
                    return OPJ_FALSE;
                }
                job->v.mem = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
                if (!job->v.mem) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_free(job);
                    opj_aligned_free(bj);
                    return OPJ_FALSE;
                }
                job->v.dn = dn;
                job->v.sn = sn;
                job->v.cas = cas_col;
                job->rh = rh;
                job->w = w;
                job->tiledp = tiledp;
                job->min_j = j * step_j;
                job->max_j = (j + 1 == num_jobs) ? rw : (j + 1) * step_j;
                job->p_encode_and_deinterleave_v = p_encode_and_deinterleave_v;
                opj_thread_pool_submit_job(tp, opj_dwt_encode_v_func, job);
            }
            opj_thread_pool_wait_completion(tp, 0);
        }

        sn = (OPJ_INT32)rw1;
        dn = (OPJ_INT32)(rw - rw1);

        /* Perform horizontal pass */
        if (num_threads <= 1 || rh <= 1) {
            for (j = 0; j < rh; j++) {
                OPJ_INT32* OPJ_RESTRICT aj = tiledp + j * w;
                (*p_encode_and_deinterleave_h_one_row)(aj, bj, rw,
                                                       cas_row == 0 ? OPJ_TRUE : OPJ_FALSE);
            }
        }  else {
            OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
            OPJ_UINT32 step_j;

            if (rh < num_jobs) {
                num_jobs = rh;
            }
            step_j = (rh / num_jobs);

            for (j = 0; j < num_jobs; j++) {
                opj_dwt_encode_h_job_t* job;

                job = (opj_dwt_encode_h_job_t*) opj_malloc(sizeof(opj_dwt_encode_h_job_t));
                if (!job) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(bj);
                    return OPJ_FALSE;
                }
                job->h.mem = (OPJ_INT32*)opj_aligned_32_malloc(l_data_size);
                if (!job->h.mem) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_free(job);
                    opj_aligned_free(bj);
                    return OPJ_FALSE;
                }
                job->h.dn = dn;
                job->h.sn = sn;
                job->h.cas = cas_row;
                job->rw = rw;
                job->w = w;
                job->tiledp = tiledp;
                job->min_j = j * step_j;
                job->max_j = (j + 1U) * step_j; /* this can overflow */
                if (j == (num_jobs - 1U)) {  /* this will take care of the overflow */
                    job->max_j = rh;
                }
                job->p_function = p_encode_and_deinterleave_h_one_row;
                opj_thread_pool_submit_job(tp, opj_dwt_encode_h_func, job);
            }
            opj_thread_pool_wait_completion(tp, 0);
        }

        l_cur_res = l_last_res;

        --l_last_res;
    }

    opj_aligned_free(bj);
    return OPJ_TRUE;
}

/* Forward 5-3 wavelet transform in 2-D. */
/* </summary>                           */
OPJ_BOOL opj_dwt_encode(opj_tcd_t *p_tcd,
                        opj_tcd_tilecomp_t * tilec)
{
    return opj_dwt_encode_procedure(p_tcd->thread_pool, tilec,
                                    opj_dwt_encode_and_deinterleave_v,
                                    opj_dwt_encode_and_deinterleave_h_one_row);
}

/* <summary>                            */
/* Inverse 5-3 wavelet transform in 2-D. */
/* </summary>                           */
OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd, opj_tcd_tilecomp_t* tilec,
                        OPJ_UINT32 numres)
{
    if (p_tcd->whole_tile_decoding) {
        return opj_dwt_decode_tile(p_tcd->thread_pool, tilec, numres);
    } else {
        return opj_dwt_decode_partial_tile(tilec, numres);
    }
}
















/* <summary>                */
/* Get norm of 5-3 wavelet. */
/* </summary>               */
OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient)
{
    /* FIXME ! This is just a band-aid to avoid a buffer overflow */
    /* but the array should really be extended up to 33 resolution levels */
    /* See https://github.com/uclouvain/openjpeg/issues/493 */
    if (orient == 0 && level >= 10) {
        level = 9;
    } else if (orient > 0 && level >= 9) {
        level = 8;
    }
    return opj_dwt_norms[orient][level];
}

/* <summary>                             */
/* Forward 9-7 wavelet transform in 2-D. */
/* </summary>                            */
OPJ_BOOL opj_dwt_encode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t * tilec)
{
    return opj_dwt_encode_procedure(p_tcd->thread_pool, tilec,

                                    opj_dwt_encode_and_deinterleave_v_real,



                                    opj_dwt_encode_and_deinterleave_h_one_row_real);



}

/* <summary>                */
/* Get norm of 9-7 wavelet. */
/* </summary>               */
OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient)
{
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
        orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1);
        level = tccp->numresolutions - 1 - resno;
        gain = (tccp->qmfbid == 0) ? 0 : ((orient == 0) ? 0 : (((orient == 1) ||
                                          (orient == 2)) ? 1 : 2));
        if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
            stepsize = 1.0;
        } else {
            OPJ_FLOAT64 norm = opj_dwt_norms_real[orient][level];
            stepsize = (1 << (gain)) / norm;
        }
        opj_dwt_encode_stepsize((OPJ_INT32) floor(stepsize * 8192.0),
                                (OPJ_INT32)(prec + gain), &tccp->stepsizes[bandno]);
    }
}








|







1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
        orient = (bandno == 0) ? 0 : ((bandno - 1) % 3 + 1);
        level = tccp->numresolutions - 1 - resno;
        gain = (tccp->qmfbid == 0) ? 0 : ((orient == 0) ? 0 : (((orient == 1) ||
                                          (orient == 2)) ? 1 : 2));
        if (tccp->qntsty == J2K_CCP_QNTSTY_NOQNT) {
            stepsize = 1.0;
        } else {
            OPJ_FLOAT64 norm = opj_dwt_getnorm_real(level, orient);
            stepsize = (1 << (gain)) / norm;
        }
        opj_dwt_encode_stepsize((OPJ_INT32) floor(stepsize * 8192.0),
                                (OPJ_INT32)(prec + gain), &tccp->stepsizes[bandno]);
    }
}

1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
typedef struct {
    opj_dwt_t h;
    OPJ_UINT32 rw;
    OPJ_UINT32 w;
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
} opj_dwd_decode_h_job_t;

static void opj_dwt_decode_h_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwd_decode_h_job_t* job;
    (void)tls;

    job = (opj_dwd_decode_h_job_t*)user_data;
    for (j = job->min_j; j < job->max_j; j++) {
        opj_idwt53_h(&job->h, &job->tiledp[j * job->w]);
    }

    opj_aligned_free(job->h.mem);
    opj_free(job);
}

typedef struct {
    opj_dwt_t v;
    OPJ_UINT32 rh;
    OPJ_UINT32 w;
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
} opj_dwd_decode_v_job_t;

static void opj_dwt_decode_v_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwd_decode_v_job_t* job;
    (void)tls;

    job = (opj_dwd_decode_v_job_t*)user_data;
    for (j = job->min_j; j + PARALLEL_COLS_53 <= job->max_j;
            j += PARALLEL_COLS_53) {
        opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
                     PARALLEL_COLS_53);
    }
    if (j < job->max_j)
        opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,







|




|


|















|




|


|







2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
typedef struct {
    opj_dwt_t h;
    OPJ_UINT32 rw;
    OPJ_UINT32 w;
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
} opj_dwt_decode_h_job_t;

static void opj_dwt_decode_h_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt_decode_h_job_t* job;
    (void)tls;

    job = (opj_dwt_decode_h_job_t*)user_data;
    for (j = job->min_j; j < job->max_j; j++) {
        opj_idwt53_h(&job->h, &job->tiledp[j * job->w]);
    }

    opj_aligned_free(job->h.mem);
    opj_free(job);
}

typedef struct {
    opj_dwt_t v;
    OPJ_UINT32 rh;
    OPJ_UINT32 w;
    OPJ_INT32 * OPJ_RESTRICT tiledp;
    OPJ_UINT32 min_j;
    OPJ_UINT32 max_j;
} opj_dwt_decode_v_job_t;

static void opj_dwt_decode_v_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt_decode_v_job_t* job;
    (void)tls;

    job = (opj_dwt_decode_v_job_t*)user_data;
    for (j = job->min_j; j + PARALLEL_COLS_53 <= job->max_j;
            j += PARALLEL_COLS_53) {
        opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
                     PARALLEL_COLS_53);
    }
    if (j < job->max_j)
        opj_idwt53_v(&job->v, &job->tiledp[j], (OPJ_SIZE_T)job->w,
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459

            if (rh < num_jobs) {
                num_jobs = rh;
            }
            step_j = (rh / num_jobs);

            for (j = 0; j < num_jobs; j++) {
                opj_dwd_decode_h_job_t* job;

                job = (opj_dwd_decode_h_job_t*) opj_malloc(sizeof(opj_dwd_decode_h_job_t));
                if (!job) {
                    /* It would be nice to fallback to single thread case, but */
                    /* unfortunately some jobs may be launched and have modified */
                    /* tiledp, so it is not practical to recover from that error */
                    /* FIXME event manager error callback */
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(h.mem);







|

|







2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142

            if (rh < num_jobs) {
                num_jobs = rh;
            }
            step_j = (rh / num_jobs);

            for (j = 0; j < num_jobs; j++) {
                opj_dwt_decode_h_job_t* job;

                job = (opj_dwt_decode_h_job_t*) opj_malloc(sizeof(opj_dwt_decode_h_job_t));
                if (!job) {
                    /* It would be nice to fallback to single thread case, but */
                    /* unfortunately some jobs may be launched and have modified */
                    /* tiledp, so it is not practical to recover from that error */
                    /* FIXME event manager error callback */
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(h.mem);
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514

            if (rw < num_jobs) {
                num_jobs = rw;
            }
            step_j = (rw / num_jobs);

            for (j = 0; j < num_jobs; j++) {
                opj_dwd_decode_v_job_t* job;

                job = (opj_dwd_decode_v_job_t*) opj_malloc(sizeof(opj_dwd_decode_v_job_t));
                if (!job) {
                    /* It would be nice to fallback to single thread case, but */
                    /* unfortunately some jobs may be launched and have modified */
                    /* tiledp, so it is not practical to recover from that error */
                    /* FIXME event manager error callback */
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(v.mem);







|

|







2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197

            if (rw < num_jobs) {
                num_jobs = rw;
            }
            step_j = (rw / num_jobs);

            for (j = 0; j < num_jobs; j++) {
                opj_dwt_decode_v_job_t* job;

                job = (opj_dwt_decode_v_job_t*) opj_malloc(sizeof(opj_dwt_decode_v_job_t));
                if (!job) {
                    /* It would be nice to fallback to single thread case, but */
                    /* unfortunately some jobs may be launched and have modified */
                    /* tiledp, so it is not practical to recover from that error */
                    /* FIXME event manager error callback */
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(v.mem);
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186

2187
2188
2189
2190
2191
2192
2193








2194
2195
2196
2197
2198

2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214




















2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316

2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327

2328
2329
2330
2331




2332

2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382

2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408

2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431




2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446








2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471





















2472
2473
2474
2475
2476
2477
2478
2479
2480
2481






















2482



2483
2484
2485


2486










2487


2488

2489

2490
2491



2492


2493
2494



2495


2496
2497
2498

2499


2500
2501


2502









2503
2504
2505
2506
2507
2508
2509
2510

2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527





2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
        assert(ret);
        OPJ_UNUSED(ret);
    }
    opj_sparse_array_int32_free(sa);
    return OPJ_TRUE;
}

static void opj_v4dwt_interleave_h(opj_v4dwt_t* OPJ_RESTRICT dwt,
                                   OPJ_FLOAT32* OPJ_RESTRICT a,
                                   OPJ_UINT32 width,
                                   OPJ_UINT32 remaining_height)
{
    OPJ_FLOAT32* OPJ_RESTRICT bi = (OPJ_FLOAT32*)(dwt->wavelet + dwt->cas);
    OPJ_UINT32 i, k;
    OPJ_UINT32 x0 = dwt->win_l_x0;
    OPJ_UINT32 x1 = dwt->win_l_x1;

    for (k = 0; k < 2; ++k) {
        if (remaining_height >= 4 && ((OPJ_SIZE_T) a & 0x0f) == 0 &&
                ((OPJ_SIZE_T) bi & 0x0f) == 0 && (width & 0x0f) == 0) {
            /* Fast code path */
            for (i = x0; i < x1; ++i) {
                OPJ_UINT32 j = i;

                bi[i * 8    ] = a[j];
                j += width;
                bi[i * 8 + 1] = a[j];
                j += width;
                bi[i * 8 + 2] = a[j];
                j += width;
                bi[i * 8 + 3] = a[j];








            }
        } else {
            /* Slow code path */
            for (i = x0; i < x1; ++i) {
                OPJ_UINT32 j = i;

                bi[i * 8    ] = a[j];
                j += width;
                if (remaining_height == 1) {
                    continue;
                }
                bi[i * 8 + 1] = a[j];
                j += width;
                if (remaining_height == 2) {
                    continue;
                }
                bi[i * 8 + 2] = a[j];
                j += width;
                if (remaining_height == 3) {
                    continue;
                }
                bi[i * 8 + 3] = a[j]; /* This one*/




















            }
        }

        bi = (OPJ_FLOAT32*)(dwt->wavelet + 1 - dwt->cas);
        a += dwt->sn;
        x0 = dwt->win_h_x0;
        x1 = dwt->win_h_x1;
    }
}

static void opj_v4dwt_interleave_partial_h(opj_v4dwt_t* dwt,
        opj_sparse_array_int32_t* sa,
        OPJ_UINT32 sa_line,
        OPJ_UINT32 remaining_height)
{
    OPJ_UINT32 i;
    for (i = 0; i < remaining_height; i++) {
        OPJ_BOOL ret;
        ret = opj_sparse_array_int32_read(sa,
                                          dwt->win_l_x0, sa_line + i,
                                          dwt->win_l_x1, sa_line + i + 1,
                                          /* Nasty cast from float* to int32* */
                                          (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0) + i,
                                          8, 0, OPJ_TRUE);
        assert(ret);
        ret = opj_sparse_array_int32_read(sa,
                                          (OPJ_UINT32)dwt->sn + dwt->win_h_x0, sa_line + i,
                                          (OPJ_UINT32)dwt->sn + dwt->win_h_x1, sa_line + i + 1,
                                          /* Nasty cast from float* to int32* */
                                          (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0) + i,
                                          8, 0, OPJ_TRUE);
        assert(ret);
        OPJ_UNUSED(ret);
    }
}

static void opj_v4dwt_interleave_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
                                   OPJ_FLOAT32* OPJ_RESTRICT a,
                                   OPJ_UINT32 width,
                                   OPJ_UINT32 nb_elts_read)
{
    opj_v4_t* OPJ_RESTRICT bi = dwt->wavelet + dwt->cas;
    OPJ_UINT32 i;

    for (i = dwt->win_l_x0; i < dwt->win_l_x1; ++i) {
        memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
               (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
    }

    a += (OPJ_UINT32)dwt->sn * (OPJ_SIZE_T)width;
    bi = dwt->wavelet + 1 - dwt->cas;

    for (i = dwt->win_h_x0; i < dwt->win_h_x1; ++i) {
        memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
               (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
    }
}

static void opj_v4dwt_interleave_partial_v(opj_v4dwt_t* OPJ_RESTRICT dwt,
        opj_sparse_array_int32_t* sa,
        OPJ_UINT32 sa_col,
        OPJ_UINT32 nb_elts_read)
{
    OPJ_BOOL ret;
    ret = opj_sparse_array_int32_read(sa,
                                      sa_col, dwt->win_l_x0,
                                      sa_col + nb_elts_read, dwt->win_l_x1,
                                      (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0),
                                      1, 8, OPJ_TRUE);
    assert(ret);
    ret = opj_sparse_array_int32_read(sa,
                                      sa_col, (OPJ_UINT32)dwt->sn + dwt->win_h_x0,
                                      sa_col + nb_elts_read, (OPJ_UINT32)dwt->sn + dwt->win_h_x1,
                                      (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0),
                                      1, 8, OPJ_TRUE);
    assert(ret);
    OPJ_UNUSED(ret);
}

#ifdef __SSE__

static void opj_v4dwt_decode_step1_sse(opj_v4_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       const __m128 c)
{
    __m128* OPJ_RESTRICT vw = (__m128*) w;
    OPJ_UINT32 i;
    /* 4x unrolled loop */
    vw += 2 * start;
    for (i = start; i + 3 < end; i += 4, vw += 8) {
        __m128 xmm0 = _mm_mul_ps(vw[0], c);
        __m128 xmm2 = _mm_mul_ps(vw[2], c);
        __m128 xmm4 = _mm_mul_ps(vw[4], c);
        __m128 xmm6 = _mm_mul_ps(vw[6], c);
        vw[0] = xmm0;
        vw[2] = xmm2;
        vw[4] = xmm4;
        vw[6] = xmm6;
    }
    for (; i < end; ++i, vw += 2) {
        vw[0] = _mm_mul_ps(vw[0], c);

    }
}

static void opj_v4dwt_decode_step2_sse(opj_v4_t* l, opj_v4_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       OPJ_UINT32 m,
                                       __m128 c)
{
    __m128* OPJ_RESTRICT vl = (__m128*) l;
    __m128* OPJ_RESTRICT vw = (__m128*) w;

    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);
    __m128 tmp1, tmp2, tmp3;
    if (start == 0) {




        tmp1 = vl[0];

    } else {
        vw += start * 2;
        tmp1 = vw[-3];
    }

    i = start;

    /* 4x loop unrolling */
    for (; i + 3 < imax; i += 4) {
        __m128 tmp4, tmp5, tmp6, tmp7, tmp8, tmp9;
        tmp2 = vw[-1];
        tmp3 = vw[ 0];
        tmp4 = vw[ 1];
        tmp5 = vw[ 2];
        tmp6 = vw[ 3];
        tmp7 = vw[ 4];
        tmp8 = vw[ 5];
        tmp9 = vw[ 6];
        vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
        vw[ 1] = _mm_add_ps(tmp4, _mm_mul_ps(_mm_add_ps(tmp3, tmp5), c));
        vw[ 3] = _mm_add_ps(tmp6, _mm_mul_ps(_mm_add_ps(tmp5, tmp7), c));
        vw[ 5] = _mm_add_ps(tmp8, _mm_mul_ps(_mm_add_ps(tmp7, tmp9), c));
        tmp1 = tmp9;
        vw += 8;
    }

    for (; i < imax; ++i) {
        tmp2 = vw[-1];
        tmp3 = vw[ 0];
        vw[-1] = _mm_add_ps(tmp2, _mm_mul_ps(_mm_add_ps(tmp1, tmp3), c));
        tmp1 = tmp3;
        vw += 2;
    }
    if (m < end) {
        assert(m + 1 == end);
        c = _mm_add_ps(c, c);
        c = _mm_mul_ps(c, vw[-2]);
        vw[-1] = _mm_add_ps(vw[-1], c);
    }
}

#else

static void opj_v4dwt_decode_step1(opj_v4_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   const OPJ_FLOAT32 c)
{
    OPJ_FLOAT32* OPJ_RESTRICT fw = (OPJ_FLOAT32*) w;
    OPJ_UINT32 i;

    for (i = start; i < end; ++i) {
        OPJ_FLOAT32 tmp1 = fw[i * 8    ];
        OPJ_FLOAT32 tmp2 = fw[i * 8 + 1];
        OPJ_FLOAT32 tmp3 = fw[i * 8 + 2];
        OPJ_FLOAT32 tmp4 = fw[i * 8 + 3];
        fw[i * 8    ] = tmp1 * c;
        fw[i * 8 + 1] = tmp2 * c;
        fw[i * 8 + 2] = tmp3 * c;
        fw[i * 8 + 3] = tmp4 * c;
    }
}

static void opj_v4dwt_decode_step2(opj_v4_t* l, opj_v4_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   OPJ_UINT32 m,
                                   OPJ_FLOAT32 c)
{
    OPJ_FLOAT32* fl = (OPJ_FLOAT32*) l;
    OPJ_FLOAT32* fw = (OPJ_FLOAT32*) w;
    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);
    if (start > 0) {
        fw += 8 * start;
        fl = fw - 8;
    }

    for (i = start; i < imax; ++i) {
        OPJ_FLOAT32 tmp1_1 = fl[0];
        OPJ_FLOAT32 tmp1_2 = fl[1];
        OPJ_FLOAT32 tmp1_3 = fl[2];
        OPJ_FLOAT32 tmp1_4 = fl[3];
        OPJ_FLOAT32 tmp2_1 = fw[-4];
        OPJ_FLOAT32 tmp2_2 = fw[-3];
        OPJ_FLOAT32 tmp2_3 = fw[-2];
        OPJ_FLOAT32 tmp2_4 = fw[-1];
        OPJ_FLOAT32 tmp3_1 = fw[0];
        OPJ_FLOAT32 tmp3_2 = fw[1];
        OPJ_FLOAT32 tmp3_3 = fw[2];
        OPJ_FLOAT32 tmp3_4 = fw[3];
        fw[-4] = tmp2_1 + ((tmp1_1 + tmp3_1) * c);
        fw[-3] = tmp2_2 + ((tmp1_2 + tmp3_2) * c);
        fw[-2] = tmp2_3 + ((tmp1_3 + tmp3_3) * c);
        fw[-1] = tmp2_4 + ((tmp1_4 + tmp3_4) * c);
        fl = fw;
        fw += 8;
    }
    if (m < end) {
        assert(m + 1 == end);
        c += c;




        fw[-4] = fw[-4] + fl[0] * c;
        fw[-3] = fw[-3] + fl[1] * c;
        fw[-2] = fw[-2] + fl[2] * c;
        fw[-1] = fw[-1] + fl[3] * c;
    }
}

#endif

/* <summary>                             */
/* Inverse 9-7 wavelet transform in 1-D. */
/* </summary>                            */
static void opj_v4dwt_decode(opj_v4dwt_t* OPJ_RESTRICT dwt)
{
    OPJ_INT32 a, b;








    if (dwt->cas == 0) {
        if (!((dwt->dn > 0) || (dwt->sn > 1))) {
            return;
        }
        a = 0;
        b = 1;
    } else {
        if (!((dwt->sn > 0) || (dwt->dn > 1))) {
            return;
        }
        a = 1;
        b = 0;
    }
#ifdef __SSE__
    opj_v4dwt_decode_step1_sse(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
                               _mm_set1_ps(opj_K));
    opj_v4dwt_decode_step1_sse(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
                               _mm_set1_ps(opj_c13318));
    opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
                               dwt->win_l_x0, dwt->win_l_x1,
                               (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                               _mm_set1_ps(opj_dwt_delta));
    opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
                               dwt->win_h_x0, dwt->win_h_x1,
                               (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),





















                               _mm_set1_ps(opj_dwt_gamma));
    opj_v4dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
                               dwt->win_l_x0, dwt->win_l_x1,
                               (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                               _mm_set1_ps(opj_dwt_beta));
    opj_v4dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
                               dwt->win_h_x0, dwt->win_h_x1,
                               (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                               _mm_set1_ps(opj_dwt_alpha));
#else






















    opj_v4dwt_decode_step1(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,



                           opj_K);
    opj_v4dwt_decode_step1(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
                           opj_c13318);


    opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,










                           dwt->win_l_x0, dwt->win_l_x1,


                           (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),

                           opj_dwt_delta);

    opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
                           dwt->win_h_x0, dwt->win_h_x1,



                           (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),


                           opj_dwt_gamma);
    opj_v4dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,



                           dwt->win_l_x0, dwt->win_l_x1,


                           (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                           opj_dwt_beta);
    opj_v4dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,

                           dwt->win_h_x0, dwt->win_h_x1,


                           (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                           opj_dwt_alpha);


#endif









}


/* <summary>                             */
/* Inverse 9-7 wavelet transform in 2-D. */
/* </summary>                            */
static
OPJ_BOOL opj_dwt_decode_tile_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,

                                OPJ_UINT32 numres)
{
    opj_v4dwt_t h;
    opj_v4dwt_t v;

    opj_tcd_resolution_t* res = tilec->resolutions;

    OPJ_UINT32 rw = (OPJ_UINT32)(res->x1 -
                                 res->x0);    /* width of the resolution level computed */
    OPJ_UINT32 rh = (OPJ_UINT32)(res->y1 -
                                 res->y0);    /* height of the resolution level computed */

    OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
                                                               1].x1 -
                                tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);

    OPJ_SIZE_T l_data_size;






    l_data_size = opj_dwt_max_resolution(res, numres);
    /* overflow check */
    if (l_data_size > (SIZE_MAX - 5U)) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    l_data_size += 5U;
    /* overflow check */
    if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
    if (!h.wavelet) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    v.wavelet = h.wavelet;

    while (--numres) {







|










|
|



>
|

|

|

|
>
>
>
>
>
>
>
>





>
|




|




|




|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>










|












|






|





|
|
|
|

|
















|









|





|






|





|
|
|
|
<
<
<
<
<
<
<
<
<
|

>



|







>


<

>
>
>
>
|
>

|
<



<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<

|
<
|
<
|




|
|





|






>

|
|
|
|
|
|
|
|



|










|
|

>

<
<
<
<
|
|
|
|
<
<
<
<
|
|
|
|

|




>
>
>
>
|
|
|
|








|


>
>
>
>
>
>
>
>














|

|
|
|


|
|


>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
|
|
|
|
|
|
|
|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
|
|
|
>
>
|
>
>
>
>
>
>
>
>
>
>
|
>
>
|
>
|
>
|
|
>
>
>
|
>
>
|
|
>
>
>
|
>
>
|
|
|
>
|
>
>
|
|
>
>
|
>
>
>
>
>
>
>
>
>







|
>


|
|













>
>
>
>
>



<
<
<
<
<
<
|



|







2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018









3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035

3036
3037
3038
3039
3040
3041
3042
3043
3044

3045
3046
3047

3048


















3049
3050

3051

3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099




3100
3101
3102
3103




3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316






3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
        assert(ret);
        OPJ_UNUSED(ret);
    }
    opj_sparse_array_int32_free(sa);
    return OPJ_TRUE;
}

static void opj_v8dwt_interleave_h(opj_v8dwt_t* OPJ_RESTRICT dwt,
                                   OPJ_FLOAT32* OPJ_RESTRICT a,
                                   OPJ_UINT32 width,
                                   OPJ_UINT32 remaining_height)
{
    OPJ_FLOAT32* OPJ_RESTRICT bi = (OPJ_FLOAT32*)(dwt->wavelet + dwt->cas);
    OPJ_UINT32 i, k;
    OPJ_UINT32 x0 = dwt->win_l_x0;
    OPJ_UINT32 x1 = dwt->win_l_x1;

    for (k = 0; k < 2; ++k) {
        if (remaining_height >= NB_ELTS_V8 && ((OPJ_SIZE_T) a & 0x0f) == 0 &&
                ((OPJ_SIZE_T) bi & 0x0f) == 0) {
            /* Fast code path */
            for (i = x0; i < x1; ++i) {
                OPJ_UINT32 j = i;
                OPJ_FLOAT32* OPJ_RESTRICT dst = bi + i * 2 * NB_ELTS_V8;
                dst[0] = a[j];
                j += width;
                dst[1] = a[j];
                j += width;
                dst[2] = a[j];
                j += width;
                dst[3] = a[j];
                j += width;
                dst[4] = a[j];
                j += width;
                dst[5] = a[j];
                j += width;
                dst[6] = a[j];
                j += width;
                dst[7] = a[j];
            }
        } else {
            /* Slow code path */
            for (i = x0; i < x1; ++i) {
                OPJ_UINT32 j = i;
                OPJ_FLOAT32* OPJ_RESTRICT dst = bi + i * 2 * NB_ELTS_V8;
                dst[0] = a[j];
                j += width;
                if (remaining_height == 1) {
                    continue;
                }
                dst[1] = a[j];
                j += width;
                if (remaining_height == 2) {
                    continue;
                }
                dst[2] = a[j];
                j += width;
                if (remaining_height == 3) {
                    continue;
                }
                dst[3] = a[j];
                j += width;
                if (remaining_height == 4) {
                    continue;
                }
                dst[4] = a[j];
                j += width;
                if (remaining_height == 5) {
                    continue;
                }
                dst[5] = a[j];
                j += width;
                if (remaining_height == 6) {
                    continue;
                }
                dst[6] = a[j];
                j += width;
                if (remaining_height == 7) {
                    continue;
                }
                dst[7] = a[j];
            }
        }

        bi = (OPJ_FLOAT32*)(dwt->wavelet + 1 - dwt->cas);
        a += dwt->sn;
        x0 = dwt->win_h_x0;
        x1 = dwt->win_h_x1;
    }
}

static void opj_v8dwt_interleave_partial_h(opj_v8dwt_t* dwt,
        opj_sparse_array_int32_t* sa,
        OPJ_UINT32 sa_line,
        OPJ_UINT32 remaining_height)
{
    OPJ_UINT32 i;
    for (i = 0; i < remaining_height; i++) {
        OPJ_BOOL ret;
        ret = opj_sparse_array_int32_read(sa,
                                          dwt->win_l_x0, sa_line + i,
                                          dwt->win_l_x1, sa_line + i + 1,
                                          /* Nasty cast from float* to int32* */
                                          (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0) + i,
                                          2 * NB_ELTS_V8, 0, OPJ_TRUE);
        assert(ret);
        ret = opj_sparse_array_int32_read(sa,
                                          (OPJ_UINT32)dwt->sn + dwt->win_h_x0, sa_line + i,
                                          (OPJ_UINT32)dwt->sn + dwt->win_h_x1, sa_line + i + 1,
                                          /* Nasty cast from float* to int32* */
                                          (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0) + i,
                                          2 * NB_ELTS_V8, 0, OPJ_TRUE);
        assert(ret);
        OPJ_UNUSED(ret);
    }
}

static INLINE void opj_v8dwt_interleave_v(opj_v8dwt_t* OPJ_RESTRICT dwt,
        OPJ_FLOAT32* OPJ_RESTRICT a,
        OPJ_UINT32 width,
        OPJ_UINT32 nb_elts_read)
{
    opj_v8_t* OPJ_RESTRICT bi = dwt->wavelet + dwt->cas;
    OPJ_UINT32 i;

    for (i = dwt->win_l_x0; i < dwt->win_l_x1; ++i) {
        memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
               (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
    }

    a += (OPJ_UINT32)dwt->sn * (OPJ_SIZE_T)width;
    bi = dwt->wavelet + 1 - dwt->cas;

    for (i = dwt->win_h_x0; i < dwt->win_h_x1; ++i) {
        memcpy(&bi[i * 2], &a[i * (OPJ_SIZE_T)width],
               (OPJ_SIZE_T)nb_elts_read * sizeof(OPJ_FLOAT32));
    }
}

static void opj_v8dwt_interleave_partial_v(opj_v8dwt_t* OPJ_RESTRICT dwt,
        opj_sparse_array_int32_t* sa,
        OPJ_UINT32 sa_col,
        OPJ_UINT32 nb_elts_read)
{
    OPJ_BOOL ret;
    ret = opj_sparse_array_int32_read(sa,
                                      sa_col, dwt->win_l_x0,
                                      sa_col + nb_elts_read, dwt->win_l_x1,
                                      (OPJ_INT32*)(dwt->wavelet + dwt->cas + 2 * dwt->win_l_x0),
                                      1, 2 * NB_ELTS_V8, OPJ_TRUE);
    assert(ret);
    ret = opj_sparse_array_int32_read(sa,
                                      sa_col, (OPJ_UINT32)dwt->sn + dwt->win_h_x0,
                                      sa_col + nb_elts_read, (OPJ_UINT32)dwt->sn + dwt->win_h_x1,
                                      (OPJ_INT32*)(dwt->wavelet + 1 - dwt->cas + 2 * dwt->win_h_x0),
                                      1, 2 * NB_ELTS_V8, OPJ_TRUE);
    assert(ret);
    OPJ_UNUSED(ret);
}

#ifdef __SSE__

static void opj_v8dwt_decode_step1_sse(opj_v8_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       const __m128 c)
{
    __m128* OPJ_RESTRICT vw = (__m128*) w;
    OPJ_UINT32 i = start;
    /* To be adapted if NB_ELTS_V8 changes */
    vw += 4 * start;
    /* Note: attempt at loop unrolling x2 doesn't help */









    for (; i < end; ++i, vw += 4) {
        vw[0] = _mm_mul_ps(vw[0], c);
        vw[1] = _mm_mul_ps(vw[1], c);
    }
}

static void opj_v8dwt_decode_step2_sse(opj_v8_t* l, opj_v8_t* w,
                                       OPJ_UINT32 start,
                                       OPJ_UINT32 end,
                                       OPJ_UINT32 m,
                                       __m128 c)
{
    __m128* OPJ_RESTRICT vl = (__m128*) l;
    __m128* OPJ_RESTRICT vw = (__m128*) w;
    /* To be adapted if NB_ELTS_V8 changes */
    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);

    if (start == 0) {
        if (imax >= 1) {
            vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(_mm_add_ps(vl[0], vw[0]), c));
            vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(_mm_add_ps(vl[1], vw[1]), c));
            vw += 4;
            start = 1;
        }
    } else {
        vw += start * 4;

    }

    i = start;

    /* Note: attempt at loop unrolling x2 doesn't help */


















    for (; i < imax; ++i) {
        vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(_mm_add_ps(vw[-4], vw[0]), c));

        vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(_mm_add_ps(vw[-3], vw[1]), c));

        vw += 4;
    }
    if (m < end) {
        assert(m + 1 == end);
        c = _mm_add_ps(c, c);
        vw[-2] = _mm_add_ps(vw[-2], _mm_mul_ps(c, vw[-4]));
        vw[-1] = _mm_add_ps(vw[-1], _mm_mul_ps(c, vw[-3]));
    }
}

#else

static void opj_v8dwt_decode_step1(opj_v8_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   const OPJ_FLOAT32 c)
{
    OPJ_FLOAT32* OPJ_RESTRICT fw = (OPJ_FLOAT32*) w;
    OPJ_UINT32 i;
    /* To be adapted if NB_ELTS_V8 changes */
    for (i = start; i < end; ++i) {
        fw[i * 2 * 8    ] = fw[i * 2 * 8    ] * c;
        fw[i * 2 * 8 + 1] = fw[i * 2 * 8 + 1] * c;
        fw[i * 2 * 8 + 2] = fw[i * 2 * 8 + 2] * c;
        fw[i * 2 * 8 + 3] = fw[i * 2 * 8 + 3] * c;
        fw[i * 2 * 8 + 4] = fw[i * 2 * 8 + 4] * c;
        fw[i * 2 * 8 + 5] = fw[i * 2 * 8 + 5] * c;
        fw[i * 2 * 8 + 6] = fw[i * 2 * 8 + 6] * c;
        fw[i * 2 * 8 + 7] = fw[i * 2 * 8 + 7] * c;
    }
}

static void opj_v8dwt_decode_step2(opj_v8_t* l, opj_v8_t* w,
                                   OPJ_UINT32 start,
                                   OPJ_UINT32 end,
                                   OPJ_UINT32 m,
                                   OPJ_FLOAT32 c)
{
    OPJ_FLOAT32* fl = (OPJ_FLOAT32*) l;
    OPJ_FLOAT32* fw = (OPJ_FLOAT32*) w;
    OPJ_UINT32 i;
    OPJ_UINT32 imax = opj_uint_min(end, m);
    if (start > 0) {
        fw += 2 * NB_ELTS_V8 * start;
        fl = fw - 2 * NB_ELTS_V8;
    }
    /* To be adapted if NB_ELTS_V8 changes */
    for (i = start; i < imax; ++i) {




        fw[-8] = fw[-8] + ((fl[0] + fw[0]) * c);
        fw[-7] = fw[-7] + ((fl[1] + fw[1]) * c);
        fw[-6] = fw[-6] + ((fl[2] + fw[2]) * c);
        fw[-5] = fw[-5] + ((fl[3] + fw[3]) * c);




        fw[-4] = fw[-4] + ((fl[4] + fw[4]) * c);
        fw[-3] = fw[-3] + ((fl[5] + fw[5]) * c);
        fw[-2] = fw[-2] + ((fl[6] + fw[6]) * c);
        fw[-1] = fw[-1] + ((fl[7] + fw[7]) * c);
        fl = fw;
        fw += 2 * NB_ELTS_V8;
    }
    if (m < end) {
        assert(m + 1 == end);
        c += c;
        fw[-8] = fw[-8] + fl[0] * c;
        fw[-7] = fw[-7] + fl[1] * c;
        fw[-6] = fw[-6] + fl[2] * c;
        fw[-5] = fw[-5] + fl[3] * c;
        fw[-4] = fw[-4] + fl[4] * c;
        fw[-3] = fw[-3] + fl[5] * c;
        fw[-2] = fw[-2] + fl[6] * c;
        fw[-1] = fw[-1] + fl[7] * c;
    }
}

#endif

/* <summary>                             */
/* Inverse 9-7 wavelet transform in 1-D. */
/* </summary>                            */
static void opj_v8dwt_decode(opj_v8dwt_t* OPJ_RESTRICT dwt)
{
    OPJ_INT32 a, b;
    /* BUG_WEIRD_TWO_INVK (look for this identifier in tcd.c) */
    /* Historic value for 2 / opj_invK */
    /* Normally, we should use invK, but if we do so, we have failures in the */
    /* conformance test, due to MSE and peak errors significantly higher than */
    /* accepted value */
    /* Due to using two_invK instead of invK, we have to compensate in tcd.c */
    /* the computation of the stepsize for the non LL subbands */
    const float two_invK = 1.625732422f;
    if (dwt->cas == 0) {
        if (!((dwt->dn > 0) || (dwt->sn > 1))) {
            return;
        }
        a = 0;
        b = 1;
    } else {
        if (!((dwt->sn > 0) || (dwt->dn > 1))) {
            return;
        }
        a = 1;
        b = 0;
    }
#ifdef __SSE__
    opj_v8dwt_decode_step1_sse(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
                               _mm_set1_ps(opj_K));
    opj_v8dwt_decode_step1_sse(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
                               _mm_set1_ps(two_invK));
    opj_v8dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
                               dwt->win_l_x0, dwt->win_l_x1,
                               (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                               _mm_set1_ps(-opj_dwt_delta));
    opj_v8dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
                               dwt->win_h_x0, dwt->win_h_x1,
                               (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                               _mm_set1_ps(-opj_dwt_gamma));
    opj_v8dwt_decode_step2_sse(dwt->wavelet + b, dwt->wavelet + a + 1,
                               dwt->win_l_x0, dwt->win_l_x1,
                               (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                               _mm_set1_ps(-opj_dwt_beta));
    opj_v8dwt_decode_step2_sse(dwt->wavelet + a, dwt->wavelet + b + 1,
                               dwt->win_h_x0, dwt->win_h_x1,
                               (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                               _mm_set1_ps(-opj_dwt_alpha));
#else
    opj_v8dwt_decode_step1(dwt->wavelet + a, dwt->win_l_x0, dwt->win_l_x1,
                           opj_K);
    opj_v8dwt_decode_step1(dwt->wavelet + b, dwt->win_h_x0, dwt->win_h_x1,
                           two_invK);
    opj_v8dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
                           dwt->win_l_x0, dwt->win_l_x1,
                           (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                           -opj_dwt_delta);
    opj_v8dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
                           dwt->win_h_x0, dwt->win_h_x1,
                           (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                           -opj_dwt_gamma);
    opj_v8dwt_decode_step2(dwt->wavelet + b, dwt->wavelet + a + 1,
                           dwt->win_l_x0, dwt->win_l_x1,
                           (OPJ_UINT32)opj_int_min(dwt->sn, dwt->dn - a),
                           -opj_dwt_beta);
    opj_v8dwt_decode_step2(dwt->wavelet + a, dwt->wavelet + b + 1,
                           dwt->win_h_x0, dwt->win_h_x1,
                           (OPJ_UINT32)opj_int_min(dwt->dn, dwt->sn - b),
                           -opj_dwt_alpha);
#endif
}

typedef struct {
    opj_v8dwt_t h;
    OPJ_UINT32 rw;
    OPJ_UINT32 w;
    OPJ_FLOAT32 * OPJ_RESTRICT aj;
    OPJ_UINT32 nb_rows;
} opj_dwt97_decode_h_job_t;

static void opj_dwt97_decode_h_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt97_decode_h_job_t* job;
    OPJ_FLOAT32 * OPJ_RESTRICT aj;
    OPJ_UINT32 w;
    (void)tls;

    job = (opj_dwt97_decode_h_job_t*)user_data;
    w = job->w;

    assert((job->nb_rows % NB_ELTS_V8) == 0);

    aj = job->aj;
    for (j = 0; j + NB_ELTS_V8 <= job->nb_rows; j += NB_ELTS_V8) {
        OPJ_UINT32 k;
        opj_v8dwt_interleave_h(&job->h, aj, job->w, NB_ELTS_V8);
        opj_v8dwt_decode(&job->h);

        /* To be adapted if NB_ELTS_V8 changes */
        for (k = 0; k < job->rw; k++) {
            aj[k      ] = job->h.wavelet[k].f[0];
            aj[k + (OPJ_SIZE_T)w  ] = job->h.wavelet[k].f[1];
            aj[k + (OPJ_SIZE_T)w * 2] = job->h.wavelet[k].f[2];
            aj[k + (OPJ_SIZE_T)w * 3] = job->h.wavelet[k].f[3];
        }
        for (k = 0; k < job->rw; k++) {
            aj[k + (OPJ_SIZE_T)w * 4] = job->h.wavelet[k].f[4];
            aj[k + (OPJ_SIZE_T)w * 5] = job->h.wavelet[k].f[5];
            aj[k + (OPJ_SIZE_T)w * 6] = job->h.wavelet[k].f[6];
            aj[k + (OPJ_SIZE_T)w * 7] = job->h.wavelet[k].f[7];
        }

        aj += w * NB_ELTS_V8;
    }

    opj_aligned_free(job->h.wavelet);
    opj_free(job);
}


typedef struct {
    opj_v8dwt_t v;
    OPJ_UINT32 rh;
    OPJ_UINT32 w;
    OPJ_FLOAT32 * OPJ_RESTRICT aj;
    OPJ_UINT32 nb_columns;
} opj_dwt97_decode_v_job_t;

static void opj_dwt97_decode_v_func(void* user_data, opj_tls_t* tls)
{
    OPJ_UINT32 j;
    opj_dwt97_decode_v_job_t* job;
    OPJ_FLOAT32 * OPJ_RESTRICT aj;
    (void)tls;

    job = (opj_dwt97_decode_v_job_t*)user_data;

    assert((job->nb_columns % NB_ELTS_V8) == 0);

    aj = job->aj;
    for (j = 0; j + NB_ELTS_V8 <= job->nb_columns; j += NB_ELTS_V8) {
        OPJ_UINT32 k;

        opj_v8dwt_interleave_v(&job->v, aj, job->w, NB_ELTS_V8);
        opj_v8dwt_decode(&job->v);

        for (k = 0; k < job->rh; ++k) {
            memcpy(&aj[k * (OPJ_SIZE_T)job->w], &job->v.wavelet[k],
                   NB_ELTS_V8 * sizeof(OPJ_FLOAT32));
        }
        aj += NB_ELTS_V8;
    }

    opj_aligned_free(job->v.wavelet);
    opj_free(job);
}


/* <summary>                             */
/* Inverse 9-7 wavelet transform in 2-D. */
/* </summary>                            */
static
OPJ_BOOL opj_dwt_decode_tile_97(opj_thread_pool_t* tp,
                                opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                                OPJ_UINT32 numres)
{
    opj_v8dwt_t h;
    opj_v8dwt_t v;

    opj_tcd_resolution_t* res = tilec->resolutions;

    OPJ_UINT32 rw = (OPJ_UINT32)(res->x1 -
                                 res->x0);    /* width of the resolution level computed */
    OPJ_UINT32 rh = (OPJ_UINT32)(res->y1 -
                                 res->y0);    /* height of the resolution level computed */

    OPJ_UINT32 w = (OPJ_UINT32)(tilec->resolutions[tilec->minimum_num_resolutions -
                                                               1].x1 -
                                tilec->resolutions[tilec->minimum_num_resolutions - 1].x0);

    OPJ_SIZE_T l_data_size;
    const int num_threads = opj_thread_pool_get_thread_count(tp);

    if (numres == 1) {
        return OPJ_TRUE;
    }

    l_data_size = opj_dwt_max_resolution(res, numres);
    /* overflow check */






    if (l_data_size > (SIZE_MAX / sizeof(opj_v8_t))) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    h.wavelet = (opj_v8_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v8_t));
    if (!h.wavelet) {
        /* FIXME event manager error callback */
        return OPJ_FALSE;
    }
    v.wavelet = h.wavelet;

    while (--numres) {
2562
2563
2564
2565
2566
2567
2568


2569
2570
2571
2572
2573

2574
2575
2576
2577
2578
2579





2580

2581










































2582
2583
2584
2585
2586
2587
2588

2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609

2610
2611
2612
2613
2614
2615
2616
2617























2618



















2619

2620

2621

2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
        h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
        h.cas = res->x0 % 2;

        h.win_l_x0 = 0;
        h.win_l_x1 = (OPJ_UINT32)h.sn;
        h.win_h_x0 = 0;
        h.win_h_x1 = (OPJ_UINT32)h.dn;


        for (j = 0; j + 3 < rh; j += 4) {
            OPJ_UINT32 k;
            opj_v4dwt_interleave_h(&h, aj, w, rh - j);
            opj_v4dwt_decode(&h);


            for (k = 0; k < rw; k++) {
                aj[k      ] = h.wavelet[k].f[0];
                aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
                aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
                aj[k + (OPJ_SIZE_T)w * 3] = h.wavelet[k].f[3];
            }







            aj += w * 4;










































        }

        if (j < rh) {
            OPJ_UINT32 k;
            opj_v4dwt_interleave_h(&h, aj, w, rh - j);
            opj_v4dwt_decode(&h);
            for (k = 0; k < rw; k++) {

                switch (rh - j) {
                case 3:
                    aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
                /* FALLTHRU */
                case 2:
                    aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
                /* FALLTHRU */
                case 1:
                    aj[k] = h.wavelet[k].f[0];
                }
            }
        }

        v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
        v.cas = res->y0 % 2;
        v.win_l_x0 = 0;
        v.win_l_x1 = (OPJ_UINT32)v.sn;
        v.win_h_x0 = 0;
        v.win_h_x1 = (OPJ_UINT32)v.dn;

        aj = (OPJ_FLOAT32*) tilec->data;

        for (j = rw; j > 3; j -= 4) {
            OPJ_UINT32 k;

            opj_v4dwt_interleave_v(&v, aj, w, 4);
            opj_v4dwt_decode(&v);

            for (k = 0; k < rh; ++k) {
                memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k], 4 * sizeof(OPJ_FLOAT32));























            }



















            aj += 4;

        }



        if (rw & 0x03) {
            OPJ_UINT32 k;

            j = rw & 0x03;

            opj_v4dwt_interleave_v(&v, aj, w, j);
            opj_v4dwt_decode(&v);

            for (k = 0; k < rh; ++k) {
                memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k],
                       (OPJ_SIZE_T)j * sizeof(OPJ_FLOAT32));
            }
        }
    }

    opj_aligned_free(h.wavelet);
    return OPJ_TRUE;
}

static
OPJ_BOOL opj_dwt_decode_partial_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                                   OPJ_UINT32 numres)
{
    opj_sparse_array_int32_t* sa;
    opj_v4dwt_t h;
    opj_v4dwt_t v;
    OPJ_UINT32 resno;
    /* This value matches the maximum left/right extension given in tables */
    /* F.2 and F.3 of the standard. Note: in opj_tcd_is_subband_area_of_interest() */
    /* we currently use 3. */
    const OPJ_UINT32 filter_width = 4U;

    opj_tcd_resolution_t* tr = tilec->resolutions;







>
>
|
|
|
|

>
|
|
|
|
|
|
>
>
>
>
>
|
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
|

>
|
<
<
<
<
<
<
<
|












>
|
|

|
|

|
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>
|
>
|
>
|


|

|
|

















|
|







3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421







3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
        h.dn = (OPJ_INT32)(rw - (OPJ_UINT32)h.sn);
        h.cas = res->x0 % 2;

        h.win_l_x0 = 0;
        h.win_l_x1 = (OPJ_UINT32)h.sn;
        h.win_h_x0 = 0;
        h.win_h_x1 = (OPJ_UINT32)h.dn;

        if (num_threads <= 1 || rh < 2 * NB_ELTS_V8) {
            for (j = 0; j + (NB_ELTS_V8 - 1) < rh; j += NB_ELTS_V8) {
                OPJ_UINT32 k;
                opj_v8dwt_interleave_h(&h, aj, w, NB_ELTS_V8);
                opj_v8dwt_decode(&h);

                /* To be adapted if NB_ELTS_V8 changes */
                for (k = 0; k < rw; k++) {
                    aj[k      ] = h.wavelet[k].f[0];
                    aj[k + (OPJ_SIZE_T)w  ] = h.wavelet[k].f[1];
                    aj[k + (OPJ_SIZE_T)w * 2] = h.wavelet[k].f[2];
                    aj[k + (OPJ_SIZE_T)w * 3] = h.wavelet[k].f[3];
                }
                for (k = 0; k < rw; k++) {
                    aj[k + (OPJ_SIZE_T)w * 4] = h.wavelet[k].f[4];
                    aj[k + (OPJ_SIZE_T)w * 5] = h.wavelet[k].f[5];
                    aj[k + (OPJ_SIZE_T)w * 6] = h.wavelet[k].f[6];
                    aj[k + (OPJ_SIZE_T)w * 7] = h.wavelet[k].f[7];
                }

                aj += w * NB_ELTS_V8;
            }
        } else {
            OPJ_UINT32 num_jobs = (OPJ_UINT32)num_threads;
            OPJ_UINT32 step_j;

            if ((rh / NB_ELTS_V8) < num_jobs) {
                num_jobs = rh / NB_ELTS_V8;
            }
            step_j = ((rh / num_jobs) / NB_ELTS_V8) * NB_ELTS_V8;
            for (j = 0; j < num_jobs; j++) {
                opj_dwt97_decode_h_job_t* job;

                job = (opj_dwt97_decode_h_job_t*) opj_malloc(sizeof(opj_dwt97_decode_h_job_t));
                if (!job) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
                job->h.wavelet = (opj_v8_t*)opj_aligned_malloc(l_data_size * sizeof(opj_v8_t));
                if (!job->h.wavelet) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_free(job);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
                job->h.dn = h.dn;
                job->h.sn = h.sn;
                job->h.cas = h.cas;
                job->h.win_l_x0 = h.win_l_x0;
                job->h.win_l_x1 = h.win_l_x1;
                job->h.win_h_x0 = h.win_h_x0;
                job->h.win_h_x1 = h.win_h_x1;
                job->rw = rw;
                job->w = w;
                job->aj = aj;
                job->nb_rows = (j + 1 == num_jobs) ? (rh & (OPJ_UINT32)~
                                                      (NB_ELTS_V8 - 1)) - j * step_j : step_j;
                aj += w * job->nb_rows;
                opj_thread_pool_submit_job(tp, opj_dwt97_decode_h_func, job);
            }
            opj_thread_pool_wait_completion(tp, 0);
            j = rh & (OPJ_UINT32)~(NB_ELTS_V8 - 1);
        }

        if (j < rh) {
            OPJ_UINT32 k;
            opj_v8dwt_interleave_h(&h, aj, w, rh - j);
            opj_v8dwt_decode(&h);
            for (k = 0; k < rw; k++) {
                OPJ_UINT32 l;
                for (l = 0; l < rh - j; l++) {







                    aj[k + (OPJ_SIZE_T)w  * l ] = h.wavelet[k].f[l];
                }
            }
        }

        v.dn = (OPJ_INT32)(rh - (OPJ_UINT32)v.sn);
        v.cas = res->y0 % 2;
        v.win_l_x0 = 0;
        v.win_l_x1 = (OPJ_UINT32)v.sn;
        v.win_h_x0 = 0;
        v.win_h_x1 = (OPJ_UINT32)v.dn;

        aj = (OPJ_FLOAT32*) tilec->data;
        if (num_threads <= 1 || rw < 2 * NB_ELTS_V8) {
            for (j = rw; j > (NB_ELTS_V8 - 1); j -= NB_ELTS_V8) {
                OPJ_UINT32 k;

                opj_v8dwt_interleave_v(&v, aj, w, NB_ELTS_V8);
                opj_v8dwt_decode(&v);

                for (k = 0; k < rh; ++k) {
                    memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k], NB_ELTS_V8 * sizeof(OPJ_FLOAT32));
                }
                aj += NB_ELTS_V8;
            }
        } else {
            /* "bench_dwt -I" shows that scaling is poor, likely due to RAM
                transfer being the limiting factor. So limit the number of
                threads.
             */
            OPJ_UINT32 num_jobs = opj_uint_max((OPJ_UINT32)num_threads / 2, 2U);
            OPJ_UINT32 step_j;

            if ((rw / NB_ELTS_V8) < num_jobs) {
                num_jobs = rw / NB_ELTS_V8;
            }
            step_j = ((rw / num_jobs) / NB_ELTS_V8) * NB_ELTS_V8;
            for (j = 0; j < num_jobs; j++) {
                opj_dwt97_decode_v_job_t* job;

                job = (opj_dwt97_decode_v_job_t*) opj_malloc(sizeof(opj_dwt97_decode_v_job_t));
                if (!job) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
                job->v.wavelet = (opj_v8_t*)opj_aligned_malloc(l_data_size * sizeof(opj_v8_t));
                if (!job->v.wavelet) {
                    opj_thread_pool_wait_completion(tp, 0);
                    opj_free(job);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
                job->v.dn = v.dn;
                job->v.sn = v.sn;
                job->v.cas = v.cas;
                job->v.win_l_x0 = v.win_l_x0;
                job->v.win_l_x1 = v.win_l_x1;
                job->v.win_h_x0 = v.win_h_x0;
                job->v.win_h_x1 = v.win_h_x1;
                job->rh = rh;
                job->w = w;
                job->aj = aj;
                job->nb_columns = (j + 1 == num_jobs) ? (rw & (OPJ_UINT32)~
                                  (NB_ELTS_V8 - 1)) - j * step_j : step_j;
                aj += job->nb_columns;
                opj_thread_pool_submit_job(tp, opj_dwt97_decode_v_func, job);
            }
            opj_thread_pool_wait_completion(tp, 0);
        }

        if (rw & (NB_ELTS_V8 - 1)) {
            OPJ_UINT32 k;

            j = rw & (NB_ELTS_V8 - 1);

            opj_v8dwt_interleave_v(&v, aj, w, j);
            opj_v8dwt_decode(&v);

            for (k = 0; k < rh; ++k) {
                memcpy(&aj[k * (OPJ_SIZE_T)w], &v.wavelet[k],
                       (OPJ_SIZE_T)j * sizeof(OPJ_FLOAT32));
            }
        }
    }

    opj_aligned_free(h.wavelet);
    return OPJ_TRUE;
}

static
OPJ_BOOL opj_dwt_decode_partial_97(opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                                   OPJ_UINT32 numres)
{
    opj_sparse_array_int32_t* sa;
    opj_v8dwt_t h;
    opj_v8dwt_t v;
    OPJ_UINT32 resno;
    /* This value matches the maximum left/right extension given in tables */
    /* F.2 and F.3 of the standard. Note: in opj_tcd_is_subband_area_of_interest() */
    /* we currently use 3. */
    const OPJ_UINT32 filter_width = 4U;

    opj_tcd_resolution_t* tr = tilec->resolutions;
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
        OPJ_UNUSED(ret);
        opj_sparse_array_int32_free(sa);
        return OPJ_TRUE;
    }

    l_data_size = opj_dwt_max_resolution(tr, numres);
    /* overflow check */
    if (l_data_size > (SIZE_MAX - 5U)) {
        /* FIXME event manager error callback */
        opj_sparse_array_int32_free(sa);
        return OPJ_FALSE;
    }
    l_data_size += 5U;
    /* overflow check */
    if (l_data_size > (SIZE_MAX / sizeof(opj_v4_t))) {
        /* FIXME event manager error callback */
        opj_sparse_array_int32_free(sa);
        return OPJ_FALSE;
    }
    h.wavelet = (opj_v4_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v4_t));
    if (!h.wavelet) {
        /* FIXME event manager error callback */
        opj_sparse_array_int32_free(sa);
        return OPJ_FALSE;
    }
    v.wavelet = h.wavelet;








|




<
<
<
<
<
<
<
|







3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572







3573
3574
3575
3576
3577
3578
3579
3580
        OPJ_UNUSED(ret);
        opj_sparse_array_int32_free(sa);
        return OPJ_TRUE;
    }

    l_data_size = opj_dwt_max_resolution(tr, numres);
    /* overflow check */
    if (l_data_size > (SIZE_MAX / sizeof(opj_v8_t))) {
        /* FIXME event manager error callback */
        opj_sparse_array_int32_free(sa);
        return OPJ_FALSE;
    }







    h.wavelet = (opj_v8_t*) opj_aligned_malloc(l_data_size * sizeof(opj_v8_t));
    if (!h.wavelet) {
        /* FIXME event manager error callback */
        opj_sparse_array_int32_free(sa);
        return OPJ_FALSE;
    }
    v.wavelet = h.wavelet;

2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
            win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
        }

        h.win_l_x0 = win_ll_x0;
        h.win_l_x1 = win_ll_x1;
        h.win_h_x0 = win_hl_x0;
        h.win_h_x1 = win_hl_x1;
        for (j = 0; j + 3 < rh; j += 4) {
            if ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
                    (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
                     j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
                opj_v4dwt_interleave_partial_h(&h, sa, j, opj_uint_min(4U, rh - j));
                opj_v4dwt_decode(&h);
                if (!opj_sparse_array_int32_write(sa,
                                                  win_tr_x0, j,
                                                  win_tr_x1, j + 4,
                                                  (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
                                                  4, 1, OPJ_TRUE)) {
                    /* FIXME event manager error callback */
                    opj_sparse_array_int32_free(sa);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
            }
        }

        if (j < rh &&
                ((j + 3 >= win_ll_y0 && j < win_ll_y1) ||
                 (j + 3 >= win_lh_y0 + (OPJ_UINT32)v.sn &&
                  j < win_lh_y1 + (OPJ_UINT32)v.sn))) {
            opj_v4dwt_interleave_partial_h(&h, sa, j, rh - j);
            opj_v4dwt_decode(&h);
            if (!opj_sparse_array_int32_write(sa,
                                              win_tr_x0, j,
                                              win_tr_x1, rh,
                                              (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
                                              4, 1, OPJ_TRUE)) {
                /* FIXME event manager error callback */
                opj_sparse_array_int32_free(sa);
                opj_aligned_free(h.wavelet);
                return OPJ_FALSE;
            }
        }

        v.win_l_x0 = win_ll_y0;
        v.win_l_x1 = win_ll_y1;
        v.win_h_x0 = win_lh_y0;
        v.win_h_x1 = win_lh_y1;
        for (j = win_tr_x0; j < win_tr_x1; j += 4) {
            OPJ_UINT32 nb_elts = opj_uint_min(4U, win_tr_x1 - j);

            opj_v4dwt_interleave_partial_v(&v, sa, j, nb_elts);
            opj_v4dwt_decode(&v);

            if (!opj_sparse_array_int32_write(sa,
                                              j, win_tr_y0,
                                              j + nb_elts, win_tr_y1,
                                              (OPJ_INT32*)&h.wavelet[win_tr_y0].f[0],
                                              1, 4, OPJ_TRUE)) {
                /* FIXME event manager error callback */
                opj_sparse_array_int32_free(sa);
                opj_aligned_free(h.wavelet);
                return OPJ_FALSE;
            }
        }
    }







|
|
|

|
|


|

|









|
|

|
|




|











|
|

|
|





|







3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
            win_tr_y1 = opj_uint_min(opj_uint_max(2 * win_lh_y1, 2 * win_ll_y1 + 1), rh);
        }

        h.win_l_x0 = win_ll_x0;
        h.win_l_x1 = win_ll_x1;
        h.win_h_x0 = win_hl_x0;
        h.win_h_x1 = win_hl_x1;
        for (j = 0; j + (NB_ELTS_V8 - 1) < rh; j += NB_ELTS_V8) {
            if ((j + (NB_ELTS_V8 - 1) >= win_ll_y0 && j < win_ll_y1) ||
                    (j + (NB_ELTS_V8 - 1) >= win_lh_y0 + (OPJ_UINT32)v.sn &&
                     j < win_lh_y1 + (OPJ_UINT32)v.sn)) {
                opj_v8dwt_interleave_partial_h(&h, sa, j, opj_uint_min(NB_ELTS_V8, rh - j));
                opj_v8dwt_decode(&h);
                if (!opj_sparse_array_int32_write(sa,
                                                  win_tr_x0, j,
                                                  win_tr_x1, j + NB_ELTS_V8,
                                                  (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
                                                  NB_ELTS_V8, 1, OPJ_TRUE)) {
                    /* FIXME event manager error callback */
                    opj_sparse_array_int32_free(sa);
                    opj_aligned_free(h.wavelet);
                    return OPJ_FALSE;
                }
            }
        }

        if (j < rh &&
                ((j + (NB_ELTS_V8 - 1) >= win_ll_y0 && j < win_ll_y1) ||
                 (j + (NB_ELTS_V8 - 1) >= win_lh_y0 + (OPJ_UINT32)v.sn &&
                  j < win_lh_y1 + (OPJ_UINT32)v.sn))) {
            opj_v8dwt_interleave_partial_h(&h, sa, j, rh - j);
            opj_v8dwt_decode(&h);
            if (!opj_sparse_array_int32_write(sa,
                                              win_tr_x0, j,
                                              win_tr_x1, rh,
                                              (OPJ_INT32*)&h.wavelet[win_tr_x0].f[0],
                                              NB_ELTS_V8, 1, OPJ_TRUE)) {
                /* FIXME event manager error callback */
                opj_sparse_array_int32_free(sa);
                opj_aligned_free(h.wavelet);
                return OPJ_FALSE;
            }
        }

        v.win_l_x0 = win_ll_y0;
        v.win_l_x1 = win_ll_y1;
        v.win_h_x0 = win_lh_y0;
        v.win_h_x1 = win_lh_y1;
        for (j = win_tr_x0; j < win_tr_x1; j += NB_ELTS_V8) {
            OPJ_UINT32 nb_elts = opj_uint_min(NB_ELTS_V8, win_tr_x1 - j);

            opj_v8dwt_interleave_partial_v(&v, sa, j, nb_elts);
            opj_v8dwt_decode(&v);

            if (!opj_sparse_array_int32_write(sa,
                                              j, win_tr_y0,
                                              j + nb_elts, win_tr_y1,
                                              (OPJ_INT32*)&h.wavelet[win_tr_y0].f[0],
                                              1, NB_ELTS_V8, OPJ_TRUE)) {
                /* FIXME event manager error callback */
                opj_sparse_array_int32_free(sa);
                opj_aligned_free(h.wavelet);
                return OPJ_FALSE;
            }
        }
    }
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892


OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                             OPJ_UINT32 numres)
{
    if (p_tcd->whole_tile_decoding) {
        return opj_dwt_decode_tile_97(tilec, numres);
    } else {
        return opj_dwt_decode_partial_97(tilec, numres);
    }
}







|




3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756


OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                             OPJ_UINT32 numres)
{
    if (p_tcd->whole_tile_decoding) {
        return opj_dwt_decode_tile_97(p_tcd->thread_pool, tilec, numres);
    } else {
        return opj_dwt_decode_partial_97(tilec, numres);
    }
}
Changes to jni/openjpeg/src/lib/openjp2/dwt.h.
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

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */
/**
Forward 5-3 wavelet transform in 2-D.
Apply a reversible DWT transform to a component of an image.

@param tilec Tile component information (current tile)
*/
OPJ_BOOL opj_dwt_encode(opj_tcd_tilecomp_t * tilec);


/**
Inverse 5-3 wavelet transform in 2-D.
Apply a reversible inverse DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
@param numres Number of resolution levels to decode
*/
OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd,
                        opj_tcd_tilecomp_t* tilec,
                        OPJ_UINT32 numres);

/**
Get the gain of a subband for the reversible 5-3 DWT.
@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH)
@return Returns 0 if orient = 0, returns 1 if orient = 1 or 2, returns 2 otherwise
*/
OPJ_UINT32 opj_dwt_getgain(OPJ_UINT32 orient) ;
/**
Get the norm of a wavelet function of a subband at a specified level for the reversible 5-3 DWT.
@param level Level of the wavelet function
@param orient Band of the wavelet function
@return Returns the norm of the wavelet function
*/
OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient);
/**
Forward 9-7 wavelet transform in 2-D.
Apply an irreversible DWT transform to a component of an image.

@param tilec Tile component information (current tile)
*/
OPJ_BOOL opj_dwt_encode_real(opj_tcd_tilecomp_t * tilec);

/**
Inverse 9-7 wavelet transform in 2-D.
Apply an irreversible inverse DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
@param numres Number of resolution levels to decode
*/
OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                             OPJ_UINT32 numres);

/**
Get the gain of a subband for the irreversible 9-7 DWT.
@param orient Number that identifies the subband (0->LL, 1->HL, 2->LH, 3->HH)
@return Returns the gain of the 9-7 wavelet transform
*/
OPJ_UINT32 opj_dwt_getgain_real(OPJ_UINT32 orient);
/**
Get the norm of a wavelet function of a subband at a specified level for the irreversible 9-7 DWT
@param level Level of the wavelet function
@param orient Band of the wavelet function
@return Returns the norm of the 9-7 wavelet
*/
OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient);
/**







>


|
>













<
<
<
<
<
<









>


|
>












<
<
<
<
<
<







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

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */
/**
Forward 5-3 wavelet transform in 2-D.
Apply a reversible DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
*/
OPJ_BOOL opj_dwt_encode(opj_tcd_t *p_tcd,
                        opj_tcd_tilecomp_t * tilec);

/**
Inverse 5-3 wavelet transform in 2-D.
Apply a reversible inverse DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
@param numres Number of resolution levels to decode
*/
OPJ_BOOL opj_dwt_decode(opj_tcd_t *p_tcd,
                        opj_tcd_tilecomp_t* tilec,
                        OPJ_UINT32 numres);

/**






Get the norm of a wavelet function of a subband at a specified level for the reversible 5-3 DWT.
@param level Level of the wavelet function
@param orient Band of the wavelet function
@return Returns the norm of the wavelet function
*/
OPJ_FLOAT64 opj_dwt_getnorm(OPJ_UINT32 level, OPJ_UINT32 orient);
/**
Forward 9-7 wavelet transform in 2-D.
Apply an irreversible DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
*/
OPJ_BOOL opj_dwt_encode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t * tilec);
/**
Inverse 9-7 wavelet transform in 2-D.
Apply an irreversible inverse DWT transform to a component of an image.
@param p_tcd TCD handle
@param tilec Tile component information (current tile)
@param numres Number of resolution levels to decode
*/
OPJ_BOOL opj_dwt_decode_real(opj_tcd_t *p_tcd,
                             opj_tcd_tilecomp_t* OPJ_RESTRICT tilec,
                             OPJ_UINT32 numres);

/**






Get the norm of a wavelet function of a subband at a specified level for the irreversible 9-7 DWT
@param level Level of the wavelet function
@param orient Band of the wavelet function
@return Returns the norm of the 9-7 wavelet
*/
OPJ_FLOAT64 opj_dwt_getnorm_real(OPJ_UINT32 level, OPJ_UINT32 orient);
/**
Changes to jni/openjpeg/src/lib/openjp2/j2k.c.
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
 */
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
        opj_event_mgr_t * p_manager);

static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 p_total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager);

static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 p_total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager);

/**
 * Gets the offset of the header.
 *
 * @param       p_stream                the stream to write data to.







|






|







396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
 */
static OPJ_BOOL opj_j2k_setup_header_writing(opj_j2k_t *p_j2k,
        opj_event_mgr_t * p_manager);

static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager);

static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager);

/**
 * Gets the offset of the header.
 *
 * @param       p_stream                the stream to write data to.
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
                                  opj_event_mgr_t * p_manager);

/**
 * Writes the SOT marker (Start of tile-part)
 *
 * @param       p_j2k            J2K codec.
 * @param       p_data           Output buffer
 * @param       p_total_data_size Output buffer size
 * @param       p_data_written   Number of bytes written into stream
 * @param       p_stream         the stream to write data to.
 * @param       p_manager        the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 p_total_data_size,
                                  OPJ_UINT32 * p_data_written,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager);

/**
 * Reads values from a SOT marker (Start of tile-part)
 *







|






|







828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
                                  opj_event_mgr_t * p_manager);

/**
 * Writes the SOT marker (Start of tile-part)
 *
 * @param       p_j2k            J2K codec.
 * @param       p_data           Output buffer
 * @param       total_data_size  Output buffer size
 * @param       p_data_written   Number of bytes written into stream
 * @param       p_stream         the stream to write data to.
 * @param       p_manager        the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 total_data_size,
                                  OPJ_UINT32 * p_data_written,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager);

/**
 * Reads values from a SOT marker (Start of tile-part)
 *
875
876
877
878
879
880
881


882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
                                 OPJ_BYTE * p_header_data,
                                 OPJ_UINT32 p_header_size,
                                 opj_event_mgr_t * p_manager);
/**
 * Writes the SOD marker (Start of data)
 *


 * @param       p_j2k               J2K codec.
 * @param       p_tile_coder        FIXME DOC
 * @param       p_data              FIXME DOC
 * @param       p_data_written      FIXME DOC
 * @param       p_total_data_size   FIXME DOC
 * @param       p_stream            the stream to write data to.
 * @param       p_manager           the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
                                  opj_tcd_t * p_tile_coder,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_total_data_size,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager);

/**
 * Reads a SOD marker (Start Of Data)
 *
 * @param       p_j2k                   the jpeg2000 codec.







>
>




|







|







875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
static OPJ_BOOL opj_j2k_read_sot(opj_j2k_t *p_j2k,
                                 OPJ_BYTE * p_header_data,
                                 OPJ_UINT32 p_header_size,
                                 opj_event_mgr_t * p_manager);
/**
 * Writes the SOD marker (Start of data)
 *
 * This also writes optional PLT markers (before SOD)
 *
 * @param       p_j2k               J2K codec.
 * @param       p_tile_coder        FIXME DOC
 * @param       p_data              FIXME DOC
 * @param       p_data_written      FIXME DOC
 * @param       total_data_size   FIXME DOC
 * @param       p_stream            the stream to write data to.
 * @param       p_manager           the user event manager.
*/
static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
                                  opj_tcd_t * p_tile_coder,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 total_data_size,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager);

/**
 * Reads a SOD marker (Start Of Data)
 *
 * @param       p_j2k                   the jpeg2000 codec.
1215
1216
1217
1218
1219
1220
1221

1222
1223
1224
1225
1226
1227
1228
1229
1230

1231
1232
1233
1234
1235
1236
1237
                                  opj_event_mgr_t * p_manager);

/**
 * Checks the progression order changes values. Tells of the poc given as input are valid.
 * A nice message is outputted at errors.
 *
 * @param       p_pocs                  the progression order changes.

 * @param       p_nb_pocs               the number of progression order changes.
 * @param       p_nb_resolutions        the number of resolutions.
 * @param       numcomps                the number of components
 * @param       numlayers               the number of layers.
 * @param       p_manager               the user event manager.
 *
 * @return      true if the pocs are valid.
 */
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,

                                      OPJ_UINT32 p_nb_pocs,
                                      OPJ_UINT32 p_nb_resolutions,
                                      OPJ_UINT32 numcomps,
                                      OPJ_UINT32 numlayers,
                                      opj_event_mgr_t * p_manager);

/**







>









>







1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
                                  opj_event_mgr_t * p_manager);

/**
 * Checks the progression order changes values. Tells of the poc given as input are valid.
 * A nice message is outputted at errors.
 *
 * @param       p_pocs                  the progression order changes.
 * @param       tileno                  the tile number of interest
 * @param       p_nb_pocs               the number of progression order changes.
 * @param       p_nb_resolutions        the number of resolutions.
 * @param       numcomps                the number of components
 * @param       numlayers               the number of layers.
 * @param       p_manager               the user event manager.
 *
 * @return      true if the pocs are valid.
 */
static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
                                      OPJ_UINT32 tileno,
                                      OPJ_UINT32 p_nb_pocs,
                                      OPJ_UINT32 p_nb_resolutions,
                                      OPJ_UINT32 numcomps,
                                      OPJ_UINT32 numlayers,
                                      opj_event_mgr_t * p_manager);

/**
1277
1278
1279
1280
1281
1282
1283







1284
1285
1286
1287
1288
1289
1290
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);

static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
        opj_image_t *image, opj_event_mgr_t *p_manager);

static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
        opj_event_mgr_t *p_manager);








/**
 * Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
 *
 * @param       p_stream            the stream to read data from.
 * @param       tile_no             tile number we're looking for.
 * @param       p_correction_needed output value. if true, non conformant codestream needs TNsot correction.







>
>
>
>
>
>
>







1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
static int opj_j2k_initialise_4K_poc(opj_poc_t *POC, int numres);

static void opj_j2k_set_cinema_parameters(opj_cparameters_t *parameters,
        opj_image_t *image, opj_event_mgr_t *p_manager);

static OPJ_BOOL opj_j2k_is_cinema_compliant(opj_image_t *image, OPJ_UINT16 rsiz,
        opj_event_mgr_t *p_manager);

static void opj_j2k_set_imf_parameters(opj_cparameters_t *parameters,
                                       opj_image_t *image, opj_event_mgr_t *p_manager);

static OPJ_BOOL opj_j2k_is_imf_compliant(opj_cparameters_t *parameters,
        opj_image_t *image,
        opj_event_mgr_t *p_manager);

/**
 * Checks for invalid number of tile-parts in SOT marker (TPsot==TNsot). See issue 254.
 *
 * @param       p_stream            the stream to read data from.
 * @param       tile_no             tile number we're looking for.
 * @param       p_correction_needed output value. if true, non conformant codestream needs TNsot correction.
1611
1612
1613
1614
1615
1616
1617

1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631

1632
1633
1634
1635
1636
1637
1638
1639
1640

1641
1642
1643
1644
1645
1646

1647
1648

1649
1650
1651
1652



1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704




1705


1706
1707
1708
1709
1710
1711
1712
            return po->str_prog;
        }
    }
    return po->str_prog;
}

static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,

                                      OPJ_UINT32 p_nb_pocs,
                                      OPJ_UINT32 p_nb_resolutions,
                                      OPJ_UINT32 p_num_comps,
                                      OPJ_UINT32 p_num_layers,
                                      opj_event_mgr_t * p_manager)
{
    OPJ_UINT32* packet_array;
    OPJ_UINT32 index, resno, compno, layno;
    OPJ_UINT32 i;
    OPJ_UINT32 step_c = 1;
    OPJ_UINT32 step_r = p_num_comps * step_c;
    OPJ_UINT32 step_l = p_nb_resolutions * step_r;
    OPJ_BOOL loss = OPJ_FALSE;
    OPJ_UINT32 layno0 = 0;


    packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
                                            sizeof(OPJ_UINT32));
    if (packet_array == 00) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough memory for checking the poc values.\n");
        return OPJ_FALSE;
    }


    if (p_nb_pocs == 0) {
        opj_free(packet_array);
        return OPJ_TRUE;
    }

    index = step_r * p_pocs->resno0;

    /* take each resolution for each poc */
    for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {

        OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;

        /* take each comp of each resolution for each poc */
        for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {



            OPJ_UINT32 comp_index = res_index + layno0 * step_l;

            /* and finally take each layer of each res of ... */
            for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
                /*index = step_r * resno + step_c * compno + step_l * layno;*/
                packet_array[comp_index] = 1;
                comp_index += step_l;
            }

            res_index += step_c;
        }

        index += step_r;
    }
    ++p_pocs;

    /* iterate through all the pocs */
    for (i = 1; i < p_nb_pocs ; ++i) {
        OPJ_UINT32 l_last_layno1 = (p_pocs - 1)->layno1 ;

        layno0 = (p_pocs->layno1 > l_last_layno1) ? l_last_layno1 : 0;
        index = step_r * p_pocs->resno0;

        /* take each resolution for each poc */
        for (resno = p_pocs->resno0 ; resno < p_pocs->resno1 ; ++resno) {
            OPJ_UINT32 res_index = index + p_pocs->compno0 * step_c;

            /* take each comp of each resolution for each poc */
            for (compno = p_pocs->compno0 ; compno < p_pocs->compno1 ; ++compno) {
                OPJ_UINT32 comp_index = res_index + layno0 * step_l;

                /* and finally take each layer of each res of ... */
                for (layno = layno0; layno < p_pocs->layno1 ; ++layno) {
                    /*index = step_r * resno + step_c * compno + step_l * layno;*/
                    packet_array[comp_index] = 1;
                    comp_index += step_l;
                }

                res_index += step_c;
            }

            index += step_r;
        }

        ++p_pocs;
    }

    index = 0;
    for (layno = 0; layno < p_num_layers ; ++layno) {
        for (resno = 0; resno < p_nb_resolutions; ++resno) {
            for (compno = 0; compno < p_num_comps; ++compno) {
                loss |= (packet_array[index] != 1);




                /*index = step_r * resno + step_c * compno + step_l * layno;*/


                index += step_c;
            }
        }
    }

    if (loss) {
        opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");







>













|
>









>
|
|
<
<
|
|
>
|
|
>
|

|
|
>
>
>
|

|
|
|
|
|
|

|
|

|
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







>
>
>
>
|
>
>







1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656


1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683

1684





























1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
            return po->str_prog;
        }
    }
    return po->str_prog;
}

static OPJ_BOOL opj_j2k_check_poc_val(const opj_poc_t *p_pocs,
                                      OPJ_UINT32 tileno,
                                      OPJ_UINT32 p_nb_pocs,
                                      OPJ_UINT32 p_nb_resolutions,
                                      OPJ_UINT32 p_num_comps,
                                      OPJ_UINT32 p_num_layers,
                                      opj_event_mgr_t * p_manager)
{
    OPJ_UINT32* packet_array;
    OPJ_UINT32 index, resno, compno, layno;
    OPJ_UINT32 i;
    OPJ_UINT32 step_c = 1;
    OPJ_UINT32 step_r = p_num_comps * step_c;
    OPJ_UINT32 step_l = p_nb_resolutions * step_r;
    OPJ_BOOL loss = OPJ_FALSE;

    assert(p_nb_pocs > 0);

    packet_array = (OPJ_UINT32*) opj_calloc(step_l * p_num_layers,
                                            sizeof(OPJ_UINT32));
    if (packet_array == 00) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough memory for checking the poc values.\n");
        return OPJ_FALSE;
    }

    /* iterate through all the pocs that match our tile of interest. */
    for (i = 0; i < p_nb_pocs; ++i) {
        const opj_poc_t *poc = &p_pocs[i];


        if (tileno + 1 == poc->tile) {
            index = step_r * poc->resno0;

            /* take each resolution for each poc */
            for (resno = poc->resno0 ;
                    resno < opj_uint_min(poc->resno1, p_nb_resolutions); ++resno) {
                OPJ_UINT32 res_index = index + poc->compno0 * step_c;

                /* take each comp of each resolution for each poc */
                for (compno = poc->compno0 ;
                        compno < opj_uint_min(poc->compno1, p_num_comps); ++compno) {
                    /* The layer index always starts at zero for every progression. */
                    const OPJ_UINT32 layno0 = 0;
                    OPJ_UINT32 comp_index = res_index + layno0 * step_l;

                    /* and finally take each layer of each res of ... */
                    for (layno = layno0; layno < opj_uint_min(poc->layno1, p_num_layers);
                            ++layno) {
                        packet_array[comp_index] = 1;
                        comp_index += step_l;
                    }

                    res_index += step_c;
                }

                index += step_r;
            }

        }





























    }

    index = 0;
    for (layno = 0; layno < p_num_layers ; ++layno) {
        for (resno = 0; resno < p_nb_resolutions; ++resno) {
            for (compno = 0; compno < p_num_comps; ++compno) {
                loss |= (packet_array[index] != 1);
#ifdef DEBUG_VERBOSE
                if (packet_array[index] != 1) {
                    fprintf(stderr,
                            "Missing packet in POC: layno=%d resno=%d compno=%d\n",
                            layno, resno, compno);
                }
#endif
                index += step_c;
            }
        }
    }

    if (loss) {
        opj_event_msg(p_manager, EVT_ERROR, "Missing packets possible loss of data\n");
2709
2710
2711
2712
2713
2714
2715








2716
2717
2718
2719
2720
2721
2722
        l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
    } else {
        l_tcp->num_layers_to_decode = l_tcp->numlayers;
    }

    opj_read_bytes(p_header_data, &l_tcp->mct, 1);          /* SGcod (C) */
    ++p_header_data;









    p_header_size -= 5;
    for (i = 0; i < l_image->numcomps; ++i) {
        l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
    }

    if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,







>
>
>
>
>
>
>
>







2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
        l_tcp->num_layers_to_decode = l_cp->m_specific_param.m_dec.m_layer;
    } else {
        l_tcp->num_layers_to_decode = l_tcp->numlayers;
    }

    opj_read_bytes(p_header_data, &l_tcp->mct, 1);          /* SGcod (C) */
    ++p_header_data;

    if (l_tcp->mct > 1) {
#if 0
        opj_event_msg(p_manager, EVT_ERROR,
                      "Invalid multiple component transformation\n");
        return OPJ_FALSE;
#endif
    }

    p_header_size -= 5;
    for (i = 0; i < l_image->numcomps; ++i) {
        l_tcp->tccps[i].csty = l_tcp->csty & J2K_CCP_CSTY_PRT;
    }

    if (! opj_j2k_read_SPCod_SPCoc(p_j2k, 0, p_header_data, &p_header_size,
3447
3448
3449
3450
3451
3452
3453






















3454
3455
3456
3457
3458
3459
3460
        l_nb_bytes += l_nb_comps * l_coc_bytes;

        l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
        l_nb_bytes += l_nb_comps * l_qcc_bytes;
    }

    l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);























    /*** DEVELOPER CORNER, Add room for your headers ***/

    return l_nb_bytes;
}

/**







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
        l_nb_bytes += l_nb_comps * l_coc_bytes;

        l_qcc_bytes = opj_j2k_get_max_qcc_size(p_j2k);
        l_nb_bytes += l_nb_comps * l_qcc_bytes;
    }

    l_nb_bytes += opj_j2k_get_max_poc_size(p_j2k);

    if (p_j2k->m_specific_param.m_encoder.m_PLT) {
        /* Reserve space for PLT markers */

        OPJ_UINT32 i;
        const opj_cp_t * l_cp = &(p_j2k->m_cp);
        OPJ_UINT32 l_max_packet_count = 0;
        for (i = 0; i < l_cp->th * l_cp->tw; ++i) {
            l_max_packet_count = opj_uint_max(l_max_packet_count,
                                              opj_get_encoding_packet_count(p_j2k->m_private_image, l_cp, i));
        }
        /* Minimum 6 bytes per PLT marker, and at a minimum (taking a pessimistic */
        /* estimate of 4 bytes for a packet size), one can write */
        /* (65536-6) / 4 = 16382 paquet sizes per PLT marker */
        p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT =
            6 * opj_uint_ceildiv(l_max_packet_count, 16382);
        /* Maximum 5 bytes per packet to encode a full UINT32 */
        p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT +=
            l_nb_bytes += 5 * l_max_packet_count;
        p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT += 1;
        l_nb_bytes += p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;
    }

    /*** DEVELOPER CORNER, Add room for your headers ***/

    return l_nb_bytes;
}

/**
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 p_total_data_size,
                                  OPJ_UINT32 * p_data_written,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager
                                 )
{
    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);

    OPJ_UNUSED(p_stream);

    if (p_total_data_size < 12) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough bytes in output buffer to write SOT marker\n");
        return OPJ_FALSE;
    }

    opj_write_bytes(p_data, J2K_MS_SOT,
                    2);                                 /* SOT */







|












|







4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_sot(opj_j2k_t *p_j2k,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 total_data_size,
                                  OPJ_UINT32 * p_data_written,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager
                                 )
{
    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);

    OPJ_UNUSED(p_stream);

    if (total_data_size < 12) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough bytes in output buffer to write SOT marker\n");
        return OPJ_FALSE;
    }

    opj_write_bytes(p_data, J2K_MS_SOT,
                    2);                                 /* SOT */
4606
4607
4608
4609
4610
4611
4612
4613























































































4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624

4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651

       p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
       p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
       p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
       }*/
    return OPJ_TRUE;
}
























































































static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
                                  opj_tcd_t * p_tile_coder,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_total_data_size,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager
                                 )
{
    opj_codestream_info_t *l_cstr_info = 00;
    OPJ_UINT32 l_remaining_data;


    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);

    OPJ_UNUSED(p_stream);

    if (p_total_data_size < 4) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough bytes in output buffer to write SOD marker\n");
        return OPJ_FALSE;
    }

    opj_write_bytes(p_data, J2K_MS_SOD,
                    2);                                 /* SOD */
    p_data += 2;

    /* make room for the EOF marker */
    l_remaining_data =  p_total_data_size - 4;

    /* update tile coder */
    p_tile_coder->tp_num =
        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
    p_tile_coder->cur_tp_num =
        p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;









>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|






>








|







<


|







4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751

4752
4753
4754
4755
4756
4757
4758
4759
4760
4761

       p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos = p_stream_tell(p_stream) - 12;
       p_j2k->cstr_info->tile[tileno].tp[partno].tp_end_pos =
       p_j2k->cstr_info->tile[tileno].tp[partno].tp_start_pos + totlen - 1;
       }*/
    return OPJ_TRUE;
}

/**
 * Write one or more PLT markers in the provided buffer
 */
static OPJ_BOOL opj_j2k_write_plt_in_memory(opj_j2k_t *p_j2k,
        opj_tcd_marker_info_t* marker_info,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        opj_event_mgr_t * p_manager)
{
    OPJ_BYTE Zplt = 0;
    OPJ_UINT16 Lplt;
    OPJ_BYTE* p_data_start = p_data;
    OPJ_BYTE* p_data_Lplt = p_data + 2;
    OPJ_UINT32 i;

    OPJ_UNUSED(p_j2k);

    opj_write_bytes(p_data, J2K_MS_PLT, 2);
    p_data += 2;

    /* Reserve space for Lplt */
    p_data += 2;

    opj_write_bytes(p_data, Zplt, 1);
    p_data += 1;

    Lplt = 3;

    for (i = 0; i < marker_info->packet_count; i++) {
        OPJ_BYTE var_bytes[5];
        OPJ_UINT8 var_bytes_size = 0;
        OPJ_UINT32 packet_size = marker_info->p_packet_size[i];

        /* Packet size written in variable-length way, starting with LSB */
        var_bytes[var_bytes_size] = (OPJ_BYTE)(packet_size & 0x7f);
        var_bytes_size ++;
        packet_size >>= 7;
        while (packet_size > 0) {
            var_bytes[var_bytes_size] = (OPJ_BYTE)((packet_size & 0x7f) | 0x80);
            var_bytes_size ++;
            packet_size >>= 7;
        }

        /* Check if that can fit in the current PLT marker. If not, finish */
        /* current one, and start a new one */
        if (Lplt + var_bytes_size > 65535) {
            if (Zplt == 255) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "More than 255 PLT markers would be needed for current tile-part !\n");
                return OPJ_FALSE;
            }

            /* Patch Lplt */
            opj_write_bytes(p_data_Lplt, Lplt, 2);

            /* Start new segment */
            opj_write_bytes(p_data, J2K_MS_PLT, 2);
            p_data += 2;

            /* Reserve space for Lplt */
            p_data_Lplt = p_data;
            p_data += 2;

            Zplt ++;
            opj_write_bytes(p_data, Zplt, 1);
            p_data += 1;

            Lplt = 3;
        }

        Lplt = (OPJ_UINT16)(Lplt + var_bytes_size);

        /* Serialize variable-length packet size, starting with MSB */
        for (; var_bytes_size > 0; --var_bytes_size) {
            opj_write_bytes(p_data, var_bytes[var_bytes_size - 1], 1);
            p_data += 1;
        }
    }

    *p_data_written = (OPJ_UINT32)(p_data - p_data_start);

    /* Patch Lplt */
    opj_write_bytes(p_data_Lplt, Lplt, 2);

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_sod(opj_j2k_t *p_j2k,
                                  opj_tcd_t * p_tile_coder,
                                  OPJ_BYTE * p_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 total_data_size,
                                  const opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager
                                 )
{
    opj_codestream_info_t *l_cstr_info = 00;
    OPJ_UINT32 l_remaining_data;
    opj_tcd_marker_info_t* marker_info = NULL;

    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);

    OPJ_UNUSED(p_stream);

    if (total_data_size < 4) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough bytes in output buffer to write SOD marker\n");
        return OPJ_FALSE;
    }

    opj_write_bytes(p_data, J2K_MS_SOD,
                    2);                                 /* SOD */


    /* make room for the EOF marker */
    l_remaining_data =  total_data_size - 4;

    /* update tile coder */
    p_tile_coder->tp_num =
        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number ;
    p_tile_coder->cur_tp_num =
        p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;

4684
4685
4686
4687
4688
4689
4690



















4691

4692

4693
4694

4695
4696
4697

4698































4699
4700
4701
4702
4703
4704
4705
            l_cstr_info->packno = 0;
        }
#endif
    }

    *p_data_written = 0;




















    if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number, p_data,

                              p_data_written, l_remaining_data, l_cstr_info,

                              p_manager)) {
        opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");

        return OPJ_FALSE;
    }


    *p_data_written += 2;
































    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
                                 opj_stream_private_t *p_stream,
                                 opj_event_mgr_t * p_manager







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|
>

>


>



>

>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
            l_cstr_info->packno = 0;
        }
#endif
    }

    *p_data_written = 0;

    if (p_j2k->m_specific_param.m_encoder.m_PLT) {
        marker_info = opj_tcd_marker_info_create(
                          p_j2k->m_specific_param.m_encoder.m_PLT);
        if (marker_info == NULL) {
            opj_event_msg(p_manager, EVT_ERROR,
                          "Cannot encode tile: opj_tcd_marker_info_create() failed\n");
            return OPJ_FALSE;
        }
    }

    if (l_remaining_data <
            p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough bytes in output buffer to write SOD marker\n");
        opj_tcd_marker_info_destroy(marker_info);
        return OPJ_FALSE;
    }
    l_remaining_data -= p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT;

    if (! opj_tcd_encode_tile(p_tile_coder, p_j2k->m_current_tile_number,
                              p_data + 2,
                              p_data_written, l_remaining_data, l_cstr_info,
                              marker_info,
                              p_manager)) {
        opj_event_msg(p_manager, EVT_ERROR, "Cannot encode tile\n");
        opj_tcd_marker_info_destroy(marker_info);
        return OPJ_FALSE;
    }

    /* For SOD */
    *p_data_written += 2;

    if (p_j2k->m_specific_param.m_encoder.m_PLT) {
        OPJ_UINT32 l_data_written_PLT = 0;
        OPJ_BYTE* p_PLT_buffer = (OPJ_BYTE*)opj_malloc(
                                     p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);
        if (!p_PLT_buffer) {
            opj_event_msg(p_manager, EVT_ERROR, "Cannot allocate memory\n");
            opj_tcd_marker_info_destroy(marker_info);
            return OPJ_FALSE;
        }
        if (!opj_j2k_write_plt_in_memory(p_j2k,
                                         marker_info,
                                         p_PLT_buffer,
                                         &l_data_written_PLT,
                                         p_manager)) {
            opj_tcd_marker_info_destroy(marker_info);
            opj_free(p_PLT_buffer);
            return OPJ_FALSE;
        }

        assert(l_data_written_PLT <=
               p_j2k->m_specific_param.m_encoder.m_reserved_bytes_for_PLT);

        /* Move PLT marker(s) before SOD */
        memmove(p_data + l_data_written_PLT, p_data, *p_data_written);
        memcpy(p_data, p_PLT_buffer, l_data_written_PLT);
        opj_free(p_PLT_buffer);
        *p_data_written += l_data_written_PLT;
    }

    opj_tcd_marker_info_destroy(marker_info);

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_read_sod(opj_j2k_t *p_j2k,
                                 opj_stream_private_t *p_stream,
                                 opj_event_mgr_t * p_manager
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
    opj_image_comp_t * l_img_comp = 00;

    OPJ_UINT32 i, j, k;
    OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
    OPJ_FLOAT32 * l_rates = 0;
    OPJ_FLOAT32 l_sot_remove;
    OPJ_UINT32 l_bits_empty, l_size_pixel;
    OPJ_UINT32 l_tile_size = 0;
    OPJ_UINT32 l_last_res;
    OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;

    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);







|







5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
    opj_image_comp_t * l_img_comp = 00;

    OPJ_UINT32 i, j, k;
    OPJ_INT32 l_x0, l_y0, l_x1, l_y1;
    OPJ_FLOAT32 * l_rates = 0;
    OPJ_FLOAT32 l_sot_remove;
    OPJ_UINT32 l_bits_empty, l_size_pixel;
    OPJ_UINT64 l_tile_size = 0;
    OPJ_UINT32 l_last_res;
    OPJ_FLOAT32(* l_tp_stride_func)(opj_tcp_t *) = 00;

    /* preconditions */
    assert(p_j2k != 00);
    assert(p_manager != 00);
    assert(p_stream != 00);
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107

5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
                               (OPJ_INT32)l_image->x1);
            l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
                               (OPJ_INT32)l_image->y1);

            l_rates = l_tcp->rates;

            /* Modification of the RATE >> */
            if (*l_rates > 0.0f) {
                *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *
                                           (OPJ_UINT32)(l_y1 - l_y0)))
                            /
                            ((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
                           )
                           -
                           l_offset;
            }

            ++l_rates;

            for (k = 1; k < l_tcp->numlayers; ++k) {
                if (*l_rates > 0.0f) {
                    *l_rates = (((OPJ_FLOAT32)(l_size_pixel * (OPJ_UINT32)(l_x1 - l_x0) *

                                               (OPJ_UINT32)(l_y1 - l_y0)))
                                /
                                ((*l_rates) * (OPJ_FLOAT32)l_bits_empty)
                               )
                               -
                               l_offset;
                }

                ++l_rates;
            }








<
<
<
<
<
<
<
<
<
<
<
<
|

|
>
|
<
|
<







5250
5251
5252
5253
5254
5255
5256












5257
5258
5259
5260
5261

5262

5263
5264
5265
5266
5267
5268
5269
                               (OPJ_INT32)l_image->x1);
            l_y1 = opj_int_min((OPJ_INT32)(l_cp->ty0 + (i + 1) * l_cp->tdy),
                               (OPJ_INT32)l_image->y1);

            l_rates = l_tcp->rates;

            /* Modification of the RATE >> */












            for (k = 0; k < l_tcp->numlayers; ++k) {
                if (*l_rates > 0.0f) {
                    *l_rates = (OPJ_FLOAT32)(((OPJ_FLOAT64)l_size_pixel * (OPJ_UINT32)(
                                                  l_x1 - l_x0) *
                                              (OPJ_UINT32)(l_y1 - l_y0))

                                             / ((*l_rates) * (OPJ_FLOAT32)l_bits_empty))

                               -
                               l_offset;
                }

                ++l_rates;
            }

5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194




5195
5196
5197
5198



5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
        }
    }

    l_img_comp = l_image->comps;
    l_tile_size = 0;

    for (i = 0; i < l_image->numcomps; ++i) {
        l_tile_size += (opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
                        *
                        opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
                        *
                        l_img_comp->prec
                       );

        ++l_img_comp;
    }

    /* TODO: where does this magic value come from ? */
    /* This used to be 1.3 / 8, but with random data and very small code */
    /* block sizes, this is not enough. For example with */
    /* bin/test_tile_encoder 1 256 256 32 32 8 0 reversible_with_precinct.j2k 4 4 3 0 0 1 16 16 */
    /* TODO revise this to take into account the overhead linked to the */
    /* number of packets and number of code blocks in packets */
    l_tile_size = (OPJ_UINT32)(l_tile_size * 1.4 / 8);

    /* Arbitrary amount to make the following work: */
    /* bin/test_tile_encoder 1 256 256 17 16 8 0 reversible_no_precinct.j2k 4 4 3 0 0 1 */
    l_tile_size += 500;

    l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);





    p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = l_tile_size;
    p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
        (OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
    if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {



        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(l_cp->rsiz)) {
        p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
            (OPJ_BYTE *) opj_malloc(5 *
                                    p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
        if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
            return OPJ_FALSE;
        }








|
|
|
|
|
<










|







>
>
>
>
|



>
>
>



|







5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326

5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
        }
    }

    l_img_comp = l_image->comps;
    l_tile_size = 0;

    for (i = 0; i < l_image->numcomps; ++i) {
        l_tile_size += (OPJ_UINT64)opj_uint_ceildiv(l_cp->tdx, l_img_comp->dx)
                       *
                       opj_uint_ceildiv(l_cp->tdy, l_img_comp->dy)
                       *
                       l_img_comp->prec;


        ++l_img_comp;
    }

    /* TODO: where does this magic value come from ? */
    /* This used to be 1.3 / 8, but with random data and very small code */
    /* block sizes, this is not enough. For example with */
    /* bin/test_tile_encoder 1 256 256 32 32 8 0 reversible_with_precinct.j2k 4 4 3 0 0 1 16 16 */
    /* TODO revise this to take into account the overhead linked to the */
    /* number of packets and number of code blocks in packets */
    l_tile_size = (OPJ_UINT64)((double)l_tile_size * 1.4 / 8);

    /* Arbitrary amount to make the following work: */
    /* bin/test_tile_encoder 1 256 256 17 16 8 0 reversible_no_precinct.j2k 4 4 3 0 0 1 */
    l_tile_size += 500;

    l_tile_size += opj_j2k_get_specific_header_sizes(p_j2k);

    if (l_tile_size > UINT_MAX) {
        l_tile_size = UINT_MAX;
    }

    p_j2k->m_specific_param.m_encoder.m_encoded_tile_size = (OPJ_UINT32)l_tile_size;
    p_j2k->m_specific_param.m_encoder.m_encoded_tile_data =
        (OPJ_BYTE *) opj_malloc(p_j2k->m_specific_param.m_encoder.m_encoded_tile_size);
    if (p_j2k->m_specific_param.m_encoder.m_encoded_tile_data == 00) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough memory to allocate m_encoded_tile_data. %u MB required\n",
                      (OPJ_UINT32)(l_tile_size / 1024 / 1024));
        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {
        p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer =
            (OPJ_BYTE *) opj_malloc(5 *
                                    p_j2k->m_specific_param.m_encoder.m_total_tile_parts);
        if (! p_j2k->m_specific_param.m_encoder.m_tlm_sot_offsets_buffer) {
            return OPJ_FALSE;
        }

6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
        }
        break;
    default :
        break;
    }

    /* Precincts */
    parameters->csty |= 0x01;
    if (parameters->numresolution == 1) {
        parameters->res_spec = 1;
        parameters->prcw_init[0] = 128;
        parameters->prch_init[0] = 128;
    } else {
        parameters->res_spec = parameters->numresolution - 1;
        for (i = 0; i < parameters->res_spec; i++) {







|







6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
        }
        break;
    default :
        break;
    }

    /* Precincts */
    parameters->csty |= J2K_CP_CSTY_PRT;
    if (parameters->numresolution == 1) {
        parameters->res_spec = 1;
        parameters->prcw_init[0] = 128;
        parameters->prch_init[0] = 128;
    } else {
        parameters->res_spec = parameters->numresolution - 1;
        for (i = 0; i < parameters->res_spec; i++) {
6748
6749
6750
6751
6752
6753
6754







































































































































































































































































































































































































































































































































































































6755
6756
6757
6758
6759
6760
6761
        break;
    default :
        break;
    }

    return OPJ_TRUE;
}








































































































































































































































































































































































































































































































































































































OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
                               opj_cparameters_t *parameters,
                               opj_image_t *image,
                               opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 i, j, tileno, numpocs_tile;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
        break;
    default :
        break;
    }

    return OPJ_TRUE;
}

static int opj_j2k_get_imf_max_NL(opj_cparameters_t *parameters,
                                  opj_image_t *image)
{
    /* Decomposition levels */
    const OPJ_UINT16 rsiz = parameters->rsiz;
    const OPJ_UINT16 profile = OPJ_GET_IMF_PROFILE(rsiz);
    const OPJ_UINT32 XTsiz = parameters->tile_size_on ? (OPJ_UINT32)
                             parameters->cp_tdx : image->x1;
    switch (profile) {
    case OPJ_PROFILE_IMF_2K:
        return 5;
    case OPJ_PROFILE_IMF_4K:
        return 6;
    case OPJ_PROFILE_IMF_8K:
        return 7;
    case OPJ_PROFILE_IMF_2K_R: {
        if (XTsiz >= 2048) {
            return 5;
        } else if (XTsiz >= 1024) {
            return 4;
        }
        break;
    }
    case OPJ_PROFILE_IMF_4K_R: {
        if (XTsiz >= 4096) {
            return 6;
        } else if (XTsiz >= 2048) {
            return 5;
        } else if (XTsiz >= 1024) {
            return 4;
        }
        break;
    }
    case OPJ_PROFILE_IMF_8K_R: {
        if (XTsiz >= 8192) {
            return 7;
        } else if (XTsiz >= 4096) {
            return 6;
        } else if (XTsiz >= 2048) {
            return 5;
        } else if (XTsiz >= 1024) {
            return 4;
        }
        break;
    }
    default:
        break;
    }
    return -1;
}

static void opj_j2k_set_imf_parameters(opj_cparameters_t *parameters,
                                       opj_image_t *image, opj_event_mgr_t *p_manager)
{
    const OPJ_UINT16 rsiz = parameters->rsiz;
    const OPJ_UINT16 profile = OPJ_GET_IMF_PROFILE(rsiz);

    OPJ_UNUSED(p_manager);

    /* Override defaults set by opj_set_default_encoder_parameters */
    if (parameters->cblockw_init == OPJ_COMP_PARAM_DEFAULT_CBLOCKW &&
            parameters->cblockh_init == OPJ_COMP_PARAM_DEFAULT_CBLOCKH) {
        parameters->cblockw_init = 32;
        parameters->cblockh_init = 32;
    }

    /* One tile part for each component */
    parameters->tp_flag = 'C';
    parameters->tp_on = 1;

    if (parameters->prog_order == OPJ_COMP_PARAM_DEFAULT_PROG_ORDER) {
        parameters->prog_order = OPJ_CPRL;
    }

    if (profile == OPJ_PROFILE_IMF_2K ||
            profile == OPJ_PROFILE_IMF_4K ||
            profile == OPJ_PROFILE_IMF_8K) {
        /* 9-7 transform */
        parameters->irreversible = 1;
    }

    /* Adjust the number of resolutions if set to its defaults */
    if (parameters->numresolution == OPJ_COMP_PARAM_DEFAULT_NUMRESOLUTION &&
            image->x0 == 0 &&
            image->y0 == 0) {
        const int max_NL = opj_j2k_get_imf_max_NL(parameters, image);
        if (max_NL >= 0 && parameters->numresolution > max_NL) {
            parameters->numresolution = max_NL + 1;
        }

        /* Note: below is generic logic */
        if (!parameters->tile_size_on) {
            while (parameters->numresolution > 0) {
                if (image->x1 < (1U << ((OPJ_UINT32)parameters->numresolution - 1U))) {
                    parameters->numresolution --;
                    continue;
                }
                if (image->y1 < (1U << ((OPJ_UINT32)parameters->numresolution - 1U))) {
                    parameters->numresolution --;
                    continue;
                }
                break;
            }
        }
    }

    /* Set defaults precincts */
    if (parameters->csty == 0) {
        parameters->csty |= J2K_CP_CSTY_PRT;
        if (parameters->numresolution == 1) {
            parameters->res_spec = 1;
            parameters->prcw_init[0] = 128;
            parameters->prch_init[0] = 128;
        } else {
            int i;
            parameters->res_spec = parameters->numresolution - 1;
            for (i = 0; i < parameters->res_spec; i++) {
                parameters->prcw_init[i] = 256;
                parameters->prch_init[i] = 256;
            }
        }
    }
}

/* Table A.53 from JPEG2000 standard */
static const OPJ_UINT16 tabMaxSubLevelFromMainLevel[] = {
    15, /* unspecified */
    1,
    1,
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9
};

static OPJ_BOOL opj_j2k_is_imf_compliant(opj_cparameters_t *parameters,
        opj_image_t *image,
        opj_event_mgr_t *p_manager)
{
    OPJ_UINT32 i;
    const OPJ_UINT16 rsiz = parameters->rsiz;
    const OPJ_UINT16 profile = OPJ_GET_IMF_PROFILE(rsiz);
    const OPJ_UINT16 mainlevel = OPJ_GET_IMF_MAINLEVEL(rsiz);
    const OPJ_UINT16 sublevel = OPJ_GET_IMF_SUBLEVEL(rsiz);
    const int NL = parameters->numresolution - 1;
    const OPJ_UINT32 XTsiz = parameters->tile_size_on ? (OPJ_UINT32)
                             parameters->cp_tdx : image->x1;
    OPJ_BOOL ret = OPJ_TRUE;

    /* Validate mainlevel */
    if (mainlevel > OPJ_IMF_MAINLEVEL_MAX) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile require mainlevel <= 11.\n"
                      "-> %d is thus not compliant\n"
                      "-> Non-IMF codestream will be generated\n",
                      mainlevel);
        ret = OPJ_FALSE;
    }

    /* Validate sublevel */
    assert(sizeof(tabMaxSubLevelFromMainLevel) ==
           (OPJ_IMF_MAINLEVEL_MAX + 1) * sizeof(tabMaxSubLevelFromMainLevel[0]));
    if (sublevel > tabMaxSubLevelFromMainLevel[mainlevel]) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile require sublevel <= %d for mainlevel = %d.\n"
                      "-> %d is thus not compliant\n"
                      "-> Non-IMF codestream will be generated\n",
                      tabMaxSubLevelFromMainLevel[mainlevel],
                      mainlevel,
                      sublevel);
        ret = OPJ_FALSE;
    }

    /* Number of components */
    if (image->numcomps > 3) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profiles require at most 3 components.\n"
                      "-> Number of components of input image (%d) is not compliant\n"
                      "-> Non-IMF codestream will be generated\n",
                      image->numcomps);
        ret = OPJ_FALSE;
    }

    if (image->x0 != 0 || image->y0 != 0) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profiles require image origin to be at 0,0.\n"
                      "-> %d,%d is not compliant\n"
                      "-> Non-IMF codestream will be generated\n",
                      image->x0, image->y0 != 0);
        ret = OPJ_FALSE;
    }

    if (parameters->cp_tx0 != 0 || parameters->cp_ty0 != 0) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profiles require tile origin to be at 0,0.\n"
                      "-> %d,%d is not compliant\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->cp_tx0, parameters->cp_ty0);
        ret = OPJ_FALSE;
    }

    if (parameters->tile_size_on) {
        if (profile == OPJ_PROFILE_IMF_2K ||
                profile == OPJ_PROFILE_IMF_4K ||
                profile == OPJ_PROFILE_IMF_8K) {
            if ((OPJ_UINT32)parameters->cp_tdx < image->x1 ||
                    (OPJ_UINT32)parameters->cp_tdy < image->y1) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 2K/4K/8K single tile profiles require tile to be greater or equal to image size.\n"
                              "-> %d,%d is lesser than %d,%d\n"
                              "-> Non-IMF codestream will be generated\n",
                              parameters->cp_tdx,
                              parameters->cp_tdy,
                              image->x1,
                              image->y1);
                ret = OPJ_FALSE;
            }
        } else {
            if ((OPJ_UINT32)parameters->cp_tdx >= image->x1 &&
                    (OPJ_UINT32)parameters->cp_tdy >= image->y1) {
                /* ok */
            } else if (parameters->cp_tdx == 1024 &&
                       parameters->cp_tdy == 1024) {
                /* ok */
            } else if (parameters->cp_tdx == 2048 &&
                       parameters->cp_tdy == 2048 &&
                       (profile == OPJ_PROFILE_IMF_4K ||
                        profile == OPJ_PROFILE_IMF_8K)) {
                /* ok */
            } else if (parameters->cp_tdx == 4096 &&
                       parameters->cp_tdy == 4096 &&
                       profile == OPJ_PROFILE_IMF_8K) {
                /* ok */
            } else {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 2K_R/4K_R/8K_R single/multiple tile profiles "
                              "require tile to be greater or equal to image size,\n"
                              "or to be (1024,1024), or (2048,2048) for 4K_R/8K_R "
                              "or (4096,4096) for 8K_R.\n"
                              "-> %d,%d is non conformant\n"
                              "-> Non-IMF codestream will be generated\n",
                              parameters->cp_tdx,
                              parameters->cp_tdy);
                ret = OPJ_FALSE;
            }
        }
    }

    /* Bitdepth */
    for (i = 0; i < image->numcomps; i++) {
        if (!(image->comps[i].bpp >= 8 && image->comps[i].bpp <= 16) ||
                (image->comps[i].sgnd)) {
            char signed_str[] = "signed";
            char unsigned_str[] = "unsigned";
            char *tmp_str = image->comps[i].sgnd ? signed_str : unsigned_str;
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require precision of each component to b in [8-16] bits unsigned"
                          "-> At least component %d of input image (%d bits, %s) is not compliant\n"
                          "-> Non-IMF codestream will be generated\n",
                          i, image->comps[i].bpp, tmp_str);
            ret = OPJ_FALSE;
        }
    }

    /* Sub-sampling */
    for (i = 0; i < image->numcomps; i++) {
        if (i == 0 && image->comps[i].dx != 1) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require XRSiz1 == 1. Here it is set to %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[i].dx);
            ret = OPJ_FALSE;
        }
        if (i == 1 && image->comps[i].dx != 1 && image->comps[i].dx != 2) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require XRSiz2 == 1 or 2. Here it is set to %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[i].dx);
            ret = OPJ_FALSE;
        }
        if (i > 1 && image->comps[i].dx != image->comps[i - 1].dx) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require XRSiz%d to be the same as XRSiz2. "
                          "Here it is set to %d instead of %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          i + 1, image->comps[i].dx, image->comps[i - 1].dx);
            ret = OPJ_FALSE;
        }
        if (image->comps[i].dy != 1) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require YRsiz == 1. "
                          "Here it is set to %d for component i.\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[i].dy, i);
            ret = OPJ_FALSE;
        }
    }

    /* Image size */
    switch (profile) {
    case OPJ_PROFILE_IMF_2K:
    case OPJ_PROFILE_IMF_2K_R:
        if (((image->comps[0].w > 2048) | (image->comps[0].h > 1556))) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 2K/2K_R profile require:\n"
                          "width <= 2048 and height <= 1556\n"
                          "-> Input image size %d x %d is not compliant\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[0].w, image->comps[0].h);
            ret = OPJ_FALSE;
        }
        break;
    case OPJ_PROFILE_IMF_4K:
    case OPJ_PROFILE_IMF_4K_R:
        if (((image->comps[0].w > 4096) | (image->comps[0].h > 3112))) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 4K/4K_R profile require:\n"
                          "width <= 4096 and height <= 3112\n"
                          "-> Input image size %d x %d is not compliant\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[0].w, image->comps[0].h);
            ret = OPJ_FALSE;
        }
        break;
    case OPJ_PROFILE_IMF_8K:
    case OPJ_PROFILE_IMF_8K_R:
        if (((image->comps[0].w > 8192) | (image->comps[0].h > 6224))) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 8K/8K_R profile require:\n"
                          "width <= 8192 and height <= 6224\n"
                          "-> Input image size %d x %d is not compliant\n"
                          "-> Non-IMF codestream will be generated\n",
                          image->comps[0].w, image->comps[0].h);
            ret = OPJ_FALSE;
        }
        break;
    default :
        assert(0);
        return OPJ_FALSE;
    }

    if (parameters->roi_compno != -1) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile forbid RGN / region of interest marker.\n"
                      "-> Compression parameters specify a ROI\n"
                      "-> Non-IMF codestream will be generated\n");
        ret = OPJ_FALSE;
    }

    if (parameters->cblockw_init != 32 || parameters->cblockh_init != 32) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile require code block size to be 32x32.\n"
                      "-> Compression parameters set it to %dx%d.\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->cblockw_init,
                      parameters->cblockh_init);
        ret = OPJ_FALSE;
    }

    if (parameters->prog_order != OPJ_CPRL) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile require progression order to be CPRL.\n"
                      "-> Compression parameters set it to %d.\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->prog_order);
        ret = OPJ_FALSE;
    }

    if (parameters->numpocs != 0) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile forbid POC markers.\n"
                      "-> Compression parameters set %d POC.\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->numpocs);
        ret = OPJ_FALSE;
    }

    /* Codeblock style: no mode switch enabled */
    if (parameters->mode != 0) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF profile forbid mode switch in code block style.\n"
                      "-> Compression parameters set code block style to %d.\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->mode);
        ret = OPJ_FALSE;
    }

    if (profile == OPJ_PROFILE_IMF_2K ||
            profile == OPJ_PROFILE_IMF_4K ||
            profile == OPJ_PROFILE_IMF_8K) {
        /* Expect 9-7 transform */
        if (parameters->irreversible != 1) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 2K/4K/8K profiles require 9-7 Irreversible Transform.\n"
                          "-> Compression parameters set it to reversible.\n"
                          "-> Non-IMF codestream will be generated\n");
            ret = OPJ_FALSE;
        }
    } else {
        /* Expect 5-3 transform */
        if (parameters->irreversible != 0) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 2K/4K/8K profiles require 5-3 reversible Transform.\n"
                          "-> Compression parameters set it to irreversible.\n"
                          "-> Non-IMF codestream will be generated\n");
            ret = OPJ_FALSE;
        }
    }

    /* Number of layers */
    if (parameters->tcp_numlayers != 1) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "IMF 2K/4K/8K profiles require 1 single quality layer.\n"
                      "-> Number of layers is %d.\n"
                      "-> Non-IMF codestream will be generated\n",
                      parameters->tcp_numlayers);
        ret = OPJ_FALSE;
    }

    /* Decomposition levels */
    switch (profile) {
    case OPJ_PROFILE_IMF_2K:
        if (!(NL >= 1 && NL <= 5)) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 2K profile requires 1 <= NL <= 5:\n"
                          "-> Number of decomposition levels is %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          NL);
            ret = OPJ_FALSE;
        }
        break;
    case OPJ_PROFILE_IMF_4K:
        if (!(NL >= 1 && NL <= 6)) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 4K profile requires 1 <= NL <= 6:\n"
                          "-> Number of decomposition levels is %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          NL);
            ret = OPJ_FALSE;
        }
        break;
    case OPJ_PROFILE_IMF_8K:
        if (!(NL >= 1 && NL <= 7)) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF 8K profile requires 1 <= NL <= 7:\n"
                          "-> Number of decomposition levels is %d.\n"
                          "-> Non-IMF codestream will be generated\n",
                          NL);
            ret = OPJ_FALSE;
        }
        break;
    case OPJ_PROFILE_IMF_2K_R: {
        if (XTsiz >= 2048) {
            if (!(NL >= 1 && NL <= 5)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 2K_R profile requires 1 <= NL <= 5 for XTsiz >= 2048:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 1024) {
            if (!(NL >= 1 && NL <= 4)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 2K_R profile requires 1 <= NL <= 4 for XTsiz in [1024,2048[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        }
        break;
    }
    case OPJ_PROFILE_IMF_4K_R: {
        if (XTsiz >= 4096) {
            if (!(NL >= 1 && NL <= 6)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 6 for XTsiz >= 4096:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 2048) {
            if (!(NL >= 1 && NL <= 5)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 5 for XTsiz in [2048,4096[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 1024) {
            if (!(NL >= 1 && NL <= 4)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 4 for XTsiz in [1024,2048[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        }
        break;
    }
    case OPJ_PROFILE_IMF_8K_R: {
        if (XTsiz >= 8192) {
            if (!(NL >= 1 && NL <= 7)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 7 for XTsiz >= 8192:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 4096) {
            if (!(NL >= 1 && NL <= 6)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 6 for XTsiz in [4096,8192[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 2048) {
            if (!(NL >= 1 && NL <= 5)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 5 for XTsiz in [2048,4096[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        } else if (XTsiz >= 1024) {
            if (!(NL >= 1 && NL <= 4)) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF 4K_R profile requires 1 <= NL <= 4 for XTsiz in [1024,2048[:\n"
                              "-> Number of decomposition levels is %d.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        }
        break;
    }
    default:
        break;
    }

    if (parameters->numresolution == 1) {
        if (parameters->res_spec != 1 ||
                parameters->prcw_init[0] != 128 ||
                parameters->prch_init[0] != 128) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "IMF profiles require PPx = PPy = 7 for NLLL band, else 8.\n"
                          "-> Supplied values are different from that.\n"
                          "-> Non-IMF codestream will be generated\n",
                          NL);
            ret = OPJ_FALSE;
        }
    } else {
        int i;
        for (i = 0; i < parameters->res_spec; i++) {
            if (parameters->prcw_init[i] != 256 ||
                    parameters->prch_init[i] != 256) {
                opj_event_msg(p_manager, EVT_WARNING,
                              "IMF profiles require PPx = PPy = 7 for NLLL band, else 8.\n"
                              "-> Supplied values are different from that.\n"
                              "-> Non-IMF codestream will be generated\n",
                              NL);
                ret = OPJ_FALSE;
            }
        }
    }

    return ret;
}


OPJ_BOOL opj_j2k_setup_encoder(opj_j2k_t *p_j2k,
                               opj_cparameters_t *parameters,
                               opj_image_t *image,
                               opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 i, j, tileno, numpocs_tile;
6941
6942
6943
6944
6945
6946
6947









6948
6949
6950
6951
6952
6953
6954
            }
        } else {
            parameters->max_cs_size = 0;
        }
    } else {
        OPJ_FLOAT32 temp_rate;
        OPJ_BOOL cap = OPJ_FALSE;









        temp_rate = (OPJ_FLOAT32)(((double)image->numcomps * image->comps[0].w *
                                   image->comps[0].h * image->comps[0].prec) /
                                  (((double)parameters->max_cs_size) * 8 * image->comps[0].dx *
                                   image->comps[0].dy));
        for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
            if (parameters->tcp_rates[i] < temp_rate) {
                parameters->tcp_rates[i] = temp_rate;







>
>
>
>
>
>
>
>
>







7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
            }
        } else {
            parameters->max_cs_size = 0;
        }
    } else {
        OPJ_FLOAT32 temp_rate;
        OPJ_BOOL cap = OPJ_FALSE;

        if (OPJ_IS_IMF(parameters->rsiz) && parameters->max_cs_size > 0 &&
                parameters->tcp_numlayers == 1 && parameters->tcp_rates[0] == 0) {
            parameters->tcp_rates[0] = (OPJ_FLOAT32)(image->numcomps * image->comps[0].w *
                                       image->comps[0].h * image->comps[0].prec) /
                                       (OPJ_FLOAT32)(((OPJ_UINT32)parameters->max_cs_size) * 8 * image->comps[0].dx *
                                               image->comps[0].dy);
        }

        temp_rate = (OPJ_FLOAT32)(((double)image->numcomps * image->comps[0].w *
                                   image->comps[0].h * image->comps[0].prec) /
                                  (((double)parameters->max_cs_size) * 8 * image->comps[0].dx *
                                   image->comps[0].dy));
        for (i = 0; i < (OPJ_UINT32) parameters->tcp_numlayers; i++) {
            if (parameters->tcp_rates[i] < temp_rate) {
                parameters->tcp_rates[i] = temp_rate;
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990

6991
6992
6993
6994
6995
6996
6997
                      "JPEG 2000 Long Term Storage profile not yet supported\n");
        parameters->rsiz = OPJ_PROFILE_NONE;
    } else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "JPEG 2000 Broadcast profiles not yet supported\n");
        parameters->rsiz = OPJ_PROFILE_NONE;
    } else if (OPJ_IS_IMF(parameters->rsiz)) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "JPEG 2000 IMF profiles not yet supported\n");
        parameters->rsiz = OPJ_PROFILE_NONE;

    } else if (OPJ_IS_PART2(parameters->rsiz)) {
        if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "JPEG 2000 Part-2 profile defined\n"
                          "but no Part-2 extension enabled.\n"
                          "Profile set to NONE.\n");
            parameters->rsiz = OPJ_PROFILE_NONE;







|
|
|
>







7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
                      "JPEG 2000 Long Term Storage profile not yet supported\n");
        parameters->rsiz = OPJ_PROFILE_NONE;
    } else if (OPJ_IS_BROADCAST(parameters->rsiz)) {
        opj_event_msg(p_manager, EVT_WARNING,
                      "JPEG 2000 Broadcast profiles not yet supported\n");
        parameters->rsiz = OPJ_PROFILE_NONE;
    } else if (OPJ_IS_IMF(parameters->rsiz)) {
        opj_j2k_set_imf_parameters(parameters, image, p_manager);
        if (!opj_j2k_is_imf_compliant(parameters, image, p_manager)) {
            parameters->rsiz = OPJ_PROFILE_NONE;
        }
    } else if (OPJ_IS_PART2(parameters->rsiz)) {
        if (parameters->rsiz == ((OPJ_PROFILE_PART2) | (OPJ_EXTENSION_NONE))) {
            opj_event_msg(p_manager, EVT_WARNING,
                          "JPEG 2000 Part-2 profile defined\n"
                          "but no Part-2 extension enabled.\n"
                          "Profile set to NONE.\n");
            parameters->rsiz = OPJ_PROFILE_NONE;
7075
7076
7077
7078
7079
7080
7081








7082
7083
7084
7085
7086
7087
7088
    }

    /*
    calculate other encoding parameters
    */

    if (parameters->tile_size_on) {








        cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
                                             (OPJ_INT32)cp->tdx);
        cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
                                             (OPJ_INT32)cp->tdy);
    } else {
        cp->tdx = image->x1 - cp->tx0;
        cp->tdy = image->y1 - cp->ty0;







>
>
>
>
>
>
>
>







7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
    }

    /*
    calculate other encoding parameters
    */

    if (parameters->tile_size_on) {
        if (cp->tdx == 0) {
            opj_event_msg(p_manager, EVT_ERROR, "Invalid tile width\n");
            return OPJ_FALSE;
        }
        if (cp->tdy == 0) {
            opj_event_msg(p_manager, EVT_ERROR, "Invalid tile height\n");
            return OPJ_FALSE;
        }
        cp->tw = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->x1 - cp->tx0),
                                             (OPJ_INT32)cp->tdx);
        cp->th = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)(image->y1 - cp->ty0),
                                             (OPJ_INT32)cp->tdy);
    } else {
        cp->tdx = image->x1 - cp->tx0;
        cp->tdy = image->y1 - cp->ty0;
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
    /* ---------------------------- */
    cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
    if (!cp->tcps) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough memory to allocate tile coding parameters\n");
        return OPJ_FALSE;
    }
    if (parameters->numpocs) {
        /* initialisation of POC */
        opj_j2k_check_poc_val(parameters->POC, parameters->numpocs,
                              (OPJ_UINT32)parameters->numresolution, image->numcomps,
                              (OPJ_UINT32)parameters->tcp_numlayers, p_manager);
        /* TODO MSD use the return value*/
    }

    for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
        opj_tcp_t *tcp = &cp->tcps[tileno];
        tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;

        for (j = 0; j < tcp->numlayers; j++) {
            if (OPJ_IS_CINEMA(cp->rsiz)) {
                if (cp->m_specific_param.m_enc.m_fixed_quality) {
                    tcp->distoratio[j] = parameters->tcp_distoratio[j];
                }
                tcp->rates[j] = parameters->tcp_rates[j];
            } else {
                if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* add fixed_quality */
                    tcp->distoratio[j] = parameters->tcp_distoratio[j];







<
<
<
<
<
<
<






|







7911
7912
7913
7914
7915
7916
7917







7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
    /* ---------------------------- */
    cp->tcps = (opj_tcp_t*) opj_calloc(cp->tw * cp->th, sizeof(opj_tcp_t));
    if (!cp->tcps) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Not enough memory to allocate tile coding parameters\n");
        return OPJ_FALSE;
    }








    for (tileno = 0; tileno < cp->tw * cp->th; tileno++) {
        opj_tcp_t *tcp = &cp->tcps[tileno];
        tcp->numlayers = (OPJ_UINT32)parameters->tcp_numlayers;

        for (j = 0; j < tcp->numlayers; j++) {
            if (OPJ_IS_CINEMA(cp->rsiz) || OPJ_IS_IMF(cp->rsiz)) {
                if (cp->m_specific_param.m_enc.m_fixed_quality) {
                    tcp->distoratio[j] = parameters->tcp_distoratio[j];
                }
                tcp->rates[j] = parameters->tcp_rates[j];
            } else {
                if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* add fixed_quality */
                    tcp->distoratio[j] = parameters->tcp_distoratio[j];
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203






7204
7205
7206
7207
7208
7209

7210
7211
7212
7213
7214
7215
7216








7217

7218
7219
7220
7221
7222
7223
7224
        tcp->mct = (OPJ_UINT32)parameters->tcp_mct;

        numpocs_tile = 0;
        tcp->POC = 0;

        if (parameters->numpocs) {
            /* initialisation of POC */
            tcp->POC = 1;
            for (i = 0; i < parameters->numpocs; i++) {
                if (tileno + 1 == parameters->POC[i].tile)  {
                    opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];







                    tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;
                    tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;
                    tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;
                    tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;
                    tcp_poc->compno1        = parameters->POC[numpocs_tile].compno1;

                    tcp_poc->prg1           = parameters->POC[numpocs_tile].prg1;
                    tcp_poc->tile           = parameters->POC[numpocs_tile].tile;

                    numpocs_tile++;
                }
            }









            tcp->numpocs = numpocs_tile - 1 ;

        } else {
            tcp->numpocs = 0;
        }

        tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
        if (!tcp->tccps) {
            opj_event_msg(p_manager, EVT_ERROR,







<



>
>
>
>
>
>





|
>







>
>
>
>
>
>
>
>
|
>







7944
7945
7946
7947
7948
7949
7950

7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
        tcp->mct = (OPJ_UINT32)parameters->tcp_mct;

        numpocs_tile = 0;
        tcp->POC = 0;

        if (parameters->numpocs) {
            /* initialisation of POC */

            for (i = 0; i < parameters->numpocs; i++) {
                if (tileno + 1 == parameters->POC[i].tile)  {
                    opj_poc_t *tcp_poc = &tcp->pocs[numpocs_tile];

                    if (parameters->POC[numpocs_tile].compno0 >= image->numcomps) {
                        opj_event_msg(p_manager, EVT_ERROR,
                                      "Invalid compno0 for POC %d\n", i);
                        return OPJ_FALSE;
                    }

                    tcp_poc->resno0         = parameters->POC[numpocs_tile].resno0;
                    tcp_poc->compno0        = parameters->POC[numpocs_tile].compno0;
                    tcp_poc->layno1         = parameters->POC[numpocs_tile].layno1;
                    tcp_poc->resno1         = parameters->POC[numpocs_tile].resno1;
                    tcp_poc->compno1        = opj_uint_min(parameters->POC[numpocs_tile].compno1,
                                                           image->numcomps);
                    tcp_poc->prg1           = parameters->POC[numpocs_tile].prg1;
                    tcp_poc->tile           = parameters->POC[numpocs_tile].tile;

                    numpocs_tile++;
                }
            }

            if (numpocs_tile) {

                /* TODO MSD use the return value*/
                opj_j2k_check_poc_val(parameters->POC, tileno, parameters->numpocs,
                                      (OPJ_UINT32)parameters->numresolution, image->numcomps,
                                      (OPJ_UINT32)parameters->tcp_numlayers, p_manager);

                tcp->POC = 1;
                tcp->numpocs = numpocs_tile - 1 ;
            }
        } else {
            tcp->numpocs = 0;
        }

        tcp->tccps = (opj_tccp_t*) opj_calloc(image->numcomps, sizeof(opj_tccp_t));
        if (!tcp->tccps) {
            opj_event_msg(p_manager, EVT_ERROR,
7538
7539
7540
7541
7542
7543
7544


7545
7546
7547
7548
7549
7550
7551
    }

    /* Copy codestream image information to the output image */
    opj_copy_image_header(p_j2k->m_private_image, *p_image);

    /*Allocate and initialize some elements of codestrem index*/
    if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {


        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,







>
>







8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
    }

    /* Copy codestream image information to the output image */
    opj_copy_image_header(p_j2k->m_private_image, *p_image);

    /*Allocate and initialize some elements of codestrem index*/
    if (!opj_j2k_allocate_tile_element_cstr_index(p_j2k)) {
        opj_image_destroy(*p_image);
        *p_image = NULL;
        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_setup_header_reading(opj_j2k_t *p_j2k,
8624
8625
8626
8627
8628
8629
8630

8631
8632
8633
8634
8635
8636
8637
                                  opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 l_current_marker = J2K_MS_SOT;
    OPJ_UINT32 l_marker_size;
    const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
    opj_tcp_t * l_tcp = NULL;


    /* preconditions */
    assert(p_stream != 00);
    assert(p_j2k != 00);
    assert(p_manager != 00);

    /* Reach the End Of Codestream ?*/







>







9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
                                  opj_stream_private_t *p_stream,
                                  opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 l_current_marker = J2K_MS_SOT;
    OPJ_UINT32 l_marker_size;
    const opj_dec_memory_marker_handler_t * l_marker_handler = 00;
    opj_tcp_t * l_tcp = NULL;
    const OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;

    /* preconditions */
    assert(p_stream != 00);
    assert(p_j2k != 00);
    assert(p_manager != 00);

    /* Reach the End Of Codestream ?*/
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838


8839
8840
8841

























8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
                if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
                        p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
                    opj_event_msg(p_manager, EVT_ERROR,
                                  "opj_j2k_apply_nb_tile_parts_correction error\n");
                    return OPJ_FALSE;
                }
                if (l_correction_needed) {
                    OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.tw * p_j2k->m_cp.th;
                    OPJ_UINT32 l_tile_no;

                    p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
                    p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
                    /* correct tiles */
                    for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
                        if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
                            p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
                        }
                    }
                    opj_event_msg(p_manager, EVT_WARNING,
                                  "Non conformant codestream TPsot==TNsot.\n");
                }
            }
            if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
                /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
                if (opj_stream_read_data(p_stream,
                                         p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {
                    opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
                    return OPJ_FALSE;
                }

                /* Read 2 bytes from buffer as the new marker ID */
                opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
                               &l_current_marker, 2);
            }
        } else {
            /* Indicate we will try to read a new tile-part header*/
            p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
            p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
            p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;



            /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
            if (opj_stream_read_data(p_stream,
                                     p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {

























                opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
                return OPJ_FALSE;
            }

            /* Read 2 bytes from buffer as the new marker ID */
            opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
                           &l_current_marker, 2);
        }
    }

    /* Current marker is the EOC marker ?*/
    if (l_current_marker == J2K_MS_EOC) {
        if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
            p_j2k->m_current_tile_number = 0;
            p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
        }
    }

    /* FIXME DOC ???*/
    if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
        OPJ_UINT32 l_nb_tiles = p_j2k->m_cp.th * p_j2k->m_cp.tw;
        l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;

        while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
            ++p_j2k->m_current_tile_number;
            ++l_tcp;
        }








<














<
<
<
<
<
<
<
<
<
<
<
<





|
>
>



>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>


















|

<







9568
9569
9570
9571
9572
9573
9574

9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588












9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644

9645
9646
9647
9648
9649
9650
9651
                if (!opj_j2k_need_nb_tile_parts_correction(p_stream,
                        p_j2k->m_current_tile_number, &l_correction_needed, p_manager)) {
                    opj_event_msg(p_manager, EVT_ERROR,
                                  "opj_j2k_apply_nb_tile_parts_correction error\n");
                    return OPJ_FALSE;
                }
                if (l_correction_needed) {

                    OPJ_UINT32 l_tile_no;

                    p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
                    p_j2k->m_specific_param.m_decoder.m_nb_tile_parts_correction = 1;
                    /* correct tiles */
                    for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
                        if (p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts != 0U) {
                            p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts += 1;
                        }
                    }
                    opj_event_msg(p_manager, EVT_WARNING,
                                  "Non conformant codestream TPsot==TNsot.\n");
                }
            }












        } else {
            /* Indicate we will try to read a new tile-part header*/
            p_j2k->m_specific_param.m_decoder.m_skip_data = 0;
            p_j2k->m_specific_param.m_decoder.m_can_decode = 0;
            p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_TPHSOT;
        }

        if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {
            /* Try to read 2 bytes (the next marker ID) from stream and copy them into the buffer */
            if (opj_stream_read_data(p_stream,
                                     p_j2k->m_specific_param.m_decoder.m_header_data, 2, p_manager) != 2) {

                /* Deal with likely non conformant SPOT6 files, where the last */
                /* row of tiles have TPsot == 0 and TNsot == 0, and missing EOC, */
                /* but no other tile-parts were found. */
                if (p_j2k->m_current_tile_number + 1 == l_nb_tiles) {
                    OPJ_UINT32 l_tile_no;
                    for (l_tile_no = 0U; l_tile_no < l_nb_tiles; ++l_tile_no) {
                        if (p_j2k->m_cp.tcps[l_tile_no].m_current_tile_part_number == 0 &&
                                p_j2k->m_cp.tcps[l_tile_no].m_nb_tile_parts == 0) {
                            break;
                        }
                    }
                    if (l_tile_no < l_nb_tiles) {
                        opj_event_msg(p_manager, EVT_INFO,
                                      "Tile %u has TPsot == 0 and TNsot == 0, "
                                      "but no other tile-parts were found. "
                                      "EOC is also missing.\n",
                                      l_tile_no);
                        p_j2k->m_current_tile_number = l_tile_no;
                        l_current_marker = J2K_MS_EOC;
                        p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
                        break;
                    }
                }

                opj_event_msg(p_manager, EVT_ERROR, "Stream too short\n");
                return OPJ_FALSE;
            }

            /* Read 2 bytes from buffer as the new marker ID */
            opj_read_bytes(p_j2k->m_specific_param.m_decoder.m_header_data,
                           &l_current_marker, 2);
        }
    }

    /* Current marker is the EOC marker ?*/
    if (l_current_marker == J2K_MS_EOC) {
        if (p_j2k->m_specific_param.m_decoder.m_state != J2K_STATE_EOC) {
            p_j2k->m_current_tile_number = 0;
            p_j2k->m_specific_param.m_decoder.m_state = J2K_STATE_EOC;
        }
    }

    /* Deal with tiles that have a single tile-part with TPsot == 0 and TNsot == 0 */
    if (! p_j2k->m_specific_param.m_decoder.m_can_decode) {

        l_tcp = p_j2k->m_cp.tcps + p_j2k->m_current_tile_number;

        while ((p_j2k->m_current_tile_number < l_nb_tiles) && (l_tcp->m_data == 00)) {
            ++p_j2k->m_current_tile_number;
            ++l_tcp;
        }

9232
9233
9234
9235
9236
9237
9238








9239
9240
9241
9242
9243
9244
9245
    OPJ_UINT32 it_comp;
    OPJ_INT32 l_comp_x1, l_comp_y1;
    opj_image_comp_t* l_img_comp = NULL;

    l_img_comp = p_image->comps;
    for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
        OPJ_INT32 l_h, l_w;









        l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
                         (OPJ_INT32)l_img_comp->dx);
        l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
                         (OPJ_INT32)l_img_comp->dy);
        l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
        l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);







>
>
>
>
>
>
>
>







10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
    OPJ_UINT32 it_comp;
    OPJ_INT32 l_comp_x1, l_comp_y1;
    opj_image_comp_t* l_img_comp = NULL;

    l_img_comp = p_image->comps;
    for (it_comp = 0; it_comp < p_image->numcomps; ++it_comp) {
        OPJ_INT32 l_h, l_w;
        if (p_image->x0 > (OPJ_UINT32)INT_MAX ||
                p_image->y0 > (OPJ_UINT32)INT_MAX ||
                p_image->x1 > (OPJ_UINT32)INT_MAX ||
                p_image->y1 > (OPJ_UINT32)INT_MAX) {
            opj_event_msg(p_manager, EVT_ERROR,
                          "Image coordinates above INT_MAX are not supported\n");
            return OPJ_FALSE;
        }

        l_img_comp->x0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->x0,
                         (OPJ_INT32)l_img_comp->dx);
        l_img_comp->y0 = (OPJ_UINT32)opj_int_ceildiv((OPJ_INT32)p_image->y0,
                         (OPJ_INT32)l_img_comp->dy);
        l_comp_x1 = opj_int_ceildiv((OPJ_INT32)p_image->x1, (OPJ_INT32)l_img_comp->dx);
        l_comp_y1 = opj_int_ceildiv((OPJ_INT32)p_image->y1, (OPJ_INT32)l_img_comp->dy);
9750
9751
9752
9753
9754
9755
9756

9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779

9780
9781
9782
9783

9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803

9804
9805






9806
9807
9808
9809
9810
9811
9812
9813
9814
9815

9816
9817
9818
9819
9820
9821
9822
9823
9824

    /* make sure room is sufficient */
    if (*p_header_size < 5) {
        opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
        return OPJ_FALSE;
    }


    opj_read_bytes(l_current_ptr, &l_tccp->numresolutions,
                   1);              /* SPcox (D) */
    ++l_tccp->numresolutions;                                                                               /* tccp->numresolutions = read() + 1 */
    if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
                      l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
        return OPJ_FALSE;
    }
    ++l_current_ptr;

    /* If user wants to remove more resolutions than the codestream contains, return error */
    if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error decoding component %d.\nThe number of resolutions "
                      "to remove (%d) is greater or equal than the number "
                      "of resolutions of this component (%d)\nModify the cp_reduce parameter.\n\n",
                      compno, l_cp->m_specific_param.m_dec.m_reduce, l_tccp->numresolutions);
        p_j2k->m_specific_param.m_decoder.m_state |=
            0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
        return OPJ_FALSE;
    }


    opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1);               /* SPcoc (E) */
    ++l_current_ptr;
    l_tccp->cblkw += 2;


    opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1);               /* SPcoc (F) */
    ++l_current_ptr;
    l_tccp->cblkh += 2;

    if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
            ((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
        return OPJ_FALSE;
    }


    opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1);             /* SPcoc (G) */
    ++l_current_ptr;
    if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error reading SPCod SPCoc element, Invalid code-block style found\n");
        return OPJ_FALSE;
    }


    opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1);              /* SPcoc (H) */
    ++l_current_ptr;







    *p_header_size = *p_header_size - 5;

    /* use custom precinct size ? */
    if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
        if (*p_header_size < l_tccp->numresolutions) {
            opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
            return OPJ_FALSE;
        }


        for (i = 0; i < l_tccp->numresolutions; ++i) {
            opj_read_bytes(l_current_ptr, &l_tmp, 1);               /* SPcoc (I_i) */
            ++l_current_ptr;
            /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
            if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
                opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
                return OPJ_FALSE;
            }
            l_tccp->prcw[i] = l_tmp & 0xf;







>
|
<
|




















>
|



>
|










|
|







>
|

>
>
>
>
>
>










>

|







10540
10541
10542
10543
10544
10545
10546
10547
10548

10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624

    /* make sure room is sufficient */
    if (*p_header_size < 5) {
        opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
        return OPJ_FALSE;
    }

    /* SPcod (D) / SPcoc (A) */
    opj_read_bytes(l_current_ptr, &l_tccp->numresolutions, 1);

    ++l_tccp->numresolutions;  /* tccp->numresolutions = read() + 1 */
    if (l_tccp->numresolutions > OPJ_J2K_MAXRLVLS) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Invalid value for numresolutions : %d, max value is set in openjpeg.h at %d\n",
                      l_tccp->numresolutions, OPJ_J2K_MAXRLVLS);
        return OPJ_FALSE;
    }
    ++l_current_ptr;

    /* If user wants to remove more resolutions than the codestream contains, return error */
    if (l_cp->m_specific_param.m_dec.m_reduce >= l_tccp->numresolutions) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error decoding component %d.\nThe number of resolutions "
                      "to remove (%d) is greater or equal than the number "
                      "of resolutions of this component (%d)\nModify the cp_reduce parameter.\n\n",
                      compno, l_cp->m_specific_param.m_dec.m_reduce, l_tccp->numresolutions);
        p_j2k->m_specific_param.m_decoder.m_state |=
            0x8000;/* FIXME J2K_DEC_STATE_ERR;*/
        return OPJ_FALSE;
    }

    /* SPcod (E) / SPcoc (B) */
    opj_read_bytes(l_current_ptr, &l_tccp->cblkw, 1);
    ++l_current_ptr;
    l_tccp->cblkw += 2;

    /* SPcod (F) / SPcoc (C) */
    opj_read_bytes(l_current_ptr, &l_tccp->cblkh, 1);
    ++l_current_ptr;
    l_tccp->cblkh += 2;

    if ((l_tccp->cblkw > 10) || (l_tccp->cblkh > 10) ||
            ((l_tccp->cblkw + l_tccp->cblkh) > 12)) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error reading SPCod SPCoc element, Invalid cblkw/cblkh combination\n");
        return OPJ_FALSE;
    }

    /* SPcod (G) / SPcoc (D) */
    opj_read_bytes(l_current_ptr, &l_tccp->cblksty, 1);
    ++l_current_ptr;
    if (l_tccp->cblksty & 0xC0U) { /* 2 msb are reserved, assume we can't read */
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error reading SPCod SPCoc element, Invalid code-block style found\n");
        return OPJ_FALSE;
    }

    /* SPcod (H) / SPcoc (E) */
    opj_read_bytes(l_current_ptr, &l_tccp->qmfbid, 1);
    ++l_current_ptr;

    if (l_tccp->qmfbid > 1) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Error reading SPCod SPCoc element, Invalid transformation found\n");
        return OPJ_FALSE;
    }

    *p_header_size = *p_header_size - 5;

    /* use custom precinct size ? */
    if (l_tccp->csty & J2K_CCP_CSTY_PRT) {
        if (*p_header_size < l_tccp->numresolutions) {
            opj_event_msg(p_manager, EVT_ERROR, "Error reading SPCod SPCoc element\n");
            return OPJ_FALSE;
        }

        /* SPcod (I_i) / SPcoc (F_i) */
        for (i = 0; i < l_tccp->numresolutions; ++i) {
            opj_read_bytes(l_current_ptr, &l_tmp, 1);
            ++l_current_ptr;
            /* Precinct exponent 0 is only allowed for lowest resolution level (Table A.21) */
            if ((i != 0) && (((l_tmp & 0xf) == 0) || ((l_tmp >> 4) == 0))) {
                opj_event_msg(p_manager, EVT_ERROR, "Invalid precinct size\n");
                return OPJ_FALSE;
            }
            l_tccp->prcw[i] = l_tmp & 0xf;
10652
10653
10654
10655
10656
10657
10658




































10659
10660
10661
10662
10663
10664
10665
        if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
            return OPJ_FALSE;
        }
    }

    return OPJ_TRUE;
}





































static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
                                     opj_stream_private_t *p_stream,
                                     opj_event_mgr_t * p_manager)
{
    OPJ_BOOL l_go_on = OPJ_TRUE;
    OPJ_UINT32 l_current_tile_no;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
        if (!p_j2k->cstr_index->tile_index[it_tile].marker) {
            return OPJ_FALSE;
        }
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_are_all_used_components_decoded(opj_j2k_t *p_j2k,
        opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 compno;
    OPJ_BOOL decoded_all_used_components = OPJ_TRUE;

    if (p_j2k->m_specific_param.m_decoder.m_numcomps_to_decode) {
        for (compno = 0;
                compno < p_j2k->m_specific_param.m_decoder.m_numcomps_to_decode; compno++) {
            OPJ_UINT32 dec_compno =
                p_j2k->m_specific_param.m_decoder.m_comps_indices_to_decode[compno];
            if (p_j2k->m_output_image->comps[dec_compno].data == NULL) {
                opj_event_msg(p_manager, EVT_WARNING, "Failed to decode component %d\n",
                              dec_compno);
                decoded_all_used_components = OPJ_FALSE;
            }
        }
    } else {
        for (compno = 0; compno < p_j2k->m_output_image->numcomps; compno++) {
            if (p_j2k->m_output_image->comps[compno].data == NULL) {
                opj_event_msg(p_manager, EVT_WARNING, "Failed to decode component %d\n",
                              compno);
                decoded_all_used_components = OPJ_FALSE;
            }
        }
    }

    if (decoded_all_used_components == OPJ_FALSE) {
        opj_event_msg(p_manager, EVT_ERROR, "Failed to decode all used components\n");
        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}


static OPJ_BOOL opj_j2k_decode_tiles(opj_j2k_t *p_j2k,
                                     opj_stream_private_t *p_stream,
                                     opj_event_mgr_t * p_manager)
{
    OPJ_BOOL l_go_on = OPJ_TRUE;
    OPJ_UINT32 l_current_tile_no;
10763
10764
10765
10766
10767
10768
10769




10770
10771
10772
10773
10774
10775
10776
                && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
            break;
        }
        if (++nr_tiles ==  p_j2k->m_cp.th * p_j2k->m_cp.tw) {
            break;
        }
    }





    return OPJ_TRUE;
}

/**
 * Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
 */







>
>
>
>







11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
                && p_j2k->m_specific_param.m_decoder.m_state == J2K_STATE_NEOC) {
            break;
        }
        if (++nr_tiles ==  p_j2k->m_cp.th * p_j2k->m_cp.tw) {
            break;
        }
    }

    if (! opj_j2k_are_all_used_components_decoded(p_j2k, p_manager)) {
        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}

/**
 * Sets up the procedures to do on decoding data. Developpers wanting to extend the library can add their own reading procedures.
 */
10891
10892
10893
10894
10895
10896
10897




10898
10899
10900
10901
10902
10903
10904
        } else {
            opj_event_msg(p_manager, EVT_WARNING,
                          "Tile read, decoded and updated is not the desired one (%d vs %d).\n",
                          l_current_tile_no + 1, l_tile_no_to_dec + 1);
        }

    }





    return OPJ_TRUE;
}

/**
 * Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
 */







>
>
>
>







11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
        } else {
            opj_event_msg(p_manager, EVT_WARNING,
                          "Tile read, decoded and updated is not the desired one (%d vs %d).\n",
                          l_current_tile_no + 1, l_tile_no_to_dec + 1);
        }

    }

    if (! opj_j2k_are_all_used_components_decoded(p_j2k, p_manager)) {
        return OPJ_FALSE;
    }

    return OPJ_TRUE;
}

/**
 * Sets up the procedures to do on decoding one tile. Developpers wanting to extend the library can add their own reading procedures.
 */
11178
11179
11180
11181
11182
11183
11184




































11185
11186
11187
11188
11189
11190
11191
            }
        }
    }

    return OPJ_FALSE;
}





































OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
                        opj_stream_private_t *p_stream,
                        opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 i, j;
    OPJ_UINT32 l_nb_tiles;
    OPJ_SIZE_T l_max_tile_size = 0, l_current_tile_size;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
            }
        }
    }

    return OPJ_FALSE;
}

/* ----------------------------------------------------------------------- */

OPJ_BOOL opj_j2k_encoder_set_extra_options(
    opj_j2k_t *p_j2k,
    const char* const* p_options,
    opj_event_mgr_t * p_manager)
{
    const char* const* p_option_iter;

    if (p_options == NULL) {
        return OPJ_TRUE;
    }

    for (p_option_iter = p_options; *p_option_iter != NULL; ++p_option_iter) {
        if (strncmp(*p_option_iter, "PLT=", 4) == 0) {
            if (strcmp(*p_option_iter, "PLT=YES") == 0) {
                p_j2k->m_specific_param.m_encoder.m_PLT = OPJ_TRUE;
            } else if (strcmp(*p_option_iter, "PLT=NO") == 0) {
                p_j2k->m_specific_param.m_encoder.m_PLT = OPJ_FALSE;
            } else {
                opj_event_msg(p_manager, EVT_ERROR,
                              "Invalid value for option: %s.\n", *p_option_iter);
                return OPJ_FALSE;
            }
        } else {
            opj_event_msg(p_manager, EVT_ERROR,
                          "Invalid option: %s.\n", *p_option_iter);
            return OPJ_FALSE;
        }
    }

    return OPJ_TRUE;
}

/* ----------------------------------------------------------------------- */

OPJ_BOOL opj_j2k_encode(opj_j2k_t * p_j2k,
                        opj_stream_private_t *p_stream,
                        opj_event_mgr_t * p_manager)
{
    OPJ_UINT32 i, j;
    OPJ_UINT32 l_nb_tiles;
    OPJ_SIZE_T l_max_tile_size = 0, l_current_tile_size;
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
                    if (l_current_data) {
                        opj_free(l_current_data);
                    }
                    return OPJ_FALSE;
                }
            }
        }
        l_current_tile_size = opj_tcd_get_encoded_tile_size(p_j2k->m_tcd);
        if (!l_reuse_data) {
            if (l_current_tile_size > l_max_tile_size) {
                OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
                                               l_current_tile_size);
                if (! l_new_current_data) {
                    if (l_current_data) {
                        opj_free(l_current_data);







|







12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
                    if (l_current_data) {
                        opj_free(l_current_data);
                    }
                    return OPJ_FALSE;
                }
            }
        }
        l_current_tile_size = opj_tcd_get_encoder_input_buffer_size(p_j2k->m_tcd);
        if (!l_reuse_data) {
            if (l_current_tile_size > l_max_tile_size) {
                OPJ_BYTE *l_new_current_data = (OPJ_BYTE *) opj_realloc(l_current_data,
                                               l_current_tile_size);
                if (! l_new_current_data) {
                    if (l_current_data) {
                        opj_free(l_current_data);
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577

    /* DEVELOPER CORNER, insert your custom procedures */
    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                           (opj_procedure)opj_j2k_write_eoc, p_manager)) {
        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
            return OPJ_FALSE;
        }
    }

    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,







|







12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457

    /* DEVELOPER CORNER, insert your custom procedures */
    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                           (opj_procedure)opj_j2k_write_eoc, p_manager)) {
        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz) || OPJ_IS_IMF(p_j2k->m_cp.rsiz)) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_updated_tlm, p_manager)) {
            return OPJ_FALSE;
        }
    }

    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
        return OPJ_FALSE;
    }
    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                           (opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz)) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_tlm, p_manager)) {
            return OPJ_FALSE;
        }

        if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
            if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,







|







12526
12527
12528
12529
12530
12531
12532
12533
12534
12535
12536
12537
12538
12539
12540
        return OPJ_FALSE;
    }
    if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                           (opj_procedure)opj_j2k_write_all_qcc, p_manager)) {
        return OPJ_FALSE;
    }

    if (OPJ_IS_CINEMA(p_j2k->m_cp.rsiz) || OPJ_IS_IMF(p_j2k->m_cp.rsiz)) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_tlm, p_manager)) {
            return OPJ_FALSE;
        }

        if (p_j2k->m_cp.rsiz == OPJ_PROFILE_CINEMA_4K) {
            if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
11673
11674
11675
11676
11677
11678
11679

11680
11681
11682
11683
11684
11685
11686
11687
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_com, p_manager)) {
            return OPJ_FALSE;
        }
    }

    /* DEVELOPER CORNER, insert your custom procedures */

    if (p_j2k->m_cp.rsiz & OPJ_EXTENSION_MCT) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
            return OPJ_FALSE;
        }
    }
    /* End of Developer Corner */








>
|







12553
12554
12555
12556
12557
12558
12559
12560
12561
12562
12563
12564
12565
12566
12567
12568
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_com, p_manager)) {
            return OPJ_FALSE;
        }
    }

    /* DEVELOPER CORNER, insert your custom procedures */
    if ((p_j2k->m_cp.rsiz & (OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT)) ==
            (OPJ_PROFILE_PART2 | OPJ_EXTENSION_MCT)) {
        if (! opj_procedure_list_add_procedure(p_j2k->m_procedure_list,
                                               (opj_procedure)opj_j2k_write_mct_data_group, p_manager)) {
            return OPJ_FALSE;
        }
    }
    /* End of Developer Corner */

11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 p_total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager)
{
    OPJ_UINT32 l_nb_bytes_written = 0;
    OPJ_UINT32 l_current_nb_bytes_written;
    OPJ_BYTE * l_begin_data = 00;








|







12584
12585
12586
12587
12588
12589
12590
12591
12592
12593
12594
12595
12596
12597
12598

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_first_tile_part(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager)
{
    OPJ_UINT32 l_nb_bytes_written = 0;
    OPJ_UINT32 l_current_nb_bytes_written;
    OPJ_BYTE * l_begin_data = 00;

11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
    p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;

    /* INDEX >> */
    /* << INDEX */

    l_current_nb_bytes_written = 0;
    l_begin_data = p_data;
    if (! opj_j2k_write_sot(p_j2k, p_data, p_total_data_size,
                            &l_current_nb_bytes_written, p_stream,
                            p_manager)) {
        return OPJ_FALSE;
    }

    l_nb_bytes_written += l_current_nb_bytes_written;
    p_data += l_current_nb_bytes_written;
    p_total_data_size -= l_current_nb_bytes_written;

    if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
        for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
            l_current_nb_bytes_written = 0;
            opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            p_total_data_size -= l_current_nb_bytes_written;

            l_current_nb_bytes_written = 0;
            opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            p_total_data_size -= l_current_nb_bytes_written;
        }
#endif
        if (l_cp->tcps[p_j2k->m_current_tile_number].numpocs) {
            l_current_nb_bytes_written = 0;
            opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            p_total_data_size -= l_current_nb_bytes_written;
        }
    }

    l_current_nb_bytes_written = 0;
    if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                            p_total_data_size, p_stream, p_manager)) {
        return OPJ_FALSE;
    }

    l_nb_bytes_written += l_current_nb_bytes_written;
    * p_data_written = l_nb_bytes_written;

    /* Writing Psot in SOT marker */
    opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
                    4);                                 /* PSOT */

    if (OPJ_IS_CINEMA(l_cp->rsiz)) {
        opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 p_total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager
                                            )
{
    OPJ_UINT32 tilepartno = 0;
    OPJ_UINT32 l_nb_bytes_written = 0;
    OPJ_UINT32 l_current_nb_bytes_written;







|







|









|






|


|





|





|










|









|







12608
12609
12610
12611
12612
12613
12614
12615
12616
12617
12618
12619
12620
12621
12622
12623
12624
12625
12626
12627
12628
12629
12630
12631
12632
12633
12634
12635
12636
12637
12638
12639
12640
12641
12642
12643
12644
12645
12646
12647
12648
12649
12650
12651
12652
12653
12654
12655
12656
12657
12658
12659
12660
12661
12662
12663
12664
12665
12666
12667
12668
12669
12670
12671
12672
12673
12674
12675
12676
12677
12678
12679
12680
12681
12682
12683
    p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = 0;

    /* INDEX >> */
    /* << INDEX */

    l_current_nb_bytes_written = 0;
    l_begin_data = p_data;
    if (! opj_j2k_write_sot(p_j2k, p_data, total_data_size,
                            &l_current_nb_bytes_written, p_stream,
                            p_manager)) {
        return OPJ_FALSE;
    }

    l_nb_bytes_written += l_current_nb_bytes_written;
    p_data += l_current_nb_bytes_written;
    total_data_size -= l_current_nb_bytes_written;

    if (!OPJ_IS_CINEMA(l_cp->rsiz)) {
#if 0
        for (compno = 1; compno < p_j2k->m_private_image->numcomps; compno++) {
            l_current_nb_bytes_written = 0;
            opj_j2k_write_coc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            total_data_size -= l_current_nb_bytes_written;

            l_current_nb_bytes_written = 0;
            opj_j2k_write_qcc_in_memory(p_j2k, compno, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            total_data_size -= l_current_nb_bytes_written;
        }
#endif
        if (l_cp->tcps[p_j2k->m_current_tile_number].POC) {
            l_current_nb_bytes_written = 0;
            opj_j2k_write_poc_in_memory(p_j2k, p_data, &l_current_nb_bytes_written,
                                        p_manager);
            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            total_data_size -= l_current_nb_bytes_written;
        }
    }

    l_current_nb_bytes_written = 0;
    if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                            total_data_size, p_stream, p_manager)) {
        return OPJ_FALSE;
    }

    l_nb_bytes_written += l_current_nb_bytes_written;
    * p_data_written = l_nb_bytes_written;

    /* Writing Psot in SOT marker */
    opj_write_bytes(l_begin_data + 6, l_nb_bytes_written,
                    4);                                 /* PSOT */

    if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {
        opj_j2k_update_tlm(p_j2k, l_nb_bytes_written);
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_j2k_write_all_tile_parts(opj_j2k_t *p_j2k,
        OPJ_BYTE * p_data,
        OPJ_UINT32 * p_data_written,
        OPJ_UINT32 total_data_size,
        opj_stream_private_t *p_stream,
        struct opj_event_mgr * p_manager
                                            )
{
    OPJ_UINT32 tilepartno = 0;
    OPJ_UINT32 l_nb_bytes_written = 0;
    OPJ_UINT32 l_current_nb_bytes_written;
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
    for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
        l_current_nb_bytes_written = 0;
        l_part_tile_size = 0;
        l_begin_data = p_data;

        if (! opj_j2k_write_sot(p_j2k, p_data,
                                p_total_data_size,
                                &l_current_nb_bytes_written,
                                p_stream,
                                p_manager)) {
            return OPJ_FALSE;
        }

        l_nb_bytes_written += l_current_nb_bytes_written;
        p_data += l_current_nb_bytes_written;
        p_total_data_size -= l_current_nb_bytes_written;
        l_part_tile_size += l_current_nb_bytes_written;

        l_current_nb_bytes_written = 0;
        if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                                p_total_data_size, p_stream, p_manager)) {
            return OPJ_FALSE;
        }

        p_data += l_current_nb_bytes_written;
        l_nb_bytes_written += l_current_nb_bytes_written;
        p_total_data_size -= l_current_nb_bytes_written;
        l_part_tile_size += l_current_nb_bytes_written;

        /* Writing Psot in SOT marker */
        opj_write_bytes(l_begin_data + 6, l_part_tile_size,
                        4);                                   /* PSOT */

        if (OPJ_IS_CINEMA(l_cp->rsiz)) {
            opj_j2k_update_tlm(p_j2k, l_part_tile_size);
        }

        ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
    }

    for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
        l_tcd->cur_pino = pino;

        /*Get number of tile parts*/
        tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
        for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
            p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
            l_current_nb_bytes_written = 0;
            l_part_tile_size = 0;
            l_begin_data = p_data;

            if (! opj_j2k_write_sot(p_j2k, p_data,
                                    p_total_data_size,
                                    &l_current_nb_bytes_written, p_stream,
                                    p_manager)) {
                return OPJ_FALSE;
            }

            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            p_total_data_size -= l_current_nb_bytes_written;
            l_part_tile_size += l_current_nb_bytes_written;

            l_current_nb_bytes_written = 0;

            if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                                    p_total_data_size, p_stream, p_manager)) {
                return OPJ_FALSE;
            }

            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            p_total_data_size -= l_current_nb_bytes_written;
            l_part_tile_size += l_current_nb_bytes_written;

            /* Writing Psot in SOT marker */
            opj_write_bytes(l_begin_data + 6, l_part_tile_size,
                            4);                                   /* PSOT */

            if (OPJ_IS_CINEMA(l_cp->rsiz)) {
                opj_j2k_update_tlm(p_j2k, l_part_tile_size);
            }

            ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
        }
    }








|








|




|





|






|


















|







|





|





|






|







12702
12703
12704
12705
12706
12707
12708
12709
12710
12711
12712
12713
12714
12715
12716
12717
12718
12719
12720
12721
12722
12723
12724
12725
12726
12727
12728
12729
12730
12731
12732
12733
12734
12735
12736
12737
12738
12739
12740
12741
12742
12743
12744
12745
12746
12747
12748
12749
12750
12751
12752
12753
12754
12755
12756
12757
12758
12759
12760
12761
12762
12763
12764
12765
12766
12767
12768
12769
12770
12771
12772
12773
12774
12775
12776
12777
12778
12779
12780
12781
12782
12783
12784
12785
12786
12787
12788
12789
    for (tilepartno = 1; tilepartno < tot_num_tp ; ++tilepartno) {
        p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
        l_current_nb_bytes_written = 0;
        l_part_tile_size = 0;
        l_begin_data = p_data;

        if (! opj_j2k_write_sot(p_j2k, p_data,
                                total_data_size,
                                &l_current_nb_bytes_written,
                                p_stream,
                                p_manager)) {
            return OPJ_FALSE;
        }

        l_nb_bytes_written += l_current_nb_bytes_written;
        p_data += l_current_nb_bytes_written;
        total_data_size -= l_current_nb_bytes_written;
        l_part_tile_size += l_current_nb_bytes_written;

        l_current_nb_bytes_written = 0;
        if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                                total_data_size, p_stream, p_manager)) {
            return OPJ_FALSE;
        }

        p_data += l_current_nb_bytes_written;
        l_nb_bytes_written += l_current_nb_bytes_written;
        total_data_size -= l_current_nb_bytes_written;
        l_part_tile_size += l_current_nb_bytes_written;

        /* Writing Psot in SOT marker */
        opj_write_bytes(l_begin_data + 6, l_part_tile_size,
                        4);                                   /* PSOT */

        if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {
            opj_j2k_update_tlm(p_j2k, l_part_tile_size);
        }

        ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
    }

    for (pino = 1; pino <= l_tcp->numpocs; ++pino) {
        l_tcd->cur_pino = pino;

        /*Get number of tile parts*/
        tot_num_tp = opj_j2k_get_num_tp(l_cp, pino, p_j2k->m_current_tile_number);
        for (tilepartno = 0; tilepartno < tot_num_tp ; ++tilepartno) {
            p_j2k->m_specific_param.m_encoder.m_current_poc_tile_part_number = tilepartno;
            l_current_nb_bytes_written = 0;
            l_part_tile_size = 0;
            l_begin_data = p_data;

            if (! opj_j2k_write_sot(p_j2k, p_data,
                                    total_data_size,
                                    &l_current_nb_bytes_written, p_stream,
                                    p_manager)) {
                return OPJ_FALSE;
            }

            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            total_data_size -= l_current_nb_bytes_written;
            l_part_tile_size += l_current_nb_bytes_written;

            l_current_nb_bytes_written = 0;

            if (! opj_j2k_write_sod(p_j2k, l_tcd, p_data, &l_current_nb_bytes_written,
                                    total_data_size, p_stream, p_manager)) {
                return OPJ_FALSE;
            }

            l_nb_bytes_written += l_current_nb_bytes_written;
            p_data += l_current_nb_bytes_written;
            total_data_size -= l_current_nb_bytes_written;
            l_part_tile_size += l_current_nb_bytes_written;

            /* Writing Psot in SOT marker */
            opj_write_bytes(l_begin_data + 6, l_part_tile_size,
                            4);                                   /* PSOT */

            if (OPJ_IS_CINEMA(l_cp->rsiz) || OPJ_IS_IMF(l_cp->rsiz)) {
                opj_j2k_update_tlm(p_j2k, l_part_tile_size);
            }

            ++p_j2k->m_specific_param.m_encoder.m_current_tile_part_number;
        }
    }

Changes to jni/openjpeg/src/lib/openjp2/j2k.h.
527
528
529
530
531
532
533

534
535





536
537
538
539
540
541
542
    /* size of the encoded_data */
    OPJ_UINT32 m_encoded_tile_size;

    /* encoded data for a tile */
    OPJ_BYTE * m_header_tile_data;

    /* size of the encoded_data */

    OPJ_UINT32 m_header_tile_data_size;







} opj_j2k_enc_t;



struct opj_tcd;
/**







>


>
>
>
>
>







527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
    /* size of the encoded_data */
    OPJ_UINT32 m_encoded_tile_size;

    /* encoded data for a tile */
    OPJ_BYTE * m_header_tile_data;

    /* size of the encoded_data */

    OPJ_UINT32 m_header_tile_data_size;

    /* whether to generate PLT markers */
    OPJ_BOOL   m_PLT;

    /* reserved bytes in m_encoded_tile_size for PLT markers */
    OPJ_UINT32 m_reserved_bytes_for_PLT;

} opj_j2k_enc_t;



struct opj_tcd;
/**
573
574
575
576
577
578
579
580
581
582
583
584
585

586


587
588

589
590
591
592
593
594
595

    /** number of the tile currently concern by coding/decoding */
    OPJ_UINT32 m_current_tile_number;

    /** the current tile coder/decoder **/
    struct opj_tcd *    m_tcd;

    /** Number of threads to use */
    int m_num_threads;

    /** Thread pool */
    opj_thread_pool_t* m_tp;


    OPJ_UINT32 ihdr_w;


    OPJ_UINT32 ihdr_h;
    OPJ_UINT32 enumcs;

    unsigned int dump_state;
}
opj_j2k_t;











<
<
<



>

>
>

|
>







579
580
581
582
583
584
585



586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602

    /** number of the tile currently concern by coding/decoding */
    OPJ_UINT32 m_current_tile_number;

    /** the current tile coder/decoder **/
    struct opj_tcd *    m_tcd;




    /** Thread pool */
    opj_thread_pool_t* m_tp;

    /** Image width coming from JP2 IHDR box. 0 from a pure codestream */
    OPJ_UINT32 ihdr_w;

    /** Image height coming from JP2 IHDR box. 0 from a pure codestream */
    OPJ_UINT32 ihdr_h;

    /** Set to 1 by the decoder initialization if OPJ_DPARAMETERS_DUMP_FLAG is set */
    unsigned int dump_state;
}
opj_j2k_t;




823
824
825
826
827
828
829













830
831
832
833
834
835
836
                          opj_event_mgr_t * p_manager,
                          OPJ_UINT32 tile_index);

OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager);















/**
 * Writes a tile.
 * @param   p_j2k       the jpeg2000 codec.
 * @param p_tile_index FIXME DOC
 * @param p_data FIXME DOC
 * @param p_data_size FIXME DOC







>
>
>
>
>
>
>
>
>
>
>
>
>







830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
                          opj_event_mgr_t * p_manager,
                          OPJ_UINT32 tile_index);

OPJ_BOOL opj_j2k_set_decoded_resolution_factor(opj_j2k_t *p_j2k,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager);

/**
 * Specify extra options for the encoder.
 *
 * @param  p_j2k        the jpeg2000 codec.
 * @param  p_options    options
 * @param  p_manager    the user event manager
 *
 * @see opj_encoder_set_extra_options() for more details.
 */
OPJ_BOOL opj_j2k_encoder_set_extra_options(
    opj_j2k_t *p_j2k,
    const char* const* p_options,
    opj_event_mgr_t * p_manager);

/**
 * Writes a tile.
 * @param   p_j2k       the jpeg2000 codec.
 * @param p_tile_index FIXME DOC
 * @param p_data FIXME DOC
 * @param p_data_size FIXME DOC
Changes to jni/openjpeg/src/lib/openjp2/jp2.c.
582
583
584
585
586
587
588






589
590
591
592
593
594
595
    opj_read_bytes(p_image_header_data, &(jp2->h), 4);          /* HEIGHT */
    p_image_header_data += 4;
    opj_read_bytes(p_image_header_data, &(jp2->w), 4);          /* WIDTH */
    p_image_header_data += 4;
    opj_read_bytes(p_image_header_data, &(jp2->numcomps), 2);   /* NC */
    p_image_header_data += 2;







    if ((jp2->numcomps - 1U) >=
            16384U) { /* unsigned underflow is well defined: 1U <= jp2->numcomps <= 16384U */
        opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components (ihdr)\n");
        return OPJ_FALSE;
    }

    /* allocate memory for components */







>
>
>
>
>
>







582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
    opj_read_bytes(p_image_header_data, &(jp2->h), 4);          /* HEIGHT */
    p_image_header_data += 4;
    opj_read_bytes(p_image_header_data, &(jp2->w), 4);          /* WIDTH */
    p_image_header_data += 4;
    opj_read_bytes(p_image_header_data, &(jp2->numcomps), 2);   /* NC */
    p_image_header_data += 2;

    if (jp2->h < 1 || jp2->w < 1 || jp2->numcomps < 1) {
        opj_event_msg(p_manager, EVT_ERROR,
                      "Wrong values for: w(%d) h(%d) numcomps(%d) (ihdr)\n",
                      jp2->w, jp2->h, jp2->numcomps);
        return OPJ_FALSE;
    }
    if ((jp2->numcomps - 1U) >=
            16384U) { /* unsigned underflow is well defined: 1U <= jp2->numcomps <= 16384U */
        opj_event_msg(p_manager, EVT_ERROR, "Invalid number of components (ihdr)\n");
        return OPJ_FALSE;
    }

    /* allocate memory for components */
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
    } else if (jp2->meth > 2) {
        /*  ISO/IEC 15444-1:2004 (E), Table I.9 Legal METH values:
        conforming JP2 reader shall ignore the entire Colour Specification box.*/
        opj_event_msg(p_manager, EVT_INFO,
                      "COLR BOX meth value is not a regular value (%d), "
                      "so we will ignore the entire Colour Specification box. \n", jp2->meth);
    }
    if (jp2->color.jp2_has_colr) {
        jp2->j2k->enumcs = jp2->enumcs;
    }
    return OPJ_TRUE;
}

OPJ_BOOL opj_jp2_decode(opj_jp2_t *jp2,
                        opj_stream_private_t *p_stream,
                        opj_image_t* p_image,
                        opj_event_mgr_t * p_manager)







<
<
|







1586
1587
1588
1589
1590
1591
1592


1593
1594
1595
1596
1597
1598
1599
1600
    } else if (jp2->meth > 2) {
        /*  ISO/IEC 15444-1:2004 (E), Table I.9 Legal METH values:
        conforming JP2 reader shall ignore the entire Colour Specification box.*/
        opj_event_msg(p_manager, EVT_INFO,
                      "COLR BOX meth value is not a regular value (%d), "
                      "so we will ignore the entire Colour Specification box. \n", jp2->meth);
    }



    return OPJ_TRUE;
}

OPJ_BOOL opj_jp2_decode(opj_jp2_t *jp2,
                        opj_stream_private_t *p_stream,
                        opj_image_t* p_image,
                        opj_event_mgr_t * p_manager)
3231
3232
3233
3234
3235
3236
3237












3238
3239
3240
3241
3242
3243
3244

OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager)
{
    return opj_j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager);
}













/* JPIP specific */

#ifdef USE_JPIP
static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2,
                                    opj_stream_private_t *cio,
                                    opj_event_mgr_t * p_manager)







>
>
>
>
>
>
>
>
>
>
>
>







3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260

OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager)
{
    return opj_j2k_set_decoded_resolution_factor(p_jp2->j2k, res_factor, p_manager);
}

/* ----------------------------------------------------------------------- */

OPJ_BOOL opj_jp2_encoder_set_extra_options(
    opj_jp2_t *p_jp2,
    const char* const* p_options,
    opj_event_mgr_t * p_manager)
{
    return opj_j2k_encoder_set_extra_options(p_jp2->j2k, p_options, p_manager);
}

/* ----------------------------------------------------------------------- */

/* JPIP specific */

#ifdef USE_JPIP
static OPJ_BOOL opj_jpip_write_iptr(opj_jp2_t *jp2,
                                    opj_stream_private_t *cio,
                                    opj_event_mgr_t * p_manager)
Changes to jni/openjpeg/src/lib/openjp2/jp2.h.
455
456
457
458
459
460
461














462
463
464
465
466
467
468
/**
 *
 */
OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager);
















/* TODO MSD: clean these 3 functions */
/**
 * Dump some elements from the JP2 decompression structure .
 *
 *@param p_jp2        the jp2 codec.
 *@param flag        flag to describe what elements are dump.







>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
/**
 *
 */
OPJ_BOOL opj_jp2_set_decoded_resolution_factor(opj_jp2_t *p_jp2,
        OPJ_UINT32 res_factor,
        opj_event_mgr_t * p_manager);

/**
 * Specify extra options for the encoder.
 *
 * @param  p_jp2        the jpeg2000 codec.
 * @param  p_options    options
 * @param  p_manager    the user event manager
 *
 * @see opj_encoder_set_extra_options() for more details.
 */
OPJ_BOOL opj_jp2_encoder_set_extra_options(
    opj_jp2_t *p_jp2,
    const char* const* p_options,
    opj_event_mgr_t * p_manager);


/* TODO MSD: clean these 3 functions */
/**
 * Dump some elements from the JP2 decompression structure .
 *
 *@param p_jp2        the jp2 codec.
 *@param flag        flag to describe what elements are dump.
Changes to jni/openjpeg/src/lib/openjp2/mct.c.
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#else
void opj_mct_decode(
    OPJ_INT32* OPJ_RESTRICT c0,
    OPJ_INT32* OPJ_RESTRICT c1,
    OPJ_INT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_UINT32 i;
    for (i = 0; i < n; ++i) {
        OPJ_INT32 y = c0[i];
        OPJ_INT32 u = c1[i];
        OPJ_INT32 v = c2[i];
        OPJ_INT32 g = y - ((u + v) >> 2);
        OPJ_INT32 r = v + g;
        OPJ_INT32 b = u + g;







|







179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
#else
void opj_mct_decode(
    OPJ_INT32* OPJ_RESTRICT c0,
    OPJ_INT32* OPJ_RESTRICT c1,
    OPJ_INT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_SIZE_T i;
    for (i = 0; i < n; ++i) {
        OPJ_INT32 y = c0[i];
        OPJ_INT32 u = c1[i];
        OPJ_INT32 v = c2[i];
        OPJ_INT32 g = y - ((u + v) >> 2);
        OPJ_INT32 r = v + g;
        OPJ_INT32 b = u + g;
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
{
    return opj_mct_norms[compno];
}

/* <summary> */
/* Forward irreversible MCT. */
/* </summary> */
#ifdef __SSE4_1__
void opj_mct_encode_real(
    OPJ_INT32* OPJ_RESTRICT c0,
    OPJ_INT32* OPJ_RESTRICT c1,
    OPJ_INT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_SIZE_T i;
    const OPJ_SIZE_T len = n;

    const __m128i ry = _mm_set1_epi32(2449);
    const __m128i gy = _mm_set1_epi32(4809);
    const __m128i by = _mm_set1_epi32(934);
    const __m128i ru = _mm_set1_epi32(1382);
    const __m128i gu = _mm_set1_epi32(2714);
    /* const __m128i bu = _mm_set1_epi32(4096); */
    /* const __m128i rv = _mm_set1_epi32(4096); */
    const __m128i gv = _mm_set1_epi32(3430);
    const __m128i bv = _mm_set1_epi32(666);
    const __m128i mulround = _mm_shuffle_epi32(_mm_cvtsi32_si128(4096),
                             _MM_SHUFFLE(1, 0, 1, 0));

    for (i = 0; i < (len & ~3U); i += 4) {
        __m128i lo, hi;
        __m128i y, u, v;
        __m128i r = _mm_load_si128((const __m128i *) & (c0[i]));
        __m128i g = _mm_load_si128((const __m128i *) & (c1[i]));
        __m128i b = _mm_load_si128((const __m128i *) & (c2[i]));

        lo = r;
        hi = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, ry);
        hi = _mm_mul_epi32(hi, ry);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        y = _mm_blend_epi16(lo, hi, 0xCC);

        lo = g;
        hi = _mm_shuffle_epi32(g, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, gy);
        hi = _mm_mul_epi32(hi, gy);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        y = _mm_add_epi32(y, _mm_blend_epi16(lo, hi, 0xCC));

        lo = b;
        hi = _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, by);
        hi = _mm_mul_epi32(hi, by);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        y = _mm_add_epi32(y, _mm_blend_epi16(lo, hi, 0xCC));
        _mm_store_si128((__m128i *) & (c0[i]), y);

        /*lo = b;
        hi = _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, mulround);
        hi = _mm_mul_epi32(hi, mulround);*/
        lo = _mm_cvtepi32_epi64(_mm_shuffle_epi32(b, _MM_SHUFFLE(3, 2, 2, 0)));
        hi = _mm_cvtepi32_epi64(_mm_shuffle_epi32(b, _MM_SHUFFLE(3, 2, 3, 1)));
        lo = _mm_slli_epi64(lo, 12);
        hi = _mm_slli_epi64(hi, 12);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        u = _mm_blend_epi16(lo, hi, 0xCC);

        lo = r;
        hi = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, ru);
        hi = _mm_mul_epi32(hi, ru);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        u = _mm_sub_epi32(u, _mm_blend_epi16(lo, hi, 0xCC));

        lo = g;
        hi = _mm_shuffle_epi32(g, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, gu);
        hi = _mm_mul_epi32(hi, gu);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        u = _mm_sub_epi32(u, _mm_blend_epi16(lo, hi, 0xCC));
        _mm_store_si128((__m128i *) & (c1[i]), u);

        /*lo = r;
        hi = _mm_shuffle_epi32(r, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, mulround);
        hi = _mm_mul_epi32(hi, mulround);*/
        lo = _mm_cvtepi32_epi64(_mm_shuffle_epi32(r, _MM_SHUFFLE(3, 2, 2, 0)));
        hi = _mm_cvtepi32_epi64(_mm_shuffle_epi32(r, _MM_SHUFFLE(3, 2, 3, 1)));
        lo = _mm_slli_epi64(lo, 12);
        hi = _mm_slli_epi64(hi, 12);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        v = _mm_blend_epi16(lo, hi, 0xCC);

        lo = g;
        hi = _mm_shuffle_epi32(g, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, gv);
        hi = _mm_mul_epi32(hi, gv);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        v = _mm_sub_epi32(v, _mm_blend_epi16(lo, hi, 0xCC));

        lo = b;
        hi = _mm_shuffle_epi32(b, _MM_SHUFFLE(3, 3, 1, 1));
        lo = _mm_mul_epi32(lo, bv);
        hi = _mm_mul_epi32(hi, bv);
        lo = _mm_add_epi64(lo, mulround);
        hi = _mm_add_epi64(hi, mulround);
        lo = _mm_srli_epi64(lo, 13);
        hi = _mm_slli_epi64(hi, 32 - 13);
        v = _mm_sub_epi32(v, _mm_blend_epi16(lo, hi, 0xCC));
        _mm_store_si128((__m128i *) & (c2[i]), v);
    }
    for (; i < len; ++i) {
        OPJ_INT32 r = c0[i];
        OPJ_INT32 g = c1[i];
        OPJ_INT32 b = c2[i];
        OPJ_INT32 y =  opj_int_fix_mul(r, 2449) + opj_int_fix_mul(g,
                       4809) + opj_int_fix_mul(b, 934);
        OPJ_INT32 u = -opj_int_fix_mul(r, 1382) - opj_int_fix_mul(g,
                      2714) + opj_int_fix_mul(b, 4096);
        OPJ_INT32 v =  opj_int_fix_mul(r, 4096) - opj_int_fix_mul(g,
                       3430) - opj_int_fix_mul(b, 666);
        c0[i] = y;
        c1[i] = u;
        c2[i] = v;
    }
}
#else
void opj_mct_encode_real(
    OPJ_INT32* OPJ_RESTRICT c0,
    OPJ_INT32* OPJ_RESTRICT c1,
    OPJ_INT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_UINT32 i;
    for (i = 0; i < n; ++i) {
        OPJ_INT32 r = c0[i];
        OPJ_INT32 g = c1[i];
        OPJ_INT32 b = c2[i];
        OPJ_INT32 y =  opj_int_fix_mul(r, 2449) + opj_int_fix_mul(g,
                       4809) + opj_int_fix_mul(b, 934);
        OPJ_INT32 u = -opj_int_fix_mul(r, 1382) - opj_int_fix_mul(g,
                      2714) + opj_int_fix_mul(b, 4096);
        OPJ_INT32 v =  opj_int_fix_mul(r, 4096) - opj_int_fix_mul(g,
                       3430) - opj_int_fix_mul(b, 666);
        c0[i] = y;
        c1[i] = u;
        c2[i] = v;
    }
}
#endif

/* <summary> */
/* Inverse irreversible MCT. */
/* </summary> */
void opj_mct_decode_real(
    OPJ_FLOAT32* OPJ_RESTRICT c0,
    OPJ_FLOAT32* OPJ_RESTRICT c1,
    OPJ_FLOAT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_UINT32 i;
#ifdef __SSE__
    __m128 vrv, vgu, vgv, vbu;
    vrv = _mm_set1_ps(1.402f);
    vgu = _mm_set1_ps(0.34413f);
    vgv = _mm_set1_ps(0.71414f);
    vbu = _mm_set1_ps(1.772f);
    for (i = 0; i < (n >> 3); ++i) {







<

|
|
|



<
|
|
|
|
|
|
|
<
|
|
<
<
|
|
<
|
<
<
<
<
<
<
<
<
<
<
<
<
<

<
<
|
|
|
|
|
<
<
|
<
<
|
<
|
|
|
|
<
|
|
|
<
<
<
<
<
|
<
<
<
<
<
<

<
<
|
|
<
<
|
<
<
|
<
<
|
<
|
<
|
<
<
<
|
<
<
|
<
<
<
|
|
<
<
|
<
<
|
|
<
|
<
<
<
<
<
<
|
|
<
<
<
|
<
<
<
<
<
<
|
|
|
|
|
<
|
<
|
<





<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<










|







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
{
    return opj_mct_norms[compno];
}

/* <summary> */
/* Forward irreversible MCT. */
/* </summary> */

void opj_mct_encode_real(
    OPJ_FLOAT32* OPJ_RESTRICT c0,
    OPJ_FLOAT32* OPJ_RESTRICT c1,
    OPJ_FLOAT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_SIZE_T i;

#ifdef __SSE__
    const __m128 YR = _mm_set1_ps(0.299f);
    const __m128 YG = _mm_set1_ps(0.587f);
    const __m128 YB = _mm_set1_ps(0.114f);
    const __m128 UR = _mm_set1_ps(-0.16875f);
    const __m128 UG = _mm_set1_ps(-0.331260f);
    const __m128 UB = _mm_set1_ps(0.5f);

    const __m128 VR = _mm_set1_ps(0.5f);
    const __m128 VG = _mm_set1_ps(-0.41869f);


    const __m128 VB = _mm_set1_ps(-0.08131f);
    for (i = 0; i < (n >> 3); i ++) {

        __m128 r, g, b, y, u, v;
















        r = _mm_load_ps(c0);
        g = _mm_load_ps(c1);
        b = _mm_load_ps(c2);
        y = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, YR), _mm_mul_ps(g, YG)),
                       _mm_mul_ps(b, YB));


        u = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, UR), _mm_mul_ps(g, UG)),


                       _mm_mul_ps(b, UB));

        v = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, VR), _mm_mul_ps(g, VG)),
                       _mm_mul_ps(b, VB));
        _mm_store_ps(c0, y);
        _mm_store_ps(c1, u);

        _mm_store_ps(c2, v);
        c0 += 4;
        c1 += 4;





        c2 += 4;









        r = _mm_load_ps(c0);
        g = _mm_load_ps(c1);


        b = _mm_load_ps(c2);


        y = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, YR), _mm_mul_ps(g, YG)),


                       _mm_mul_ps(b, YB));

        u = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, UR), _mm_mul_ps(g, UG)),

                       _mm_mul_ps(b, UB));



        v = _mm_add_ps(_mm_add_ps(_mm_mul_ps(r, VR), _mm_mul_ps(g, VG)),


                       _mm_mul_ps(b, VB));



        _mm_store_ps(c0, y);
        _mm_store_ps(c1, u);


        _mm_store_ps(c2, v);


        c0 += 4;
        c1 += 4;

        c2 += 4;






    }
    n &= 7;



#endif






    for (i = 0; i < n; ++i) {
        OPJ_FLOAT32 r = c0[i];
        OPJ_FLOAT32 g = c1[i];
        OPJ_FLOAT32 b = c2[i];
        OPJ_FLOAT32 y = 0.299f * r + 0.587f * g + 0.114f * b;

        OPJ_FLOAT32 u = -0.16875f * r - 0.331260f * g + 0.5f * b;

        OPJ_FLOAT32 v = 0.5f * r - 0.41869f * g - 0.08131f * b;

        c0[i] = y;
        c1[i] = u;
        c2[i] = v;
    }
}

























/* <summary> */
/* Inverse irreversible MCT. */
/* </summary> */
void opj_mct_decode_real(
    OPJ_FLOAT32* OPJ_RESTRICT c0,
    OPJ_FLOAT32* OPJ_RESTRICT c1,
    OPJ_FLOAT32* OPJ_RESTRICT c2,
    OPJ_SIZE_T n)
{
    OPJ_SIZE_T i;
#ifdef __SSE__
    __m128 vrv, vgu, vgv, vbu;
    vrv = _mm_set1_ps(1.402f);
    vgu = _mm_set1_ps(0.34413f);
    vgv = _mm_set1_ps(0.71414f);
    vbu = _mm_set1_ps(1.772f);
    for (i = 0; i < (n >> 3); ++i) {
Changes to jni/openjpeg/src/lib/openjp2/mct.h.
81
82
83
84
85
86
87
88

89
90
91
92
93
94
95
96
/**
Apply an irreversible multi-component transform to an image
@param c0 Samples for red component
@param c1 Samples for green component
@param c2 Samples blue component
@param n Number of samples for each component
*/
void opj_mct_encode_real(OPJ_INT32* OPJ_RESTRICT c0, OPJ_INT32* OPJ_RESTRICT c1,

                         OPJ_INT32* OPJ_RESTRICT c2, OPJ_SIZE_T n);
/**
Apply an irreversible multi-component inverse transform to an image
@param c0 Samples for luminance component
@param c1 Samples for red chrominance component
@param c2 Samples for blue chrominance component
@param n Number of samples for each component
*/







|
>
|







81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
Apply an irreversible multi-component transform to an image
@param c0 Samples for red component
@param c1 Samples for green component
@param c2 Samples blue component
@param n Number of samples for each component
*/
void opj_mct_encode_real(OPJ_FLOAT32* OPJ_RESTRICT c0,
                         OPJ_FLOAT32* OPJ_RESTRICT c1,
                         OPJ_FLOAT32* OPJ_RESTRICT c2, OPJ_SIZE_T n);
/**
Apply an irreversible multi-component inverse transform to an image
@param c0 Samples for luminance component
@param c1 Samples for red chrominance component
@param c2 Samples for blue chrominance component
@param n Number of samples for each component
*/
Changes to jni/openjpeg/src/lib/openjp2/mqc.c.
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
/** @defgroup MQC MQC - Implementation of an MQ-Coder */
/*@{*/

/** @name Local static functions */
/*@{*/

/**
Output a byte, doing bit-stuffing if necessary.
After a 0xff byte, the next byte must be smaller than 0x90.
@param mqc MQC handle
*/
static void opj_mqc_byteout(opj_mqc_t *mqc);
/**
Renormalize mqc->a and mqc->c while encoding, so that mqc->a stays between 0x8000 and 0x10000
@param mqc MQC handle
*/
static void opj_mqc_renorme(opj_mqc_t *mqc);
/**
Encode the most probable symbol
@param mqc MQC handle
*/
static void opj_mqc_codemps(opj_mqc_t *mqc);
/**
Encode the most least symbol
@param mqc MQC handle
*/
static void opj_mqc_codelps(opj_mqc_t *mqc);
/**
Fill mqc->c with 1's for flushing
@param mqc MQC handle
*/
static void opj_mqc_setbits(opj_mqc_t *mqc);
/*@}*/

/*@}*/







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







43
44
45
46
47
48
49





















50
51
52
53
54
55
56
/** @defgroup MQC MQC - Implementation of an MQ-Coder */
/*@{*/

/** @name Local static functions */
/*@{*/

/**





















Fill mqc->c with 1's for flushing
@param mqc MQC handle
*/
static void opj_mqc_setbits(opj_mqc_t *mqc);
/*@}*/

/*@}*/
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

/*
==========================================================
   local functions
==========================================================
*/

static void opj_mqc_byteout(opj_mqc_t *mqc)
{
    /* bp is initialized to start - 1 in opj_mqc_init_enc() */
    /* but this is safe, see opj_tcd_code_block_enc_allocate_data() */
    assert(mqc->bp >= mqc->start - 1);
    if (*mqc->bp == 0xff) {
        mqc->bp++;
        *mqc->bp = (OPJ_BYTE)(mqc->c >> 20);
        mqc->c &= 0xfffff;
        mqc->ct = 7;
    } else {
        if ((mqc->c & 0x8000000) == 0) {
            mqc->bp++;
            *mqc->bp = (OPJ_BYTE)(mqc->c >> 19);
            mqc->c &= 0x7ffff;
            mqc->ct = 8;
        } else {
            (*mqc->bp)++;
            if (*mqc->bp == 0xff) {
                mqc->c &= 0x7ffffff;
                mqc->bp++;
                *mqc->bp = (OPJ_BYTE)(mqc->c >> 20);
                mqc->c &= 0xfffff;
                mqc->ct = 7;
            } else {
                mqc->bp++;
                *mqc->bp = (OPJ_BYTE)(mqc->c >> 19);
                mqc->c &= 0x7ffff;
                mqc->ct = 8;
            }
        }
    }
}

static void opj_mqc_renorme(opj_mqc_t *mqc)
{
    do {
        mqc->a <<= 1;
        mqc->c <<= 1;
        mqc->ct--;
        if (mqc->ct == 0) {
            opj_mqc_byteout(mqc);
        }
    } while ((mqc->a & 0x8000) == 0);
}

static void opj_mqc_codemps(opj_mqc_t *mqc)
{
    mqc->a -= (*mqc->curctx)->qeval;
    if ((mqc->a & 0x8000) == 0) {
        if (mqc->a < (*mqc->curctx)->qeval) {
            mqc->a = (*mqc->curctx)->qeval;
        } else {
            mqc->c += (*mqc->curctx)->qeval;
        }
        *mqc->curctx = (*mqc->curctx)->nmps;
        opj_mqc_renorme(mqc);
    } else {
        mqc->c += (*mqc->curctx)->qeval;
    }
}

static void opj_mqc_codelps(opj_mqc_t *mqc)
{
    mqc->a -= (*mqc->curctx)->qeval;
    if (mqc->a < (*mqc->curctx)->qeval) {
        mqc->c += (*mqc->curctx)->qeval;
    } else {
        mqc->a = (*mqc->curctx)->qeval;
    }
    *mqc->curctx = (*mqc->curctx)->nlps;
    opj_mqc_renorme(mqc);
}

static void opj_mqc_setbits(opj_mqc_t *mqc)
{
    OPJ_UINT32 tempc = mqc->c + mqc->a;
    mqc->c |= 0xffff;
    if (mqc->c >= tempc) {
        mqc->c -= 0x8000;
    }







<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<







157
158
159
160
161
162
163










































































164
165
166
167
168
169
170

/*
==========================================================
   local functions
==========================================================
*/











































































static void opj_mqc_setbits(opj_mqc_t *mqc)
{
    OPJ_UINT32 tempc = mqc->c + mqc->a;
    mqc->c |= 0xffff;
    if (mqc->c >= tempc) {
        mqc->c -= 0x8000;
    }
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
    /* and our initial fake byte is set at 0 */
    assert(*(mqc->bp) != 0xff);

    mqc->start = bp;
    mqc->end_of_byte_stream_counter = 0;
}

void opj_mqc_encode(opj_mqc_t *mqc, OPJ_UINT32 d)
{
    if ((*mqc->curctx)->mps == d) {
        opj_mqc_codemps(mqc);
    } else {
        opj_mqc_codelps(mqc);
    }
}

void opj_mqc_flush(opj_mqc_t *mqc)
{
    /* C.2.9 Termination of coding (FLUSH) */
    /* Figure C.11 – FLUSH procedure */
    opj_mqc_setbits(mqc);
    mqc->c <<= mqc->ct;
    opj_mqc_byteout(mqc);
    mqc->c <<= mqc->ct;
    opj_mqc_byteout(mqc);

    /* It is forbidden that a coding pass ends with 0xff */
    if (*mqc->bp != 0xff) {
        /* Advance pointer so that opj_mqc_numbytes() returns a valid value */
        mqc->bp++;
    }
}

#define BYPASS_CT_INIT  0xDEADBEEF

void opj_mqc_bypass_init_enc(opj_mqc_t *mqc)
{
    /* This function is normally called after at least one opj_mqc_flush() */
    /* which will have advance mqc->bp by at least 2 bytes beyond its */
    /* initial position */
    assert(mqc->bp >= mqc->start);
    mqc->c = 0;







<
<
<
<
<
<
<
<


















<
<







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
    /* and our initial fake byte is set at 0 */
    assert(*(mqc->bp) != 0xff);

    mqc->start = bp;
    mqc->end_of_byte_stream_counter = 0;
}










void opj_mqc_flush(opj_mqc_t *mqc)
{
    /* C.2.9 Termination of coding (FLUSH) */
    /* Figure C.11 – FLUSH procedure */
    opj_mqc_setbits(mqc);
    mqc->c <<= mqc->ct;
    opj_mqc_byteout(mqc);
    mqc->c <<= mqc->ct;
    opj_mqc_byteout(mqc);

    /* It is forbidden that a coding pass ends with 0xff */
    if (*mqc->bp != 0xff) {
        /* Advance pointer so that opj_mqc_numbytes() returns a valid value */
        mqc->bp++;
    }
}



void opj_mqc_bypass_init_enc(opj_mqc_t *mqc)
{
    /* This function is normally called after at least one opj_mqc_flush() */
    /* which will have advance mqc->bp by at least 2 bytes beyond its */
    /* initial position */
    assert(mqc->bp >= mqc->start);
    mqc->c = 0;
470
471
472
473
474
475
476





































477
478
479
480
481
482
483
        k -= (OPJ_INT32)mqc->ct;
    }

    if (*mqc->bp != 0xff) {
        opj_mqc_byteout(mqc);
    }
}






































void opj_mqc_segmark_enc(opj_mqc_t *mqc)
{
    OPJ_UINT32 i;
    opj_mqc_setcurctx(mqc, 18);

    for (i = 1; i < 5; i++) {







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
        k -= (OPJ_INT32)mqc->ct;
    }

    if (*mqc->bp != 0xff) {
        opj_mqc_byteout(mqc);
    }
}

static INLINE void opj_mqc_renorme(opj_mqc_t *mqc)
{
    opj_mqc_renorme_macro(mqc, mqc->a, mqc->c, mqc->ct);
}

/**
Encode the most probable symbol
@param mqc MQC handle
*/
static INLINE void opj_mqc_codemps(opj_mqc_t *mqc)
{
    opj_mqc_codemps_macro(mqc, mqc->curctx, mqc->a, mqc->c, mqc->ct);
}

/**
Encode the most least symbol
@param mqc MQC handle
*/
static INLINE void opj_mqc_codelps(opj_mqc_t *mqc)
{
    opj_mqc_codelps_macro(mqc, mqc->curctx, mqc->a, mqc->c, mqc->ct);
}

/**
Encode a symbol using the MQ-coder
@param mqc MQC handle
@param d The symbol to be encoded (0 or 1)
*/
static INLINE void opj_mqc_encode(opj_mqc_t *mqc, OPJ_UINT32 d)
{
    if ((*mqc->curctx)->mps == d) {
        opj_mqc_codemps(mqc);
    } else {
        opj_mqc_codelps(mqc);
    }
}

void opj_mqc_segmark_enc(opj_mqc_t *mqc)
{
    OPJ_UINT32 i;
    opj_mqc_setcurctx(mqc, 18);

    for (i = 1; i < 5; i++) {
553
554
555
556
557
558
559

560
































void opj_mqc_setstate(opj_mqc_t *mqc, OPJ_UINT32 ctxno, OPJ_UINT32 msb,
                      OPJ_INT32 prob)
{
    mqc->ctxs[ctxno] = &mqc_states[msb + (OPJ_UINT32)(prob << 1)];
}









































>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
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

void opj_mqc_setstate(opj_mqc_t *mqc, OPJ_UINT32 ctxno, OPJ_UINT32 msb,
                      OPJ_INT32 prob)
{
    mqc->ctxs[ctxno] = &mqc_states[msb + (OPJ_UINT32)(prob << 1)];
}

void opj_mqc_byteout(opj_mqc_t *mqc)
{
    /* bp is initialized to start - 1 in opj_mqc_init_enc() */
    /* but this is safe, see opj_tcd_code_block_enc_allocate_data() */
    assert(mqc->bp >= mqc->start - 1);
    if (*mqc->bp == 0xff) {
        mqc->bp++;
        *mqc->bp = (OPJ_BYTE)(mqc->c >> 20);
        mqc->c &= 0xfffff;
        mqc->ct = 7;
    } else {
        if ((mqc->c & 0x8000000) == 0) {
            mqc->bp++;
            *mqc->bp = (OPJ_BYTE)(mqc->c >> 19);
            mqc->c &= 0x7ffff;
            mqc->ct = 8;
        } else {
            (*mqc->bp)++;
            if (*mqc->bp == 0xff) {
                mqc->c &= 0x7ffffff;
                mqc->bp++;
                *mqc->bp = (OPJ_BYTE)(mqc->c >> 20);
                mqc->c &= 0xfffff;
                mqc->ct = 7;
            } else {
                mqc->bp++;
                *mqc->bp = (OPJ_BYTE)(mqc->c >> 19);
                mqc->c &= 0x7ffff;
                mqc->ct = 8;
            }
        }
    }
}
Changes to jni/openjpeg/src/lib/openjp2/mqc.h.
92
93
94
95
96
97
98


99
100
101
102
103
104
105
    const opj_mqc_state_t **curctx;
    /* lut_ctxno_zc shifted by (1 << 9) * bandno */
    const OPJ_BYTE* lut_ctxno_zc_orient;
    /** Original value of the 2 bytes at end[0] and end[1] */
    OPJ_BYTE backup[OPJ_COMMON_CBLK_DATA_EXTRA];
} opj_mqc_t;



#include "mqc_inl.h"

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**







>
>







92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
    const opj_mqc_state_t **curctx;
    /* lut_ctxno_zc shifted by (1 << 9) * bandno */
    const OPJ_BYTE* lut_ctxno_zc_orient;
    /** Original value of the 2 bytes at end[0] and end[1] */
    OPJ_BYTE backup[OPJ_COMMON_CBLK_DATA_EXTRA];
} opj_mqc_t;

#define BYPASS_CT_INIT  0xDEADBEEF

#include "mqc_inl.h"

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
void opj_mqc_init_enc(opj_mqc_t *mqc, OPJ_BYTE *bp);
/**
Set the current context used for coding/decoding
@param mqc MQC handle
@param ctxno Number that identifies the context
*/
#define opj_mqc_setcurctx(mqc, ctxno)   (mqc)->curctx = &(mqc)->ctxs[(OPJ_UINT32)(ctxno)]
/**
Encode a symbol using the MQ-coder
@param mqc MQC handle
@param d The symbol to be encoded (0 or 1)
*/
void opj_mqc_encode(opj_mqc_t *mqc, OPJ_UINT32 d);
/**
Flush the encoder, so that all remaining data is written
@param mqc MQC handle
*/
void opj_mqc_flush(opj_mqc_t *mqc);
/**
BYPASS mode switch, initialization operation.







|
<
<
<
<
<







133
134
135
136
137
138
139
140





141
142
143
144
145
146
147
void opj_mqc_init_enc(opj_mqc_t *mqc, OPJ_BYTE *bp);
/**
Set the current context used for coding/decoding
@param mqc MQC handle
@param ctxno Number that identifies the context
*/
#define opj_mqc_setcurctx(mqc, ctxno)   (mqc)->curctx = &(mqc)->ctxs[(OPJ_UINT32)(ctxno)]






/**
Flush the encoder, so that all remaining data is written
@param mqc MQC handle
*/
void opj_mqc_flush(opj_mqc_t *mqc);
/**
BYPASS mode switch, initialization operation.
Changes to jni/openjpeg/src/lib/openjp2/mqc_inl.h.
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
            opj_mqc_renormd_macro(mqc, a, c, ct); \
        } else { \
            d = (*curctx)->mps; \
        } \
    } \
}

#define DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct) \
        register const opj_mqc_state_t **curctx = mqc->curctx; \
        register OPJ_UINT32 c = mqc->c; \
        register OPJ_UINT32 a = mqc->a; \
        register OPJ_UINT32 ct = mqc->ct

#define UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct) \
        mqc->curctx = curctx; \
        mqc->c = c; \
        mqc->a = a; \
        mqc->ct = ct;

/**
Input a byte







|





|







152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
            opj_mqc_renormd_macro(mqc, a, c, ct); \
        } else { \
            d = (*curctx)->mps; \
        } \
    } \
}

#define DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct) \
        register const opj_mqc_state_t **curctx = mqc->curctx; \
        register OPJ_UINT32 c = mqc->c; \
        register OPJ_UINT32 a = mqc->a; \
        register OPJ_UINT32 ct = mqc->ct

#define UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct) \
        mqc->curctx = curctx; \
        mqc->c = c; \
        mqc->a = a; \
        mqc->ct = ct;

/**
Input a byte
188
189
190
191
192
193
194
195






















































































196
Decode a symbol
@param d OPJ_UINT32 value where to store the decoded symbol
@param mqc MQC handle
@return Returns the decoded symbol (0 or 1) in d
*/
#define opj_mqc_decode(d, mqc) \
    opj_mqc_decode_macro(d, mqc, mqc->curctx, mqc->a, mqc->c, mqc->ct)























































































#endif /* OPJ_MQC_INL_H */








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

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
Decode a symbol
@param d OPJ_UINT32 value where to store the decoded symbol
@param mqc MQC handle
@return Returns the decoded symbol (0 or 1) in d
*/
#define opj_mqc_decode(d, mqc) \
    opj_mqc_decode_macro(d, mqc, mqc->curctx, mqc->a, mqc->c, mqc->ct)

/**
Output a byte, doing bit-stuffing if necessary.
After a 0xff byte, the next byte must be smaller than 0x90.
@param mqc MQC handle
*/
void opj_mqc_byteout(opj_mqc_t *mqc);

/**
Renormalize mqc->a and mqc->c while encoding, so that mqc->a stays between 0x8000 and 0x10000
@param mqc MQC handle
@param a_ value of mqc->a
@param c_ value of mqc->c_
@param ct_ value of mqc->ct_
*/
#define opj_mqc_renorme_macro(mqc, a_, c_, ct_) \
{ \
    do { \
        a_ <<= 1; \
        c_ <<= 1; \
        ct_--; \
        if (ct_ == 0) { \
            mqc->c = c_; \
            opj_mqc_byteout(mqc); \
            c_ = mqc->c; \
            ct_ = mqc->ct; \
        } \
    } while( (a_ & 0x8000) == 0); \
}

#define opj_mqc_codemps_macro(mqc, curctx, a, c, ct) \
{ \
    a -= (*curctx)->qeval; \
    if ((a & 0x8000) == 0) { \
        if (a < (*curctx)->qeval) { \
            a = (*curctx)->qeval; \
        } else { \
            c += (*curctx)->qeval; \
        } \
        *curctx = (*curctx)->nmps; \
        opj_mqc_renorme_macro(mqc, a, c, ct); \
    } else { \
        c += (*curctx)->qeval; \
    } \
}

#define opj_mqc_codelps_macro(mqc, curctx, a, c, ct) \
{ \
    a -= (*curctx)->qeval; \
    if (a < (*curctx)->qeval) { \
        c += (*curctx)->qeval; \
    } else { \
        a = (*curctx)->qeval; \
    } \
    *curctx = (*curctx)->nlps; \
    opj_mqc_renorme_macro(mqc, a, c, ct); \
}

#define opj_mqc_encode_macro(mqc, curctx, a, c, ct, d) \
{ \
    if ((*curctx)->mps == (d)) { \
        opj_mqc_codemps_macro(mqc, curctx, a, c, ct); \
    } else { \
        opj_mqc_codelps_macro(mqc, curctx, a, c, ct); \
    } \
}


#define opj_mqc_bypass_enc_macro(mqc, c, ct, d) \
{\
    if (ct == BYPASS_CT_INIT) {\
        ct = 8;\
    }\
    ct--;\
    c = c + ((d) << ct);\
    if (ct == 0) {\
        *mqc->bp = (OPJ_BYTE)c;\
        ct = 8;\
        /* If the previous byte was 0xff, make sure that the next msb is 0 */ \
        if (*mqc->bp == 0xff) {\
            ct = 7;\
        }\
        mqc->bp++;\
        c = 0;\
    }\
}

#endif /* OPJ_MQC_INL_H */
Changes to jni/openjpeg/src/lib/openjp2/openjpeg.c.
648
649
650
651
652
653
654








655
656
657
658
659
660
661
                    void *)) opj_j2k_destroy;

        l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL(*)(void *,
                opj_cparameters_t *,
                struct opj_image *,
                struct opj_event_mgr *)) opj_j2k_setup_encoder;









        l_codec->m_codec = opj_j2k_create_compress();
        if (! l_codec->m_codec) {
            opj_free(l_codec);
            return 00;
        }

        break;







>
>
>
>
>
>
>
>







648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
                    void *)) opj_j2k_destroy;

        l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL(*)(void *,
                opj_cparameters_t *,
                struct opj_image *,
                struct opj_event_mgr *)) opj_j2k_setup_encoder;

        l_codec->m_codec_data.m_compression.opj_encoder_set_extra_options = (OPJ_BOOL(
                    *)(void *,
                       const char* const*,
                       struct opj_event_mgr *)) opj_j2k_encoder_set_extra_options;

        l_codec->opj_set_threads =
            (OPJ_BOOL(*)(void * p_codec, OPJ_UINT32 num_threads)) opj_j2k_set_threads;

        l_codec->m_codec = opj_j2k_create_compress();
        if (! l_codec->m_codec) {
            opj_free(l_codec);
            return 00;
        }

        break;
686
687
688
689
690
691
692








693
694
695
696
697
698
699
                    void *)) opj_jp2_destroy;

        l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL(*)(void *,
                opj_cparameters_t *,
                struct opj_image *,
                struct opj_event_mgr *)) opj_jp2_setup_encoder;









        l_codec->m_codec = opj_jp2_create(OPJ_FALSE);
        if (! l_codec->m_codec) {
            opj_free(l_codec);
            return 00;
        }

        break;







>
>
>
>
>
>
>
>







694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
                    void *)) opj_jp2_destroy;

        l_codec->m_codec_data.m_compression.opj_setup_encoder = (OPJ_BOOL(*)(void *,
                opj_cparameters_t *,
                struct opj_image *,
                struct opj_event_mgr *)) opj_jp2_setup_encoder;

        l_codec->m_codec_data.m_compression.opj_encoder_set_extra_options = (OPJ_BOOL(
                    *)(void *,
                       const char* const*,
                       struct opj_event_mgr *)) opj_jp2_encoder_set_extra_options;

        l_codec->opj_set_threads =
            (OPJ_BOOL(*)(void * p_codec, OPJ_UINT32 num_threads)) opj_jp2_set_threads;

        l_codec->m_codec = opj_jp2_create(OPJ_FALSE);
        if (! l_codec->m_codec) {
            opj_free(l_codec);
            return 00;
        }

        break;
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
{
    if (parameters) {
        memset(parameters, 0, sizeof(opj_cparameters_t));
        /* default coding parameters */
        parameters->cp_cinema = OPJ_OFF; /* DEPRECATED */
        parameters->rsiz = OPJ_PROFILE_NONE;
        parameters->max_comp_size = 0;
        parameters->numresolution = 6;
        parameters->cp_rsiz = OPJ_STD_RSIZ; /* DEPRECATED */
        parameters->cblockw_init = 64;
        parameters->cblockh_init = 64;
        parameters->prog_order = OPJ_LRCP;
        parameters->roi_compno = -1;        /* no ROI */
        parameters->subsampling_dx = 1;
        parameters->subsampling_dy = 1;
        parameters->tp_on = 0;
        parameters->decod_format = -1;
        parameters->cod_format = -1;
        parameters->tcp_rates[0] = 0;







|

|
|
|







730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
{
    if (parameters) {
        memset(parameters, 0, sizeof(opj_cparameters_t));
        /* default coding parameters */
        parameters->cp_cinema = OPJ_OFF; /* DEPRECATED */
        parameters->rsiz = OPJ_PROFILE_NONE;
        parameters->max_comp_size = 0;
        parameters->numresolution = OPJ_COMP_PARAM_DEFAULT_NUMRESOLUTION;
        parameters->cp_rsiz = OPJ_STD_RSIZ; /* DEPRECATED */
        parameters->cblockw_init = OPJ_COMP_PARAM_DEFAULT_CBLOCKW;
        parameters->cblockh_init = OPJ_COMP_PARAM_DEFAULT_CBLOCKH;
        parameters->prog_order = OPJ_COMP_PARAM_DEFAULT_PROG_ORDER;
        parameters->roi_compno = -1;        /* no ROI */
        parameters->subsampling_dx = 1;
        parameters->subsampling_dy = 1;
        parameters->tp_on = 0;
        parameters->decod_format = -1;
        parameters->cod_format = -1;
        parameters->tcp_rates[0] = 0;
783
784
785
786
787
788
789





















790
791
792
793
794
795
796
                    p_image,
                    &(l_codec->m_event_mgr));
        }
    }

    return OPJ_FALSE;
}






















OPJ_BOOL OPJ_CALLCONV opj_start_compress(opj_codec_t *p_codec,
        opj_image_t * p_image,
        opj_stream_t *p_stream)
{
    if (p_codec && p_stream) {
        opj_codec_private_t * l_codec = (opj_codec_private_t *) p_codec;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
                    p_image,
                    &(l_codec->m_event_mgr));
        }
    }

    return OPJ_FALSE;
}

/* ----------------------------------------------------------------------- */

OPJ_BOOL OPJ_CALLCONV opj_encoder_set_extra_options(opj_codec_t *p_codec,
        const char* const* options)
{
    if (p_codec) {
        opj_codec_private_t * l_codec = (opj_codec_private_t *) p_codec;

        if (! l_codec->is_decompressor) {
            return l_codec->m_codec_data.m_compression.opj_encoder_set_extra_options(
                       l_codec->m_codec,
                       options,
                       &(l_codec->m_event_mgr));
        }
    }

    return OPJ_FALSE;
}

/* ----------------------------------------------------------------------- */

OPJ_BOOL OPJ_CALLCONV opj_start_compress(opj_codec_t *p_codec,
        opj_image_t * p_image,
        opj_stream_t *p_stream)
{
    if (p_codec && p_stream) {
        opj_codec_private_t * l_codec = (opj_codec_private_t *) p_codec;
Changes to jni/openjpeg/src/lib/openjp2/openjpeg.h.
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define OPJ_DEPRECATED(func) func
#endif

#if defined(OPJ_STATIC) || !defined(_WIN32)
/* http://gcc.gnu.org/wiki/Visibility */
#   if __GNUC__ >= 4
#       if defined(OPJ_STATIC) /* static library uses "hidden" */
#           define OPJ_API    __attribute__ ((visibility ("hidden")))
#       else
#           define OPJ_API    __attribute__ ((visibility ("default")))
#       endif
#       define OPJ_LOCAL  __attribute__ ((visibility ("hidden")))
#   else







|







74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#else
#pragma message("WARNING: You need to implement DEPRECATED for this compiler")
#define OPJ_DEPRECATED(func) func
#endif

#if defined(OPJ_STATIC) || !defined(_WIN32)
/* http://gcc.gnu.org/wiki/Visibility */
#   if !defined(_WIN32) && __GNUC__ >= 4
#       if defined(OPJ_STATIC) /* static library uses "hidden" */
#           define OPJ_API    __attribute__ ((visibility ("hidden")))
#       else
#           define OPJ_API    __attribute__ ((visibility ("default")))
#       endif
#       define OPJ_LOCAL  __attribute__ ((visibility ("hidden")))
#   else
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
#define OPJ_PROFILE_CINEMA_S2K  0x0005 /** Scalable 2K cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_CINEMA_S4K  0x0006 /** Scalable 4K cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_CINEMA_LTS  0x0007 /** Long term storage cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_BC_SINGLE   0x0100 /** Single Tile Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_BC_MULTI    0x0200 /** Multi Tile Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_BC_MULTI_R  0x0300 /** Multi Tile Reversible Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_IMF_2K      0x0400 /** 2K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_4K      0x0401 /** 4K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_8K      0x0402 /** 8K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_2K_R    0x0403 /** 2K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_4K_R    0x0800 /** 4K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_8K_R    0x0801  /** 8K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */

/**
 * JPEG 2000 Part-2 extensions
 * */
#define OPJ_EXTENSION_NONE      0x0000 /** No Part-2 extension */
#define OPJ_EXTENSION_MCT       0x0100  /** Custom MCT support */

/**
 * JPEG 2000 profile macros
 * */
#define OPJ_IS_CINEMA(v)     (((v) >= OPJ_PROFILE_CINEMA_2K)&&((v) <= OPJ_PROFILE_CINEMA_S4K))
#define OPJ_IS_STORAGE(v)    ((v) == OPJ_PROFILE_CINEMA_LTS)
#define OPJ_IS_BROADCAST(v)  (((v) >= OPJ_PROFILE_BC_SINGLE)&&((v) <= ((OPJ_PROFILE_BC_MULTI_R) | (0x000b))))
#define OPJ_IS_IMF(v)        (((v) >= OPJ_PROFILE_IMF_2K)&&((v) <= ((OPJ_PROFILE_IMF_8K_R) | (0x009b))))
#define OPJ_IS_PART2(v)      ((v) & OPJ_PROFILE_PART2)































/**
 * JPEG 2000 codestream and component size limits in cinema profiles
 * */
#define OPJ_CINEMA_24_CS     1302083    /** Maximum codestream length for 24fps */
#define OPJ_CINEMA_48_CS     651041     /** Maximum codestream length for 48fps */
#define OPJ_CINEMA_24_COMP   1041666    /** Maximum size per color component for 2K & 4K @ 24fps */







|
|
|

|















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
#define OPJ_PROFILE_CINEMA_S2K  0x0005 /** Scalable 2K cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_CINEMA_S4K  0x0006 /** Scalable 4K cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_CINEMA_LTS  0x0007 /** Long term storage cinema profile defined in 15444-1 AMD2 */
#define OPJ_PROFILE_BC_SINGLE   0x0100 /** Single Tile Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_BC_MULTI    0x0200 /** Multi Tile Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_BC_MULTI_R  0x0300 /** Multi Tile Reversible Broadcast profile defined in 15444-1 AMD3 */
#define OPJ_PROFILE_IMF_2K      0x0400 /** 2K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_4K      0x0500 /** 4K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_8K      0x0600 /** 8K Single Tile Lossy IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_2K_R    0x0700 /** 2K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_4K_R    0x0800 /** 4K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */
#define OPJ_PROFILE_IMF_8K_R    0x0900 /** 8K Single/Multi Tile Reversible IMF profile defined in 15444-1 AMD 8 */

/**
 * JPEG 2000 Part-2 extensions
 * */
#define OPJ_EXTENSION_NONE      0x0000 /** No Part-2 extension */
#define OPJ_EXTENSION_MCT       0x0100  /** Custom MCT support */

/**
 * JPEG 2000 profile macros
 * */
#define OPJ_IS_CINEMA(v)     (((v) >= OPJ_PROFILE_CINEMA_2K)&&((v) <= OPJ_PROFILE_CINEMA_S4K))
#define OPJ_IS_STORAGE(v)    ((v) == OPJ_PROFILE_CINEMA_LTS)
#define OPJ_IS_BROADCAST(v)  (((v) >= OPJ_PROFILE_BC_SINGLE)&&((v) <= ((OPJ_PROFILE_BC_MULTI_R) | (0x000b))))
#define OPJ_IS_IMF(v)        (((v) >= OPJ_PROFILE_IMF_2K)&&((v) <= ((OPJ_PROFILE_IMF_8K_R) | (0x009b))))
#define OPJ_IS_PART2(v)      ((v) & OPJ_PROFILE_PART2)

#define OPJ_GET_IMF_PROFILE(v)   ((v) & 0xff00)      /** Extract IMF profile without mainlevel/sublevel */
#define OPJ_GET_IMF_MAINLEVEL(v) ((v) & 0xf)         /** Extract IMF main level */
#define OPJ_GET_IMF_SUBLEVEL(v)  (((v) >> 4) & 0xf)  /** Extract IMF sub level */

#define OPJ_IMF_MAINLEVEL_MAX    11   /** Maximum main level */

/** Max. Components Sampling Rate (MSamples/sec) per IMF main level */
#define OPJ_IMF_MAINLEVEL_1_MSAMPLESEC   65      /** MSamples/sec for IMF main level 1 */
#define OPJ_IMF_MAINLEVEL_2_MSAMPLESEC   130     /** MSamples/sec for IMF main level 2 */
#define OPJ_IMF_MAINLEVEL_3_MSAMPLESEC   195     /** MSamples/sec for IMF main level 3 */
#define OPJ_IMF_MAINLEVEL_4_MSAMPLESEC   260     /** MSamples/sec for IMF main level 4 */
#define OPJ_IMF_MAINLEVEL_5_MSAMPLESEC   520     /** MSamples/sec for IMF main level 5 */
#define OPJ_IMF_MAINLEVEL_6_MSAMPLESEC   1200    /** MSamples/sec for IMF main level 6 */
#define OPJ_IMF_MAINLEVEL_7_MSAMPLESEC   2400    /** MSamples/sec for IMF main level 7 */
#define OPJ_IMF_MAINLEVEL_8_MSAMPLESEC   4800    /** MSamples/sec for IMF main level 8 */
#define OPJ_IMF_MAINLEVEL_9_MSAMPLESEC   9600    /** MSamples/sec for IMF main level 9 */
#define OPJ_IMF_MAINLEVEL_10_MSAMPLESEC  19200   /** MSamples/sec for IMF main level 10 */
#define OPJ_IMF_MAINLEVEL_11_MSAMPLESEC  38400   /** MSamples/sec for IMF main level 11 */

/** Max. compressed Bit Rate (Mbits/s) per IMF sub level */
#define OPJ_IMF_SUBLEVEL_1_MBITSSEC      200     /** Mbits/s for IMF sub level 1 */
#define OPJ_IMF_SUBLEVEL_2_MBITSSEC      400     /** Mbits/s for IMF sub level 2 */
#define OPJ_IMF_SUBLEVEL_3_MBITSSEC      800     /** Mbits/s for IMF sub level 3 */
#define OPJ_IMF_SUBLEVEL_4_MBITSSEC     1600     /** Mbits/s for IMF sub level 4 */
#define OPJ_IMF_SUBLEVEL_5_MBITSSEC     3200     /** Mbits/s for IMF sub level 5 */
#define OPJ_IMF_SUBLEVEL_6_MBITSSEC     6400     /** Mbits/s for IMF sub level 6 */
#define OPJ_IMF_SUBLEVEL_7_MBITSSEC    12800     /** Mbits/s for IMF sub level 7 */
#define OPJ_IMF_SUBLEVEL_8_MBITSSEC    25600     /** Mbits/s for IMF sub level 8 */
#define OPJ_IMF_SUBLEVEL_9_MBITSSEC    51200     /** Mbits/s for IMF sub level 9 */

/**
 * JPEG 2000 codestream and component size limits in cinema profiles
 * */
#define OPJ_CINEMA_24_CS     1302083    /** Maximum codestream length for 24fps */
#define OPJ_CINEMA_48_CS     651041     /** Maximum codestream length for 48fps */
#define OPJ_CINEMA_24_COMP   1041666    /** Maximum size per color component for 2K & 4K @ 24fps */
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

/*
==========================================================
   codec typedef definitions
==========================================================
*/





/**
 * Progression order changes
 *
 */
typedef struct opj_poc {
    /** Resolution num start, Component num start, given by POC */
    OPJ_UINT32 resno0, compno0;
    /** Layer num end,Resolution num end, Component num end, given by POC */
    OPJ_UINT32 layno1, resno1, compno1;
    /** Layer num start,Precinct num start, Precinct num end */
    OPJ_UINT32 layno0, precno0, precno1;
    /** Progression order enum*/
    OPJ_PROG_ORDER prg1, prg;
    /** Progression order string*/
    OPJ_CHAR progorder[5];
    /** Tile number */
    OPJ_UINT32 tile;
    /** Start and end values for Tile width and height*/
    OPJ_INT32 tx0, tx1, ty0, ty1;
    /** Start value, initialised in pi_initialise_encode*/
    OPJ_UINT32 layS, resS, compS, prcS;
    /** End value, initialised in pi_initialise_encode */
    OPJ_UINT32 layE, resE, compE, prcE;
    /** Start and end values of Tile width and height, initialised in pi_initialise_encode*/
    OPJ_UINT32 txS, txE, tyS, tyE, dx, dy;
    /** Temporary values for Tile parts, initialised in pi_create_encode */







>
>
>
>















|


|







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

/*
==========================================================
   codec typedef definitions
==========================================================
*/

#ifndef OPJ_UINT32_SEMANTICALLY_BUT_INT32
#define OPJ_UINT32_SEMANTICALLY_BUT_INT32 OPJ_INT32
#endif

/**
 * Progression order changes
 *
 */
typedef struct opj_poc {
    /** Resolution num start, Component num start, given by POC */
    OPJ_UINT32 resno0, compno0;
    /** Layer num end,Resolution num end, Component num end, given by POC */
    OPJ_UINT32 layno1, resno1, compno1;
    /** Layer num start,Precinct num start, Precinct num end */
    OPJ_UINT32 layno0, precno0, precno1;
    /** Progression order enum*/
    OPJ_PROG_ORDER prg1, prg;
    /** Progression order string*/
    OPJ_CHAR progorder[5];
    /** Tile number (starting at 1) */
    OPJ_UINT32 tile;
    /** Start and end values for Tile width and height*/
    OPJ_UINT32_SEMANTICALLY_BUT_INT32 tx0, tx1, ty0, ty1;
    /** Start value, initialised in pi_initialise_encode*/
    OPJ_UINT32 layS, resS, compS, prcS;
    /** End value, initialised in pi_initialise_encode */
    OPJ_UINT32 layE, resE, compE, prcE;
    /** Start and end values of Tile width and height, initialised in pi_initialise_encode*/
    OPJ_UINT32 txS, txE, tyS, tyE, dx, dy;
    /** Temporary values for Tile parts, initialised in pi_create_encode */
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
 *
 * By default, only the main thread is used. If this function is not used,
 * but the OPJ_NUM_THREADS environment variable is set, its value will be
 * used to initialize the number of threads. The value can be either an integer
 * number, or "ALL_CPUS". If OPJ_NUM_THREADS is set and this function is called,
 * this function will override the behaviour of the environment variable.
 *
 * Currently this function must be called after opj_setup_decoder() and
 * before opj_read_header().
 *
 * Note: currently only has effect on the decompressor.
 *
 * @param p_codec       decompressor handler
 * @param num_threads   number of threads.
 *
 * @return OPJ_TRUE     if the decoder is correctly set
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_codec_set_threads(opj_codec_t *p_codec,
        int num_threads);

/**
 * Decodes an image header.
 *







|
|
<
|

|


|







1344
1345
1346
1347
1348
1349
1350
1351
1352

1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
 *
 * By default, only the main thread is used. If this function is not used,
 * but the OPJ_NUM_THREADS environment variable is set, its value will be
 * used to initialize the number of threads. The value can be either an integer
 * number, or "ALL_CPUS". If OPJ_NUM_THREADS is set and this function is called,
 * this function will override the behaviour of the environment variable.
 *
 * This function must be called after opj_setup_decoder() and
 * before opj_read_header() for the decoding side, or after opj_setup_encoder()

 * and before opj_start_compress() for the encoding side.
 *
 * @param p_codec       decompressor or compressor handler
 * @param num_threads   number of threads.
 *
 * @return OPJ_TRUE     if the function is successful.
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_codec_set_threads(opj_codec_t *p_codec,
        int num_threads);

/**
 * Decodes an image header.
 *
1542
1543
1544
1545
1546
1547
1548



























1549
1550
1551
1552
1553
1554
1555
 * @param parameters    Compression parameters
 * @param image         Input filled image
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_setup_encoder(opj_codec_t *p_codec,
        opj_cparameters_t *parameters,
        opj_image_t *image);




























/**
 * Start to compress the current image.
 * @param p_codec       Compressor handle
 * @param p_image       Input filled image
 * @param p_stream      Input stgream
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_start_compress(opj_codec_t *p_codec,







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
 * @param parameters    Compression parameters
 * @param image         Input filled image
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_setup_encoder(opj_codec_t *p_codec,
        opj_cparameters_t *parameters,
        opj_image_t *image);


/**
 * Specify extra options for the encoder.
 *
 * This may be called after opj_setup_encoder() and before opj_start_compress()
 *
 * This is the way to add new options in a fully ABI compatible way, without
 * extending the opj_cparameters_t structure.
 *
 * Currently supported options are:
 * <ul>
 * <li>PLT=YES/NO. Defaults to NO. If set to YES, PLT marker segments,
 *     indicating the length of each packet in the tile-part header, will be
 *     written. Since 2.3.2</li>
 * </ul>
 *
 * @param p_codec       Compressor handle
 * @param p_options     Compression options. This should be a NULL terminated
 *                      array of strings. Each string is of the form KEY=VALUE.
 *
 * @return OPJ_TRUE in case of success.
 * @since 2.3.2
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_encoder_set_extra_options(
    opj_codec_t *p_codec,
    const char* const* p_options);

/**
 * Start to compress the current image.
 * @param p_codec       Compressor handle
 * @param p_image       Input filled image
 * @param p_stream      Input stgream
 */
OPJ_API OPJ_BOOL OPJ_CALLCONV opj_start_compress(opj_codec_t *p_codec,
Changes to jni/openjpeg/src/lib/openjp2/opj_codec.h.
144
145
146
147
148
149
150





151
152
153
154
155
156
157

            void (* opj_destroy)(void * p_codec);

            OPJ_BOOL(* opj_setup_encoder)(void * p_codec,
                                          opj_cparameters_t * p_param,
                                          struct opj_image * p_image,
                                          struct opj_event_mgr * p_manager);





        } m_compression;
    } m_codec_data;
    /** FIXME DOC*/
    void * m_codec;
    /** Event handler */
    opj_event_mgr_t m_event_mgr;
    /** Flag to indicate if the codec is used to decode or encode*/







>
>
>
>
>







144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162

            void (* opj_destroy)(void * p_codec);

            OPJ_BOOL(* opj_setup_encoder)(void * p_codec,
                                          opj_cparameters_t * p_param,
                                          struct opj_image * p_image,
                                          struct opj_event_mgr * p_manager);

            OPJ_BOOL(* opj_encoder_set_extra_options)(void * p_codec,
                    const char* const* p_options,
                    struct opj_event_mgr * p_manager);

        } m_compression;
    } m_codec_data;
    /** FIXME DOC*/
    void * m_codec;
    /** Event handler */
    opj_event_mgr_t m_event_mgr;
    /** Flag to indicate if the codec is used to decode or encode*/
Changes to jni/openjpeg/src/lib/openjp2/opj_common.h.
34
35
36
37
38
39
40






41
/*
 ==========================================================
   Common constants shared among several modules
 ==========================================================
*/
#define OPJ_COMMON_CBLK_DATA_EXTRA        2    /**< Margin for a fake FFFF marker */







#endif /* OPJ_COMMMON_H */







>
>
>
>
>
>

34
35
36
37
38
39
40
41
42
43
44
45
46
47
/*
 ==========================================================
   Common constants shared among several modules
 ==========================================================
*/
#define OPJ_COMMON_CBLK_DATA_EXTRA        2    /**< Margin for a fake FFFF marker */


#define OPJ_COMP_PARAM_DEFAULT_CBLOCKW        64
#define OPJ_COMP_PARAM_DEFAULT_CBLOCKH        64
#define OPJ_COMP_PARAM_DEFAULT_PROG_ORDER     OPJ_LRCP
#define OPJ_COMP_PARAM_DEFAULT_NUMRESOLUTION  6

#endif /* OPJ_COMMMON_H */
Changes to jni/openjpeg/src/lib/openjp2/opj_intmath.h.
204
205
206
207
208
209
210










211
212
213
214
215
216
217
Divide an integer by a power of 2 and round downwards
@return Returns a divided by 2^b
*/
static INLINE OPJ_INT32 opj_int_floordivpow2(OPJ_INT32 a, OPJ_INT32 b)
{
    return a >> b;
}










/**
Get logarithm of an integer and round downwards
@return Returns log2(a)
*/
static INLINE OPJ_INT32 opj_int_floorlog2(OPJ_INT32 a)
{
    OPJ_INT32 l;







>
>
>
>
>
>
>
>
>
>







204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
Divide an integer by a power of 2 and round downwards
@return Returns a divided by 2^b
*/
static INLINE OPJ_INT32 opj_int_floordivpow2(OPJ_INT32 a, OPJ_INT32 b)
{
    return a >> b;
}

/**
Divide an integer by a power of 2 and round downwards
@return Returns a divided by 2^b
*/
static INLINE OPJ_UINT32 opj_uint_floordivpow2(OPJ_UINT32 a, OPJ_UINT32 b)
{
    return a >> b;
}

/**
Get logarithm of an integer and round downwards
@return Returns log2(a)
*/
static INLINE OPJ_INT32 opj_int_floorlog2(OPJ_INT32 a)
{
    OPJ_INT32 l;
Changes to jni/openjpeg/src/lib/openjp2/pi.c.
32
33
34
35
36
37
38


39
40
41
42
43
44
45
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */



#include "opj_includes.h"

/** @defgroup PI PI - Implementation of a packet iterator */
/*@{*/

/** @name Local static functions */
/*@{*/







>
>







32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */

#define OPJ_UINT32_SEMANTICALLY_BUT_INT32 OPJ_UINT32

#include "opj_includes.h"

/** @defgroup PI PI - Implementation of a packet iterator */
/*@{*/

/** @name Local static functions */
/*@{*/
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
 * @param   p_max_prec  the maximum precision for all the bands of the tile
 * @param   p_max_res   the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min        the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp,
        OPJ_UINT32 p_tileno,
        OPJ_INT32 p_tx0,
        OPJ_INT32 p_tx1,
        OPJ_INT32 p_ty0,
        OPJ_INT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min);

/**
 * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used).







|
|
|
|







89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
 * @param   p_max_prec  the maximum precision for all the bands of the tile
 * @param   p_max_res   the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min        the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp,
        OPJ_UINT32 p_tileno,
        OPJ_UINT32 p_tx0,
        OPJ_UINT32 p_tx1,
        OPJ_UINT32 p_ty0,
        OPJ_UINT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min);

/**
 * Updates the coding parameters if the encoding is not used with Progression order changes and final (and cinema parameters are used).
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
 * @param   p_max_res   the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min        the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp,
        OPJ_UINT32 p_num_comps,
        OPJ_UINT32 p_tileno,
        OPJ_INT32 p_tx0,
        OPJ_INT32 p_tx1,
        OPJ_INT32 p_ty0,
        OPJ_INT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min);
/**
 * Gets the encoding parameters needed to update the coding parameters and all the pocs.
 *







|
|
|
|







116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
 * @param   p_max_res   the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min        the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp,
        OPJ_UINT32 p_num_comps,
        OPJ_UINT32 p_tileno,
        OPJ_UINT32 p_tx0,
        OPJ_UINT32 p_tx1,
        OPJ_UINT32 p_ty0,
        OPJ_UINT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min);
/**
 * Gets the encoding parameters needed to update the coding parameters and all the pocs.
 *
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
 * @param   p_max_res       pointer that will hold the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min            pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min            pointer that will hold the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_get_encoding_parameters(const opj_image_t *p_image,
                                        const opj_cp_t *p_cp,
                                        OPJ_UINT32  tileno,
                                        OPJ_INT32  * p_tx0,
                                        OPJ_INT32 * p_tx1,
                                        OPJ_INT32 * p_ty0,
                                        OPJ_INT32 * p_ty1,
                                        OPJ_UINT32 * p_dx_min,
                                        OPJ_UINT32 * p_dy_min,
                                        OPJ_UINT32 * p_max_prec,
                                        OPJ_UINT32 * p_max_res);

/**
 * Gets the encoding parameters needed to update the coding parameters and all the pocs.







|
|
|
|







142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
 * @param   p_max_res       pointer that will hold the maximum number of resolutions for all the poc inside the tile.
 * @param   p_dx_min            pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min            pointer that will hold the minimum dy of all the components of all the resolutions for the tile.
 */
static void opj_get_encoding_parameters(const opj_image_t *p_image,
                                        const opj_cp_t *p_cp,
                                        OPJ_UINT32  tileno,
                                        OPJ_UINT32 * p_tx0,
                                        OPJ_UINT32 * p_tx1,
                                        OPJ_UINT32 * p_ty0,
                                        OPJ_UINT32 * p_ty1,
                                        OPJ_UINT32 * p_dx_min,
                                        OPJ_UINT32 * p_dy_min,
                                        OPJ_UINT32 * p_max_prec,
                                        OPJ_UINT32 * p_max_res);

/**
 * Gets the encoding parameters needed to update the coding parameters and all the pocs.
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
 * @param   p_dx_min        pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        pointer that will hold the minimum dy of all the components of all the resolutions for the tile.
 * @param   p_resolutions   pointer to an area corresponding to the one described above.
 */
static void opj_get_all_encoding_parameters(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno,
        OPJ_INT32 * p_tx0,
        OPJ_INT32 * p_tx1,
        OPJ_INT32 * p_ty0,
        OPJ_INT32 * p_ty1,
        OPJ_UINT32 * p_dx_min,
        OPJ_UINT32 * p_dy_min,
        OPJ_UINT32 * p_max_prec,
        OPJ_UINT32 * p_max_res,
        OPJ_UINT32 ** p_resolutions);
/**
 * Allocates memory for a packet iterator. Data and data sizes are set by this operation.
 * No other data is set. The include section of the packet  iterator is not allocated.
 *
 * @param   p_image     the image used to initialize the packet iterator (in fact only the number of components is relevant.
 * @param   p_cp        the coding parameters.
 * @param   tileno  the index of the tile from which creating the packet iterator.

 */
static opj_pi_iterator_t * opj_pi_create(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno);

/**
 * FIXME DOC
 */
static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi,
        opj_tcp_t * p_tcp,
        OPJ_UINT32 p_max_precision,
        OPJ_UINT32 p_max_res);







|
|
|
|












>



|
>







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
 * @param   p_dx_min        pointer that will hold the minimum dx of all the components of all the resolutions for the tile.
 * @param   p_dy_min        pointer that will hold the minimum dy of all the components of all the resolutions for the tile.
 * @param   p_resolutions   pointer to an area corresponding to the one described above.
 */
static void opj_get_all_encoding_parameters(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno,
        OPJ_UINT32 * p_tx0,
        OPJ_UINT32 * p_tx1,
        OPJ_UINT32 * p_ty0,
        OPJ_UINT32 * p_ty1,
        OPJ_UINT32 * p_dx_min,
        OPJ_UINT32 * p_dy_min,
        OPJ_UINT32 * p_max_prec,
        OPJ_UINT32 * p_max_res,
        OPJ_UINT32 ** p_resolutions);
/**
 * Allocates memory for a packet iterator. Data and data sizes are set by this operation.
 * No other data is set. The include section of the packet  iterator is not allocated.
 *
 * @param   p_image     the image used to initialize the packet iterator (in fact only the number of components is relevant.
 * @param   p_cp        the coding parameters.
 * @param   tileno  the index of the tile from which creating the packet iterator.
 * @param   manager Event manager
 */
static opj_pi_iterator_t * opj_pi_create(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno,
        opj_event_mgr_t* manager);
/**
 * FIXME DOC
 */
static void opj_pi_update_decode_not_poc(opj_pi_iterator_t * p_pi,
        opj_tcp_t * p_tcp,
        OPJ_UINT32 p_max_precision,
        OPJ_UINT32 p_max_res);
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

/*
==========================================================
   local functions
==========================================================
*/

static void opj_pi_emit_error(opj_pi_iterator_t * pi, const char* msg)
{
    (void)pi;
    (void)msg;
}

static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;








    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        res = &comp->resolutions[pi->resno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;







<
<
<
<
<
<





>
>
>
>
>
>
>







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

/*
==========================================================
   local functions
==========================================================
*/







static OPJ_BOOL opj_pi_next_lrcp(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;

    if (pi->poc.compno0 >= pi->numcomps ||
            pi->poc.compno1 >= pi->numcomps + 1) {
        opj_event_msg(pi->manager, EVT_ERROR,
                      "opj_pi_next_lrcp(): invalid compno0/compno1\n");
        return OPJ_FALSE;
    }

    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        res = &comp->resolutions[pi->resno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
                    /* Avoids index out of bounds access with */
                    /* id_000098,sig_11,src_005411,op_havoc,rep_2 of */
                    /* https://github.com/uclouvain/openjpeg/issues/938 */
                    /* Not sure if this is the most clever fix. Perhaps */
                    /* include should be resized when a POC arises, or */
                    /* the POC should be rejected */
                    if (index >= pi->include_size) {
                        opj_pi_emit_error(pi, "Invalid access to pi->include");
                        return OPJ_FALSE;
                    }
                    if (!pi->include[index]) {
                        pi->include[index] = 1;
                        return OPJ_TRUE;
                    }
LABEL_SKIP:







|







273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
                    /* Avoids index out of bounds access with */
                    /* id_000098,sig_11,src_005411,op_havoc,rep_2 of */
                    /* https://github.com/uclouvain/openjpeg/issues/938 */
                    /* Not sure if this is the most clever fix. Perhaps */
                    /* include should be resized when a POC arises, or */
                    /* the POC should be rejected */
                    if (index >= pi->include_size) {
                        opj_event_msg(pi->manager, EVT_ERROR, "Invalid access to pi->include");
                        return OPJ_FALSE;
                    }
                    if (!pi->include[index]) {
                        pi->include[index] = 1;
                        return OPJ_TRUE;
                    }
LABEL_SKIP:
290
291
292
293
294
295
296







297
298
299
300
301
302
303
}

static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;








    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        res = &comp->resolutions[pi->resno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;







>
>
>
>
>
>
>







295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
}

static OPJ_BOOL opj_pi_next_rlcp(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;

    if (pi->poc.compno0 >= pi->numcomps ||
            pi->poc.compno1 >= pi->numcomps + 1) {
        opj_event_msg(pi->manager, EVT_ERROR,
                      "opj_pi_next_rlcp(): invalid compno0/compno1\n");
        return OPJ_FALSE;
    }

    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        res = &comp->resolutions[pi->resno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
                if (!pi->tp_on) {
                    pi->poc.precno1 = res->pw * res->ph;
                }
                for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
                    index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                            pi->step_c + pi->precno * pi->step_p;
                    if (index >= pi->include_size) {
                        opj_pi_emit_error(pi, "Invalid access to pi->include");
                        return OPJ_FALSE;
                    }
                    if (!pi->include[index]) {
                        pi->include[index] = 1;
                        return OPJ_TRUE;
                    }
LABEL_SKIP:







|







326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
                if (!pi->tp_on) {
                    pi->poc.precno1 = res->pw * res->ph;
                }
                for (pi->precno = pi->poc.precno0; pi->precno < pi->poc.precno1; pi->precno++) {
                    index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                            pi->step_c + pi->precno * pi->step_p;
                    if (index >= pi->include_size) {
                        opj_event_msg(pi->manager, EVT_ERROR, "Invalid access to pi->include");
                        return OPJ_FALSE;
                    }
                    if (!pi->include[index]) {
                        pi->include[index] = 1;
                        return OPJ_TRUE;
                    }
LABEL_SKIP:
336
337
338
339
340
341
342







343
344
345
346
347
348
349
}

static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;








    if (!pi->first) {
        goto LABEL_SKIP;
    } else {
        OPJ_UINT32 compno, resno;
        pi->first = 0;
        pi->dx = 0;







>
>
>
>
>
>
>







348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
}

static OPJ_BOOL opj_pi_next_rpcl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;

    if (pi->poc.compno0 >= pi->numcomps ||
            pi->poc.compno1 >= pi->numcomps + 1) {
        opj_event_msg(pi->manager, EVT_ERROR,
                      "opj_pi_next_rpcl(): invalid compno0/compno1\n");
        return OPJ_FALSE;
    }

    if (!pi->first) {
        goto LABEL_SKIP;
    } else {
        OPJ_UINT32 compno, resno;
        pi->first = 0;
        pi->dx = 0;
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
    if (!pi->tp_on) {
        pi->poc.ty0 = pi->ty0;
        pi->poc.tx0 = pi->tx0;
        pi->poc.ty1 = pi->ty1;
        pi->poc.tx1 = pi->tx1;
    }
    for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
        for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
                pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
            for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
                    pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
                for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
                    OPJ_UINT32 levelno;
                    OPJ_INT32 trx0, try0;
                    OPJ_INT32  trx1, try1;
                    OPJ_UINT32  rpx, rpy;
                    OPJ_INT32  prci, prcj;
                    comp = &pi->comps[pi->compno];
                    if (pi->resno >= comp->numresolutions) {
                        continue;
                    }
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero */
                    /* Relates to id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
                    try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
                    trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
                    try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Fixes reading id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.3 Resolution level-position-component-layer progression */
                    if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1 << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1 << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
                                                (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
                           - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
                    prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
                                                (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
                           - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
                    pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_pi_emit_error(pi, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:







|
|
|
|


|
|

|


















|
|
|
|













|
|


|
|











|
|
|
|
|
|
|




|







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
    if (!pi->tp_on) {
        pi->poc.ty0 = pi->ty0;
        pi->poc.tx0 = pi->tx0;
        pi->poc.ty1 = pi->ty1;
        pi->poc.tx1 = pi->tx1;
    }
    for (pi->resno = pi->poc.resno0; pi->resno < pi->poc.resno1; pi->resno++) {
        for (pi->y = (OPJ_UINT32)pi->poc.ty0; pi->y < (OPJ_UINT32)pi->poc.ty1;
                pi->y += (pi->dy - (pi->y % pi->dy))) {
            for (pi->x = (OPJ_UINT32)pi->poc.tx0; pi->x < (OPJ_UINT32)pi->poc.tx1;
                    pi->x += (pi->dx - (pi->x % pi->dx))) {
                for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
                    OPJ_UINT32 levelno;
                    OPJ_UINT32 trx0, try0;
                    OPJ_UINT32  trx1, try1;
                    OPJ_UINT32  rpx, rpy;
                    OPJ_UINT32  prci, prcj;
                    comp = &pi->comps[pi->compno];
                    if (pi->resno >= comp->numresolutions) {
                        continue;
                    }
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero */
                    /* Relates to id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_uint_ceildiv(pi->tx0, (comp->dx << levelno));
                    try0 = opj_uint_ceildiv(pi->ty0, (comp->dy << levelno));
                    trx1 = opj_uint_ceildiv(pi->tx1, (comp->dx << levelno));
                    try1 = opj_uint_ceildiv(pi->ty1, (comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Fixes reading id:000026,sig:08,src:002419,op:int32,pos:60,val:+32 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.3 Resolution level-position-component-layer progression */
                    if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1U << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1U << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_uint_floordivpow2(opj_uint_ceildiv(pi->x,
                                                 (comp->dx << levelno)), res->pdx)
                           - opj_uint_floordivpow2(trx0, res->pdx);
                    prcj = opj_uint_floordivpow2(opj_uint_ceildiv(pi->y,
                                                 (comp->dy << levelno)), res->pdy)
                           - opj_uint_floordivpow2(try0, res->pdy);
                    pi->precno = prci + prcj * res->pw;
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_event_msg(pi->manager, EVT_ERROR, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:
468
469
470
471
472
473
474







475
476
477
478
479
480
481
}

static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;








    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        goto LABEL_SKIP;
    } else {
        OPJ_UINT32 compno, resno;
        pi->first = 0;







>
>
>
>
>
>
>







487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
}

static OPJ_BOOL opj_pi_next_pcrl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;

    if (pi->poc.compno0 >= pi->numcomps ||
            pi->poc.compno1 >= pi->numcomps + 1) {
        opj_event_msg(pi->manager, EVT_ERROR,
                      "opj_pi_next_pcrl(): invalid compno0/compno1\n");
        return OPJ_FALSE;
    }

    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        goto LABEL_SKIP;
    } else {
        OPJ_UINT32 compno, resno;
        pi->first = 0;
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    }
    if (!pi->tp_on) {
        pi->poc.ty0 = pi->ty0;
        pi->poc.tx0 = pi->tx0;
        pi->poc.ty1 = pi->ty1;
        pi->poc.tx1 = pi->tx1;
    }
    for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
            pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
        for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
                pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
            for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
                comp = &pi->comps[pi->compno];
                for (pi->resno = pi->poc.resno0;
                        pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
                    OPJ_UINT32 levelno;
                    OPJ_INT32 trx0, try0;
                    OPJ_INT32 trx1, try1;
                    OPJ_UINT32 rpx, rpy;
                    OPJ_INT32 prci, prcj;
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero */
                    /* Relates to id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
                    try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
                    trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
                    try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Relates to id:000019,sig:08,src:001098,op:flip1,pos:49 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.4 Position-component-resolution level-layer progression */
                    if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1 << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1 << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
                                                (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
                           - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
                    prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
                                                (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
                           - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
                    pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_pi_emit_error(pi, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:







|
|
|
|





|
|

|














|
|
|
|













|
|


|
|











|
|
|
|
|
|
|




|







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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
    }
    if (!pi->tp_on) {
        pi->poc.ty0 = pi->ty0;
        pi->poc.tx0 = pi->tx0;
        pi->poc.ty1 = pi->ty1;
        pi->poc.tx1 = pi->tx1;
    }
    for (pi->y = (OPJ_UINT32)pi->poc.ty0; pi->y < (OPJ_UINT32)pi->poc.ty1;
            pi->y += (pi->dy - (pi->y % pi->dy))) {
        for (pi->x = (OPJ_UINT32)pi->poc.tx0; pi->x < (OPJ_UINT32)pi->poc.tx1;
                pi->x += (pi->dx - (pi->x % pi->dx))) {
            for (pi->compno = pi->poc.compno0; pi->compno < pi->poc.compno1; pi->compno++) {
                comp = &pi->comps[pi->compno];
                for (pi->resno = pi->poc.resno0;
                        pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
                    OPJ_UINT32 levelno;
                    OPJ_UINT32 trx0, try0;
                    OPJ_UINT32 trx1, try1;
                    OPJ_UINT32 rpx, rpy;
                    OPJ_UINT32 prci, prcj;
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero */
                    /* Relates to id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_uint_ceildiv(pi->tx0, (comp->dx << levelno));
                    try0 = opj_uint_ceildiv(pi->ty0, (comp->dy << levelno));
                    trx1 = opj_uint_ceildiv(pi->tx1, (comp->dx << levelno));
                    try1 = opj_uint_ceildiv(pi->ty1, (comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Relates to id:000019,sig:08,src:001098,op:flip1,pos:49 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.4 Position-component-resolution level-layer progression */
                    if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1U << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1U << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_uint_floordivpow2(opj_uint_ceildiv(pi->x,
                                                 (comp->dx << levelno)), res->pdx)
                           - opj_uint_floordivpow2(trx0, res->pdx);
                    prcj = opj_uint_floordivpow2(opj_uint_ceildiv(pi->y,
                                                 (comp->dy << levelno)), res->pdy)
                           - opj_uint_floordivpow2(try0, res->pdy);
                    pi->precno = prci + prcj * res->pw;
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_event_msg(pi->manager, EVT_ERROR, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:
599
600
601
602
603
604
605







606
607
608
609
610
611
612
}

static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;








    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;
    }







>
>
>
>
>
>
>







625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
}

static OPJ_BOOL opj_pi_next_cprl(opj_pi_iterator_t * pi)
{
    opj_pi_comp_t *comp = NULL;
    opj_pi_resolution_t *res = NULL;
    OPJ_UINT32 index = 0;

    if (pi->poc.compno0 >= pi->numcomps ||
            pi->poc.compno1 >= pi->numcomps + 1) {
        opj_event_msg(pi->manager, EVT_ERROR,
                      "opj_pi_next_cprl(): invalid compno0/compno1\n");
        return OPJ_FALSE;
    }

    if (!pi->first) {
        comp = &pi->comps[pi->compno];
        goto LABEL_SKIP;
    } else {
        pi->first = 0;
    }
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
        }
        if (!pi->tp_on) {
            pi->poc.ty0 = pi->ty0;
            pi->poc.tx0 = pi->tx0;
            pi->poc.ty1 = pi->ty1;
            pi->poc.tx1 = pi->tx1;
        }
        for (pi->y = pi->poc.ty0; pi->y < pi->poc.ty1;
                pi->y += (OPJ_INT32)(pi->dy - (OPJ_UINT32)(pi->y % (OPJ_INT32)pi->dy))) {
            for (pi->x = pi->poc.tx0; pi->x < pi->poc.tx1;
                    pi->x += (OPJ_INT32)(pi->dx - (OPJ_UINT32)(pi->x % (OPJ_INT32)pi->dx))) {
                for (pi->resno = pi->poc.resno0;
                        pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
                    OPJ_UINT32 levelno;
                    OPJ_INT32 trx0, try0;
                    OPJ_INT32 trx1, try1;
                    OPJ_UINT32 rpx, rpy;
                    OPJ_INT32 prci, prcj;
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero on id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_int_ceildiv(pi->tx0, (OPJ_INT32)(comp->dx << levelno));
                    try0 = opj_int_ceildiv(pi->ty0, (OPJ_INT32)(comp->dy << levelno));
                    trx1 = opj_int_ceildiv(pi->tx1, (OPJ_INT32)(comp->dx << levelno));
                    try1 = opj_int_ceildiv(pi->ty1, (OPJ_INT32)(comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Fixes reading id:000019,sig:08,src:001098,op:flip1,pos:49 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.5 Component-position-resolution level-layer progression */
                    if (!((pi->y % (OPJ_INT32)(comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1 << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (OPJ_INT32)(comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1 << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_int_floordivpow2(opj_int_ceildiv(pi->x,
                                                (OPJ_INT32)(comp->dx << levelno)), (OPJ_INT32)res->pdx)
                           - opj_int_floordivpow2(trx0, (OPJ_INT32)res->pdx);
                    prcj = opj_int_floordivpow2(opj_int_ceildiv(pi->y,
                                                (OPJ_INT32)(comp->dy << levelno)), (OPJ_INT32)res->pdy)
                           - opj_int_floordivpow2(try0, (OPJ_INT32)res->pdy);
                    pi->precno = (OPJ_UINT32)(prci + prcj * (OPJ_INT32)res->pw);
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_pi_emit_error(pi, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:
                        ;
                    }
                }
            }
        }
    }

    return OPJ_FALSE;
}

static void opj_get_encoding_parameters(const opj_image_t *p_image,
                                        const opj_cp_t *p_cp,
                                        OPJ_UINT32 p_tileno,
                                        OPJ_INT32 * p_tx0,
                                        OPJ_INT32  * p_tx1,
                                        OPJ_INT32  * p_ty0,
                                        OPJ_INT32  * p_ty1,
                                        OPJ_UINT32 * p_dx_min,
                                        OPJ_UINT32 * p_dy_min,
                                        OPJ_UINT32 * p_max_prec,
                                        OPJ_UINT32 * p_max_res)
{
    /* loop */
    OPJ_UINT32  compno, resno;







|
|
|
|



|
|

|













|
|
|
|













|
|


|
|











|
|
|
|
|
|
|




|




















|
|
|
|







668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
        }
        if (!pi->tp_on) {
            pi->poc.ty0 = pi->ty0;
            pi->poc.tx0 = pi->tx0;
            pi->poc.ty1 = pi->ty1;
            pi->poc.tx1 = pi->tx1;
        }
        for (pi->y = (OPJ_UINT32)pi->poc.ty0; pi->y < (OPJ_UINT32)pi->poc.ty1;
                pi->y += (pi->dy - (pi->y % pi->dy))) {
            for (pi->x = (OPJ_UINT32)pi->poc.tx0; pi->x < (OPJ_UINT32)pi->poc.tx1;
                    pi->x += (pi->dx - (pi->x % pi->dx))) {
                for (pi->resno = pi->poc.resno0;
                        pi->resno < opj_uint_min(pi->poc.resno1, comp->numresolutions); pi->resno++) {
                    OPJ_UINT32 levelno;
                    OPJ_UINT32 trx0, try0;
                    OPJ_UINT32 trx1, try1;
                    OPJ_UINT32 rpx, rpy;
                    OPJ_UINT32 prci, prcj;
                    res = &comp->resolutions[pi->resno];
                    levelno = comp->numresolutions - 1 - pi->resno;
                    /* Avoids division by zero on id_000004,sig_06,src_000679,op_arith8,pos_49,val_-17 */
                    /* of  https://github.com/uclouvain/openjpeg/issues/938 */
                    if (levelno >= 32 ||
                            ((comp->dx << levelno) >> levelno) != comp->dx ||
                            ((comp->dy << levelno) >> levelno) != comp->dy) {
                        continue;
                    }
                    if ((comp->dx << levelno) > INT_MAX ||
                            (comp->dy << levelno) > INT_MAX) {
                        continue;
                    }
                    trx0 = opj_uint_ceildiv(pi->tx0, (comp->dx << levelno));
                    try0 = opj_uint_ceildiv(pi->ty0, (comp->dy << levelno));
                    trx1 = opj_uint_ceildiv(pi->tx1, (comp->dx << levelno));
                    try1 = opj_uint_ceildiv(pi->ty1, (comp->dy << levelno));
                    rpx = res->pdx + levelno;
                    rpy = res->pdy + levelno;

                    /* To avoid divisions by zero / undefined behaviour on shift */
                    /* in below tests */
                    /* Fixes reading id:000019,sig:08,src:001098,op:flip1,pos:49 */
                    /* of https://github.com/uclouvain/openjpeg/issues/938 */
                    if (rpx >= 31 || ((comp->dx << rpx) >> rpx) != comp->dx ||
                            rpy >= 31 || ((comp->dy << rpy) >> rpy) != comp->dy) {
                        continue;
                    }

                    /* See ISO-15441. B.12.1.5 Component-position-resolution level-layer progression */
                    if (!((pi->y % (comp->dy << rpy) == 0) || ((pi->y == pi->ty0) &&
                            ((try0 << levelno) % (1U << rpy))))) {
                        continue;
                    }
                    if (!((pi->x % (comp->dx << rpx) == 0) || ((pi->x == pi->tx0) &&
                            ((trx0 << levelno) % (1U << rpx))))) {
                        continue;
                    }

                    if ((res->pw == 0) || (res->ph == 0)) {
                        continue;
                    }

                    if ((trx0 == trx1) || (try0 == try1)) {
                        continue;
                    }

                    prci = opj_uint_floordivpow2(opj_uint_ceildiv(pi->x,
                                                 (comp->dx << levelno)), res->pdx)
                           - opj_uint_floordivpow2(trx0, res->pdx);
                    prcj = opj_uint_floordivpow2(opj_uint_ceildiv(pi->y,
                                                 (comp->dy << levelno)), res->pdy)
                           - opj_uint_floordivpow2(try0, res->pdy);
                    pi->precno = (OPJ_UINT32)(prci + prcj * res->pw);
                    for (pi->layno = pi->poc.layno0; pi->layno < pi->poc.layno1; pi->layno++) {
                        index = pi->layno * pi->step_l + pi->resno * pi->step_r + pi->compno *
                                pi->step_c + pi->precno * pi->step_p;
                        if (index >= pi->include_size) {
                            opj_event_msg(pi->manager, EVT_ERROR, "Invalid access to pi->include");
                            return OPJ_FALSE;
                        }
                        if (!pi->include[index]) {
                            pi->include[index] = 1;
                            return OPJ_TRUE;
                        }
LABEL_SKIP:
                        ;
                    }
                }
            }
        }
    }

    return OPJ_FALSE;
}

static void opj_get_encoding_parameters(const opj_image_t *p_image,
                                        const opj_cp_t *p_cp,
                                        OPJ_UINT32 p_tileno,
                                        OPJ_UINT32 * p_tx0,
                                        OPJ_UINT32  * p_tx1,
                                        OPJ_UINT32  * p_ty0,
                                        OPJ_UINT32  * p_ty1,
                                        OPJ_UINT32 * p_dx_min,
                                        OPJ_UINT32 * p_dy_min,
                                        OPJ_UINT32 * p_max_prec,
                                        OPJ_UINT32 * p_max_res)
{
    /* loop */
    OPJ_UINT32  compno, resno;
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
    /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
    p = p_tileno % p_cp->tw;
    q = p_tileno / p_cp->tw;

    /* find extent of tile */
    l_tx0 = p_cp->tx0 + p *
            p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
    *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);
    *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
    l_ty0 = p_cp->ty0 + q *
            p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
    *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);
    *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);

    /* max precision is 0 (can only grow) */
    *p_max_prec = 0;
    *p_max_res = 0;

    /* take the largest value for dx_min and dy_min */
    *p_dx_min = 0x7fffffff;
    *p_dy_min  = 0x7fffffff;

    for (compno = 0; compno < p_image->numcomps; ++compno) {
        /* arithmetic variables to calculate */
        OPJ_UINT32 l_level_no;
        OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
        OPJ_INT32 l_px0, l_py0, l_px1, py1;
        OPJ_UINT32 l_pdx, l_pdy;
        OPJ_UINT32 l_pw, l_ph;
        OPJ_UINT32 l_product;
        OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;

        l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
        l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
        l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
        l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);

        if (l_tccp->numresolutions > *p_max_res) {
            *p_max_res = l_tccp->numresolutions;
        }

        /* use custom size for precincts */
        for (resno = 0; resno < l_tccp->numresolutions; ++resno) {







|
|


|
|












|
|



|

|
|
|
|







797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
    /* here calculation of tx0, tx1, ty0, ty1, maxprec, dx and dy */
    p = p_tileno % p_cp->tw;
    q = p_tileno / p_cp->tw;

    /* find extent of tile */
    l_tx0 = p_cp->tx0 + p *
            p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
    *p_tx0 = opj_uint_max(l_tx0, p_image->x0);
    *p_tx1 = opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
    l_ty0 = p_cp->ty0 + q *
            p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
    *p_ty0 = opj_uint_max(l_ty0, p_image->y0);
    *p_ty1 = opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);

    /* max precision is 0 (can only grow) */
    *p_max_prec = 0;
    *p_max_res = 0;

    /* take the largest value for dx_min and dy_min */
    *p_dx_min = 0x7fffffff;
    *p_dy_min  = 0x7fffffff;

    for (compno = 0; compno < p_image->numcomps; ++compno) {
        /* arithmetic variables to calculate */
        OPJ_UINT32 l_level_no;
        OPJ_UINT32 l_rx0, l_ry0, l_rx1, l_ry1;
        OPJ_UINT32 l_px0, l_py0, l_px1, py1;
        OPJ_UINT32 l_pdx, l_pdy;
        OPJ_UINT32 l_pw, l_ph;
        OPJ_UINT32 l_product;
        OPJ_UINT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;

        l_tcx0 = opj_uint_ceildiv(*p_tx0, l_img_comp->dx);
        l_tcy0 = opj_uint_ceildiv(*p_ty0, l_img_comp->dy);
        l_tcx1 = opj_uint_ceildiv(*p_tx1, l_img_comp->dx);
        l_tcy1 = opj_uint_ceildiv(*p_ty1, l_img_comp->dy);

        if (l_tccp->numresolutions > *p_max_res) {
            *p_max_res = l_tccp->numresolutions;
        }

        /* use custom size for precincts */
        for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
            /* take the minimum size for dx for each comp and resolution */
            *p_dx_min = opj_uint_min(*p_dx_min, l_dx);
            *p_dy_min = opj_uint_min(*p_dy_min, l_dy);

            /* various calculations of extents */
            l_level_no = l_tccp->numresolutions - 1 - resno;

            l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
            l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
            l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
            l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);

            l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
            l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
            l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;

            py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;

            l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
            l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);

            l_product = l_pw * l_ph;

            /* update precision */
            if (l_product > *p_max_prec) {
                *p_max_prec = l_product;
            }
        }
        ++l_img_comp;
        ++l_tccp;
    }
}


static void opj_get_all_encoding_parameters(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno,
        OPJ_INT32 * p_tx0,
        OPJ_INT32 * p_tx1,
        OPJ_INT32 * p_ty0,
        OPJ_INT32 * p_ty1,
        OPJ_UINT32 * p_dx_min,
        OPJ_UINT32 * p_dy_min,
        OPJ_UINT32 * p_max_prec,
        OPJ_UINT32 * p_max_res,
        OPJ_UINT32 ** p_resolutions)
{
    /* loop*/







|
|
|
|

|
|
|

|

|
|

















|
|
|
|







849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
            /* take the minimum size for dx for each comp and resolution */
            *p_dx_min = opj_uint_min(*p_dx_min, l_dx);
            *p_dy_min = opj_uint_min(*p_dy_min, l_dy);

            /* various calculations of extents */
            l_level_no = l_tccp->numresolutions - 1 - resno;

            l_rx0 = opj_uint_ceildivpow2(l_tcx0, l_level_no);
            l_ry0 = opj_uint_ceildivpow2(l_tcy0, l_level_no);
            l_rx1 = opj_uint_ceildivpow2(l_tcx1, l_level_no);
            l_ry1 = opj_uint_ceildivpow2(l_tcy1, l_level_no);

            l_px0 = opj_uint_floordivpow2(l_rx0, l_pdx) << l_pdx;
            l_py0 = opj_uint_floordivpow2(l_ry0, l_pdy) << l_pdy;
            l_px1 = opj_uint_ceildivpow2(l_rx1, l_pdx) << l_pdx;

            py1 = opj_uint_ceildivpow2(l_ry1, l_pdy) << l_pdy;

            l_pw = (l_rx0 == l_rx1) ? 0 : ((l_px1 - l_px0) >> l_pdx);
            l_ph = (l_ry0 == l_ry1) ? 0 : ((py1 - l_py0) >> l_pdy);

            l_product = l_pw * l_ph;

            /* update precision */
            if (l_product > *p_max_prec) {
                *p_max_prec = l_product;
            }
        }
        ++l_img_comp;
        ++l_tccp;
    }
}


static void opj_get_all_encoding_parameters(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 tileno,
        OPJ_UINT32 * p_tx0,
        OPJ_UINT32 * p_tx1,
        OPJ_UINT32 * p_ty0,
        OPJ_UINT32 * p_ty1,
        OPJ_UINT32 * p_dx_min,
        OPJ_UINT32 * p_dy_min,
        OPJ_UINT32 * p_max_prec,
        OPJ_UINT32 * p_max_res,
        OPJ_UINT32 ** p_resolutions)
{
    /* loop*/
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941

942
943

944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966

967
968

969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984

985
986
987
988
989
990
991
    /* position in x and y of tile*/
    p = tileno % p_cp->tw;
    q = tileno / p_cp->tw;

    /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
    l_tx0 = p_cp->tx0 + p *
            p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
    *p_tx0 = (OPJ_INT32)opj_uint_max(l_tx0, p_image->x0);
    *p_tx1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
    l_ty0 = p_cp->ty0 + q *
            p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
    *p_ty0 = (OPJ_INT32)opj_uint_max(l_ty0, p_image->y0);
    *p_ty1 = (OPJ_INT32)opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);

    /* max precision and resolution is 0 (can only grow)*/
    *p_max_prec = 0;
    *p_max_res = 0;

    /* take the largest value for dx_min and dy_min*/
    *p_dx_min = 0x7fffffff;
    *p_dy_min = 0x7fffffff;

    for (compno = 0; compno < p_image->numcomps; ++compno) {
        /* aritmetic variables to calculate*/
        OPJ_UINT32 l_level_no;
        OPJ_INT32 l_rx0, l_ry0, l_rx1, l_ry1;
        OPJ_INT32 l_px0, l_py0, l_px1, py1;
        OPJ_UINT32 l_product;
        OPJ_INT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
        OPJ_UINT32 l_pdx, l_pdy, l_pw, l_ph;

        lResolutionPtr = p_resolutions[compno];

        l_tcx0 = opj_int_ceildiv(*p_tx0, (OPJ_INT32)l_img_comp->dx);
        l_tcy0 = opj_int_ceildiv(*p_ty0, (OPJ_INT32)l_img_comp->dy);
        l_tcx1 = opj_int_ceildiv(*p_tx1, (OPJ_INT32)l_img_comp->dx);
        l_tcy1 = opj_int_ceildiv(*p_ty1, (OPJ_INT32)l_img_comp->dy);

        if (l_tccp->numresolutions > *p_max_res) {
            *p_max_res = l_tccp->numresolutions;
        }

        /* use custom size for precincts*/
        l_level_no = l_tccp->numresolutions;
        for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
            OPJ_UINT32 l_dx, l_dy;

            --l_level_no;

            /* precinct width and height*/
            l_pdx = l_tccp->prcw[resno];
            l_pdy = l_tccp->prch[resno];

            *lResolutionPtr++ = l_pdx;
            *lResolutionPtr++ = l_pdy;

            if (l_pdx + l_level_no < 32 &&
                    l_img_comp->dx <= UINT_MAX / (1u << (l_pdx + l_level_no))) {
                l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
                /* take the minimum size for l_dx for each comp and resolution*/
                *p_dx_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dx_min, (OPJ_INT32)l_dx);
            }
            if (l_pdy + l_level_no < 32 &&
                    l_img_comp->dy <= UINT_MAX / (1u << (l_pdy + l_level_no))) {
                l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
                *p_dy_min = (OPJ_UINT32)opj_int_min((OPJ_INT32) * p_dy_min, (OPJ_INT32)l_dy);
            }

            /* various calculations of extents*/
            l_rx0 = opj_int_ceildivpow2(l_tcx0, (OPJ_INT32)l_level_no);
            l_ry0 = opj_int_ceildivpow2(l_tcy0, (OPJ_INT32)l_level_no);
            l_rx1 = opj_int_ceildivpow2(l_tcx1, (OPJ_INT32)l_level_no);
            l_ry1 = opj_int_ceildivpow2(l_tcy1, (OPJ_INT32)l_level_no);
            l_px0 = opj_int_floordivpow2(l_rx0, (OPJ_INT32)l_pdx) << l_pdx;
            l_py0 = opj_int_floordivpow2(l_ry0, (OPJ_INT32)l_pdy) << l_pdy;
            l_px1 = opj_int_ceildivpow2(l_rx1, (OPJ_INT32)l_pdx) << l_pdx;
            py1 = opj_int_ceildivpow2(l_ry1, (OPJ_INT32)l_pdy) << l_pdy;
            l_pw = (l_rx0 == l_rx1) ? 0 : (OPJ_UINT32)((l_px1 - l_px0) >> l_pdx);
            l_ph = (l_ry0 == l_ry1) ? 0 : (OPJ_UINT32)((py1 - l_py0) >> l_pdy);

            *lResolutionPtr++ = l_pw;
            *lResolutionPtr++ = l_ph;

            l_product = l_pw * l_ph;

            /* update precision*/
            if (l_product > *p_max_prec) {
                *p_max_prec = l_product;
            }

        }
        ++l_tccp;
        ++l_img_comp;
    }
}

static opj_pi_iterator_t * opj_pi_create(const opj_image_t *image,
        const opj_cp_t *cp,
        OPJ_UINT32 tileno)

{
    /* loop*/
    OPJ_UINT32 pino, compno;
    /* number of poc in the p_pi*/
    OPJ_UINT32 l_poc_bound;

    /* pointers to tile coding parameters and components.*/







|
|


|
|












|
|

|


|

|
|
|
|















>
|
|
>




|




|



|
|
|
|
|
|
|
|
|
|
>
|
|
>















|
>







923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
    /* position in x and y of tile*/
    p = tileno % p_cp->tw;
    q = tileno / p_cp->tw;

    /* here calculation of tx0, tx1, ty0, ty1, maxprec, l_dx and l_dy */
    l_tx0 = p_cp->tx0 + p *
            p_cp->tdx; /* can't be greater than p_image->x1 so won't overflow */
    *p_tx0 = opj_uint_max(l_tx0, p_image->x0);
    *p_tx1 = opj_uint_min(opj_uint_adds(l_tx0, p_cp->tdx), p_image->x1);
    l_ty0 = p_cp->ty0 + q *
            p_cp->tdy; /* can't be greater than p_image->y1 so won't overflow */
    *p_ty0 = opj_uint_max(l_ty0, p_image->y0);
    *p_ty1 = opj_uint_min(opj_uint_adds(l_ty0, p_cp->tdy), p_image->y1);

    /* max precision and resolution is 0 (can only grow)*/
    *p_max_prec = 0;
    *p_max_res = 0;

    /* take the largest value for dx_min and dy_min*/
    *p_dx_min = 0x7fffffff;
    *p_dy_min = 0x7fffffff;

    for (compno = 0; compno < p_image->numcomps; ++compno) {
        /* aritmetic variables to calculate*/
        OPJ_UINT32 l_level_no;
        OPJ_UINT32 l_rx0, l_ry0, l_rx1, l_ry1;
        OPJ_UINT32 l_px0, l_py0, l_px1, py1;
        OPJ_UINT32 l_product;
        OPJ_UINT32 l_tcx0, l_tcy0, l_tcx1, l_tcy1;
        OPJ_UINT32 l_pdx, l_pdy, l_pw, l_ph;

        lResolutionPtr = p_resolutions ? p_resolutions[compno] : NULL;

        l_tcx0 = opj_uint_ceildiv(*p_tx0, l_img_comp->dx);
        l_tcy0 = opj_uint_ceildiv(*p_ty0, l_img_comp->dy);
        l_tcx1 = opj_uint_ceildiv(*p_tx1, l_img_comp->dx);
        l_tcy1 = opj_uint_ceildiv(*p_ty1, l_img_comp->dy);

        if (l_tccp->numresolutions > *p_max_res) {
            *p_max_res = l_tccp->numresolutions;
        }

        /* use custom size for precincts*/
        l_level_no = l_tccp->numresolutions;
        for (resno = 0; resno < l_tccp->numresolutions; ++resno) {
            OPJ_UINT32 l_dx, l_dy;

            --l_level_no;

            /* precinct width and height*/
            l_pdx = l_tccp->prcw[resno];
            l_pdy = l_tccp->prch[resno];
            if (lResolutionPtr) {
                *lResolutionPtr++ = l_pdx;
                *lResolutionPtr++ = l_pdy;
            }
            if (l_pdx + l_level_no < 32 &&
                    l_img_comp->dx <= UINT_MAX / (1u << (l_pdx + l_level_no))) {
                l_dx = l_img_comp->dx * (1u << (l_pdx + l_level_no));
                /* take the minimum size for l_dx for each comp and resolution*/
                *p_dx_min = opj_uint_min(*p_dx_min, l_dx);
            }
            if (l_pdy + l_level_no < 32 &&
                    l_img_comp->dy <= UINT_MAX / (1u << (l_pdy + l_level_no))) {
                l_dy = l_img_comp->dy * (1u << (l_pdy + l_level_no));
                *p_dy_min = opj_uint_min(*p_dy_min, l_dy);
            }

            /* various calculations of extents*/
            l_rx0 = opj_uint_ceildivpow2(l_tcx0, l_level_no);
            l_ry0 = opj_uint_ceildivpow2(l_tcy0, l_level_no);
            l_rx1 = opj_uint_ceildivpow2(l_tcx1, l_level_no);
            l_ry1 = opj_uint_ceildivpow2(l_tcy1, l_level_no);
            l_px0 = opj_uint_floordivpow2(l_rx0, l_pdx) << l_pdx;
            l_py0 = opj_uint_floordivpow2(l_ry0, l_pdy) << l_pdy;
            l_px1 = opj_uint_ceildivpow2(l_rx1, l_pdx) << l_pdx;
            py1 = opj_uint_ceildivpow2(l_ry1, l_pdy) << l_pdy;
            l_pw = (l_rx0 == l_rx1) ? 0 : ((l_px1 - l_px0) >> l_pdx);
            l_ph = (l_ry0 == l_ry1) ? 0 : ((py1 - l_py0) >> l_pdy);
            if (lResolutionPtr) {
                *lResolutionPtr++ = l_pw;
                *lResolutionPtr++ = l_ph;
            }
            l_product = l_pw * l_ph;

            /* update precision*/
            if (l_product > *p_max_prec) {
                *p_max_prec = l_product;
            }

        }
        ++l_tccp;
        ++l_img_comp;
    }
}

static opj_pi_iterator_t * opj_pi_create(const opj_image_t *image,
        const opj_cp_t *cp,
        OPJ_UINT32 tileno,
        opj_event_mgr_t* manager)
{
    /* loop*/
    OPJ_UINT32 pino, compno;
    /* number of poc in the p_pi*/
    OPJ_UINT32 l_poc_bound;

    /* pointers to tile coding parameters and components.*/
1010
1011
1012
1013
1014
1015
1016


1017
1018
1019
1020
1021
1022
1023
                                           sizeof(opj_pi_iterator_t));
    if (!l_pi) {
        return NULL;
    }

    l_current_pi = l_pi;
    for (pino = 0; pino < l_poc_bound ; ++pino) {



        l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps,
                              sizeof(opj_pi_comp_t));
        if (! l_current_pi->comps) {
            opj_pi_destroy(l_pi, l_poc_bound);
            return NULL;
        }







>
>







1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
                                           sizeof(opj_pi_iterator_t));
    if (!l_pi) {
        return NULL;
    }

    l_current_pi = l_pi;
    for (pino = 0; pino < l_poc_bound ; ++pino) {

        l_current_pi->manager = manager;

        l_current_pi->comps = (opj_pi_comp_t*) opj_calloc(image->numcomps,
                              sizeof(opj_pi_comp_t));
        if (! l_current_pi->comps) {
            opj_pi_destroy(l_pi, l_poc_bound);
            return NULL;
        }
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
        ++l_current_pi;
    }
    return l_pi;
}

static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp,
        OPJ_UINT32 p_tileno,
        OPJ_INT32 p_tx0,
        OPJ_INT32 p_tx1,
        OPJ_INT32 p_ty0,
        OPJ_INT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min)
{
    /* loop*/
    OPJ_UINT32 pino;







|
|
|
|







1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
        ++l_current_pi;
    }
    return l_pi;
}

static void opj_pi_update_encode_poc_and_final(opj_cp_t *p_cp,
        OPJ_UINT32 p_tileno,
        OPJ_UINT32 p_tx0,
        OPJ_UINT32 p_tx1,
        OPJ_UINT32 p_ty0,
        OPJ_UINT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min)
{
    /* loop*/
    OPJ_UINT32 pino;
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
        ++ l_current_poc;
    }
}

static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp,
        OPJ_UINT32 p_num_comps,
        OPJ_UINT32 p_tileno,
        OPJ_INT32 p_tx0,
        OPJ_INT32 p_tx1,
        OPJ_INT32 p_ty0,
        OPJ_INT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min)
{
    /* loop*/
    OPJ_UINT32 pino;







|
|
|
|







1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
        ++ l_current_poc;
    }
}

static void opj_pi_update_encode_not_poc(opj_cp_t *p_cp,
        OPJ_UINT32 p_num_comps,
        OPJ_UINT32 p_tileno,
        OPJ_UINT32 p_tx0,
        OPJ_UINT32 p_tx1,
        OPJ_UINT32 p_ty0,
        OPJ_UINT32 p_ty1,
        OPJ_UINT32 p_max_prec,
        OPJ_UINT32 p_max_res,
        OPJ_UINT32 p_dx_min,
        OPJ_UINT32 p_dy_min)
{
    /* loop*/
    OPJ_UINT32 pino;
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
        l_current_poc->resS = 0;
        l_current_poc->resE = p_max_res;
        l_current_poc->layS = 0;
        l_current_poc->layE = l_tcp->numlayers;
        l_current_poc->prg  = l_tcp->prg;
        l_current_poc->prcS = 0;
        l_current_poc->prcE = p_max_prec;
        l_current_poc->txS = (OPJ_UINT32)p_tx0;
        l_current_poc->txE = (OPJ_UINT32)p_tx1;
        l_current_poc->tyS = (OPJ_UINT32)p_ty0;
        l_current_poc->tyE = (OPJ_UINT32)p_ty1;
        l_current_poc->dx = p_dx_min;
        l_current_poc->dy = p_dy_min;
        ++ l_current_poc;
    }
}

static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi,







|
|
|
|







1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
        l_current_poc->resS = 0;
        l_current_poc->resE = p_max_res;
        l_current_poc->layS = 0;
        l_current_poc->layE = l_tcp->numlayers;
        l_current_poc->prg  = l_tcp->prg;
        l_current_poc->prcS = 0;
        l_current_poc->prcE = p_max_prec;
        l_current_poc->txS = p_tx0;
        l_current_poc->txE = p_tx1;
        l_current_poc->tyS = p_ty0;
        l_current_poc->tyE = p_ty1;
        l_current_poc->dx = p_dx_min;
        l_current_poc->dy = p_dy_min;
        ++ l_current_poc;
    }
}

static void opj_pi_update_decode_poc(opj_pi_iterator_t * p_pi,
1348
1349
1350
1351
1352
1353
1354
1355

1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
/*
==========================================================
   Packet iterator interface
==========================================================
*/
opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
                                        opj_cp_t *p_cp,
                                        OPJ_UINT32 p_tile_no)

{
    OPJ_UINT32 numcomps = p_image->numcomps;

    /* loop */
    OPJ_UINT32 pino;
    OPJ_UINT32 compno, resno;

    /* to store w, h, dx and dy fro all components and resolutions */
    OPJ_UINT32 * l_tmp_data;
    OPJ_UINT32 ** l_tmp_ptr;

    /* encoding prameters to set */
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;
    OPJ_UINT32 l_bound;
    OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ;
    OPJ_UINT32 l_data_stride;

    /* pointers */
    opj_pi_iterator_t *l_pi = 00;







|
>














|







1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
/*
==========================================================
   Packet iterator interface
==========================================================
*/
opj_pi_iterator_t *opj_pi_create_decode(opj_image_t *p_image,
                                        opj_cp_t *p_cp,
                                        OPJ_UINT32 p_tile_no,
                                        opj_event_mgr_t* manager)
{
    OPJ_UINT32 numcomps = p_image->numcomps;

    /* loop */
    OPJ_UINT32 pino;
    OPJ_UINT32 compno, resno;

    /* to store w, h, dx and dy fro all components and resolutions */
    OPJ_UINT32 * l_tmp_data;
    OPJ_UINT32 ** l_tmp_ptr;

    /* encoding prameters to set */
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_UINT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;
    OPJ_UINT32 l_bound;
    OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ;
    OPJ_UINT32 l_data_stride;

    /* pointers */
    opj_pi_iterator_t *l_pi = 00;
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
    if
    (! l_tmp_ptr) {
        opj_free(l_tmp_data);
        return 00;
    }

    /* memory allocation for pi */
    l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
    if (!l_pi) {
        opj_free(l_tmp_data);
        opj_free(l_tmp_ptr);
        return 00;
    }

    l_encoding_value_ptr = l_tmp_data;







|







1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
    if
    (! l_tmp_ptr) {
        opj_free(l_tmp_data);
        return 00;
    }

    /* memory allocation for pi */
    l_pi = opj_pi_create(p_image, p_cp, p_tile_no, manager);
    if (!l_pi) {
        opj_free(l_tmp_data);
        opj_free(l_tmp_ptr);
        return 00;
    }

    l_encoding_value_ptr = l_tmp_data;
1544
1545
1546
1547
1548
1549
1550






















1551
1552
1553
1554
1555

1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
    } else {
        opj_pi_update_decode_not_poc(l_pi, l_tcp, l_max_prec, l_max_res);
    }
    return l_pi;
}

























opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image,
        opj_cp_t *p_cp,
        OPJ_UINT32 p_tile_no,
        J2K_T2_MODE p_t2_mode)

{
    OPJ_UINT32 numcomps = p_image->numcomps;

    /* loop*/
    OPJ_UINT32 pino;
    OPJ_UINT32 compno, resno;

    /* to store w, h, dx and dy fro all components and resolutions*/
    OPJ_UINT32 * l_tmp_data;
    OPJ_UINT32 ** l_tmp_ptr;

    /* encoding prameters to set*/
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;
    OPJ_UINT32 l_bound;
    OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ;
    OPJ_UINT32 l_data_stride;

    /* pointers*/
    opj_pi_iterator_t *l_pi = 00;







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>




|
>














|







1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
    } else {
        opj_pi_update_decode_not_poc(l_pi, l_tcp, l_max_prec, l_max_res);
    }
    return l_pi;
}


OPJ_UINT32 opj_get_encoding_packet_count(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 p_tile_no)
{
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_UINT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;

    /* preconditions in debug*/
    assert(p_cp != 00);
    assert(p_image != 00);
    assert(p_tile_no < p_cp->tw * p_cp->th);

    /* get encoding parameters*/
    opj_get_all_encoding_parameters(p_image, p_cp, p_tile_no, &l_tx0, &l_tx1,
                                    &l_ty0, &l_ty1, &l_dx_min, &l_dy_min, &l_max_prec, &l_max_res, NULL);

    return p_cp->tcps[p_tile_no].numlayers * l_max_prec * p_image->numcomps *
           l_max_res;
}


opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *p_image,
        opj_cp_t *p_cp,
        OPJ_UINT32 p_tile_no,
        J2K_T2_MODE p_t2_mode,
        opj_event_mgr_t* manager)
{
    OPJ_UINT32 numcomps = p_image->numcomps;

    /* loop*/
    OPJ_UINT32 pino;
    OPJ_UINT32 compno, resno;

    /* to store w, h, dx and dy fro all components and resolutions*/
    OPJ_UINT32 * l_tmp_data;
    OPJ_UINT32 ** l_tmp_ptr;

    /* encoding prameters to set*/
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_UINT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;
    OPJ_UINT32 l_bound;
    OPJ_UINT32 l_step_p, l_step_c, l_step_r, l_step_l ;
    OPJ_UINT32 l_data_stride;

    /* pointers*/
    opj_pi_iterator_t *l_pi = 00;
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
                    numcomps * sizeof(OPJ_UINT32 *));
    if (! l_tmp_ptr) {
        opj_free(l_tmp_data);
        return 00;
    }

    /* memory allocation for pi*/
    l_pi = opj_pi_create(p_image, p_cp, p_tile_no);
    if (!l_pi) {
        opj_free(l_tmp_data);
        opj_free(l_tmp_ptr);
        return 00;
    }

    l_encoding_value_ptr = l_tmp_data;







|







1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
                    numcomps * sizeof(OPJ_UINT32 *));
    if (! l_tmp_ptr) {
        opj_free(l_tmp_data);
        return 00;
    }

    /* memory allocation for pi*/
    l_pi = opj_pi_create(p_image, p_cp, p_tile_no, manager);
    if (!l_pi) {
        opj_free(l_tmp_data);
        opj_free(l_tmp_ptr);
        return 00;
    }

    l_encoding_value_ptr = l_tmp_data;
1757
1758
1759
1760
1761
1762
1763

1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783

    prog = opj_j2k_convert_progression_order(tcp->prg);

    pi[pino].first = 1;
    pi[pino].poc.prg = tcp->prg;

    if (!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) &&

            (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz)))) {
        pi[pino].poc.resno0 = tcp->resS;
        pi[pino].poc.resno1 = tcp->resE;
        pi[pino].poc.compno0 = tcp->compS;
        pi[pino].poc.compno1 = tcp->compE;
        pi[pino].poc.layno0 = tcp->layS;
        pi[pino].poc.layno1 = tcp->layE;
        pi[pino].poc.precno0 = tcp->prcS;
        pi[pino].poc.precno1 = tcp->prcE;
        pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS;
        pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS;
        pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE;
        pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE;
    } else {
        for (i = tppos + 1; i < 4; i++) {
            switch (prog[i]) {
            case 'R':
                pi[pino].poc.resno0 = tcp->resS;
                pi[pino].poc.resno1 = tcp->resE;
                break;







>
|








|
|
|
|







1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848

    prog = opj_j2k_convert_progression_order(tcp->prg);

    pi[pino].first = 1;
    pi[pino].poc.prg = tcp->prg;

    if (!(cp->m_specific_param.m_enc.m_tp_on && ((!OPJ_IS_CINEMA(cp->rsiz) &&
            !OPJ_IS_IMF(cp->rsiz) &&
            (t2_mode == FINAL_PASS)) || OPJ_IS_CINEMA(cp->rsiz) || OPJ_IS_IMF(cp->rsiz)))) {
        pi[pino].poc.resno0 = tcp->resS;
        pi[pino].poc.resno1 = tcp->resE;
        pi[pino].poc.compno0 = tcp->compS;
        pi[pino].poc.compno1 = tcp->compE;
        pi[pino].poc.layno0 = tcp->layS;
        pi[pino].poc.layno1 = tcp->layE;
        pi[pino].poc.precno0 = tcp->prcS;
        pi[pino].poc.precno1 = tcp->prcE;
        pi[pino].poc.tx0 = tcp->txS;
        pi[pino].poc.ty0 = tcp->tyS;
        pi[pino].poc.tx1 = tcp->txE;
        pi[pino].poc.ty1 = tcp->tyE;
    } else {
        for (i = tppos + 1; i < 4; i++) {
            switch (prog[i]) {
            case 'R':
                pi[pino].poc.resno0 = tcp->resS;
                pi[pino].poc.resno1 = tcp->resE;
                break;
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
                switch (tcp->prg) {
                case OPJ_LRCP:
                case OPJ_RLCP:
                    pi[pino].poc.precno0 = tcp->prcS;
                    pi[pino].poc.precno1 = tcp->prcE;
                    break;
                default:
                    pi[pino].poc.tx0 = (OPJ_INT32)tcp->txS;
                    pi[pino].poc.ty0 = (OPJ_INT32)tcp->tyS;
                    pi[pino].poc.tx1 = (OPJ_INT32)tcp->txE;
                    pi[pino].poc.ty1 = (OPJ_INT32)tcp->tyE;
                    break;
                }
                break;
            }
        }

        if (tpnum == 0) {







|
|
|
|







1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
                switch (tcp->prg) {
                case OPJ_LRCP:
                case OPJ_RLCP:
                    pi[pino].poc.precno0 = tcp->prcS;
                    pi[pino].poc.precno1 = tcp->prcE;
                    break;
                default:
                    pi[pino].poc.tx0 = tcp->txS;
                    pi[pino].poc.ty0 = tcp->tyS;
                    pi[pino].poc.tx1 = tcp->txE;
                    pi[pino].poc.ty1 = tcp->tyE;
                    break;
                }
                break;
            }
        }

        if (tpnum == 0) {
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
                        pi[pino].poc.precno0 = tcp->prc_t;
                        pi[pino].poc.precno1 = tcp->prc_t + 1;
                        tcp->prc_t += 1;
                        break;
                    default:
                        tcp->tx0_t = tcp->txS;
                        tcp->ty0_t = tcp->tyS;
                        pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t;
                        pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx));
                        pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t;
                        pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy));
                        tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                        tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                        break;
                    }
                    break;
                }
            }







|
|
|
|







1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
                        pi[pino].poc.precno0 = tcp->prc_t;
                        pi[pino].poc.precno1 = tcp->prc_t + 1;
                        tcp->prc_t += 1;
                        break;
                    default:
                        tcp->tx0_t = tcp->txS;
                        tcp->ty0_t = tcp->tyS;
                        pi[pino].poc.tx0 = tcp->tx0_t;
                        pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
                        pi[pino].poc.ty0 = tcp->ty0_t;
                        pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
                        tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                        tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                        break;
                    }
                    break;
                }
            }
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
                    switch (tcp->prg) {
                    case OPJ_LRCP:
                    case OPJ_RLCP:
                        pi[pino].poc.precno0 = tcp->prc_t - 1;
                        pi[pino].poc.precno1 = tcp->prc_t;
                        break;
                    default:
                        pi[pino].poc.tx0 = (OPJ_INT32)(tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx));
                        pi[pino].poc.tx1 = (OPJ_INT32)tcp->tx0_t ;
                        pi[pino].poc.ty0 = (OPJ_INT32)(tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy));
                        pi[pino].poc.ty1 = (OPJ_INT32)tcp->ty0_t ;
                        break;
                    }
                    break;
                }
                if (incr_top == 1) {
                    switch (prog[i]) {
                    case 'R':







|
|
|
|







1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
                    switch (tcp->prg) {
                    case OPJ_LRCP:
                    case OPJ_RLCP:
                        pi[pino].poc.precno0 = tcp->prc_t - 1;
                        pi[pino].poc.precno1 = tcp->prc_t;
                        break;
                    default:
                        pi[pino].poc.tx0 = tcp->tx0_t - tcp->dx - (tcp->tx0_t % tcp->dx);
                        pi[pino].poc.tx1 = tcp->tx0_t ;
                        pi[pino].poc.ty0 = tcp->ty0_t - tcp->dy - (tcp->ty0_t % tcp->dy);
                        pi[pino].poc.ty1 = tcp->ty0_t ;
                        break;
                    }
                    break;
                }
                if (incr_top == 1) {
                    switch (prog[i]) {
                    case 'R':
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
                            }
                            break;
                        default:
                            if (tcp->tx0_t >= tcp->txE) {
                                if (tcp->ty0_t >= tcp->tyE) {
                                    if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) {
                                        tcp->ty0_t = tcp->tyS;
                                        pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t;
                                        pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy));
                                        tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                                        incr_top = 1;
                                        resetX = 1;
                                    } else {
                                        incr_top = 0;
                                        resetX = 0;
                                    }
                                } else {
                                    pi[pino].poc.ty0 = (OPJ_INT32)tcp->ty0_t;
                                    pi[pino].poc.ty1 = (OPJ_INT32)(tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy));
                                    tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                                    incr_top = 0;
                                    resetX = 1;
                                }
                                if (resetX == 1) {
                                    tcp->tx0_t = tcp->txS;
                                    pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t;
                                    pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx));
                                    tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                                }
                            } else {
                                pi[pino].poc.tx0 = (OPJ_INT32)tcp->tx0_t;
                                pi[pino].poc.tx1 = (OPJ_INT32)(tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx));
                                tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                                incr_top = 0;
                            }
                            break;
                        }
                        break;
                    }







|
|








|
|






|
|



|
|







2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
                            }
                            break;
                        default:
                            if (tcp->tx0_t >= tcp->txE) {
                                if (tcp->ty0_t >= tcp->tyE) {
                                    if (opj_pi_check_next_level(i - 1, cp, tileno, pino, prog)) {
                                        tcp->ty0_t = tcp->tyS;
                                        pi[pino].poc.ty0 = tcp->ty0_t;
                                        pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
                                        tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                                        incr_top = 1;
                                        resetX = 1;
                                    } else {
                                        incr_top = 0;
                                        resetX = 0;
                                    }
                                } else {
                                    pi[pino].poc.ty0 = tcp->ty0_t;
                                    pi[pino].poc.ty1 = tcp->ty0_t + tcp->dy - (tcp->ty0_t % tcp->dy);
                                    tcp->ty0_t = (OPJ_UINT32)pi[pino].poc.ty1;
                                    incr_top = 0;
                                    resetX = 1;
                                }
                                if (resetX == 1) {
                                    tcp->tx0_t = tcp->txS;
                                    pi[pino].poc.tx0 = tcp->tx0_t;
                                    pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
                                    tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                                }
                            } else {
                                pi[pino].poc.tx0 = tcp->tx0_t;
                                pi[pino].poc.tx1 = tcp->tx0_t + tcp->dx - (tcp->tx0_t % tcp->dx);
                                tcp->tx0_t = (OPJ_UINT32)pi[pino].poc.tx1;
                                incr_top = 0;
                            }
                            break;
                        }
                        break;
                    }
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
void opj_pi_update_encoding_parameters(const opj_image_t *p_image,
                                       opj_cp_t *p_cp,
                                       OPJ_UINT32 p_tile_no)
{
    /* encoding parameters to set */
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_INT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;

    /* pointers */
    opj_tcp_t *l_tcp = 00;

    /* preconditions */
    assert(p_cp != 00);







|







2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
void opj_pi_update_encoding_parameters(const opj_image_t *p_image,
                                       opj_cp_t *p_cp,
                                       OPJ_UINT32 p_tile_no)
{
    /* encoding parameters to set */
    OPJ_UINT32 l_max_res;
    OPJ_UINT32 l_max_prec;
    OPJ_UINT32 l_tx0, l_tx1, l_ty0, l_ty1;
    OPJ_UINT32 l_dx_min, l_dy_min;

    /* pointers */
    opj_tcp_t *l_tcp = 00;

    /* preconditions */
    assert(p_cp != 00);
Changes to jni/openjpeg/src/lib/openjp2/pi.h.
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
    /** progression order change information */
    opj_poc_t poc;
    /** number of components in the image */
    OPJ_UINT32 numcomps;
    /** Components*/
    opj_pi_comp_t *comps;
    /** FIXME DOC*/
    OPJ_INT32 tx0, ty0, tx1, ty1;
    /** FIXME DOC*/
    OPJ_INT32 x, y;
    /** FIXME DOC*/
    OPJ_UINT32 dx, dy;


} opj_pi_iterator_t;

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */
/**
 * Creates a packet iterator for encoding.
 *
 * @param   image       the image being encoded.
 * @param   cp      the coding parameters.
 * @param   tileno  index of the tile being encoded.
 * @param   t2_mode the type of pass for generating the packet iterator

 *
 * @return  a list of packet iterator that points to the first packet of the tile (not true).
*/
opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *image,
        opj_cp_t *cp,
        OPJ_UINT32 tileno,
        J2K_T2_MODE t2_mode);


/**
 * Updates the encoding parameters of the codec.
 *
 * @param   p_image     the image being encoded.
 * @param   p_cp        the coding parameters.
 * @param   p_tile_no   index of the tile being encoded.







|

|


>
>












>






|
>







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
    /** progression order change information */
    opj_poc_t poc;
    /** number of components in the image */
    OPJ_UINT32 numcomps;
    /** Components*/
    opj_pi_comp_t *comps;
    /** FIXME DOC*/
    OPJ_UINT32 tx0, ty0, tx1, ty1;
    /** FIXME DOC*/
    OPJ_UINT32 x, y;
    /** FIXME DOC*/
    OPJ_UINT32 dx, dy;
    /** event manager */
    opj_event_mgr_t* manager;
} opj_pi_iterator_t;

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */
/**
 * Creates a packet iterator for encoding.
 *
 * @param   image       the image being encoded.
 * @param   cp      the coding parameters.
 * @param   tileno  index of the tile being encoded.
 * @param   t2_mode the type of pass for generating the packet iterator
 * @param   manager Event manager
 *
 * @return  a list of packet iterator that points to the first packet of the tile (not true).
*/
opj_pi_iterator_t *opj_pi_initialise_encode(const opj_image_t *image,
        opj_cp_t *cp,
        OPJ_UINT32 tileno,
        J2K_T2_MODE t2_mode,
        opj_event_mgr_t* manager);

/**
 * Updates the encoding parameters of the codec.
 *
 * @param   p_image     the image being encoded.
 * @param   p_cp        the coding parameters.
 * @param   p_tile_no   index of the tile being encoded.
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
                          J2K_T2_MODE t2_mode);

/**
Create a packet iterator for Decoder
@param image Raw image for which the packets will be listed
@param cp Coding parameters
@param tileno Number that identifies the tile for which to list the packets

@return Returns a packet iterator that points to the first packet of the tile
@see opj_pi_destroy
*/
opj_pi_iterator_t *opj_pi_create_decode(opj_image_t * image,
                                        opj_cp_t * cp,
                                        OPJ_UINT32 tileno);

/**
 * Destroys a packet iterator array.
 *
 * @param   p_pi            the packet iterator array to destroy.
 * @param   p_nb_elements   the number of elements in the array.
 */
void opj_pi_destroy(opj_pi_iterator_t *p_pi,
                    OPJ_UINT32 p_nb_elements);

/**
Modify the packet iterator to point to the next packet
@param pi Packet iterator to modify
@return Returns false if pi pointed to the last packet or else returns true
*/
OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi);











/* ----------------------------------------------------------------------- */
/*@}*/

/*@}*/

#endif /* OPJ_PI_H */







>





|
>















>
>
>
>
>
>
>
>
>
>
>






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
                          J2K_T2_MODE t2_mode);

/**
Create a packet iterator for Decoder
@param image Raw image for which the packets will be listed
@param cp Coding parameters
@param tileno Number that identifies the tile for which to list the packets
@param manager Event manager
@return Returns a packet iterator that points to the first packet of the tile
@see opj_pi_destroy
*/
opj_pi_iterator_t *opj_pi_create_decode(opj_image_t * image,
                                        opj_cp_t * cp,
                                        OPJ_UINT32 tileno,
                                        opj_event_mgr_t* manager);
/**
 * Destroys a packet iterator array.
 *
 * @param   p_pi            the packet iterator array to destroy.
 * @param   p_nb_elements   the number of elements in the array.
 */
void opj_pi_destroy(opj_pi_iterator_t *p_pi,
                    OPJ_UINT32 p_nb_elements);

/**
Modify the packet iterator to point to the next packet
@param pi Packet iterator to modify
@return Returns false if pi pointed to the last packet or else returns true
*/
OPJ_BOOL opj_pi_next(opj_pi_iterator_t * pi);

/**
 * Return the number of packets in the tile.
 * @param   image       the image being encoded.
 * @param cp Coding parameters
 * @param tileno Number that identifies the tile.
 */
OPJ_UINT32 opj_get_encoding_packet_count(const opj_image_t *p_image,
        const opj_cp_t *p_cp,
        OPJ_UINT32 p_tile_no);

/* ----------------------------------------------------------------------- */
/*@}*/

/*@}*/

#endif /* OPJ_PI_H */
Changes to jni/openjpeg/src/lib/openjp2/t1.c.
56
57
58
59
60
61
62







63
64
65
66
67
68
69

/** @defgroup T1 T1 - Implementation of the tier-1 coding */
/*@{*/

#define T1_FLAGS(x, y) (t1->flags[x + 1 + ((y / 4) + 1) * (t1->w+2)])

#define opj_t1_setcurctx(curctx, ctxno)  curctx = &(mqc)->ctxs[(OPJ_UINT32)(ctxno)]








/** @name Local static functions */
/*@{*/

static INLINE OPJ_BYTE opj_t1_getctxno_zc(opj_mqc_t *mqc, OPJ_UINT32 f);
static INLINE OPJ_UINT32 opj_t1_getctxno_mag(OPJ_UINT32 f);
static OPJ_INT16 opj_t1_getnmsedec_sig(OPJ_UINT32 x, OPJ_UINT32 bitpos);







>
>
>
>
>
>
>







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76

/** @defgroup T1 T1 - Implementation of the tier-1 coding */
/*@{*/

#define T1_FLAGS(x, y) (t1->flags[x + 1 + ((y / 4) + 1) * (t1->w+2)])

#define opj_t1_setcurctx(curctx, ctxno)  curctx = &(mqc)->ctxs[(OPJ_UINT32)(ctxno)]

/* Macros to deal with signed integer with just MSB bit set for
 * negative values (smr = signed magnitude representation) */
#define opj_smr_abs(x)  (((OPJ_UINT32)(x)) & 0x7FFFFFFFU)
#define opj_smr_sign(x) (((OPJ_UINT32)(x)) >> 31)
#define opj_to_smr(x)   ((x) >= 0 ? (OPJ_UINT32)(x) : ((OPJ_UINT32)(-x) | 0x80000000U))


/** @name Local static functions */
/*@{*/

static INLINE OPJ_BYTE opj_t1_getctxno_zc(opj_mqc_t *mqc, OPJ_UINT32 f);
static INLINE OPJ_UINT32 opj_t1_getctxno_mag(OPJ_UINT32 f);
static OPJ_INT16 opj_t1_getnmsedec_sig(OPJ_UINT32 x, OPJ_UINT32 bitpos);
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
    OPJ_INT32 bpno,
    OPJ_UINT32 qmfbid,
    OPJ_FLOAT64 stepsize,
    OPJ_UINT32 numcomps,
    const OPJ_FLOAT64 * mct_norms,
    OPJ_UINT32 mct_numcomps);


static void opj_t1_encode_cblk(opj_t1_t *t1,
                               opj_tcd_cblk_enc_t* cblk,
                               OPJ_UINT32 orient,
                               OPJ_UINT32 compno,
                               OPJ_UINT32 level,
                               OPJ_UINT32 qmfbid,
                               OPJ_FLOAT64 stepsize,
                               OPJ_UINT32 cblksty,
                               OPJ_UINT32 numcomps,
                               opj_tcd_tile_t * tile,
                               const OPJ_FLOAT64 * mct_norms,
                               OPJ_UINT32 mct_numcomps);

/**
Decode 1 code-block
@param t1 T1 handle
@param cblk Code-block coding parameters
@param orient
@param roishift Region of interest shifting value







>
|
|
|
|
|
|
|
|
|
<
|
|







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
    OPJ_INT32 bpno,
    OPJ_UINT32 qmfbid,
    OPJ_FLOAT64 stepsize,
    OPJ_UINT32 numcomps,
    const OPJ_FLOAT64 * mct_norms,
    OPJ_UINT32 mct_numcomps);

/** Return "cumwmsedec" that should be used to increase tile->distotile */
static double opj_t1_encode_cblk(opj_t1_t *t1,
                                 opj_tcd_cblk_enc_t* cblk,
                                 OPJ_UINT32 orient,
                                 OPJ_UINT32 compno,
                                 OPJ_UINT32 level,
                                 OPJ_UINT32 qmfbid,
                                 OPJ_FLOAT64 stepsize,
                                 OPJ_UINT32 cblksty,
                                 OPJ_UINT32 numcomps,

                                 const OPJ_FLOAT64 * mct_norms,
                                 OPJ_UINT32 mct_numcomps);

/**
Decode 1 code-block
@param t1 T1 handle
@param cblk Code-block coding parameters
@param orient
@param roishift Region of interest shifting value
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
{
    opj_t1_update_flags_macro(*flagsp, flagsp, ci, s, stride, vsc);
}

/**
Encode significant pass
*/
static INLINE void opj_t1_enc_sigpass_step(opj_t1_t *t1,
        opj_flag_t *flagsp,
        OPJ_INT32 *datap,
        OPJ_INT32 bpno,
        OPJ_INT32 one,
        OPJ_INT32 *nmsedec,
        OPJ_BYTE type,
        OPJ_UINT32 ci,
        OPJ_UINT32 vsc)
{
    OPJ_UINT32 v;

    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */

    OPJ_UINT32 const flags = *flagsp;

    if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == 0U &&
            (flags & (T1_SIGMA_NEIGHBOURS << (ci * 3U))) != 0U) {
        OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U));
        v = (opj_int_abs(*datap) & one) ? 1 : 0;
#ifdef DEBUG_ENC_SIG
        fprintf(stderr, "   ctxt1=%d\n", ctxt1);
#endif
        opj_mqc_setcurctx(mqc, ctxt1);
        if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */
            opj_mqc_bypass_enc(mqc, v);
        } else {
            opj_mqc_encode(mqc, v);
        }
        if (v) {
            OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index(
                                *flagsp,
                                flagsp[-1], flagsp[1],
                                ci);
            OPJ_UINT32 ctxt2 = opj_t1_getctxno_sc(lu);
            v = *datap < 0 ? 1U : 0U;
            *nmsedec += opj_t1_getnmsedec_sig((OPJ_UINT32)opj_int_abs(*datap),
                                              (OPJ_UINT32)bpno);
#ifdef DEBUG_ENC_SIG
            fprintf(stderr, "   ctxt2=%d\n", ctxt2);
#endif
            opj_mqc_setcurctx(mqc, ctxt2);
            if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */
                opj_mqc_bypass_enc(mqc, v);
            } else {
                OPJ_UINT32 spb = opj_t1_getspb(lu);
#ifdef DEBUG_ENC_SIG
                fprintf(stderr, "   spb=%d\n", spb);
#endif
                opj_mqc_encode(mqc, v ^ spb);
            }
            opj_t1_update_flags(flagsp, ci, v, t1->w + 2, vsc);
        }
        *flagsp |= T1_PI_THIS << (ci * 3U);
    }
}

static INLINE void opj_t1_dec_sigpass_step_raw(
    opj_t1_t *t1,
    opj_flag_t *flagsp,
    OPJ_INT32 *datap,
    OPJ_INT32 oneplushalf,







|
<
<
<
|
<
<
|
|
<
|
|
<
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|







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
{
    opj_t1_update_flags_macro(*flagsp, flagsp, ci, s, stride, vsc);
}

/**
Encode significant pass
*/
#define opj_t1_enc_sigpass_step_macro(mqc, curctx, a, c, ct, flagspIn, datapIn, bpno, one, nmsedec, type, ciIn, vscIn) \



{ \


    OPJ_UINT32 v; \
    const OPJ_UINT32 ci = (ciIn); \

    const OPJ_UINT32 vsc = (vscIn); \
    const OPJ_INT32* l_datap = (datapIn); \

    opj_flag_t* flagsp = (flagspIn); \
    OPJ_UINT32 const flags = *flagsp; \

    if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U))) == 0U && \
            (flags & (T1_SIGMA_NEIGHBOURS << (ci * 3U))) != 0U) { \
        OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U)); \
        v = (opj_smr_abs(*l_datap) & (OPJ_UINT32)one) ? 1 : 0; \
/* #ifdef DEBUG_ENC_SIG */ \
/*        fprintf(stderr, "   ctxt1=%d\n", ctxt1); */ \
/* #endif */ \
        opj_t1_setcurctx(curctx, ctxt1); \
        if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */ \
            opj_mqc_bypass_enc_macro(mqc, c, ct, v); \
        } else { \
            opj_mqc_encode_macro(mqc, curctx, a, c, ct, v); \
        } \
        if (v) { \
            OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index( \
                                *flagsp, \
                                flagsp[-1], flagsp[1], \
                                ci); \
            OPJ_UINT32 ctxt2 = opj_t1_getctxno_sc(lu); \
            v = opj_smr_sign(*l_datap); \
            *nmsedec += opj_t1_getnmsedec_sig(opj_smr_abs(*l_datap), \
                                              (OPJ_UINT32)bpno); \
/* #ifdef DEBUG_ENC_SIG */ \
/*            fprintf(stderr, "   ctxt2=%d\n", ctxt2); */ \
/* #endif */ \
            opj_t1_setcurctx(curctx, ctxt2); \
            if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */ \
                opj_mqc_bypass_enc_macro(mqc, c, ct, v); \
            } else { \
                OPJ_UINT32 spb = opj_t1_getspb(lu); \
/* #ifdef DEBUG_ENC_SIG */ \
/*                fprintf(stderr, "   spb=%d\n", spb); */ \
/* #endif */ \
                opj_mqc_encode_macro(mqc, curctx, a, c, ct, v ^ spb); \
            } \
            opj_t1_update_flags(flagsp, ci, v, t1->w + 2, vsc); \
        } \
        *flagsp |= T1_PI_THIS << (ci * 3U); \
    } \
}

static INLINE void opj_t1_dec_sigpass_step_raw(
    opj_t1_t *t1,
    opj_flag_t *flagsp,
    OPJ_INT32 *datap,
    OPJ_INT32 oneplushalf,
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
                               OPJ_UINT32 cblksty
                              )
{
    OPJ_UINT32 i, k;
    OPJ_INT32 const one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
    opj_flag_t* f = &T1_FLAGS(0, 0);
    OPJ_UINT32 const extra = 2;




    *nmsedec = 0;
#ifdef DEBUG_ENC_SIG
    fprintf(stderr, "enc_sigpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4) {

#ifdef DEBUG_ENC_SIG
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_SIG
            fprintf(stderr, " i=%d\n", i);
#endif
            if (*f == 0U) {
                /* Nothing to do for any of the 4 data points */
                f++;
                continue;
            }
            opj_t1_enc_sigpass_step(
                t1,

                f,
                &t1->data[((k + 0) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                0, cblksty & J2K_CCP_CBLKSTY_VSC);
            opj_t1_enc_sigpass_step(
                t1,
                f,
                &t1->data[((k + 1) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                1, 0);
            opj_t1_enc_sigpass_step(
                t1,
                f,
                &t1->data[((k + 2) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                2, 0);
            opj_t1_enc_sigpass_step(
                t1,
                f,
                &t1->data[((k + 3) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                3, 0);
            ++f;
        }
        f += extra;
    }

    if (k < t1->h) {
        OPJ_UINT32 j;
#ifdef DEBUG_ENC_SIG
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_SIG
            fprintf(stderr, " i=%d\n", i);
#endif
            if (*f == 0U) {
                /* Nothing to do for any of the 4 data points */
                f++;
                continue;
            }
            for (j = k; j < t1->h; ++j) {
                opj_t1_enc_sigpass_step(
                    t1,
                    f,
                    &t1->data[(j * t1->data_stride) + i],
                    bpno,
                    one,
                    nmsedec,
                    type,
                    j - k,
                    (j == k && (cblksty & J2K_CCP_CBLKSTY_VSC) != 0));
            }
            ++f;
        }
    }


}

static void opj_t1_dec_sigpass_raw(
    opj_t1_t *t1,
    OPJ_INT32 bpno,
    OPJ_INT32 cblksty)
{







>
>
>





|
>



|





<


|
<
>

|





|
|

|





|
|

|





|
|

|





<

<







|





|


|
|
|

|







<


>
>







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
                               OPJ_UINT32 cblksty
                              )
{
    OPJ_UINT32 i, k;
    OPJ_INT32 const one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
    opj_flag_t* f = &T1_FLAGS(0, 0);
    OPJ_UINT32 const extra = 2;
    opj_mqc_t* mqc = &(t1->mqc);
    DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
    const OPJ_INT32* datap = t1->data;

    *nmsedec = 0;
#ifdef DEBUG_ENC_SIG
    fprintf(stderr, "enc_sigpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4, f += extra) {
        const OPJ_UINT32 w = t1->w;
#ifdef DEBUG_ENC_SIG
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < w; ++i, ++f, datap += 4) {
#ifdef DEBUG_ENC_SIG
            fprintf(stderr, " i=%d\n", i);
#endif
            if (*f == 0U) {
                /* Nothing to do for any of the 4 data points */

                continue;
            }
            opj_t1_enc_sigpass_step_macro(

                mqc, curctx, a, c, ct,
                f,
                &datap[0],
                bpno,
                one,
                nmsedec,
                type,
                0, cblksty & J2K_CCP_CBLKSTY_VSC);
            opj_t1_enc_sigpass_step_macro(
                mqc, curctx, a, c, ct,
                f,
                &datap[1],
                bpno,
                one,
                nmsedec,
                type,
                1, 0);
            opj_t1_enc_sigpass_step_macro(
                mqc, curctx, a, c, ct,
                f,
                &datap[2],
                bpno,
                one,
                nmsedec,
                type,
                2, 0);
            opj_t1_enc_sigpass_step_macro(
                mqc, curctx, a, c, ct,
                f,
                &datap[3],
                bpno,
                one,
                nmsedec,
                type,
                3, 0);

        }

    }

    if (k < t1->h) {
        OPJ_UINT32 j;
#ifdef DEBUG_ENC_SIG
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i, ++f) {
#ifdef DEBUG_ENC_SIG
            fprintf(stderr, " i=%d\n", i);
#endif
            if (*f == 0U) {
                /* Nothing to do for any of the 4 data points */
                datap += (t1->h - k);
                continue;
            }
            for (j = k; j < t1->h; ++j, ++datap) {
                opj_t1_enc_sigpass_step_macro(
                    mqc, curctx, a, c, ct,
                    f,
                    &datap[0],
                    bpno,
                    one,
                    nmsedec,
                    type,
                    j - k,
                    (j == k && (cblksty & J2K_CCP_CBLKSTY_VSC) != 0));
            }

        }
    }

    UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
}

static void opj_t1_dec_sigpass_raw(
    opj_t1_t *t1,
    OPJ_INT32 bpno,
    OPJ_INT32 cblksty)
{
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
{ \
        OPJ_INT32 one, half, oneplushalf; \
        OPJ_UINT32 i, j, k; \
        register OPJ_INT32 *data = t1->data; \
        register opj_flag_t *flagsp = &t1->flags[(flags_stride) + 1]; \
        const OPJ_UINT32 l_w = w; \
        opj_mqc_t* mqc = &(t1->mqc); \
        DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
        register OPJ_UINT32 v; \
        one = 1 << bpno; \
        half = one >> 1; \
        oneplushalf = one | half; \
        for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
                for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                        opj_flag_t flags = *flagsp; \







|







623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
{ \
        OPJ_INT32 one, half, oneplushalf; \
        OPJ_UINT32 i, j, k; \
        register OPJ_INT32 *data = t1->data; \
        register opj_flag_t *flagsp = &t1->flags[(flags_stride) + 1]; \
        const OPJ_UINT32 l_w = w; \
        opj_mqc_t* mqc = &(t1->mqc); \
        DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
        register OPJ_UINT32 v; \
        one = 1 << bpno; \
        half = one >> 1; \
        oneplushalf = one | half; \
        for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
                for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                        opj_flag_t flags = *flagsp; \
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
                            opj_t1_dec_sigpass_step_mqc_macro( \
                                flags, flagsp, flags_stride, data, \
                                l_w, 3, mqc, curctx, v, a, c, ct, oneplushalf, OPJ_FALSE); \
                            *flagsp = flags; \
                        } \
                } \
        } \
        UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
        if( k < h ) { \
            for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                for (j = 0; j < h - k; ++j) { \
                        opj_t1_dec_sigpass_step_mqc(t1, flagsp, \
                            data + j * l_w, oneplushalf, j, flags_stride, vsc); \
                } \
            } \







|







648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
                            opj_t1_dec_sigpass_step_mqc_macro( \
                                flags, flagsp, flags_stride, data, \
                                l_w, 3, mqc, curctx, v, a, c, ct, oneplushalf, OPJ_FALSE); \
                            *flagsp = flags; \
                        } \
                } \
        } \
        UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
        if( k < h ) { \
            for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                for (j = 0; j < h - k; ++j) { \
                        opj_t1_dec_sigpass_step_mqc(t1, flagsp, \
                            data + j * l_w, oneplushalf, j, flags_stride, vsc); \
                } \
            } \
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735

736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
        }
    }
}

/**
Encode refinement pass step
*/
static INLINE void opj_t1_enc_refpass_step(opj_t1_t *t1,
        opj_flag_t *flagsp,
        OPJ_INT32 *datap,
        OPJ_INT32 bpno,
        OPJ_INT32 one,
        OPJ_INT32 *nmsedec,
        OPJ_BYTE type,
        OPJ_UINT32 ci)
{
    OPJ_UINT32 v;

    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */

    OPJ_UINT32 const shift_flags =
        (*flagsp >> (ci * 3U));

    if ((shift_flags & (T1_SIGMA_THIS | T1_PI_THIS)) == T1_SIGMA_THIS) {
        OPJ_UINT32 ctxt = opj_t1_getctxno_mag(shift_flags);

        *nmsedec += opj_t1_getnmsedec_ref((OPJ_UINT32)opj_int_abs(*datap),
                                          (OPJ_UINT32)bpno);
        v = (opj_int_abs(*datap) & one) ? 1 : 0;
#ifdef DEBUG_ENC_REF
        fprintf(stderr, "  ctxt=%d\n", ctxt);
#endif
        opj_mqc_setcurctx(mqc, ctxt);
        if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */
            opj_mqc_bypass_enc(mqc, v);
        } else {
            opj_mqc_encode(mqc, v);
        }
        *flagsp |= T1_MU_THIS << (ci * 3U);
    }
}


static INLINE void opj_t1_dec_refpass_step_raw(
    opj_t1_t *t1,
    opj_flag_t *flagsp,
    OPJ_INT32 *datap,







|
<
<
<
<
<
<
<
|
|
|
<
|
<
<
<
<
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
|







712
713
714
715
716
717
718
719







720
721
722

723




724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
        }
    }
}

/**
Encode refinement pass step
*/
#define opj_t1_enc_refpass_step_macro(mqc, curctx, a, c, ct, flags, flagsUpdated, datap, bpno, one, nmsedec, type, ci) \







{\
    OPJ_UINT32 v; \
    if ((flags & ((T1_SIGMA_THIS | T1_PI_THIS) << ((ci) * 3U))) == (T1_SIGMA_THIS << ((ci) * 3U))) { \

        const OPJ_UINT32 shift_flags = (flags >> ((ci) * 3U)); \




        OPJ_UINT32 ctxt = opj_t1_getctxno_mag(shift_flags); \
        OPJ_UINT32 abs_data = opj_smr_abs(*datap); \
        *nmsedec += opj_t1_getnmsedec_ref(abs_data, \
                                          (OPJ_UINT32)bpno); \
        v = ((OPJ_INT32)abs_data & one) ? 1 : 0; \
/* #ifdef DEBUG_ENC_REF */ \
/*        fprintf(stderr, "  ctxt=%d\n", ctxt); */ \
/* #endif */ \
        opj_t1_setcurctx(curctx, ctxt); \
        if (type == T1_TYPE_RAW) {  /* BYPASS/LAZY MODE */ \
            opj_mqc_bypass_enc_macro(mqc, c, ct, v); \
        } else { \
            opj_mqc_encode_macro(mqc, curctx, a, c, ct, v); \
        } \
        flagsUpdated |= T1_MU_THIS << ((ci) * 3U); \
    } \
}


static INLINE void opj_t1_dec_refpass_step_raw(
    opj_t1_t *t1,
    opj_flag_t *flagsp,
    OPJ_INT32 *datap,
803
804
805
806
807
808
809



810
811
812
813
814
815
816
817
818
819


820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835


836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877

878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903


904
905
906
907
908
909
910
    OPJ_INT32 *nmsedec,
    OPJ_BYTE type)
{
    OPJ_UINT32 i, k;
    const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
    opj_flag_t* f = &T1_FLAGS(0, 0);
    const OPJ_UINT32 extra = 2U;




    *nmsedec = 0;
#ifdef DEBUG_ENC_REF
    fprintf(stderr, "enc_refpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4) {
#ifdef DEBUG_ENC_REF
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {


#ifdef DEBUG_ENC_REF
            fprintf(stderr, " i=%d\n", i);
#endif
            if ((*f & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
                /* none significant */
                f++;
                continue;
            }
            if ((*f & (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) ==
                    (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) {
                /* all processed by sigpass */
                f++;
                continue;
            }

            opj_t1_enc_refpass_step(


                t1,
                f,
                &t1->data[((k + 0) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                0);
            opj_t1_enc_refpass_step(
                t1,
                f,
                &t1->data[((k + 1) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                1);
            opj_t1_enc_refpass_step(
                t1,
                f,
                &t1->data[((k + 2) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                2);
            opj_t1_enc_refpass_step(
                t1,
                f,
                &t1->data[((k + 3) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                type,
                3);
            ++f;
        }
        f += extra;
    }

    if (k < t1->h) {
        OPJ_UINT32 j;

#ifdef DEBUG_ENC_REF
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_REF
            fprintf(stderr, " i=%d\n", i);
#endif
            if ((*f & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
                /* none significant */
                f++;
                continue;
            }
            for (j = k; j < t1->h; ++j) {
                opj_t1_enc_refpass_step(
                    t1,
                    f,
                    &t1->data[(j * t1->data_stride) + i],
                    bpno,
                    one,
                    nmsedec,
                    type,
                    j - k);
            }
            ++f;
        }
    }


}


static void opj_t1_dec_refpass_raw(
    opj_t1_t *t1,
    OPJ_INT32 bpno)
{







>
>
>





|



|
>
>



|

<


|


<



|
>
>
|
<
<





|
|
|
|





|
|
|
|





|
|
|
|





|

<




>



|





|


|
|
|
|
|




|

<


>
>







793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819

820
821
822
823
824

825
826
827
828
829
830
831


832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865

866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893

894
895
896
897
898
899
900
901
902
903
904
    OPJ_INT32 *nmsedec,
    OPJ_BYTE type)
{
    OPJ_UINT32 i, k;
    const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
    opj_flag_t* f = &T1_FLAGS(0, 0);
    const OPJ_UINT32 extra = 2U;
    opj_mqc_t* mqc = &(t1->mqc);
    DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
    const OPJ_INT32* datap = t1->data;

    *nmsedec = 0;
#ifdef DEBUG_ENC_REF
    fprintf(stderr, "enc_refpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4, f += extra) {
#ifdef DEBUG_ENC_REF
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i, f++, datap += 4) {
            const OPJ_UINT32 flags = *f;
            OPJ_UINT32 flagsUpdated = flags;
#ifdef DEBUG_ENC_REF
            fprintf(stderr, " i=%d\n", i);
#endif
            if ((flags & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
                /* none significant */

                continue;
            }
            if ((flags & (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) ==
                    (T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3)) {
                /* all processed by sigpass */

                continue;
            }

            opj_t1_enc_refpass_step_macro(
                mqc, curctx, a, c, ct,
                flags, flagsUpdated,
                &datap[0],


                bpno,
                one,
                nmsedec,
                type,
                0);
            opj_t1_enc_refpass_step_macro(
                mqc, curctx, a, c, ct,
                flags, flagsUpdated,
                &datap[1],
                bpno,
                one,
                nmsedec,
                type,
                1);
            opj_t1_enc_refpass_step_macro(
                mqc, curctx, a, c, ct,
                flags, flagsUpdated,
                &datap[2],
                bpno,
                one,
                nmsedec,
                type,
                2);
            opj_t1_enc_refpass_step_macro(
                mqc, curctx, a, c, ct,
                flags, flagsUpdated,
                &datap[3],
                bpno,
                one,
                nmsedec,
                type,
                3);
            *f = flagsUpdated;
        }

    }

    if (k < t1->h) {
        OPJ_UINT32 j;
        const OPJ_UINT32 remaining_lines = t1->h - k;
#ifdef DEBUG_ENC_REF
        fprintf(stderr, " k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i, ++f) {
#ifdef DEBUG_ENC_REF
            fprintf(stderr, " i=%d\n", i);
#endif
            if ((*f & (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13)) == 0) {
                /* none significant */
                datap += remaining_lines;
                continue;
            }
            for (j = 0; j < remaining_lines; ++j, datap ++) {
                opj_t1_enc_refpass_step_macro(
                    mqc, curctx, a, c, ct,
                    *f, *f,
                    &datap[0],
                    bpno,
                    one,
                    nmsedec,
                    type,
                    j);
            }

        }
    }

    UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
}


static void opj_t1_dec_refpass_raw(
    opj_t1_t *t1,
    OPJ_INT32 bpno)
{
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
{ \
        OPJ_INT32 one, poshalf; \
        OPJ_UINT32 i, j, k; \
        register OPJ_INT32 *data = t1->data; \
        register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
        const OPJ_UINT32 l_w = w; \
        opj_mqc_t* mqc = &(t1->mqc); \
        DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
        register OPJ_UINT32 v; \
        one = 1 << bpno; \
        poshalf = one >> 1; \
        for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
                for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                        opj_flag_t flags = *flagsp; \
                        if( flags != 0 ) { \







|







958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
{ \
        OPJ_INT32 one, poshalf; \
        OPJ_UINT32 i, j, k; \
        register OPJ_INT32 *data = t1->data; \
        register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
        const OPJ_UINT32 l_w = w; \
        opj_mqc_t* mqc = &(t1->mqc); \
        DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
        register OPJ_UINT32 v; \
        one = 1 << bpno; \
        poshalf = one >> 1; \
        for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
                for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                        opj_flag_t flags = *flagsp; \
                        if( flags != 0 ) { \
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
                            opj_t1_dec_refpass_step_mqc_macro( \
                                flags, data, l_w, 3, \
                                mqc, curctx, v, a, c, ct, poshalf); \
                            *flagsp = flags; \
                        } \
                } \
        } \
        UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
        if( k < h ) { \
            for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                for (j = 0; j < h - k; ++j) { \
                        opj_t1_dec_refpass_step_mqc(t1, flagsp, data + j * l_w, poshalf, j); \
                } \
            } \
        } \







|







982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
                            opj_t1_dec_refpass_step_mqc_macro( \
                                flags, data, l_w, 3, \
                                mqc, curctx, v, a, c, ct, poshalf); \
                            *flagsp = flags; \
                        } \
                } \
        } \
        UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
        if( k < h ) { \
            for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
                for (j = 0; j < h - k; ++j) { \
                        opj_t1_dec_refpass_step_mqc(t1, flagsp, data + j * l_w, poshalf, j); \
                } \
            } \
        } \
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048

1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065


1066
1067

1068
1069

1070
1071


1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
        opj_t1_dec_refpass_mqc_generic(t1, bpno);
    }
}

/**
Encode clean-up pass step
*/
static void opj_t1_enc_clnpass_step(
    opj_t1_t *t1,
    opj_flag_t *flagsp,
    OPJ_INT32 *datap,
    OPJ_INT32 bpno,
    OPJ_INT32 one,
    OPJ_INT32 *nmsedec,
    OPJ_UINT32 agg,
    OPJ_UINT32 runlen,
    OPJ_UINT32 lim,
    OPJ_UINT32 cblksty)
{
    OPJ_UINT32 v;
    OPJ_UINT32 ci;
    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */


    const OPJ_UINT32 check = (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13 |
                              T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);

    if ((*flagsp & check) == check) {
        if (runlen == 0) {
            *flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3);
        } else if (runlen == 1) {
            *flagsp &= ~(T1_PI_1 | T1_PI_2 | T1_PI_3);
        } else if (runlen == 2) {
            *flagsp &= ~(T1_PI_2 | T1_PI_3);
        } else if (runlen == 3) {
            *flagsp &= ~(T1_PI_3);
        }
        return;
    }

    for (ci = runlen; ci < lim; ++ci) {


        OPJ_UINT32 vsc;
        opj_flag_t flags;

        OPJ_UINT32 ctxt1;


        flags = *flagsp;



        if ((agg != 0) && (ci == runlen)) {
            goto LABEL_PARTIAL;
        }

        if (!(flags & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U)))) {
            ctxt1 = opj_t1_getctxno_zc(mqc, flags >> (ci * 3U));
#ifdef DEBUG_ENC_CLN
            printf("   ctxt1=%d\n", ctxt1);
#endif
            opj_mqc_setcurctx(mqc, ctxt1);
            v = (opj_int_abs(*datap) & one) ? 1 : 0;
            opj_mqc_encode(mqc, v);
            if (v) {
                OPJ_UINT32 ctxt2, spb;
                OPJ_UINT32 lu;
LABEL_PARTIAL:
                lu = opj_t1_getctxtno_sc_or_spb_index(
                         *flagsp,
                         flagsp[-1], flagsp[1],
                         ci);
                *nmsedec += opj_t1_getnmsedec_sig((OPJ_UINT32)opj_int_abs(*datap),
                                                  (OPJ_UINT32)bpno);
                ctxt2 = opj_t1_getctxno_sc(lu);
#ifdef DEBUG_ENC_CLN
                printf("   ctxt2=%d\n", ctxt2);
#endif
                opj_mqc_setcurctx(mqc, ctxt2);

                v = *datap < 0 ? 1U : 0U;
                spb = opj_t1_getspb(lu);
#ifdef DEBUG_ENC_CLN
                printf("   spb=%d\n", spb);
#endif
                opj_mqc_encode(mqc, v ^ spb);
                vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (ci == 0)) ? 1 : 0;
                opj_t1_update_flags(flagsp, ci, v, t1->w + 2U, vsc);
            }
        }
        *flagsp &= ~(T1_PI_THIS << (3U * ci));
        datap += t1->data_stride;
    }
}

#define opj_t1_dec_clnpass_step_macro(check_flags, partial, \
                                      flags, flagsp, flags_stride, data, \
                                      data_stride, ci, mqc, curctx, \
                                      v, a, c, ct, oneplushalf, vsc) \
{ \







|
<
<
<
<
<
<
<
<
<
<
|
|
|
<
|
>
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|
>
>
|
|
>
|
|
>
|
|
>
>
|
|
|
|
<
<
<
<
<
<
<
<
|
|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
<
|
|
|







1020
1021
1022
1023
1024
1025
1026
1027










1028
1029
1030

1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045

1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064








1065
1066
1067

1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088

1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
        opj_t1_dec_refpass_mqc_generic(t1, bpno);
    }
}

/**
Encode clean-up pass step
*/
#define opj_t1_enc_clnpass_step_macro(mqc, curctx, a, c, ct, flagspIn, datapIn, bpno, one, nmsedec, agg, runlen, lim, cblksty) \










{ \
    OPJ_UINT32 v; \
    OPJ_UINT32 ci; \

    opj_flag_t* const flagsp = (flagspIn); \
    const OPJ_INT32* l_datap = (datapIn); \
    const OPJ_UINT32 check = (T1_SIGMA_4 | T1_SIGMA_7 | T1_SIGMA_10 | T1_SIGMA_13 | \
                              T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
 \
    if ((*flagsp & check) == check) { \
        if (runlen == 0) { \
            *flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } else if (runlen == 1) { \
            *flagsp &= ~(T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } else if (runlen == 2) { \
            *flagsp &= ~(T1_PI_2 | T1_PI_3); \
        } else if (runlen == 3) { \
            *flagsp &= ~(T1_PI_3); \
        } \

    } \
    else \
    for (ci = runlen; ci < lim; ++ci) { \
        OPJ_BOOL goto_PARTIAL = OPJ_FALSE; \
        if ((agg != 0) && (ci == runlen)) { \
            goto_PARTIAL = OPJ_TRUE; \
        } \
        else if (!(*flagsp & ((T1_SIGMA_THIS | T1_PI_THIS) << (ci * 3U)))) { \
            OPJ_UINT32 ctxt1 = opj_t1_getctxno_zc(mqc, *flagsp >> (ci * 3U)); \
/* #ifdef DEBUG_ENC_CLN */ \
/*            printf("   ctxt1=%d\n", ctxt1); */ \
/* #endif */ \
            opj_t1_setcurctx(curctx, ctxt1); \
            v = (opj_smr_abs(*l_datap) & (OPJ_UINT32)one) ? 1 : 0; \
            opj_mqc_encode_macro(mqc, curctx, a, c, ct, v); \
            if (v) { \
                goto_PARTIAL = OPJ_TRUE; \
            } \
        } \








        if( goto_PARTIAL ) { \
            OPJ_UINT32 vsc; \
            OPJ_UINT32 ctxt2, spb; \

            OPJ_UINT32 lu = opj_t1_getctxtno_sc_or_spb_index( \
                        *flagsp, \
                        flagsp[-1], flagsp[1], \
                        ci); \
            *nmsedec += opj_t1_getnmsedec_sig(opj_smr_abs(*l_datap), \
                                                (OPJ_UINT32)bpno); \
            ctxt2 = opj_t1_getctxno_sc(lu); \
/* #ifdef DEBUG_ENC_CLN */ \
/*           printf("   ctxt2=%d\n", ctxt2); */ \
/* #endif */ \
            opj_t1_setcurctx(curctx, ctxt2); \
 \
            v = opj_smr_sign(*l_datap); \
            spb = opj_t1_getspb(lu); \
/* #ifdef DEBUG_ENC_CLN */ \
/*           printf("   spb=%d\n", spb); */\
/* #endif */ \
            opj_mqc_encode_macro(mqc, curctx, a, c, ct, v ^ spb); \
            vsc = ((cblksty & J2K_CCP_CBLKSTY_VSC) && (ci == 0)) ? 1 : 0; \
            opj_t1_update_flags(flagsp, ci, v, t1->w + 2U, vsc); \
        } \

        *flagsp &= ~(T1_PI_THIS << (3U * ci)); \
        l_datap ++; \
    } \
}

#define opj_t1_dec_clnpass_step_macro(check_flags, partial, \
                                      flags, flagsp, flags_stride, data, \
                                      data_stride, ci, mqc, curctx, \
                                      v, a, c, ct, oneplushalf, vsc) \
{ \
1161
1162
1163
1164
1165
1166
1167


1168
1169
1170

1171
1172
1173
1174
1175
1176
1177
1178
1179
1180

1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207

1208
1209
1210
1211
1212
1213
1214
1215

1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231

1232
1233
1234
1235
1236
1237
1238
1239

1240
1241


1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
    opj_t1_t *t1,
    OPJ_INT32 bpno,
    OPJ_INT32 *nmsedec,
    OPJ_UINT32 cblksty)
{
    OPJ_UINT32 i, k;
    const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);


    OPJ_UINT32 agg, runlen;

    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */


    *nmsedec = 0;
#ifdef DEBUG_ENC_CLN
    printf("enc_clnpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4) {
#ifdef DEBUG_ENC_CLN
        printf(" k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {

#ifdef DEBUG_ENC_CLN
            printf("  i=%d\n", i);
#endif
            agg = !(T1_FLAGS(i, k));
#ifdef DEBUG_ENC_CLN
            printf("   agg=%d\n", agg);
#endif
            if (agg) {
                for (runlen = 0; runlen < 4; ++runlen) {
                    if (opj_int_abs(t1->data[((k + runlen)*t1->data_stride) + i]) & one) {
                        break;
                    }
                }
                opj_mqc_setcurctx(mqc, T1_CTXNO_AGG);
                opj_mqc_encode(mqc, runlen != 4);
                if (runlen == 4) {
                    continue;
                }
                opj_mqc_setcurctx(mqc, T1_CTXNO_UNI);
                opj_mqc_encode(mqc, runlen >> 1);
                opj_mqc_encode(mqc, runlen & 1);
            } else {
                runlen = 0;
            }
            opj_t1_enc_clnpass_step(
                t1,
                &T1_FLAGS(i, k),

                &t1->data[((k + runlen) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                agg,
                runlen,
                4U,
                cblksty);

        }
    }
    if (k < t1->h) {
        agg = 0;
        runlen = 0;
#ifdef DEBUG_ENC_CLN
        printf(" k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i) {
#ifdef DEBUG_ENC_CLN
            printf("  i=%d\n", i);
            printf("   agg=%d\n", agg);
#endif
            opj_t1_enc_clnpass_step(
                t1,
                &T1_FLAGS(i, k),

                &t1->data[((k + runlen) * t1->data_stride) + i],
                bpno,
                one,
                nmsedec,
                agg,
                runlen,
                t1->h - k,
                cblksty);

        }
    }


}

#define opj_t1_dec_clnpass_internal(t1, bpno, vsc, w, h, flags_stride) \
{ \
    OPJ_INT32 one, half, oneplushalf; \
    OPJ_UINT32 runlen; \
    OPJ_UINT32 i, j, k; \
    const OPJ_UINT32 l_w = w; \
    opj_mqc_t* mqc = &(t1->mqc); \
    register OPJ_INT32 *data = t1->data; \
    register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
    DOWNLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
    register OPJ_UINT32 v; \
    one = 1 << bpno; \
    half = one >> 1; \
    oneplushalf = one | half; \
    for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
        for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
            opj_flag_t flags = *flagsp; \







>
>
|
|
<
>





|



|
>



|




|
|



|
|



|
|
|



|
<
|
>
|







>



|
|



|




|
<
|
>
|







>


>
>











|







1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150

1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187

1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212

1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
    opj_t1_t *t1,
    OPJ_INT32 bpno,
    OPJ_INT32 *nmsedec,
    OPJ_UINT32 cblksty)
{
    OPJ_UINT32 i, k;
    const OPJ_INT32 one = 1 << (bpno + T1_NMSEDEC_FRACBITS);
    opj_mqc_t* mqc = &(t1->mqc);
    DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
    const OPJ_INT32* datap = t1->data;
    opj_flag_t *f = &T1_FLAGS(0, 0);

    const OPJ_UINT32 extra = 2U;

    *nmsedec = 0;
#ifdef DEBUG_ENC_CLN
    printf("enc_clnpass: bpno=%d\n", bpno);
#endif
    for (k = 0; k < (t1->h & ~3U); k += 4, f += extra) {
#ifdef DEBUG_ENC_CLN
        printf(" k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i, f++) {
            OPJ_UINT32 agg, runlen;
#ifdef DEBUG_ENC_CLN
            printf("  i=%d\n", i);
#endif
            agg = !*f;
#ifdef DEBUG_ENC_CLN
            printf("   agg=%d\n", agg);
#endif
            if (agg) {
                for (runlen = 0; runlen < 4; ++runlen, ++datap) {
                    if (opj_smr_abs(*datap) & (OPJ_UINT32)one) {
                        break;
                    }
                }
                opj_t1_setcurctx(curctx, T1_CTXNO_AGG);
                opj_mqc_encode_macro(mqc, curctx, a, c, ct, runlen != 4);
                if (runlen == 4) {
                    continue;
                }
                opj_t1_setcurctx(curctx, T1_CTXNO_UNI);
                opj_mqc_encode_macro(mqc, curctx, a, c, ct, runlen >> 1);
                opj_mqc_encode_macro(mqc, curctx, a, c, ct, runlen & 1);
            } else {
                runlen = 0;
            }
            opj_t1_enc_clnpass_step_macro(

                mqc, curctx, a, c, ct,
                f,
                datap,
                bpno,
                one,
                nmsedec,
                agg,
                runlen,
                4U,
                cblksty);
            datap += 4 - runlen;
        }
    }
    if (k < t1->h) {
        const OPJ_UINT32 agg = 0;
        const OPJ_UINT32 runlen = 0;
#ifdef DEBUG_ENC_CLN
        printf(" k=%d\n", k);
#endif
        for (i = 0; i < t1->w; ++i, f++) {
#ifdef DEBUG_ENC_CLN
            printf("  i=%d\n", i);
            printf("   agg=%d\n", agg);
#endif
            opj_t1_enc_clnpass_step_macro(

                mqc, curctx, a, c, ct,
                f,
                datap,
                bpno,
                one,
                nmsedec,
                agg,
                runlen,
                t1->h - k,
                cblksty);
            datap += t1->h - k;
        }
    }

    UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct);
}

#define opj_t1_dec_clnpass_internal(t1, bpno, vsc, w, h, flags_stride) \
{ \
    OPJ_INT32 one, half, oneplushalf; \
    OPJ_UINT32 runlen; \
    OPJ_UINT32 i, j, k; \
    const OPJ_UINT32 l_w = w; \
    opj_mqc_t* mqc = &(t1->mqc); \
    register OPJ_INT32 *data = t1->data; \
    register opj_flag_t *flagsp = &t1->flags[flags_stride + 1]; \
    DOWNLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
    register OPJ_UINT32 v; \
    one = 1 << bpno; \
    half = one >> 1; \
    oneplushalf = one | half; \
    for (k = 0; k < (h & ~3u); k += 4, data += 3*l_w, flagsp += 2) { \
        for (i = 0; i < l_w; ++i, ++data, ++flagsp) { \
            opj_flag_t flags = *flagsp; \
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
                                    flags, flagsp, flags_stride, data, \
                                    l_w, 3, mqc, curctx, \
                                    v, a, c, ct, oneplushalf, OPJ_FALSE); \
            } \
            *flagsp = flags & ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } \
    } \
    UPLOAD_MQC_VARIABLES(mqc, curctx, c, a, ct); \
    if( k < h ) { \
        for (i = 0; i < l_w; ++i, ++flagsp, ++data) { \
            for (j = 0; j < h - k; ++j) { \
                opj_t1_dec_clnpass_step(t1, flagsp, data + j * l_w, oneplushalf, j, vsc); \
            } \
            *flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } \







|







1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
                                    flags, flagsp, flags_stride, data, \
                                    l_w, 3, mqc, curctx, \
                                    v, a, c, ct, oneplushalf, OPJ_FALSE); \
            } \
            *flagsp = flags & ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } \
    } \
    UPLOAD_MQC_VARIABLES(mqc, curctx, a, c, ct); \
    if( k < h ) { \
        for (i = 0; i < l_w; ++i, ++flagsp, ++data) { \
            for (j = 0; j < h - k; ++j) { \
                opj_t1_dec_clnpass_step(t1, flagsp, data + j * l_w, oneplushalf, j, vsc); \
            } \
            *flagsp &= ~(T1_PI_0 | T1_PI_1 | T1_PI_2 | T1_PI_3); \
        } \
1422
1423
1424
1425
1426
1427
1428


1429


1430
1431
1432
1433
1434
1435
1436
    if (mct_norms && (compno < mct_numcomps)) {
        w1 = mct_norms[compno];
    }

    if (qmfbid == 1) {
        w2 = opj_dwt_getnorm(level, orient);
    } else {    /* if (qmfbid == 0) */


        w2 = opj_dwt_getnorm_real(level, orient);


    }

    wmsedec = w1 * w2 * stepsize * (1 << bpno);
    wmsedec *= wmsedec * nmsedec / 8192.0;

    return wmsedec;
}







>
>

>
>







1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
    if (mct_norms && (compno < mct_numcomps)) {
        w1 = mct_norms[compno];
    }

    if (qmfbid == 1) {
        w2 = opj_dwt_getnorm(level, orient);
    } else {    /* if (qmfbid == 0) */
        const OPJ_INT32 log2_gain = (orient == 0) ? 0 :
                                    (orient == 3) ? 2 : 1;
        w2 = opj_dwt_getnorm_real(level, orient);
        /* Not sure this is right. But preserves past behaviour */
        stepsize /= (1 << log2_gain);
    }

    wmsedec = w1 * w2 * stepsize * (1 << bpno);
    wmsedec *= wmsedec * nmsedec / 8192.0;

    return wmsedec;
}
1446
1447
1448
1449
1450
1451
1452
1453

1454
1455
1456
1457
1458
1459
1460
    /* No risk of overflow. Prior checks ensure those assert are met */
    /* They are per the specification */
    assert(w <= 1024);
    assert(h <= 1024);
    assert(w * h <= 4096);

    /* encoder uses tile buffer, so no need to allocate */
    if (!t1->encoder) {

        OPJ_UINT32 datasize = w * h;

        if (datasize > t1->datasize) {
            opj_aligned_free(t1->data);
            t1->data = (OPJ_INT32*) opj_aligned_malloc(datasize * sizeof(OPJ_INT32));
            if (!t1->data) {
                /* FIXME event manager error callback */







<
>







1436
1437
1438
1439
1440
1441
1442

1443
1444
1445
1446
1447
1448
1449
1450
    /* No risk of overflow. Prior checks ensure those assert are met */
    /* They are per the specification */
    assert(w <= 1024);
    assert(h <= 1024);
    assert(w * h <= 4096);

    /* encoder uses tile buffer, so no need to allocate */

    {
        OPJ_UINT32 datasize = w * h;

        if (datasize > t1->datasize) {
            opj_aligned_free(t1->data);
            t1->data = (OPJ_INT32*) opj_aligned_malloc(datasize * sizeof(OPJ_INT32));
            if (!t1->data) {
                /* FIXME event manager error callback */
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
*/
void opj_t1_destroy(opj_t1_t *p_t1)
{
    if (! p_t1) {
        return;
    }

    /* encoder uses tile buffer, so no need to free */
    if (!p_t1->encoder && p_t1->data) {
        opj_aligned_free(p_t1->data);
        p_t1->data = 00;
    }

    if (p_t1->flags) {
        opj_aligned_free(p_t1->flags);
        p_t1->flags = 00;







<
|







1546
1547
1548
1549
1550
1551
1552

1553
1554
1555
1556
1557
1558
1559
1560
*/
void opj_t1_destroy(opj_t1_t *p_t1)
{
    if (! p_t1) {
        return;
    }


    if (p_t1->data) {
        opj_aligned_free(p_t1->data);
        p_t1->data = 00;
    }

    if (p_t1->flags) {
        opj_aligned_free(p_t1->flags);
        p_t1->flags = 00;
1654
1655
1656
1657
1658
1659
1660







1661







1662
1663
1664
1665
1666
1667
1668
        opj_free(job);
        return;
    }

    t1 = (opj_t1_t*) opj_tls_get(tls, OPJ_TLS_KEY_T1);
    if (t1 == NULL) {
        t1 = opj_t1_create(OPJ_FALSE);







        opj_tls_set(tls, OPJ_TLS_KEY_T1, t1, opj_t1_destroy_wrapper);







    }
    t1->mustuse_cblkdatabuffer = job->mustuse_cblkdatabuffer;

    if (OPJ_FALSE == opj_t1_decode_cblk(
                t1,
                cblk,
                band->bandno,







>
>
>
>
>
>
>
|
>
>
>
>
>
>
>







1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
        opj_free(job);
        return;
    }

    t1 = (opj_t1_t*) opj_tls_get(tls, OPJ_TLS_KEY_T1);
    if (t1 == NULL) {
        t1 = opj_t1_create(OPJ_FALSE);
        if (t1 == NULL) {
            opj_event_msg(job->p_manager, EVT_ERROR,
                          "Cannot allocate Tier 1 handle\n");
            *(job->pret) = OPJ_FALSE;
            opj_free(job);
            return;
        }
        if (!opj_tls_set(tls, OPJ_TLS_KEY_T1, t1, opj_t1_destroy_wrapper)) {
            opj_event_msg(job->p_manager, EVT_ERROR,
                          "Unable to set t1 handle as TLS\n");
            opj_t1_destroy(t1);
            *(job->pret) = OPJ_FALSE;
            opj_free(job);
            return;
        }
    }
    t1->mustuse_cblkdatabuffer = job->mustuse_cblkdatabuffer;

    if (OPJ_FALSE == opj_t1_decode_cblk(
                t1,
                cblk,
                band->bandno,
1721
1722
1723
1724
1725
1726
1727

1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
    if (cblk->decoded_data) {
        OPJ_UINT32 cblk_size = cblk_w * cblk_h;
        if (tccp->qmfbid == 1) {
            for (i = 0; i < cblk_size; ++i) {
                datap[i] /= 2;
            }
        } else {        /* if (tccp->qmfbid == 0) */

            i = 0;
#ifdef __SSE2__
            {
                const __m128 xmm_stepsize = _mm_set1_ps(band->stepsize);
                for (; i < (cblk_size & ~15U); i += 16) {
                    __m128 xmm0_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 0)));
                    __m128 xmm1_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 4)));
                    __m128 xmm2_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 8)));
                    __m128 xmm3_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 12)));
                    _mm_store_ps((float*)(datap +  0), _mm_mul_ps(xmm0_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap +  4), _mm_mul_ps(xmm1_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap +  8), _mm_mul_ps(xmm2_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap + 12), _mm_mul_ps(xmm3_data, xmm_stepsize));
                    datap += 16;
                }
            }
#endif
            for (; i < cblk_size; ++i) {
                OPJ_FLOAT32 tmp = ((OPJ_FLOAT32)(*datap)) * band->stepsize;
                memcpy(datap, &tmp, sizeof(tmp));
                datap++;
            }
        }
    } else if (tccp->qmfbid == 1) {
        OPJ_INT32* OPJ_RESTRICT tiledp = &tilec->data[(OPJ_SIZE_T)y * tile_w +
                                                       (OPJ_SIZE_T)x];







>



|


















|







1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
    if (cblk->decoded_data) {
        OPJ_UINT32 cblk_size = cblk_w * cblk_h;
        if (tccp->qmfbid == 1) {
            for (i = 0; i < cblk_size; ++i) {
                datap[i] /= 2;
            }
        } else {        /* if (tccp->qmfbid == 0) */
            const float stepsize = 0.5f * band->stepsize;
            i = 0;
#ifdef __SSE2__
            {
                const __m128 xmm_stepsize = _mm_set1_ps(stepsize);
                for (; i < (cblk_size & ~15U); i += 16) {
                    __m128 xmm0_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 0)));
                    __m128 xmm1_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 4)));
                    __m128 xmm2_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 8)));
                    __m128 xmm3_data = _mm_cvtepi32_ps(_mm_load_si128((__m128i * const)(
                                                           datap + 12)));
                    _mm_store_ps((float*)(datap +  0), _mm_mul_ps(xmm0_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap +  4), _mm_mul_ps(xmm1_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap +  8), _mm_mul_ps(xmm2_data, xmm_stepsize));
                    _mm_store_ps((float*)(datap + 12), _mm_mul_ps(xmm3_data, xmm_stepsize));
                    datap += 16;
                }
            }
#endif
            for (; i < cblk_size; ++i) {
                OPJ_FLOAT32 tmp = ((OPJ_FLOAT32)(*datap)) * stepsize;
                memcpy(datap, &tmp, sizeof(tmp));
                datap++;
            }
        }
    } else if (tccp->qmfbid == 1) {
        OPJ_INT32* OPJ_RESTRICT tiledp = &tilec->data[(OPJ_SIZE_T)y * tile_w +
                                                       (OPJ_SIZE_T)x];
1769
1770
1771
1772
1773
1774
1775

1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
            }
            for (; i < cblk_w; ++i) {
                OPJ_INT32 tmp = datap[(j * cblk_w) + i];
                ((OPJ_INT32*)tiledp)[(j * (OPJ_SIZE_T)tile_w) + i] = tmp / 2;
            }
        }
    } else {        /* if (tccp->qmfbid == 0) */

        OPJ_FLOAT32* OPJ_RESTRICT tiledp = (OPJ_FLOAT32*) &tilec->data[(OPJ_SIZE_T)y *
                                                         tile_w + (OPJ_SIZE_T)x];
        for (j = 0; j < cblk_h; ++j) {
            OPJ_FLOAT32* OPJ_RESTRICT tiledp2 = tiledp;
            for (i = 0; i < cblk_w; ++i) {
                OPJ_FLOAT32 tmp = (OPJ_FLOAT32) * datap * band->stepsize;
                *tiledp2 = tmp;
                datap++;
                tiledp2++;
            }
            tiledp += tile_w;
        }
    }







>





|







1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
            }
            for (; i < cblk_w; ++i) {
                OPJ_INT32 tmp = datap[(j * cblk_w) + i];
                ((OPJ_INT32*)tiledp)[(j * (OPJ_SIZE_T)tile_w) + i] = tmp / 2;
            }
        }
    } else {        /* if (tccp->qmfbid == 0) */
        const float stepsize = 0.5f * band->stepsize;
        OPJ_FLOAT32* OPJ_RESTRICT tiledp = (OPJ_FLOAT32*) &tilec->data[(OPJ_SIZE_T)y *
                                                         tile_w + (OPJ_SIZE_T)x];
        for (j = 0; j < cblk_h; ++j) {
            OPJ_FLOAT32* OPJ_RESTRICT tiledp2 = tiledp;
            for (i = 0; i < cblk_w; ++i) {
                OPJ_FLOAT32 tmp = (OPJ_FLOAT32) * datap * stepsize;
                *tiledp2 = tmp;
                datap++;
                tiledp2++;
            }
            tiledp += tile_w;
        }
    }
2096
2097
2098
2099
2100
2101
2102













2103

2104















































































































































2105
2106
2107
2108
2109
2110
2111


2112

2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213



2214
2215
2216
2217
2218
2219







2220
2221
2222
2223
2224
2225
2226
2227
        t1->data = original_t1_data;
    }

    return OPJ_TRUE;
}

































































































































































OPJ_BOOL opj_t1_encode_cblks(opj_t1_t *t1,
                             opj_tcd_tile_t *tile,
                             opj_tcp_t *tcp,
                             const OPJ_FLOAT64 * mct_norms,
                             OPJ_UINT32 mct_numcomps
                            )
{


    OPJ_UINT32 compno, resno, bandno, precno, cblkno;


    tile->distotile = 0;        /* fixed_quality */

    for (compno = 0; compno < tile->numcomps; ++compno) {
        opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
        opj_tccp_t* tccp = &tcp->tccps[compno];
        OPJ_UINT32 tile_w = (OPJ_UINT32)(tilec->x1 - tilec->x0);

        for (resno = 0; resno < tilec->numresolutions; ++resno) {
            opj_tcd_resolution_t *res = &tilec->resolutions[resno];

            for (bandno = 0; bandno < res->numbands; ++bandno) {
                opj_tcd_band_t* OPJ_RESTRICT band = &res->bands[bandno];
                OPJ_INT32 bandconst;

                /* Skip empty bands */
                if (opj_tcd_is_band_empty(band)) {
                    continue;
                }

                bandconst = 8192 * 8192 / ((OPJ_INT32) floor(band->stepsize * 8192));
                for (precno = 0; precno < res->pw * res->ph; ++precno) {
                    opj_tcd_precinct_t *prc = &band->precincts[precno];

                    for (cblkno = 0; cblkno < prc->cw * prc->ch; ++cblkno) {
                        opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];
                        OPJ_INT32* OPJ_RESTRICT tiledp;
                        OPJ_UINT32 cblk_w;
                        OPJ_UINT32 cblk_h;
                        OPJ_UINT32 i, j, tileLineAdvance;
                        OPJ_SIZE_T tileIndex = 0;

                        OPJ_INT32 x = cblk->x0 - band->x0;
                        OPJ_INT32 y = cblk->y0 - band->y0;
                        if (band->bandno & 1) {
                            opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
                            x += pres->x1 - pres->x0;
                        }
                        if (band->bandno & 2) {
                            opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
                            y += pres->y1 - pres->y0;
                        }

                        if (!opj_t1_allocate_buffers(
                                    t1,
                                    (OPJ_UINT32)(cblk->x1 - cblk->x0),
                                    (OPJ_UINT32)(cblk->y1 - cblk->y0))) {
                            return OPJ_FALSE;
                        }

                        cblk_w = t1->w;
                        cblk_h = t1->h;
                        tileLineAdvance = tile_w - cblk_w;

                        tiledp = &tilec->data[(OPJ_SIZE_T)y * tile_w + (OPJ_SIZE_T)x];
                        t1->data = tiledp;
                        t1->data_stride = tile_w;
                        if (tccp->qmfbid == 1) {
                            /* Do multiplication on unsigned type, even if the
                             * underlying type is signed, to avoid potential
                             * int overflow on large value (the output will be
                             * incorrect in such situation, but whatever...)
                             * This assumes complement-to-2 signed integer
                             * representation
                             * Fixes https://github.com/uclouvain/openjpeg/issues/1053
                             */
                            OPJ_UINT32* OPJ_RESTRICT tiledp_u = (OPJ_UINT32*) tiledp;
                            for (j = 0; j < cblk_h; ++j) {
                                for (i = 0; i < cblk_w; ++i) {
                                    tiledp_u[tileIndex] <<= T1_NMSEDEC_FRACBITS;
                                    tileIndex++;
                                }
                                tileIndex += tileLineAdvance;
                            }
                        } else {        /* if (tccp->qmfbid == 0) */
                            for (j = 0; j < cblk_h; ++j) {
                                for (i = 0; i < cblk_w; ++i) {
                                    OPJ_INT32 tmp = tiledp[tileIndex];
                                    tiledp[tileIndex] =
                                        opj_int_fix_mul_t1(
                                            tmp,
                                            bandconst);
                                    tileIndex++;
                                }
                                tileIndex += tileLineAdvance;
                            }
                        }

                        opj_t1_encode_cblk(
                            t1,
                            cblk,
                            band->bandno,
                            compno,
                            tilec->numresolutions - 1 - resno,
                            tccp->qmfbid,
                            band->stepsize,
                            tccp->cblksty,
                            tile->numcomps,
                            tile,
                            mct_norms,
                            mct_numcomps);




                    } /* cblkno */
                } /* precno */
            } /* bandno */
        } /* resno  */
    } /* compno  */







    return OPJ_TRUE;
}

/* Returns whether the pass (bpno, passtype) is terminated */
static int opj_t1_enc_is_term_pass(opj_tcd_cblk_enc_t* cblk,
                                   OPJ_UINT32 cblksty,
                                   OPJ_INT32 bpno,
                                   OPJ_UINT32 passtype)







>
>
>
>
>
>
>
>
>
>
>
>
>

>
|
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
|






>
>

>






<






<





<
<





<
<
<
<
<

|
<
<
<
<
<
<
<
<
<
|
|
<
<
|
|
<
|
<
<
<
|
<
|
|
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
<
|
<
<
|
|
<
|
|
<
<
<
<
|
|
>
>
>






>
>
>
>
>
>
>
|







2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283

2284
2285
2286
2287
2288
2289

2290
2291
2292
2293
2294


2295
2296
2297
2298
2299





2300
2301









2302
2303


2304
2305

2306



2307

2308
2309






























2310


2311
2312

2313
2314




2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
        t1->data = original_t1_data;
    }

    return OPJ_TRUE;
}


typedef struct {
    OPJ_UINT32 compno;
    OPJ_UINT32 resno;
    opj_tcd_cblk_enc_t* cblk;
    opj_tcd_tile_t *tile;
    opj_tcd_band_t* band;
    opj_tcd_tilecomp_t* tilec;
    opj_tccp_t* tccp;
    const OPJ_FLOAT64 * mct_norms;
    OPJ_UINT32 mct_numcomps;
    volatile OPJ_BOOL* pret;
    opj_mutex_t* mutex;
} opj_t1_cblk_encode_processing_job_t;

/** Procedure to deal with a asynchronous code-block encoding job.
 *
 * @param user_data Pointer to a opj_t1_cblk_encode_processing_job_t* structure
 * @param tls       TLS handle.
 */
static void opj_t1_cblk_encode_processor(void* user_data, opj_tls_t* tls)
{
    opj_t1_cblk_encode_processing_job_t* job =
        (opj_t1_cblk_encode_processing_job_t*)user_data;
    opj_tcd_cblk_enc_t* cblk = job->cblk;
    const opj_tcd_band_t* band = job->band;
    const opj_tcd_tilecomp_t* tilec = job->tilec;
    const opj_tccp_t* tccp = job->tccp;
    const OPJ_UINT32 resno = job->resno;
    opj_t1_t* t1;
    const OPJ_UINT32 tile_w = (OPJ_UINT32)(tilec->x1 - tilec->x0);

    OPJ_INT32* OPJ_RESTRICT tiledp;
    OPJ_UINT32 cblk_w;
    OPJ_UINT32 cblk_h;
    OPJ_UINT32 i, j;

    OPJ_INT32 x = cblk->x0 - band->x0;
    OPJ_INT32 y = cblk->y0 - band->y0;

    if (!*(job->pret)) {
        opj_free(job);
        return;
    }

    t1 = (opj_t1_t*) opj_tls_get(tls, OPJ_TLS_KEY_T1);
    if (t1 == NULL) {
        t1 = opj_t1_create(OPJ_TRUE); /* OPJ_TRUE == T1 for encoding */
        opj_tls_set(tls, OPJ_TLS_KEY_T1, t1, opj_t1_destroy_wrapper);
    }

    if (band->bandno & 1) {
        opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
        x += pres->x1 - pres->x0;
    }
    if (band->bandno & 2) {
        opj_tcd_resolution_t *pres = &tilec->resolutions[resno - 1];
        y += pres->y1 - pres->y0;
    }

    if (!opj_t1_allocate_buffers(
                t1,
                (OPJ_UINT32)(cblk->x1 - cblk->x0),
                (OPJ_UINT32)(cblk->y1 - cblk->y0))) {
        *(job->pret) = OPJ_FALSE;
        opj_free(job);
        return;
    }

    cblk_w = t1->w;
    cblk_h = t1->h;

    tiledp = &tilec->data[(OPJ_SIZE_T)y * tile_w + (OPJ_SIZE_T)x];

    if (tccp->qmfbid == 1) {
        /* Do multiplication on unsigned type, even if the
            * underlying type is signed, to avoid potential
            * int overflow on large value (the output will be
            * incorrect in such situation, but whatever...)
            * This assumes complement-to-2 signed integer
            * representation
            * Fixes https://github.com/uclouvain/openjpeg/issues/1053
            */
        OPJ_UINT32* OPJ_RESTRICT tiledp_u = (OPJ_UINT32*) tiledp;
        OPJ_UINT32* OPJ_RESTRICT t1data = (OPJ_UINT32*) t1->data;
        /* Change from "natural" order to "zigzag" order of T1 passes */
        for (j = 0; j < (cblk_h & ~3U); j += 4) {
            for (i = 0; i < cblk_w; ++i) {
                t1data[0] = tiledp_u[(j + 0) * tile_w + i] << T1_NMSEDEC_FRACBITS;
                t1data[1] = tiledp_u[(j + 1) * tile_w + i] << T1_NMSEDEC_FRACBITS;
                t1data[2] = tiledp_u[(j + 2) * tile_w + i] << T1_NMSEDEC_FRACBITS;
                t1data[3] = tiledp_u[(j + 3) * tile_w + i] << T1_NMSEDEC_FRACBITS;
                t1data += 4;
            }
        }
        if (j < cblk_h) {
            for (i = 0; i < cblk_w; ++i) {
                OPJ_UINT32 k;
                for (k = j; k < cblk_h; k++) {
                    t1data[0] = tiledp_u[k * tile_w + i] << T1_NMSEDEC_FRACBITS;
                    t1data ++;
                }
            }
        }
    } else {        /* if (tccp->qmfbid == 0) */
        OPJ_FLOAT32* OPJ_RESTRICT tiledp_f = (OPJ_FLOAT32*) tiledp;
        OPJ_INT32* OPJ_RESTRICT t1data = t1->data;
        /* Change from "natural" order to "zigzag" order of T1 passes */
        for (j = 0; j < (cblk_h & ~3U); j += 4) {
            for (i = 0; i < cblk_w; ++i) {
                t1data[0] = (OPJ_INT32)opj_lrintf((tiledp_f[(j + 0) * tile_w + i] /
                                                   band->stepsize) * (1 << T1_NMSEDEC_FRACBITS));
                t1data[1] = (OPJ_INT32)opj_lrintf((tiledp_f[(j + 1) * tile_w + i] /
                                                   band->stepsize) * (1 << T1_NMSEDEC_FRACBITS));
                t1data[2] = (OPJ_INT32)opj_lrintf((tiledp_f[(j + 2) * tile_w + i] /
                                                   band->stepsize) * (1 << T1_NMSEDEC_FRACBITS));
                t1data[3] = (OPJ_INT32)opj_lrintf((tiledp_f[(j + 3) * tile_w + i] /
                                                   band->stepsize) * (1 << T1_NMSEDEC_FRACBITS));
                t1data += 4;
            }
        }
        if (j < cblk_h) {
            for (i = 0; i < cblk_w; ++i) {
                OPJ_UINT32 k;
                for (k = j; k < cblk_h; k++) {
                    t1data[0] = (OPJ_INT32)opj_lrintf((tiledp_f[k * tile_w + i] / band->stepsize)
                                                      * (1 << T1_NMSEDEC_FRACBITS));
                    t1data ++;
                }
            }
        }
    }

    {
        OPJ_FLOAT64 cumwmsedec =
            opj_t1_encode_cblk(
                t1,
                cblk,
                band->bandno,
                job->compno,
                tilec->numresolutions - 1 - resno,
                tccp->qmfbid,
                band->stepsize,
                tccp->cblksty,
                job->tile->numcomps,
                job->mct_norms,
                job->mct_numcomps);
        if (job->mutex) {
            opj_mutex_lock(job->mutex);
        }
        job->tile->distotile += cumwmsedec;
        if (job->mutex) {
            opj_mutex_unlock(job->mutex);
        }
    }

    opj_free(job);
}


OPJ_BOOL opj_t1_encode_cblks(opj_tcd_t* tcd,
                             opj_tcd_tile_t *tile,
                             opj_tcp_t *tcp,
                             const OPJ_FLOAT64 * mct_norms,
                             OPJ_UINT32 mct_numcomps
                            )
{
    volatile OPJ_BOOL ret = OPJ_TRUE;
    opj_thread_pool_t* tp = tcd->thread_pool;
    OPJ_UINT32 compno, resno, bandno, precno, cblkno;
    opj_mutex_t* mutex = opj_mutex_create();

    tile->distotile = 0;        /* fixed_quality */

    for (compno = 0; compno < tile->numcomps; ++compno) {
        opj_tcd_tilecomp_t* tilec = &tile->comps[compno];
        opj_tccp_t* tccp = &tcp->tccps[compno];


        for (resno = 0; resno < tilec->numresolutions; ++resno) {
            opj_tcd_resolution_t *res = &tilec->resolutions[resno];

            for (bandno = 0; bandno < res->numbands; ++bandno) {
                opj_tcd_band_t* OPJ_RESTRICT band = &res->bands[bandno];


                /* Skip empty bands */
                if (opj_tcd_is_band_empty(band)) {
                    continue;
                }


                for (precno = 0; precno < res->pw * res->ph; ++precno) {
                    opj_tcd_precinct_t *prc = &band->precincts[precno];

                    for (cblkno = 0; cblkno < prc->cw * prc->ch; ++cblkno) {
                        opj_tcd_cblk_enc_t* cblk = &prc->cblks.enc[cblkno];






                        opj_t1_cblk_encode_processing_job_t* job =









                            (opj_t1_cblk_encode_processing_job_t*) opj_calloc(1,
                                    sizeof(opj_t1_cblk_encode_processing_job_t));


                        if (!job) {
                            ret = OPJ_FALSE;

                            goto end;



                        }

                        job->compno = compno;
                        job->tile = tile;






























                        job->resno = resno;


                        job->cblk = cblk;
                        job->band = band;

                        job->tilec = tilec;
                        job->tccp = tccp;




                        job->mct_norms = mct_norms;
                        job->mct_numcomps = mct_numcomps;
                        job->pret = &ret;
                        job->mutex = mutex;
                        opj_thread_pool_submit_job(tp, opj_t1_cblk_encode_processor, job);

                    } /* cblkno */
                } /* precno */
            } /* bandno */
        } /* resno  */
    } /* compno  */

end:
    opj_thread_pool_wait_completion(tcd->thread_pool, 0);
    if (mutex) {
        opj_mutex_destroy(mutex);
    }

    return ret;
}

/* Returns whether the pass (bpno, passtype) is terminated */
static int opj_t1_enc_is_term_pass(opj_tcd_cblk_enc_t* cblk,
                                   OPJ_UINT32 cblksty,
                                   OPJ_INT32 bpno,
                                   OPJ_UINT32 passtype)
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279

2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290


2291






2292

2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
    }

    return OPJ_FALSE;
}


/** mod fixed_quality */
static void opj_t1_encode_cblk(opj_t1_t *t1,
                               opj_tcd_cblk_enc_t* cblk,
                               OPJ_UINT32 orient,
                               OPJ_UINT32 compno,
                               OPJ_UINT32 level,
                               OPJ_UINT32 qmfbid,
                               OPJ_FLOAT64 stepsize,
                               OPJ_UINT32 cblksty,
                               OPJ_UINT32 numcomps,
                               opj_tcd_tile_t * tile,
                               const OPJ_FLOAT64 * mct_norms,
                               OPJ_UINT32 mct_numcomps)
{
    OPJ_FLOAT64 cumwmsedec = 0.0;

    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */

    OPJ_UINT32 passno;
    OPJ_INT32 bpno;
    OPJ_UINT32 passtype;
    OPJ_INT32 nmsedec = 0;
    OPJ_INT32 max;
    OPJ_UINT32 i, j;
    OPJ_BYTE type = T1_TYPE_MQ;
    OPJ_FLOAT64 tempwmsedec;


#ifdef EXTRA_DEBUG
    printf("encode_cblk(x=%d,y=%d,x1=%d,y1=%d,orient=%d,compno=%d,level=%d\n",
           cblk->x0, cblk->y0, cblk->x1, cblk->y1, orient, compno, level);
#endif

    mqc->lut_ctxno_zc_orient = lut_ctxno_zc + (orient << 9);

    max = 0;
    for (i = 0; i < t1->w; ++i) {
        for (j = 0; j < t1->h; ++j) {


            OPJ_INT32 tmp = abs(t1->data[i + j * t1->data_stride]);






            max = opj_int_max(max, tmp);

        }
    }

    cblk->numbps = max ? (OPJ_UINT32)((opj_int_floorlog2(max) + 1) -
                                      T1_NMSEDEC_FRACBITS) : 0;
    if (cblk->numbps == 0) {
        cblk->totalpasses = 0;
        return;
    }

    bpno = (OPJ_INT32)(cblk->numbps - 1);
    passtype = 2;

    opj_mqc_resetstates(mqc);
    opj_mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);







|
|
|
|
|
|
|
|
|
<
|
|













>









|
|
>
>
|
>
>
>
>
>
>
|
>







|







2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376

2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
    }

    return OPJ_FALSE;
}


/** mod fixed_quality */
static OPJ_FLOAT64 opj_t1_encode_cblk(opj_t1_t *t1,
                                      opj_tcd_cblk_enc_t* cblk,
                                      OPJ_UINT32 orient,
                                      OPJ_UINT32 compno,
                                      OPJ_UINT32 level,
                                      OPJ_UINT32 qmfbid,
                                      OPJ_FLOAT64 stepsize,
                                      OPJ_UINT32 cblksty,
                                      OPJ_UINT32 numcomps,

                                      const OPJ_FLOAT64 * mct_norms,
                                      OPJ_UINT32 mct_numcomps)
{
    OPJ_FLOAT64 cumwmsedec = 0.0;

    opj_mqc_t *mqc = &(t1->mqc);   /* MQC component */

    OPJ_UINT32 passno;
    OPJ_INT32 bpno;
    OPJ_UINT32 passtype;
    OPJ_INT32 nmsedec = 0;
    OPJ_INT32 max;
    OPJ_UINT32 i, j;
    OPJ_BYTE type = T1_TYPE_MQ;
    OPJ_FLOAT64 tempwmsedec;
    OPJ_INT32* datap;

#ifdef EXTRA_DEBUG
    printf("encode_cblk(x=%d,y=%d,x1=%d,y1=%d,orient=%d,compno=%d,level=%d\n",
           cblk->x0, cblk->y0, cblk->x1, cblk->y1, orient, compno, level);
#endif

    mqc->lut_ctxno_zc_orient = lut_ctxno_zc + (orient << 9);

    max = 0;
    datap = t1->data;
    for (j = 0; j < t1->h; ++j) {
        const OPJ_UINT32 w = t1->w;
        for (i = 0; i < w; ++i, ++datap) {
            OPJ_INT32 tmp = *datap;
            if (tmp < 0) {
                OPJ_UINT32 tmp_unsigned;
                max = opj_int_max(max, -tmp);
                tmp_unsigned = opj_to_smr(tmp);
                memcpy(datap, &tmp_unsigned, sizeof(OPJ_INT32));
            } else {
                max = opj_int_max(max, tmp);
            }
        }
    }

    cblk->numbps = max ? (OPJ_UINT32)((opj_int_floorlog2(max) + 1) -
                                      T1_NMSEDEC_FRACBITS) : 0;
    if (cblk->numbps == 0) {
        cblk->totalpasses = 0;
        return cumwmsedec;
    }

    bpno = (OPJ_INT32)(cblk->numbps - 1);
    passtype = 2;

    opj_mqc_resetstates(mqc);
    opj_mqc_setstate(mqc, T1_CTXNO_UNI, 0, 46);
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
            break;
        }

        /* fixed_quality */
        tempwmsedec = opj_t1_getwmsedec(nmsedec, compno, level, orient, bpno, qmfbid,
                                        stepsize, numcomps, mct_norms, mct_numcomps) ;
        cumwmsedec += tempwmsedec;
        tile->distotile += tempwmsedec;
        pass->distortiondec = cumwmsedec;

        if (opj_t1_enc_is_term_pass(cblk, cblksty, bpno, passtype)) {
            /* If it is a terminated pass, terminate it */
            if (type == T1_TYPE_RAW) {
                opj_mqc_bypass_flush_enc(mqc, cblksty & J2K_CCP_CBLKSTY_PTERM);
            } else {







<







2461
2462
2463
2464
2465
2466
2467

2468
2469
2470
2471
2472
2473
2474
            break;
        }

        /* fixed_quality */
        tempwmsedec = opj_t1_getwmsedec(nmsedec, compno, level, orient, bpno, qmfbid,
                                        stepsize, numcomps, mct_norms, mct_numcomps) ;
        cumwmsedec += tempwmsedec;

        pass->distortiondec = cumwmsedec;

        if (opj_t1_enc_is_term_pass(cblk, cblksty, bpno, passtype)) {
            /* If it is a terminated pass, terminate it */
            if (type == T1_TYPE_RAW) {
                opj_mqc_bypass_flush_enc(mqc, cblksty & J2K_CCP_CBLKSTY_PTERM);
            } else {
2421
2422
2423
2424
2425
2426
2427
2428


            if (cblk->data[i - 1] == 0xff && cblk->data[i] >= 0x90) {
                printf("0xff %02x at offset %d\n", cblk->data[i], i - 1);
                abort();
            }
        }
    }
#endif
}









|
>
>
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
            if (cblk->data[i - 1] == 0xff && cblk->data[i] >= 0x90) {
                printf("0xff %02x at offset %d\n", cblk->data[i], i - 1);
                abort();
            }
        }
    }
#endif

    return cumwmsedec;
}
Changes to jni/openjpeg/src/lib/openjp2/t1.h.
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
       as done in the various decoding steps. */
    opj_flag_t *flags;

    OPJ_UINT32 w;
    OPJ_UINT32 h;
    OPJ_UINT32 datasize;
    OPJ_UINT32 flagssize;
    OPJ_UINT32 data_stride;
    OPJ_BOOL   encoder;

    /* Thre 3 variables below are only used by the decoder */
    /* set to TRUE in multithreaded context */
    OPJ_BOOL     mustuse_cblkdatabuffer;
    /* Temporary buffer to concatenate all chunks of a codebock */
    OPJ_BYTE    *cblkdatabuffer;
    /* Maximum size available in cblkdatabuffer */
    OPJ_UINT32   cblkdatabuffersize;
} opj_t1_t;

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**
Encode the code-blocks of a tile
@param t1 T1 handle
@param tile The tile to encode
@param tcp Tile coding parameters
@param mct_norms  FIXME DOC
@param mct_numcomps Number of components used for MCT
*/
OPJ_BOOL opj_t1_encode_cblks(opj_t1_t *t1,
                             opj_tcd_tile_t *tile,
                             opj_tcp_t *tcp,
                             const OPJ_FLOAT64 * mct_norms,
                             OPJ_UINT32 mct_numcomps);

/**
Decode the code-blocks of a tile







<

















|





|







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
       as done in the various decoding steps. */
    opj_flag_t *flags;

    OPJ_UINT32 w;
    OPJ_UINT32 h;
    OPJ_UINT32 datasize;
    OPJ_UINT32 flagssize;

    OPJ_BOOL   encoder;

    /* Thre 3 variables below are only used by the decoder */
    /* set to TRUE in multithreaded context */
    OPJ_BOOL     mustuse_cblkdatabuffer;
    /* Temporary buffer to concatenate all chunks of a codebock */
    OPJ_BYTE    *cblkdatabuffer;
    /* Maximum size available in cblkdatabuffer */
    OPJ_UINT32   cblkdatabuffersize;
} opj_t1_t;

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**
Encode the code-blocks of a tile
@param tcd TCD handle
@param tile The tile to encode
@param tcp Tile coding parameters
@param mct_norms  FIXME DOC
@param mct_numcomps Number of components used for MCT
*/
OPJ_BOOL opj_t1_encode_cblks(opj_tcd_t* tcd,
                             opj_tcd_tile_t *tile,
                             opj_tcp_t *tcp,
                             const OPJ_FLOAT64 * mct_norms,
                             OPJ_UINT32 mct_numcomps);

/**
Decode the code-blocks of a tile
Changes to jni/openjpeg/src/lib/openjp2/t2.c.
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
                               OPJ_UINT32 p_tile_no,
                               opj_tcd_tile_t *p_tile,
                               OPJ_UINT32 p_maxlayers,
                               OPJ_BYTE *p_dest,
                               OPJ_UINT32 * p_data_written,
                               OPJ_UINT32 p_max_len,
                               opj_codestream_info_t *cstr_info,

                               OPJ_UINT32 p_tp_num,
                               OPJ_INT32 p_tp_pos,
                               OPJ_UINT32 p_pino,
                               J2K_T2_MODE p_t2_mode,
                               opj_event_mgr_t *p_manager)
{
    OPJ_BYTE *l_current_data = p_dest;
    OPJ_UINT32 l_nb_bytes = 0;
    OPJ_UINT32 compno;
    OPJ_UINT32 poc;
    opj_pi_iterator_t *l_pi = 00;
    opj_pi_iterator_t *l_current_pi = 00;
    opj_image_t *l_image = p_t2->image;
    opj_cp_t *l_cp = p_t2->cp;
    opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
    OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K) ? 2 : 1;
    OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ?
                            l_image->numcomps : 1;
    OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;

    l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode);
    if (!l_pi) {
        return OPJ_FALSE;
    }

    * p_data_written = 0;

    if (p_t2_mode == THRESH_CALC) { /* Calculating threshold */







>




















|







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
                               OPJ_UINT32 p_tile_no,
                               opj_tcd_tile_t *p_tile,
                               OPJ_UINT32 p_maxlayers,
                               OPJ_BYTE *p_dest,
                               OPJ_UINT32 * p_data_written,
                               OPJ_UINT32 p_max_len,
                               opj_codestream_info_t *cstr_info,
                               opj_tcd_marker_info_t* p_marker_info,
                               OPJ_UINT32 p_tp_num,
                               OPJ_INT32 p_tp_pos,
                               OPJ_UINT32 p_pino,
                               J2K_T2_MODE p_t2_mode,
                               opj_event_mgr_t *p_manager)
{
    OPJ_BYTE *l_current_data = p_dest;
    OPJ_UINT32 l_nb_bytes = 0;
    OPJ_UINT32 compno;
    OPJ_UINT32 poc;
    opj_pi_iterator_t *l_pi = 00;
    opj_pi_iterator_t *l_current_pi = 00;
    opj_image_t *l_image = p_t2->image;
    opj_cp_t *l_cp = p_t2->cp;
    opj_tcp_t *l_tcp = &l_cp->tcps[p_tile_no];
    OPJ_UINT32 pocno = (l_cp->rsiz == OPJ_PROFILE_CINEMA_4K) ? 2 : 1;
    OPJ_UINT32 l_max_comp = l_cp->m_specific_param.m_enc.m_max_comp_size > 0 ?
                            l_image->numcomps : 1;
    OPJ_UINT32 l_nb_pocs = l_tcp->numpocs + 1;

    l_pi = opj_pi_initialise_encode(l_image, l_cp, p_tile_no, p_t2_mode, p_manager);
    if (!l_pi) {
        return OPJ_FALSE;
    }

    * p_data_written = 0;

    if (p_t2_mode == THRESH_CALC) { /* Calculating threshold */
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

        l_current_pi = &l_pi[p_pino];
        if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
            /* TODO ADE : add an error */
            opj_pi_destroy(l_pi, l_nb_pocs);
            return OPJ_FALSE;
        }














        while (opj_pi_next(l_current_pi)) {
            if (l_current_pi->layno < p_maxlayers) {
                l_nb_bytes = 0;

                if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
                                           l_current_data, &l_nb_bytes, p_max_len,
                                           cstr_info, p_t2_mode, p_manager)) {
                    opj_pi_destroy(l_pi, l_nb_pocs);
                    return OPJ_FALSE;
                }

                l_current_data += l_nb_bytes;
                p_max_len -= l_nb_bytes;

                * p_data_written += l_nb_bytes;






                /* INDEX >> */
                if (cstr_info) {
                    if (cstr_info->index_write) {
                        opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
                        opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
                        if (!cstr_info->packno) {







>
>
>
>
>
>
>
>
>
>
>
>
>
>















>
>
>
>
>







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

        l_current_pi = &l_pi[p_pino];
        if (l_current_pi->poc.prg == OPJ_PROG_UNKNOWN) {
            /* TODO ADE : add an error */
            opj_pi_destroy(l_pi, l_nb_pocs);
            return OPJ_FALSE;
        }

        if (p_marker_info && p_marker_info->need_PLT) {
            /* One time use intended */
            assert(p_marker_info->packet_count == 0);
            assert(p_marker_info->p_packet_size == NULL);

            p_marker_info->p_packet_size = (OPJ_UINT32*) opj_malloc(
                                               opj_get_encoding_packet_count(l_image, l_cp, p_tile_no) * sizeof(OPJ_UINT32));
            if (p_marker_info->p_packet_size == NULL) {
                opj_pi_destroy(l_pi, l_nb_pocs);
                return OPJ_FALSE;
            }
        }

        while (opj_pi_next(l_current_pi)) {
            if (l_current_pi->layno < p_maxlayers) {
                l_nb_bytes = 0;

                if (! opj_t2_encode_packet(p_tile_no, p_tile, l_tcp, l_current_pi,
                                           l_current_data, &l_nb_bytes, p_max_len,
                                           cstr_info, p_t2_mode, p_manager)) {
                    opj_pi_destroy(l_pi, l_nb_pocs);
                    return OPJ_FALSE;
                }

                l_current_data += l_nb_bytes;
                p_max_len -= l_nb_bytes;

                * p_data_written += l_nb_bytes;

                if (p_marker_info && p_marker_info->need_PLT) {
                    p_marker_info->p_packet_size[p_marker_info->packet_count] = l_nb_bytes;
                    p_marker_info->packet_count ++;
                }

                /* INDEX >> */
                if (cstr_info) {
                    if (cstr_info->index_write) {
                        opj_tile_info_t *info_TL = &cstr_info->tile[p_tile_no];
                        opj_packet_info_t *info_PK = &info_TL->packet[cstr_info->packno];
                        if (!cstr_info->packno) {
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#ifdef TODO_MSD
    if (p_cstr_index) {
        l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
    }
#endif

    /* create a packet iterator */
    l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no);
    if (!l_pi) {
        return OPJ_FALSE;
    }


    l_current_pi = l_pi;








|







421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
#ifdef TODO_MSD
    if (p_cstr_index) {
        l_pack_info = p_cstr_index->tile_index[p_tile_no].packet;
    }
#endif

    /* create a packet iterator */
    l_pi = opj_pi_create_decode(l_image, l_cp, p_tile_no, p_manager);
    if (!l_pi) {
        return OPJ_FALSE;
    }


    l_current_pi = l_pi;

668
669
670
671
672
673
674








675
676
677
678
679
680
681

    opj_bio_t *bio = 00;    /* BIO component */
#ifdef ENABLE_EMPTY_PACKET_OPTIMIZATION
    OPJ_BOOL packet_empty = OPJ_TRUE;
#else
    OPJ_BOOL packet_empty = OPJ_FALSE;
#endif









    /* <SOP 0xff91> */
    if (tcp->csty & J2K_CP_CSTY_SOP) {
        if (length < 6) {
            if (p_t2_mode == FINAL_PASS) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "opj_t2_encode_packet(): only %u bytes remaining in "







>
>
>
>
>
>
>
>







688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709

    opj_bio_t *bio = 00;    /* BIO component */
#ifdef ENABLE_EMPTY_PACKET_OPTIMIZATION
    OPJ_BOOL packet_empty = OPJ_TRUE;
#else
    OPJ_BOOL packet_empty = OPJ_FALSE;
#endif

#ifdef DEBUG_VERBOSE
    if (p_t2_mode == FINAL_PASS) {
        fprintf(stderr,
                "encode packet compono=%d, resno=%d, precno=%d, layno=%d\n",
                compno, resno, precno, layno);
    }
#endif

    /* <SOP 0xff91> */
    if (tcp->csty & J2K_CP_CSTY_SOP) {
        if (length < 6) {
            if (p_t2_mode == FINAL_PASS) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "opj_t2_encode_packet(): only %u bytes remaining in "
706
707
708
709
710
711
712









713
714
715
716
717
718
719
        for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
            opj_tcd_precinct_t *prc;

            /* Skip empty bands */
            if (opj_tcd_is_band_empty(band)) {
                continue;
            }










            prc = &band->precincts[precno];
            opj_tgt_reset(prc->incltree);
            opj_tgt_reset(prc->imsbtree);

            l_nb_blocks = prc->cw * prc->ch;
            for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {







>
>
>
>
>
>
>
>
>







734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
        for (bandno = 0; bandno < res->numbands; ++bandno, ++band) {
            opj_tcd_precinct_t *prc;

            /* Skip empty bands */
            if (opj_tcd_is_band_empty(band)) {
                continue;
            }

            /* Avoid out of bounds access of https://github.com/uclouvain/openjpeg/issues/1294 */
            /* but likely not a proper fix. */
            if (precno >= res->pw * res->ph) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "opj_t2_encode_packet(): accessing precno=%u >= %u\n",
                              precno, res->pw * res->ph);
                return OPJ_FALSE;
            }

            prc = &band->precincts[precno];
            opj_tgt_reset(prc->incltree);
            opj_tgt_reset(prc->imsbtree);

            l_nb_blocks = prc->cw * prc->ch;
            for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
773
774
775
776
777
778
779









780
781
782
783
784
785
786
            bandno < res->numbands; ++bandno, ++band)      {
        opj_tcd_precinct_t *prc;

        /* Skip empty bands */
        if (opj_tcd_is_band_empty(band)) {
            continue;
        }










        prc = &band->precincts[precno];
        l_nb_blocks = prc->cw * prc->ch;
        cblk = prc->cblks.enc;

        for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
            opj_tcd_layer_t *layer = &cblk->layers[layno];







>
>
>
>
>
>
>
>
>







810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
            bandno < res->numbands; ++bandno, ++band)      {
        opj_tcd_precinct_t *prc;

        /* Skip empty bands */
        if (opj_tcd_is_band_empty(band)) {
            continue;
        }

        /* Avoid out of bounds access of https://github.com/uclouvain/openjpeg/issues/1297 */
        /* but likely not a proper fix. */
        if (precno >= res->pw * res->ph) {
            opj_event_msg(p_manager, EVT_ERROR,
                          "opj_t2_encode_packet(): accessing precno=%u >= %u\n",
                          precno, res->pw * res->ph);
            return OPJ_FALSE;
        }

        prc = &band->precincts[precno];
        l_nb_blocks = prc->cw * prc->ch;
        cblk = prc->cblks.enc;

        for (cblkno = 0; cblkno < l_nb_blocks; ++cblkno) {
            opj_tcd_layer_t *layer = &cblk->layers[layno];
Changes to jni/openjpeg/src/lib/openjp2/t2.h.
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
@param tileno           number of the tile encoded
@param tile             the tile for which to write the packets
@param maxlayers        maximum number of layers
@param dest             the destination buffer
@param p_data_written   FIXME DOC
@param len              the length of the destination buffer
@param cstr_info        Codestream information structure

@param tpnum            Tile part number of the current tile
@param tppos            The position of the tile part flag in the progression order
@param pino             FIXME DOC
@param t2_mode          If == THRESH_CALC In Threshold calculation ,If == FINAL_PASS Final pass
@param p_manager        the user event manager
*/
OPJ_BOOL opj_t2_encode_packets(opj_t2_t* t2,
                               OPJ_UINT32 tileno,
                               opj_tcd_tile_t *tile,
                               OPJ_UINT32 maxlayers,
                               OPJ_BYTE *dest,
                               OPJ_UINT32 * p_data_written,
                               OPJ_UINT32 len,
                               opj_codestream_info_t *cstr_info,

                               OPJ_UINT32 tpnum,
                               OPJ_INT32 tppos,
                               OPJ_UINT32 pino,
                               J2K_T2_MODE t2_mode,
                               opj_event_mgr_t *p_manager);

/**







>














>







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
@param tileno           number of the tile encoded
@param tile             the tile for which to write the packets
@param maxlayers        maximum number of layers
@param dest             the destination buffer
@param p_data_written   FIXME DOC
@param len              the length of the destination buffer
@param cstr_info        Codestream information structure
@param p_marker_info    Marker information structure
@param tpnum            Tile part number of the current tile
@param tppos            The position of the tile part flag in the progression order
@param pino             FIXME DOC
@param t2_mode          If == THRESH_CALC In Threshold calculation ,If == FINAL_PASS Final pass
@param p_manager        the user event manager
*/
OPJ_BOOL opj_t2_encode_packets(opj_t2_t* t2,
                               OPJ_UINT32 tileno,
                               opj_tcd_tile_t *tile,
                               OPJ_UINT32 maxlayers,
                               OPJ_BYTE *dest,
                               OPJ_UINT32 * p_data_written,
                               OPJ_UINT32 len,
                               opj_codestream_info_t *cstr_info,
                               opj_tcd_marker_info_t* p_marker_info,
                               OPJ_UINT32 tpnum,
                               OPJ_INT32 tppos,
                               OPJ_UINT32 pino,
                               J2K_T2_MODE t2_mode,
                               opj_event_mgr_t *p_manager);

/**
Changes to jni/openjpeg/src/lib/openjp2/tcd.c.
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
}
#endif

/**
 * Initializes tile coding/decoding
 */
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
        OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
        opj_event_mgr_t* manager);

/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
        p_code_block);







|







108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
}
#endif

/**
 * Initializes tile coding/decoding
 */
static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
        OPJ_BOOL isEncoder, OPJ_SIZE_T sizeof_block,
        opj_event_mgr_t* manager);

/**
* Allocates memory for a decoding code block.
*/
static OPJ_BOOL opj_tcd_code_block_dec_allocate(opj_tcd_cblk_dec_t *
        p_code_block);
178
179
180
181
182
183
184

185
186
187
188
189
190
191
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd);

static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_max_dest_size,
                                  opj_codestream_info_t *p_cstr_info,

                                  opj_event_mgr_t *p_manager);

static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
        OPJ_BYTE * p_dest_data,
        OPJ_UINT32 p_max_dest_size,
        opj_codestream_info_t *p_cstr_info,
        opj_event_mgr_t *p_manager);







>







178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd);

static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_max_dest_size,
                                  opj_codestream_info_t *p_cstr_info,
                                  opj_tcd_marker_info_t* p_marker_info,
                                  opj_event_mgr_t *p_manager);

static OPJ_BOOL opj_tcd_rate_allocate_encode(opj_tcd_t *p_tcd,
        OPJ_BYTE * p_dest_data,
        OPJ_UINT32 p_max_dest_size,
        opj_codestream_info_t *p_cstr_info,
        opj_event_mgr_t *p_manager);
569
570
571
572
573
574
575
576
577
578

579
580
581
582
583
584
585
                OPJ_FLOAT64 distoachieved = 0;  /* fixed_quality */

                thresh = (lo + hi) / 2;

                opj_tcd_makelayer(tcd, layno, thresh, 0);

                if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* fixed_quality */
                    if (OPJ_IS_CINEMA(cp->rsiz)) {
                        if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
                                                    p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,

                                                    THRESH_CALC, p_manager)) {

                            lo = thresh;
                            continue;
                        } else {
                            distoachieved = layno == 0 ?
                                            tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];







|

|
>







570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
                OPJ_FLOAT64 distoachieved = 0;  /* fixed_quality */

                thresh = (lo + hi) / 2;

                opj_tcd_makelayer(tcd, layno, thresh, 0);

                if (cp->m_specific_param.m_enc.m_fixed_quality) {       /* fixed_quality */
                    if (OPJ_IS_CINEMA(cp->rsiz) || OPJ_IS_IMF(cp->rsiz)) {
                        if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
                                                    p_data_written, maxlen, cstr_info, NULL, tcd->cur_tp_num, tcd->tp_pos,
                                                    tcd->cur_pino,
                                                    THRESH_CALC, p_manager)) {

                            lo = thresh;
                            continue;
                        } else {
                            distoachieved = layno == 0 ?
                                            tcd_tile->distolayer[0] : cumdisto[layno - 1] + tcd_tile->distolayer[layno];
601
602
603
604
605
606
607
608

609
610
611
612
613
614
615
                            stable_thresh = thresh;
                            continue;
                        }
                        lo = thresh;
                    }
                } else {
                    if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
                                                p_data_written, maxlen, cstr_info, tcd->cur_tp_num, tcd->tp_pos, tcd->cur_pino,

                                                THRESH_CALC, p_manager)) {
                        /* TODO: what to do with l ??? seek / tell ??? */
                        /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
                        lo = thresh;
                        continue;
                    }








|
>







603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
                            stable_thresh = thresh;
                            continue;
                        }
                        lo = thresh;
                    }
                } else {
                    if (! opj_t2_encode_packets(t2, tcd->tcd_tileno, tcd_tile, layno + 1, dest,
                                                p_data_written, maxlen, cstr_info, NULL, tcd->cur_tp_num, tcd->tp_pos,
                                                tcd->cur_pino,
                                                THRESH_CALC, p_manager)) {
                        /* TODO: what to do with l ??? seek / tell ??? */
                        /* opj_event_msg(tcd->cinfo, EVT_INFO, "rate alloc: len=%d, max=%d\n", l, maxlen); */
                        lo = thresh;
                        continue;
                    }

714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
    }
    return OPJ_TRUE;
}

/* ----------------------------------------------------------------------- */

static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
        OPJ_BOOL isEncoder, OPJ_FLOAT32 fraction, OPJ_SIZE_T sizeof_block,
        opj_event_mgr_t* manager)
{
    OPJ_UINT32(*l_gain_ptr)(OPJ_UINT32) = 00;
    OPJ_UINT32 compno, resno, bandno, precno, cblkno;
    opj_tcp_t * l_tcp = 00;
    opj_cp_t * l_cp = 00;
    opj_tcd_tile_t * l_tile = 00;
    opj_tccp_t *l_tccp = 00;
    opj_tcd_tilecomp_t *l_tilec = 00;
    opj_image_comp_t * l_image_comp = 00;
    opj_tcd_resolution_t *l_res = 00;
    opj_tcd_band_t *l_band = 00;
    opj_stepsize_t * l_step_size = 00;
    opj_tcd_precinct_t *l_current_precinct = 00;
    opj_image_t *l_image = 00;
    OPJ_UINT32 p, q;
    OPJ_UINT32 l_level_no;
    OPJ_UINT32 l_pdx, l_pdy;
    OPJ_UINT32 l_gain;
    OPJ_INT32 l_x0b, l_y0b;
    OPJ_UINT32 l_tx0, l_ty0;
    /* extent of precincts , top left, bottom right**/
    OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
    /* number of precinct for a resolution */
    OPJ_UINT32 l_nb_precincts;
    /* room needed to store l_nb_precinct precinct for a resolution */







|


<















<







717
718
719
720
721
722
723
724
725
726

727
728
729
730
731
732
733
734
735
736
737
738
739
740
741

742
743
744
745
746
747
748
    }
    return OPJ_TRUE;
}

/* ----------------------------------------------------------------------- */

static INLINE OPJ_BOOL opj_tcd_init_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
        OPJ_BOOL isEncoder, OPJ_SIZE_T sizeof_block,
        opj_event_mgr_t* manager)
{

    OPJ_UINT32 compno, resno, bandno, precno, cblkno;
    opj_tcp_t * l_tcp = 00;
    opj_cp_t * l_cp = 00;
    opj_tcd_tile_t * l_tile = 00;
    opj_tccp_t *l_tccp = 00;
    opj_tcd_tilecomp_t *l_tilec = 00;
    opj_image_comp_t * l_image_comp = 00;
    opj_tcd_resolution_t *l_res = 00;
    opj_tcd_band_t *l_band = 00;
    opj_stepsize_t * l_step_size = 00;
    opj_tcd_precinct_t *l_current_precinct = 00;
    opj_image_t *l_image = 00;
    OPJ_UINT32 p, q;
    OPJ_UINT32 l_level_no;
    OPJ_UINT32 l_pdx, l_pdy;

    OPJ_INT32 l_x0b, l_y0b;
    OPJ_UINT32 l_tx0, l_ty0;
    /* extent of precincts , top left, bottom right**/
    OPJ_INT32 l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end, l_br_prc_y_end;
    /* number of precinct for a resolution */
    OPJ_UINT32 l_nb_precincts;
    /* room needed to store l_nb_precinct precinct for a resolution */
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
                   l_data_size - l_tilec->resolutions_size);
            l_tilec->resolutions_size = l_data_size;
        }

        l_level_no = l_tilec->numresolutions;
        l_res = l_tilec->resolutions;
        l_step_size = l_tccp->stepsizes;
        if (l_tccp->qmfbid == 0) {
            l_gain_ptr = &opj_dwt_getgain_real;
        } else {
            l_gain_ptr  = &opj_dwt_getgain;
        }
        /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/

        for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
            /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
            OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
            OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
            OPJ_UINT32 cblkwidthexpn, cblkheightexpn;







<
<
<
<
<







873
874
875
876
877
878
879





880
881
882
883
884
885
886
                   l_data_size - l_tilec->resolutions_size);
            l_tilec->resolutions_size = l_data_size;
        }

        l_level_no = l_tilec->numresolutions;
        l_res = l_tilec->resolutions;
        l_step_size = l_tccp->stepsizes;





        /*fprintf(stderr, "\tlevel_no=%d\n",l_level_no);*/

        for (resno = 0; resno < l_tilec->numresolutions; ++resno) {
            /*fprintf(stderr, "\t\tresno = %d/%d\n", resno, l_tilec->numresolutions);*/
            OPJ_INT32 tlcbgxstart, tlcbgystart /*, brcbgxend, brcbgyend*/;
            OPJ_UINT32 cbgwidthexpn, cbgheightexpn;
            OPJ_UINT32 cblkwidthexpn, cblkheightexpn;
901
902
903
904
905
906
907







908








909

910
911
912
913
914
915
916
            /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
            l_pdx = l_tccp->prcw[resno];
            l_pdy = l_tccp->prch[resno];
            /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
            /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000)  */
            l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
            l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;







            l_br_prc_x_end = opj_int_ceildivpow2(l_res->x1, (OPJ_INT32)l_pdx) << l_pdx;








            l_br_prc_y_end = opj_int_ceildivpow2(l_res->y1, (OPJ_INT32)l_pdy) << l_pdy;

            /*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/

            l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
                            l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
            l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
                            l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
            /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/







>
>
>
>
>
>
>
|
>
>
>
>
>
>
>
>
|
>







897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
            /* p. 35, table A-23, ISO/IEC FDIS154444-1 : 2000 (18 august 2000) */
            l_pdx = l_tccp->prcw[resno];
            l_pdy = l_tccp->prch[resno];
            /*fprintf(stderr, "\t\t\tpdx=%d, pdy=%d\n", l_pdx, l_pdy);*/
            /* p. 64, B.6, ISO/IEC FDIS15444-1 : 2000 (18 august 2000)  */
            l_tl_prc_x_start = opj_int_floordivpow2(l_res->x0, (OPJ_INT32)l_pdx) << l_pdx;
            l_tl_prc_y_start = opj_int_floordivpow2(l_res->y0, (OPJ_INT32)l_pdy) << l_pdy;
            {
                OPJ_UINT32 tmp = ((OPJ_UINT32)opj_int_ceildivpow2(l_res->x1,
                                  (OPJ_INT32)l_pdx)) << l_pdx;
                if (tmp > (OPJ_UINT32)INT_MAX) {
                    opj_event_msg(manager, EVT_ERROR, "Integer overflow\n");
                    return OPJ_FALSE;
                }
                l_br_prc_x_end = (OPJ_INT32)tmp;
            }
            {
                OPJ_UINT32 tmp = ((OPJ_UINT32)opj_int_ceildivpow2(l_res->y1,
                                  (OPJ_INT32)l_pdy)) << l_pdy;
                if (tmp > (OPJ_UINT32)INT_MAX) {
                    opj_event_msg(manager, EVT_ERROR, "Integer overflow\n");
                    return OPJ_FALSE;
                }
                l_br_prc_y_end = (OPJ_INT32)tmp;
            }
            /*fprintf(stderr, "\t\t\tprc_x_start=%d, prc_y_start=%d, br_prc_x_end=%d, br_prc_y_end=%d \n", l_tl_prc_x_start, l_tl_prc_y_start, l_br_prc_x_end ,l_br_prc_y_end );*/

            l_res->pw = (l_res->x0 == l_res->x1) ? 0U : (OPJ_UINT32)((
                            l_br_prc_x_end - l_tl_prc_x_start) >> l_pdx);
            l_res->ph = (l_res->y0 == l_res->y1) ? 0U : (OPJ_UINT32)((
                            l_br_prc_y_end - l_tl_prc_y_start) >> l_pdy);
            /*fprintf(stderr, "\t\t\tres_pw=%d, res_ph=%d\n", l_res->pw, l_res->ph );*/
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
            }

            cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
            cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
            l_band = l_res->bands;

            for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {
                OPJ_INT32 numbps;
                /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/

                if (resno == 0) {
                    l_band->bandno = 0 ;
                    l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
                    l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
                    l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);







<







959
960
961
962
963
964
965

966
967
968
969
970
971
972
            }

            cblkwidthexpn = opj_uint_min(l_tccp->cblkw, cbgwidthexpn);
            cblkheightexpn = opj_uint_min(l_tccp->cblkh, cbgheightexpn);
            l_band = l_res->bands;

            for (bandno = 0; bandno < l_res->numbands; ++bandno, ++l_band, ++l_step_size) {

                /*fprintf(stderr, "\t\t\tband_no=%d/%d\n", bandno, l_res->numbands );*/

                if (resno == 0) {
                    l_band->bandno = 0 ;
                    l_band->x0 = opj_int_ceildivpow2(l_tilec->x0, (OPJ_INT32)l_level_no);
                    l_band->y0 = opj_int_ceildivpow2(l_tilec->y0, (OPJ_INT32)l_level_no);
                    l_band->x1 = opj_int_ceildivpow2(l_tilec->x1, (OPJ_INT32)l_level_no);
983
984
985
986
987
988
989
990







991


992



993
994


995
996
997
998
999
1000
1001
                        /* Do not zero l_band->precints to avoid leaks */
                        /* but make sure we don't use it later, since */
                        /* it will point to precincts of previous bands... */
                        continue;
                    }
                }

                /** avoid an if with storing function pointer */







                l_gain = (*l_gain_ptr)(l_band->bandno);


                numbps = (OPJ_INT32)(l_image_comp->prec + l_gain);



                l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
                                                  (OPJ_INT32)(numbps - l_step_size->expn)))) * fraction;


                /* Mb value of Equation E-2 in "E.1 Inverse quantization
                 * procedure" of the standard */
                l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
                                 1;

                if (!l_band->precincts && (l_nb_precincts > 0U)) {
                    l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */







<
>
>
>
>
>
>
>
|
>
>
|
>
>
>
|
|
>
>







994
995
996
997
998
999
1000

1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
                        /* Do not zero l_band->precints to avoid leaks */
                        /* but make sure we don't use it later, since */
                        /* it will point to precincts of previous bands... */
                        continue;
                    }
                }


                {
                    /* Table E-1 - Sub-band gains */
                    /* BUG_WEIRD_TWO_INVK (look for this identifier in dwt.c): */
                    /* the test (!isEncoder && l_tccp->qmfbid == 0) is strongly */
                    /* linked to the use of two_invK instead of invK */
                    const OPJ_INT32 log2_gain = (!isEncoder &&
                                                 l_tccp->qmfbid == 0) ? 0 : (l_band->bandno == 0) ? 0 :
                                                (l_band->bandno == 3) ? 2 : 1;

                    /* Nominal dynamic range. Equation E-4 */
                    const OPJ_INT32 Rb = (OPJ_INT32)l_image_comp->prec + log2_gain;

                    /* Delta_b value of Equation E-3 in "E.1 Inverse quantization
                    * procedure" of the standard */
                    l_band->stepsize = (OPJ_FLOAT32)(((1.0 + l_step_size->mant / 2048.0) * pow(2.0,
                                                      (OPJ_INT32)(Rb - l_step_size->expn))));
                }

                /* Mb value of Equation E-2 in "E.1 Inverse quantization
                 * procedure" of the standard */
                l_band->numbps = l_step_size->expn + (OPJ_INT32)l_tccp->numgbits -
                                 1;

                if (!l_band->precincts && (l_nb_precincts > 0U)) {
                    l_band->precincts = (opj_tcd_precinct_t *) opj_malloc(/*3 * */
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
    } /* compno */
    return OPJ_TRUE;
}

OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
                                  opj_event_mgr_t* p_manager)
{
    return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE, 1.0F,
                             sizeof(opj_tcd_cblk_enc_t), p_manager);
}

OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
                                  opj_event_mgr_t* p_manager)
{
    return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE, 0.5F,
                             sizeof(opj_tcd_cblk_dec_t), p_manager);
}

/**
 * Allocates memory for an encoding code block (but not data memory).
 */
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *







|






|







1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
    } /* compno */
    return OPJ_TRUE;
}

OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
                                  opj_event_mgr_t* p_manager)
{
    return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_TRUE,
                             sizeof(opj_tcd_cblk_enc_t), p_manager);
}

OPJ_BOOL opj_tcd_init_decode_tile(opj_tcd_t *p_tcd, OPJ_UINT32 p_tile_no,
                                  opj_event_mgr_t* p_manager)
{
    return opj_tcd_init_tile(p_tcd, p_tile_no, OPJ_FALSE,
                             sizeof(opj_tcd_cblk_dec_t), p_manager);
}

/**
 * Allocates memory for an encoding code block (but not data memory).
 */
static OPJ_BOOL opj_tcd_code_block_enc_allocate(opj_tcd_cblk_enc_t *
1215
1216
1217
1218
1219
1220
1221






1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
        p_code_block)
{
    OPJ_UINT32 l_data_size;

    /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
    /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */






    /* TODO: is there a theoretical upper-bound for the compressed code */
    /* block size ? */
    l_data_size = 2 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
                                   (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));

    if (l_data_size > p_code_block->data_size) {
        if (p_code_block->data) {
            /* We refer to data - 1 since below we incremented it */
            opj_free(p_code_block->data - 1);
        }
        p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);







>
>
>
>
>
>


|
|







1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
static OPJ_BOOL opj_tcd_code_block_enc_allocate_data(opj_tcd_cblk_enc_t *
        p_code_block)
{
    OPJ_UINT32 l_data_size;

    /* +1 is needed for https://github.com/uclouvain/openjpeg/issues/835 */
    /* and actually +2 required for https://github.com/uclouvain/openjpeg/issues/982 */
    /* and +7 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 3) */
    /* and +26 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 7) */
    /* and +28 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 44) */
    /* and +33 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 4) */
    /* and +63 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 4 -IMF 2K) */
    /* and +74 for https://github.com/uclouvain/openjpeg/issues/1283 (-M 4 -n 8 -s 7,7 -I) */
    /* TODO: is there a theoretical upper-bound for the compressed code */
    /* block size ? */
    l_data_size = 74 + (OPJ_UINT32)((p_code_block->x1 - p_code_block->x0) *
                                    (p_code_block->y1 - p_code_block->y0) * (OPJ_INT32)sizeof(OPJ_UINT32));

    if (l_data_size > p_code_block->data_size) {
        if (p_code_block->data) {
            /* We refer to data - 1 since below we incremented it */
            opj_free(p_code_block->data - 1);
        }
        p_code_block->data = (OPJ_BYTE*) opj_malloc(l_data_size + 1);
1350
1351
1352
1353
1354
1355
1356

1357
1358
1359
1360
1361
1362
1363

OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
                             OPJ_UINT32 p_tile_no,
                             OPJ_BYTE *p_dest,
                             OPJ_UINT32 * p_data_written,
                             OPJ_UINT32 p_max_length,
                             opj_codestream_info_t *p_cstr_info,

                             opj_event_mgr_t *p_manager)
{

    if (p_tcd->cur_tp_num == 0) {

        p_tcd->tcd_tileno = p_tile_no;
        p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];







>







1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394

OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
                             OPJ_UINT32 p_tile_no,
                             OPJ_BYTE *p_dest,
                             OPJ_UINT32 * p_data_written,
                             OPJ_UINT32 p_max_length,
                             opj_codestream_info_t *p_cstr_info,
                             opj_tcd_marker_info_t* p_marker_info,
                             opj_event_mgr_t *p_manager)
{

    if (p_tcd->cur_tp_num == 0) {

        p_tcd->tcd_tileno = p_tile_no;
        p_tcd->tcp = &p_tcd->cp->tcps[p_tile_no];
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
    /* INDEX */
    if (p_cstr_info) {
        p_cstr_info->index_write = 1;
    }
    /* FIXME _ProfStart(PGROUP_T2); */

    if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
                            p_cstr_info, p_manager)) {
        return OPJ_FALSE;
    }
    /* FIXME _ProfStop(PGROUP_T2); */

    /*---------------CLEAN-------------------*/

    return OPJ_TRUE;







|







1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
    /* INDEX */
    if (p_cstr_info) {
        p_cstr_info->index_write = 1;
    }
    /* FIXME _ProfStart(PGROUP_T2); */

    if (! opj_tcd_t2_encode(p_tcd, p_dest, p_data_written, p_max_length,
                            p_cstr_info, p_marker_info, p_manager)) {
        return OPJ_FALSE;
    }
    /* FIXME _ProfStop(PGROUP_T2); */

    /*---------------CLEAN-------------------*/

    return OPJ_TRUE;
2013
2014
2015
2016
2017
2018
2019

2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
}

static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
    opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
    opj_tcp_t * l_tcp = p_tcd->tcp;
    opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;

    OPJ_UINT32 l_samples, i;

    if (l_tcp->mct == 0 || p_tcd->used_component != NULL) {
        return OPJ_TRUE;
    }

    if (p_tcd->whole_tile_decoding) {
        opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
                                          l_tile_comp->minimum_num_resolutions - 1;

        /* A bit inefficient: we process more data than needed if */
        /* resno_decoded < l_tile_comp->minimum_num_resolutions-1, */
        /* but we would need to take into account a stride then */
        l_samples = (OPJ_UINT32)((res_comp0->x1 - res_comp0->x0) *
                                 (res_comp0->y1 - res_comp0->y0));
        if (l_tile->numcomps >= 3) {
            if (l_tile_comp->minimum_num_resolutions !=
                    l_tile->comps[1].minimum_num_resolutions ||
                    l_tile_comp->minimum_num_resolutions !=
                    l_tile->comps[2].minimum_num_resolutions) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "Tiles don't all have the same dimension. Skip the MCT step.\n");







>
|












|
|







2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
}

static OPJ_BOOL opj_tcd_mct_decode(opj_tcd_t *p_tcd, opj_event_mgr_t *p_manager)
{
    opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
    opj_tcp_t * l_tcp = p_tcd->tcp;
    opj_tcd_tilecomp_t * l_tile_comp = l_tile->comps;
    OPJ_SIZE_T l_samples;
    OPJ_UINT32 i;

    if (l_tcp->mct == 0 || p_tcd->used_component != NULL) {
        return OPJ_TRUE;
    }

    if (p_tcd->whole_tile_decoding) {
        opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
                                          l_tile_comp->minimum_num_resolutions - 1;

        /* A bit inefficient: we process more data than needed if */
        /* resno_decoded < l_tile_comp->minimum_num_resolutions-1, */
        /* but we would need to take into account a stride then */
        l_samples = (OPJ_SIZE_T)(res_comp0->x1 - res_comp0->x0) *
                    (OPJ_SIZE_T)(res_comp0->y1 - res_comp0->y0);
        if (l_tile->numcomps >= 3) {
            if (l_tile_comp->minimum_num_resolutions !=
                    l_tile->comps[1].minimum_num_resolutions ||
                    l_tile_comp->minimum_num_resolutions !=
                    l_tile->comps[2].minimum_num_resolutions) {
                opj_event_msg(p_manager, EVT_ERROR,
                              "Tiles don't all have the same dimension. Skip the MCT step.\n");
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
                return OPJ_FALSE;
            }
        }
    } else {
        opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
                                          p_tcd->image->comps[0].resno_decoded;

        l_samples = (res_comp0->win_x1 - res_comp0->win_x0) *
                    (res_comp0->win_y1 - res_comp0->win_y0);
        if (l_tile->numcomps >= 3) {
            opj_tcd_resolution_t* res_comp1 = l_tile->comps[1].resolutions +
                                              p_tcd->image->comps[1].resno_decoded;
            opj_tcd_resolution_t* res_comp2 = l_tile->comps[2].resolutions +
                                              p_tcd->image->comps[2].resno_decoded;
            /* testcase 1336.pdf.asan.47.376 */
            if (p_tcd->image->comps[0].resno_decoded !=







|
|







2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
                return OPJ_FALSE;
            }
        }
    } else {
        opj_tcd_resolution_t* res_comp0 = l_tile->comps[0].resolutions +
                                          p_tcd->image->comps[0].resno_decoded;

        l_samples = (OPJ_SIZE_T)(res_comp0->win_x1 - res_comp0->win_x0) *
                    (OPJ_SIZE_T)(res_comp0->win_y1 - res_comp0->win_y0);
        if (l_tile->numcomps >= 3) {
            opj_tcd_resolution_t* res_comp1 = l_tile->comps[1].resolutions +
                                              p_tcd->image->comps[1].resno_decoded;
            opj_tcd_resolution_t* res_comp2 = l_tile->comps[2].resolutions +
                                              p_tcd->image->comps[2].resno_decoded;
            /* testcase 1336.pdf.asan.47.376 */
            if (p_tcd->image->comps[0].resno_decoded !=
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342

        opj_free(p_precinct->cblks.enc);

        p_precinct->cblks.enc = 00;
    }
}

OPJ_SIZE_T opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd)
{
    OPJ_UINT32 i;
    OPJ_SIZE_T l_data_size = 0;
    opj_image_comp_t * l_img_comp = 00;
    opj_tcd_tilecomp_t * l_tilec = 00;
    OPJ_UINT32 l_size_comp, l_remaining;








|







2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374

        opj_free(p_precinct->cblks.enc);

        p_precinct->cblks.enc = 00;
    }
}

OPJ_SIZE_T opj_tcd_get_encoder_input_buffer_size(opj_tcd_t *p_tcd)
{
    OPJ_UINT32 i;
    OPJ_SIZE_T l_data_size = 0;
    opj_image_comp_t * l_img_comp = 00;
    opj_tcd_tilecomp_t * l_tilec = 00;
    OPJ_UINT32 l_size_comp, l_remaining;

2386
2387
2388
2389
2390
2391
2392

2393
2394
2395
2396
2397
2398
2399
2400
        if (l_tccp->qmfbid == 1) {
            for (i = 0; i < l_nb_elem; ++i) {
                *l_current_ptr -= l_tccp->m_dc_level_shift ;
                ++l_current_ptr;
            }
        } else {
            for (i = 0; i < l_nb_elem; ++i) {

                *l_current_ptr = (*l_current_ptr - l_tccp->m_dc_level_shift) * (1 << 11);
                ++l_current_ptr;
            }
        }

        ++l_img_comp;
        ++l_tccp;
        ++l_tile_comp;







>
|







2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
        if (l_tccp->qmfbid == 1) {
            for (i = 0; i < l_nb_elem; ++i) {
                *l_current_ptr -= l_tccp->m_dc_level_shift ;
                ++l_current_ptr;
            }
        } else {
            for (i = 0; i < l_nb_elem; ++i) {
                *((OPJ_FLOAT32 *) l_current_ptr) = (OPJ_FLOAT32)(*l_current_ptr -
                                                   l_tccp->m_dc_level_shift);
                ++l_current_ptr;
            }
        }

        ++l_img_comp;
        ++l_tccp;
        ++l_tile_comp;
2444
2445
2446
2447
2448
2449
2450
2451


2452

2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510

2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526

2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544

2545
2546
2547
2548
2549
2550
2551
                    p_tcd->image->comps->sgnd)) {
            opj_free(l_data);
            return OPJ_FALSE;
        }

        opj_free(l_data);
    } else if (l_tcp->tccps->qmfbid == 0) {
        opj_mct_encode_real(l_tile->comps[0].data, l_tile->comps[1].data,


                            l_tile->comps[2].data, samples);

    } else {
        opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
                       l_tile->comps[2].data, samples);
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
{
    opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
    opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
    opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
    OPJ_UINT32 compno;

    for (compno = 0; compno < l_tile->numcomps; ++compno) {
        if (l_tccp->qmfbid == 1) {
            if (! opj_dwt_encode(l_tile_comp)) {
                return OPJ_FALSE;
            }
        } else if (l_tccp->qmfbid == 0) {
            if (! opj_dwt_encode_real(l_tile_comp)) {
                return OPJ_FALSE;
            }
        }

        ++l_tile_comp;
        ++l_tccp;
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
{
    opj_t1_t * l_t1;
    const OPJ_FLOAT64 * l_mct_norms;
    OPJ_UINT32 l_mct_numcomps = 0U;
    opj_tcp_t * l_tcp = p_tcd->tcp;

    l_t1 = opj_t1_create(OPJ_TRUE);
    if (l_t1 == 00) {
        return OPJ_FALSE;
    }

    if (l_tcp->mct == 1) {
        l_mct_numcomps = 3U;
        /* irreversible encoding */
        if (l_tcp->tccps->qmfbid == 0) {
            l_mct_norms = opj_mct_get_mct_norms_real();
        } else {
            l_mct_norms = opj_mct_get_mct_norms();
        }
    } else {
        l_mct_numcomps = p_tcd->image->numcomps;
        l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
    }


    if (! opj_t1_encode_cblks(l_t1, p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
                              l_mct_numcomps)) {
        opj_t1_destroy(l_t1);
        return OPJ_FALSE;
    }

    opj_t1_destroy(l_t1);

    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_max_dest_size,
                                  opj_codestream_info_t *p_cstr_info,

                                  opj_event_mgr_t *p_manager)
{
    opj_t2_t * l_t2;

    l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
    if (l_t2 == 00) {
        return OPJ_FALSE;
    }

    if (! opj_t2_encode_packets(
                l_t2,
                p_tcd->tcd_tileno,
                p_tcd->tcd_image->tiles,
                p_tcd->tcp->numlayers,
                p_dest_data,
                p_data_written,
                p_max_dest_size,
                p_cstr_info,

                p_tcd->tp_num,
                p_tcd->tp_pos,
                p_tcd->cur_pino,
                FINAL_PASS,
                p_manager)) {
        opj_t2_destroy(l_t2);
        return OPJ_FALSE;







|
>
>
|
>

















|



|













<




<
<
<
<
<













>
|
|
<
<
<
<
<









>


















>







2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523

2524
2525
2526
2527





2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543





2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
                    p_tcd->image->comps->sgnd)) {
            opj_free(l_data);
            return OPJ_FALSE;
        }

        opj_free(l_data);
    } else if (l_tcp->tccps->qmfbid == 0) {
        opj_mct_encode_real(
            (OPJ_FLOAT32*)l_tile->comps[0].data,
            (OPJ_FLOAT32*)l_tile->comps[1].data,
            (OPJ_FLOAT32*)l_tile->comps[2].data,
            samples);
    } else {
        opj_mct_encode(l_tile->comps[0].data, l_tile->comps[1].data,
                       l_tile->comps[2].data, samples);
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_dwt_encode(opj_tcd_t *p_tcd)
{
    opj_tcd_tile_t * l_tile = p_tcd->tcd_image->tiles;
    opj_tcd_tilecomp_t * l_tile_comp = p_tcd->tcd_image->tiles->comps;
    opj_tccp_t * l_tccp = p_tcd->tcp->tccps;
    OPJ_UINT32 compno;

    for (compno = 0; compno < l_tile->numcomps; ++compno) {
        if (l_tccp->qmfbid == 1) {
            if (! opj_dwt_encode(p_tcd, l_tile_comp)) {
                return OPJ_FALSE;
            }
        } else if (l_tccp->qmfbid == 0) {
            if (! opj_dwt_encode_real(p_tcd, l_tile_comp)) {
                return OPJ_FALSE;
            }
        }

        ++l_tile_comp;
        ++l_tccp;
    }

    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_t1_encode(opj_tcd_t *p_tcd)
{

    const OPJ_FLOAT64 * l_mct_norms;
    OPJ_UINT32 l_mct_numcomps = 0U;
    opj_tcp_t * l_tcp = p_tcd->tcp;






    if (l_tcp->mct == 1) {
        l_mct_numcomps = 3U;
        /* irreversible encoding */
        if (l_tcp->tccps->qmfbid == 0) {
            l_mct_norms = opj_mct_get_mct_norms_real();
        } else {
            l_mct_norms = opj_mct_get_mct_norms();
        }
    } else {
        l_mct_numcomps = p_tcd->image->numcomps;
        l_mct_norms = (const OPJ_FLOAT64 *)(l_tcp->mct_norms);
    }

    return opj_t1_encode_cblks(p_tcd,
                               p_tcd->tcd_image->tiles, l_tcp, l_mct_norms,
                               l_mct_numcomps);






    return OPJ_TRUE;
}

static OPJ_BOOL opj_tcd_t2_encode(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest_data,
                                  OPJ_UINT32 * p_data_written,
                                  OPJ_UINT32 p_max_dest_size,
                                  opj_codestream_info_t *p_cstr_info,
                                  opj_tcd_marker_info_t* p_marker_info,
                                  opj_event_mgr_t *p_manager)
{
    opj_t2_t * l_t2;

    l_t2 = opj_t2_create(p_tcd->image, p_tcd->cp);
    if (l_t2 == 00) {
        return OPJ_FALSE;
    }

    if (! opj_t2_encode_packets(
                l_t2,
                p_tcd->tcd_tileno,
                p_tcd->tcd_image->tiles,
                p_tcd->tcp->numlayers,
                p_dest_data,
                p_data_written,
                p_max_dest_size,
                p_cstr_info,
                p_marker_info,
                p_tcd->tp_num,
                p_tcd->tp_pos,
                p_tcd->cur_pino,
                FINAL_PASS,
                p_manager)) {
        opj_t2_destroy(l_t2);
        return OPJ_FALSE;
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
    OPJ_SIZE_T j;
    OPJ_SIZE_T l_data_size = 0;
    opj_image_comp_t * l_img_comp = 00;
    opj_tcd_tilecomp_t * l_tilec = 00;
    OPJ_UINT32 l_size_comp, l_remaining;
    OPJ_SIZE_T l_nb_elem;

    l_data_size = opj_tcd_get_encoded_tile_size(p_tcd);
    if (l_data_size != p_src_length) {
        return OPJ_FALSE;
    }

    l_tilec = p_tcd->tcd_image->tiles->comps;
    l_img_comp = p_tcd->image->comps;
    for (i = 0; i < p_tcd->image->numcomps; ++i) {







|







2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
    OPJ_SIZE_T j;
    OPJ_SIZE_T l_data_size = 0;
    opj_image_comp_t * l_img_comp = 00;
    opj_tcd_tilecomp_t * l_tilec = 00;
    OPJ_UINT32 l_size_comp, l_remaining;
    OPJ_SIZE_T l_nb_elem;

    l_data_size = opj_tcd_get_encoder_input_buffer_size(p_tcd);
    if (l_data_size != p_src_length) {
        return OPJ_FALSE;
    }

    l_tilec = p_tcd->tcd_image->tiles->comps;
    l_img_comp = p_tcd->image->comps;
    for (i = 0; i < p_tcd->image->numcomps; ++i) {
2798
2799
2800
2801
2802
2803
2804



























            tcy1 <= (OPJ_UINT32)tilec->y1 &&
            (shift >= 32 ||
             (((tcx0 - (OPJ_UINT32)tilec->x0) >> shift) == 0 &&
              ((tcy0 - (OPJ_UINT32)tilec->y0) >> shift) == 0 &&
              (((OPJ_UINT32)tilec->x1 - tcx1) >> shift) == 0 &&
              (((OPJ_UINT32)tilec->y1 - tcy1) >> shift) == 0)));
}


































>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
            tcy1 <= (OPJ_UINT32)tilec->y1 &&
            (shift >= 32 ||
             (((tcx0 - (OPJ_UINT32)tilec->x0) >> shift) == 0 &&
              ((tcy0 - (OPJ_UINT32)tilec->y0) >> shift) == 0 &&
              (((OPJ_UINT32)tilec->x1 - tcx1) >> shift) == 0 &&
              (((OPJ_UINT32)tilec->y1 - tcy1) >> shift) == 0)));
}

/* ----------------------------------------------------------------------- */

opj_tcd_marker_info_t* opj_tcd_marker_info_create(OPJ_BOOL need_PLT)
{
    opj_tcd_marker_info_t *l_tcd_marker_info =
        (opj_tcd_marker_info_t*) opj_calloc(1, sizeof(opj_tcd_marker_info_t));
    if (!l_tcd_marker_info) {
        return NULL;
    }

    l_tcd_marker_info->need_PLT = need_PLT;

    return l_tcd_marker_info;
}

/* ----------------------------------------------------------------------- */

void opj_tcd_marker_info_destroy(opj_tcd_marker_info_t *p_tcd_marker_info)
{
    if (p_tcd_marker_info) {
        opj_free(p_tcd_marker_info->p_packet_size);
        opj_free(p_tcd_marker_info);
    }
}

/* ----------------------------------------------------------------------- */
Changes to jni/openjpeg/src/lib/openjp2/tcd.h.
280
281
282
283
284
285
286
















287
288
289
290
291
292
293
    OPJ_UINT32 win_y1;
    /** Only valid for decoding. Whether the whole tile is decoded, or just the region in win_x0/win_y0/win_x1/win_y1 */
    OPJ_BOOL   whole_tile_decoding;
    /* Array of size image->numcomps indicating if a component must be decoded. NULL if all components must be decoded */
    OPJ_BOOL* used_component;
} opj_tcd_t;

















/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**
Dump the content of a tcd structure
*/







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
    OPJ_UINT32 win_y1;
    /** Only valid for decoding. Whether the whole tile is decoded, or just the region in win_x0/win_y0/win_x1/win_y1 */
    OPJ_BOOL   whole_tile_decoding;
    /* Array of size image->numcomps indicating if a component must be decoded. NULL if all components must be decoded */
    OPJ_BOOL* used_component;
} opj_tcd_t;

/**
 * Structure to hold information needed to generate some markers.
 * Used by encoder.
 */
typedef struct opj_tcd_marker_info {
    /** In: Whether information to generate PLT markers in needed */
    OPJ_BOOL    need_PLT;

    /** OUT: Number of elements in p_packet_size[] array */
    OPJ_UINT32  packet_count;

    /** OUT: Array of size packet_count, such that p_packet_size[i] is
     *       the size in bytes of the ith packet */
    OPJ_UINT32* p_packet_size;
} opj_tcd_marker_info_t;

/** @name Exported functions */
/*@{*/
/* ----------------------------------------------------------------------- */

/**
Dump the content of a tcd structure
*/
301
302
303
304
305
306
307















308
309
310
311
312
313
314
opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder);

/**
Destroy a previously created TCD handle
@param tcd TCD handle to destroy
*/
void opj_tcd_destroy(opj_tcd_t *tcd);
















/**
 * Initialize the tile coder and may reuse some memory.
 * @param   p_tcd       TCD handle.
 * @param   p_image     raw image.
 * @param   p_cp        coding parameters.
 * @param   p_tp        thread pool







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
opj_tcd_t* opj_tcd_create(OPJ_BOOL p_is_decoder);

/**
Destroy a previously created TCD handle
@param tcd TCD handle to destroy
*/
void opj_tcd_destroy(opj_tcd_t *tcd);


/**
 * Create a new opj_tcd_marker_info_t* structure
 * @param need_PLT Whether information is needed to generate PLT markers.
 */
opj_tcd_marker_info_t* opj_tcd_marker_info_create(OPJ_BOOL need_PLT);


/**
Destroy a previously created opj_tcd_marker_info_t* structure
@param p_tcd_marker_info Structure to destroy
*/
void opj_tcd_marker_info_destroy(opj_tcd_marker_info_t *p_tcd_marker_info);


/**
 * Initialize the tile coder and may reuse some memory.
 * @param   p_tcd       TCD handle.
 * @param   p_image     raw image.
 * @param   p_cp        coding parameters.
 * @param   p_tp        thread pool
360
361
362
363
364
365
366

367
368
369
370
371
372
373
374
375

376
377
378
379
380
381
382
 * Encodes a tile from the raw image into the given buffer.
 * @param   p_tcd           Tile Coder handle
 * @param   p_tile_no       Index of the tile to encode.
 * @param   p_dest          Destination buffer
 * @param   p_data_written  pointer to an int that is incremented by the number of bytes really written on p_dest
 * @param   p_len           Maximum length of the destination buffer
 * @param   p_cstr_info     Codestream information structure

 * @param   p_manager       the user event manager
 * @return  true if the coding is successful.
*/
OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
                             OPJ_UINT32 p_tile_no,
                             OPJ_BYTE *p_dest,
                             OPJ_UINT32 * p_data_written,
                             OPJ_UINT32 p_len,
                             struct opj_codestream_info *p_cstr_info,

                             opj_event_mgr_t *p_manager);


/**
Decode a tile from a buffer into a raw image
@param tcd TCD handle
@param win_x0 Upper left x of region to decode (in grid coordinates)







>









>







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
 * Encodes a tile from the raw image into the given buffer.
 * @param   p_tcd           Tile Coder handle
 * @param   p_tile_no       Index of the tile to encode.
 * @param   p_dest          Destination buffer
 * @param   p_data_written  pointer to an int that is incremented by the number of bytes really written on p_dest
 * @param   p_len           Maximum length of the destination buffer
 * @param   p_cstr_info     Codestream information structure
 * @param   p_marker_info   Marker information structure
 * @param   p_manager       the user event manager
 * @return  true if the coding is successful.
*/
OPJ_BOOL opj_tcd_encode_tile(opj_tcd_t *p_tcd,
                             OPJ_UINT32 p_tile_no,
                             OPJ_BYTE *p_dest,
                             OPJ_UINT32 * p_data_written,
                             OPJ_UINT32 p_len,
                             struct opj_codestream_info *p_cstr_info,
                             opj_tcd_marker_info_t* p_marker_info,
                             opj_event_mgr_t *p_manager);


/**
Decode a tile from a buffer into a raw image
@param tcd TCD handle
@param win_x0 Upper left x of region to decode (in grid coordinates)
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
 * Copies tile data from the system onto the given memory block.
 */
OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest,
                                  OPJ_UINT32 p_dest_length);

/**
 *


 */
OPJ_SIZE_T opj_tcd_get_encoded_tile_size(opj_tcd_t *p_tcd);

/**
 * Initialize the tile coder and may reuse some meory.
 *
 * @param   p_tcd       TCD handle.
 * @param   p_tile_no   current tile index to encode.
 * @param p_manager the event manager.
 *
 * @return true if the encoding values could be set (false otherwise).
*/
OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd,
                                  OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager);

/**
 * Copies tile data from the given memory block onto the system.


 */
OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
                                OPJ_BYTE * p_src,
                                OPJ_SIZE_T p_src_length);

/**
 * Allocates tile component data







|
>
>

|















>
>







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
 * Copies tile data from the system onto the given memory block.
 */
OPJ_BOOL opj_tcd_update_tile_data(opj_tcd_t *p_tcd,
                                  OPJ_BYTE * p_dest,
                                  OPJ_UINT32 p_dest_length);

/**
 * Get the size in bytes of the input buffer provided before encoded.
 * This must be the size provided to the p_src_length argument of
 * opj_tcd_copy_tile_data()
 */
OPJ_SIZE_T opj_tcd_get_encoder_input_buffer_size(opj_tcd_t *p_tcd);

/**
 * Initialize the tile coder and may reuse some meory.
 *
 * @param   p_tcd       TCD handle.
 * @param   p_tile_no   current tile index to encode.
 * @param p_manager the event manager.
 *
 * @return true if the encoding values could be set (false otherwise).
*/
OPJ_BOOL opj_tcd_init_encode_tile(opj_tcd_t *p_tcd,
                                  OPJ_UINT32 p_tile_no, opj_event_mgr_t* p_manager);

/**
 * Copies tile data from the given memory block onto the system.
 *
 * p_src_length must be equal to opj_tcd_get_encoder_input_buffer_size()
 */
OPJ_BOOL opj_tcd_copy_tile_data(opj_tcd_t *p_tcd,
                                OPJ_BYTE * p_src,
                                OPJ_SIZE_T p_src_length);

/**
 * Allocates tile component data
Changes to jni/openjpeg/src/lib/openjp3d/t2.c.
264
265
266
267
268
269
270

271
272
273
274
275
276
277
            }

        }
    }


    if (bio_flush(bio)) {

        return -999;        /* modified to eliminate longjmp !! */
    }

    c += bio_numbytes(bio);

    bio_destroy(bio);








>







264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
            }

        }
    }


    if (bio_flush(bio)) {
        bio_destroy(bio);
        return -999;        /* modified to eliminate longjmp !! */
    }

    c += bio_numbytes(bio);

    bio_destroy(bio);

Changes to jni/openjpeg/src/lib/openjpip/auxtrans_manager.c.
227
228
229
230
231
232
233



234
235
236
237
238
239
240
                remlen -= maxLenOfBody;
                ptr += maxLenOfBody;
            }
            if (close_socket(connected_socket) != 0) {
                perror("close");
            }
            break;



        }
    }
    opj_free(chunk);

    delete_auxresponse(&auxresponse);

#ifdef _WIN32







>
>
>







227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
                remlen -= maxLenOfBody;
                ptr += maxLenOfBody;
            }
            if (close_socket(connected_socket) != 0) {
                perror("close");
            }
            break;
        }
        if (close_socket(connected_socket) != 0) {
            perror("close");
        }
    }
    opj_free(chunk);

    delete_auxresponse(&auxresponse);

#ifdef _WIN32
Changes to jni/openjpeg/src/lib/openjpip/box_manager.c.
207
208
209
210
211
212
213

214
215
216
217
218
219
220
                /* read XLBox*/
                if ((data2 = fetch_bytes(fd, pos + 8, 8))) {
                    boxlen = big8(data2);
                    free(data2);
                } else {
                    fprintf(FCGI_stderr, "Error: error in gene_boxbyType( %d, %" PRId64 ", %" PRId64
                            ", %s)\n", fd, offset, length, TBox);

                    return NULL;
                }
            }
            if (strncmp(boxtype, TBox, 4) == 0) {
                foundbox = (box_param_t *)malloc(sizeof(box_param_t));
                foundbox->fd = fd;
                foundbox->offset = pos;







>







207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
                /* read XLBox*/
                if ((data2 = fetch_bytes(fd, pos + 8, 8))) {
                    boxlen = big8(data2);
                    free(data2);
                } else {
                    fprintf(FCGI_stderr, "Error: error in gene_boxbyType( %d, %" PRId64 ", %" PRId64
                            ", %s)\n", fd, offset, length, TBox);
                    free(data);
                    return NULL;
                }
            }
            if (strncmp(boxtype, TBox, 4) == 0) {
                foundbox = (box_param_t *)malloc(sizeof(box_param_t));
                foundbox->fd = fd;
                foundbox->offset = pos;
Changes to jni/openjpeg/src/lib/openjpip/index_manager.c.
266
267
268
269
270
271
272

273
274
275
276
277
278
279
    }
    pos += obh->headlen;
    opj_free(obh);

    ni = fetch_DBox1byte(prxy, pos);
    if (ni != 1) {
        fprintf(FCGI_stderr, "Multiple indexes not supported\n");

        return OPJ_FALSE;
    }
    pos += 1;

    ioff = fetch_DBox8bytebigendian(prxy, pos);
    if (ioff != (Byte8_t)cidx->offset) {
        fprintf(FCGI_stderr, "Reference cidx offset in prxy box not correct\n");







>







266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
    }
    pos += obh->headlen;
    opj_free(obh);

    ni = fetch_DBox1byte(prxy, pos);
    if (ni != 1) {
        fprintf(FCGI_stderr, "Multiple indexes not supported\n");
        opj_free(prxy);
        return OPJ_FALSE;
    }
    pos += 1;

    ioff = fetch_DBox8bytebigendian(prxy, pos);
    if (ioff != (Byte8_t)cidx->offset) {
        fprintf(FCGI_stderr, "Reference cidx offset in prxy box not correct\n");
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
    manf_box = gene_boxbyType(cidx_box->fd, get_DBoxoff(cidx_box),
                              get_DBoxlen(cidx_box), "manf");
    manf = gene_manfbox(manf_box);

    if (!search_boxheader("mhix", manf)) {
        fprintf(FCGI_stderr, "Error: mhix box not present in manfbox\n");
        opj_free(jp2idx);

        return OPJ_FALSE;
    }
    set_mainmhixdata(cidx_box, codestream, jp2idx);

    if (!search_boxheader("tpix", manf)) {
        fprintf(FCGI_stderr, "Error: tpix box not present in manfbox\n");
        opj_free(jp2idx);

        return OPJ_FALSE;
    }
    set_tpixdata(cidx_box, jp2idx);

    if (!search_boxheader("thix", manf)) {
        fprintf(FCGI_stderr, "Error: thix box not present in manfbox\n");
        opj_free(jp2idx);

        return OPJ_FALSE;
    }
    set_thixdata(cidx_box, jp2idx);

    if (!search_boxheader("ppix", manf)) {
        fprintf(FCGI_stderr, "Error: ppix box not present in manfbox\n");
        opj_free(jp2idx);

        return OPJ_FALSE;
    }
    set_ppixdata(cidx_box, jp2idx);

    delete_manfbox(&manf);
    opj_free(manf_box);








>







>







>







>







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
    manf_box = gene_boxbyType(cidx_box->fd, get_DBoxoff(cidx_box),
                              get_DBoxlen(cidx_box), "manf");
    manf = gene_manfbox(manf_box);

    if (!search_boxheader("mhix", manf)) {
        fprintf(FCGI_stderr, "Error: mhix box not present in manfbox\n");
        opj_free(jp2idx);
        delete_manfbox(&manf);
        return OPJ_FALSE;
    }
    set_mainmhixdata(cidx_box, codestream, jp2idx);

    if (!search_boxheader("tpix", manf)) {
        fprintf(FCGI_stderr, "Error: tpix box not present in manfbox\n");
        opj_free(jp2idx);
        delete_manfbox(&manf);
        return OPJ_FALSE;
    }
    set_tpixdata(cidx_box, jp2idx);

    if (!search_boxheader("thix", manf)) {
        fprintf(FCGI_stderr, "Error: thix box not present in manfbox\n");
        opj_free(jp2idx);
        delete_manfbox(&manf);
        return OPJ_FALSE;
    }
    set_thixdata(cidx_box, jp2idx);

    if (!search_boxheader("ppix", manf)) {
        fprintf(FCGI_stderr, "Error: ppix box not present in manfbox\n");
        opj_free(jp2idx);
        delete_manfbox(&manf);
        return OPJ_FALSE;
    }
    set_ppixdata(cidx_box, jp2idx);

    delete_manfbox(&manf);
    opj_free(manf_box);

493
494
495
496
497
498
499

500
501
502
503
504
505
506
        fprintf(FCGI_stderr, "Error: tpix box not present in cidx box\n");
        return OPJ_FALSE;
    }

    if (!(faix_box = gene_boxbyType(tpix_box->fd, get_DBoxoff(tpix_box),
                                    get_DBoxlen(tpix_box), "faix"))) {
        fprintf(FCGI_stderr, "Error: faix box not present in tpix box\n");

        return OPJ_FALSE;
    }

    jp2idx->tilepart = gene_faixbox(faix_box);

    opj_free(tpix_box);
    opj_free(faix_box);







>







498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
        fprintf(FCGI_stderr, "Error: tpix box not present in cidx box\n");
        return OPJ_FALSE;
    }

    if (!(faix_box = gene_boxbyType(tpix_box->fd, get_DBoxoff(tpix_box),
                                    get_DBoxlen(tpix_box), "faix"))) {
        fprintf(FCGI_stderr, "Error: faix box not present in tpix box\n");
        opj_free(tpix_box);
        return OPJ_FALSE;
    }

    jp2idx->tilepart = gene_faixbox(faix_box);

    opj_free(tpix_box);
    opj_free(faix_box);
598
599
600
601
602
603
604

605
606
607
608
609

610
611
612
613
614
615
616
    jp2idx->precpacket = (faixbox_param_t **)opj_malloc(jp2idx->SIZ.Csiz * sizeof(
                             faixbox_param_t *));

    for (comp_idx = 0; bh != NULL; bh = bh->next, comp_idx++) {
        if (jp2idx->SIZ.Csiz <= comp_idx) {
            fprintf(FCGI_stderr,
                    "Error: num of faix boxes is not identical to num of components in ppix box\n");

            return OPJ_FALSE;
        }

        if (!(faix_box = gene_boxbyOffset(cidx_box->fd, inbox_offset))) {
            fprintf(FCGI_stderr, "Error: faix box not present in ppix box\n");

            return OPJ_FALSE;
        }

        faix = gene_faixbox(faix_box);
        jp2idx->precpacket[comp_idx] = faix;

        inbox_offset = faix_box->offset + (OPJ_OFF_T)faix_box->length;







>





>







604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
    jp2idx->precpacket = (faixbox_param_t **)opj_malloc(jp2idx->SIZ.Csiz * sizeof(
                             faixbox_param_t *));

    for (comp_idx = 0; bh != NULL; bh = bh->next, comp_idx++) {
        if (jp2idx->SIZ.Csiz <= comp_idx) {
            fprintf(FCGI_stderr,
                    "Error: num of faix boxes is not identical to num of components in ppix box\n");
            delete_manfbox(&manf);
            return OPJ_FALSE;
        }

        if (!(faix_box = gene_boxbyOffset(cidx_box->fd, inbox_offset))) {
            fprintf(FCGI_stderr, "Error: faix box not present in ppix box\n");
            delete_manfbox(&manf);
            return OPJ_FALSE;
        }

        faix = gene_faixbox(faix_box);
        jp2idx->precpacket[comp_idx] = faix;

        inbox_offset = faix_box->offset + (OPJ_OFF_T)faix_box->length;
Changes to jni/openjpeg/src/lib/openjpip/jp2k_decoder.c.
72
73
74
75
76
77
78


79
80
81
82
83
84
85
    opj_set_info_handler(l_codec, info_callback, 00);
    opj_set_warning_handler(l_codec, warning_callback, 00);
    opj_set_error_handler(l_codec, error_callback, 00);

    /* setup the decoder decoding parameters using user parameters */
    if (!opj_setup_decoder(l_codec, &parameters)) {
        fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");


        return NULL;
    }

    /* Read the main header of the codestream and if necessary the JP2 boxes*/
    if (! opj_read_header(l_stream, l_codec, &image)) {
        fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n");
        opj_stream_destroy(l_stream);







>
>







72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
    opj_set_info_handler(l_codec, info_callback, 00);
    opj_set_warning_handler(l_codec, warning_callback, 00);
    opj_set_error_handler(l_codec, error_callback, 00);

    /* setup the decoder decoding parameters using user parameters */
    if (!opj_setup_decoder(l_codec, &parameters)) {
        fprintf(stderr, "ERROR -> j2k_dump: failed to setup the decoder\n");
        opj_stream_destroy(l_stream);
        opj_destroy_codec(l_codec);
        return NULL;
    }

    /* Read the main header of the codestream and if necessary the JP2 boxes*/
    if (! opj_read_header(l_stream, l_codec, &image)) {
        fprintf(stderr, "ERROR -> j2k_to_image: failed to read the header\n");
        opj_stream_destroy(l_stream);
Changes to jni/openjpeg/src/lib/openjpip/openjpip.c.
353
354
355
356
357
358
359

360
361
362
363
364
365
366
367

368
369
370
371
372
373
374

    if ((infd = open(fname, O_RDONLY)) == -1) {
        fprintf(stderr, "file %s not exist\n", fname);
        return OPJ_FALSE;
    }

    if (!(dec->jpiplen = (Byte8_t)get_filesize(infd))) {

        return OPJ_FALSE;
    }

    dec->jpipstream = (Byte_t *)opj_malloc(dec->jpiplen);

    if (read(infd, dec->jpipstream, dec->jpiplen) != (int)dec->jpiplen) {
        fprintf(stderr, "file reading error\n");
        opj_free(dec->jpipstream);

        return OPJ_FALSE;
    }

    close(infd);

    return OPJ_TRUE;
}







>








>







353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376

    if ((infd = open(fname, O_RDONLY)) == -1) {
        fprintf(stderr, "file %s not exist\n", fname);
        return OPJ_FALSE;
    }

    if (!(dec->jpiplen = (Byte8_t)get_filesize(infd))) {
        close(infd);
        return OPJ_FALSE;
    }

    dec->jpipstream = (Byte_t *)opj_malloc(dec->jpiplen);

    if (read(infd, dec->jpipstream, dec->jpiplen) != (int)dec->jpiplen) {
        fprintf(stderr, "file reading error\n");
        opj_free(dec->jpipstream);
        close(infd);
        return OPJ_FALSE;
    }

    close(infd);

    return OPJ_TRUE;
}
Changes to jni/openjpeg/src/lib/openmj2/mj2.c.
2818
2819
2820
2821
2822
2823
2824






2825
2826
2827
2828

2829
2830
2831
2832
2833
2834

2835
2836
2837
2838
2839
2840
2841
        }
        cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 8);
        mj2_read_boxhdr(&box, cio);
    }

    fseek(file, foffset, SEEK_SET);
    src = (unsigned char*)opj_realloc(src, box.length);






    fsresult = fread(src, box.length, 1, file);
    if (fsresult != 1) {
        opj_event_msg(cio->cinfo, EVT_ERROR,
                      "End of file reached while trying to read MOOV box\n");

        return 1;
    }

    cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, box.length);

    if (mj2_read_moov(movie, &img, cio)) {

        return 1;
    }

    opj_free(src);
    return 0;
}








>
>
>
>
>
>




>






>







2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
        }
        cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, 8);
        mj2_read_boxhdr(&box, cio);
    }

    fseek(file, foffset, SEEK_SET);
    src = (unsigned char*)opj_realloc(src, box.length);
    if (src == NULL) {
        opj_event_msg(cio->cinfo, EVT_ERROR, "Error reallocation memory\n");
        opj_free(src);
        return 1;
    }

    fsresult = fread(src, box.length, 1, file);
    if (fsresult != 1) {
        opj_event_msg(cio->cinfo, EVT_ERROR,
                      "End of file reached while trying to read MOOV box\n");
        opj_free(src);
        return 1;
    }

    cio = opj_cio_open((opj_common_ptr)movie->cinfo, src, box.length);

    if (mj2_read_moov(movie, &img, cio)) {
        opj_free(src);
        return 1;
    }

    opj_free(src);
    return 0;
}

Changes to jni/openjpeg/src/lib/openmj2/mj2_convert.c.
58
59
60
61
62
63
64

65
66
67
68
69
70
71
    fseek(f, 0, SEEK_END);
    end_of_f = ftell(f);      /* Calculate file size */

    if (end_of_f < frame_size) {
        fprintf(stderr,
                "YUV does not contains any frame of %d x %d size\n", tk->w,
                tk->h);

        return 0;
    }
    fclose(f);

    return (unsigned int)(end_of_f / frame_size);
}








>







58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
    fseek(f, 0, SEEK_END);
    end_of_f = ftell(f);      /* Calculate file size */

    if (end_of_f < frame_size) {
        fprintf(stderr,
                "YUV does not contains any frame of %d x %d size\n", tk->w,
                tk->h);
        fclose(f);
        return 0;
    }
    fclose(f);

    return (unsigned int)(end_of_f / frame_size);
}

Changes to jni/openjpeg/tests/compare_images.c.
1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France 
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.

|







1
2
3
4
5
6
7
8
9
/*
 * Copyright (c) 2011-2012, Centre National d'Etudes Spatiales (CNES), France
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
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
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625






626
627

628


629
630
631
632
633

634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683

684
685
686
687

688
689
690
691
692
693
694

695
696

697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712

713
714
715
716

717
718
719
720
721
722
723
724
725
726
727
728

729
730

731
732
733
734
735
736
737
738
739
740
741
742

743
744
745
746
747
748
749
750
751
752
753
754

755
756

757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775

776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793

794
795
796
797
798

799

800
801
802
803
804


805
806
807
808
809
810
811

812
813
814
815
816
817

818
819
820
821
822

823
824

825
826
827
828
829
830
831
832
833
834
835

836
837
838
839










840
841

842
843
844

845
846
847
848
849
850
851
852
853

854
855
856
857
858

859
860

861

862

863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878

879

880

881

882
883
884
885

886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926

927
928
929
930
931

932
933

934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
#include <tiffio.h> /* TIFFSetWarningHandler */
#endif /* OPJ_HAVE_LIBTIFF */

/*******************************************************************************
 * Parse MSE and PEAK input values (
 * separator = ":"
 *******************************************************************************/
static double* parseToleranceValues( char* inArg, const int nbcomp)
{
  double* outArgs= malloc((size_t)nbcomp * sizeof(double));
  int it_comp = 0;
  const char delims[] = ":";
  char *result = strtok( inArg, delims );

  while( (result != NULL) && (it_comp < nbcomp ))
    {
    outArgs[it_comp] = atof(result);
    result = strtok( NULL, delims );
    it_comp++;
    }

  if (it_comp != nbcomp)
    {
    free(outArgs);
    return NULL;
    }
  /* else */
  return outArgs;
}

/*******************************************************************************
 * Command line help function
 *******************************************************************************/
static void compare_images_help_display(void)
{
  fprintf(stdout,"\nList of parameters for the compare_images function  \n");
  fprintf(stdout,"\n");

  fprintf(stdout,"  -b \t REQUIRED \t filename to the reference/baseline PGX/TIF/PNM image \n");
  fprintf(stdout,"  -t \t REQUIRED \t filename to the test PGX/TIF/PNM image\n");

  fprintf(stdout,"  -n \t REQUIRED \t number of component of the image (used to generate correct filename, not used when both input files are TIF)\n");

  fprintf(stdout,"  -m \t OPTIONAL \t list of MSE tolerances, separated by : (size must correspond to the number of component) of \n");

  fprintf(stdout,"  -p \t OPTIONAL \t list of PEAK tolerances, separated by : (size must correspond to the number of component) \n");

  fprintf(stdout,"  -s \t OPTIONAL \t 1 or 2 filename separator to take into account PGX/PNM image with different components, "
                                      "please indicate b or t before separator to indicate respectively the separator "
                                      "for ref/base file and for test file.  \n");

  fprintf(stdout,"  -d \t OPTIONAL \t indicate if you want to run this function as conformance test or as non regression test\n");


  fprintf(stdout,"\n");
}

static int get_decod_format_from_string(const char *filename)
{
  const int dot = '.';
  char * ext = strrchr(filename, dot);

  if( strcmp(ext,".pgx") == 0 ) return PGX_DFMT;


  if( strcmp(ext,".tif") == 0 ) return TIF_DFMT;


  if( strcmp(ext,".ppm") == 0 ) return PXM_DFMT;

  return -1;
}


/*******************************************************************************
 * Create filenames from a filename using separator and nb components
 * (begin from 0)
 *******************************************************************************/
static char* createMultiComponentsFilename(const char* inFilename, const int indexF, const char* separator)

{
  char s[255];
  char *outFilename, *ptr;
  const char token = '.';
  size_t posToken = 0;
  int decod_format;

  /*printf("inFilename = %s\n", inFilename);*/
  if ((ptr = strrchr(inFilename, token)) != NULL)
    {
    posToken = strlen(inFilename) - strlen(ptr);
    /*printf("Position of %c character inside inFilename = %d\n", token, posToken);*/
    }
  else
    {
    /*printf("Token %c not found\n", token);*/
    outFilename = (char*)malloc(1);
    outFilename[0] = '\0';
    return outFilename;
    }

  outFilename = (char*)malloc((posToken + 7) * sizeof(char)); /*6*/

  strncpy(outFilename, inFilename, posToken);
  outFilename[posToken] = '\0';
  strcat(outFilename, separator);
  sprintf(s, "%i", indexF);
  strcat(outFilename, s);

  decod_format = get_decod_format_from_string(inFilename);
  if( decod_format == PGX_DFMT )
    {
    strcat(outFilename, ".pgx");
    }
  else if( decod_format == PXM_DFMT )
    {
    strcat(outFilename, ".pgm");
    }

  /*printf("outfilename: %s\n", outFilename);*/
  return outFilename;
}

/*******************************************************************************
 *
 *******************************************************************************/
static opj_image_t* readImageFromFilePPM(const char* filename, int nbFilenamePGX, const char *separator)

{
  int it_file;
  opj_image_t* image_read = NULL;
  opj_image_t* image = NULL;
  opj_cparameters_t parameters;
  opj_image_cmptparm_t* param_image_read;
  int** data;

  /* If separator is empty => nb file to read is equal to one*/
  if ( strlen(separator) == 0 )
    nbFilenamePGX = 1;


  /* set encoding parameters to default values */
  opj_set_default_encoder_parameters(&parameters);
  parameters.decod_format = PXM_DFMT;
  strcpy(parameters.infile, filename);

  /* Allocate memory*/
  param_image_read = malloc((size_t)nbFilenamePGX * sizeof(opj_image_cmptparm_t));
  data = malloc((size_t)nbFilenamePGX * sizeof(*data));

  for (it_file = 0; it_file < nbFilenamePGX; it_file++)
    {
    /* Create the right filename*/
    char *filenameComponentPGX;
    if (strlen(separator) == 0)
      {
      filenameComponentPGX = malloc((strlen(filename) + 1) * sizeof(*filenameComponentPGX));

      strcpy(filenameComponentPGX, filename);
      }
    else
      filenameComponentPGX = createMultiComponentsFilename(filename, it_file, separator);



    /* Read the tif file corresponding to the component */
    image_read = pnmtoimage(filenameComponentPGX, &parameters);
    if (!image_read)
      {
      int it_free_data;
      fprintf(stderr, "Unable to load ppm file: %s\n", filenameComponentPGX);

      free(param_image_read);

      for (it_free_data = 0; it_free_data < it_file; it_free_data++) {
        free(data[it_free_data]);
      }
      free(data);

      free(filenameComponentPGX);

      return NULL;
      }

    /* Set the image_read parameters*/
    param_image_read[it_file].x0 = 0;
    param_image_read[it_file].y0 = 0;
    param_image_read[it_file].dx = 0;
    param_image_read[it_file].dy = 0;
    param_image_read[it_file].h = image_read->comps->h;
    param_image_read[it_file].w = image_read->comps->w;
    param_image_read[it_file].bpp = image_read->comps->bpp;
    param_image_read[it_file].prec = image_read->comps->prec;
    param_image_read[it_file].sgnd = image_read->comps->sgnd;

    /* Copy data*/
    data[it_file] = malloc(param_image_read[it_file].h * param_image_read[it_file].w * sizeof(int));

    memcpy(data[it_file], image_read->comps->data, image_read->comps->h * image_read->comps->w * sizeof(int));


    /* Free memory*/
    opj_image_destroy(image_read);
    free(filenameComponentPGX);
    }

  image = opj_image_create((OPJ_UINT32)nbFilenamePGX, param_image_read, OPJ_CLRSPC_UNSPECIFIED);

  for (it_file = 0; it_file < nbFilenamePGX; it_file++)
    {
    /* Copy data into output image and free memory*/
    memcpy(image->comps[it_file].data, data[it_file], image->comps[it_file].h * image->comps[it_file].w * sizeof(int));

    free(data[it_file]);
    }

  /* Free memory*/
  free(param_image_read);
  free(data);

  return image;
}

static opj_image_t* readImageFromFileTIF(const char* filename, int nbFilenamePGX, const char *separator)

{
  opj_image_t* image_read = NULL;
  opj_cparameters_t parameters;
  (void)nbFilenamePGX;
  (void)separator;

  /* conformance test suite produce annoying warning/error:
   * TIFFReadDirectory: Warning, /.../data/baseline/conformance/jp2_1.tif: unknown field with tag 37724 (0x935c) encountered.
   * TIFFOpen: /.../data/baseline/nonregression/opj_jp2_1.tif: Cannot open.
   * On Win32 this open a message box by default, so remove it from the test suite:
   */
#ifdef OPJ_HAVE_LIBTIFF
  TIFFSetWarningHandler(NULL);
  TIFFSetErrorHandler(NULL);
#endif

  if ( strlen(separator) != 0 ) return NULL;



  /* set encoding parameters to default values */
  opj_set_default_encoder_parameters(&parameters);
  parameters.decod_format = TIF_DFMT;
  strcpy(parameters.infile, filename);

  /* Read the tif file corresponding to the component */
#ifdef OPJ_HAVE_LIBTIFF
  image_read = tiftoimage(filename, &parameters);
#endif
  if (!image_read)
    {
    fprintf(stderr, "Unable to load TIF file\n");
    return NULL;
    }

  return image_read;
}

static opj_image_t* readImageFromFilePGX(const char* filename, int nbFilenamePGX, const char *separator)

{
  int it_file;
  opj_image_t* image_read = NULL;
  opj_image_t* image = NULL;
  opj_cparameters_t parameters;
  opj_image_cmptparm_t* param_image_read;
  int** data;

  /* If separator is empty => nb file to read is equal to one*/
  if ( strlen(separator) == 0 )
    nbFilenamePGX = 1;


  /* set encoding parameters to default values */
  opj_set_default_encoder_parameters(&parameters);
  parameters.decod_format = PGX_DFMT;
  strcpy(parameters.infile, filename);

  /* Allocate memory*/
  param_image_read = malloc((size_t)nbFilenamePGX * sizeof(opj_image_cmptparm_t));
  data = malloc((size_t)nbFilenamePGX * sizeof(*data));

  for (it_file = 0; it_file < nbFilenamePGX; it_file++)
    {
    /* Create the right filename*/
    char *filenameComponentPGX;
    if (strlen(separator) == 0)
      {
      filenameComponentPGX = malloc((strlen(filename) + 1) * sizeof(*filenameComponentPGX));

      strcpy(filenameComponentPGX, filename);
      }
    else
      filenameComponentPGX = createMultiComponentsFilename(filename, it_file, separator);



    /* Read the pgx file corresponding to the component */
    image_read = pgxtoimage(filenameComponentPGX, &parameters);
    if (!image_read)
      {
      int it_free_data;
      fprintf(stderr, "Unable to load pgx file\n");

      free(param_image_read);

      for (it_free_data = 0; it_free_data < it_file; it_free_data++) {
        free(data[it_free_data]);
      }
      free(data);

      free(filenameComponentPGX);

      return NULL;
      }

    /* Set the image_read parameters*/
    param_image_read[it_file].x0 = 0;
    param_image_read[it_file].y0 = 0;
    param_image_read[it_file].dx = 0;
    param_image_read[it_file].dy = 0;
    param_image_read[it_file].h = image_read->comps->h;
    param_image_read[it_file].w = image_read->comps->w;
    param_image_read[it_file].bpp = image_read->comps->bpp;
    param_image_read[it_file].prec = image_read->comps->prec;
    param_image_read[it_file].sgnd = image_read->comps->sgnd;

    /* Copy data*/
    data[it_file] = malloc(param_image_read[it_file].h * param_image_read[it_file].w * sizeof(int));

    memcpy(data[it_file], image_read->comps->data, image_read->comps->h * image_read->comps->w * sizeof(int));


    /* Free memory*/
    opj_image_destroy(image_read);
    free(filenameComponentPGX);
    }

  image = opj_image_create((OPJ_UINT32)nbFilenamePGX, param_image_read, OPJ_CLRSPC_UNSPECIFIED);

  for (it_file = 0; it_file < nbFilenamePGX; it_file++)
    {
    /* Copy data into output image and free memory*/
    memcpy(image->comps[it_file].data, data[it_file], image->comps[it_file].h * image->comps[it_file].w * sizeof(int));

    free(data[it_file]);
    }

  /* Free memory*/
  free(param_image_read);
  free(data);

  return image;
}

#if defined(OPJ_HAVE_LIBPNG) && 0 /* remove for now */
/*******************************************************************************
 *
 *******************************************************************************/
static int imageToPNG(const opj_image_t* image, const char* filename, int num_comp_select)

{
  opj_image_cmptparm_t param_image_write;
  opj_image_t* image_write = NULL;

  param_image_write.x0 = 0;
  param_image_write.y0 = 0;
  param_image_write.dx = 0;
  param_image_write.dy = 0;
  param_image_write.h = image->comps[num_comp_select].h;
  param_image_write.w = image->comps[num_comp_select].w;
  param_image_write.bpp = image->comps[num_comp_select].bpp;
  param_image_write.prec = image->comps[num_comp_select].prec;
  param_image_write.sgnd = image->comps[num_comp_select].sgnd;

  image_write = opj_image_create(1u, &param_image_write, OPJ_CLRSPC_GRAY);
  memcpy(image_write->comps->data, image->comps[num_comp_select].data, param_image_write.h * param_image_write.w * sizeof(int));


  imagetopng(image_write, filename);

  opj_image_destroy(image_write);

  return EXIT_SUCCESS;
}
#endif

typedef struct test_cmp_parameters
{
  /**  */
  char* base_filename;
  /**  */
  char* test_filename;
  /** Number of components */
  int nbcomp;
  /**  */
  double* tabMSEvalues;
  /**  */
  double* tabPEAKvalues;
  /**  */
  int nr_flag;
  /**  */
  char separator_base[2];
  /**  */
  char separator_test[2];



} test_cmp_parameters;

/* return decode format PGX / TIF / PPM , return -1 on error */
static int get_decod_format(test_cmp_parameters* param)
{
  int base_format = get_decod_format_from_string( param->base_filename );
  int test_format = get_decod_format_from_string( param->test_filename );
  if( base_format != test_format ) return -1;


  /* handle case -1: */
  return base_format;
}

/*******************************************************************************
 * Parse command line
 *******************************************************************************/
static int parse_cmdline_cmp(int argc, char **argv, test_cmp_parameters* param)
{
  char *MSElistvalues = NULL;  char *PEAKlistvalues= NULL;

  char *separatorList = NULL;
  size_t sizemembasefile, sizememtestfile;
  int index, flagM=0, flagP=0;
  const char optlist[] = "b:t:n:m:p:s:d";

  int c;

  /* Init parameters*/
  param->base_filename = NULL;
  param->test_filename = NULL;
  param->nbcomp = 0;
  param->tabMSEvalues = NULL;
  param->tabPEAKvalues = NULL;
  param->nr_flag = 0;
  param->separator_base[0] = 0;
  param->separator_test[0] = 0;


  opj_opterr = 0;

  while ((c = opj_getopt(argc, argv, optlist)) != -1)
    switch (c)
      {
      case 'b':
        sizemembasefile = strlen(opj_optarg) + 1;
        param->base_filename = (char*) malloc(sizemembasefile);
        strcpy(param->base_filename, opj_optarg);
        /*printf("param->base_filename = %s [%d / %d]\n", param->base_filename, strlen(param->base_filename), sizemembasefile );*/
        break;
      case 't':
        sizememtestfile = strlen(opj_optarg) + 1;
        param->test_filename = (char*) malloc(sizememtestfile);
        strcpy(param->test_filename, opj_optarg);
        /*printf("param->test_filename = %s [%d / %d]\n", param->test_filename, strlen(param->test_filename), sizememtestfile);*/
       break;
      case 'n':
        param->nbcomp = atoi(opj_optarg);
        break;
      case 'm':
        MSElistvalues = opj_optarg;
        flagM = 1;
        break;
      case 'p':
        PEAKlistvalues = opj_optarg;
        flagP = 1;
        break;
      case 'd':
        param->nr_flag = 1;
        break;
      case 's':
        separatorList = opj_optarg;
        break;



      case '?':
        if ((opj_optopt == 'b') || (opj_optopt == 't') || (opj_optopt == 'n') || (opj_optopt == 'p') || (opj_optopt == 'm') || (opj_optopt

            == 's'))
          fprintf(stderr, "Option -%c requires an argument.\n", opj_optopt);
        else
          if (isprint(opj_optopt)) fprintf(stderr, "Unknown option `-%c'.\n", opj_optopt);

          else fprintf(stderr, "Unknown option character `\\x%x'.\n", opj_optopt);

        return 1;
      default:
        fprintf(stderr, "WARNING -> this option is not valid \"-%c %s\"\n", c, opj_optarg);

        break;
      }

  if (opj_optind != argc)
    {

    for (index = opj_optind; index < argc; index++)
      fprintf(stderr,"Non-option argument %s\n", argv[index]);

    return 1;
    }

  if (param->nbcomp == 0)
    {
    fprintf(stderr,"Need to indicate the number of components !\n");
    return 1;
    }
  /* else */
  if ( flagM && flagP )
    {
    param->tabMSEvalues = parseToleranceValues( MSElistvalues, param->nbcomp);
    param->tabPEAKvalues = parseToleranceValues( PEAKlistvalues, param->nbcomp);
    if ( (param->tabMSEvalues == NULL) || (param->tabPEAKvalues == NULL))
      {

      fprintf(stderr,"MSE and PEAK values are not correct (respectively need %d values)\n",param->nbcomp);

      return 1;
      }
    }

  /* Get separators after corresponding letter (b or t)*/
  if (separatorList != NULL)
    {
    if( (strlen(separatorList) ==2) || (strlen(separatorList) ==4) )
      {
      /* keep original string*/
      size_t sizeseplist = strlen(separatorList)+1;
      char* separatorList2 = (char*)malloc( sizeseplist );
      strcpy(separatorList2, separatorList);
      /*printf("separatorList2 = %s [%d / %d]\n", separatorList2, strlen(separatorList2), sizeseplist);*/

      if (strlen(separatorList) == 2) /* one separator behind b or t*/
        {
        char *resultT = NULL;
        resultT = strtok(separatorList2, "t");
        if (strlen(resultT) == strlen(separatorList)) /* didn't find t character, try to find b*/
          {

          char *resultB = NULL;
          resultB = strtok(resultT, "b");
          if (strlen(resultB) == 1)
            {
            param->separator_base[0] = separatorList[1];
            param->separator_base[1] = 0;
            param->separator_test[0] = 0;
            }
          else /* not found b*/
            {
            free(separatorList2);
            return 1;
            }
          }
        else /* found t*/
          {
          param->separator_base[0] = 0;
          param->separator_test[0] = separatorList[1];
          param->separator_test[1] = 0;
          }
        /*printf("sep b = %s [%d] and sep t = %s [%d]\n",param->separator_base, strlen(param->separator_base), param->separator_test, strlen(param->separator_test) );*/
        }
      else /* == 4 characters we must found t and b*/
        {
        char *resultT = NULL;
        resultT = strtok(separatorList2, "t");
        if (strlen(resultT) == 3) /* found t in first place*/
          {
          char *resultB = NULL;
          resultB = strtok(resultT, "b");
          if (strlen(resultB) == 1) /* found b after t*/
            {
            param->separator_test[0] = separatorList[1];
            param->separator_test[1] = 0;
            param->separator_base[0] = separatorList[3];
            param->separator_base[1] = 0;
            }
          else /* didn't find b after t*/
            {
            free(separatorList2);
            return 1;
            }
          }
        else /* == 2, didn't find t in first place*/
          {
          char *resultB = NULL;
          resultB = strtok(resultT, "b");
          if (strlen(resultB) == 1) /* found b in first place*/
            {
            param->separator_base[0] = separatorList[1];
            param->separator_base[1] = 0;
            param->separator_test[0] = separatorList[3];
            param->separator_test[1] = 0;
            }
          else /* didn't found b in first place => problem*/
            {
            free(separatorList2);
            return 1;
            }
          }
        }
      free(separatorList2);
      }
    else /* wrong number of argument after -s*/
      {
      return 1;
      }
    }
  else
    {
    if (param->nbcomp == 1)
      {
      assert( param->separator_base[0] == 0 );
      assert( param->separator_test[0] == 0 );
      }
    else
      {
      fprintf(stderr,"If number of component is > 1, we need separator\n");
      return 1;
      }
    }








  if ( (param->nr_flag) && (flagP || flagM) )

    {


    fprintf(stderr,"Wrong input parameters list: it is non-regression test or tolerance comparison\n");
    return 1;
    }
  if ( (!param->nr_flag) && (!flagP || !flagM) )
    {

    fprintf(stderr,"Wrong input parameters list: it is non-regression test or tolerance comparison\n");
    return 1;
    }

  return 0;
}

/*******************************************************************************
 * MAIN
 *******************************************************************************/
int main(int argc, char **argv)
{
  test_cmp_parameters inParam;
  OPJ_UINT32 it_comp, itpxl;
  int failed = 1;
  int nbFilenamePGXbase = 0, nbFilenamePGXtest = 0;
  char *filenamePNGtest= NULL, *filenamePNGbase = NULL, *filenamePNGdiff = NULL;
  size_t memsizebasefilename, memsizetestfilename;
  size_t memsizedifffilename;
  int valueDiff = 0, nbPixelDiff = 0;
  double sumDiff = 0.0;
  /* Structures to store image parameters and data*/
  opj_image_t *imageBase = NULL, *imageTest = NULL, *imageDiff = NULL;
  opj_image_cmptparm_t* param_image_diff = NULL;
  int decod_format;

  /* Get parameters from command line*/
  if( parse_cmdline_cmp(argc, argv, &inParam) )
    {
    compare_images_help_display();
    goto cleanup;
    }

  /* Display Parameters*/
  printf("******Parameters********* \n");
  printf(" base_filename = %s\n"
         " test_filename = %s\n"
         " nb of Components = %d\n"
         " Non regression test = %d\n"
         " separator Base = %s\n"
         " separator Test = %s\n",
         inParam.base_filename, inParam.test_filename, inParam.nbcomp,
         inParam.nr_flag, inParam.separator_base, inParam.separator_test);

  if ( (inParam.tabMSEvalues != NULL) && (inParam.tabPEAKvalues != NULL))
    {
    int it_comp2;
    printf(" MSE values = [");
    for (it_comp2 = 0; it_comp2 < inParam.nbcomp; it_comp2++)
      printf(" %f ", inParam.tabMSEvalues[it_comp2]);

    printf("]\n");
    printf(" PEAK values = [");
    for (it_comp2 = 0; it_comp2 < inParam.nbcomp; it_comp2++)
      printf(" %f ", inParam.tabPEAKvalues[it_comp2]);

    printf("]\n");
    printf(" Non-regression test = %d\n", inParam.nr_flag);
    }

  if (strlen(inParam.separator_base) != 0)
    nbFilenamePGXbase = inParam.nbcomp;


  if (strlen(inParam.separator_test) != 0)
    nbFilenamePGXtest = inParam.nbcomp;


  printf(" NbFilename to generate from base filename = %d\n", nbFilenamePGXbase);
  printf(" NbFilename to generate from test filename = %d\n", nbFilenamePGXtest);
  printf("************************* \n");

  /*----------BASELINE IMAGE--------*/
  memsizebasefilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;
  memsizetestfilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;

  decod_format = get_decod_format(&inParam);
  if( decod_format == -1 )
    {
    fprintf( stderr, "Unhandled file format\n" );
    goto cleanup;
    }
  assert( decod_format == PGX_DFMT || decod_format == TIF_DFMT || decod_format == PXM_DFMT );


  if( decod_format == PGX_DFMT )
    {
    imageBase = readImageFromFilePGX( inParam.base_filename, nbFilenamePGXbase, inParam.separator_base);

    if ( imageBase == NULL )
      goto cleanup;
    }
  else if( decod_format == TIF_DFMT )
    {
    imageBase = readImageFromFileTIF( inParam.base_filename, nbFilenamePGXbase, "");
    if ( imageBase == NULL )
      goto cleanup;
    }
  else if( decod_format == PXM_DFMT )
    {
    imageBase = readImageFromFilePPM( inParam.base_filename, nbFilenamePGXbase, inParam.separator_base);

    if ( imageBase == NULL )
      goto cleanup;

    }

  filenamePNGbase = (char*) malloc(memsizebasefilename);
  strcpy(filenamePNGbase, inParam.test_filename);
  strcat(filenamePNGbase, ".base");
  /*printf("filenamePNGbase = %s [%d / %d octets]\n",filenamePNGbase, strlen(filenamePNGbase),memsizebasefilename );*/

  /*----------TEST IMAGE--------*/

  if( decod_format == PGX_DFMT )
    {
    imageTest = readImageFromFilePGX(inParam.test_filename, nbFilenamePGXtest, inParam.separator_test);

    if ( imageTest == NULL )
      goto cleanup;
    }
  else if( decod_format == TIF_DFMT )
    {
    imageTest = readImageFromFileTIF(inParam.test_filename, nbFilenamePGXtest, "");
    if ( imageTest == NULL )
      goto cleanup;
    }
  else if( decod_format == PXM_DFMT )
    {
    imageTest = readImageFromFilePPM(inParam.test_filename, nbFilenamePGXtest, inParam.separator_test);

    if ( imageTest == NULL )
      goto cleanup;

    }

  filenamePNGtest = (char*) malloc(memsizetestfilename);
  strcpy(filenamePNGtest, inParam.test_filename);
  strcat(filenamePNGtest, ".test");
  /*printf("filenamePNGtest = %s [%d / %d octets]\n",filenamePNGtest, strlen(filenamePNGtest),memsizetestfilename );*/

  /*----------DIFF IMAGE--------*/

  /* Allocate memory*/
  param_image_diff = malloc( imageBase->numcomps * sizeof(opj_image_cmptparm_t));

  /* Comparison of header parameters*/
  printf("Step 1 -> Header comparison\n");

  /* check dimensions (issue 286)*/
  if(imageBase->numcomps != imageTest->numcomps )
    {
    printf("ERROR: dim mismatch (%d><%d)\n", imageBase->numcomps, imageTest->numcomps);

    goto cleanup;
    }

  for (it_comp = 0; it_comp < imageBase->numcomps; it_comp++)
    {
    param_image_diff[it_comp].x0 = 0;
    param_image_diff[it_comp].y0 = 0;
    param_image_diff[it_comp].dx = 0;
    param_image_diff[it_comp].dy = 0;
    param_image_diff[it_comp].sgnd = 0;
    param_image_diff[it_comp].prec = 8;
    param_image_diff[it_comp].bpp = 1;
    param_image_diff[it_comp].h = imageBase->comps[it_comp].h;
    param_image_diff[it_comp].w = imageBase->comps[it_comp].w;

    if (imageBase->comps[it_comp].sgnd != imageTest->comps[it_comp].sgnd)
      {
      printf("ERROR: sign mismatch [comp %d] (%d><%d)\n", it_comp, ((imageBase->comps)[it_comp]).sgnd, ((imageTest->comps)[it_comp]).sgnd);

      goto cleanup;
      }

    if (((imageBase->comps)[it_comp]).prec != ((imageTest->comps)[it_comp]).prec)
      {

      printf("ERROR: prec mismatch [comp %d] (%d><%d)\n", it_comp, ((imageBase->comps)[it_comp]).prec, ((imageTest->comps)[it_comp]).prec);

      goto cleanup;
      }

    if (((imageBase->comps)[it_comp]).bpp != ((imageTest->comps)[it_comp]).bpp)
      {


      printf("ERROR: byte per pixel mismatch [comp %d] (%d><%d)\n", it_comp, ((imageBase->comps)[it_comp]).bpp, ((imageTest->comps)[it_comp]).bpp);
      goto cleanup;
      }

    if (((imageBase->comps)[it_comp]).h != ((imageTest->comps)[it_comp]).h)
      {
      printf("ERROR: height mismatch [comp %d] (%d><%d)\n", it_comp, ((imageBase->comps)[it_comp]).h, ((imageTest->comps)[it_comp]).h);

      goto cleanup;
      }

    if (((imageBase->comps)[it_comp]).w != ((imageTest->comps)[it_comp]).w)
      {
      printf("ERROR: width mismatch [comp %d] (%d><%d)\n", it_comp, ((imageBase->comps)[it_comp]).w, ((imageTest->comps)[it_comp]).w);

      goto cleanup;
      }
    }

   imageDiff = opj_image_create(imageBase->numcomps, param_image_diff, OPJ_CLRSPC_UNSPECIFIED);

   /* Free memory*/
   free(param_image_diff); param_image_diff = NULL;


   /* Measurement computation*/
   printf("Step 2 -> measurement comparison\n");

   memsizedifffilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;
   filenamePNGdiff = (char*) malloc(memsizedifffilename);
   strcpy(filenamePNGdiff, inParam.test_filename);
   strcat(filenamePNGdiff, ".diff");
   /*printf("filenamePNGdiff = %s [%d / %d octets]\n",filenamePNGdiff, strlen(filenamePNGdiff),memsizedifffilename );*/

   /* Compute pixel diff*/

   for (it_comp = 0; it_comp < imageDiff->numcomps; it_comp++)
     {
     double SE=0,PEAK=0;
     double MSE=0;










     for (itpxl = 0; itpxl < ((imageDiff->comps)[it_comp]).w * ((imageDiff->comps)[it_comp]).h; itpxl++)
       {

       if (abs( ((imageBase->comps)[it_comp]).data[itpxl] - ((imageTest->comps)[it_comp]).data[itpxl] ) > 0)
         {
         valueDiff = ((imageBase->comps)[it_comp]).data[itpxl] - ((imageTest->comps)[it_comp]).data[itpxl];

         ((imageDiff->comps)[it_comp]).data[itpxl] = abs(valueDiff);
         sumDiff += valueDiff;
         nbPixelDiff++;

         SE += (double)valueDiff * valueDiff;
         PEAK = (PEAK > abs(valueDiff)) ? PEAK : abs(valueDiff);
         }
       else
         ((imageDiff->comps)[it_comp]).data[itpxl] = 0;

       }/* h*w loop */

     MSE = SE / ( ((imageDiff->comps)[it_comp]).w * ((imageDiff->comps)[it_comp]).h );

     if (!inParam.nr_flag && (inParam.tabMSEvalues != NULL) && (inParam.tabPEAKvalues != NULL))

       { /* Conformance test*/
       printf("<DartMeasurement name=\"PEAK_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n", it_comp, PEAK);

       printf("<DartMeasurement name=\"MSE_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n", it_comp, MSE);



       if ( (MSE > inParam.tabMSEvalues[it_comp]) || (PEAK > inParam.tabPEAKvalues[it_comp]) )
         {
         printf("ERROR: MSE (%f) or PEAK (%f) values produced by the decoded file are greater "
           "than the allowable error (respectively %f and %f) \n",
           MSE, PEAK, inParam.tabMSEvalues[it_comp], inParam.tabPEAKvalues[it_comp]);
         goto cleanup;
         }
       }
     else  /* Non regression-test */
       {
       if ( nbPixelDiff > 0)
         {
         char it_compc[255];
         it_compc[0] = 0;

         printf("<DartMeasurement name=\"NumberOfPixelsWithDifferences_%d\" type=\"numeric/int\"> %d </DartMeasurement> \n", it_comp, nbPixelDiff);

         printf("<DartMeasurement name=\"ComponentError_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n", it_comp, sumDiff);

         printf("<DartMeasurement name=\"PEAK_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n", it_comp, PEAK);

         printf("<DartMeasurement name=\"MSE_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n", it_comp, MSE);


#ifdef OPJ_HAVE_LIBPNG
           {
           char *filenamePNGbase_it_comp, *filenamePNGtest_it_comp, *filenamePNGdiff_it_comp;


           filenamePNGbase_it_comp = (char*) malloc(memsizebasefilename);
           strcpy(filenamePNGbase_it_comp,filenamePNGbase);

           filenamePNGtest_it_comp = (char*) malloc(memsizetestfilename);
           strcpy(filenamePNGtest_it_comp,filenamePNGtest);

           filenamePNGdiff_it_comp = (char*) malloc(memsizedifffilename);
           strcpy(filenamePNGdiff_it_comp,filenamePNGdiff);

           sprintf(it_compc, "_%i", it_comp);
           strcat(it_compc,".png");
           strcat(filenamePNGbase_it_comp, it_compc);
           /*printf("filenamePNGbase_it = %s [%d / %d octets]\n",filenamePNGbase_it_comp, strlen(filenamePNGbase_it_comp),memsizebasefilename );*/
           strcat(filenamePNGtest_it_comp, it_compc);
           /*printf("filenamePNGtest_it = %s [%d / %d octets]\n",filenamePNGtest_it_comp, strlen(filenamePNGtest_it_comp),memsizetestfilename );*/
           strcat(filenamePNGdiff_it_comp, it_compc);
           /*printf("filenamePNGdiff_it = %s [%d / %d octets]\n",filenamePNGdiff_it_comp, strlen(filenamePNGdiff_it_comp),memsizedifffilename );*/

           /*
           if ( imageToPNG(imageBase, filenamePNGbase_it_comp, it_comp) == EXIT_SUCCESS )
           {
           printf("<DartMeasurementFile name=\"BaselineImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGbase_it_comp);
           }

           if ( imageToPNG(imageTest, filenamePNGtest_it_comp, it_comp) == EXIT_SUCCESS )
           {
           printf("<DartMeasurementFile name=\"TestImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGtest_it_comp);
           }

           if ( imageToPNG(imageDiff, filenamePNGdiff_it_comp, it_comp) == EXIT_SUCCESS )
           {
           printf("<DartMeasurementFile name=\"DiffferenceImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGdiff_it_comp);
           }
            */

           free(filenamePNGbase_it_comp);
           free(filenamePNGtest_it_comp);
           free(filenamePNGdiff_it_comp);
           }
#endif

         goto cleanup;
         }
       }
     } /* it_comp loop */


   printf("---- TEST SUCCEED ----\n");
   failed = 0;

cleanup:
  /*-----------------------------*/
  free(param_image_diff);
  /* Free memory */
  opj_image_destroy(imageBase);
  opj_image_destroy(imageTest);
  opj_image_destroy(imageDiff);

  free(filenamePNGbase);
  free(filenamePNGtest);
  free(filenamePNGdiff);

  free(inParam.tabMSEvalues);
  free(inParam.tabPEAKvalues);
  free(inParam.base_filename);
  free(inParam.test_filename);

  return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}







|

|
|
|
|

|
<
|
|
|


|
<
|
|

|
|







|
|
>
|
|
>
|
>
|
>
|
>
|
|
|
>
|
>
>
|




|
|
>
|
>
>
|
>
>
|
>
|







|
>

|
|
|
|
|

|
|
<
|
|
<
|
<
|
|
|
|


|

|
|
|
|
|

|
|
<
|
<
|
<
|


|
|





|
>

|
|
|
|
|
|

|
|
|
>

|
|
|
|

|
|
|

|
<
|
|
|
<
|
>
|
<
|
|
>
|
>
|
|
|
<
|
|

|

|
|
|
|

|

|
|

|
|
|
|
|
|
|
|
|
|

|
|
>
|
>

|
|
|


|
>
|
<
|
|
>
|


|
|
|

|


|
>

|
|
|
|

|
|
|
|
|

|
|


|
>
|
>
|
|
|
|

|

|

|
<
|
|


|


|
>

|
|
|
|
|
|

|
|
|
>

|
|
|
|

|
|
|

|
<
|
|
|
<
|
>
|
<
|
|
>
|
>
|
|
|
<
|
|

|

|
|
|
|

|

|
|

|
|
|
|
|
|
|
|
|
|

|
|
>
|
>

|
|
|


|
>
|
<
|
|
>
|


|
|
|

|






|
>

|
|

|
|
|
|
|
|
|
|
|

|
|
>

|

|

|



|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>






|
|
|
>
>
|
|







|
>
|
|
|
|
>
|

|
|
|
|
|
|
|
|
|
>

|

|
|
<
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
>
>
>
|
|
>
|
|
|
|
>
|
>
|
|
|
>
|
|
<
<
|
>
|
|
>
|


|
<
|
|

|
|
<
|
|
|
<
>
|
>
|
|


|
|
<
|
<
|
|
|
|
|

|
<
|
|
|
<
>
|
|
|
<
|
|
|
<
|
<
|
|
|
<
|
<
|
|
|
|
|
<
|
<
|
|
|
<
|
|
|
<
|
|
|
|
<
|
<
|
|
|
<
|
<
|
|
|
<
|
|
|
|
<
|
<
|
|
|
|
|
|
<
|
<
|
|
<
|
<
|
<
|
|
<
|
<
|
|
|


>
>
>
>
>
>
|
<
>
|
>
>
|
|

|
<
>
|
|


|







|
|
|
|
|
|
|
|
|
|
|
|
|

|
|
<
|
|


|
|
|
|
|
|
|
|
|
|

|
<
|
|
|
|
>
|
|
|
|
>
|
|


|
|
|
>
|
|
>

|
|
|

|
|
|

|
|
<
|
|

|
>

|
<
|
>
|
|
|
|
<
|
|
|
|
|
<
|
>
|
|
>


|
|
|
|

|

|
<
|
>
|
|
|
|
<
|
|
|
|
|
<
|
>
|
|
>


|
|
|
|

|

|
|

|
|

|
|
<
|
>
|


|
<
|
|
|
|
|
|
|
|
|

|
<
|
>
|
|

|
<
>
|
>
|
|

|
<
>
>
|
|
|

|
<
|
>
|
|

|
<
|
>
|
|


|
>
|
|
>

|
|

|
|
|
|
|

|
>
|
<
|
|
>
>
>
>
>
>
>
>
>
>
|
<
>
|
<
|
>
|
|
|

|
|
<
|
|
>
|

|

|
>
|
|
>
|
>

>
|
<
|
|
|
|
|
<
|
<
|
<
|
|

|
>
|
>
|
>
|
>


|
|
>

|
|

|
|

|
|

|
|
|
|
|
|
|
|

|
|
|
|
|

|
|
|
|

|
|
|
|
|

|
|
|
|

>
|
|
|
|

>
|
<
>

|
|
|
|
|
|

|
|
|

|
|
|
|

|

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
572
573

574
575
576

577

578
579
580

581

582
583
584
585
586

587

588
589
590

591
592
593

594
595
596
597

598

599
600
601

602

603
604
605

606
607
608
609

610

611
612
613
614
615
616

617

618
619

620

621

622
623

624

625
626
627
628
629
630
631
632
633
634
635
636

637
638
639
640
641
642
643
644

645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673

674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689

690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721

722
723
724
725
726
727
728

729
730
731
732
733
734

735
736
737
738
739

740
741
742
743
744
745
746
747
748
749
750
751
752
753
754

755
756
757
758
759
760

761
762
763
764
765

766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787

788
789
790
791
792
793

794
795
796
797
798
799
800
801
802
803
804

805
806
807
808
809
810

811
812
813
814
815
816
817

818
819
820
821
822
823
824

825
826
827
828
829
830

831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854

855
856
857
858
859
860
861
862
863
864
865
866
867

868
869

870
871
872
873
874
875
876
877

878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894

895
896
897
898
899

900

901

902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966

967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
#include <tiffio.h> /* TIFFSetWarningHandler */
#endif /* OPJ_HAVE_LIBTIFF */

/*******************************************************************************
 * Parse MSE and PEAK input values (
 * separator = ":"
 *******************************************************************************/
static double* parseToleranceValues(char* inArg, const int nbcomp)
{
    double* outArgs = malloc((size_t)nbcomp * sizeof(double));
    int it_comp = 0;
    const char delims[] = ":";
    char *result = strtok(inArg, delims);

    while ((result != NULL) && (it_comp < nbcomp)) {

        outArgs[it_comp] = atof(result);
        result = strtok(NULL, delims);
        it_comp++;
    }

    if (it_comp != nbcomp) {

        free(outArgs);
        return NULL;
    }
    /* else */
    return outArgs;
}

/*******************************************************************************
 * Command line help function
 *******************************************************************************/
static void compare_images_help_display(void)
{
    fprintf(stdout, "\nList of parameters for the compare_images function  \n");
    fprintf(stdout, "\n");
    fprintf(stdout,
            "  -b \t REQUIRED \t filename to the reference/baseline PGX/TIF/PNM image \n");
    fprintf(stdout, "  -t \t REQUIRED \t filename to the test PGX/TIF/PNM image\n");
    fprintf(stdout,
            "  -n \t REQUIRED \t number of component of the image (used to generate correct filename, not used when both input files are TIF)\n");
    fprintf(stdout,
            "  -m \t OPTIONAL \t list of MSE tolerances, separated by : (size must correspond to the number of component) of \n");
    fprintf(stdout,
            "  -p \t OPTIONAL \t list of PEAK tolerances, separated by : (size must correspond to the number of component) \n");
    fprintf(stdout,
            "  -s \t OPTIONAL \t 1 or 2 filename separator to take into account PGX/PNM image with different components, "
            "please indicate b or t before separator to indicate respectively the separator "
            "for ref/base file and for test file.  \n");
    fprintf(stdout,
            "  -d \t OPTIONAL \t indicate if you want to run this function as conformance test or as non regression test\n");
    fprintf(stdout,
            "  -i \t OPTIONAL \t list of features to ignore. Currently 'prec' only supported\n");
    fprintf(stdout, "\n");
}

static int get_decod_format_from_string(const char *filename)
{
    const int dot = '.';
    char * ext = strrchr(filename, dot);
    if (strcmp(ext, ".pgx") == 0) {
        return PGX_DFMT;
    }
    if (strcmp(ext, ".tif") == 0) {
        return TIF_DFMT;
    }
    if (strcmp(ext, ".ppm") == 0) {
        return PXM_DFMT;
    }
    return -1;
}


/*******************************************************************************
 * Create filenames from a filename using separator and nb components
 * (begin from 0)
 *******************************************************************************/
static char* createMultiComponentsFilename(const char* inFilename,
        const int indexF, const char* separator)
{
    char s[255];
    char *outFilename, *ptr;
    const char token = '.';
    size_t posToken = 0;
    int decod_format;

    /*printf("inFilename = %s\n", inFilename);*/
    if ((ptr = strrchr(inFilename, token)) != NULL) {

        posToken = strlen(inFilename) - strlen(ptr);
        /*printf("Position of %c character inside inFilename = %d\n", token, posToken);*/

    } else {

        /*printf("Token %c not found\n", token);*/
        outFilename = (char*)malloc(1);
        outFilename[0] = '\0';
        return outFilename;
    }

    outFilename = (char*)malloc((posToken + 7) * sizeof(char)); /*6*/

    strncpy(outFilename, inFilename, posToken);
    outFilename[posToken] = '\0';
    strcat(outFilename, separator);
    sprintf(s, "%i", indexF);
    strcat(outFilename, s);

    decod_format = get_decod_format_from_string(inFilename);
    if (decod_format == PGX_DFMT) {

        strcat(outFilename, ".pgx");

    } else if (decod_format == PXM_DFMT) {

        strcat(outFilename, ".pgm");
    }

    /*printf("outfilename: %s\n", outFilename);*/
    return outFilename;
}

/*******************************************************************************
 *
 *******************************************************************************/
static opj_image_t* readImageFromFilePPM(const char* filename,
        int nbFilenamePGX, const char *separator)
{
    int it_file;
    opj_image_t* image_read = NULL;
    opj_image_t* image = NULL;
    opj_cparameters_t parameters;
    opj_image_cmptparm_t* param_image_read;
    int** data;

    /* If separator is empty => nb file to read is equal to one*/
    if (strlen(separator) == 0) {
        nbFilenamePGX = 1;
    }

    /* set encoding parameters to default values */
    opj_set_default_encoder_parameters(&parameters);
    parameters.decod_format = PXM_DFMT;
    strcpy(parameters.infile, filename);

    /* Allocate memory*/
    param_image_read = malloc((size_t)nbFilenamePGX * sizeof(opj_image_cmptparm_t));
    data = malloc((size_t)nbFilenamePGX * sizeof(*data));

    for (it_file = 0; it_file < nbFilenamePGX; it_file++) {

        /* Create the right filename*/
        char *filenameComponentPGX;
        if (strlen(separator) == 0) {

            filenameComponentPGX = malloc((strlen(filename) + 1) * sizeof(
                                              *filenameComponentPGX));
            strcpy(filenameComponentPGX, filename);

        } else {
            filenameComponentPGX = createMultiComponentsFilename(filename, it_file,
                                   separator);
        }

        /* Read the tif file corresponding to the component */
        image_read = pnmtoimage(filenameComponentPGX, &parameters);
        if (!image_read) {

            int it_free_data;
            fprintf(stderr, "Unable to load ppm file: %s\n", filenameComponentPGX);

            free(param_image_read);

            for (it_free_data = 0; it_free_data < it_file; it_free_data++) {
                free(data[it_free_data]);
            }
            free(data);

            free(filenameComponentPGX);

            return NULL;
        }

        /* Set the image_read parameters*/
        param_image_read[it_file].x0 = 0;
        param_image_read[it_file].y0 = 0;
        param_image_read[it_file].dx = 0;
        param_image_read[it_file].dy = 0;
        param_image_read[it_file].h = image_read->comps->h;
        param_image_read[it_file].w = image_read->comps->w;
        param_image_read[it_file].bpp = image_read->comps->bpp;
        param_image_read[it_file].prec = image_read->comps->prec;
        param_image_read[it_file].sgnd = image_read->comps->sgnd;

        /* Copy data*/
        data[it_file] = malloc(param_image_read[it_file].h * param_image_read[it_file].w
                               * sizeof(int));
        memcpy(data[it_file], image_read->comps->data,
               image_read->comps->h * image_read->comps->w * sizeof(int));

        /* Free memory*/
        opj_image_destroy(image_read);
        free(filenameComponentPGX);
    }

    image = opj_image_create((OPJ_UINT32)nbFilenamePGX, param_image_read,
                             OPJ_CLRSPC_UNSPECIFIED);
    for (it_file = 0; it_file < nbFilenamePGX; it_file++) {

        /* Copy data into output image and free memory*/
        memcpy(image->comps[it_file].data, data[it_file],
               image->comps[it_file].h * image->comps[it_file].w * sizeof(int));
        free(data[it_file]);
    }

    /* Free memory*/
    free(param_image_read);
    free(data);

    return image;
}

static opj_image_t* readImageFromFileTIF(const char* filename,
        int nbFilenamePGX, const char *separator)
{
    opj_image_t* image_read = NULL;
    opj_cparameters_t parameters;
    (void)nbFilenamePGX;
    (void)separator;

    /* conformance test suite produce annoying warning/error:
     * TIFFReadDirectory: Warning, /.../data/baseline/conformance/jp2_1.tif: unknown field with tag 37724 (0x935c) encountered.
     * TIFFOpen: /.../data/baseline/nonregression/opj_jp2_1.tif: Cannot open.
     * On Win32 this open a message box by default, so remove it from the test suite:
     */
#ifdef OPJ_HAVE_LIBTIFF
    TIFFSetWarningHandler(NULL);
    TIFFSetErrorHandler(NULL);
#endif

    if (strlen(separator) != 0) {
        return NULL;
    }

    /* set encoding parameters to default values */
    opj_set_default_encoder_parameters(&parameters);
    parameters.decod_format = TIF_DFMT;
    strcpy(parameters.infile, filename);

    /* Read the tif file corresponding to the component */
#ifdef OPJ_HAVE_LIBTIFF
    image_read = tiftoimage(filename, &parameters);
#endif
    if (!image_read) {

        fprintf(stderr, "Unable to load TIF file\n");
        return NULL;
    }

    return image_read;
}

static opj_image_t* readImageFromFilePGX(const char* filename,
        int nbFilenamePGX, const char *separator)
{
    int it_file;
    opj_image_t* image_read = NULL;
    opj_image_t* image = NULL;
    opj_cparameters_t parameters;
    opj_image_cmptparm_t* param_image_read;
    int** data;

    /* If separator is empty => nb file to read is equal to one*/
    if (strlen(separator) == 0) {
        nbFilenamePGX = 1;
    }

    /* set encoding parameters to default values */
    opj_set_default_encoder_parameters(&parameters);
    parameters.decod_format = PGX_DFMT;
    strcpy(parameters.infile, filename);

    /* Allocate memory*/
    param_image_read = malloc((size_t)nbFilenamePGX * sizeof(opj_image_cmptparm_t));
    data = malloc((size_t)nbFilenamePGX * sizeof(*data));

    for (it_file = 0; it_file < nbFilenamePGX; it_file++) {

        /* Create the right filename*/
        char *filenameComponentPGX;
        if (strlen(separator) == 0) {

            filenameComponentPGX = malloc((strlen(filename) + 1) * sizeof(
                                              *filenameComponentPGX));
            strcpy(filenameComponentPGX, filename);

        } else {
            filenameComponentPGX = createMultiComponentsFilename(filename, it_file,
                                   separator);
        }

        /* Read the pgx file corresponding to the component */
        image_read = pgxtoimage(filenameComponentPGX, &parameters);
        if (!image_read) {

            int it_free_data;
            fprintf(stderr, "Unable to load pgx file\n");

            free(param_image_read);

            for (it_free_data = 0; it_free_data < it_file; it_free_data++) {
                free(data[it_free_data]);
            }
            free(data);

            free(filenameComponentPGX);

            return NULL;
        }

        /* Set the image_read parameters*/
        param_image_read[it_file].x0 = 0;
        param_image_read[it_file].y0 = 0;
        param_image_read[it_file].dx = 0;
        param_image_read[it_file].dy = 0;
        param_image_read[it_file].h = image_read->comps->h;
        param_image_read[it_file].w = image_read->comps->w;
        param_image_read[it_file].bpp = image_read->comps->bpp;
        param_image_read[it_file].prec = image_read->comps->prec;
        param_image_read[it_file].sgnd = image_read->comps->sgnd;

        /* Copy data*/
        data[it_file] = malloc(param_image_read[it_file].h * param_image_read[it_file].w
                               * sizeof(int));
        memcpy(data[it_file], image_read->comps->data,
               image_read->comps->h * image_read->comps->w * sizeof(int));

        /* Free memory*/
        opj_image_destroy(image_read);
        free(filenameComponentPGX);
    }

    image = opj_image_create((OPJ_UINT32)nbFilenamePGX, param_image_read,
                             OPJ_CLRSPC_UNSPECIFIED);
    for (it_file = 0; it_file < nbFilenamePGX; it_file++) {

        /* Copy data into output image and free memory*/
        memcpy(image->comps[it_file].data, data[it_file],
               image->comps[it_file].h * image->comps[it_file].w * sizeof(int));
        free(data[it_file]);
    }

    /* Free memory*/
    free(param_image_read);
    free(data);

    return image;
}

#if defined(OPJ_HAVE_LIBPNG) && 0 /* remove for now */
/*******************************************************************************
 *
 *******************************************************************************/
static int imageToPNG(const opj_image_t* image, const char* filename,
                      int num_comp_select)
{
    opj_image_cmptparm_t param_image_write;
    opj_image_t* image_write = NULL;

    param_image_write.x0 = 0;
    param_image_write.y0 = 0;
    param_image_write.dx = 0;
    param_image_write.dy = 0;
    param_image_write.h = image->comps[num_comp_select].h;
    param_image_write.w = image->comps[num_comp_select].w;
    param_image_write.bpp = image->comps[num_comp_select].bpp;
    param_image_write.prec = image->comps[num_comp_select].prec;
    param_image_write.sgnd = image->comps[num_comp_select].sgnd;

    image_write = opj_image_create(1u, &param_image_write, OPJ_CLRSPC_GRAY);
    memcpy(image_write->comps->data, image->comps[num_comp_select].data,
           param_image_write.h * param_image_write.w * sizeof(int));

    imagetopng(image_write, filename);

    opj_image_destroy(image_write);

    return EXIT_SUCCESS;
}
#endif

typedef struct test_cmp_parameters {

    /**  */
    char* base_filename;
    /**  */
    char* test_filename;
    /** Number of components */
    int nbcomp;
    /**  */
    double* tabMSEvalues;
    /**  */
    double* tabPEAKvalues;
    /**  */
    int nr_flag;
    /**  */
    char separator_base[2];
    /**  */
    char separator_test[2];
    /** whether to ignore prec differences */
    int ignore_prec;

} test_cmp_parameters;

/* return decode format PGX / TIF / PPM , return -1 on error */
static int get_decod_format(test_cmp_parameters* param)
{
    int base_format = get_decod_format_from_string(param->base_filename);
    int test_format = get_decod_format_from_string(param->test_filename);
    if (base_format != test_format) {
        return -1;
    }
    /* handle case -1: */
    return base_format;
}

/*******************************************************************************
 * Parse command line
 *******************************************************************************/
static int parse_cmdline_cmp(int argc, char **argv, test_cmp_parameters* param)
{
    char *MSElistvalues = NULL;
    char *PEAKlistvalues = NULL;
    char *separatorList = NULL;
    size_t sizemembasefile, sizememtestfile;
    int index, flagM = 0, flagP = 0;
    const char optlist[] = "b:t:n:m:p:s:di:";
    char* ignoreList = NULL;
    int c;

    /* Init parameters*/
    param->base_filename = NULL;
    param->test_filename = NULL;
    param->nbcomp = 0;
    param->tabMSEvalues = NULL;
    param->tabPEAKvalues = NULL;
    param->nr_flag = 0;
    param->separator_base[0] = 0;
    param->separator_test[0] = 0;
    param->ignore_prec = 0;

    opj_opterr = 0;

    while ((c = opj_getopt(argc, argv, optlist)) != -1)
        switch (c) {

        case 'b':
            sizemembasefile = strlen(opj_optarg) + 1;
            param->base_filename = (char*) malloc(sizemembasefile);
            strcpy(param->base_filename, opj_optarg);
            /*printf("param->base_filename = %s [%d / %d]\n", param->base_filename, strlen(param->base_filename), sizemembasefile );*/
            break;
        case 't':
            sizememtestfile = strlen(opj_optarg) + 1;
            param->test_filename = (char*) malloc(sizememtestfile);
            strcpy(param->test_filename, opj_optarg);
            /*printf("param->test_filename = %s [%d / %d]\n", param->test_filename, strlen(param->test_filename), sizememtestfile);*/
            break;
        case 'n':
            param->nbcomp = atoi(opj_optarg);
            break;
        case 'm':
            MSElistvalues = opj_optarg;
            flagM = 1;
            break;
        case 'p':
            PEAKlistvalues = opj_optarg;
            flagP = 1;
            break;
        case 'd':
            param->nr_flag = 1;
            break;
        case 's':
            separatorList = opj_optarg;
            break;
        case 'i':
            ignoreList = opj_optarg;
            break;
        case '?':
            if ((opj_optopt == 'b') || (opj_optopt == 't') || (opj_optopt == 'n') ||
                    (opj_optopt == 'p') || (opj_optopt == 'm') || (opj_optopt
                            == 's')) {
                fprintf(stderr, "Option -%c requires an argument.\n", opj_optopt);
            } else if (isprint(opj_optopt)) {
                fprintf(stderr, "Unknown option `-%c'.\n", opj_optopt);
            } else {
                fprintf(stderr, "Unknown option character `\\x%x'.\n", opj_optopt);
            }
            return 1;
        default:
            fprintf(stderr, "WARNING -> this option is not valid \"-%c %s\"\n", c,
                    opj_optarg);
            break;
        }



    if (opj_optind != argc) {
        for (index = opj_optind; index < argc; index++) {
            fprintf(stderr, "Non-option argument %s\n", argv[index]);
        }
        return 1;
    }

    if (param->nbcomp == 0) {

        fprintf(stderr, "Need to indicate the number of components !\n");
        return 1;
    }
    /* else */
    if (flagM && flagP) {

        param->tabMSEvalues = parseToleranceValues(MSElistvalues, param->nbcomp);
        param->tabPEAKvalues = parseToleranceValues(PEAKlistvalues, param->nbcomp);
        if ((param->tabMSEvalues == NULL) || (param->tabPEAKvalues == NULL)) {

            fprintf(stderr,
                    "MSE and PEAK values are not correct (respectively need %d values)\n",
                    param->nbcomp);
            return 1;
        }
    }

    /* Get separators after corresponding letter (b or t)*/
    if (separatorList != NULL) {

        if ((strlen(separatorList) == 2) || (strlen(separatorList) == 4)) {

            /* keep original string*/
            size_t sizeseplist = strlen(separatorList) + 1;
            char* separatorList2 = (char*)malloc(sizeseplist);
            strcpy(separatorList2, separatorList);
            /*printf("separatorList2 = %s [%d / %d]\n", separatorList2, strlen(separatorList2), sizeseplist);*/

            if (strlen(separatorList) == 2) { /* one separator behind b or t*/

                char *resultT = NULL;
                resultT = strtok(separatorList2, "t");
                if (strlen(resultT) == strlen(

                            separatorList)) { /* didn't find t character, try to find b*/
                    char *resultB = NULL;
                    resultB = strtok(resultT, "b");
                    if (strlen(resultB) == 1) {

                        param->separator_base[0] = separatorList[1];
                        param->separator_base[1] = 0;
                        param->separator_test[0] = 0;

                    } else { /* not found b*/

                        free(separatorList2);
                        return 1;
                    }

                } else { /* found t*/

                    param->separator_base[0] = 0;
                    param->separator_test[0] = separatorList[1];
                    param->separator_test[1] = 0;
                }
                /*printf("sep b = %s [%d] and sep t = %s [%d]\n",param->separator_base, strlen(param->separator_base), param->separator_test, strlen(param->separator_test) );*/

            } else { /* == 4 characters we must found t and b*/

                char *resultT = NULL;
                resultT = strtok(separatorList2, "t");
                if (strlen(resultT) == 3) { /* found t in first place*/

                    char *resultB = NULL;
                    resultB = strtok(resultT, "b");
                    if (strlen(resultB) == 1) { /* found b after t*/

                        param->separator_test[0] = separatorList[1];
                        param->separator_test[1] = 0;
                        param->separator_base[0] = separatorList[3];
                        param->separator_base[1] = 0;

                    } else { /* didn't find b after t*/

                        free(separatorList2);
                        return 1;
                    }

                } else { /* == 2, didn't find t in first place*/

                    char *resultB = NULL;
                    resultB = strtok(resultT, "b");
                    if (strlen(resultB) == 1) { /* found b in first place*/

                        param->separator_base[0] = separatorList[1];
                        param->separator_base[1] = 0;
                        param->separator_test[0] = separatorList[3];
                        param->separator_test[1] = 0;

                    } else { /* didn't found b in first place => problem*/

                        free(separatorList2);
                        return 1;
                    }
                }
            }
            free(separatorList2);

        } else { /* wrong number of argument after -s*/

            return 1;
        }

    } else {

        if (param->nbcomp == 1) {

            assert(param->separator_base[0] == 0);
            assert(param->separator_test[0] == 0);

        } else {

            fprintf(stderr, "If number of component is > 1, we need separator\n");
            return 1;
        }
    }

    if (ignoreList != NULL) {
        if (strcmp(ignoreList, "prec") == 0) {
            param->ignore_prec = 1;
        } else {
            fprintf(stderr, "Unsupported value for -i\n");
            return 1;
        }

    }

    if ((param->nr_flag) && (flagP || flagM)) {
        fprintf(stderr,
                "Wrong input parameters list: it is non-regression test or tolerance comparison\n");
        return 1;
    }
    if ((!param->nr_flag) && (!flagP || !flagM)) {

        fprintf(stderr,
                "Wrong input parameters list: it is non-regression test or tolerance comparison\n");
        return 1;
    }

    return 0;
}

/*******************************************************************************
 * MAIN
 *******************************************************************************/
int main(int argc, char **argv)
{
    test_cmp_parameters inParam;
    OPJ_UINT32 it_comp, itpxl;
    int failed = 1;
    int nbFilenamePGXbase = 0, nbFilenamePGXtest = 0;
    char *filenamePNGtest = NULL, *filenamePNGbase = NULL, *filenamePNGdiff = NULL;
    size_t memsizebasefilename, memsizetestfilename;
    size_t memsizedifffilename;
    int nbPixelDiff = 0;
    double sumDiff = 0.0;
    /* Structures to store image parameters and data*/
    opj_image_t *imageBase = NULL, *imageTest = NULL, *imageDiff = NULL;
    opj_image_cmptparm_t* param_image_diff = NULL;
    int decod_format;

    /* Get parameters from command line*/
    if (parse_cmdline_cmp(argc, argv, &inParam)) {

        compare_images_help_display();
        goto cleanup;
    }

    /* Display Parameters*/
    printf("******Parameters********* \n");
    printf(" base_filename = %s\n"
           " test_filename = %s\n"
           " nb of Components = %d\n"
           " Non regression test = %d\n"
           " separator Base = %s\n"
           " separator Test = %s\n",
           inParam.base_filename, inParam.test_filename, inParam.nbcomp,
           inParam.nr_flag, inParam.separator_base, inParam.separator_test);

    if ((inParam.tabMSEvalues != NULL) && (inParam.tabPEAKvalues != NULL)) {

        int it_comp2;
        printf(" MSE values = [");
        for (it_comp2 = 0; it_comp2 < inParam.nbcomp; it_comp2++) {
            printf(" %f ", inParam.tabMSEvalues[it_comp2]);
        }
        printf("]\n");
        printf(" PEAK values = [");
        for (it_comp2 = 0; it_comp2 < inParam.nbcomp; it_comp2++) {
            printf(" %f ", inParam.tabPEAKvalues[it_comp2]);
        }
        printf("]\n");
        printf(" Non-regression test = %d\n", inParam.nr_flag);
    }

    if (strlen(inParam.separator_base) != 0) {
        nbFilenamePGXbase = inParam.nbcomp;
    }

    if (strlen(inParam.separator_test) != 0) {
        nbFilenamePGXtest = inParam.nbcomp;
    }

    printf(" NbFilename to generate from base filename = %d\n", nbFilenamePGXbase);
    printf(" NbFilename to generate from test filename = %d\n", nbFilenamePGXtest);
    printf("************************* \n");

    /*----------BASELINE IMAGE--------*/
    memsizebasefilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;
    memsizetestfilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;

    decod_format = get_decod_format(&inParam);
    if (decod_format == -1) {

        fprintf(stderr, "Unhandled file format\n");
        goto cleanup;
    }
    assert(decod_format == PGX_DFMT || decod_format == TIF_DFMT ||
           decod_format == PXM_DFMT);

    if (decod_format == PGX_DFMT) {

        imageBase = readImageFromFilePGX(inParam.base_filename, nbFilenamePGXbase,
                                         inParam.separator_base);
        if (imageBase == NULL) {
            goto cleanup;
        }
    } else if (decod_format == TIF_DFMT) {

        imageBase = readImageFromFileTIF(inParam.base_filename, nbFilenamePGXbase, "");
        if (imageBase == NULL) {
            goto cleanup;
        }
    } else if (decod_format == PXM_DFMT) {

        imageBase = readImageFromFilePPM(inParam.base_filename, nbFilenamePGXbase,
                                         inParam.separator_base);
        if (imageBase == NULL) {
            goto cleanup;
        }
    }

    filenamePNGbase = (char*) malloc(memsizebasefilename);
    strcpy(filenamePNGbase, inParam.test_filename);
    strcat(filenamePNGbase, ".base");
    /*printf("filenamePNGbase = %s [%d / %d octets]\n",filenamePNGbase, strlen(filenamePNGbase),memsizebasefilename );*/

    /*----------TEST IMAGE--------*/

    if (decod_format == PGX_DFMT) {

        imageTest = readImageFromFilePGX(inParam.test_filename, nbFilenamePGXtest,
                                         inParam.separator_test);
        if (imageTest == NULL) {
            goto cleanup;
        }
    } else if (decod_format == TIF_DFMT) {

        imageTest = readImageFromFileTIF(inParam.test_filename, nbFilenamePGXtest, "");
        if (imageTest == NULL) {
            goto cleanup;
        }
    } else if (decod_format == PXM_DFMT) {

        imageTest = readImageFromFilePPM(inParam.test_filename, nbFilenamePGXtest,
                                         inParam.separator_test);
        if (imageTest == NULL) {
            goto cleanup;
        }
    }

    filenamePNGtest = (char*) malloc(memsizetestfilename);
    strcpy(filenamePNGtest, inParam.test_filename);
    strcat(filenamePNGtest, ".test");
    /*printf("filenamePNGtest = %s [%d / %d octets]\n",filenamePNGtest, strlen(filenamePNGtest),memsizetestfilename );*/

    /*----------DIFF IMAGE--------*/

    /* Allocate memory*/
    param_image_diff = malloc(imageBase->numcomps * sizeof(opj_image_cmptparm_t));

    /* Comparison of header parameters*/
    printf("Step 1 -> Header comparison\n");

    /* check dimensions (issue 286)*/
    if (imageBase->numcomps != imageTest->numcomps) {

        printf("ERROR: dim mismatch (%d><%d)\n", imageBase->numcomps,
               imageTest->numcomps);
        goto cleanup;
    }

    for (it_comp = 0; it_comp < imageBase->numcomps; it_comp++) {

        param_image_diff[it_comp].x0 = 0;
        param_image_diff[it_comp].y0 = 0;
        param_image_diff[it_comp].dx = 0;
        param_image_diff[it_comp].dy = 0;
        param_image_diff[it_comp].sgnd = 0;
        param_image_diff[it_comp].prec = 8;
        param_image_diff[it_comp].bpp = 1;
        param_image_diff[it_comp].h = imageBase->comps[it_comp].h;
        param_image_diff[it_comp].w = imageBase->comps[it_comp].w;

        if (imageBase->comps[it_comp].sgnd != imageTest->comps[it_comp].sgnd) {

            printf("ERROR: sign mismatch [comp %d] (%d><%d)\n", it_comp,
                   ((imageBase->comps)[it_comp]).sgnd, ((imageTest->comps)[it_comp]).sgnd);
            goto cleanup;
        }

        if (((imageBase->comps)[it_comp]).prec != ((imageTest->comps)[it_comp]).prec &&

                !inParam.ignore_prec) {
            printf("ERROR: prec mismatch [comp %d] (%d><%d)\n", it_comp,
                   ((imageBase->comps)[it_comp]).prec, ((imageTest->comps)[it_comp]).prec);
            goto cleanup;
        }

        if (((imageBase->comps)[it_comp]).bpp != ((imageTest->comps)[it_comp]).bpp &&

                !inParam.ignore_prec) {
            printf("ERROR: bit per pixel mismatch [comp %d] (%d><%d)\n", it_comp,
                   ((imageBase->comps)[it_comp]).bpp, ((imageTest->comps)[it_comp]).bpp);
            goto cleanup;
        }

        if (((imageBase->comps)[it_comp]).h != ((imageTest->comps)[it_comp]).h) {

            printf("ERROR: height mismatch [comp %d] (%d><%d)\n", it_comp,
                   ((imageBase->comps)[it_comp]).h, ((imageTest->comps)[it_comp]).h);
            goto cleanup;
        }

        if (((imageBase->comps)[it_comp]).w != ((imageTest->comps)[it_comp]).w) {

            printf("ERROR: width mismatch [comp %d] (%d><%d)\n", it_comp,
                   ((imageBase->comps)[it_comp]).w, ((imageTest->comps)[it_comp]).w);
            goto cleanup;
        }
    }

    imageDiff = opj_image_create(imageBase->numcomps, param_image_diff,
                                 OPJ_CLRSPC_UNSPECIFIED);
    /* Free memory*/
    free(param_image_diff);
    param_image_diff = NULL;

    /* Measurement computation*/
    printf("Step 2 -> measurement comparison\n");

    memsizedifffilename = strlen(inParam.test_filename) + 1 + 5 + 2 + 4;
    filenamePNGdiff = (char*) malloc(memsizedifffilename);
    strcpy(filenamePNGdiff, inParam.test_filename);
    strcat(filenamePNGdiff, ".diff");
    /*printf("filenamePNGdiff = %s [%d / %d octets]\n",filenamePNGdiff, strlen(filenamePNGdiff),memsizedifffilename );*/

    /* Compute pixel diff*/
    failed = 0;
    for (it_comp = 0; it_comp < imageDiff->numcomps; it_comp++) {

        double SE = 0, PEAK = 0;
        double MSE = 0;
        unsigned right_shift_input = 0;
        unsigned right_shift_output = 0;
        if (((imageBase->comps)[it_comp]).bpp > ((imageTest->comps)[it_comp]).bpp) {
            right_shift_input = ((imageBase->comps)[it_comp]).bpp - ((
                                    imageTest->comps)[it_comp]).bpp;
        } else {
            right_shift_output = ((imageTest->comps)[it_comp]).bpp - ((
                                     imageBase->comps)[it_comp]).bpp;
        }
        for (itpxl = 0;
                itpxl < ((imageDiff->comps)[it_comp]).w * ((imageDiff->comps)[it_comp]).h;

                itpxl++) {
            int valueDiff = (((imageBase->comps)[it_comp]).data[itpxl] >> right_shift_input)

                            - (((imageTest->comps)[it_comp]).data[itpxl] >> right_shift_output);
            if (valueDiff != 0) {
                ((imageDiff->comps)[it_comp]).data[itpxl] = abs(valueDiff);
                sumDiff += valueDiff;
                nbPixelDiff++;

                SE += (double)valueDiff * valueDiff;
                PEAK = (PEAK > abs(valueDiff)) ? PEAK : abs(valueDiff);

            } else {
                ((imageDiff->comps)[it_comp]).data[itpxl] = 0;
            }
        }/* h*w loop */

        MSE = SE / (((imageDiff->comps)[it_comp]).w * ((imageDiff->comps)[it_comp]).h);

        if (!inParam.nr_flag && (inParam.tabMSEvalues != NULL) &&
                (inParam.tabPEAKvalues != NULL)) {
            /* Conformance test*/
            printf("<DartMeasurement name=\"PEAK_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n",
                   it_comp, PEAK);
            printf("<DartMeasurement name=\"MSE_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n",
                   it_comp, MSE);

            if ((MSE > inParam.tabMSEvalues[it_comp]) ||
                    (PEAK > inParam.tabPEAKvalues[it_comp])) {

                printf("ERROR: MSE (%f) or PEAK (%f) values produced by the decoded file are greater "
                       "than the allowable error (respectively %f and %f) \n",
                       MSE, PEAK, inParam.tabMSEvalues[it_comp], inParam.tabPEAKvalues[it_comp]);
                failed = 1;
            }

        } else { /* Non regression-test */

            if (nbPixelDiff > 0) {

                char it_compc[255];
                it_compc[0] = 0;

                printf("<DartMeasurement name=\"NumberOfPixelsWithDifferences_%d\" type=\"numeric/int\"> %d </DartMeasurement> \n",
                       it_comp, nbPixelDiff);
                printf("<DartMeasurement name=\"ComponentError_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n",
                       it_comp, sumDiff);
                printf("<DartMeasurement name=\"PEAK_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n",
                       it_comp, PEAK);
                printf("<DartMeasurement name=\"MSE_%d\" type=\"numeric/double\"> %f </DartMeasurement> \n",
                       it_comp, MSE);

#ifdef OPJ_HAVE_LIBPNG
                {
                    char *filenamePNGbase_it_comp, *filenamePNGtest_it_comp,
                         *filenamePNGdiff_it_comp;

                    filenamePNGbase_it_comp = (char*) malloc(memsizebasefilename);
                    strcpy(filenamePNGbase_it_comp, filenamePNGbase);

                    filenamePNGtest_it_comp = (char*) malloc(memsizetestfilename);
                    strcpy(filenamePNGtest_it_comp, filenamePNGtest);

                    filenamePNGdiff_it_comp = (char*) malloc(memsizedifffilename);
                    strcpy(filenamePNGdiff_it_comp, filenamePNGdiff);

                    sprintf(it_compc, "_%i", it_comp);
                    strcat(it_compc, ".png");
                    strcat(filenamePNGbase_it_comp, it_compc);
                    /*printf("filenamePNGbase_it = %s [%d / %d octets]\n",filenamePNGbase_it_comp, strlen(filenamePNGbase_it_comp),memsizebasefilename );*/
                    strcat(filenamePNGtest_it_comp, it_compc);
                    /*printf("filenamePNGtest_it = %s [%d / %d octets]\n",filenamePNGtest_it_comp, strlen(filenamePNGtest_it_comp),memsizetestfilename );*/
                    strcat(filenamePNGdiff_it_comp, it_compc);
                    /*printf("filenamePNGdiff_it = %s [%d / %d octets]\n",filenamePNGdiff_it_comp, strlen(filenamePNGdiff_it_comp),memsizedifffilename );*/

                    /*
                    if ( imageToPNG(imageBase, filenamePNGbase_it_comp, it_comp) == EXIT_SUCCESS )
                    {
                    printf("<DartMeasurementFile name=\"BaselineImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGbase_it_comp);
                    }

                    if ( imageToPNG(imageTest, filenamePNGtest_it_comp, it_comp) == EXIT_SUCCESS )
                    {
                    printf("<DartMeasurementFile name=\"TestImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGtest_it_comp);
                    }

                    if ( imageToPNG(imageDiff, filenamePNGdiff_it_comp, it_comp) == EXIT_SUCCESS )
                    {
                    printf("<DartMeasurementFile name=\"DiffferenceImage_%d\" type=\"image/png\"> %s </DartMeasurementFile> \n", it_comp, filenamePNGdiff_it_comp);
                    }
                     */

                    free(filenamePNGbase_it_comp);
                    free(filenamePNGtest_it_comp);
                    free(filenamePNGdiff_it_comp);
                }
#endif
                failed = 1;
                goto cleanup;
            }
        }
    } /* it_comp loop */

    if (!failed) {
        printf("---- TEST SUCCEED ----\n");

    }
cleanup:
    /*-----------------------------*/
    free(param_image_diff);
    /* Free memory */
    opj_image_destroy(imageBase);
    opj_image_destroy(imageTest);
    opj_image_destroy(imageDiff);

    free(filenamePNGbase);
    free(filenamePNGtest);
    free(filenamePNGdiff);

    free(inParam.tabMSEvalues);
    free(inParam.tabPEAKvalues);
    free(inParam.base_filename);
    free(inParam.test_filename);

    return failed ? EXIT_FAILURE : EXIT_SUCCESS;
}
Changes to jni/openjpeg/tests/fuzzers/GNUmakefile.
1
2
3
4
5
6
7
8
9
10

11
12
default: dummyfuzzers

clean:
	$(RM) -f *.o *.a

fuzzingengine.o: fuzzingengine.c
	$(CC) $(CFLAGS) -c -o $@ $<

dummyfuzzers: fuzzingengine.o
	$(AR) r libFuzzingEngine.a fuzzingengine.o

	CXX="${CXX}" CXXFLAGS="-L. ${CXXFLAGS}" SRC=/tmp OUT=/tmp ./build_google_oss_fuzzers.sh
	OUT=/tmp ./build_seed_corpus.sh










>
|

1
2
3
4
5
6
7
8
9
10
11
12
13
default: dummyfuzzers

clean:
	$(RM) -f *.o *.a

fuzzingengine.o: fuzzingengine.c
	$(CC) $(CFLAGS) -c -o $@ $<

dummyfuzzers: fuzzingengine.o
	$(AR) r libFuzzingEngine.a fuzzingengine.o
	LIB_FUZZING_ENGINE="-lFuzzingEngine" CXX="${CXX}" CXXFLAGS="-L. ${CXXFLAGS}" \
	    SRC=/tmp OUT=/tmp ./build_google_oss_fuzzers.sh
	OUT=/tmp ./build_seed_corpus.sh
Changes to jni/openjpeg/tests/fuzzers/build_google_oss_fuzzers.sh.
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    fuzzerName=$1
    sourceFilename=$2
    shift
    shift
    echo "Building fuzzer $fuzzerName"
    $CXX $CXXFLAGS -std=c++11 -I$SRC_DIR/src/lib/openjp2 -I$SRC_DIR/build/src/lib/openjp2 \
        $sourceFilename $* -o $OUT/$fuzzerName \
        -lFuzzingEngine $SRC_DIR/build/bin/libopenjp2.a -lm -lpthread
}

fuzzerFiles=$(dirname $0)/*.cpp
for F in $fuzzerFiles; do
    fuzzerName=$(basename $F .cpp)
    build_fuzzer $fuzzerName $F
done







|







24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
    fuzzerName=$1
    sourceFilename=$2
    shift
    shift
    echo "Building fuzzer $fuzzerName"
    $CXX $CXXFLAGS -std=c++11 -I$SRC_DIR/src/lib/openjp2 -I$SRC_DIR/build/src/lib/openjp2 \
        $sourceFilename $* -o $OUT/$fuzzerName \
        $LIB_FUZZING_ENGINE $SRC_DIR/build/bin/libopenjp2.a -lm -lpthread
}

fuzzerFiles=$(dirname $0)/*.cpp
for F in $fuzzerFiles; do
    fuzzerName=$(basename $F .cpp)
    build_fuzzer $fuzzerName $F
done
Changes to jni/openjpeg/tests/fuzzers/opj_decompress_fuzzer.cpp.
149
150
151
152
153
154
155

156
157
158
159
160
161
162
        opj_image_destroy(psImage);
        return 0;
    }

    OPJ_UINT32 width = psImage->x1 - psImage->x0;
    OPJ_UINT32 height = psImage->y1 - psImage->y0;


    // Reject too big images since that will require allocating a lot of
    // memory
    if (width != 0 && psImage->numcomps != 0 &&
            (width > INT_MAX / psImage->numcomps ||
             height > INT_MAX / (width * psImage->numcomps * sizeof(OPJ_UINT32)))) {
        opj_stream_destroy(pStream);
        opj_destroy_codec(pCodec);







>







149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
        opj_image_destroy(psImage);
        return 0;
    }

    OPJ_UINT32 width = psImage->x1 - psImage->x0;
    OPJ_UINT32 height = psImage->y1 - psImage->y0;

#if 0
    // Reject too big images since that will require allocating a lot of
    // memory
    if (width != 0 && psImage->numcomps != 0 &&
            (width > INT_MAX / psImage->numcomps ||
             height > INT_MAX / (width * psImage->numcomps * sizeof(OPJ_UINT32)))) {
        opj_stream_destroy(pStream);
        opj_destroy_codec(pCodec);
176
177
178
179
180
181
182

183
184
185
186
187
188
189
    if (nTileW > 2048 || nTileH > 2048) {
        opj_stream_destroy(pStream);
        opj_destroy_codec(pCodec);
        opj_image_destroy(psImage);

        return 0;
    }


    OPJ_UINT32 width_to_read = width;
    if (width_to_read > 1024) {
        width_to_read = 1024;
    }
    OPJ_UINT32 height_to_read = height;
    if (height_to_read > 1024) {







>







177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
    if (nTileW > 2048 || nTileH > 2048) {
        opj_stream_destroy(pStream);
        opj_destroy_codec(pCodec);
        opj_image_destroy(psImage);

        return 0;
    }
#endif

    OPJ_UINT32 width_to_read = width;
    if (width_to_read > 1024) {
        width_to_read = 1024;
    }
    OPJ_UINT32 height_to_read = height;
    if (height_to_read > 1024) {
Changes to jni/openjpeg/tests/nonregression/CMakeLists.txt.
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    4035.pdf.SIGSEGV.d8b.3375.jp2
    3635.pdf.asan.77.2930.jp2
    issue165.jp2
    #edf_c2_1103421.jp2
    edf_c2_1178956.jp2
    edf_c2_1000290.jp2
    #edf_c2_1000691.jp2 # ok
    #edf_c2_20.jp2 #looks ok as per kdu_jp2info
    edf_c2_1377017.jp2
    edf_c2_1002767.jp2
    edf_c2_10025.jp2
    edf_c2_1000234.jp2
    edf_c2_225881.jp2
    edf_c2_1000671.jp2
    #edf_c2_1013627.jp2 # weird box, but kdu_jp2info ok







<







30
31
32
33
34
35
36

37
38
39
40
41
42
43
    4035.pdf.SIGSEGV.d8b.3375.jp2
    3635.pdf.asan.77.2930.jp2
    issue165.jp2
    #edf_c2_1103421.jp2
    edf_c2_1178956.jp2
    edf_c2_1000290.jp2
    #edf_c2_1000691.jp2 # ok

    edf_c2_1377017.jp2
    edf_c2_1002767.jp2
    edf_c2_10025.jp2
    edf_c2_1000234.jp2
    edf_c2_225881.jp2
    edf_c2_1000671.jp2
    #edf_c2_1013627.jp2 # weird box, but kdu_jp2info ok
57
58
59
60
61
62
63

64
65
66
67
68
69
70
# Define a list of file which should be gracefully rejected:
set(BLACKLIST_JPEG2000
    ${BLACKLIST_JPEG2000_TMP}
    broken1.jp2
    broken2.jp2
    broken3.jp2
    broken4.jp2

    gdal_fuzzer_assert_in_opj_j2k_read_SQcd_SQcc.patch.jp2	
    gdal_fuzzer_check_comp_dx_dy.jp2
    gdal_fuzzer_check_number_of_tiles.jp2
    gdal_fuzzer_unchecked_numresolutions.jp2
    mem-b2ace68c-1381.jp2
    1851.pdf.SIGSEGV.ce9.948.jp2
    1888.pdf.asan.35.988.jp2







>







56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# Define a list of file which should be gracefully rejected:
set(BLACKLIST_JPEG2000
    ${BLACKLIST_JPEG2000_TMP}
    broken1.jp2
    broken2.jp2
    broken3.jp2
    broken4.jp2
    edf_c2_20.jp2 #may look ok as per kdu_jp2info, but inspection it reveals that the transformation value is out of range
    gdal_fuzzer_assert_in_opj_j2k_read_SQcd_SQcc.patch.jp2	
    gdal_fuzzer_check_comp_dx_dy.jp2
    gdal_fuzzer_check_number_of_tiles.jp2
    gdal_fuzzer_unchecked_numresolutions.jp2
    mem-b2ace68c-1381.jp2
    1851.pdf.SIGSEGV.ce9.948.jp2
    1888.pdf.asan.35.988.jp2
78
79
80
81
82
83
84


85
86
87
88
89
90
91
    issue408.jp2 #kdu_jp2info ok
    issue420.jp2 #kdu_jp2info ok
    27ac957758a35d00d6765a0c86350d9c.SIGFPE.d25.537.jpc #kdu_jp2info crash
    3672da2f1f67bbecad27d7181b4e9d7c.SIGFPE.d25.805.jpc #kdu_jp2info crash
    issue475.jp2 #kdu_jp2info ok
    issue413.jp2 #kdu_jp2info ok
    issue823.jp2 #kdu_jp2info ok


   )

file(GLOB_RECURSE OPJ_DATA_NR_LIST
     "${INPUT_NR}/*.j2k"
     "${INPUT_NR}/*.j2c"
     "${INPUT_NR}/*.jp2"
     "${INPUT_NR}/*.jpc"







>
>







78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
    issue408.jp2 #kdu_jp2info ok
    issue420.jp2 #kdu_jp2info ok
    27ac957758a35d00d6765a0c86350d9c.SIGFPE.d25.537.jpc #kdu_jp2info crash
    3672da2f1f67bbecad27d7181b4e9d7c.SIGFPE.d25.805.jpc #kdu_jp2info crash
    issue475.jp2 #kdu_jp2info ok
    issue413.jp2 #kdu_jp2info ok
    issue823.jp2 #kdu_jp2info ok
    issue826.jp2 #inspection reveales that the transformation value is out of range
    oss-fuzz2785.jp2 #inspection reveales that the transformation value is out of range
   )

file(GLOB_RECURSE OPJ_DATA_NR_LIST
     "${INPUT_NR}/*.j2k"
     "${INPUT_NR}/*.j2c"
     "${INPUT_NR}/*.jp2"
     "${INPUT_NR}/*.jpc"
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
          message( FATAL_ERROR "${EXE_NAME} is not the right executable name to encode file (try to use opj_compress or opj_decompress)")

        endif ()
      endif ()

    else ()
      # Check if the first argument is equal to opj_compress
      string(REGEX MATCH "^opj_compress$|^opj_decompress$" EXE_NAME_FOUND ${EXE_NAME})

      if(EXE_NAME_FOUND)



        string(REGEX MATCH "opj_compress" ENC_TEST_FOUND ${EXE_NAME})

      else()

        message( FATAL_ERROR "${EXE_NAME} is not the right executable name to encode file (try to use opj_compress)")

      endif()

      list(REMOVE_AT CMD_ARG_LIST 0)



























    endif ()

    # Parse the argument list to find the input filename and output filename
    set(CMD_ARG_LIST_2 "")
    set(ARG_POS 0)
    set(INPUT_ARG_POS 0)







|



>
>
|








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
          message( FATAL_ERROR "${EXE_NAME} is not the right executable name to encode file (try to use opj_compress or opj_decompress)")

        endif ()
      endif ()

    else ()
      # Check if the first argument is equal to opj_compress
      string(REGEX MATCH "^opj_compress$|^opj_compress_no_raw$|^opj_compress_no_raw_lossless$|^opj_decompress$" EXE_NAME_FOUND ${EXE_NAME})

      if(EXE_NAME_FOUND)

        string(REGEX MATCH "^opj_compress$|^opj_compress_no_raw$|^opj_compress_no_raw_lossless$" ENC_TEST_FOUND ${EXE_NAME})
        string(REGEX MATCH "^opj_compress_no_raw$|^opj_compress_no_raw_lossless$" NO_RAW ${EXE_NAME})
        string(REGEX MATCH "opj_compress_no_raw_lossless" LOSSLESS ${EXE_NAME})

      else()

        message( FATAL_ERROR "${EXE_NAME} is not the right executable name to encode file (try to use opj_compress)")

      endif()

      list(REMOVE_AT CMD_ARG_LIST 0)

      if(ENC_TEST_FOUND)

        # Parse lines like opj_compress lossy-check { -n 3 -m 0:0:0 -p 0:0:0 } ...
        set(LOSSY_CHECK_ARG_LIST "")
        list(GET CMD_ARG_LIST 0 NEXT_ARG)
        string(REGEX MATCH "^lossy-check$" LOSSY_CHECK ${NEXT_ARG})
        if(LOSSY_CHECK)
            list(REMOVE_AT CMD_ARG_LIST 0)
            list(GET CMD_ARG_LIST 0 NEXT_ARG)
            string(REGEX MATCH "^{$" FOUND_OPEN_CURL ${NEXT_ARG})
            if(NOT FOUND_OPEN_CURL)
                message( FATAL_ERROR "'{' expected after lossy-check")
            endif()
            list(REMOVE_AT CMD_ARG_LIST 0)
            while(TRUE)
                list(GET CMD_ARG_LIST 0 NEXT_ARG)
                list(REMOVE_AT CMD_ARG_LIST 0)
                string(REGEX MATCH "^}$" FOUND_CLOSE_CURL ${NEXT_ARG})
                if(FOUND_CLOSE_CURL)
                    break()
                endif()
                list (APPEND LOSSY_CHECK_ARG_LIST ${NEXT_ARG})
            endwhile()
        endif()
      endif()

    endif ()

    # Parse the argument list to find the input filename and output filename
    set(CMD_ARG_LIST_2 "")
    set(ARG_POS 0)
    set(INPUT_ARG_POS 0)
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
            -t ${OUTPUT_FILENAME}-ENC-${IT_TEST_ENC}.txt
          )

          set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dump2base
                               PROPERTIES DEPENDS
                               NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-dump)

























          # Decode the encoding file with kakadu expand command
          if (KDU_EXPAND_EXECUTABLE)
            add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
              COMMAND ${KDU_EXPAND_EXECUTABLE}
              -i ${OUTPUT_FILENAME}
              -o ${OUTPUT_FILENAME}.raw
              )

            set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
                                 PROPERTIES DEPENDS
                                 NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode)


            # Compare the decoding file with baseline generated from the kdu_expand and baseline.j2k
            add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
              COMMAND compare_raw_files
              -b ${BASELINE_NR}/opj_${OUTPUT_FILENAME_NAME_WE}-ENC-${IT_TEST_ENC}.raw
              -t ${OUTPUT_FILENAME}.raw
            )

            set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
                                 PROPERTIES DEPENDS
                                 NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref)

          endif()

          # Test the encoded file is a valid JP2 file
          if (JPYLYZER_EXECUTABLE)
            if (${OUTPUT_FILENAME} MATCHES "\\.jp2$")
              add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-jpylyser
                COMMAND ${JPYLYZER_EXECUTABLE}
                ${OUTPUT_FILENAME}
                )
              set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-jpylyser PROPERTIES
                DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode
                PASS_REGULAR_EXPRESSION "<isValidJP2>True</isValidJP2>"
                )		
            endif()
          endif(JPYLYZER_EXECUTABLE)

          # If lossless compression (simple test is 4 arguments), decompress & compare
          list(LENGTH CMD_ARG_LIST_2 ARG_COUNT)
          if (ARG_COUNT EQUAL 4)
            # can we compare with the input image ?
            if (${INPUT_FILENAME_NAME} MATCHES "\\.tif$")
              add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode
                COMMAND opj_decompress -i ${OUTPUT_FILENAME} -o ${OUTPUT_FILENAME}.lossless.tif
                )
              set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode PROPERTIES
                DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>

|










>
|
|
|
|
|
|

|
|
|
|


















|







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
            -t ${OUTPUT_FILENAME}-ENC-${IT_TEST_ENC}.txt
          )

          set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dump2base
                               PROPERTIES DEPENDS
                               NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-dump)

          if(LOSSY_CHECK)
            add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
            COMMAND opj_decompress
            -i ${OUTPUT_FILENAME}
            -o ${OUTPUT_FILENAME}.tif
            )

            set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
                                PROPERTIES DEPENDS
                                NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode)

            # Compare the decoding file with original one, using tolerance
            add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
            COMMAND compare_images
            -b ${INPUT_FILENAME}
            -t ${OUTPUT_FILENAME}.tif
            -s bXtY
            ${LOSSY_CHECK_ARG_LIST}
            )

            set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
                                PROPERTIES DEPENDS
                                NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref)

          # Decode the encoding file with kakadu expand command
          elseif (KDU_EXPAND_EXECUTABLE)
            add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
              COMMAND ${KDU_EXPAND_EXECUTABLE}
              -i ${OUTPUT_FILENAME}
              -o ${OUTPUT_FILENAME}.raw
              )

            set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref
                                 PROPERTIES DEPENDS
                                 NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode)

            if(NOT NO_RAW)
                # Compare the decoding file with baseline generated from the kdu_expand and baseline.j2k
                add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
                COMMAND compare_raw_files
                -b ${BASELINE_NR}/opj_${OUTPUT_FILENAME_NAME_WE}-ENC-${IT_TEST_ENC}.raw
                -t ${OUTPUT_FILENAME}.raw
                )

                set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-compare_dec-ref-out2base
                                    PROPERTIES DEPENDS
                                    NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-decode-ref)
            endif()
          endif()

          # Test the encoded file is a valid JP2 file
          if (JPYLYZER_EXECUTABLE)
            if (${OUTPUT_FILENAME} MATCHES "\\.jp2$")
              add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-jpylyser
                COMMAND ${JPYLYZER_EXECUTABLE}
                ${OUTPUT_FILENAME}
                )
              set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-jpylyser PROPERTIES
                DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode
                PASS_REGULAR_EXPRESSION "<isValidJP2>True</isValidJP2>"
                )		
            endif()
          endif(JPYLYZER_EXECUTABLE)

          # If lossless compression (simple test is 4 arguments), decompress & compare
          list(LENGTH CMD_ARG_LIST_2 ARG_COUNT)
          if ((ARG_COUNT EQUAL 4) OR LOSSLESS)
            # can we compare with the input image ?
            if (${INPUT_FILENAME_NAME} MATCHES "\\.tif$")
              add_test(NAME NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode
                COMMAND opj_decompress -i ${OUTPUT_FILENAME} -o ${OUTPUT_FILENAME}.lossless.tif
                )
              set_tests_properties(NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-lossless-decode PROPERTIES
                DEPENDS NR-ENC-${INPUT_FILENAME_NAME}-${IT_TEST_ENC}-encode
Changes to jni/openjpeg/tests/nonregression/checkmd5refs.cmake.
42
43
44
45
46
47
48



49
50
51
52


53
54
55
56

foreach(pgxfullpath ${globfiles})
  file(MD5 ${pgxfullpath} output)
  get_filename_component(pgxfile ${pgxfullpath} NAME)

  string(REGEX MATCH "[0-9a-f]+  ${pgxfile}" output_var "${variable}")




  set(output "${output}  ${pgxfile}")

  if("${output_var}" STREQUAL "${output}")
    message(STATUS "equal: [${output_var}] vs [${output}]")


  else()
    message(SEND_ERROR "not equal: [${output_var}] vs [${output}]")
  endif()
endforeach()







>
>
>




>
>




42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61

foreach(pgxfullpath ${globfiles})
  file(MD5 ${pgxfullpath} output)
  get_filename_component(pgxfile ${pgxfullpath} NAME)

  string(REGEX MATCH "[0-9a-f]+  ${pgxfile}" output_var "${variable}")

  # Search for variant md5sum for libtiff >= 4.1
  string(REGEX MATCH "libtiff_4_1:[0-9a-f]+  ${pgxfile}" alternate_output_var "${variable}")

  set(output "${output}  ${pgxfile}")

  if("${output_var}" STREQUAL "${output}")
    message(STATUS "equal: [${output_var}] vs [${output}]")
  elseif("${alternate_output_var}" STREQUAL "libtiff_4_1:${output}")
    message(STATUS "equal: [${alternate_output_var}] vs [libtiff_4_1:${output}]")
  else()
    message(SEND_ERROR "not equal: [${output_var}] vs [${output}]")
  endif()
endforeach()
Changes to jni/openjpeg/tests/nonregression/md5refs.txt.
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
3c7ff2e4bdae849167be36589f32bcd5  issue458.jp2_0.pgx
f004b48eafb2e52529cc9c7b6a3ff5d2  issue458.jp2_1.pgx
3127bd0a591d113c3c2428c8d2c14ec8  issue458.jp2_2.pgx
dacaf60e4c430916a8c2a9ebec32e71c  issue458.jp2_3.pgx
d33fb5dbddb9b9b4438eb51fa27445a3  issue495.jp2_0.pgx
27db8c35e12a5d5eb94d403d2aae2909  issue495.jp2_1.pgx
97da625d2f2d0b75bf891d8083ce8bfb  issue495.jp2_2.pgx

86729c5f2b74b2dfd42cb0d8e47aef79  a1_mono_tif-1.tif
fa9b7b896536b25a7a1d8eeeacb59141  a1_mono_tif-10.tif
e1f194f69d1c58ce8bed62cd4f1d5b6a  a1_mono_tif-11.tif
b0ee13aa90ca4421e09a3b7b41f410c0  a1_mono_tif-12.tif
de53251a33356e206a793fbdbaf90db2  a1_mono_tif-13.tif
4699894fedd3758727d8288cd7adb56c  a1_mono_tif-14.tif
012958af4207f4a779c0cdc9e18bc9be  a1_mono_tif-15.tif
4ad682c58e63d3223914c10a6656c8ae  a1_mono_tif-16.tif
22c2fa09a4d7b9fade6a3cddc6c6a4dc  a1_mono_tif-2.tif
7aea003d047d6c26475d0d257a0cfdfc  a1_mono_tif-3.tif
996c5e67a663218be90e86bff8ecad89  a1_mono_tif-4.tif
0489a5d490588fa603a8e59af60ef8fc  a1_mono_tif-5.tif
7f451a5ac89915c5cdc023fd8c813a3c  a1_mono_tif-6.tif
e164a6c0219737ee05a3d55d6e3a3104  a1_mono_tif-7.tif
c3ebfcf478b1c4fc786748813f2b5d53  a1_mono_tif-8.tif
67adb084f1fe234f240a1d0b2698507e  a1_mono_tif-9.tif


















31650ec40241737634179fff6ad306f8  basn4a08_tif-1.tif
abf884080bcfbf58c044a9d86bfa5e5d  basn4a08_tif-10.tif
b0d82c12aa2c9b3ecd96c6a5b5663a8c  basn4a08_tif-11.tif
916d97c098d9792993cc91fee4a83f77  basn4a08_tif-12.tif
90cabbb0f401b75dcfa64e4fbb987020  basn4a08_tif-13.tif
57643174986481d336db6ddf04b970df  basn4a08_tif-14.tif
3cbf7868617a0dfdbeddd5c50ea96b31  basn4a08_tif-15.tif
fb5cf848d63c61dc485c87c9246ee9c7  basn4a08_tif-16.tif
5d7b01d98c82ad563bb28c2d83484a2a  basn4a08_tif-2.tif
7928de544e7d9731572a625beeb2b3ee  basn4a08_tif-3.tif
2401cebbb1d5494fcbe0d899484c342d  basn4a08_tif-4.tif
05ea9dfd48a6cd613bf935394988ec38  basn4a08_tif-5.tif
6dbeb5b708bbde76e204c0887da61f6b  basn4a08_tif-6.tif
18a59ac6036ee64e92af19b7e3cd3d64  basn4a08_tif-7.tif
dc40cc1da6de28e7e973c8ba796ca189  basn4a08_tif-8.tif
824b776a5aa3459b77894b5f77621311  basn4a08_tif-9.tif


















59e32c45591fd3bb44fe99381a116ba1  basn6a08_tif-1.tif
630e6fb6deba0b3efd93b610561d607a  basn6a08_tif-10.tif
5419fec92f0e0e5907d838dacf9712b4  basn6a08_tif-11.tif
765555e75e59de27f7b2177d04f36bc1  basn6a08_tif-12.tif
7d20d3e026fc1ac25be16dd44e9fb2e5  basn6a08_tif-13.tif
62384c112d5fe40aefd0a9b0b9a4bcc6  basn6a08_tif-14.tif
325de66e18e133f2ad865fc1faa20439  basn6a08_tif-15.tif
d725d41557658a28ab31dff74e2467fa  basn6a08_tif-16.tif
96d91df6b10e866ea26ebbf0b8ddc7da  basn6a08_tif-2.tif
36690c1fe565b6efc229f5c7e486de31  basn6a08_tif-3.tif
a324032339808d5fe85d6e354f14c183  basn6a08_tif-4.tif
64dfb6af672ea8e890e24cfb208c6755  basn6a08_tif-5.tif
d60864a6a5c8a49a202d98ae6f5165c7  basn6a08_tif-6.tif
086fd12fec963995fe2e405dcef7e477  basn6a08_tif-7.tif
c3e93f61125f82a9832d0b9440468034  basn6a08_tif-8.tif
a9723dcc0732e74c9e8cd2bf93474a7d  basn6a08_tif-9.tif


















cfe04d15cf9d615fc36357dcb3b3956b  p0_14_tif-1.tif
9ad87e7fddc77ac85e2e92509bee2365  p0_14_tif-10.tif
f144e26d6d5aa24d98f0415f10751025  p0_14_tif-11.tif
38e67f9d573e61166761d5eee0104448  p0_14_tif-12.tif
4e804903537e4c52a7e4c15bd74eb15c  p0_14_tif-13.tif
77486f0468694b94290d0b55361498a0  p0_14_tif-14.tif
2aa3211823a8ee41cc5061f401dfd52d  p0_14_tif-15.tif
51be675689949dd08b6ee1427af3eb4a  p0_14_tif-16.tif
3e34e94bd8f7380c8d159676fee9ea57  p0_14_tif-2.tif
f623c6b98711ba8582f2b60620c6494a  p0_14_tif-3.tif
b6f71c941e3a5b8d2547792ccec58d54  p0_14_tif-4.tif
5a8498d473cc57318ab9d216fdc5dcc9  p0_14_tif-5.tif
81fcdd90917efb95aed94c6522d1c188  p0_14_tif-6.tif
951c99efbd922d8f3feb015e9ef8e350  p0_14_tif-7.tif
6808377b760b4ef3559ba8b14ed9b91a  p0_14_tif-8.tif
96aa7dafa873d0ce33f84bb1ff78fa9b  p0_14_tif-9.tif


















dd15b3d487d36a3682be0679300a4319  issue235.jp2_0.pgx
b9cd6dc76b141fb1fec15f50c1f70e01  issue235.jp2_1.pgx
3edef2ae197ef30b08deda1b28825399  issue235.jp2_2.pgx
b6a84b3215333efc80326715f9078c58  a1_mono_png-1.png
88f96456667b8b3fd69c406fe40636b5  a1_mono_png-10.png
077148452a9506a2337afa2777c57834  a1_mono_png-12.png
c4eee75c1da8d43e1510cb36326f948b  a1_mono_png-14.png







>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
















>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
3c7ff2e4bdae849167be36589f32bcd5  issue458.jp2_0.pgx
f004b48eafb2e52529cc9c7b6a3ff5d2  issue458.jp2_1.pgx
3127bd0a591d113c3c2428c8d2c14ec8  issue458.jp2_2.pgx
dacaf60e4c430916a8c2a9ebec32e71c  issue458.jp2_3.pgx
d33fb5dbddb9b9b4438eb51fa27445a3  issue495.jp2_0.pgx
27db8c35e12a5d5eb94d403d2aae2909  issue495.jp2_1.pgx
97da625d2f2d0b75bf891d8083ce8bfb  issue495.jp2_2.pgx

86729c5f2b74b2dfd42cb0d8e47aef79  a1_mono_tif-1.tif
fa9b7b896536b25a7a1d8eeeacb59141  a1_mono_tif-10.tif
e1f194f69d1c58ce8bed62cd4f1d5b6a  a1_mono_tif-11.tif
b0ee13aa90ca4421e09a3b7b41f410c0  a1_mono_tif-12.tif
de53251a33356e206a793fbdbaf90db2  a1_mono_tif-13.tif
4699894fedd3758727d8288cd7adb56c  a1_mono_tif-14.tif
012958af4207f4a779c0cdc9e18bc9be  a1_mono_tif-15.tif
4ad682c58e63d3223914c10a6656c8ae  a1_mono_tif-16.tif
22c2fa09a4d7b9fade6a3cddc6c6a4dc  a1_mono_tif-2.tif
7aea003d047d6c26475d0d257a0cfdfc  a1_mono_tif-3.tif
996c5e67a663218be90e86bff8ecad89  a1_mono_tif-4.tif
0489a5d490588fa603a8e59af60ef8fc  a1_mono_tif-5.tif
7f451a5ac89915c5cdc023fd8c813a3c  a1_mono_tif-6.tif
e164a6c0219737ee05a3d55d6e3a3104  a1_mono_tif-7.tif
c3ebfcf478b1c4fc786748813f2b5d53  a1_mono_tif-8.tif
67adb084f1fe234f240a1d0b2698507e  a1_mono_tif-9.tif

libtiff_4_1:fc19057ff2d65c24daf9c9e25e34a48a  a1_mono_tif-1.tif
libtiff_4_1:66246b6bbc83c06962f034235acb9924  a1_mono_tif-10.tif
libtiff_4_1:ce1e07bdafe83a84a5df87fce2ffde6a  a1_mono_tif-11.tif
libtiff_4_1:614f1ab59ca8473f5f8b1772b7a19d24  a1_mono_tif-12.tif
libtiff_4_1:941bdcdf9103a22f7b6f66aaca3276d1  a1_mono_tif-13.tif
libtiff_4_1:38df45296861df2b44879e8a0787d43c  a1_mono_tif-14.tif
libtiff_4_1:387575ff38bed3d177776891e1b2804e  a1_mono_tif-15.tif
libtiff_4_1:ee4838fbd88ddcb73ef26df523a3bb5d  a1_mono_tif-16.tif
libtiff_4_1:6de7e8cbd95e2c465b587f2273daf9dc  a1_mono_tif-2.tif
libtiff_4_1:e1e026d7ed26e8f3334cf25a8884abbd  a1_mono_tif-3.tif
libtiff_4_1:c120fac03d1b3756a2deb9b92ba519d4  a1_mono_tif-4.tif
libtiff_4_1:3a7b84ed9061e0b13996660fc2910e8a  a1_mono_tif-5.tif
libtiff_4_1:7ac8316261d54f22e6c847fbac01542b  a1_mono_tif-6.tif
libtiff_4_1:d714670f6746931c4e7defbfbe38b249  a1_mono_tif-7.tif
libtiff_4_1:b28f4b92be5e3481d44f50f2cd7626aa  a1_mono_tif-8.tif
libtiff_4_1:2a12dcda3e9927384e7344c4ecabdcf1  a1_mono_tif-9.tif

31650ec40241737634179fff6ad306f8  basn4a08_tif-1.tif
abf884080bcfbf58c044a9d86bfa5e5d  basn4a08_tif-10.tif
b0d82c12aa2c9b3ecd96c6a5b5663a8c  basn4a08_tif-11.tif
916d97c098d9792993cc91fee4a83f77  basn4a08_tif-12.tif
90cabbb0f401b75dcfa64e4fbb987020  basn4a08_tif-13.tif
57643174986481d336db6ddf04b970df  basn4a08_tif-14.tif
3cbf7868617a0dfdbeddd5c50ea96b31  basn4a08_tif-15.tif
fb5cf848d63c61dc485c87c9246ee9c7  basn4a08_tif-16.tif
5d7b01d98c82ad563bb28c2d83484a2a  basn4a08_tif-2.tif
7928de544e7d9731572a625beeb2b3ee  basn4a08_tif-3.tif
2401cebbb1d5494fcbe0d899484c342d  basn4a08_tif-4.tif
05ea9dfd48a6cd613bf935394988ec38  basn4a08_tif-5.tif
6dbeb5b708bbde76e204c0887da61f6b  basn4a08_tif-6.tif
18a59ac6036ee64e92af19b7e3cd3d64  basn4a08_tif-7.tif
dc40cc1da6de28e7e973c8ba796ca189  basn4a08_tif-8.tif
824b776a5aa3459b77894b5f77621311  basn4a08_tif-9.tif

libtiff_4_1:4c50df5b25e006041b05e8a6fb77c95e  basn4a08_tif-1.tif
libtiff_4_1:68cc9a9bc5f95474744d06ea4efb2cf3  basn4a08_tif-10.tif
libtiff_4_1:f643c00bd0673c8f6092125e38759a35  basn4a08_tif-11.tif
libtiff_4_1:cfcefece2fb08a437876d85941cdaa27  basn4a08_tif-12.tif
libtiff_4_1:1c3850831691aa8b565e4cd0d13166f9  basn4a08_tif-13.tif
libtiff_4_1:06059e0429956946ecd3b1893ad39d18  basn4a08_tif-14.tif
libtiff_4_1:71557ba6728e6641ad289b1d142acade  basn4a08_tif-15.tif
libtiff_4_1:150c663277b43d0331112f24d47fd34e  basn4a08_tif-16.tif
libtiff_4_1:9b43011e7a19079c21d65318b4a1139b  basn4a08_tif-2.tif
libtiff_4_1:125ca7b2e45fafa4e003f5adc9f11da8  basn4a08_tif-3.tif
libtiff_4_1:9fbc1a8f4d12c8152cde3e004cebd191  basn4a08_tif-4.tif
libtiff_4_1:51c6b54e9d8b53355c3f73ad813bdeef  basn4a08_tif-5.tif
libtiff_4_1:604ac42b1a9e7a75d63e97ce40e43442  basn4a08_tif-6.tif
libtiff_4_1:360d1ce74faffa1a736d5f30c22976ed  basn4a08_tif-7.tif
libtiff_4_1:2059aaa9e54c09f36d16107870c1546a  basn4a08_tif-8.tif
libtiff_4_1:07496859507882401d66d70dcf392505  basn4a08_tif-9.tif

59e32c45591fd3bb44fe99381a116ba1  basn6a08_tif-1.tif
630e6fb6deba0b3efd93b610561d607a  basn6a08_tif-10.tif
5419fec92f0e0e5907d838dacf9712b4  basn6a08_tif-11.tif
765555e75e59de27f7b2177d04f36bc1  basn6a08_tif-12.tif
7d20d3e026fc1ac25be16dd44e9fb2e5  basn6a08_tif-13.tif
62384c112d5fe40aefd0a9b0b9a4bcc6  basn6a08_tif-14.tif
325de66e18e133f2ad865fc1faa20439  basn6a08_tif-15.tif
d725d41557658a28ab31dff74e2467fa  basn6a08_tif-16.tif
96d91df6b10e866ea26ebbf0b8ddc7da  basn6a08_tif-2.tif
36690c1fe565b6efc229f5c7e486de31  basn6a08_tif-3.tif
a324032339808d5fe85d6e354f14c183  basn6a08_tif-4.tif
64dfb6af672ea8e890e24cfb208c6755  basn6a08_tif-5.tif
d60864a6a5c8a49a202d98ae6f5165c7  basn6a08_tif-6.tif
086fd12fec963995fe2e405dcef7e477  basn6a08_tif-7.tif
c3e93f61125f82a9832d0b9440468034  basn6a08_tif-8.tif
a9723dcc0732e74c9e8cd2bf93474a7d  basn6a08_tif-9.tif

libtiff_4_1:98f777ca80a132d8ab820d4533daa5b6  basn6a08_tif-1.tif
libtiff_4_1:9c5873a1fa5571aad9e73d36d5a4206a  basn6a08_tif-10.tif
libtiff_4_1:c05dac7d4c19bc4b78cea426e5e52430  basn6a08_tif-11.tif
libtiff_4_1:0223432f61df2508d0195f696988ddeb  basn6a08_tif-12.tif
libtiff_4_1:ccc64d14279063ed9daf371be62077f7  basn6a08_tif-13.tif
libtiff_4_1:ace0bab2c2fbb5f92a8214600df9159f  basn6a08_tif-14.tif
libtiff_4_1:9b54bda92a09bcac9870fa02b428b7e6  basn6a08_tif-15.tif
libtiff_4_1:178665d070f54f2920521c4e1cb9d5d0  basn6a08_tif-16.tif
libtiff_4_1:c4b1e96d19429137cd8871833af2ea5a  basn6a08_tif-2.tif
libtiff_4_1:44e8b5591740289d0ca52a3e19f19c22  basn6a08_tif-3.tif
libtiff_4_1:70b4f469dd29c8e99d3f0525301286b8  basn6a08_tif-4.tif
libtiff_4_1:bf7c35a2b05eecb406aab7959431a842  basn6a08_tif-5.tif
libtiff_4_1:7d2ecb1c35869ddbafd11b4896357b81  basn6a08_tif-6.tif
libtiff_4_1:2cd6ec32a0256806f46706c0ca564d9d  basn6a08_tif-7.tif
libtiff_4_1:116b611b7a358bee2c4f2695732ec357  basn6a08_tif-8.tif
libtiff_4_1:ed9ca54d25fb5b0cd5339eedfa16cbea  basn6a08_tif-9.tif

cfe04d15cf9d615fc36357dcb3b3956b  p0_14_tif-1.tif
9ad87e7fddc77ac85e2e92509bee2365  p0_14_tif-10.tif
f144e26d6d5aa24d98f0415f10751025  p0_14_tif-11.tif
38e67f9d573e61166761d5eee0104448  p0_14_tif-12.tif
4e804903537e4c52a7e4c15bd74eb15c  p0_14_tif-13.tif
77486f0468694b94290d0b55361498a0  p0_14_tif-14.tif
2aa3211823a8ee41cc5061f401dfd52d  p0_14_tif-15.tif
51be675689949dd08b6ee1427af3eb4a  p0_14_tif-16.tif
3e34e94bd8f7380c8d159676fee9ea57  p0_14_tif-2.tif
f623c6b98711ba8582f2b60620c6494a  p0_14_tif-3.tif
b6f71c941e3a5b8d2547792ccec58d54  p0_14_tif-4.tif
5a8498d473cc57318ab9d216fdc5dcc9  p0_14_tif-5.tif
81fcdd90917efb95aed94c6522d1c188  p0_14_tif-6.tif
951c99efbd922d8f3feb015e9ef8e350  p0_14_tif-7.tif
6808377b760b4ef3559ba8b14ed9b91a  p0_14_tif-8.tif
96aa7dafa873d0ce33f84bb1ff78fa9b  p0_14_tif-9.tif

libtiff_4_1:5f97d4bbab138f99b6b125e5a5bf96bd  p0_14_tif-1.tif
libtiff_4_1:686c7a1561d73e53c000800ec0c5fa0a  p0_14_tif-10.tif
libtiff_4_1:a8585d901cc1b7cbbda6e524ecb5db35  p0_14_tif-11.tif
libtiff_4_1:17b5497c9b8a0c68739c0beae90aa432  p0_14_tif-12.tif
libtiff_4_1:a024a04b96ccb13c81cd57a5ee6ad07a  p0_14_tif-13.tif
libtiff_4_1:aabadca3f87437a32878fef7e265b23a  p0_14_tif-14.tif
libtiff_4_1:5390a77296962268b73a793467092633  p0_14_tif-15.tif
libtiff_4_1:47dc7cc71832e5739c32794a713966c3  p0_14_tif-16.tif
libtiff_4_1:1a9247cd1fb26f5fffa870e8543f6d30  p0_14_tif-2.tif
libtiff_4_1:e4c0c9481d4032ea6b7e6a08a39e9030  p0_14_tif-3.tif
libtiff_4_1:c7d6ec9b235aaff146228875e69edbaa  p0_14_tif-4.tif
libtiff_4_1:d3b8110b2284a09cfb7d5c4ffd451aff  p0_14_tif-5.tif
libtiff_4_1:6189ee17c4a276f99302ac7e296b3daa  p0_14_tif-6.tif
libtiff_4_1:b4a3b9b63681448abb7c460702de4df9  p0_14_tif-7.tif
libtiff_4_1:04deb4e9679e7971c2cd0449fcd255b7  p0_14_tif-8.tif
libtiff_4_1:254443e438ed6a5b0631d6188cc84789  p0_14_tif-9.tif

dd15b3d487d36a3682be0679300a4319  issue235.jp2_0.pgx
b9cd6dc76b141fb1fec15f50c1f70e01  issue235.jp2_1.pgx
3edef2ae197ef30b08deda1b28825399  issue235.jp2_2.pgx
b6a84b3215333efc80326715f9078c58  a1_mono_png-1.png
88f96456667b8b3fd69c406fe40636b5  a1_mono_png-10.png
077148452a9506a2337afa2777c57834  a1_mono_png-12.png
c4eee75c1da8d43e1510cb36326f948b  a1_mono_png-14.png
284
285
286
287
288
289
290

291
292
293
294
295
296
297
0c1cc85c051dd95394d06103c8d9bbef  p0_14_png-6.png
230e4968cb445b222ee2095014ba1d26  p0_14_png-8.png
5a6131ad9ea5d191ffcdf6435be89cb4  v4dwt_interleave_h.gsr105.j2k_0.pgx
65e41ed91283b5e2f0c79ee1c867a86c  dwt_interleave_h.gsr105.jp2_0.pgx
8d7685f1569d446787476c0a56c93750  dwt_interleave_h.gsr105.jp2_1.pgx
ddfff2ce2df4a9102518c92a362e6d25  dwt_interleave_h.gsr105.jp2_2.pgx
63bf755af5a1f8a478d65079dc7c8964  issue205-tif.jp2.tif

b01ed87dbac424bc820b2ac590e4884e  issue236-ESYCC-CDEF.jp2_0.pgx
2635cc00b1e18ef11adcba09e845d459  issue236-ESYCC-CDEF.jp2_1.pgx
f9c95d0aec2f6e7b814fa1d09edcdbda  issue236-ESYCC-CDEF.jp2_2.pgx
4c3a5c669aaaa330134c7014b26ed06f  issue559-eci-090-CIELab.jp2_0.pgx
d6698c71d1ed3861edaadc430af928eb  issue559-eci-090-CIELab.jp2_1.pgx
04f3ec1fea6049769c43b1ac3b05794e  issue559-eci-090-CIELab.jp2_2.pgx
a190e10941e6145e69816c909f832c1a  issue559-eci-091-CIELab.jp2_0.pgx







>







357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
0c1cc85c051dd95394d06103c8d9bbef  p0_14_png-6.png
230e4968cb445b222ee2095014ba1d26  p0_14_png-8.png
5a6131ad9ea5d191ffcdf6435be89cb4  v4dwt_interleave_h.gsr105.j2k_0.pgx
65e41ed91283b5e2f0c79ee1c867a86c  dwt_interleave_h.gsr105.jp2_0.pgx
8d7685f1569d446787476c0a56c93750  dwt_interleave_h.gsr105.jp2_1.pgx
ddfff2ce2df4a9102518c92a362e6d25  dwt_interleave_h.gsr105.jp2_2.pgx
63bf755af5a1f8a478d65079dc7c8964  issue205-tif.jp2.tif
libtiff_4_1:f9678a9e12d540f768ebebaee2af8f14  issue205-tif.jp2.tif
b01ed87dbac424bc820b2ac590e4884e  issue236-ESYCC-CDEF.jp2_0.pgx
2635cc00b1e18ef11adcba09e845d459  issue236-ESYCC-CDEF.jp2_1.pgx
f9c95d0aec2f6e7b814fa1d09edcdbda  issue236-ESYCC-CDEF.jp2_2.pgx
4c3a5c669aaaa330134c7014b26ed06f  issue559-eci-090-CIELab.jp2_0.pgx
d6698c71d1ed3861edaadc430af928eb  issue559-eci-090-CIELab.jp2_1.pgx
04f3ec1fea6049769c43b1ac3b05794e  issue559-eci-090-CIELab.jp2_2.pgx
a190e10941e6145e69816c909f832c1a  issue559-eci-091-CIELab.jp2_0.pgx
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320

dacaf60e4c430916a8c2a9ebec32e71c  issue979.j2k_3.pgx
3d710c406d4c9a53f33945db781ee544  broken.jpc_0.pgx
d1bb7f93f4c0eb984b2e9c54e544b7e9  broken.jpc_1.pgx
8cc41ccf2ef66261f1a440b8753a3f90  broken.jpc_2.pgx
b704ad4c0cfefffd78c20a54f5541265  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_0.pgx
9d7fe43cd7a50b7bbaf712926ee11980  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_1.pgx
0960b580f991ff10f693b24aa41ad58b  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_2.pgx
fa7382fd8b2e788b28b807e200dd95b9  file1.jp2-c0.tif
ed79b7fe443955cdefba2b039ddc846a  file1.jp2-c0_1_2.tif
ac8f6ab3acc9c692ed7c41bd62a0e1e8  file1.jp2-c0-r1.tif
fbfcf662b6f7549574b2885490fbcf12  file1.jp2-c0-d10_20_30_40.tif
fa7382fd8b2e788b28b807e200dd95b9  file1.jp2-c0-t0.tif
ac8f6ab3acc9c692ed7c41bd62a0e1e8  file1.jp2-c0-t0-r1.tif
f31bcb01c771f829054cdb013575e86a  issue1043.png
62bc654c830efddf1b23d6e208447dab  tnsot_zero.png








|
|
|
|
|
|


>
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
dacaf60e4c430916a8c2a9ebec32e71c  issue979.j2k_3.pgx
3d710c406d4c9a53f33945db781ee544  broken.jpc_0.pgx
d1bb7f93f4c0eb984b2e9c54e544b7e9  broken.jpc_1.pgx
8cc41ccf2ef66261f1a440b8753a3f90  broken.jpc_2.pgx
b704ad4c0cfefffd78c20a54f5541265  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_0.pgx
9d7fe43cd7a50b7bbaf712926ee11980  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_1.pgx
0960b580f991ff10f693b24aa41ad58b  dwt_interleave_h.gsr105.jp2_d_1_1_33_33_2.pgx
6e23ded7d3ca0b1dd8405448e3ff931b  file1.jp2-c0.png
5acabea0ef6d09d2c1f681773e886935  file1.jp2-c0_1_2.png
1150acbee2c1e33c57592c05c76e565a  file1.jp2-c0-r1.png
1b8ab42d8ee4e28d2868c04a815fb569  file1.jp2-c0-d10_20_30_40.png
6e23ded7d3ca0b1dd8405448e3ff931b  file1.jp2-c0-t0.png
1150acbee2c1e33c57592c05c76e565a  file1.jp2-c0-t0-r1.png
f31bcb01c771f829054cdb013575e86a  issue1043.png
62bc654c830efddf1b23d6e208447dab  tnsot_zero.png
c34637a0f218e4074936e0c89534c5b5  tnsot_zero_missing_eoc.png
Changes to jni/openjpeg/tests/nonregression/test_suite.ctest.in.
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
opj_compress -i @INPUT_NR_PATH@/Cevennes2.ppm -o @TEMP_PATH@/Cevennes2.jp2 -r 50
opj_compress -i @INPUT_NR_PATH@/Rome.bmp -o @TEMP_PATH@/Rome.jp2 -q 30,35,50 -p LRCP -n 3
# related to issue 5
opj_compress -i @INPUT_NR_PATH@/random-issue-0005.tif -o @TEMP_PATH@/random-issue-0005.tif.j2k
# related to issue 62
opj_compress -i @INPUT_NR_PATH@/tmp-issue-0062.raw -o @TEMP_PATH@/tmp-issue-0062-u.raw.j2k -F 512,512,1,16,u
opj_compress -i @INPUT_NR_PATH@/tmp-issue-0062.raw -o @TEMP_PATH@/tmp-issue-0062-s.raw.j2k -F 512,512,1,16,s
opj_compress -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_C2K_24.j2k -cinema2K 24
opj_compress -i @INPUT_NR_PATH@/X_5_2K_24_235_CBR_STEM24_000.tif -o @TEMP_PATH@/X_5_2K_24_235_CBR_STEM24_000_C2K_24.j2k -cinema2K 24
opj_compress -i @INPUT_NR_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o @TEMP_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000_C2K_24.j2k -cinema2K 24
opj_compress -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_C2K_48.j2k -cinema2K 48
opj_compress -i @INPUT_NR_PATH@/X_5_2K_24_235_CBR_STEM24_000.tif -o @TEMP_PATH@/X_5_2K_24_235_CBR_STEM24_000_C2K_48.j2k -cinema2K 48
opj_compress -i @INPUT_NR_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o @TEMP_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000_C2K_48.j2k -cinema2K 48
opj_compress -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/ElephantDream_4K_C4K.j2k -cinema4K
# issue 141
opj_compress -i @INPUT_NR_PATH@/issue141.rawl -o @TEMP_PATH@/issue141.rawl.j2k   -F 2048,32,1,16,u
opj_compress -i @INPUT_NR_PATH@/issue141.rawl -o @TEMP_PATH@/issue141-I.rawl.j2k -F 2048,32,1,16,u -I
# issue 46:
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_5.j2k -c [64,64]
# issue 316
opj_compress -i @INPUT_NR_PATH@/issue316.png -o @TEMP_PATH@/issue316.png.jp2
# issue 416 (cdef for png with alpha) + issue 436 (MCT norm read buffer overflow for num comp > 3 + Issue 215 number of decomp levels
opj_compress -i @INPUT_NR_PATH@/pngsuite/basn6a08.png -o @TEMP_PATH@/basn6a08.png.jp2 -n 6
# issue 203 BMP Files not handled properly







|
|
|
|
|
|
|


|







28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
opj_compress -i @INPUT_NR_PATH@/Cevennes2.ppm -o @TEMP_PATH@/Cevennes2.jp2 -r 50
opj_compress -i @INPUT_NR_PATH@/Rome.bmp -o @TEMP_PATH@/Rome.jp2 -q 30,35,50 -p LRCP -n 3
# related to issue 5
opj_compress -i @INPUT_NR_PATH@/random-issue-0005.tif -o @TEMP_PATH@/random-issue-0005.tif.j2k
# related to issue 62
opj_compress -i @INPUT_NR_PATH@/tmp-issue-0062.raw -o @TEMP_PATH@/tmp-issue-0062-u.raw.j2k -F 512,512,1,16,u
opj_compress -i @INPUT_NR_PATH@/tmp-issue-0062.raw -o @TEMP_PATH@/tmp-issue-0062-s.raw.j2k -F 512,512,1,16,s
opj_compress lossy-check { -n 3 -i prec -m 175:100:212 -p 79:64:92 } -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_C2K_24.j2k -cinema2K 24
opj_compress lossy-check { -n 3 -i prec -m 298:168:363 -p 122:73:164 } -i @INPUT_NR_PATH@/X_5_2K_24_235_CBR_STEM24_000.tif -o @TEMP_PATH@/X_5_2K_24_235_CBR_STEM24_000_C2K_24.j2k -cinema2K 24
opj_compress lossy-check { -n 3 -i prec -m 76:54:140 -p 56:49:74 } -i @INPUT_NR_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o @TEMP_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000_C2K_24.j2k -cinema2K 24
opj_compress lossy-check { -n 3 -i prec -m 384:385:842 -p 135:144:202 } -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_C2K_48.j2k -cinema2K 48
opj_compress lossy-check { -n 3 -i prec -m 933:827:2206 -p 201:184:314 } -i @INPUT_NR_PATH@/X_5_2K_24_235_CBR_STEM24_000.tif -o @TEMP_PATH@/X_5_2K_24_235_CBR_STEM24_000_C2K_48.j2k -cinema2K 48
opj_compress lossy-check { -n 3 -i prec -m 194:173:531 -p 94:79:154 } -i @INPUT_NR_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000.tif -o @TEMP_PATH@/X_6_2K_24_FULL_CBR_CIRCLE_000_C2K_48.j2k -cinema2K 48
opj_compress lossy-check { -n 3 -i prec -m 6:4:7 -p 141:141:191 } -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/ElephantDream_4K_C4K.j2k -cinema4K
# issue 141
opj_compress -i @INPUT_NR_PATH@/issue141.rawl -o @TEMP_PATH@/issue141.rawl.j2k   -F 2048,32,1,16,u
opj_compress lossy-check { -n 1 -m 0.1 -p 2 } -i @INPUT_NR_PATH@/issue141.tif -o @TEMP_PATH@/issue141-I.rawl.j2k -I
# issue 46:
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_5.j2k -c [64,64]
# issue 316
opj_compress -i @INPUT_NR_PATH@/issue316.png -o @TEMP_PATH@/issue316.png.jp2
# issue 416 (cdef for png with alpha) + issue 436 (MCT norm read buffer overflow for num comp > 3 + Issue 215 number of decomp levels
opj_compress -i @INPUT_NR_PATH@/pngsuite/basn6a08.png -o @TEMP_PATH@/basn6a08.png.jp2 -n 6
# issue 203 BMP Files not handled properly
167
168
169
170
171
172
173















174
175
176
177
178
179
180
# Test fix for #891/#892 (tiles smaller than decomposition levels)
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_empty_band.j2k -t 2591,1943 -n 2
# Same rate as Bretagne2_4.j2k
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_empty_band_r800.j2k -t 2591,1943 -n 2 -r 800

opj_compress -i @INPUT_NR_PATH@/issue982.bmp -o @TEMP_PATH@/issue982.j2k -n 1
















# DECODER TEST SUITE
opj_decompress -i  @INPUT_NR_PATH@/Bretagne2.j2k -o @TEMP_PATH@/Bretagne2.j2k.pgx
opj_decompress -i  @INPUT_NR_PATH@/_00042.j2k -o @TEMP_PATH@/_00042.j2k.pgx
opj_decompress -i  @INPUT_NR_PATH@/123.j2c -o @TEMP_PATH@/123.j2c.pgx
# The 4 following tests should failed (kakadu indicates that they are corrupted)
!opj_decompress -i  @INPUT_NR_PATH@/broken1.jp2 -o @TEMP_PATH@/broken1.jp2.pgx
!opj_decompress -i  @INPUT_NR_PATH@/broken2.jp2 -o @TEMP_PATH@/broken2.jp2.pgx







>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
# Test fix for #891/#892 (tiles smaller than decomposition levels)
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_empty_band.j2k -t 2591,1943 -n 2
# Same rate as Bretagne2_4.j2k
opj_compress -i @INPUT_NR_PATH@/Bretagne2.ppm -o @TEMP_PATH@/Bretagne2_empty_band_r800.j2k -t 2591,1943 -n 2 -r 800

opj_compress -i @INPUT_NR_PATH@/issue982.bmp -o @TEMP_PATH@/issue982.j2k -n 1

# Test generating only one POC
opj_compress -i @INPUT_NR_PATH@/byte.tif -o @TEMP_PATH@/byte_one_poc.j2k -n 2 -r 20,1 -POC T1=0,0,2,2,1,CPRL -b 4,4
opj_compress -i @INPUT_NR_PATH@/byte.tif -o @TEMP_PATH@/byte_one_poc_funky_bounds.j2k -n 2 -r 20,1 -POC T1=0,0,65535,33,255,CPRL -b 4,4
opj_compress -i @INPUT_NR_PATH@/byte.tif -o @TEMP_PATH@/byte_one_poc_unrelated_tile.j2k -n 1 -POC T1000=0,0,1,1,1,CPRL

opj_compress_no_raw -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_2K.j2k -IMF 2K
opj_compress_no_raw -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_4K.j2k -IMF 4K
opj_compress_no_raw -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_8K.j2k -IMF 8K
opj_compress_no_raw_lossless -i @INPUT_NR_PATH@/X_4_2K_24_185_CBR_WB_000.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_2K_R.j2k -IMF 2K_R
opj_compress_no_raw_lossless -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_4K_R.j2k -IMF 4K_R
opj_compress_no_raw_lossless -i @INPUT_NR_PATH@/ElephantDream_4K.tif -o @TEMP_PATH@/X_4_2K_24_185_CBR_WB_000_IMF_8K_R.j2k -IMF 8K_R

opj_compress_no_raw_lossless -i @INPUT_NR_PATH@/byte.tif -o @TEMP_PATH@/byte_PLT.j2k -n 1 -PLT
opj_compress_no_raw_lossless -i @INPUT_NR_PATH@/byte.tif -o @TEMP_PATH@/byte_PLT.jp2 -n 1 -PLT

# DECODER TEST SUITE
opj_decompress -i  @INPUT_NR_PATH@/Bretagne2.j2k -o @TEMP_PATH@/Bretagne2.j2k.pgx
opj_decompress -i  @INPUT_NR_PATH@/_00042.j2k -o @TEMP_PATH@/_00042.j2k.pgx
opj_decompress -i  @INPUT_NR_PATH@/123.j2c -o @TEMP_PATH@/123.j2c.pgx
# The 4 following tests should failed (kakadu indicates that they are corrupted)
!opj_decompress -i  @INPUT_NR_PATH@/broken1.jp2 -o @TEMP_PATH@/broken1.jp2.pgx
!opj_decompress -i  @INPUT_NR_PATH@/broken2.jp2 -o @TEMP_PATH@/broken2.jp2.pgx
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632


# issue 979 (.j2k with different bit depth per component)
opj_decompress -i @INPUT_NR_PATH@/issue979.j2k -o @TEMP_PATH@/issue979.j2k.pgx

# https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=3115
opj_decompress -i @INPUT_NR_PATH@/dwt_interleave_h.gsr105.jp2 -o @TEMP_PATH@/dwt_interleave_h.gsr105.jp2_d_1_1_33_33.pgx -d 1,1,33,33

# partial component decoding with opj_decode(): one component
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0.tif -c 0
# partial component decoding with opj_decode(): 3 components without MCT
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0_1_2.tif -c 0,1,2
# partial component decoding with opj_decode() and opj_set_decode_area()
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-d10_20_30_40.tif -c 0 -d 10,20,30,40
# partial component decoding with opj_decode() and reduced resolution
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-r1.tif -c 0 -r 1
# partial component decoding with opj_get_decoded_tile()
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-t0.tif -c 0 -t 0
# partial component decoding with opj_get_decoded_tile() and reduced resolution
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-t0-r1.tif -c 0 -t 0 -r 1

# try to map the same component several times
!opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0_0.tif -c 0,0
# try to map an invalid component
!opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c10.tif -c 10

opj_decompress -i @INPUT_NR_PATH@/db11217111510058.jp2 -o @TEMP_PATH@/issue1043.png

opj_decompress -i @INPUT_NR_PATH@/tnsot_zero.jp2 -o @TEMP_PATH@/tnsot_zero.png

# try to decompress file with repeated PPT marker
!opj_decompress -i @INPUT_NR_PATH@/oss-fuzz2785.jp2 -o @TEMP_PATH@/oss-fuzz2785.png









|

|

|

|

|

|


|

|







>
>
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
# issue 979 (.j2k with different bit depth per component)
opj_decompress -i @INPUT_NR_PATH@/issue979.j2k -o @TEMP_PATH@/issue979.j2k.pgx

# https://bugs.chromium.org/p/oss-fuzz/issues/detail?id=3115
opj_decompress -i @INPUT_NR_PATH@/dwt_interleave_h.gsr105.jp2 -o @TEMP_PATH@/dwt_interleave_h.gsr105.jp2_d_1_1_33_33.pgx -d 1,1,33,33

# partial component decoding with opj_decode(): one component
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0.png -c 0
# partial component decoding with opj_decode(): 3 components without MCT
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0_1_2.png -c 0,1,2
# partial component decoding with opj_decode() and opj_set_decode_area()
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-d10_20_30_40.png -c 0 -d 10,20,30,40
# partial component decoding with opj_decode() and reduced resolution
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-r1.png -c 0 -r 1
# partial component decoding with opj_get_decoded_tile()
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-t0.png -c 0 -t 0
# partial component decoding with opj_get_decoded_tile() and reduced resolution
opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0-t0-r1.png -c 0 -t 0 -r 1

# try to map the same component several times
!opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c0_0.png -c 0,0
# try to map an invalid component
!opj_decompress -i @INPUT_CONF_PATH@/file1.jp2 -o @TEMP_PATH@/file1.jp2-c10.png -c 10

opj_decompress -i @INPUT_NR_PATH@/db11217111510058.jp2 -o @TEMP_PATH@/issue1043.png

opj_decompress -i @INPUT_NR_PATH@/tnsot_zero.jp2 -o @TEMP_PATH@/tnsot_zero.png

# try to decompress file with repeated PPT marker
!opj_decompress -i @INPUT_NR_PATH@/oss-fuzz2785.jp2 -o @TEMP_PATH@/oss-fuzz2785.png

opj_decompress -i @INPUT_NR_PATH@/tnsot_zero_missing_eoc.jp2 -o @TEMP_PATH@/tnsot_zero_missing_eoc.png
Changes to jni/openjpeg/tests/test_decode_area.c.
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

    {
        opj_codestream_info_v2_t* pCodeStreamInfo = opj_get_cstr_info(l_codec);
        if (ptilew) {
            *ptilew = pCodeStreamInfo->tdx;
        }
        if (ptileh) {
            *ptilew = pCodeStreamInfo->tdy;
        }
        //int numResolutions = pCodeStreamInfo->m_default_tile_info.tccp_info[0].numresolutions;
        if (pcblkw) {
            *pcblkw = 1U << pCodeStreamInfo->m_default_tile_info.tccp_info[0].cblkw;
        }
        if (pcblkh) {
            *pcblkh = 1U << pCodeStreamInfo->m_default_tile_info.tccp_info[0].cblkh;







|







194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

    {
        opj_codestream_info_v2_t* pCodeStreamInfo = opj_get_cstr_info(l_codec);
        if (ptilew) {
            *ptilew = pCodeStreamInfo->tdx;
        }
        if (ptileh) {
            *ptileh = pCodeStreamInfo->tdy;
        }
        //int numResolutions = pCodeStreamInfo->m_default_tile_info.tccp_info[0].numresolutions;
        if (pcblkw) {
            *pcblkw = 1U << pCodeStreamInfo->m_default_tile_info.tccp_info[0].cblkw;
        }
        if (pcblkh) {
            *pcblkh = 1U << pCodeStreamInfo->m_default_tile_info.tccp_info[0].cblkh;
Changes to jni/openjpeg/thirdparty/include/zlib.h.
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
  deflate data.  The header type is detected automatically, if requested when
  initializing with inflateInit2().  Any information contained in the gzip
  header is not retained, so applications that need that information should
  instead use raw inflate, see inflateInit2() below, or inflateBack() and
  perform their own processing of the gzip header and trailer.  When processing
  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
  producted so far.  The CRC-32 is checked against the gzip trailer.

    inflate() returns Z_OK if some progress has been made (more input processed
  or more output produced), Z_STREAM_END if the end of the compressed data has
  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  corrupted (input stream not conforming to the zlib format or incorrect check
  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example







|







483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
  deflate data.  The header type is detected automatically, if requested when
  initializing with inflateInit2().  Any information contained in the gzip
  header is not retained, so applications that need that information should
  instead use raw inflate, see inflateInit2() below, or inflateBack() and
  perform their own processing of the gzip header and trailer.  When processing
  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
  produced so far.  The CRC-32 is checked against the gzip trailer.

    inflate() returns Z_OK if some progress has been made (more input processed
  or more output produced), Z_STREAM_END if the end of the compressed data has
  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  corrupted (input stream not conforming to the zlib format or incorrect check
  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
Changes to jni/openjpeg/thirdparty/libz/zlib.h.
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
  deflate data.  The header type is detected automatically, if requested when
  initializing with inflateInit2().  Any information contained in the gzip
  header is not retained, so applications that need that information should
  instead use raw inflate, see inflateInit2() below, or inflateBack() and
  perform their own processing of the gzip header and trailer.  When processing
  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
  producted so far.  The CRC-32 is checked against the gzip trailer.

    inflate() returns Z_OK if some progress has been made (more input processed
  or more output produced), Z_STREAM_END if the end of the compressed data has
  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  corrupted (input stream not conforming to the zlib format or incorrect check
  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example







|







483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
  deflate data.  The header type is detected automatically, if requested when
  initializing with inflateInit2().  Any information contained in the gzip
  header is not retained, so applications that need that information should
  instead use raw inflate, see inflateInit2() below, or inflateBack() and
  perform their own processing of the gzip header and trailer.  When processing
  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
  produced so far.  The CRC-32 is checked against the gzip trailer.

    inflate() returns Z_OK if some progress has been made (more input processed
  or more output produced), Z_STREAM_END if the end of the compressed data has
  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  corrupted (input stream not conforming to the zlib format or incorrect check
  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
Changes to jni/openjpeg/tools/ctest_scripts/travis-ci.cmake.
116
117
118
119
120
121
122



123
124
125
126
127
128
129
CMAKE_CXX_FLAGS:STRING= ${CCFLAGS_ARCH}

# Use to activate the test suite
BUILD_TESTING:BOOL=${BUILD_TESTING}

# Build Thirdparty, useful but not required for test suite
BUILD_THIRDPARTY:BOOL=TRUE




# JPEG2000 test files are available with git clone https://github.com/uclouvain/openjpeg-data.git
OPJ_DATA_ROOT:PATH=$ENV{PWD}/data

# jpylyzer is available with on GitHub: https://github.com/openpreserve/jpylyzer
JPYLYZER_EXECUTABLE=$ENV{PWD}/jpylyzer/jpylyzer.${JPYLYZER_EXT}








>
>
>







116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
CMAKE_CXX_FLAGS:STRING= ${CCFLAGS_ARCH}

# Use to activate the test suite
BUILD_TESTING:BOOL=${BUILD_TESTING}

# Build Thirdparty, useful but not required for test suite
BUILD_THIRDPARTY:BOOL=TRUE

# Build unit tests that test subcomponents of libopenjp2 (e.g. DWT)
BUILD_UNIT_TESTS:BOOL=TRUE

# JPEG2000 test files are available with git clone https://github.com/uclouvain/openjpeg-data.git
OPJ_DATA_ROOT:PATH=$ENV{PWD}/data

# jpylyzer is available with on GitHub: https://github.com/openpreserve/jpylyzer
JPYLYZER_EXECUTABLE=$ENV{PWD}/jpylyzer/jpylyzer.${JPYLYZER_EXT}

Changes to jni/openjpeg/tools/travis-ci/abi-check.sh.
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

if [ "${OPJ_CI_CXX:-}" != "" ]; then
    export CXX=${OPJ_CI_CXX}
    echo "Using ${CXX}"
fi

OPJ_UPLOAD_ABI_REPORT=0
#OPJ_PREVIOUS_VERSION="2.2.0"
OPJ_LATEST_VERSION="2.3.0"
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	OPJ_LIMIT_ABI_BUILDS="-limit 3"
else
	OPJ_LIMIT_ABI_BUILDS="-limit 2"
fi
OPJ_REPO="https://github.com/uclouvain/openjpeg.git"
OPJ_SSH_REPO=${OPJ_REPO/https:\/\/github.com\//git@github.com:}







|
|







20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

if [ "${OPJ_CI_CXX:-}" != "" ]; then
    export CXX=${OPJ_CI_CXX}
    echo "Using ${CXX}"
fi

OPJ_UPLOAD_ABI_REPORT=0
#OPJ_PREVIOUS_VERSION="2.3.0"
OPJ_LATEST_VERSION="2.3.1"
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	OPJ_LIMIT_ABI_BUILDS="-limit 3"
else
	OPJ_LIMIT_ABI_BUILDS="-limit 2"
fi
OPJ_REPO="https://github.com/uclouvain/openjpeg.git"
OPJ_SSH_REPO=${OPJ_REPO/https:\/\/github.com\//git@github.com:}
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
	cp -f ${OPJ_SOURCE_DIR}/tools/abi-tracker/openjpeg.json ./openjpeg.json
else
	# Old versions of openjpeg don't like -fvisibility=hidden...
	grep -v Configure ${OPJ_SOURCE_DIR}/tools/abi-tracker/openjpeg.json > ./openjpeg.json
fi
cp -rf ${OPJ_SOURCE_DIR} src/openjpeg/current
abi-monitor -v current -build openjpeg.json






abi-monitor -v ${OPJ_LATEST_VERSION} -build openjpeg.json
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	abi-monitor -v ${OPJ_PREVIOUS_VERSION} -build openjpeg.json
fi
abi-tracker -build openjpeg.json

EXIT_CODE=0

# Check API
abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/current -name '*.dump') -header openjpeg.h -api -s || EXIT_CODE=1
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_PREVIOUS_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -header openjpeg.h -api -s || EXIT_CODE=1
fi

# Check ABI
if [ "${OPJ_LIMIT_ABI_BUILDS}" != "" ]; then
	abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/current -name '*.dump') -header openjpeg.h -abi -s || EXIT_CODE=1



	if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
		abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_PREVIOUS_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -header openjpeg.h -abi -s || EXIT_CODE=1
	fi
else
	echo "Disable ABI check for now, problems with symbol visibility..."
fi








>
>
>
>
>
>

















>
>
>







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
	cp -f ${OPJ_SOURCE_DIR}/tools/abi-tracker/openjpeg.json ./openjpeg.json
else
	# Old versions of openjpeg don't like -fvisibility=hidden...
	grep -v Configure ${OPJ_SOURCE_DIR}/tools/abi-tracker/openjpeg.json > ./openjpeg.json
fi
cp -rf ${OPJ_SOURCE_DIR} src/openjpeg/current
abi-monitor -v current -build openjpeg.json

rm -rf ./installed/openjpeg/${OPJ_LATEST_VERSION}
rm -rf ./compat_report/openjpeg/${OPJ_LATEST_VERSION}
rm -rf ./abi_dump/openjpeg/${OPJ_LATEST_VERSION}
rm -rf ./headers_diff/openjpeg/${OPJ_LATEST_VERSION}
rm -rf ./objects_report/openjpeg/${OPJ_LATEST_VERSION}
abi-monitor -v ${OPJ_LATEST_VERSION} -build openjpeg.json
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	abi-monitor -v ${OPJ_PREVIOUS_VERSION} -build openjpeg.json
fi
abi-tracker -build openjpeg.json

EXIT_CODE=0

# Check API
abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/current -name '*.dump') -header openjpeg.h -api -s || EXIT_CODE=1
if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
	abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_PREVIOUS_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -header openjpeg.h -api -s || EXIT_CODE=1
fi

# Check ABI
if [ "${OPJ_LIMIT_ABI_BUILDS}" != "" ]; then
	abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/current -name '*.dump') -header openjpeg.h -abi -s || EXIT_CODE=1
        if [ ${EXIT_CODE} -eq 1 ]; then
            cat "compat_reports/openjpeg/${OPJ_LATEST_VERSION}_to_current/abi_compat_report.html"
        fi
	if [ "${OPJ_PREVIOUS_VERSION:-}" != "" ]; then
		abi-compliance-checker -l openjpeg -old $(find ./abi_dump/openjpeg/$OPJ_PREVIOUS_VERSION -name '*.dump') -new $(find ./abi_dump/openjpeg/$OPJ_LATEST_VERSION -name '*.dump') -header openjpeg.h -abi -s || EXIT_CODE=1
	fi
else
	echo "Disable ABI check for now, problems with symbol visibility..."
fi

Changes to jni/openjpeg/tools/travis-ci/knownfailures-Ubuntu14.04-gcc4.8.4-i386-Release-3rdP.txt.
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
NR-DEC-issue559-eci-090-CIELab.jp2-255-decode-md5
NR-DEC-issue559-eci-091-CIELab.jp2-256-decode-md5
NR-DEC-kodak_2layers_lrcp.j2c-31-decode-md5
NR-DEC-kodak_2layers_lrcp.j2c-32-decode-md5
NR-DEC-issue135.j2k-68-decode-md5
NR-DEC-db11217111510058.jp2-306-decode-md5
NR-DEC-tnsot_zero.jp2-307-decode-md5
NR-ENC-X_4_2K_24_185_CBR_WB_000.tif-15-compare_dec-ref-out2base
NR-ENC-X_5_2K_24_235_CBR_STEM24_000.tif-16-compare_dec-ref-out2base
NR-ENC-X_6_2K_24_FULL_CBR_CIRCLE_000.tif-17-compare_dec-ref-out2base
NR-ENC-X_4_2K_24_185_CBR_WB_000.tif-18-compare_dec-ref-out2base
NR-ENC-X_5_2K_24_235_CBR_STEM24_000.tif-19-compare_dec-ref-out2base
NR-ENC-X_6_2K_24_FULL_CBR_CIRCLE_000.tif-20-compare_dec-ref-out2base
NR-ENC-ElephantDream_4K.tif-21-compare_dec-ref-out2base
NR-ENC-issue141.rawl-23-compare_dec-ref-out2base







<
<
<
<
<
<
<
<
42
43
44
45
46
47
48








NR-DEC-issue559-eci-090-CIELab.jp2-255-decode-md5
NR-DEC-issue559-eci-091-CIELab.jp2-256-decode-md5
NR-DEC-kodak_2layers_lrcp.j2c-31-decode-md5
NR-DEC-kodak_2layers_lrcp.j2c-32-decode-md5
NR-DEC-issue135.j2k-68-decode-md5
NR-DEC-db11217111510058.jp2-306-decode-md5
NR-DEC-tnsot_zero.jp2-307-decode-md5








Changes to jni/openjpeg/wrapping/java/openjp2/CMakeLists.txt.
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

install(TARGETS openjpegjni
  EXPORT OpenJPEGTargets
  LIBRARY DESTINATION ${OPENJPEG_INSTALL_JNI_DIR} COMPONENT Libraries
)

# build jar:
find_package(Java 1.5 REQUIRED) # javac, jar

# build dep list:
file(GLOB java_srcs "java-sources/org/openJpeg/*.java")

# make sure target javac dir exists:
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/classes)
# Build java







|







40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

install(TARGETS openjpegjni
  EXPORT OpenJPEGTargets
  LIBRARY DESTINATION ${OPENJPEG_INSTALL_JNI_DIR} COMPONENT Libraries
)

# build jar:
find_package(Java 1.6 REQUIRED) # javac, jar

# build dep list:
file(GLOB java_srcs "java-sources/org/openJpeg/*.java")

# make sure target javac dir exists:
file(MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/classes)
# Build java