Merge pull request #125 from Team-LJY/features/archive-preview
압축파일 미리보기를 추가한다
- 작성자
- LeeJunyoung
- 작성 시각
- 커밋
ecad460b2d3eba5c039fd557c174062fd7edd02c
변경된 파일 78개
+2,550-18변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1,24 @@ | ||
| 1 | 추가: # JPEG 스캔 완전성 패치 | |
| 2 | 추가: | |
| 3 | 추가: 미리보기 작업자는 `experiments/rust-archive-worker/vendor/zune-jpeg`의 `zipelo-jpeg 0.5.15`를 사용한다. 순수 Rust인 zune-jpeg 0.5.15의 MIT 조건을 선택한 로컬 패치이며, PNG와 통신 계약은 변경하지 않는다. | |
| 4 | 추가: | |
| 5 | 추가: 원본은 crates.io의 [zune-jpeg 0.5.15](https://crates.io/crates/zune-jpeg/0.5.15)이다. 원본 crate의 SHA-256은 `27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296`이다. `LICENSE-MIT` 원문과 소스의 저작권 고지를 보존했다. 패키지 이름을 구분하고 미리보기 작업자만 이 패치를 사용한다. 앱의 기존 이미지 의존성은 유지한다. | |
| 6 | 추가: | |
| 7 | 추가: ## 수정 이유와 범위 | |
| 8 | 추가: | |
| 9 | 추가: 원본은 strict 모드에서도 스캔 종료 마커 뒤에 비트를 보충한다. 헤더에 해당하는 앞 623바이트와 EOI만 있는 시험 JPEG도 이 보충 비트로 픽셀을 만들고 성공한다. 출력 버퍼 길이나 초기값 검사로는 실제 그림 데이터와 보충 데이터를 구분할 수 없다. | |
| 10 | 추가: | |
| 11 | 추가: - `bitstream.rs`는 실제 엔트로피 비트 수를 별도로 집계한다. Huffman 조회의 미리 읽기는 허용하고 실제 소비가 입력 비트를 넘을 때 오류를 기록한다. 보충 비트는 입력량으로 세지 않는다. | |
| 12 | 추가: - `mcu.rs`와 `mcu_prog.rs`는 MCU 행, progressive MCU 및 재시작 경계에서 오류를 확인한다. baseline의 직접 출력 경로는 기록한 픽셀 바이트 수도 확인한다. | |
| 13 | 추가: - 작업자의 `preview.rs`는 모든 색상 성분의 최초 DC 스캔을 요구하고, baseline에서 중복되거나 불완전한 성분 스캔을 거부한다. 원본과 결과 크기 상한, 암호, 자원 승인과 취소 정책은 유지한다. | |
| 14 | 추가: - Cargo manifest를 프로젝트 경로 의존성으로 바꿨고 사용하지 않는 upstream 시험 모듈과 주석 처리된 시험, 잘못된 crate 단위 `macro_use` 속성과 주석의 이모지를 제외했다. upstream 시험 코드는 복사하지 않았다. 회귀 시험과 새 표본은 루트 `tests/rust-archive-worker/`에만 둔다. | |
| 15 | 추가: | |
| 16 | 추가: `packaging/licenses.py`는 프로젝트 경로 패키지에 명시된 라이선스 원문을 해당 패키지 내부에서 읽으며, 경로 이탈과 라이선스 파일의 심볼릭 링크를 거부한다. 배포 고지에는 `zipelo-jpeg`의 upstream MIT 원문이 포함된다. 새 registry 버전이나 네이티브 라이브러리는 추가하지 않는다. | |
| 17 | 추가: | |
| 18 | 추가: ## 검증과 유지 | |
| 19 | 추가: | |
| 20 | 추가: 기존 baseline 표본의 앞 623바이트와 EOI, 이미지 높이만 늘린 불완전한 스캔, 각 progressive 스캔의 데이터 누락, 여러 MCU 행과 재시작 마커를 시험한다. PNG는 완전한 IEND와 올바른 CRC가 있지만 픽셀 행이 부족한 입력도 손상으로 거부해야 한다. 실제 ZIP 작업자는 오류 시 Begin/Chunk/End를 전송하지 않아야 한다. | |
| 21 | 추가: | |
| 22 | 추가: 여러 행의 JPEG 표본 5개는 시험용 RGB 그라데이션을 baseline, progressive, 회색조, CMYK와 재시작 마커 형식으로 직접 생성했다. upstream 버전을 바꾸거나 패치를 제거할 때 이 회귀와 `python3 tests/ci/run_rust.py local`, 라이선스 시험을 다시 실행한다. 동일한 스캔 완전성 보장이 확인된 upstream 릴리스가 있으면 경로 의존성을 제거할 수 있다. | |
| 23 | 추가: | |
| 24 | 추가: 로컬 패키지 이름은 `zipelo-jpeg`이므로 보안 권고를 확인할 때 원본 이름인 `zune-jpeg 0.5.15`도 대조해야 한다. 패치는 엔트로피 완전성만 보강하며 다른 upstream 결함이나 향후 권고의 부재를 보장하지 않는다. |
| @@ -147,3 +147,24 @@ Windows NSIS 제거 프로그램은 앱과 별도의 실행 파일입니다. 이 | ||
| 147 | 147 | 실제 검증은 전용 Windows VM에서 설치와 기본 앱 지정 후 Uninstall.exe를 실행합니다. 설정에서 ZIP의 다른 기본 앱을 선택하고 제거한 뒤 ZIP을 열어야 합니다. 설정을 열지 않고 제거한 경우의 [연결 프로그램] 경로, 취소 시 앱 유지, /S 무인 제거의 창 생략, 사용자가 바꾼 등록 값 보존도 확인합니다. NSIS 컴파일 시험은 이 운영체제 화면 검증을 대신하지 않습니다. |
| 148 | 148 | |
| 149 | 149 | Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전 기본 앱이 있는 경우, 삭제된 경우, 기록이 없는 경우, 설치 후 다른 앱으로 바꾼 경우와 다른 사용자의 제거를 구분해 확인합니다. 사용자 홈 전체나 MIME 설정 파일 전체를 초기화하지 않습니다. |
| 150 | 추가: | |
| 151 | 추가: ### 파일 미리보기 | |
| 152 | 추가: | |
| 153 | 추가: - preview-catalog-bytes-approval: 전체 목록 크기가 16 GiB를 넘는 압축파일에서 7바이트 텍스트를 미리볼 때 새 승인을 요청. 미리보기 고유 상한은 유지. | |
| 154 | 추가: - preview-catalog-approval: 10,001개 목록에서 파일 하나를 미리볼 때 목록 전체 처리 예산의 새 승인을 요청. 텍스트 1 MiB와 이미지 8 MiB 고유 상한은 유지. | |
| 155 | 추가: - preview-loading: 미리보기 로딩 중 [취소] 또는 Esc로 닫기. 닫힌 결과는 늦게 도착해도 표시하지 않음. | |
| 156 | 추가: - preview-text: UTF-8 텍스트의 읽기 전용 표시와 스크롤. | |
| 157 | 추가: - preview-image: 디코딩된 정적 이미지의 화면 맞춤 표시. | |
| 158 | 추가: - preview-empty: 빈 텍스트 파일 안내. | |
| 159 | 추가: - preview-limit: 크기 또는 처리 한도 초과 안내. 미리보기 상한을 늘리는 버튼은 제공하지 않음. | |
| 160 | 추가: - preview-damaged: 손상 또는 잘못된 UTF-8 안내. | |
| 161 | 추가: - preview-unsupported: 지원하지 않는 형식 안내. | |
| 162 | 추가: - preview-implicit-folder: 디렉터리 항목 없이 파일 하나만 포함한 가상 폴더 선택 시 [미리보기] 비활성화. 폴더 안에서 파일을 선택하면 활성화. | |
| 163 | 추가: - preview-selection: 폴더 또는 여러 항목 선택 시 [미리보기] 비활성화. | |
| 164 | 추가: | |
| 165 | 추가: `--ui-scenario` 화면은 기존 규칙대로 입력을 받지 않는 디자인 점검용이다. | |
| 166 | 추가: 키보드 상호작용은 `--ui-fixture /absolute/example.zip` 또는 실제 압축파일로 확인한다. | |
| 167 | 추가: 파일을 고르고 Tab으로 [미리보기]에 이동해 Enter로 열며, 닫기 버튼 또는 Esc로 닫는다. | |
| 168 | 추가: 실제 압축파일에서는 파일 하나를 선택하고 [미리보기]를 직접 눌렀을 때만 읽기를 시작한다. | |
| 169 | 추가: 닫은 뒤 선택, 폴더 위치와 스크롤을 유지하고 실행 전 키보드 포커스로 돌아간다. | |
| 170 | 추가: 시나리오의 텍스트와 이미지는 화면 점검용이며 디코더 검증은 실제 압축파일로 별도 수행한다. |
| @@ -2,6 +2,12 @@ | ||
| 2 | 2 | # It is not intended for manual editing. |
| 3 | 3 | version = 4 |
| 4 | 4 | |
| 5 | 추가: [[package]] | |
| 6 | 추가: name = "adler2" | |
| 7 | 추가: version = "2.0.1" | |
| 8 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 9 | 추가: checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" | |
| 10 | 추가: | |
| 5 | 11 | [[package]] |
| 6 | 12 | name = "aes" |
| 7 | 13 | version = "0.8.4" |
| @@ -14,6 +20,12 @@ dependencies = [ | ||
| 14 | 20 | "zeroize", |
| 15 | 21 | ] |
| 16 | 22 | |
| 23 | 추가: [[package]] | |
| 24 | 추가: name = "bitflags" | |
| 25 | 추가: version = "2.13.2" | |
| 26 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 27 | 추가: checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" | |
| 28 | 추가: | |
| 17 | 29 | [[package]] |
| 18 | 30 | name = "block-buffer" |
| 19 | 31 | version = "0.10.4" |
| @@ -81,6 +93,15 @@ dependencies = [ | ||
| 81 | 93 | "libc", |
| 82 | 94 | ] |
| 83 | 95 | |
| 96 | 추가: [[package]] | |
| 97 | 추가: name = "crc32fast" | |
| 98 | 추가: version = "1.5.5" | |
| 99 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 100 | 추가: checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64" | |
| 101 | 추가: dependencies = [ | |
| 102 | 추가: "cfg-if", | |
| 103 | 추가: ] | |
| 104 | 추가: | |
| 84 | 105 | [[package]] |
| 85 | 106 | name = "crypto-common" |
| 86 | 107 | version = "0.1.7" |
| @@ -122,6 +143,26 @@ dependencies = [ | ||
| 122 | 143 | "crypto-common 0.2.2", |
| 123 | 144 | ] |
| 124 | 145 | |
| 146 | 추가: [[package]] | |
| 147 | 추가: name = "fdeflate" | |
| 148 | 추가: version = "0.3.7" | |
| 149 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 150 | 추가: checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" | |
| 151 | 추가: dependencies = [ | |
| 152 | 추가: "simd-adler32", | |
| 153 | 추가: ] | |
| 154 | 추가: | |
| 155 | 추가: [[package]] | |
| 156 | 추가: name = "flate2" | |
| 157 | 추가: version = "1.1.11" | |
| 158 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 159 | 추가: checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" | |
| 160 | 추가: dependencies = [ | |
| 161 | 추가: "crc32fast", | |
| 162 | 추가: "miniz_oxide 0.9.1", | |
| 163 | 추가: "zlib-rs", | |
| 164 | 추가: ] | |
| 165 | 추가: | |
| 125 | 166 | [[package]] |
| 126 | 167 | name = "generic-array" |
| 127 | 168 | version = "0.14.7" |
| @@ -180,6 +221,26 @@ dependencies = [ | ||
| 180 | 221 | "sha2 0.11.1", |
| 181 | 222 | ] |
| 182 | 223 | |
| 224 | 추가: [[package]] | |
| 225 | 추가: name = "miniz_oxide" | |
| 226 | 추가: version = "0.8.9" | |
| 227 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 228 | 추가: checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" | |
| 229 | 추가: dependencies = [ | |
| 230 | 추가: "adler2", | |
| 231 | 추가: "simd-adler32", | |
| 232 | 추가: ] | |
| 233 | 추가: | |
| 234 | 추가: [[package]] | |
| 235 | 추가: name = "miniz_oxide" | |
| 236 | 추가: version = "0.9.1" | |
| 237 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 238 | 추가: checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" | |
| 239 | 추가: dependencies = [ | |
| 240 | 추가: "adler2", | |
| 241 | 추가: "simd-adler32", | |
| 242 | 추가: ] | |
| 243 | 추가: | |
| 183 | 244 | [[package]] |
| 184 | 245 | name = "pbkdf2" |
| 185 | 246 | version = "0.12.2" |
| @@ -190,6 +251,19 @@ dependencies = [ | ||
| 190 | 251 | "hmac", |
| 191 | 252 | ] |
| 192 | 253 | |
| 254 | 추가: [[package]] | |
| 255 | 추가: name = "png" | |
| 256 | 추가: version = "0.18.1" | |
| 257 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 258 | 추가: checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" | |
| 259 | 추가: dependencies = [ | |
| 260 | 추가: "bitflags", | |
| 261 | 추가: "crc32fast", | |
| 262 | 추가: "fdeflate", | |
| 263 | 추가: "flate2", | |
| 264 | 추가: "miniz_oxide 0.8.9", | |
| 265 | 추가: ] | |
| 266 | 추가: | |
| 193 | 267 | [[package]] |
| 194 | 268 | name = "sha1" |
| 195 | 269 | version = "0.10.7" |
| @@ -223,6 +297,12 @@ dependencies = [ | ||
| 223 | 297 | "digest 0.11.3", |
| 224 | 298 | ] |
| 225 | 299 | |
| 300 | 추가: [[package]] | |
| 301 | 추가: name = "simd-adler32" | |
| 302 | 추가: version = "0.3.10" | |
| 303 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 304 | 추가: checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" | |
| 305 | 추가: | |
| 226 | 306 | [[package]] |
| 227 | 307 | name = "subtle" |
| 228 | 308 | version = "2.6.1" |
| @@ -256,11 +336,21 @@ dependencies = [ | ||
| 256 | 336 | "hmac", |
| 257 | 337 | "lzma-rust2", |
| 258 | 338 | "pbkdf2", |
| 339 | 추가: "png", | |
| 259 | 340 | "sha1", |
| 260 | 341 | "sha2 0.10.9", |
| 261 | 342 | "subtle", |
| 262 | 343 | "zeroize", |
| 344 | 추가: "zipelo-jpeg", | |
| 263 | 345 | "zlib-rs", |
| 346 | 추가: "zune-core", | |
| 347 | 추가: ] | |
| 348 | 추가: | |
| 349 | 추가: [[package]] | |
| 350 | 추가: name = "zipelo-jpeg" | |
| 351 | 추가: version = "0.5.15" | |
| 352 | 추가: dependencies = [ | |
| 353 | 추가: "zune-core", | |
| 264 | 354 | ] |
| 265 | 355 | |
| 266 | 356 | [[package]] |
| @@ -268,3 +358,9 @@ name = "zlib-rs" | ||
| 268 | 358 | version = "0.6.8" |
| 269 | 359 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 270 | 360 | checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" |
| 361 | 추가: | |
| 362 | 추가: [[package]] | |
| 363 | 추가: name = "zune-core" | |
| 364 | 추가: version = "0.5.3" | |
| 365 | 추가: source = "registry+https://github.com/rust-lang/crates.io-index" | |
| 366 | 추가: checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" |
| @@ -7,6 +7,9 @@ publish = false | ||
| 7 | 7 | autotests = false |
| 8 | 8 | |
| 9 | 9 | [dependencies] |
| 10 | 추가: png = "=0.18.1" | |
| 11 | 추가: zune-jpeg = { package = "zipelo-jpeg", path = "vendor/zune-jpeg", default-features = false, features = ["std"] } | |
| 12 | 추가: zune-core = { version = "=0.5.3", default-features = false, features = ["std"] } | |
| 10 | 13 | bzip2 = "=0.6.1" |
| 11 | 14 | lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] } |
| 12 | 15 | aes = { version = "=0.8.4", features = ["zeroize"] } |
| @@ -19,6 +22,7 @@ sha2 = "=0.10.9" | ||
| 19 | 22 | zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] } |
| 20 | 23 | |
| 21 | 24 | [workspace] |
| 25 | 추가: exclude = ["vendor/zune-jpeg"] | |
| 22 | 26 | |
| 23 | 27 | [[test]] |
| 24 | 28 | name = "archive_worker" |
| @@ -129,3 +129,49 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2 | ||
| 129 | 129 | 직접 의존성은 기존 zlib-rs=0.6.8와 허용된 RustCrypto sha2=0.10.9입니다. 2026-11-11에 확인한 [zlib-rs RUSTSEC-2024-0401](https://rustsec.org/advisories/RUSTSEC-2024-0401.html)은 >=0.4.0, [sha2 RUSTSEC-2021-0100](https://rustsec.org/advisories/RUSTSEC-2021-0100.html)은 >=0.9.8을 수정 버전으로 명시합니다. 선택 버전은 이 수정 범위에 들어갑니다. 이는 전체 전이 의존성의 취약점 부재나 완전한 보안 감사를 의미하지 않습니다. |
| 130 | 130 | |
| 131 | 131 | 암호 구현에 RustCrypto aes=0.8.4(zeroize 기능), hmac=0.12.1, pbkdf2=0.12.2, sha1=0.10.7, zeroize=1.9.1과 상수 시간 비교용 subtle=2.6.1을 추가했습니다. SHA-1은 ZIP 호환용 HMAC/KDF에만 사용합니다. 고정 버전과 전이 의존성은 Cargo.lock에 있습니다. 로컬 RustSec DB(1645308, 2026-10-23)의 해당 패키지 기록과 공개 RustSec 검색을 확인했지만 cargo-audit 명령이 없어 최신 DB 전체 자동 감사는 수행하지 못했습니다. 이 확인은 취약점 부재나 전체 보안 감사의 증거가 아닙니다. |
| 132 | 추가: | |
| 133 | 추가: ## 미리보기 계약 | |
| 134 | 추가: | |
| 135 | 추가: 상태: frontend와 backend의 계약 합의가 완료되었다. protocol.rs와 wire.rs에 공용 타입, 전송 규칙과 상한 검증을 반영했다. 작업자의 제한된 해제와 PNG/JPEG 디코더를 연결했다. 실제 압축파일을 사용하는 운영체제별 화면 검증과 독립 리뷰는 완료 전이다. 확정된 범위는 [PLANS 8.7](../../docs/PLANS.md)을 따른다. 8.8 분할 7z는 이 구현에서 제외한다. | |
| 136 | 추가: | |
| 137 | 추가: ### 요청과 수명 | |
| 138 | 추가: | |
| 139 | 추가: - 기존 프레임 헤더 버전 1과 본문 1 MiB 상한을 유지한다. Action과 ActionKind에 Preview(태그 3)를 추가하고 StartGuarded(kind 6)의 interactive=true로만 시작한다. 일반 Start와 StartInteractive에는 Preview를 허용하지 않는다. 기존 요청과 태그의 의미는 바꾸지 않으며 구버전 작업자가 거부하면 일반 해제로 자동 재시도하지 않는다. | |
| 140 | 추가: - Preview 요청은 archive NativePath, entry_id u32, 필수 list_id ListId 순서다. 목적지와 출력 파일 이름은 받지 않는다. 한 작업자 프로세스는 한 미리보기 요청만 처리하고 0이 아닌 기존 job_id로 구분한다. 앱은 별도로 단조 증가하는 화면 세대를 작업에 연결한다. | |
| 141 | 추가: - 입력 Snapshot과 ListId를 먼저 대조한다. 단일 일반 파일만 허용하고 폴더, 링크 및 유효하지 않은 항목 ID는 거부한다. 목록에서 보지 않은 입력이나 바뀐 입력의 이전 entry_id를 사용하지 않는다. | |
| 142 | 추가: - 전체 해독, solid 선행 처리, 입력 사본과 임시 공간에는 기존 기본/승인 자원 예산 및 압축률 감시를 유지한다. 확대 승인과 암호는 기존 질문/응답을 사용하고 충돌 질문과 목적지 게시는 없다. 승인 전 전체 300초, 승인 후 진행 없는 60초 및 질문 대기 제외를 유지한다. | |
| 143 | 추가: - 미리보기 고유의 텍스트/이미지 바이트와 픽셀 상한은 큰 작업 승인으로 늘어나지 않는다. 원본 검증과 필요한 압축 데이터의 무결성 검증, 선택 항목 및 디코딩 검증을 모두 마친 뒤에만 전송을 시작한다. | |
| 144 | 추가: | |
| 145 | 추가: ### 결과와 흐름 제어 | |
| 146 | 추가: | |
| 147 | 추가: 아래 정수는 기존 little-endian 부호 없는 타입을 사용하며 필드 순서를 고정한다. kind 111~113을 새 선택적 확장으로 사용하며 별도 ACK 메시지를 추가하지 않는다. 원래 초안의 64 KiB 청크 및 kind 8 PreviewAck는 철회한다. | |
| 148 | 추가: | |
| 149 | 추가: - Message::PreviewBegin(PreviewInfo)(kind 111): PreviewInfo의 필드는 entry_id u32, format PreviewFormat, total_bytes u64, width u32, height u32 순서다. PreviewFormat::Utf8Text=0, PreviewFormat::Rgba8=1을 u8로 전송한다. Utf8Text는 완전히 검증한 UTF-8 텍스트이며 width=height=0, total_bytes<=1 MiB다. 선행 UTF-8 BOM만 제거하며 항목 바이트 상한에는 BOM도 포함한다. | |
| 150 | 추가: - PreviewFormat::Rgba8은 행 우선, 왼쪽 위 시작, 채널 순서 RGBA, 알파를 미리 곱하지 않은 RGBA8 픽셀이다. width/height는 각각 1~8192, width*height<=16,000,000, total_bytes=width*height*4<=64 MiB를 만족해야 한다. 모든 곱셈과 길이 변환은 검사한다. | |
| 151 | 추가: - Message::PreviewChunk { entry_id: u32, offset: u64, data: Vec<u8> }(kind 112): 직렬화 순서는 entry_id u32, offset u64, data_len u32, data 원시 바이트다. data_len은 1~32,768이며 offset은 0부터 직전 청크 끝과 정확히 이어져야 한다. 부가 필드를 포함한 본문은 1 MiB보다 작다. 빈 텍스트는 Begin과 End만 보낸다. 텍스트의 UTF-8 문자는 청크 경계에서 나뉠 수 있으므로 전체 재조립 후 문자열로 만든다. | |
| 152 | 추가: - 흐름 제어는 기존 크기 64 수신 큐와 파이프의 역압을 사용한다. 청크 payload 대기는 최대 64*32 KiB=2 MiB이며 프레임/이벤트 부가 비용과 현재 읽는 프레임은 별도다. 전송 중에도 기존 취소, 부모 종료와 시간 감시를 유지한다. | |
| 153 | 추가: - 앱 수신기는 Begin을 검증한 뒤 상한 이내에서만 재조립 공간을 준비한다. 일치하는 job_id/entry_id의 연속 청크만 복사한다. 총량 초과, 잘못된 순서, 중복 Begin/End 및 메타정보와 다른 결과는 Protocol로 중단한다. | |
| 154 | 추가: - Message::PreviewEnd { entry_id: u32, total_bytes: u64, sha256: [u8; 32] }(kind 113): 필드 순서는 entry_id, total_bytes, sha256이다. 앱은 실제 수신 길이, Begin/End 길이와 SHA256을 대조하고 UTF-8 또는 픽셀 레이아웃을 재검사한다. End만으로 표시하지 않고 기존 Terminal::Completed 및 정상 통신 종료/자식 회수를 확인한 뒤 현재 화면 세대의 결과만 표시한다. | |
| 155 | 추가: - Terminal의 publication=None, created_count=0, retained_partial_count=0, durability=NotApplicable를 유지하고 임시 정리 상태는 실제 결과대로 보고한다. 실패하거나 취소한 결과는 일부라도 표시하지 않는다. | |
| 156 | 추가: | |
| 157 | 추가: ### 버퍼와 취소 | |
| 158 | 추가: | |
| 159 | 추가: - 작업당 결과 재조립 버퍼는 텍스트 1 MiB 또는 RGBA 64 MiB 이하다. 별도 데이터 큐를 만들지 않고 기존 수신 큐의 청크 payload 최대 2 MiB를 지키며 수신 프레임의 기존 1 MiB 상한은 별도다. UI 전달 대기도 결과 한 개만 허용하고 이전 미리보기의 CPU 결과는 새 요청 전에 해제한다. 화면 렌더러와 GPU 복사 비용을 포함한 프로세스 전체 메모리 상한을 뜻하지 않는다. | |
| 160 | 추가: - 취소, 닫기와 선택 변경은 즉시 화면 세대를 무효화하고 누적 버퍼를 해제한 뒤 기존 Cancel을 보낸다. 미리보기 창을 닫아도 작업자 회수까지 수신 큐를 계속 비우며 해당 작업의 후속 Begin/Chunk/End와 늦은 완료를 모두 폐기한다. 큐를 비울 수 없어 연결을 중단할 때는 기존 종료/회수 절차를 수행하며 닫힌 화면 때문에 데이터 큐가 가득 찬 채 방치하지 않는다. | |
| 161 | 추가: - CancelAck가 TooLate 또는 Finished여도 취소한 화면의 결과는 복원하지 않는다. 다음 작업은 이전 자식을 회수한 후 새 job_id와 세대로 시작한다. 작업자 오류나 종료 지연은 기존 종료/회수 정책을 적용하고, 상한을 피하려고 사용자 폴더에 미리보기 파일을 쓰지 않는다. | |
| 162 | 추가: | |
| 163 | 추가: ### 형식과 오류 | |
| 164 | 추가: | |
| 165 | 추가: - 텍스트 확장자는 대소문자 구분 없이 .txt, .md, .log, .csv, .json이며 UTF-8 전체 검증을 통과해야 한다. 이미지 후보는 .png, .jpg, .jpeg이며 실제 PNG/JPEG 형식도 일치해야 한다. 일반 GZip은 입력 이름에서 .gz를 제거한 이름을 기준으로 하고 나머지는 카탈로그 항목 이름을 사용한다. | |
| 166 | 추가: - 선택 항목 해제 후 원본 바이트는 텍스트 1 MiB, 이미지 8 MiB 이하다. 실제 읽는 양에도 같은 상한을 적용하며 차원과 픽셀 수를 할당 전에 검사한다. APNG, 다른 애니메이션, 미지원 형식은 제외한다. 손상 입력을 복구하거나 부분 디코딩으로 성공 처리하지 않는다. | |
| 167 | 추가: - UnsupportedFormat/UnsupportedFeature는 형식/확장자 불일치와 미지원, Integrity는 잘못된 UTF-8과 손상, Limit는 바이트/픽셀 또는 공통 자원 상한을 뜻한다. SourceChanged, WrongPassword와 기존 I/O/Protocol 오류는 유지한다. 앱은 미리보기 Limit에 고유 상한 확대를 제안하지 않고 일반 해제를 별도 사용자 동작으로 안내한다. | |
| 168 | 추가: | |
| 169 | 추가: ### 디코더와 담당 | |
| 170 | 추가: | |
| 171 | 추가: - PNG는 png 0.18.1(MIT OR Apache-2.0), JPEG는 zune-jpeg 0.5.15와 zune-core 0.5.3(MIT OR Apache-2.0 OR Zlib)을 직접 사용하며 모두 MIT 조건을 선택한다. zune는 std 기능만 켜고 순수 Rust 디코더를 사용한다. strict 모드, 입력/출력 길이와 치수를 직접 제어하기 위해 공통 image 래퍼 대신 선택했다. packaging/licenses.py에서 선택한 MIT와 체크섬을 대조한 라이선스 원문을 배포 고지에 포함한다. | |
| 172 | 추가: - PNG는 모든 청크 CRC와 마지막 IEND를 검증하고 APNG를 거부한다. 텍스트와 ICC 메타데이터의 추가 해독은 끄고 16비트/팔레트/회색조를 RGBA8로 정규화한다. JPEG는 헤더와 스캔 경계를 먼저 확인해 단일 8비트 baseline/progressive 프레임만 해독한다. 회색조와 CMYK도 RGB 해독 뒤 같은 결과 버퍼에서 불투명 RGBA8로 변환한다. 산술 부호화, lossless JPEG와 MPO는 지원하지 않는다. | |
| 173 | 추가: - ZIP은 선택 항목만 해제하며 7z는 선택 항목이 속한 solid 블록 전체를 무결성 검증한다. TAR 계열과 GZip 컨테이너 해독, solid 블록 및 메타데이터에는 기존 공통 예산과 임시 공간 감시를 적용한다. 선택 항목을 결과 버퍼로 읽는 양은 텍스트/이미지 고유 상한을 넘지 않는다. PNG 입력 읽기, 변환 행과 결과 청크마다 취소를 확인한다. JPEG 라이브러리 호출은 전후에 취소를 확인하고 기존 자식 종료/회수 정책을 유지한다. | |
| 174 | 추가: - 2026-11-14 공개 RustSec DB의 crates 트리 86148de9e400d7460a03b8089d1de31af2d1e6c3에서 추가 의존성 10종 이름의 권고 기록이 없는 것을 확인했다. 이 확인은 전체 잠금 파일의 자동 감사나 취약점 부재를 보장하지 않는다. | |
| 175 | 추가: - PNG의 제한된 Decoder와 행/프레임 API는 [공식 문서](https://docs.rs/png/0.18.1/png/)를 참고한다. 라이브러리 내부 할당 제한을 작업자 전체 RSS의 강제 상한으로 표현하지 않는다. 엄격한 항목 길이, 치수와 결과 길이 검사를 별도로 적용한다. | |
| 176 | 추가: - backend는 작업자 protocol.rs, wire.rs, runtime 및 디코더, 작업자 시험과 packaging/licenses.py 고지를 맡는다. frontend는 앱 재조립/전송 제어, 화면과 앱 시험, --ui-scenario 및 가이드를 맡는다. 같은 원격 브랜치는 양쪽 결과를 확인하며 순차 갱신하고 공용 타입 변경은 이 계약 합의 후 backend가 반영한다. | |
| 177 | 추가: - 시험은 바이트/치수/픽셀 경계, UTF-8 청크 경계와 BOM, 형식 불일치/APNG/손상, 암호와 solid 예산, malformed/순서/중복/초과 전송, 64개 큐 역압과 디코딩 및 전송 중 취소, 늦은 완료 폐기와 정리 및 원본 해시 보존을 포함한다. |
| @@ -6,6 +6,7 @@ mod crypto; | ||
| 6 | 6 | pub mod filesystem; |
| 7 | 7 | mod lzma; |
| 8 | 8 | mod parent; |
| 9 | 추가: mod preview; | |
| 9 | 10 | pub mod protocol; |
| 10 | 11 | pub mod resources; |
| 11 | 12 | pub mod runtime; |
| @@ -0,0 +1,399 @@ | ||
| 1 | 추가: use crate::{protocol::*, resources::Monitor}; | |
| 2 | 추가: use std::io::{self, BufRead, Cursor, Read, Seek, SeekFrom}; | |
| 3 | 추가: use zlib_rs::crc32::crc32; | |
| 4 | 추가: use zune_core::{bytestream::ZCursor, colorspace::ColorSpace, options::DecoderOptions}; | |
| 5 | 추가: | |
| 6 | 추가: type Result<T> = std::result::Result<T, ErrorCode>; | |
| 7 | 추가: | |
| 8 | 추가: #[derive(Clone, Copy)] | |
| 9 | 추가: pub(crate) enum Kind { | |
| 10 | 추가: Text, | |
| 11 | 추가: Png, | |
| 12 | 추가: Jpeg, | |
| 13 | 추가: } | |
| 14 | 추가: impl Kind { | |
| 15 | 추가: pub fn from_name(name: &str) -> Result<Self> { | |
| 16 | 추가: match name | |
| 17 | 추가: .rsplit_once('.') | |
| 18 | 추가: .map(|(_, ext)| ext.to_ascii_lowercase()) | |
| 19 | 추가: .as_deref() | |
| 20 | 추가: { | |
| 21 | 추가: Some("txt" | "md" | "log" | "csv" | "json") => Ok(Self::Text), | |
| 22 | 추가: Some("png") => Ok(Self::Png), | |
| 23 | 추가: Some("jpg" | "jpeg") => Ok(Self::Jpeg), | |
| 24 | 추가: _ => Err(ErrorCode::UnsupportedFeature), | |
| 25 | 추가: } | |
| 26 | 추가: } | |
| 27 | 추가: pub fn limit(self) -> u64 { | |
| 28 | 추가: match self { | |
| 29 | 추가: Self::Text => MAX_PREVIEW_TEXT_BYTES, | |
| 30 | 추가: Self::Png | Self::Jpeg => MAX_PREVIEW_IMAGE_BYTES, | |
| 31 | 추가: } | |
| 32 | 추가: } | |
| 33 | 추가: } | |
| 34 | 추가: fn rgba_info(entry_id: u32, width: u32, height: u32) -> Result<PreviewInfo> { | |
| 35 | 추가: if width == 0 || height == 0 { | |
| 36 | 추가: return Err(ErrorCode::Integrity); | |
| 37 | 추가: } | |
| 38 | 추가: let total_bytes = u64::from(width) | |
| 39 | 추가: .checked_mul(u64::from(height)) | |
| 40 | 추가: .and_then(|n| n.checked_mul(4)) | |
| 41 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 42 | 추가: let info = PreviewInfo { | |
| 43 | 추가: entry_id, | |
| 44 | 추가: format: PreviewFormat::Rgba8, | |
| 45 | 추가: total_bytes, | |
| 46 | 추가: width, | |
| 47 | 추가: height, | |
| 48 | 추가: }; | |
| 49 | 추가: if !info.valid() { | |
| 50 | 추가: return Err(ErrorCode::Limit); | |
| 51 | 추가: } | |
| 52 | 추가: Ok(info) | |
| 53 | 추가: } | |
| 54 | 추가: fn buffer(length: usize) -> Result<Vec<u8>> { | |
| 55 | 추가: let mut bytes = Vec::new(); | |
| 56 | 추가: bytes | |
| 57 | 추가: .try_reserve_exact(length) | |
| 58 | 추가: .map_err(|_| ErrorCode::Limit)?; | |
| 59 | 추가: bytes.resize(length, 0); | |
| 60 | 추가: Ok(bytes) | |
| 61 | 추가: } | |
| 62 | 추가: pub(crate) fn decode( | |
| 63 | 추가: kind: Kind, | |
| 64 | 추가: entry_id: u32, | |
| 65 | 추가: mut source: Vec<u8>, | |
| 66 | 추가: check: &mut impl Monitor, | |
| 67 | 추가: ) -> Result<(PreviewInfo, Vec<u8>)> { | |
| 68 | 추가: check.check()?; | |
| 69 | 추가: if source.len() as u64 > kind.limit() { | |
| 70 | 추가: return Err(ErrorCode::Limit); | |
| 71 | 추가: } | |
| 72 | 추가: let result = match kind { | |
| 73 | 추가: Kind::Text => { | |
| 74 | 추가: std::str::from_utf8(&source).map_err(|_| ErrorCode::Integrity)?; | |
| 75 | 추가: if source.starts_with(&[0xef, 0xbb, 0xbf]) { | |
| 76 | 추가: source.drain(..3); | |
| 77 | 추가: } | |
| 78 | 추가: Ok(( | |
| 79 | 추가: PreviewInfo { | |
| 80 | 추가: entry_id, | |
| 81 | 추가: format: PreviewFormat::Utf8Text, | |
| 82 | 추가: total_bytes: source.len() as u64, | |
| 83 | 추가: width: 0, | |
| 84 | 추가: height: 0, | |
| 85 | 추가: }, | |
| 86 | 추가: source, | |
| 87 | 추가: )) | |
| 88 | 추가: } | |
| 89 | 추가: Kind::Png => png(entry_id, &source, check), | |
| 90 | 추가: Kind::Jpeg => jpeg(entry_id, &source, check), | |
| 91 | 추가: }; | |
| 92 | 추가: check.activity()?; | |
| 93 | 추가: result | |
| 94 | 추가: } | |
| 95 | 추가: struct Input<'a, M> { | |
| 96 | 추가: bytes: Cursor<&'a [u8]>, | |
| 97 | 추가: check: &'a mut M, | |
| 98 | 추가: } | |
| 99 | 추가: impl<M: Monitor> Read for Input<'_, M> { | |
| 100 | 추가: fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> { | |
| 101 | 추가: self.check | |
| 102 | 추가: .check() | |
| 103 | 추가: .map_err(|_| io::Error::other("preview interrupted"))?; | |
| 104 | 추가: let length = self.bytes.read(bytes)?; | |
| 105 | 추가: if length != 0 { | |
| 106 | 추가: self.check | |
| 107 | 추가: .activity() | |
| 108 | 추가: .map_err(|_| io::Error::other("preview interrupted"))?; | |
| 109 | 추가: } | |
| 110 | 추가: Ok(length) | |
| 111 | 추가: } | |
| 112 | 추가: } | |
| 113 | 추가: impl<M: Monitor> BufRead for Input<'_, M> { | |
| 114 | 추가: fn fill_buf(&mut self) -> io::Result<&[u8]> { | |
| 115 | 추가: self.check | |
| 116 | 추가: .check() | |
| 117 | 추가: .map_err(|_| io::Error::other("preview interrupted"))?; | |
| 118 | 추가: self.bytes.fill_buf() | |
| 119 | 추가: } | |
| 120 | 추가: fn consume(&mut self, length: usize) { | |
| 121 | 추가: self.bytes.consume(length); | |
| 122 | 추가: } | |
| 123 | 추가: } | |
| 124 | 추가: impl<M: Monitor> Seek for Input<'_, M> { | |
| 125 | 추가: fn seek(&mut self, position: SeekFrom) -> io::Result<u64> { | |
| 126 | 추가: self.check | |
| 127 | 추가: .check() | |
| 128 | 추가: .map_err(|_| io::Error::other("preview interrupted"))?; | |
| 129 | 추가: self.bytes.seek(position) | |
| 130 | 추가: } | |
| 131 | 추가: } | |
| 132 | 추가: fn png(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> { | |
| 133 | 추가: if !source.starts_with(b"\x89PNG\r\n\x1a\n") { | |
| 134 | 추가: return Err(ErrorCode::UnsupportedFormat); | |
| 135 | 추가: } | |
| 136 | 추가: let mut at = 8usize; | |
| 137 | 추가: let mut ended = false; | |
| 138 | 추가: while at < source.len() { | |
| 139 | 추가: check.check()?; | |
| 140 | 추가: let header = source.get(at..at + 8).ok_or(ErrorCode::Integrity)?; | |
| 141 | 추가: let length = u32::from_be_bytes(header[..4].try_into().unwrap()) as usize; | |
| 142 | 추가: let end = at | |
| 143 | 추가: .checked_add(12) | |
| 144 | 추가: .and_then(|n| n.checked_add(length)) | |
| 145 | 추가: .filter(|n| *n <= source.len()) | |
| 146 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 147 | 추가: if crc32(0, &source[at + 4..end - 4]) | |
| 148 | 추가: != u32::from_be_bytes(source[end - 4..end].try_into().unwrap()) | |
| 149 | 추가: { | |
| 150 | 추가: return Err(ErrorCode::Integrity); | |
| 151 | 추가: } | |
| 152 | 추가: if at == 8 && (&header[4..] != b"IHDR" || length != 13) { | |
| 153 | 추가: return Err(ErrorCode::Integrity); | |
| 154 | 추가: } | |
| 155 | 추가: if matches!(&header[4..], b"acTL" | b"fcTL" | b"fdAT") { | |
| 156 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 157 | 추가: } | |
| 158 | 추가: if &header[4..] == b"IEND" { | |
| 159 | 추가: if length != 0 || end != source.len() { | |
| 160 | 추가: return Err(ErrorCode::Integrity); | |
| 161 | 추가: } | |
| 162 | 추가: ended = true; | |
| 163 | 추가: } | |
| 164 | 추가: at = end; | |
| 165 | 추가: check.activity()?; | |
| 166 | 추가: } | |
| 167 | 추가: if !ended { | |
| 168 | 추가: return Err(ErrorCode::Integrity); | |
| 169 | 추가: } | |
| 170 | 추가: let mut decoder = png::Decoder::new_with_limits( | |
| 171 | 추가: Input { | |
| 172 | 추가: bytes: Cursor::new(source), | |
| 173 | 추가: check, | |
| 174 | 추가: }, | |
| 175 | 추가: png::Limits { | |
| 176 | 추가: bytes: 128 * 1024 * 1024, | |
| 177 | 추가: }, | |
| 178 | 추가: ); | |
| 179 | 추가: decoder.set_ignore_text_chunk(true); | |
| 180 | 추가: decoder.set_ignore_iccp_chunk(true); | |
| 181 | 추가: decoder.set_transformations(png::Transformations::EXPAND | png::Transformations::STRIP_16); | |
| 182 | 추가: let header = decoder | |
| 183 | 추가: .read_header_info() | |
| 184 | 추가: .map_err(|_| ErrorCode::Integrity)?; | |
| 185 | 추가: let info = rgba_info(entry_id, header.width, header.height)?; | |
| 186 | 추가: let mut reader = decoder.read_info().map_err(|_| ErrorCode::Integrity)?; | |
| 187 | 추가: let length = reader | |
| 188 | 추가: .output_buffer_size() | |
| 189 | 추가: .filter(|n| *n as u64 <= info.total_bytes) | |
| 190 | 추가: .ok_or(ErrorCode::Limit)?; | |
| 191 | 추가: let mut raw = buffer(length)?; | |
| 192 | 추가: let decoded = reader | |
| 193 | 추가: .next_frame(&mut raw) | |
| 194 | 추가: .map_err(|_| ErrorCode::Integrity)?; | |
| 195 | 추가: reader.finish().map_err(|_| ErrorCode::Integrity)?; | |
| 196 | 추가: drop(reader); | |
| 197 | 추가: check.activity()?; | |
| 198 | 추가: if decoded.width != info.width | |
| 199 | 추가: || decoded.height != info.height | |
| 200 | 추가: || decoded.bit_depth != png::BitDepth::Eight | |
| 201 | 추가: { | |
| 202 | 추가: return Err(ErrorCode::Integrity); | |
| 203 | 추가: } | |
| 204 | 추가: raw.truncate(decoded.buffer_size()); | |
| 205 | 추가: let channels = match decoded.color_type { | |
| 206 | 추가: png::ColorType::Grayscale => 1, | |
| 207 | 추가: png::ColorType::GrayscaleAlpha => 2, | |
| 208 | 추가: png::ColorType::Rgb => 3, | |
| 209 | 추가: png::ColorType::Rgba => 4, | |
| 210 | 추가: _ => return Err(ErrorCode::UnsupportedFeature), | |
| 211 | 추가: }; | |
| 212 | 추가: if raw.len() != info.width as usize * info.height as usize * channels { | |
| 213 | 추가: return Err(ErrorCode::Integrity); | |
| 214 | 추가: } | |
| 215 | 추가: if channels == 4 { | |
| 216 | 추가: return Ok((info, raw)); | |
| 217 | 추가: } | |
| 218 | 추가: let mut rgba = buffer(info.total_bytes as usize)?; | |
| 219 | 추가: for (source, target) in raw | |
| 220 | 추가: .chunks_exact(info.width as usize * channels) | |
| 221 | 추가: .zip(rgba.chunks_exact_mut(info.width as usize * 4)) | |
| 222 | 추가: { | |
| 223 | 추가: check.activity()?; | |
| 224 | 추가: for (pixel, out) in source | |
| 225 | 추가: .chunks_exact(channels) | |
| 226 | 추가: .zip(target.chunks_exact_mut(4)) | |
| 227 | 추가: { | |
| 228 | 추가: match channels { | |
| 229 | 추가: 1 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], 255]), | |
| 230 | 추가: 2 => out.copy_from_slice(&[pixel[0], pixel[0], pixel[0], pixel[1]]), | |
| 231 | 추가: 3 => out.copy_from_slice(&[pixel[0], pixel[1], pixel[2], 255]), | |
| 232 | 추가: _ => unreachable!(), | |
| 233 | 추가: } | |
| 234 | 추가: } | |
| 235 | 추가: } | |
| 236 | 추가: Ok((info, rgba)) | |
| 237 | 추가: } | |
| 238 | 추가: fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<PreviewInfo> { | |
| 239 | 추가: let mut at = 2usize; | |
| 240 | 추가: let mut scanning = false; | |
| 241 | 추가: let mut info = None; | |
| 242 | 추가: let mut seen_scan = false; | |
| 243 | 추가: let mut components = Vec::new(); | |
| 244 | 추가: let mut decoded_components = 0u8; | |
| 245 | 추가: let mut progressive = false; | |
| 246 | 추가: while at < source.len() { | |
| 247 | 추가: check.check()?; | |
| 248 | 추가: if scanning { | |
| 249 | 추가: at += source[at..] | |
| 250 | 추가: .iter() | |
| 251 | 추가: .position(|byte| *byte == 0xff) | |
| 252 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 253 | 추가: } | |
| 254 | 추가: if source[at] != 0xff { | |
| 255 | 추가: return Err(ErrorCode::Integrity); | |
| 256 | 추가: } | |
| 257 | 추가: while source.get(at) == Some(&0xff) { | |
| 258 | 추가: at += 1; | |
| 259 | 추가: } | |
| 260 | 추가: let marker = *source.get(at).ok_or(ErrorCode::Integrity)?; | |
| 261 | 추가: at += 1; | |
| 262 | 추가: match marker { | |
| 263 | 추가: 0 | 0xd0..=0xd7 if scanning => continue, | |
| 264 | 추가: 0xd9 if at == source.len() && seen_scan => { | |
| 265 | 추가: if decoded_components != (1 << components.len()) - 1 { | |
| 266 | 추가: return Err(ErrorCode::Integrity); | |
| 267 | 추가: } | |
| 268 | 추가: return info.ok_or(ErrorCode::Integrity); | |
| 269 | 추가: } | |
| 270 | 추가: 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity), | |
| 271 | 추가: 1 => continue, | |
| 272 | 추가: _ => {} | |
| 273 | 추가: } | |
| 274 | 추가: let length = source.get(at..at + 2).ok_or(ErrorCode::Integrity)?; | |
| 275 | 추가: let length = u16::from_be_bytes(length.try_into().unwrap()) as usize; | |
| 276 | 추가: let end = at | |
| 277 | 추가: .checked_add(length) | |
| 278 | 추가: .filter(|n| length >= 2 && *n <= source.len()) | |
| 279 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 280 | 추가: let body = &source[at + 2..end]; | |
| 281 | 추가: if matches!(marker, 0xc0..=0xcf) && !matches!(marker, 0xc4 | 0xc8 | 0xcc) { | |
| 282 | 추가: if info.is_some() || body.len() < 6 { | |
| 283 | 추가: return Err(ErrorCode::Integrity); | |
| 284 | 추가: } | |
| 285 | 추가: if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 { | |
| 286 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 287 | 추가: } | |
| 288 | 추가: progressive = marker == 0xc2; | |
| 289 | 추가: let count = usize::from(body[5]); | |
| 290 | 추가: if !(1..=4).contains(&count) || body.len() != 6 + count * 3 { | |
| 291 | 추가: return Err(ErrorCode::Integrity); | |
| 292 | 추가: } | |
| 293 | 추가: for component in body[6..].chunks_exact(3) { | |
| 294 | 추가: if components.contains(&component[0]) { | |
| 295 | 추가: return Err(ErrorCode::Integrity); | |
| 296 | 추가: } | |
| 297 | 추가: components.push(component[0]); | |
| 298 | 추가: } | |
| 299 | 추가: info = Some(rgba_info( | |
| 300 | 추가: entry_id, | |
| 301 | 추가: u32::from(u16::from_be_bytes(body[3..5].try_into().unwrap())), | |
| 302 | 추가: u32::from(u16::from_be_bytes(body[1..3].try_into().unwrap())), | |
| 303 | 추가: )?); | |
| 304 | 추가: } | |
| 305 | 추가: if marker == 0xe2 && body.starts_with(b"MPF\0") { | |
| 306 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 307 | 추가: } | |
| 308 | 추가: scanning = marker == 0xda; | |
| 309 | 추가: if scanning { | |
| 310 | 추가: let count = usize::from(*body.first().ok_or(ErrorCode::Integrity)?); | |
| 311 | 추가: if info.is_none() | |
| 312 | 추가: || count == 0 | |
| 313 | 추가: || count > components.len() | |
| 314 | 추가: || body.len() != 4 + count * 2 | |
| 315 | 추가: { | |
| 316 | 추가: return Err(ErrorCode::Integrity); | |
| 317 | 추가: } | |
| 318 | 추가: let mut scan_components = 0u8; | |
| 319 | 추가: for component in body[1..1 + count * 2].chunks_exact(2) { | |
| 320 | 추가: let index = components | |
| 321 | 추가: .iter() | |
| 322 | 추가: .position(|id| *id == component[0]) | |
| 323 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 324 | 추가: let bit = 1 << index; | |
| 325 | 추가: if scan_components & bit != 0 { | |
| 326 | 추가: return Err(ErrorCode::Integrity); | |
| 327 | 추가: } | |
| 328 | 추가: scan_components |= bit; | |
| 329 | 추가: } | |
| 330 | 추가: if !progressive | |
| 331 | 추가: && (scan_components & decoded_components != 0 | |
| 332 | 추가: || body[1 + count * 2..] != [0, 63, 0]) | |
| 333 | 추가: { | |
| 334 | 추가: return Err(ErrorCode::Integrity); | |
| 335 | 추가: } | |
| 336 | 추가: // 모든 색상 성분의 최초 DC 스캔이 있어야 완전한 그림으로 처리함. | |
| 337 | 추가: if body[1 + count * 2] == 0 && body[3 + count * 2] >> 4 == 0 { | |
| 338 | 추가: decoded_components |= scan_components; | |
| 339 | 추가: } | |
| 340 | 추가: } | |
| 341 | 추가: seen_scan |= scanning; | |
| 342 | 추가: at = end; | |
| 343 | 추가: check.activity()?; | |
| 344 | 추가: } | |
| 345 | 추가: Err(ErrorCode::Integrity) | |
| 346 | 추가: } | |
| 347 | 추가: fn jpeg_error(error: zune_jpeg::errors::DecodeErrors) -> ErrorCode { | |
| 348 | 추가: match error { | |
| 349 | 추가: zune_jpeg::errors::DecodeErrors::LargeDimensions(_) => ErrorCode::Limit, | |
| 350 | 추가: zune_jpeg::errors::DecodeErrors::Unsupported(_) => ErrorCode::UnsupportedFeature, | |
| 351 | 추가: _ => ErrorCode::Integrity, | |
| 352 | 추가: } | |
| 353 | 추가: } | |
| 354 | 추가: fn jpeg(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<(PreviewInfo, Vec<u8>)> { | |
| 355 | 추가: if !source.starts_with(&[0xff, 0xd8]) { | |
| 356 | 추가: return Err(ErrorCode::UnsupportedFormat); | |
| 357 | 추가: } | |
| 358 | 추가: if !source.ends_with(&[0xff, 0xd9]) { | |
| 359 | 추가: return Err(ErrorCode::Integrity); | |
| 360 | 추가: } | |
| 361 | 추가: let expected = jpeg_info(entry_id, source, check)?; | |
| 362 | 추가: let options = DecoderOptions::new_safe() | |
| 363 | 추가: .set_strict_mode(true) | |
| 364 | 추가: .set_max_width(MAX_PREVIEW_DIMENSION as usize) | |
| 365 | 추가: .set_max_height(MAX_PREVIEW_DIMENSION as usize) | |
| 366 | 추가: .jpeg_set_max_scans(100) | |
| 367 | 추가: .jpeg_set_out_colorspace(ColorSpace::RGB); | |
| 368 | 추가: let mut decoder = zune_jpeg::JpegDecoder::new_with_options(ZCursor::new(source), options); | |
| 369 | 추가: decoder.decode_headers().map_err(jpeg_error)?; | |
| 370 | 추가: let header = decoder.info().ok_or(ErrorCode::Integrity)?; | |
| 371 | 추가: let info = rgba_info(entry_id, u32::from(header.width), u32::from(header.height))?; | |
| 372 | 추가: let rgb_bytes = (info.total_bytes / 4 * 3) as usize; | |
| 373 | 추가: if info != expected || decoder.output_buffer_size() != Some(rgb_bytes) { | |
| 374 | 추가: return Err(ErrorCode::Integrity); | |
| 375 | 추가: } | |
| 376 | 추가: let mut rgba = buffer(info.total_bytes as usize)?; | |
| 377 | 추가: decoder | |
| 378 | 추가: .decode_into(&mut rgba[..rgb_bytes]) | |
| 379 | 추가: .map_err(jpeg_error)?; | |
| 380 | 추가: // CMYK의 RGBA 경로를 피하고 같은 버퍼 안에서 불투명 알파를 채움. | |
| 381 | 추가: for row in (0..info.height as usize).rev() { | |
| 382 | 추가: check.activity()?; | |
| 383 | 추가: for column in (0..info.width as usize).rev() { | |
| 384 | 추가: let pixel = row * info.width as usize + column; | |
| 385 | 추가: let rgb = [ | |
| 386 | 추가: rgba[pixel * 3], | |
| 387 | 추가: rgba[pixel * 3 + 1], | |
| 388 | 추가: rgba[pixel * 3 + 2], | |
| 389 | 추가: 255, | |
| 390 | 추가: ]; | |
| 391 | 추가: rgba[pixel * 4..pixel * 4 + 4].copy_from_slice(&rgb); | |
| 392 | 추가: } | |
| 393 | 추가: } | |
| 394 | 추가: Ok((info, rgba)) | |
| 395 | 추가: } | |
| 396 | 추가: | |
| 397 | 추가: #[cfg(test)] | |
| 398 | 추가: #[path = "../../../tests/rust-archive-worker/preview_decode.rs"] | |
| 399 | 추가: mod tests; |
| @@ -1,5 +1,12 @@ | ||
| 1 | 1 | use std::path::{Path, PathBuf}; |
| 2 | 2 | |
| 3 | 추가: pub const MAX_PREVIEW_TEXT_BYTES: u64 = 1024 * 1024; | |
| 4 | 추가: pub const MAX_PREVIEW_IMAGE_BYTES: u64 = 8 * 1024 * 1024; | |
| 5 | 추가: pub const MAX_PREVIEW_RGBA_BYTES: u64 = 64 * 1024 * 1024; | |
| 6 | 추가: pub const MAX_PREVIEW_DIMENSION: u32 = 8192; | |
| 7 | 추가: pub const MAX_PREVIEW_PIXELS: u64 = 16_000_000; | |
| 8 | 추가: pub const MAX_PREVIEW_CHUNK_BYTES: usize = 32 * 1024; | |
| 9 | 추가: | |
| 3 | 10 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 4 | 11 | pub enum NativePath { |
| 5 | 12 | Unix(Vec<u8>), |
| @@ -96,7 +103,12 @@ impl GuardedStart { | ||
| 96 | 103 | && self.ceiling.output <= 64 * 1024 * 1024 * 1024 |
| 97 | 104 | && self.ceiling.entries >= self.start.limits.entries |
| 98 | 105 | && self.ceiling.entries <= 200_000 |
| 99 | 삭제: && (!self.interactive || matches!(self.start.action, Action::Extract { .. })) | |
| 106 | 추가: && (!self.interactive | |
| 107 | 추가: || matches!( | |
| 108 | 추가: self.start.action, | |
| 109 | 추가: Action::Extract { .. } | Action::Preview { .. } | |
| 110 | 추가: )) | |
| 111 | 추가: && (!matches!(self.start.action, Action::Preview { .. }) || self.interactive) | |
| 100 | 112 | } |
| 101 | 113 | } |
| 102 | 114 | #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] |
| @@ -185,12 +197,18 @@ pub enum Action { | ||
| 185 | 197 | method: Method, |
| 186 | 198 | encryption: Encryption, |
| 187 | 199 | }, |
| 200 | 추가: Preview { | |
| 201 | 추가: archive: NativePath, | |
| 202 | 추가: entry_id: u32, | |
| 203 | 추가: list_id: ListId, | |
| 204 | 추가: }, | |
| 188 | 205 | } |
| 189 | 206 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 190 | 207 | pub enum ActionKind { |
| 191 | 208 | List, |
| 192 | 209 | Extract, |
| 193 | 210 | CreateZip, |
| 211 | 추가: Preview, | |
| 194 | 212 | } |
| 195 | 213 | impl Action { |
| 196 | 214 | pub fn kind(&self) -> ActionKind { |
| @@ -198,6 +216,7 @@ impl Action { | ||
| 198 | 216 | Self::List { .. } => ActionKind::List, |
| 199 | 217 | Self::Extract { .. } => ActionKind::Extract, |
| 200 | 218 | Self::CreateZip { .. } => ActionKind::CreateZip, |
| 219 | 추가: Self::Preview { .. } => ActionKind::Preview, | |
| 201 | 220 | } |
| 202 | 221 | } |
| 203 | 222 | } |
| @@ -223,6 +242,39 @@ pub struct Entry { | ||
| 223 | 242 | pub encrypted: bool, |
| 224 | 243 | } |
| 225 | 244 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 245 | 추가: pub enum PreviewFormat { | |
| 246 | 추가: Utf8Text, | |
| 247 | 추가: Rgba8, | |
| 248 | 추가: } | |
| 249 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 250 | 추가: pub struct PreviewInfo { | |
| 251 | 추가: pub entry_id: u32, | |
| 252 | 추가: pub format: PreviewFormat, | |
| 253 | 추가: pub total_bytes: u64, | |
| 254 | 추가: pub width: u32, | |
| 255 | 추가: pub height: u32, | |
| 256 | 추가: } | |
| 257 | 추가: impl PreviewInfo { | |
| 258 | 추가: pub fn valid(&self) -> bool { | |
| 259 | 추가: match self.format { | |
| 260 | 추가: PreviewFormat::Utf8Text => { | |
| 261 | 추가: self.width == 0 && self.height == 0 && self.total_bytes <= MAX_PREVIEW_TEXT_BYTES | |
| 262 | 추가: } | |
| 263 | 추가: PreviewFormat::Rgba8 => { | |
| 264 | 추가: if !(1..=MAX_PREVIEW_DIMENSION).contains(&self.width) | |
| 265 | 추가: || !(1..=MAX_PREVIEW_DIMENSION).contains(&self.height) | |
| 266 | 추가: { | |
| 267 | 추가: return false; | |
| 268 | 추가: } | |
| 269 | 추가: let pixels = u64::from(self.width) * u64::from(self.height); | |
| 270 | 추가: pixels <= MAX_PREVIEW_PIXELS | |
| 271 | 추가: && pixels.checked_mul(4) == Some(self.total_bytes) | |
| 272 | 추가: && self.total_bytes <= MAX_PREVIEW_RGBA_BYTES | |
| 273 | 추가: } | |
| 274 | 추가: } | |
| 275 | 추가: } | |
| 276 | 추가: } | |
| 277 | 추가: #[derive(Clone, Copy, Debug, PartialEq, Eq)] | |
| 226 | 278 | pub enum Stage { |
| 227 | 279 | Scan, |
| 228 | 280 | Read, |
| @@ -374,6 +426,17 @@ pub enum Message { | ||
| 374 | 426 | relative_name: String, |
| 375 | 427 | disposition: Disposition, |
| 376 | 428 | }, |
| 429 | 추가: PreviewBegin(PreviewInfo), | |
| 430 | 추가: PreviewChunk { | |
| 431 | 추가: entry_id: u32, | |
| 432 | 추가: offset: u64, | |
| 433 | 추가: data: Vec<u8>, | |
| 434 | 추가: }, | |
| 435 | 추가: PreviewEnd { | |
| 436 | 추가: entry_id: u32, | |
| 437 | 추가: total_bytes: u64, | |
| 438 | 추가: sha256: [u8; 32], | |
| 439 | 추가: }, | |
| 377 | 440 | Terminal(Terminal), |
| 378 | 441 | CancelAck { |
| 379 | 442 | request_sequence: u64, |
| @@ -352,6 +352,140 @@ impl<W: Write> Job<W> { | ||
| 352 | 352 | } |
| 353 | 353 | Ok(()) |
| 354 | 354 | } |
| 355 | 추가: fn preview( | |
| 356 | 추가: &mut self, | |
| 357 | 추가: archive: NativePath, | |
| 358 | 추가: entry_id: u32, | |
| 359 | 추가: expected: ListId, | |
| 360 | 추가: limits: Limits, | |
| 361 | 추가: ) -> Result<()> { | |
| 362 | 추가: use sha2::{Digest, Sha256}; | |
| 363 | 추가: use std::io::{Read, Seek, SeekFrom}; | |
| 364 | 추가: let path = archive.to_path()?; | |
| 365 | 추가: self.progress(Stage::Read, 0, None, 0)?; | |
| 366 | 추가: let mut snapshot = | |
| 367 | 추가: crate::spool::Snapshot::open_reporting(&path, limits.input, &mut |step| match step { | |
| 368 | 추가: crate::spool::Step::Check => self.check(), | |
| 369 | 추가: crate::spool::Step::Activity => completed(Ok(()), self), | |
| 370 | 추가: crate::spool::Step::Read { bytes, total } => { | |
| 371 | 추가: self.progress(Stage::Read, bytes, Some(total), 0) | |
| 372 | 추가: } | |
| 373 | 추가: })?; | |
| 374 | 추가: if expected.catalog_version != 1 | |
| 375 | 추가: || expected.source_object != snapshot.object | |
| 376 | 추가: || expected.archive_bytes != snapshot.len | |
| 377 | 추가: || expected.archive_sha256 != snapshot.hash | |
| 378 | 추가: { | |
| 379 | 추가: return Err(ErrorCode::SourceChanged); | |
| 380 | 추가: } | |
| 381 | 추가: let mut catalog = crate::streaming::Catalog::open( | |
| 382 | 추가: &mut snapshot.file, | |
| 383 | 추가: snapshot.len, | |
| 384 | 추가: limits, | |
| 385 | 추가: false, | |
| 386 | 추가: None, | |
| 387 | 추가: self, | |
| 388 | 추가: )?; | |
| 389 | 추가: if expected.format != catalog.format { | |
| 390 | 추가: return Err(ErrorCode::SourceChanged); | |
| 391 | 추가: } | |
| 392 | 추가: let entry = catalog | |
| 393 | 추가: .members | |
| 394 | 추가: .get(entry_id as usize) | |
| 395 | 추가: .ok_or(ErrorCode::InvalidRequest)? | |
| 396 | 추가: .entry | |
| 397 | 추가: .clone(); | |
| 398 | 추가: if entry.entry_id != entry_id || entry.kind != EntryKind::File { | |
| 399 | 추가: return Err(ErrorCode::InvalidRequest); | |
| 400 | 추가: } | |
| 401 | 추가: let name = if catalog.format == Format::Gzip { | |
| 402 | 추가: let name = path | |
| 403 | 추가: .file_name() | |
| 404 | 추가: .and_then(|s| s.to_str()) | |
| 405 | 추가: .ok_or(ErrorCode::UnsupportedFeature)?; | |
| 406 | 추가: if !name.to_ascii_lowercase().ends_with(".gz") { | |
| 407 | 추가: return Err(ErrorCode::UnsupportedFeature); | |
| 408 | 추가: } | |
| 409 | 추가: &name[..name.len() - 3] | |
| 410 | 추가: } else { | |
| 411 | 추가: &entry.name | |
| 412 | 추가: }; | |
| 413 | 추가: let kind = crate::preview::Kind::from_name(name)?; | |
| 414 | 추가: if entry.size > kind.limit() { | |
| 415 | 추가: return Err(ErrorCode::Limit); | |
| 416 | 추가: } | |
| 417 | 추가: self.progress(Stage::Decode, 0, Some(entry.size), 0)?; | |
| 418 | 추가: if matches!(catalog.format, Format::Zip | Format::SevenZip) { | |
| 419 | 추가: for attempt in 1..=3 { | |
| 420 | 추가: let secret = if entry.encrypted { | |
| 421 | 추가: Some(self.password(PasswordPurpose::Decrypt, attempt)?) | |
| 422 | 추가: } else { | |
| 423 | 추가: None | |
| 424 | 추가: }; | |
| 425 | 추가: match crate::streaming::Catalog::preview( | |
| 426 | 추가: &mut snapshot.file, | |
| 427 | 추가: snapshot.len, | |
| 428 | 추가: limits, | |
| 429 | 추가: secret.as_ref().map(|s| s.0.as_slice()), | |
| 430 | 추가: entry_id, | |
| 431 | 추가: self, | |
| 432 | 추가: ) { | |
| 433 | 추가: Ok(decoded) => { | |
| 434 | 추가: catalog = decoded; | |
| 435 | 추가: break; | |
| 436 | 추가: } | |
| 437 | 추가: Err(ErrorCode::WrongPassword) if entry.encrypted && attempt < 3 => continue, | |
| 438 | 추가: Err(error) => return Err(error), | |
| 439 | 추가: } | |
| 440 | 추가: } | |
| 441 | 추가: } | |
| 442 | 추가: let mut bytes = Vec::new(); | |
| 443 | 추가: bytes | |
| 444 | 추가: .try_reserve_exact(entry.size as usize) | |
| 445 | 추가: .map_err(|_| ErrorCode::Limit)?; | |
| 446 | 추가: catalog | |
| 447 | 추가: .data | |
| 448 | 추가: .seek(SeekFrom::Start(catalog.offsets[entry_id as usize])) | |
| 449 | 추가: .map_err(crate::space::io_error)?; | |
| 450 | 추가: let mut remaining = entry.size; | |
| 451 | 추가: let mut chunk = [0; 32768]; | |
| 452 | 추가: while remaining != 0 { | |
| 453 | 추가: self.check()?; | |
| 454 | 추가: let length = remaining.min(chunk.len() as u64) as usize; | |
| 455 | 추가: catalog | |
| 456 | 추가: .data | |
| 457 | 추가: .read_exact(&mut chunk[..length]) | |
| 458 | 추가: .map_err(|_| ErrorCode::Integrity)?; | |
| 459 | 추가: bytes.extend_from_slice(&chunk[..length]); | |
| 460 | 추가: remaining -= length as u64; | |
| 461 | 추가: completed(Ok(()), self)?; | |
| 462 | 추가: } | |
| 463 | 추가: let (info, bytes) = crate::preview::decode(kind, entry_id, bytes, self)?; | |
| 464 | 추가: self.check()?; | |
| 465 | 추가: let hash: [u8; 32] = Sha256::digest(&bytes).into(); | |
| 466 | 추가: completed(self.event(Message::PreviewBegin(info)), self)?; | |
| 467 | 추가: for (index, chunk) in bytes.chunks(MAX_PREVIEW_CHUNK_BYTES).enumerate() { | |
| 468 | 추가: self.check()?; | |
| 469 | 추가: completed( | |
| 470 | 추가: self.event(Message::PreviewChunk { | |
| 471 | 추가: entry_id, | |
| 472 | 추가: offset: (index * MAX_PREVIEW_CHUNK_BYTES) as u64, | |
| 473 | 추가: data: chunk.to_vec(), | |
| 474 | 추가: }), | |
| 475 | 추가: self, | |
| 476 | 추가: )?; | |
| 477 | 추가: } | |
| 478 | 추가: self.check()?; | |
| 479 | 추가: completed( | |
| 480 | 추가: self.event(Message::PreviewEnd { | |
| 481 | 추가: entry_id, | |
| 482 | 추가: total_bytes: info.total_bytes, | |
| 483 | 추가: sha256: hash, | |
| 484 | 추가: }), | |
| 485 | 추가: self, | |
| 486 | 추가: )?; | |
| 487 | 추가: Ok(()) | |
| 488 | 추가: } | |
| 355 | 489 | fn run(&mut self, start: Start) -> Result<()> { |
| 356 | 490 | if !start.limits.valid() { |
| 357 | 491 | return Err(ErrorCode::InvalidRequest); |
| @@ -649,6 +783,13 @@ impl<W: Write> Job<W> { | ||
| 649 | 783 | } |
| 650 | 784 | } |
| 651 | 785 | } |
| 786 | 추가: Action::Preview { | |
| 787 | 추가: archive, | |
| 788 | 추가: entry_id, | |
| 789 | 추가: list_id, | |
| 790 | 추가: } => { | |
| 791 | 추가: self.preview(archive, entry_id, list_id, limits)?; | |
| 792 | 추가: } | |
| 652 | 793 | Action::CreateZip { |
| 653 | 794 | sources, |
| 654 | 795 | output_file, |
| @@ -306,18 +306,28 @@ impl Streams { | ||
| 306 | 306 | input: &mut std::fs::File, |
| 307 | 307 | ranges: &[(u64, u64)], |
| 308 | 308 | output: &mut std::fs::File, |
| 309 | 추가: selected: Option<usize>, | |
| 309 | 310 | check: &mut impl crate::resources::Monitor, |
| 310 | 311 | ) -> Result<()> { |
| 311 | 312 | use std::io::{Read, Seek, SeekFrom, Write}; |
| 312 | 삭제: let total = self.folders.iter().try_fold(0u64, |sum, f| { | |
| 313 | 삭제: crate::resources::completed( | |
| 314 | 삭제: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit), | |
| 315 | 삭제: check, | |
| 316 | 삭제: ) | |
| 317 | 삭제: })?; | |
| 313 | 추가: let total = self | |
| 314 | 추가: .folders | |
| 315 | 추가: .iter() | |
| 316 | 추가: .enumerate() | |
| 317 | 추가: .filter(|(index, _)| selected.is_none_or(|id| id == *index)) | |
| 318 | 추가: .try_fold(0u64, |sum, (_, f)| { | |
| 319 | 추가: crate::resources::completed( | |
| 320 | 추가: sum.checked_add(f.size as u64).ok_or(ErrorCode::Limit), | |
| 321 | 추가: check, | |
| 322 | 추가: ) | |
| 323 | 추가: })?; | |
| 318 | 324 | crate::space::ensure(output, total)?; |
| 319 | 삭제: for (f, (start, size)) in self.folders.iter().zip(ranges) { | |
| 325 | 추가: for (index, (f, (start, size))) in self.folders.iter().zip(ranges).enumerate() { | |
| 320 | 326 | check.check()?; |
| 327 | 추가: if selected.is_some_and(|id| id != index) { | |
| 328 | 추가: crate::resources::completed(Ok(()), check)?; | |
| 329 | 추가: continue; | |
| 330 | 추가: } | |
| 321 | 331 | let base = output.stream_position().map_err(crate::space::io_error)?; |
| 322 | 332 | check.observe( |
| 323 | 333 | ResourceUsage { |
| @@ -584,6 +594,16 @@ pub(crate) fn open( | ||
| 584 | 594 | limits: Limits, |
| 585 | 595 | decode: bool, |
| 586 | 596 | check: &mut impl crate::resources::Monitor, |
| 597 | 추가: ) -> Result<crate::streaming::Catalog> { | |
| 598 | 추가: open_selected(input, length, limits, decode, None, check) | |
| 599 | 추가: } | |
| 600 | 추가: pub(crate) fn open_selected( | |
| 601 | 추가: input: &mut std::fs::File, | |
| 602 | 추가: length: u64, | |
| 603 | 추가: limits: Limits, | |
| 604 | 추가: decode: bool, | |
| 605 | 추가: selected: Option<u32>, | |
| 606 | 추가: check: &mut impl crate::resources::Monitor, | |
| 587 | 607 | ) -> Result<crate::streaming::Catalog> { |
| 588 | 608 | use std::io::{Read, Seek, SeekFrom}; |
| 589 | 609 | check.check()?; |
| @@ -652,6 +672,7 @@ pub(crate) fn open( | ||
| 652 | 672 | input, |
| 653 | 673 | &ranges, |
| 654 | 674 | &mut data, |
| 675 | 추가: None, | |
| 655 | 676 | &mut crate::resources::MetadataMonitor(check), |
| 656 | 677 | )?; |
| 657 | 678 | data_end = 32u64 |
| @@ -725,9 +746,15 @@ pub(crate) fn open( | ||
| 725 | 746 | let ranges = streams.ranges(input, data_end, check)?; |
| 726 | 747 | let mut at = 0u64; |
| 727 | 748 | let mut ids = stream_indices.into_iter(); |
| 728 | 삭제: for f in &streams.folders { | |
| 749 | 추가: let mut selected_folder = None; | |
| 750 | 추가: for (folder, f) in streams.folders.iter().enumerate() { | |
| 751 | 추가: let base = at; | |
| 729 | 752 | for size in &f.sizes { |
| 730 | 삭제: offsets[ids.next().ok_or(ErrorCode::Integrity)?] = at; | |
| 753 | 추가: let id = ids.next().ok_or(ErrorCode::Integrity)?; | |
| 754 | 추가: offsets[id] = if selected.is_some() { at - base } else { at }; | |
| 755 | 추가: if selected == Some(id as u32) { | |
| 756 | 추가: selected_folder = Some(folder); | |
| 757 | 추가: } | |
| 731 | 758 | at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?; |
| 732 | 759 | crate::resources::completed(Ok(()), check)?; |
| 733 | 760 | } |
| @@ -735,8 +762,8 @@ pub(crate) fn open( | ||
| 735 | 762 | if at > limits.output { |
| 736 | 763 | return Err(ErrorCode::Limit); |
| 737 | 764 | } |
| 738 | 삭제: if decode { | |
| 739 | 삭제: streams.decode_file(input, &ranges, &mut data, check)?; | |
| 765 | 추가: if decode && (selected.is_none() || selected_folder.is_some()) { | |
| 766 | 추가: streams.decode_file(input, &ranges, &mut data, selected_folder, check)?; | |
| 740 | 767 | } |
| 741 | 768 | } |
| 742 | 769 | Ok(crate::streaming::Catalog { |
| @@ -53,18 +53,39 @@ impl Catalog { | ||
| 53 | 53 | decode: bool, |
| 54 | 54 | password: Option<&[u8]>, |
| 55 | 55 | check: &mut impl crate::resources::Monitor, |
| 56 | 추가: ) -> Result<Self> { | |
| 57 | 추가: Self::open_selected(source, len, limits, decode, password, None, check) | |
| 58 | 추가: } | |
| 59 | 추가: pub fn preview( | |
| 60 | 추가: source: &mut File, | |
| 61 | 추가: len: u64, | |
| 62 | 추가: limits: Limits, | |
| 63 | 추가: password: Option<&[u8]>, | |
| 64 | 추가: entry_id: u32, | |
| 65 | 추가: check: &mut impl crate::resources::Monitor, | |
| 66 | 추가: ) -> Result<Self> { | |
| 67 | 추가: Self::open_selected(source, len, limits, true, password, Some(entry_id), check) | |
| 68 | 추가: } | |
| 69 | 추가: fn open_selected( | |
| 70 | 추가: source: &mut File, | |
| 71 | 추가: len: u64, | |
| 72 | 추가: limits: Limits, | |
| 73 | 추가: decode: bool, | |
| 74 | 추가: password: Option<&[u8]>, | |
| 75 | 추가: selected: Option<u32>, | |
| 76 | 추가: check: &mut impl crate::resources::Monitor, | |
| 56 | 77 | ) -> Result<Self> { |
| 57 | 78 | let mut magic = [0; 6]; |
| 58 | 79 | let n = len.min(6) as usize; |
| 59 | 80 | at(source, 0, &mut magic[..n])?; |
| 60 | 81 | if magic.starts_with(b"7z\xbc\xaf\x27\x1c") { |
| 61 | 삭제: return crate::seven_zip::open(source, len, limits, decode, check); | |
| 82 | 추가: return crate::seven_zip::open_selected(source, len, limits, decode, selected, check); | |
| 62 | 83 | } |
| 63 | 84 | if magic.starts_with(b"PK\x03\x04") |
| 64 | 85 | || magic.starts_with(b"PK\x05\x06") |
| 65 | 86 | || magic.starts_with(b"PK\x06\x06") |
| 66 | 87 | { |
| 67 | 삭제: return zip(source, len, limits, decode, password, check); | |
| 88 | 추가: return zip(source, len, limits, decode, password, selected, check); | |
| 68 | 89 | } |
| 69 | 90 | let compression = if magic.starts_with(b"BZh") { |
| 70 | 91 | Some(crate::compressed_tar::Compression::Bzip2) |
| @@ -425,6 +446,7 @@ fn zip( | ||
| 425 | 446 | limits: Limits, |
| 426 | 447 | decode: bool, |
| 427 | 448 | password: Option<&[u8]>, |
| 449 | 추가: selected: Option<u32>, | |
| 428 | 450 | check: &mut impl crate::resources::Monitor, |
| 429 | 451 | ) -> Result<Catalog> { |
| 430 | 452 | if len < 22 { |
| @@ -712,13 +734,22 @@ fn zip( | ||
| 712 | 734 | )?; |
| 713 | 735 | let mut data = spool::temporary()?; |
| 714 | 736 | if decode { |
| 715 | 삭제: crate::space::ensure(&data, total)?; | |
| 737 | 추가: let required = if let Some(id) = selected { | |
| 738 | 추가: members | |
| 739 | 추가: .get(id as usize) | |
| 740 | 추가: .ok_or(ErrorCode::InvalidRequest)? | |
| 741 | 추가: .entry | |
| 742 | 추가: .size | |
| 743 | 추가: } else { | |
| 744 | 추가: total | |
| 745 | 추가: }; | |
| 746 | 추가: crate::space::ensure(&data, required)?; | |
| 716 | 747 | } |
| 717 | 748 | let mut offsets = Vec::new(); |
| 718 | 749 | for (member, packed) in members.iter().zip(packed) { |
| 719 | 750 | check.check()?; |
| 720 | 751 | offsets.push(io(data.stream_position())?); |
| 721 | 삭제: if !decode { | |
| 752 | 추가: if !decode || selected.is_some_and(|id| id != member.entry.entry_id) { | |
| 722 | 753 | crate::resources::completed(Ok(()), check)?; |
| 723 | 754 | continue; |
| 724 | 755 | } |
| @@ -138,7 +138,8 @@ macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wir | ||
| 138 | 138 | enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4}); |
| 139 | 139 | enumeration!(Method{Store=0,Deflate=1}); |
| 140 | 140 | enumeration!(Encryption{None=0,Aes256=1}); |
| 141 | 삭제: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2}); | |
| 141 | 추가: enumeration!(ActionKind{List=0,Extract=1,CreateZip=2,Preview=3}); | |
| 142 | 추가: enumeration!(PreviewFormat{Utf8Text=0,Rgba8=1}); | |
| 142 | 143 | enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3}); |
| 143 | 144 | enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5}); |
| 144 | 145 | enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3}); |
| @@ -166,6 +167,31 @@ structure!(ListId { | ||
| 166 | 167 | archive_bytes, |
| 167 | 168 | archive_sha256 |
| 168 | 169 | }); |
| 170 | 추가: impl Wire for PreviewInfo { | |
| 171 | 추가: fn enc(&self, e: &mut Encoder) -> io::Result<()> { | |
| 172 | 추가: if !self.valid() { | |
| 173 | 추가: return Err(invalid()); | |
| 174 | 추가: } | |
| 175 | 추가: self.entry_id.enc(e)?; | |
| 176 | 추가: self.format.enc(e)?; | |
| 177 | 추가: self.total_bytes.enc(e)?; | |
| 178 | 추가: self.width.enc(e)?; | |
| 179 | 추가: self.height.enc(e) | |
| 180 | 추가: } | |
| 181 | 추가: fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { | |
| 182 | 추가: let info = Self { | |
| 183 | 추가: entry_id: Wire::dec(d)?, | |
| 184 | 추가: format: Wire::dec(d)?, | |
| 185 | 추가: total_bytes: Wire::dec(d)?, | |
| 186 | 추가: width: Wire::dec(d)?, | |
| 187 | 추가: height: Wire::dec(d)?, | |
| 188 | 추가: }; | |
| 189 | 추가: if !info.valid() { | |
| 190 | 추가: return Err(invalid()); | |
| 191 | 추가: } | |
| 192 | 추가: Ok(info) | |
| 193 | 추가: } | |
| 194 | 추가: } | |
| 169 | 195 | structure!(Source { path, archive_name }); |
| 170 | 196 | structure!(Start { action, limits }); |
| 171 | 197 | structure!(GuardedStart { |
| @@ -309,6 +335,16 @@ impl Wire for Action { | ||
| 309 | 335 | method.enc(e)?; |
| 310 | 336 | encryption.enc(e) |
| 311 | 337 | } |
| 338 | 추가: Self::Preview { | |
| 339 | 추가: archive, | |
| 340 | 추가: entry_id, | |
| 341 | 추가: list_id, | |
| 342 | 추가: } => { | |
| 343 | 추가: 3u8.enc(e)?; | |
| 344 | 추가: archive.enc(e)?; | |
| 345 | 추가: entry_id.enc(e)?; | |
| 346 | 추가: list_id.enc(e) | |
| 347 | 추가: } | |
| 312 | 348 | } |
| 313 | 349 | } |
| 314 | 350 | fn dec(d: &mut Decoder<'_>) -> io::Result<Self> { |
| @@ -329,10 +365,21 @@ impl Wire for Action { | ||
| 329 | 365 | method: Wire::dec(d)?, |
| 330 | 366 | encryption: Wire::dec(d)?, |
| 331 | 367 | }), |
| 368 | 추가: 3 => Ok(Self::Preview { | |
| 369 | 추가: archive: Wire::dec(d)?, | |
| 370 | 추가: entry_id: Wire::dec(d)?, | |
| 371 | 추가: list_id: Wire::dec(d)?, | |
| 372 | 추가: }), | |
| 332 | 373 | _ => Err(invalid()), |
| 333 | 374 | } |
| 334 | 375 | } |
| 335 | 376 | } |
| 377 | 추가: fn valid_preview_chunk(offset: u64, length: usize) -> bool { | |
| 378 | 추가: (1..=MAX_PREVIEW_CHUNK_BYTES).contains(&length) | |
| 379 | 추가: && offset | |
| 380 | 추가: .checked_add(length as u64) | |
| 381 | 추가: .is_some_and(|end| end <= MAX_PREVIEW_RGBA_BYTES) | |
| 382 | 추가: } | |
| 336 | 383 | impl Message { |
| 337 | 384 | fn encode(&self) -> io::Result<(u16, Vec<u8>)> { |
| 338 | 385 | let mut e = Encoder { |
| @@ -341,6 +388,9 @@ impl Message { | ||
| 341 | 388 | }; |
| 342 | 389 | let kind = match self { |
| 343 | 390 | Self::Start(v) => { |
| 391 | 추가: if matches!(v.action, Action::Preview { .. }) { | |
| 392 | 추가: return Err(invalid()); | |
| 393 | 추가: } | |
| 344 | 394 | v.enc(&mut e)?; |
| 345 | 395 | 1 |
| 346 | 396 | } |
| @@ -456,6 +506,37 @@ impl Message { | ||
| 456 | 506 | disposition.enc(&mut e)?; |
| 457 | 507 | 105 |
| 458 | 508 | } |
| 509 | 추가: Self::PreviewBegin(info) => { | |
| 510 | 추가: info.enc(&mut e)?; | |
| 511 | 추가: 111 | |
| 512 | 추가: } | |
| 513 | 추가: Self::PreviewChunk { | |
| 514 | 추가: entry_id, | |
| 515 | 추가: offset, | |
| 516 | 추가: data, | |
| 517 | 추가: } => { | |
| 518 | 추가: if !valid_preview_chunk(*offset, data.len()) { | |
| 519 | 추가: return Err(invalid()); | |
| 520 | 추가: } | |
| 521 | 추가: entry_id.enc(&mut e)?; | |
| 522 | 추가: offset.enc(&mut e)?; | |
| 523 | 추가: (data.len() as u32).enc(&mut e)?; | |
| 524 | 추가: e.put(data)?; | |
| 525 | 추가: 112 | |
| 526 | 추가: } | |
| 527 | 추가: Self::PreviewEnd { | |
| 528 | 추가: entry_id, | |
| 529 | 추가: total_bytes, | |
| 530 | 추가: sha256, | |
| 531 | 추가: } => { | |
| 532 | 추가: if *total_bytes > MAX_PREVIEW_RGBA_BYTES { | |
| 533 | 추가: return Err(invalid()); | |
| 534 | 추가: } | |
| 535 | 추가: entry_id.enc(&mut e)?; | |
| 536 | 추가: total_bytes.enc(&mut e)?; | |
| 537 | 추가: sha256.enc(&mut e)?; | |
| 538 | 추가: 113 | |
| 539 | 추가: } | |
| 459 | 540 | Self::Terminal(v) => { |
| 460 | 541 | if v.detail.len() > 4096 { |
| 461 | 542 | return Err(invalid()); |
| @@ -509,7 +590,13 @@ impl Message { | ||
| 509 | 590 | }, |
| 510 | 591 | }; |
| 511 | 592 | let m = match kind { |
| 512 | 삭제: 1 => Self::Start(Wire::dec(&mut d)?), | |
| 593 | 추가: 1 => { | |
| 594 | 추가: let start = Start::dec(&mut d)?; | |
| 595 | 추가: if matches!(start.action, Action::Preview { .. }) { | |
| 596 | 추가: return Err(invalid()); | |
| 597 | 추가: } | |
| 598 | 추가: Self::Start(start) | |
| 599 | 추가: } | |
| 513 | 600 | 2 => { |
| 514 | 601 | let challenge_id = Wire::dec(&mut d)?; |
| 515 | 602 | let secret = Secret(Vec::<u8>::dec(&mut d)?); |
| @@ -585,6 +672,36 @@ impl Message { | ||
| 585 | 672 | relative_name: Wire::dec(&mut d)?, |
| 586 | 673 | disposition: Wire::dec(&mut d)?, |
| 587 | 674 | }, |
| 675 | 추가: 111 => Self::PreviewBegin(Wire::dec(&mut d)?), | |
| 676 | 추가: 112 => { | |
| 677 | 추가: let entry_id = Wire::dec(&mut d)?; | |
| 678 | 추가: let offset = Wire::dec(&mut d)?; | |
| 679 | 추가: let length = u32::dec(&mut d)? as usize; | |
| 680 | 추가: if !valid_preview_chunk(offset, length) { | |
| 681 | 추가: return Err(invalid()); | |
| 682 | 추가: } | |
| 683 | 추가: let bytes = d.take(length)?; | |
| 684 | 추가: let mut data = Vec::new(); | |
| 685 | 추가: data.try_reserve_exact(length).map_err(|_| invalid())?; | |
| 686 | 추가: data.extend_from_slice(bytes); | |
| 687 | 추가: Self::PreviewChunk { | |
| 688 | 추가: entry_id, | |
| 689 | 추가: offset, | |
| 690 | 추가: data, | |
| 691 | 추가: } | |
| 692 | 추가: } | |
| 693 | 추가: 113 => { | |
| 694 | 추가: let entry_id = Wire::dec(&mut d)?; | |
| 695 | 추가: let total_bytes = u64::dec(&mut d)?; | |
| 696 | 추가: if total_bytes > MAX_PREVIEW_RGBA_BYTES { | |
| 697 | 추가: return Err(invalid()); | |
| 698 | 추가: } | |
| 699 | 추가: Self::PreviewEnd { | |
| 700 | 추가: entry_id, | |
| 701 | 추가: total_bytes, | |
| 702 | 추가: sha256: Wire::dec(&mut d)?, | |
| 703 | 추가: } | |
| 704 | 추가: } | |
| 588 | 705 | 106 => { |
| 589 | 706 | let t = Terminal::dec(&mut d)?; |
| 590 | 707 | if t.detail.len() > 4096 { |
| @@ -0,0 +1,28 @@ | ||
| 1 | 추가: [package] | |
| 2 | 추가: name = "zipelo-jpeg" | |
| 3 | 추가: version = "0.5.15" | |
| 4 | 추가: edition = "2021" | |
| 5 | 추가: license = "MIT" | |
| 6 | 추가: license-file = "LICENSE-MIT" | |
| 7 | 추가: authors = ["caleb <[email protected]>"] | |
| 8 | 추가: publish = false | |
| 9 | 추가: | |
| 10 | 추가: [lib] | |
| 11 | 추가: name = "zune_jpeg" | |
| 12 | 추가: path = "src/lib.rs" | |
| 13 | 추가: doctest = false | |
| 14 | 추가: | |
| 15 | 추가: [features] | |
| 16 | 추가: default = [] | |
| 17 | 추가: std = ["zune-core/std"] | |
| 18 | 추가: x86 = [] | |
| 19 | 추가: neon = [] | |
| 20 | 추가: portable_simd = [] | |
| 21 | 추가: log = ["zune-core/log"] | |
| 22 | 추가: | |
| 23 | 추가: [dependencies] | |
| 24 | 추가: zune-core = { version = "=0.5.3", default-features = false } | |
| 25 | 추가: | |
| 26 | 추가: [lints.rust.unexpected_cfgs] | |
| 27 | 추가: level = "warn" | |
| 28 | 추가: check-cfg = ["cfg(fuzzing)"] |
| @@ -0,0 +1,21 @@ | ||
| 1 | 추가: MIT License | |
| 2 | 추가: | |
| 3 | 추가: Copyright (c) zune-image developers | |
| 4 | 추가: | |
| 5 | 추가: Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | 추가: of this software and associated documentation files (the "Software"), to deal | |
| 7 | 추가: in the Software without restriction, including without limitation the rights | |
| 8 | 추가: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | 추가: copies of the Software, and to permit persons to whom the Software is | |
| 10 | 추가: furnished to do so, subject to the following conditions: | |
| 11 | 추가: | |
| 12 | 추가: The above copyright notice and this permission notice shall be included in all | |
| 13 | 추가: copies or substantial portions of the Software. | |
| 14 | 추가: | |
| 15 | 추가: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | 추가: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | 추가: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | 추가: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | 추가: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | 추가: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | 추가: SOFTWARE. |
| @@ -0,0 +1,829 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: #![allow( | |
| 10 | 추가: clippy::if_not_else, | |
| 11 | 추가: clippy::similar_names, | |
| 12 | 추가: clippy::inline_always, | |
| 13 | 추가: clippy::doc_markdown, | |
| 14 | 추가: clippy::cast_sign_loss, | |
| 15 | 추가: clippy::cast_possible_truncation | |
| 16 | 추가: )] | |
| 17 | 추가: | |
| 18 | 추가: //! This file exposes a single struct that can decode a huffman encoded | |
| 19 | 추가: //! Bitstream in a JPEG file | |
| 20 | 추가: //! | |
| 21 | 추가: //! This code is optimized for speed. | |
| 22 | 추가: //! It's meant to be super duper super fast, because everyone else depends on this being fast. | |
| 23 | 추가: //! It's (annoyingly) serial hence we cant use parallel bitstreams(it's variable length coding.) | |
| 24 | 추가: //! | |
| 25 | 추가: //! Furthermore, on the case of refills, we have to do bytewise processing because the standard decided | |
| 26 | 추가: //! that we want to support markers in the middle of streams(seriously few people use RST markers). | |
| 27 | 추가: //! | |
| 28 | 추가: //! So we pull in all optimization steps: | |
| 29 | 추가: //! - use `inline[always]`? , | |
| 30 | 추가: //! - pre-execute most common cases , | |
| 31 | 추가: //! - add random comments | |
| 32 | 추가: //! - fast paths . | |
| 33 | 추가: //! | |
| 34 | 추가: //! Speed-wise: It is probably the fastest JPEG BitStream decoder to ever sail the seven seas because of | |
| 35 | 추가: //! a couple of optimization tricks. | |
| 36 | 추가: //! 1. Fast refills from libjpeg-turbo | |
| 37 | 추가: //! 2. As few as possible branches in decoder fast paths. | |
| 38 | 추가: //! 3. Accelerated AC table decoding borrowed from stb_image.h written by Fabian Gissen (@ rygorous), | |
| 39 | 추가: //! improved by me to handle more cases. | |
| 40 | 추가: //! 4. Safe and extensible routines(e.g. cool ways to eliminate bounds check) | |
| 41 | 추가: //! 5. No unsafe here | |
| 42 | 추가: //! | |
| 43 | 추가: //! Readability comes as a second priority(I tried with variable names this time, and we are wayy better than libjpeg). | |
| 44 | 추가: //! | |
| 45 | 추가: //! Anyway if you are reading this it means your cool and I hope you get whatever part of the code you are looking for | |
| 46 | 추가: //! (or learn something cool) | |
| 47 | 추가: //! | |
| 48 | 추가: //! Knock yourself out. | |
| 49 | 추가: use alloc::format; | |
| 50 | 추가: use alloc::string::ToString; | |
| 51 | 추가: use zune_core::log::warn; | |
| 52 | 추가: use core::cmp::min; | |
| 53 | 추가: | |
| 54 | 추가: use zune_core::bytestream::{ZByteReaderTrait, ZReader}; | |
| 55 | 추가: | |
| 56 | 추가: use crate::errors::DecodeErrors; | |
| 57 | 추가: use crate::huffman::{HuffmanTable, HUFF_LOOKAHEAD}; | |
| 58 | 추가: use crate::marker::Marker; | |
| 59 | 추가: use crate::mcu::DCT_BLOCK; | |
| 60 | 추가: use crate::misc::UN_ZIGZAG; | |
| 61 | 추가: | |
| 62 | 추가: macro_rules! decode_huff { | |
| 63 | 추가: ($stream:tt,$symbol:tt,$table:tt) => { | |
| 64 | 추가: let mut code_length = $symbol >> HUFF_LOOKAHEAD; | |
| 65 | 추가: | |
| 66 | 추가: ($symbol) &= (1 << HUFF_LOOKAHEAD) - 1; | |
| 67 | 추가: | |
| 68 | 추가: if code_length > i32::from(HUFF_LOOKAHEAD) | |
| 69 | 추가: { | |
| 70 | 추가: // if the symbol cannot be resolved in the first HUFF_LOOKAHEAD bits, | |
| 71 | 추가: // we know it lies somewhere between HUFF_LOOKAHEAD and 16 bits since jpeg imposes 16 bit | |
| 72 | 추가: // limit, we can therefore look 16 bits ahead and try to resolve the symbol | |
| 73 | 추가: // starting from 1+HUFF_LOOKAHEAD bits. | |
| 74 | 추가: $symbol = ($stream).peek_bits::<16>() as i32; | |
| 75 | 추가: // (Credits to Sean T. Barrett stb library for this optimization) | |
| 76 | 추가: // maxcode is pre-shifted 16 bytes long so that it has (16-code_length) | |
| 77 | 추가: // zeroes at the end hence we do not need to shift in the inner loop. | |
| 78 | 추가: while code_length < 17{ | |
| 79 | 추가: if $symbol < $table.maxcode[code_length as usize] { | |
| 80 | 추가: break; | |
| 81 | 추가: } | |
| 82 | 추가: code_length += 1; | |
| 83 | 추가: } | |
| 84 | 추가: | |
| 85 | 추가: if code_length == 17{ | |
| 86 | 추가: // symbol could not be decoded. | |
| 87 | 추가: // | |
| 88 | 추가: // We may think, lets fake zeroes, noo | |
| 89 | 추가: // panic, because Huffman codes are sensitive, probably everything | |
| 90 | 추가: // after this will be corrupt, so no need to continue. | |
| 91 | 추가: // panic!("Bad Huffman code length"); | |
| 92 | 추가: return Err(DecodeErrors::Format(format!("Bad Huffman Code 0x{:X}, corrupt JPEG",$symbol))) | |
| 93 | 추가: } | |
| 94 | 추가: | |
| 95 | 추가: $symbol >>= (16-code_length); | |
| 96 | 추가: ($symbol) = i32::from( | |
| 97 | 추가: ($table).values | |
| 98 | 추가: [(($symbol + ($table).offset[code_length as usize]) & 0xFF) as usize], | |
| 99 | 추가: ); | |
| 100 | 추가: } | |
| 101 | 추가: if code_length> i32::from(($stream).bits_left){ | |
| 102 | 추가: return Err(DecodeErrors::Format(format!("Code length {code_length} more than bits left {}",($stream).bits_left))) | |
| 103 | 추가: } | |
| 104 | 추가: // drop bits read | |
| 105 | 추가: ($stream).drop_bits(code_length as u8); | |
| 106 | 추가: }; | |
| 107 | 추가: } | |
| 108 | 추가: | |
| 109 | 추가: /// A `BitStream` struct, a bit by bit reader with super powers | |
| 110 | 추가: /// | |
| 111 | 추가: #[rustfmt::skip] | |
| 112 | 추가: pub(crate) struct BitStream { | |
| 113 | 추가: /// A MSB type buffer that is used for some certain operations | |
| 114 | 추가: pub buffer: u64, | |
| 115 | 추가: /// A TOP aligned MSB type buffer that is used to accelerate some operations like | |
| 116 | 추가: /// peek_bits and get_bits. | |
| 117 | 추가: /// | |
| 118 | 추가: /// By top aligned, I mean the top bit (63) represents the top bit in the buffer. | |
| 119 | 추가: aligned_buffer: u64, | |
| 120 | 추가: /// Tell us the bits left the two buffer | |
| 121 | 추가: pub(crate) bits_left: u8, | |
| 122 | 추가: /// Did we find a marker(RST/EOF) during decoding? | |
| 123 | 추가: pub marker: Option<Marker>, | |
| 124 | 추가: /// An i16 with the bit corresponding to successive_low set to 1, others 0. | |
| 125 | 추가: pub successive_low_mask: i16, | |
| 126 | 추가: spec_start: u8, | |
| 127 | 추가: spec_end: u8, | |
| 128 | 추가: pub eob_run: i32, | |
| 129 | 추가: pub overread_by: usize, | |
| 130 | 추가: /// True if we have seen end of image marker. | |
| 131 | 추가: /// Don't read anything after that. | |
| 132 | 추가: pub seen_eoi: bool, | |
| 133 | 추가: // 실제 입력 비트와 디코더가 보충한 비트의 소비를 구분함. | |
| 134 | 추가: input_bits: u8, | |
| 135 | 추가: exhausted_input: bool, | |
| 136 | 추가: } | |
| 137 | 추가: | |
| 138 | 추가: impl BitStream { | |
| 139 | 추가: /// Create a new BitStream | |
| 140 | 추가: #[rustfmt::skip] | |
| 141 | 추가: pub(crate) const fn new() -> BitStream { | |
| 142 | 추가: BitStream { | |
| 143 | 추가: buffer: 0, | |
| 144 | 추가: aligned_buffer: 0, | |
| 145 | 추가: bits_left: 0, | |
| 146 | 추가: marker: None, | |
| 147 | 추가: successive_low_mask: 1, | |
| 148 | 추가: spec_start: 0, | |
| 149 | 추가: spec_end: 0, | |
| 150 | 추가: eob_run: 0, | |
| 151 | 추가: overread_by: 0, | |
| 152 | 추가: seen_eoi: false, | |
| 153 | 추가: input_bits: 0, | |
| 154 | 추가: exhausted_input: false, | |
| 155 | 추가: } | |
| 156 | 추가: } | |
| 157 | 추가: | |
| 158 | 추가: /// Create a new Bitstream for progressive decoding | |
| 159 | 추가: #[allow(clippy::redundant_field_names)] | |
| 160 | 추가: #[rustfmt::skip] | |
| 161 | 추가: pub(crate) fn new_progressive(al: u8, spec_start: u8, spec_end: u8) -> BitStream { | |
| 162 | 추가: BitStream { | |
| 163 | 추가: buffer: 0, | |
| 164 | 추가: aligned_buffer: 0, | |
| 165 | 추가: bits_left: 0, | |
| 166 | 추가: marker: None, | |
| 167 | 추가: successive_low_mask: 1i16 << al, | |
| 168 | 추가: spec_start: spec_start, | |
| 169 | 추가: spec_end: spec_end, | |
| 170 | 추가: eob_run: 0, | |
| 171 | 추가: overread_by: 0, | |
| 172 | 추가: seen_eoi: false, | |
| 173 | 추가: input_bits: 0, | |
| 174 | 추가: exhausted_input: false, | |
| 175 | 추가: } | |
| 176 | 추가: } | |
| 177 | 추가: | |
| 178 | 추가: /// Refill the bit buffer by (a maximum of) 32 bits | |
| 179 | 추가: /// | |
| 180 | 추가: /// # Arguments | |
| 181 | 추가: /// - `reader`:`&mut BufReader<R>`: A mutable reference to an underlying | |
| 182 | 추가: /// File/Memory buffer containing a valid JPEG stream | |
| 183 | 추가: /// | |
| 184 | 추가: /// This function will only refill if `self.count` is less than 32 | |
| 185 | 추가: #[inline(always)] // to many call sites? ( perf improvement by 4%) | |
| 186 | 추가: pub fn refill<T>(&mut self, reader: &mut ZReader<T>) -> Result<bool, DecodeErrors> | |
| 187 | 추가: where | |
| 188 | 추가: T: ZByteReaderTrait | |
| 189 | 추가: { | |
| 190 | 추가: /// Macro version of a single byte refill. | |
| 191 | 추가: /// Arguments | |
| 192 | 추가: /// buffer-> our io buffer, because rust macros cannot get values from | |
| 193 | 추가: /// the surrounding environment bits_left-> number of bits left | |
| 194 | 추가: /// to full refill | |
| 195 | 추가: macro_rules! refill { | |
| 196 | 추가: ($buffer:expr,$byte:expr,$bits_left:expr) => { | |
| 197 | 추가: // read a byte from the stream | |
| 198 | 추가: $byte = u64::from(reader.read_u8()); | |
| 199 | 추가: self.overread_by += usize::from(reader.eof()?); | |
| 200 | 추가: // append to the buffer | |
| 201 | 추가: // JPEG is a MSB type buffer so that means we append this | |
| 202 | 추가: // to the lower end (0..8) of the buffer and push the rest bits above.. | |
| 203 | 추가: $buffer = ($buffer << 8) | $byte; | |
| 204 | 추가: // Increment bits left | |
| 205 | 추가: $bits_left += 8; | |
| 206 | 추가: // Check for special case of OxFF, to see if it's a stream or a marker | |
| 207 | 추가: if $byte == 0xff { | |
| 208 | 추가: // read next byte | |
| 209 | 추가: let mut next_byte = u64::from(reader.read_u8()); | |
| 210 | 추가: // Byte snuffing, if we encounter byte snuff, we skip the byte | |
| 211 | 추가: if next_byte != 0x00 { | |
| 212 | 추가: // skip that byte we read | |
| 213 | 추가: while next_byte == 0xFF { | |
| 214 | 추가: next_byte = u64::from(reader.read_u8()); | |
| 215 | 추가: } | |
| 216 | 추가: | |
| 217 | 추가: if next_byte != 0x00 { | |
| 218 | 추가: // Undo the byte append and return | |
| 219 | 추가: $buffer >>= 8; | |
| 220 | 추가: $bits_left -= 8; | |
| 221 | 추가: | |
| 222 | 추가: if $bits_left != 0 { | |
| 223 | 추가: self.aligned_buffer = $buffer << (64 - $bits_left); | |
| 224 | 추가: } | |
| 225 | 추가: | |
| 226 | 추가: let marker = Marker::from_u8(next_byte as u8); | |
| 227 | 추가: self.marker = marker; | |
| 228 | 추가: | |
| 229 | 추가: if let Some(Marker::UNKNOWN(_)) = marker{ | |
| 230 | 추가: return Err(DecodeErrors::Format("Unknown marker in bit stream".to_string())); | |
| 231 | 추가: } | |
| 232 | 추가: if next_byte == 0xD9 { | |
| 233 | 추가: // special handling for eoi, fill some bytes,even if its zero, | |
| 234 | 추가: // removes some panics | |
| 235 | 추가: self.buffer <<= 8; | |
| 236 | 추가: self.bits_left += 8; | |
| 237 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 238 | 추가: } | |
| 239 | 추가: | |
| 240 | 추가: return Ok(false); | |
| 241 | 추가: } | |
| 242 | 추가: } | |
| 243 | 추가: } | |
| 244 | 추가: if self.overread_by == 0 { | |
| 245 | 추가: self.input_bits += 8; | |
| 246 | 추가: } | |
| 247 | 추가: }; | |
| 248 | 추가: } | |
| 249 | 추가: | |
| 250 | 추가: self.require_input()?; | |
| 251 | 추가: // 32 bits is enough for a decode(16 bits) and receive_extend(max 16 bits) | |
| 252 | 추가: if self.bits_left < 32 { | |
| 253 | 추가: if self.marker.is_some() || self.seen_eoi { | |
| 254 | 추가: // found a marker, or we are in EOI | |
| 255 | 추가: // also we are in over-reading mode, where we fill it with zeroes | |
| 256 | 추가: | |
| 257 | 추가: // fill with zeroes | |
| 258 | 추가: self.buffer <<= 32; | |
| 259 | 추가: self.bits_left += 32; | |
| 260 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 261 | 추가: return Ok(true); | |
| 262 | 추가: } | |
| 263 | 추가: | |
| 264 | 추가: if self.overread_by > 0 { | |
| 265 | 추가: if self.bits_left == 0 { | |
| 266 | 추가: return Err(DecodeErrors::ExhaustedData); | |
| 267 | 추가: } | |
| 268 | 추가: // We already hit EOF while refilling. Continue consuming the buffered bits | |
| 269 | 추가: // but don't synthesize additional bytes from zero-fill. | |
| 270 | 추가: return Ok(true); | |
| 271 | 추가: } | |
| 272 | 추가: | |
| 273 | 추가: // we optimize for the case where we don't have 255 in the stream and have 4 bytes left | |
| 274 | 추가: // as it is the common case | |
| 275 | 추가: // | |
| 276 | 추가: // so we always read 4 bytes, if read_fixed_bytes errors out, the cursor is | |
| 277 | 추가: // guaranteed not to advance in case of failure (is this true), so | |
| 278 | 추가: // we revert the read later on (if we have 255), if this fails, we use the normal | |
| 279 | 추가: // byte at a time read | |
| 280 | 추가: | |
| 281 | 추가: if let Ok(bytes) = reader.read_fixed_bytes_or_error::<4>() { | |
| 282 | 추가: // we have 4 bytes to spare, read the 4 bytes into a temporary buffer | |
| 283 | 추가: // create buffer | |
| 284 | 추가: let msb_buf = u32::from_be_bytes(bytes); | |
| 285 | 추가: // check if we have 0xff | |
| 286 | 추가: if !has_byte(msb_buf, 255) { | |
| 287 | 추가: self.bits_left += 32; | |
| 288 | 추가: self.input_bits += 32; | |
| 289 | 추가: self.buffer <<= 32; | |
| 290 | 추가: self.buffer |= u64::from(msb_buf); | |
| 291 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 292 | 추가: return Ok(true); | |
| 293 | 추가: } | |
| 294 | 추가: | |
| 295 | 추가: reader.rewind(4)?; | |
| 296 | 추가: } | |
| 297 | 추가: // This serves two reasons, | |
| 298 | 추가: // 1: Make clippy shut up | |
| 299 | 추가: // 2: Favour register reuse | |
| 300 | 추가: let mut byte; | |
| 301 | 추가: // 4 refills, if all succeed the stream should contain enough bits to decode a | |
| 302 | 추가: // value | |
| 303 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 304 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 305 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 306 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 307 | 추가: // Construct an MSB buffer whose top bits are the bitstream we are currently holding. | |
| 308 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 309 | 추가: } | |
| 310 | 추가: return Ok(true); | |
| 311 | 추가: } | |
| 312 | 추가: /// Decode the DC coefficient in a MCU block. | |
| 313 | 추가: /// | |
| 314 | 추가: /// The decoded coefficient is written to `dc_prediction` | |
| 315 | 추가: /// | |
| 316 | 추가: #[allow( | |
| 317 | 추가: clippy::cast_possible_truncation, | |
| 318 | 추가: clippy::cast_sign_loss, | |
| 319 | 추가: clippy::unwrap_used | |
| 320 | 추가: )] | |
| 321 | 추가: #[inline(always)] | |
| 322 | 추가: fn decode_dc<T>( | |
| 323 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, dc_prediction: &mut i32 | |
| 324 | 추가: ) -> Result<bool, DecodeErrors> | |
| 325 | 추가: where | |
| 326 | 추가: T: ZByteReaderTrait | |
| 327 | 추가: { | |
| 328 | 추가: let (mut symbol, r); | |
| 329 | 추가: | |
| 330 | 추가: if self.bits_left < 32 { | |
| 331 | 추가: self.refill(reader)?; | |
| 332 | 추가: }; | |
| 333 | 추가: // look a head HUFF_LOOKAHEAD bits into the bitstream | |
| 334 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 335 | 추가: symbol = dc_table.lookup[symbol as usize]; | |
| 336 | 추가: | |
| 337 | 추가: decode_huff!(self, symbol, dc_table); | |
| 338 | 추가: | |
| 339 | 추가: if symbol != 0 { | |
| 340 | 추가: r = self.get_bits(symbol as u8); | |
| 341 | 추가: symbol = huff_extend(r, symbol); | |
| 342 | 추가: } | |
| 343 | 추가: // Update DC prediction | |
| 344 | 추가: *dc_prediction = dc_prediction.wrapping_add(symbol); | |
| 345 | 추가: | |
| 346 | 추가: return Ok(true); | |
| 347 | 추가: } | |
| 348 | 추가: | |
| 349 | 추가: /// Like `decode_dc` but we do not need the result of the component, we only want to remove it | |
| 350 | 추가: /// from the bitstream of the MCU. | |
| 351 | 추가: fn discard_dc<T>( | |
| 352 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable | |
| 353 | 추가: ) -> Result<bool, DecodeErrors> | |
| 354 | 추가: where | |
| 355 | 추가: T: ZByteReaderTrait | |
| 356 | 추가: { | |
| 357 | 추가: let mut symbol; | |
| 358 | 추가: | |
| 359 | 추가: if self.bits_left < 32 { | |
| 360 | 추가: self.refill(reader)?; | |
| 361 | 추가: }; | |
| 362 | 추가: // look a head HUFF_LOOKAHEAD bits into the bitstream | |
| 363 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 364 | 추가: symbol = dc_table.lookup[symbol as usize]; | |
| 365 | 추가: | |
| 366 | 추가: decode_huff!(self, symbol, dc_table); | |
| 367 | 추가: | |
| 368 | 추가: if symbol != 0 { | |
| 369 | 추가: let _ = self.get_bits(symbol as u8); | |
| 370 | 추가: } | |
| 371 | 추가: | |
| 372 | 추가: return Ok(true); | |
| 373 | 추가: } | |
| 374 | 추가: | |
| 375 | 추가: /// Decode a Minimum Code Unit(MCU) as quickly as possible | |
| 376 | 추가: /// | |
| 377 | 추가: /// # Arguments | |
| 378 | 추가: /// - reader: The bitstream from where we read more bits. | |
| 379 | 추가: /// - dc_table: The Huffman table used to decode the DC coefficient | |
| 380 | 추가: /// - ac_table: The Huffman table used to decode AC values | |
| 381 | 추가: /// - block: A memory region where we will write out the decoded values | |
| 382 | 추가: /// - DC prediction: Last DC value for this component | |
| 383 | 추가: /// | |
| 384 | 추가: #[allow( | |
| 385 | 추가: clippy::many_single_char_names, | |
| 386 | 추가: clippy::cast_possible_truncation, | |
| 387 | 추가: clippy::cast_sign_loss | |
| 388 | 추가: )] | |
| 389 | 추가: #[inline(never)] | |
| 390 | 추가: pub fn decode_mcu_block<T>( | |
| 391 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable, | |
| 392 | 추가: qt_table: &[i32; DCT_BLOCK], block: &mut [i32; 64], dc_prediction: &mut i32 | |
| 393 | 추가: ) -> Result<u16, DecodeErrors> | |
| 394 | 추가: where | |
| 395 | 추가: T: ZByteReaderTrait | |
| 396 | 추가: { | |
| 397 | 추가: // Get fast AC table as a reference before we enter the hot path | |
| 398 | 추가: let ac_lookup = ac_table.ac_lookup.as_ref().unwrap(); | |
| 399 | 추가: | |
| 400 | 추가: let (mut symbol, mut r, mut fast_ac); | |
| 401 | 추가: // Decode AC coefficients | |
| 402 | 추가: let mut pos: usize = 1; | |
| 403 | 추가: if self.bits_left < 1 && self.marker.is_some() { | |
| 404 | 추가: return Err(DecodeErrors::Format( | |
| 405 | 추가: "No more bytes left in stream before marker".to_string() | |
| 406 | 추가: )); | |
| 407 | 추가: } | |
| 408 | 추가: // decode DC, dc prediction will contain the value | |
| 409 | 추가: self.decode_dc(reader, dc_table, dc_prediction)?; | |
| 410 | 추가: | |
| 411 | 추가: // set dc to be the dc prediction. | |
| 412 | 추가: block[0] = *dc_prediction * qt_table[0]; | |
| 413 | 추가: | |
| 414 | 추가: while pos < 64 { | |
| 415 | 추가: self.refill(reader)?; | |
| 416 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 417 | 추가: fast_ac = ac_lookup[symbol as usize]; | |
| 418 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 419 | 추가: | |
| 420 | 추가: if fast_ac != 0 { | |
| 421 | 추가: // FAST AC path | |
| 422 | 추가: pos += ((fast_ac >> 4) & 15) as usize; // run | |
| 423 | 추가: let t_pos = UN_ZIGZAG[min(pos, 63)] & 63; | |
| 424 | 추가: | |
| 425 | 추가: block[t_pos] = i32::from(fast_ac >> 8) * (qt_table[t_pos]); // Value | |
| 426 | 추가: self.drop_bits((fast_ac & 15) as u8); | |
| 427 | 추가: pos += 1; | |
| 428 | 추가: } else { | |
| 429 | 추가: decode_huff!(self, symbol, ac_table); | |
| 430 | 추가: | |
| 431 | 추가: r = symbol >> 4; | |
| 432 | 추가: symbol &= 15; | |
| 433 | 추가: | |
| 434 | 추가: if symbol != 0 { | |
| 435 | 추가: pos += r as usize; | |
| 436 | 추가: r = self.get_bits(symbol as u8); | |
| 437 | 추가: symbol = huff_extend(r, symbol); | |
| 438 | 추가: let t_pos = UN_ZIGZAG[pos & 63] & 63; | |
| 439 | 추가: | |
| 440 | 추가: block[t_pos] = symbol * qt_table[t_pos]; | |
| 441 | 추가: | |
| 442 | 추가: pos += 1; | |
| 443 | 추가: } else if r != 15 { | |
| 444 | 추가: return Ok(pos as u16); | |
| 445 | 추가: } else { | |
| 446 | 추가: pos += 16; | |
| 447 | 추가: } | |
| 448 | 추가: } | |
| 449 | 추가: } | |
| 450 | 추가: | |
| 451 | 추가: return Ok(64); | |
| 452 | 추가: } | |
| 453 | 추가: | |
| 454 | 추가: /// Advance the bitstream over a block but ignore the data contained. | |
| 455 | 추가: /// | |
| 456 | 추가: /// This updates DC prediction but we never dequantize and we never do any Zig-Zag translation | |
| 457 | 추가: /// either. Still returns the index of the last component read. | |
| 458 | 추가: pub fn discard_mcu_block<T>( | |
| 459 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable | |
| 460 | 추가: ) -> Result<u16, DecodeErrors> | |
| 461 | 추가: where | |
| 462 | 추가: T: ZByteReaderTrait | |
| 463 | 추가: { | |
| 464 | 추가: // Get fast AC table as a reference before we enter the hot path | |
| 465 | 추가: let ac_lookup = ac_table.ac_lookup.as_ref().unwrap(); | |
| 466 | 추가: | |
| 467 | 추가: let (mut symbol, mut r, mut fast_ac); | |
| 468 | 추가: // Decode AC coefficients | |
| 469 | 추가: let mut pos: usize = 1; | |
| 470 | 추가: | |
| 471 | 추가: // decode DC, dc prediction will contain the value | |
| 472 | 추가: self.discard_dc(reader, dc_table)?; | |
| 473 | 추가: | |
| 474 | 추가: while pos < 64 { | |
| 475 | 추가: self.refill(reader)?; | |
| 476 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 477 | 추가: fast_ac = ac_lookup[symbol as usize]; | |
| 478 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 479 | 추가: | |
| 480 | 추가: if fast_ac != 0 { | |
| 481 | 추가: // FAST AC path | |
| 482 | 추가: pos += ((fast_ac >> 4) & 15) as usize; // run | |
| 483 | 추가: | |
| 484 | 추가: self.drop_bits((fast_ac & 15) as u8); | |
| 485 | 추가: pos += 1; | |
| 486 | 추가: } else { | |
| 487 | 추가: decode_huff!(self, symbol, ac_table); | |
| 488 | 추가: | |
| 489 | 추가: r = symbol >> 4; | |
| 490 | 추가: symbol &= 15; | |
| 491 | 추가: | |
| 492 | 추가: if symbol != 0 { | |
| 493 | 추가: pos += r as usize; | |
| 494 | 추가: // Advance over bits but ignore. | |
| 495 | 추가: let _ = self.get_bits(symbol as u8); | |
| 496 | 추가: | |
| 497 | 추가: pos += 1; | |
| 498 | 추가: } else if r != 15 { | |
| 499 | 추가: return Ok(pos as u16); | |
| 500 | 추가: } else { | |
| 501 | 추가: pos += 16; | |
| 502 | 추가: } | |
| 503 | 추가: } | |
| 504 | 추가: } | |
| 505 | 추가: | |
| 506 | 추가: return Ok(64); | |
| 507 | 추가: } | |
| 508 | 추가: | |
| 509 | 추가: /// Peek `look_ahead` bits ahead without discarding them from the buffer | |
| 510 | 추가: #[inline(always)] | |
| 511 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 512 | 추가: const fn peek_bits<const LOOKAHEAD: u8>(&self) -> i32 { | |
| 513 | 추가: (self.aligned_buffer >> (64 - LOOKAHEAD)) as i32 | |
| 514 | 추가: } | |
| 515 | 추가: | |
| 516 | 추가: /// Discard the next `N` bits without checking | |
| 517 | 추가: #[inline] | |
| 518 | 추가: fn drop_bits(&mut self, n: u8) { | |
| 519 | 추가: self.consume_input(n); | |
| 520 | 추가: // PS: Its a good check, but triggers fuzzer and a lot of false positives | |
| 521 | 추가: //debug_assert!(self.bits_left >= n); | |
| 522 | 추가: //self.bits_left -= n; | |
| 523 | 추가: self.bits_left = self.bits_left.saturating_sub(n); | |
| 524 | 추가: self.aligned_buffer <<= n; | |
| 525 | 추가: } | |
| 526 | 추가: | |
| 527 | 추가: /// Read `n_bits` from the buffer and discard them | |
| 528 | 추가: #[inline(always)] | |
| 529 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 530 | 추가: fn get_bits(&mut self, n_bits: u8) -> i32 { | |
| 531 | 추가: self.consume_input(n_bits); | |
| 532 | 추가: let mask = (1_u64 << n_bits) - 1; | |
| 533 | 추가: | |
| 534 | 추가: self.aligned_buffer = self.aligned_buffer.rotate_left(u32::from(n_bits)); | |
| 535 | 추가: let bits = (self.aligned_buffer & mask) as i32; | |
| 536 | 추가: self.bits_left = self.bits_left.wrapping_sub(n_bits); | |
| 537 | 추가: bits | |
| 538 | 추가: } | |
| 539 | 추가: | |
| 540 | 추가: /// Decode a DC block | |
| 541 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 542 | 추가: #[inline] | |
| 543 | 추가: pub(crate) fn decode_prog_dc_first<T>( | |
| 544 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, block: &mut i16, | |
| 545 | 추가: dc_prediction: &mut i32 | |
| 546 | 추가: ) -> Result<(), DecodeErrors> | |
| 547 | 추가: where | |
| 548 | 추가: T: ZByteReaderTrait | |
| 549 | 추가: { | |
| 550 | 추가: self.decode_dc(reader, dc_table, dc_prediction)?; | |
| 551 | 추가: *block = (*dc_prediction as i16).wrapping_mul(self.successive_low_mask); | |
| 552 | 추가: return Ok(()); | |
| 553 | 추가: } | |
| 554 | 추가: #[inline] | |
| 555 | 추가: pub(crate) fn decode_prog_dc_refine<T>( | |
| 556 | 추가: &mut self, reader: &mut ZReader<T>, block: &mut i16 | |
| 557 | 추가: ) -> Result<(), DecodeErrors> | |
| 558 | 추가: where | |
| 559 | 추가: T: ZByteReaderTrait | |
| 560 | 추가: { | |
| 561 | 추가: // refinement scan | |
| 562 | 추가: if self.bits_left < 1 { | |
| 563 | 추가: self.refill(reader)?; | |
| 564 | 추가: // if we find a marker, it may happens we don't refill. | |
| 565 | 추가: // So let's confirm again that refill worked | |
| 566 | 추가: if self.bits_left < 1 { | |
| 567 | 추가: return Err(DecodeErrors::Format( | |
| 568 | 추가: "Marker found where not expected in refine bit".to_string() | |
| 569 | 추가: )); | |
| 570 | 추가: } | |
| 571 | 추가: } | |
| 572 | 추가: | |
| 573 | 추가: if self.get_bit() == 1 { | |
| 574 | 추가: *block = block.wrapping_add(self.successive_low_mask); | |
| 575 | 추가: } | |
| 576 | 추가: | |
| 577 | 추가: Ok(()) | |
| 578 | 추가: } | |
| 579 | 추가: | |
| 580 | 추가: /// Get a single bit from the bitstream | |
| 581 | 추가: fn get_bit(&mut self) -> u8 { | |
| 582 | 추가: let k = (self.aligned_buffer >> 63) as u8; | |
| 583 | 추가: // discard a bit | |
| 584 | 추가: self.drop_bits(1); | |
| 585 | 추가: return k; | |
| 586 | 추가: } | |
| 587 | 추가: pub(crate) fn decode_mcu_ac_first<T>( | |
| 588 | 추가: &mut self, reader: &mut ZReader<T>, ac_table: &HuffmanTable, block: &mut [i16; 64] | |
| 589 | 추가: ) -> Result<bool, DecodeErrors> | |
| 590 | 추가: where | |
| 591 | 추가: T: ZByteReaderTrait | |
| 592 | 추가: { | |
| 593 | 추가: let fast_ac = ac_table.ac_lookup.as_ref().unwrap(); | |
| 594 | 추가: let bit = self.successive_low_mask; | |
| 595 | 추가: | |
| 596 | 추가: let mut k = self.spec_start as usize; | |
| 597 | 추가: let (mut symbol, mut r, mut fac); | |
| 598 | 추가: | |
| 599 | 추가: // EOB runs are handled in mcu_prog.rs | |
| 600 | 추가: 'block: loop { | |
| 601 | 추가: self.refill(reader)?; | |
| 602 | 추가: // Check for marker in the stream | |
| 603 | 추가: | |
| 604 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 605 | 추가: fac = fast_ac[symbol as usize]; | |
| 606 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 607 | 추가: | |
| 608 | 추가: if fac != 0 { | |
| 609 | 추가: // fast ac path | |
| 610 | 추가: k += ((fac >> 4) & 15) as usize; // run | |
| 611 | 추가: block[UN_ZIGZAG[min(k, 63)] & 63] = (fac >> 8).wrapping_mul(bit); // value | |
| 612 | 추가: self.drop_bits((fac & 15) as u8); | |
| 613 | 추가: k += 1; | |
| 614 | 추가: } else { | |
| 615 | 추가: decode_huff!(self, symbol, ac_table); | |
| 616 | 추가: | |
| 617 | 추가: r = symbol >> 4; | |
| 618 | 추가: symbol &= 15; | |
| 619 | 추가: | |
| 620 | 추가: if symbol != 0 { | |
| 621 | 추가: k += r as usize; | |
| 622 | 추가: r = self.get_bits(symbol as u8); | |
| 623 | 추가: symbol = huff_extend(r, symbol); | |
| 624 | 추가: block[UN_ZIGZAG[k & 63] & 63] = (symbol as i16).wrapping_mul(bit); | |
| 625 | 추가: k += 1; | |
| 626 | 추가: } else { | |
| 627 | 추가: if r != 15 { | |
| 628 | 추가: self.eob_run = 1 << r; | |
| 629 | 추가: self.eob_run += self.get_bits(r as u8); | |
| 630 | 추가: self.eob_run -= 1; | |
| 631 | 추가: break; | |
| 632 | 추가: } | |
| 633 | 추가: | |
| 634 | 추가: k += 16; | |
| 635 | 추가: } | |
| 636 | 추가: } | |
| 637 | 추가: | |
| 638 | 추가: if k > self.spec_end as usize { | |
| 639 | 추가: break 'block; | |
| 640 | 추가: } | |
| 641 | 추가: } | |
| 642 | 추가: return Ok(true); | |
| 643 | 추가: } | |
| 644 | 추가: #[allow(clippy::too_many_lines, clippy::op_ref)] | |
| 645 | 추가: pub(crate) fn decode_mcu_ac_refine<T>( | |
| 646 | 추가: &mut self, reader: &mut ZReader<T>, table: &HuffmanTable, block: &mut [i16; 64] | |
| 647 | 추가: ) -> Result<bool, DecodeErrors> | |
| 648 | 추가: where | |
| 649 | 추가: T: ZByteReaderTrait | |
| 650 | 추가: { | |
| 651 | 추가: let bit = self.successive_low_mask; | |
| 652 | 추가: | |
| 653 | 추가: let mut k = self.spec_start; | |
| 654 | 추가: let (mut symbol, mut r); | |
| 655 | 추가: | |
| 656 | 추가: if self.eob_run == 0 { | |
| 657 | 추가: 'no_eob: loop { | |
| 658 | 추가: // Decode a coefficient from the bit stream | |
| 659 | 추가: self.refill(reader)?; | |
| 660 | 추가: | |
| 661 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 662 | 추가: symbol = table.lookup[symbol as usize]; | |
| 663 | 추가: | |
| 664 | 추가: decode_huff!(self, symbol, table); | |
| 665 | 추가: | |
| 666 | 추가: r = symbol >> 4; | |
| 667 | 추가: symbol &= 15; | |
| 668 | 추가: | |
| 669 | 추가: if symbol == 0 { | |
| 670 | 추가: if r != 15 { | |
| 671 | 추가: // EOB run is 2^r + bits | |
| 672 | 추가: self.eob_run = 1 << r; | |
| 673 | 추가: self.eob_run += self.get_bits(r as u8); | |
| 674 | 추가: // EOB runs are handled by the eob logic | |
| 675 | 추가: break 'no_eob; | |
| 676 | 추가: } | |
| 677 | 추가: } else { | |
| 678 | 추가: // libjpeg-turbo also doesn't return an error here, so let's also warn. | |
| 679 | 추가: if symbol != 1 { | |
| 680 | 추가: warn!("Bad Huffman code, corrupt JPEG?"); | |
| 681 | 추가: } | |
| 682 | 추가: // get sign bit | |
| 683 | 추가: // We assume we have enough bits, which should be correct for sane images | |
| 684 | 추가: // since we refill by 32 above | |
| 685 | 추가: if self.get_bit() == 1 { | |
| 686 | 추가: symbol = i32::from(bit); | |
| 687 | 추가: } else { | |
| 688 | 추가: symbol = i32::from(-bit); | |
| 689 | 추가: } | |
| 690 | 추가: } | |
| 691 | 추가: | |
| 692 | 추가: // Advance over already nonzero coefficients appending | |
| 693 | 추가: // correction bits to the non-zeroes. | |
| 694 | 추가: // A correction bit is 1 if the absolute value of the coefficient must be increased | |
| 695 | 추가: | |
| 696 | 추가: if k <= self.spec_end { | |
| 697 | 추가: 'advance_nonzero: loop { | |
| 698 | 추가: let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63]; | |
| 699 | 추가: | |
| 700 | 추가: if *coefficient != 0 { | |
| 701 | 추가: if self.bits_left < 1 { | |
| 702 | 추가: self.refill(reader)?; | |
| 703 | 추가: if self.bits_left < 1 && self.marker.is_some() { | |
| 704 | 추가: return Err(DecodeErrors::Format( | |
| 705 | 추가: "Marker found where not expected in refine bit".to_string() | |
| 706 | 추가: )); | |
| 707 | 추가: } | |
| 708 | 추가: } | |
| 709 | 추가: if self.get_bit() == 1 && (*coefficient & bit) == 0 { | |
| 710 | 추가: if *coefficient > 0 { | |
| 711 | 추가: *coefficient = coefficient.wrapping_add(bit); | |
| 712 | 추가: } else { | |
| 713 | 추가: *coefficient = coefficient.wrapping_sub(bit); | |
| 714 | 추가: } | |
| 715 | 추가: } | |
| 716 | 추가: } else { | |
| 717 | 추가: r -= 1; | |
| 718 | 추가: | |
| 719 | 추가: if r < 0 { | |
| 720 | 추가: // reached target zero coefficient. | |
| 721 | 추가: break 'advance_nonzero; | |
| 722 | 추가: } | |
| 723 | 추가: }; | |
| 724 | 추가: | |
| 725 | 추가: if k == self.spec_end { | |
| 726 | 추가: break 'advance_nonzero; | |
| 727 | 추가: } | |
| 728 | 추가: | |
| 729 | 추가: k += 1; | |
| 730 | 추가: } | |
| 731 | 추가: } | |
| 732 | 추가: | |
| 733 | 추가: if symbol != 0 { | |
| 734 | 추가: let pos = UN_ZIGZAG[k as usize & 63]; | |
| 735 | 추가: // output new non-zero coefficient. | |
| 736 | 추가: block[pos & 63] = symbol as i16; | |
| 737 | 추가: } | |
| 738 | 추가: | |
| 739 | 추가: k += 1; | |
| 740 | 추가: | |
| 741 | 추가: if k > self.spec_end { | |
| 742 | 추가: break 'no_eob; | |
| 743 | 추가: } | |
| 744 | 추가: } | |
| 745 | 추가: } | |
| 746 | 추가: if self.eob_run > 0 { | |
| 747 | 추가: // only run if block does not consists of purely zeroes | |
| 748 | 추가: if &block[1..] != &[0; 63] { | |
| 749 | 추가: self.refill(reader)?; | |
| 750 | 추가: | |
| 751 | 추가: while k <= self.spec_end { | |
| 752 | 추가: let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63]; | |
| 753 | 추가: | |
| 754 | 추가: if *coefficient != 0 && self.get_bit() == 1 { | |
| 755 | 추가: // check if we already modified it, if so do nothing, otherwise | |
| 756 | 추가: // append the correction bit. | |
| 757 | 추가: if (*coefficient & bit) == 0 { | |
| 758 | 추가: if *coefficient >= 0 { | |
| 759 | 추가: *coefficient = coefficient.wrapping_add(bit); | |
| 760 | 추가: } else { | |
| 761 | 추가: *coefficient = coefficient.wrapping_sub(bit); | |
| 762 | 추가: } | |
| 763 | 추가: } | |
| 764 | 추가: } | |
| 765 | 추가: if self.bits_left < 1 { | |
| 766 | 추가: // refill at the last possible moment | |
| 767 | 추가: self.refill(reader)?; | |
| 768 | 추가: } | |
| 769 | 추가: k += 1; | |
| 770 | 추가: } | |
| 771 | 추가: } | |
| 772 | 추가: // count a block completed in EOB run | |
| 773 | 추가: self.eob_run -= 1; | |
| 774 | 추가: } | |
| 775 | 추가: return Ok(true); | |
| 776 | 추가: } | |
| 777 | 추가: | |
| 778 | 추가: pub fn update_progressive_params(&mut self, _ah: u8, al: u8, spec_start: u8, spec_end: u8) { | |
| 779 | 추가: self.successive_low_mask = 1i16 << al; | |
| 780 | 추가: self.spec_start = spec_start; | |
| 781 | 추가: self.spec_end = spec_end; | |
| 782 | 추가: } | |
| 783 | 추가: | |
| 784 | 추가: fn consume_input(&mut self, bits: u8) { | |
| 785 | 추가: self.exhausted_input |= bits > self.input_bits; | |
| 786 | 추가: self.input_bits = self.input_bits.saturating_sub(bits); | |
| 787 | 추가: } | |
| 788 | 추가: | |
| 789 | 추가: pub(crate) fn require_input(&self) -> Result<(), DecodeErrors> { | |
| 790 | 추가: if self.exhausted_input { | |
| 791 | 추가: return Err(DecodeErrors::FormatStatic("Incomplete entropy-coded image data")); | |
| 792 | 추가: } | |
| 793 | 추가: Ok(()) | |
| 794 | 추가: } | |
| 795 | 추가: | |
| 796 | 추가: /// Reset the stream if we have a restart marker | |
| 797 | 추가: /// | |
| 798 | 추가: /// Restart markers indicate drop those bits in the stream and zero out | |
| 799 | 추가: /// everything | |
| 800 | 추가: #[cold] | |
| 801 | 추가: pub fn reset(&mut self) { | |
| 802 | 추가: self.bits_left = 0; | |
| 803 | 추가: self.input_bits = 0; | |
| 804 | 추가: self.exhausted_input = false; | |
| 805 | 추가: self.marker = None; | |
| 806 | 추가: self.buffer = 0; | |
| 807 | 추가: self.aligned_buffer = 0; | |
| 808 | 추가: self.eob_run = 0; | |
| 809 | 추가: } | |
| 810 | 추가: } | |
| 811 | 추가: | |
| 812 | 추가: /// Do the equivalent of JPEG HUFF_EXTEND | |
| 813 | 추가: #[inline(always)] | |
| 814 | 추가: fn huff_extend(x: i32, s: i32) -> i32 { | |
| 815 | 추가: // if x<s return x else return x+offset[s] where offset[s] = ( (-1<<s)+1) | |
| 816 | 추가: (x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((-1) << (s)) + 1)) | |
| 817 | 추가: } | |
| 818 | 추가: | |
| 819 | 추가: const fn has_zero(v: u32) -> bool { | |
| 820 | 추가: // Retrieved from Stanford bithacks | |
| 821 | 추가: // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord | |
| 822 | 추가: return !((((v & 0x7F7F_7F7F) + 0x7F7F_7F7F) | v) | 0x7F7F_7F7F) != 0; | |
| 823 | 추가: } | |
| 824 | 추가: | |
| 825 | 추가: const fn has_byte(b: u32, val: u8) -> bool { | |
| 826 | 추가: // Retrieved from Stanford bithacks | |
| 827 | 추가: // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord | |
| 828 | 추가: has_zero(b ^ ((!0_u32 / 255) * (val as u32))) | |
| 829 | 추가: } |
| @@ -0,0 +1,102 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: #![allow( | |
| 10 | 추가: clippy::many_single_char_names, | |
| 11 | 추가: clippy::similar_names, | |
| 12 | 추가: clippy::cast_possible_truncation, | |
| 13 | 추가: clippy::cast_sign_loss, | |
| 14 | 추가: clippy::cast_possible_wrap, | |
| 15 | 추가: clippy::too_many_arguments, | |
| 16 | 추가: clippy::doc_markdown | |
| 17 | 추가: )] | |
| 18 | 추가: | |
| 19 | 추가: //! Color space conversion routines | |
| 20 | 추가: //! | |
| 21 | 추가: //! This files exposes functions to convert one colorspace to another in a jpeg | |
| 22 | 추가: //! image | |
| 23 | 추가: //! | |
| 24 | 추가: //! Currently supported conversions are | |
| 25 | 추가: //! | |
| 26 | 추가: //! - `YCbCr` to `RGB,RGBA,GRAYSCALE,RGBX`. | |
| 27 | 추가: //! | |
| 28 | 추가: //! | |
| 29 | 추가: //! Hey there, if your reading this it means you probably need something, so let me help you. | |
| 30 | 추가: //! | |
| 31 | 추가: //! There are 3 supported cpu extensions here. | |
| 32 | 추가: //! 1. Scalar | |
| 33 | 추가: //! 2. SSE | |
| 34 | 추가: //! 3. AVX | |
| 35 | 추가: //! | |
| 36 | 추가: //! There are two types of the color convert functions | |
| 37 | 추가: //! | |
| 38 | 추가: //! 1. Acts on 16 pixels. | |
| 39 | 추가: //! 2. Acts on 8 pixels. | |
| 40 | 추가: //! | |
| 41 | 추가: //! The reason for this is because when implementing the AVX part it occurred to me that we can actually | |
| 42 | 추가: //! do better and process 2 MCU's if we change IDCT return type to be `i16's`, since a lot of | |
| 43 | 추가: //! CPU's these days support AVX extensions, it becomes nice if we optimize for that path , | |
| 44 | 추가: //! therefore AVX routines can process 16 pixels directly and SSE and Scalar just compensate. | |
| 45 | 추가: //! | |
| 46 | 추가: //! By compensating, I mean I wrote the 16 pixels version operating on the 8 pixel version twice. | |
| 47 | 추가: //! | |
| 48 | 추가: //! Therefore if your looking to optimize some routines, probably start there. | |
| 49 | 추가: | |
| 50 | 추가: pub use scalar::ycbcr_to_grayscale; | |
| 51 | 추가: use zune_core::colorspace::ColorSpace; | |
| 52 | 추가: use zune_core::options::DecoderOptions; | |
| 53 | 추가: | |
| 54 | 추가: #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 55 | 추가: #[cfg(feature = "x86")] | |
| 56 | 추가: pub use crate::color_convert::avx::{ycbcr_to_rgb_avx2, ycbcr_to_rgba_avx2}; | |
| 57 | 추가: use crate::decoder::ColorConvert16Ptr; | |
| 58 | 추가: | |
| 59 | 추가: mod avx; | |
| 60 | 추가: mod neon64; | |
| 61 | 추가: mod scalar; | |
| 62 | 추가: | |
| 63 | 추가: #[allow(unused_variables)] | |
| 64 | 추가: pub fn choose_ycbcr_to_rgb_convert_func( | |
| 65 | 추가: type_need: ColorSpace, options: &DecoderOptions | |
| 66 | 추가: ) -> Option<ColorConvert16Ptr> { | |
| 67 | 추가: #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 68 | 추가: #[cfg(feature = "x86")] | |
| 69 | 추가: { | |
| 70 | 추가: use zune_core::log::debug; | |
| 71 | 추가: if options.use_avx2() { | |
| 72 | 추가: debug!("Using AVX optimised color conversion functions"); | |
| 73 | 추가: | |
| 74 | 추가: // I believe avx2 means sse4 is also available | |
| 75 | 추가: // match colorspace | |
| 76 | 추가: match type_need { | |
| 77 | 추가: ColorSpace::RGB => return Some(ycbcr_to_rgb_avx2), | |
| 78 | 추가: ColorSpace::RGBA => return Some(ycbcr_to_rgba_avx2), | |
| 79 | 추가: _ => () // fall through to scalar, which has more types | |
| 80 | 추가: }; | |
| 81 | 추가: } | |
| 82 | 추가: } | |
| 83 | 추가: #[cfg(all(feature = "neon", target_arch = "aarch64"))] | |
| 84 | 추가: { | |
| 85 | 추가: if options.use_neon() { | |
| 86 | 추가: use crate::color_convert::neon64::{ycbcr_to_rgb_neon, ycbcr_to_rgba_neon}; | |
| 87 | 추가: match type_need { | |
| 88 | 추가: ColorSpace::RGB => return Some(ycbcr_to_rgb_neon), | |
| 89 | 추가: ColorSpace::RGBA => return Some(ycbcr_to_rgba_neon), | |
| 90 | 추가: _ => () // fall through to scalar, which has more types | |
| 91 | 추가: }; | |
| 92 | 추가: } | |
| 93 | 추가: } | |
| 94 | 추가: // when there is no x86 or we haven't returned by here, resort to scalar | |
| 95 | 추가: return match type_need { | |
| 96 | 추가: ColorSpace::RGB => Some(scalar::ycbcr_to_rgb_inner_16_scalar::<false>), | |
| 97 | 추가: ColorSpace::RGBA => Some(scalar::ycbcr_to_rgba_inner_16_scalar::<false>), | |
| 98 | 추가: ColorSpace::BGRA => Some(scalar::ycbcr_to_rgba_inner_16_scalar::<true>), | |
| 99 | 추가: ColorSpace::BGR => Some(scalar::ycbcr_to_rgb_inner_16_scalar::<true>), | |
| 100 | 추가: _ => None | |
| 101 | 추가: }; | |
| 102 | 추가: } |
| @@ -0,0 +1,297 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: //! AVX color conversion routines | |
| 10 | 추가: //! | |
| 11 | 추가: //! Okay these codes are cool | |
| 12 | 추가: //! | |
| 13 | 추가: //! Herein lies super optimized codes to do color conversions. | |
| 14 | 추가: //! | |
| 15 | 추가: //! | |
| 16 | 추가: //! 1. The YCbCr to RGB use integer approximations and not the floating point equivalent. | |
| 17 | 추가: //! That means we may be +- 2 of pixels generated by libjpeg-turbo jpeg decoding | |
| 18 | 추가: //! (also libjpeg uses routines like `Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G`) | |
| 19 | 추가: //! | |
| 20 | 추가: //! Firstly, we use integers (fun fact:there is no part of this code base where were dealing with | |
| 21 | 추가: //! floating points.., fun fact: the first fun fact wasn't even fun.) | |
| 22 | 추가: //! | |
| 23 | 추가: //! Secondly ,we have cool clamping code, especially for rgba , where we don't need clamping and we | |
| 24 | 추가: //! spend our time cursing that Intel decided permute instructions to work like 2 128 bit vectors(the compiler opitmizes | |
| 25 | 추가: //! it out to something cool). | |
| 26 | 추가: //! | |
| 27 | 추가: //! There isn't a lot here (not as fun as bitstream ) but I hope you find what you're looking for. | |
| 28 | 추가: //! | |
| 29 | 추가: //! O and ~~subscribe to my youtube channel~~ | |
| 30 | 추가: | |
| 31 | 추가: #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 32 | 추가: #![cfg(feature = "x86")] | |
| 33 | 추가: #![allow( | |
| 34 | 추가: clippy::wildcard_imports, | |
| 35 | 추가: clippy::cast_possible_truncation, | |
| 36 | 추가: clippy::too_many_arguments, | |
| 37 | 추가: clippy::inline_always, | |
| 38 | 추가: clippy::doc_markdown, | |
| 39 | 추가: dead_code | |
| 40 | 추가: )] | |
| 41 | 추가: | |
| 42 | 추가: #[cfg(target_arch = "x86")] | |
| 43 | 추가: use core::arch::x86::*; | |
| 44 | 추가: #[cfg(target_arch = "x86_64")] | |
| 45 | 추가: use core::arch::x86_64::*; | |
| 46 | 추가: | |
| 47 | 추가: use crate::color_convert::scalar::{CB_CF, CR_CF, C_G_CB_COEF_2, C_G_CR_COEF_1, YUV_RND, Y_CF}; | |
| 48 | 추가: | |
| 49 | 추가: pub union YmmRegister { | |
| 50 | 추가: // both are 32 when using std::mem::size_of | |
| 51 | 추가: mm256: __m256i, | |
| 52 | 추가: // for avx color conversion | |
| 53 | 추가: array: [i16; 16] | |
| 54 | 추가: } | |
| 55 | 추가: | |
| 56 | 추가: const R_AVX_COEF: i32 = i32::from_ne_bytes([CR_CF.to_ne_bytes()[0], CR_CF.to_ne_bytes()[1], 0, 0]); | |
| 57 | 추가: const B_AVX_COEF: i32 = i32::from_ne_bytes([0, 0, CB_CF.to_ne_bytes()[0], CB_CF.to_ne_bytes()[1]]); | |
| 58 | 추가: const G_COEF_AVX_COEF: i32 = i32::from_ne_bytes([ | |
| 59 | 추가: C_G_CR_COEF_1.to_ne_bytes()[0], | |
| 60 | 추가: C_G_CR_COEF_1.to_ne_bytes()[1], | |
| 61 | 추가: C_G_CB_COEF_2.to_ne_bytes()[0], | |
| 62 | 추가: C_G_CB_COEF_2.to_ne_bytes()[1] | |
| 63 | 추가: ]); | |
| 64 | 추가: | |
| 65 | 추가: //-------------------------------------------------------------------------------------------------- | |
| 66 | 추가: // AVX conversion routines | |
| 67 | 추가: //-------------------------------------------------------------------------------------------------- | |
| 68 | 추가: | |
| 69 | 추가: /// | |
| 70 | 추가: /// Convert YCBCR to RGB using AVX instructions | |
| 71 | 추가: /// | |
| 72 | 추가: /// # Note | |
| 73 | 추가: ///**IT IS THE RESPONSIBILITY OF THE CALLER TO CALL THIS IN CPUS SUPPORTING | |
| 74 | 추가: /// AVX2 OTHERWISE THIS IS UB** | |
| 75 | 추가: /// | |
| 76 | 추가: /// *Peace* | |
| 77 | 추가: /// | |
| 78 | 추가: /// This library itself will ensure that it's never called in CPU's not | |
| 79 | 추가: /// supporting AVX2 | |
| 80 | 추가: /// | |
| 81 | 추가: /// # Arguments | |
| 82 | 추가: /// - `y`,`cb`,`cr`: A reference of 8 i32's | |
| 83 | 추가: /// - `out`: The output array where we store our converted items | |
| 84 | 추가: /// - `offset`: The position from 0 where we write these RGB values | |
| 85 | 추가: #[inline(always)] | |
| 86 | 추가: pub fn ycbcr_to_rgb_avx2( | |
| 87 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 88 | 추가: ) { | |
| 89 | 추가: // call this in another function to tell RUST to vectorize this | |
| 90 | 추가: // storing | |
| 91 | 추가: unsafe { | |
| 92 | 추가: ycbcr_to_rgb_avx2_1(y, cb, cr, out, offset); | |
| 93 | 추가: } | |
| 94 | 추가: } | |
| 95 | 추가: | |
| 96 | 추가: #[inline] | |
| 97 | 추가: #[target_feature(enable = "avx2")] | |
| 98 | 추가: unsafe fn ycbcr_to_rgb_avx2_1( | |
| 99 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 100 | 추가: ) { | |
| 101 | 추가: let (mut r, mut g, mut b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 102 | 추가: | |
| 103 | 추가: r = _mm256_packus_epi16(r, _mm256_setzero_si256()); | |
| 104 | 추가: g = _mm256_packus_epi16(g, _mm256_setzero_si256()); | |
| 105 | 추가: b = _mm256_packus_epi16(b, _mm256_setzero_si256()); | |
| 106 | 추가: | |
| 107 | 추가: r = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(r); | |
| 108 | 추가: g = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(g); | |
| 109 | 추가: b = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(b); | |
| 110 | 추가: | |
| 111 | 추가: let sh_r = _mm256_setr_epi8( | |
| 112 | 추가: 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, | |
| 113 | 추가: 9, 4, 15, 10, 5 | |
| 114 | 추가: ); | |
| 115 | 추가: let sh_g = _mm256_setr_epi8( | |
| 116 | 추가: 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, | |
| 117 | 추가: 14, 9, 4, 15, 10 | |
| 118 | 추가: ); | |
| 119 | 추가: let sh_b = _mm256_setr_epi8( | |
| 120 | 추가: 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, | |
| 121 | 추가: 3, 14, 9, 4, 15 | |
| 122 | 추가: ); | |
| 123 | 추가: | |
| 124 | 추가: let r0 = _mm256_shuffle_epi8(r, sh_r); | |
| 125 | 추가: let g0 = _mm256_shuffle_epi8(g, sh_g); | |
| 126 | 추가: let b0 = _mm256_shuffle_epi8(b, sh_b); | |
| 127 | 추가: | |
| 128 | 추가: let m0 = _mm256_setr_epi8( | |
| 129 | 추가: 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, | |
| 130 | 추가: 0, 0, -1, 0, 0 | |
| 131 | 추가: ); | |
| 132 | 추가: let m1 = _mm256_setr_epi8( | |
| 133 | 추가: 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, | |
| 134 | 추가: -1, 0, 0, -1, 0 | |
| 135 | 추가: ); | |
| 136 | 추가: | |
| 137 | 추가: let p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, g0, m0), b0, m1); | |
| 138 | 추가: let p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, b0, m0), r0, m1); | |
| 139 | 추가: let p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, r0, m0), g0, m1); | |
| 140 | 추가: | |
| 141 | 추가: let rgb0 = _mm256_permute2x128_si256::<32>(p0, p1); | |
| 142 | 추가: let rgb1 = _mm256_permute2x128_si256::<48>(p2, p0); | |
| 143 | 추가: | |
| 144 | 추가: _mm256_storeu_si256(out.as_mut_ptr().cast(), rgb0); | |
| 145 | 추가: _mm_storeu_si128(out[32..].as_mut_ptr().cast(), _mm256_castsi256_si128(rgb1)); | |
| 146 | 추가: | |
| 147 | 추가: *offset += 48; | |
| 148 | 추가: } | |
| 149 | 추가: | |
| 150 | 추가: // Enabled avx2 automatically enables avx. | |
| 151 | 추가: #[inline] | |
| 152 | 추가: #[target_feature(enable = "avx2")] | |
| 153 | 추가: /// A baseline implementation of YCbCr to RGB conversion which does not carry | |
| 154 | 추가: /// out clamping | |
| 155 | 추가: /// | |
| 156 | 추가: /// This is used by the `ycbcr_to_rgba_avx` and `ycbcr_to_rgbx` conversion | |
| 157 | 추가: /// routines | |
| 158 | 추가: unsafe fn ycbcr_to_rgb_baseline_no_clamp( | |
| 159 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16] | |
| 160 | 추가: ) -> (__m256i, __m256i, __m256i) { | |
| 161 | 추가: // Load values into a register | |
| 162 | 추가: // | |
| 163 | 추가: let y_c = _mm256_loadu_si256(y.as_ptr().cast()); | |
| 164 | 추가: let cb_c = _mm256_loadu_si256(cb.as_ptr().cast()); | |
| 165 | 추가: let cr_c = _mm256_loadu_si256(cr.as_ptr().cast()); | |
| 166 | 추가: | |
| 167 | 추가: // Here we want to use _mm256_madd_epi16 to perform 2 multiplications | |
| 168 | 추가: // and one addition per instruction. | |
| 169 | 추가: | |
| 170 | 추가: // At first, we have to pack i16 U and V that stores u8 into one u8 [U,V] | |
| 171 | 추가: // then zero extend, and keep in mind that lanes is already been permuted. | |
| 172 | 추가: | |
| 173 | 추가: let y_coeff = _mm256_set1_epi32(i32::from(Y_CF)); | |
| 174 | 추가: let cr_coeff = _mm256_set1_epi32(R_AVX_COEF); | |
| 175 | 추가: let cb_coeff = _mm256_set1_epi32(B_AVX_COEF); | |
| 176 | 추가: let cg_coeff = _mm256_set1_epi32(G_COEF_AVX_COEF); | |
| 177 | 추가: let v_rnd = _mm256_set1_epi32(i32::from(YUV_RND)); | |
| 178 | 추가: let uv_bias = _mm256_set1_epi16(128); | |
| 179 | 추가: | |
| 180 | 추가: // UV in memory because x86/x86_64 is always little endian | |
| 181 | 추가: let v_0 = _mm256_slli_epi16::<8>(cb_c); | |
| 182 | 추가: let u_v_8 = _mm256_or_si256(v_0, cr_c); | |
| 183 | 추가: | |
| 184 | 추가: let mut u_v_lo = _mm256_unpacklo_epi8(u_v_8, _mm256_setzero_si256()); | |
| 185 | 추가: let mut u_v_hi = _mm256_unpackhi_epi8(u_v_8, _mm256_setzero_si256()); | |
| 186 | 추가: | |
| 187 | 추가: let mut y_lo = _mm256_unpacklo_epi16(y_c, _mm256_setzero_si256()); | |
| 188 | 추가: let mut y_hi = _mm256_unpackhi_epi16(y_c, _mm256_setzero_si256()); | |
| 189 | 추가: | |
| 190 | 추가: u_v_lo = _mm256_sub_epi16(u_v_lo, uv_bias); | |
| 191 | 추가: u_v_hi = _mm256_sub_epi16(u_v_hi, uv_bias); | |
| 192 | 추가: | |
| 193 | 추가: y_lo = _mm256_madd_epi16(y_lo, y_coeff); | |
| 194 | 추가: y_hi = _mm256_madd_epi16(y_hi, y_coeff); | |
| 195 | 추가: | |
| 196 | 추가: let mut r_lo = _mm256_madd_epi16(u_v_lo, cr_coeff); | |
| 197 | 추가: let mut r_hi = _mm256_madd_epi16(u_v_hi, cr_coeff); | |
| 198 | 추가: | |
| 199 | 추가: let mut g_lo = _mm256_madd_epi16(u_v_lo, cg_coeff); | |
| 200 | 추가: let mut g_hi = _mm256_madd_epi16(u_v_hi, cg_coeff); | |
| 201 | 추가: | |
| 202 | 추가: // This ordering is preferred to reduce register file pressure. | |
| 203 | 추가: | |
| 204 | 추가: y_lo = _mm256_add_epi32(y_lo, v_rnd); | |
| 205 | 추가: y_hi = _mm256_add_epi32(y_hi, v_rnd); | |
| 206 | 추가: | |
| 207 | 추가: let mut b_lo = _mm256_madd_epi16(u_v_lo, cb_coeff); | |
| 208 | 추가: let mut b_hi = _mm256_madd_epi16(u_v_hi, cb_coeff); | |
| 209 | 추가: | |
| 210 | 추가: r_lo = _mm256_add_epi32(r_lo, y_lo); | |
| 211 | 추가: r_hi = _mm256_add_epi32(r_hi, y_hi); | |
| 212 | 추가: | |
| 213 | 추가: g_lo = _mm256_add_epi32(g_lo, y_lo); | |
| 214 | 추가: g_hi = _mm256_add_epi32(g_hi, y_hi); | |
| 215 | 추가: | |
| 216 | 추가: b_lo = _mm256_add_epi32(b_lo, y_lo); | |
| 217 | 추가: b_hi = _mm256_add_epi32(b_hi, y_hi); | |
| 218 | 추가: | |
| 219 | 추가: r_lo = _mm256_srai_epi32::<14>(r_lo); | |
| 220 | 추가: r_hi = _mm256_srai_epi32::<14>(r_hi); | |
| 221 | 추가: | |
| 222 | 추가: g_lo = _mm256_srai_epi32::<14>(g_lo); | |
| 223 | 추가: g_hi = _mm256_srai_epi32::<14>(g_hi); | |
| 224 | 추가: | |
| 225 | 추가: b_lo = _mm256_srai_epi32::<14>(b_lo); | |
| 226 | 추가: b_hi = _mm256_srai_epi32::<14>(b_hi); | |
| 227 | 추가: | |
| 228 | 추가: let r = _mm256_packus_epi32(r_lo, r_hi); | |
| 229 | 추가: let g = _mm256_packus_epi32(g_lo, g_hi); | |
| 230 | 추가: let b = _mm256_packus_epi32(b_lo, b_hi); | |
| 231 | 추가: | |
| 232 | 추가: return (r, g, b); | |
| 233 | 추가: } | |
| 234 | 추가: | |
| 235 | 추가: #[inline(always)] | |
| 236 | 추가: pub fn ycbcr_to_rgba_avx2( | |
| 237 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 238 | 추가: ) { | |
| 239 | 추가: unsafe { | |
| 240 | 추가: ycbcr_to_rgba_unsafe(y, cb, cr, out, offset); | |
| 241 | 추가: } | |
| 242 | 추가: } | |
| 243 | 추가: | |
| 244 | 추가: #[inline] | |
| 245 | 추가: #[target_feature(enable = "avx2")] | |
| 246 | 추가: #[rustfmt::skip] | |
| 247 | 추가: unsafe fn ycbcr_to_rgba_unsafe( | |
| 248 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], | |
| 249 | 추가: out: &mut [u8], | |
| 250 | 추가: offset: &mut usize, | |
| 251 | 추가: ) | |
| 252 | 추가: { | |
| 253 | 추가: // check if we have enough space to write. | |
| 254 | 추가: let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice to small cannot write").try_into().unwrap(); | |
| 255 | 추가: | |
| 256 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 257 | 추가: | |
| 258 | 추가: // set alpha channel to 255 for opaque | |
| 259 | 추가: | |
| 260 | 추가: // And no these comments were not from me pressing the keyboard | |
| 261 | 추가: | |
| 262 | 추가: // Pack the integers into u8's using unsigned saturation. | |
| 263 | 추가: let c = _mm256_packus_epi16(r, g); //aaaaa_bbbbb_aaaaa_bbbbbb | |
| 264 | 추가: let d = _mm256_packus_epi16(b, _mm256_set1_epi16(255)); // cccccc_dddddd_ccccccc_ddddd | |
| 265 | 추가: // transpose_u16 and interleave channels | |
| 266 | 추가: let e = _mm256_unpacklo_epi8(c, d); //ab_ab_ab_ab_ab_ab_ab_ab | |
| 267 | 추가: let f = _mm256_unpackhi_epi8(c, d); //cd_cd_cd_cd_cd_cd_cd_cd | |
| 268 | 추가: // final transpose_u16 | |
| 269 | 추가: let g = _mm256_unpacklo_epi8(e, f); //abcd_abcd_abcd_abcd_abcd | |
| 270 | 추가: let h = _mm256_unpackhi_epi8(e, f); | |
| 271 | 추가: | |
| 272 | 추가: // undo packus shuffling... | |
| 273 | 추가: let i = _mm256_permute2x128_si256::<{ shuffle(3, 2, 1, 0) }>(g, h); | |
| 274 | 추가: | |
| 275 | 추가: let j = _mm256_permute2x128_si256::<{ shuffle(1, 2, 3, 0) }>(g, h); | |
| 276 | 추가: | |
| 277 | 추가: let k = _mm256_permute2x128_si256::<{ shuffle(3, 2, 0, 1) }>(g, h); | |
| 278 | 추가: | |
| 279 | 추가: let l = _mm256_permute2x128_si256::<{ shuffle(0, 3, 2, 1) }>(g, h); | |
| 280 | 추가: | |
| 281 | 추가: let m = _mm256_blend_epi32::<0b1111_0000>(i, j); | |
| 282 | 추가: | |
| 283 | 추가: let n = _mm256_blend_epi32::<0b1111_0000>(k, l); | |
| 284 | 추가: | |
| 285 | 추가: // Store | |
| 286 | 추가: // Use streaming instructions to prevent polluting the cache? | |
| 287 | 추가: _mm256_storeu_si256(tmp.as_mut_ptr().cast(), m); | |
| 288 | 추가: | |
| 289 | 추가: _mm256_storeu_si256(tmp[32..].as_mut_ptr().cast(), n); | |
| 290 | 추가: | |
| 291 | 추가: *offset += 64; | |
| 292 | 추가: } | |
| 293 | 추가: | |
| 294 | 추가: #[inline] | |
| 295 | 추가: const fn shuffle(z: i32, y: i32, x: i32, w: i32) -> i32 { | |
| 296 | 추가: (z << 6) | (y << 4) | (x << 2) | w | |
| 297 | 추가: } |
| @@ -0,0 +1,146 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2025. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: //! Aarch64 color conversion routines | |
| 10 | 추가: //! NEON is mandatory on aarch64. | |
| 11 | 추가: | |
| 12 | 추가: #![cfg(all(feature = "neon", target_arch = "aarch64"))] | |
| 13 | 추가: use core::arch::aarch64::*; | |
| 14 | 추가: | |
| 15 | 추가: use crate::color_convert::scalar::{CB_CF, CR_CF, C_G_CB_COEF_2, C_G_CR_COEF_1, YUV_RND, Y_CF}; | |
| 16 | 추가: | |
| 17 | 추가: const C_1: u64 = u64::from_ne_bytes([ | |
| 18 | 추가: Y_CF.to_ne_bytes()[0], | |
| 19 | 추가: Y_CF.to_ne_bytes()[1], | |
| 20 | 추가: CR_CF.to_ne_bytes()[0], | |
| 21 | 추가: CR_CF.to_ne_bytes()[1], | |
| 22 | 추가: CB_CF.to_ne_bytes()[0], | |
| 23 | 추가: CB_CF.to_ne_bytes()[1], | |
| 24 | 추가: C_G_CR_COEF_1.to_ne_bytes()[0], | |
| 25 | 추가: C_G_CR_COEF_1.to_ne_bytes()[1] | |
| 26 | 추가: ]); | |
| 27 | 추가: const C_2: u64 = u64::from_ne_bytes([ | |
| 28 | 추가: C_G_CB_COEF_2.to_ne_bytes()[0], | |
| 29 | 추가: C_G_CB_COEF_2.to_ne_bytes()[1], | |
| 30 | 추가: 0, | |
| 31 | 추가: 0, | |
| 32 | 추가: 0, | |
| 33 | 추가: 0, | |
| 34 | 추가: 0, | |
| 35 | 추가: 0 | |
| 36 | 추가: ]); | |
| 37 | 추가: | |
| 38 | 추가: #[inline(always)] | |
| 39 | 추가: unsafe fn ycbcr_to_rgb_baseline_no_clamp( | |
| 40 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16] | |
| 41 | 추가: ) -> (uint8x16_t, uint8x16_t, uint8x16_t) { | |
| 42 | 추가: unsafe { | |
| 43 | 추가: // NEON has 32 registers, so it is good idea to utilize a lot of variables at once | |
| 44 | 추가: | |
| 45 | 추가: let cb_cr_bias = vdupq_n_s16(128); | |
| 46 | 추가: // 0 - Y coeff, 1 - Cr, 2 - Cb, 3 - G1, 4 - G2 | |
| 47 | 추가: let coefficients = vcombine_s16(vcreate_s16(C_1), vcreate_s16(C_2)); | |
| 48 | 추가: | |
| 49 | 추가: let y0 = vld1q_s16(y.as_ptr().cast()); | |
| 50 | 추가: let y1 = vld1q_s16(y[8..].as_ptr().cast()); | |
| 51 | 추가: | |
| 52 | 추가: let mut cb0 = vld1q_s16(cb.as_ptr().cast()); | |
| 53 | 추가: let mut cb1 = vld1q_s16(cb[8..].as_ptr().cast()); | |
| 54 | 추가: | |
| 55 | 추가: let mut cr0 = vld1q_s16(cr.as_ptr().cast()); | |
| 56 | 추가: let mut cr1 = vld1q_s16(cr[8..].as_ptr().cast()); | |
| 57 | 추가: | |
| 58 | 추가: cb0 = vsubq_s16(cb0, cb_cr_bias); | |
| 59 | 추가: cb1 = vsubq_s16(cb1, cb_cr_bias); | |
| 60 | 추가: | |
| 61 | 추가: cr0 = vsubq_s16(cr0, cb_cr_bias); | |
| 62 | 추가: cr1 = vsubq_s16(cr1, cb_cr_bias); | |
| 63 | 추가: | |
| 64 | 추가: let bias = vdupq_n_s32(i32::from(YUV_RND)); | |
| 65 | 추가: | |
| 66 | 추가: let acc0 = vmlal_laneq_s16::<0>(bias, vget_low_s16(y0), coefficients); | |
| 67 | 추가: let acc1 = vmlal_high_laneq_s16::<0>(bias, y0, coefficients); | |
| 68 | 추가: let acc2 = vmlal_laneq_s16::<0>(bias, vget_low_s16(y1), coefficients); | |
| 69 | 추가: let acc3 = vmlal_high_laneq_s16::<0>(bias, y1, coefficients); | |
| 70 | 추가: | |
| 71 | 추가: let r0 = vmlal_laneq_s16::<1>(acc0, vget_low_s16(cr0), coefficients); | |
| 72 | 추가: let r1 = vmlal_high_laneq_s16::<1>(acc1, cr0, coefficients); | |
| 73 | 추가: let r2 = vmlal_laneq_s16::<1>(acc2, vget_low_s16(cr1), coefficients); | |
| 74 | 추가: let r3 = vmlal_high_laneq_s16::<1>(acc3, cr1, coefficients); | |
| 75 | 추가: | |
| 76 | 추가: let b0 = vmlal_laneq_s16::<2>(acc0, vget_low_s16(cb0), coefficients); | |
| 77 | 추가: let b1 = vmlal_high_laneq_s16::<2>(acc1, cb0, coefficients); | |
| 78 | 추가: let b2 = vmlal_laneq_s16::<2>(acc2, vget_low_s16(cb1), coefficients); | |
| 79 | 추가: let b3 = vmlal_high_laneq_s16::<2>(acc3, cb1, coefficients); | |
| 80 | 추가: | |
| 81 | 추가: // Saturating shift right with signed -> unsigned saturation | |
| 82 | 추가: let qr0 = vqshrun_n_s32::<14>(r0); | |
| 83 | 추가: let qr1 = vqshrun_n_s32::<14>(r1); | |
| 84 | 추가: let qr2 = vqshrun_n_s32::<14>(r2); | |
| 85 | 추가: let qr3 = vqshrun_n_s32::<14>(r3); | |
| 86 | 추가: | |
| 87 | 추가: let mut g0 = vmlal_laneq_s16::<4>(acc0, vget_low_s16(cb0), coefficients); | |
| 88 | 추가: let mut g1 = vmlal_high_laneq_s16::<4>(acc1, cb0, coefficients); | |
| 89 | 추가: let mut g2 = vmlal_laneq_s16::<4>(acc2, vget_low_s16(cb1), coefficients); | |
| 90 | 추가: let mut g3 = vmlal_high_laneq_s16::<4>(acc3, cb1, coefficients); | |
| 91 | 추가: | |
| 92 | 추가: let qb0 = vqshrun_n_s32::<14>(b0); | |
| 93 | 추가: let qb1 = vqshrun_n_s32::<14>(b1); | |
| 94 | 추가: let qb2 = vqshrun_n_s32::<14>(b2); | |
| 95 | 추가: let qb3 = vqshrun_n_s32::<14>(b3); | |
| 96 | 추가: | |
| 97 | 추가: let r0 = vqmovn_u16(vcombine_u16(qr0, qr1)); | |
| 98 | 추가: let r1 = vqmovn_u16(vcombine_u16(qr2, qr3)); | |
| 99 | 추가: | |
| 100 | 추가: let b0 = vqmovn_u16(vcombine_u16(qb0, qb1)); | |
| 101 | 추가: let b1 = vqmovn_u16(vcombine_u16(qb2, qb3)); | |
| 102 | 추가: | |
| 103 | 추가: g0 = vmlal_laneq_s16::<3>(g0, vget_low_s16(cr0), coefficients); | |
| 104 | 추가: g1 = vmlal_high_laneq_s16::<3>(g1, cr0, coefficients); | |
| 105 | 추가: g2 = vmlal_laneq_s16::<3>(g2, vget_low_s16(cr1), coefficients); | |
| 106 | 추가: g3 = vmlal_high_laneq_s16::<3>(g3, cr1, coefficients); | |
| 107 | 추가: | |
| 108 | 추가: let qg0 = vqshrun_n_s32::<14>(g0); | |
| 109 | 추가: let qg1 = vqshrun_n_s32::<14>(g1); | |
| 110 | 추가: let qg2 = vqshrun_n_s32::<14>(g2); | |
| 111 | 추가: let qg3 = vqshrun_n_s32::<14>(g3); | |
| 112 | 추가: | |
| 113 | 추가: let g0 = vqmovn_u16(vcombine_u16(qg0, qg1)); | |
| 114 | 추가: let g1 = vqmovn_u16(vcombine_u16(qg2, qg3)); | |
| 115 | 추가: | |
| 116 | 추가: ( | |
| 117 | 추가: vcombine_u8(r0, r1), | |
| 118 | 추가: vcombine_u8(g0, g1), | |
| 119 | 추가: vcombine_u8(b0, b1) | |
| 120 | 추가: ) | |
| 121 | 추가: } | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: #[inline(always)] | |
| 125 | 추가: pub fn ycbcr_to_rgb_neon( | |
| 126 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 127 | 추가: ) { | |
| 128 | 추가: // call this in another function to tell RUST to vectorize this | |
| 129 | 추가: // storing | |
| 130 | 추가: unsafe { | |
| 131 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 132 | 추가: vst3q_u8(out.as_mut_ptr(), uint8x16x3_t(r, g, b)); | |
| 133 | 추가: *offset += 48; | |
| 134 | 추가: } | |
| 135 | 추가: } | |
| 136 | 추가: | |
| 137 | 추가: #[inline(always)] | |
| 138 | 추가: pub fn ycbcr_to_rgba_neon( | |
| 139 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 140 | 추가: ) { | |
| 141 | 추가: unsafe { | |
| 142 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 143 | 추가: vst4q_u8(out.as_mut_ptr(), uint8x16x4_t(r, g, b, vdupq_n_u8(255))); | |
| 144 | 추가: *offset += 64; | |
| 145 | 추가: } | |
| 146 | 추가: } |
| @@ -0,0 +1,139 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: use core::convert::TryInto; | |
| 10 | 추가: | |
| 11 | 추가: // Bt.601 Full Range inverse coefficients computed with 14 bits of precision with MPFR. | |
| 12 | 추가: // This is important to keep them in i16. | |
| 13 | 추가: // In most cases LLVM will detect what we're doing i16 widening to i32 math and will use | |
| 14 | 추가: // appropriate optimizations. | |
| 15 | 추가: pub(crate) const Y_CF: i16 = 16384; | |
| 16 | 추가: pub(crate) const CR_CF: i16 = 22970; | |
| 17 | 추가: pub(crate) const CB_CF: i16 = 29032; | |
| 18 | 추가: pub(crate) const C_G_CR_COEF_1: i16 = -11700; | |
| 19 | 추가: pub(crate) const C_G_CB_COEF_2: i16 = -5638; | |
| 20 | 추가: pub(crate) const YUV_PREC: i16 = 14; | |
| 21 | 추가: // Rounding const for YUV -> RGB conversion: floating equivalent 0.499(9). | |
| 22 | 추가: pub(crate) const YUV_RND: i16 = (1 << (YUV_PREC - 1)) - 1; | |
| 23 | 추가: | |
| 24 | 추가: /// Limit values to 0 and 255 | |
| 25 | 추가: #[inline] | |
| 26 | 추가: #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, dead_code)] | |
| 27 | 추가: fn clamp(a: i32) -> u8 { | |
| 28 | 추가: a.clamp(0, 255) as u8 | |
| 29 | 추가: } | |
| 30 | 추가: | |
| 31 | 추가: /// YCbCr to RGBA color conversion | |
| 32 | 추가: | |
| 33 | 추가: /// Convert YCbCr to RGB/BGR | |
| 34 | 추가: /// | |
| 35 | 추가: /// Converts to RGB if const BGRA is false | |
| 36 | 추가: /// | |
| 37 | 추가: /// Converts to BGR if const BGRA is true | |
| 38 | 추가: pub fn ycbcr_to_rgba_inner_16_scalar<const BGRA: bool>( | |
| 39 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], output: &mut [u8], pos: &mut usize | |
| 40 | 추가: ) { | |
| 41 | 추가: let (_, output_position) = output.split_at_mut(*pos); | |
| 42 | 추가: | |
| 43 | 추가: // Convert into a slice with 64 elements for Rust to see we won't go out of bounds. | |
| 44 | 추가: let opt: &mut [u8; 64] = output_position | |
| 45 | 추가: .get_mut(0..64) | |
| 46 | 추가: .expect("Slice to small cannot write") | |
| 47 | 추가: .try_into() | |
| 48 | 추가: .unwrap(); | |
| 49 | 추가: for ((&y, (cb, cr)), out) in y | |
| 50 | 추가: .iter() | |
| 51 | 추가: .zip(cb.iter().zip(cr.iter())) | |
| 52 | 추가: .zip(opt.chunks_exact_mut(4)) | |
| 53 | 추가: { | |
| 54 | 추가: let cr = cr - 128; | |
| 55 | 추가: let cb = cb - 128; | |
| 56 | 추가: | |
| 57 | 추가: let y0 = i32::from(y) * i32::from(Y_CF) + i32::from(YUV_RND); | |
| 58 | 추가: | |
| 59 | 추가: let r = (y0 + i32::from(cr) * i32::from(CR_CF)) >> YUV_PREC; | |
| 60 | 추가: let g = (y0 | |
| 61 | 추가: + i32::from(cr) * i32::from(C_G_CR_COEF_1) | |
| 62 | 추가: + i32::from(cb) * i32::from(C_G_CB_COEF_2)) | |
| 63 | 추가: >> YUV_PREC; | |
| 64 | 추가: let b = (y0 + i32::from(cb) * i32::from(CB_CF)) >> YUV_PREC; | |
| 65 | 추가: | |
| 66 | 추가: if BGRA { | |
| 67 | 추가: out[0] = clamp(b); | |
| 68 | 추가: out[1] = clamp(g); | |
| 69 | 추가: out[2] = clamp(r); | |
| 70 | 추가: out[3] = 255; | |
| 71 | 추가: } else { | |
| 72 | 추가: out[0] = clamp(r); | |
| 73 | 추가: out[1] = clamp(g); | |
| 74 | 추가: out[2] = clamp(b); | |
| 75 | 추가: out[3] = 255; | |
| 76 | 추가: } | |
| 77 | 추가: } | |
| 78 | 추가: *pos += 64; | |
| 79 | 추가: } | |
| 80 | 추가: | |
| 81 | 추가: /// Convert YCbCr to RGB/BGR | |
| 82 | 추가: /// | |
| 83 | 추가: /// Converts to RGB if const BGRA is false | |
| 84 | 추가: /// | |
| 85 | 추가: /// Converts to BGR if const BGRA is true | |
| 86 | 추가: pub fn ycbcr_to_rgb_inner_16_scalar<const BGRA: bool>( | |
| 87 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], output: &mut [u8], pos: &mut usize | |
| 88 | 추가: ) { | |
| 89 | 추가: let (_, output_position) = output.split_at_mut(*pos); | |
| 90 | 추가: | |
| 91 | 추가: // Convert into a slice with 48 elements | |
| 92 | 추가: let opt: &mut [u8; 48] = output_position | |
| 93 | 추가: .get_mut(0..48) | |
| 94 | 추가: .expect("Slice to small cannot write") | |
| 95 | 추가: .try_into() | |
| 96 | 추가: .unwrap(); | |
| 97 | 추가: | |
| 98 | 추가: for ((&y, (cb, cr)), out) in y | |
| 99 | 추가: .iter() | |
| 100 | 추가: .zip(cb.iter().zip(cr.iter())) | |
| 101 | 추가: .zip(opt.chunks_exact_mut(3)) | |
| 102 | 추가: { | |
| 103 | 추가: let cr = cr - 128; | |
| 104 | 추가: let cb = cb - 128; | |
| 105 | 추가: | |
| 106 | 추가: let y0 = i32::from(y) * i32::from(Y_CF) + i32::from(YUV_RND); | |
| 107 | 추가: | |
| 108 | 추가: let r = (y0 + i32::from(cr) * i32::from(CR_CF)) >> YUV_PREC; | |
| 109 | 추가: let g = (y0 | |
| 110 | 추가: + i32::from(cr) * i32::from(C_G_CR_COEF_1) | |
| 111 | 추가: + i32::from(cb) * i32::from(C_G_CB_COEF_2)) | |
| 112 | 추가: >> YUV_PREC; | |
| 113 | 추가: let b = (y0 + i32::from(cb) * i32::from(CB_CF)) >> YUV_PREC; | |
| 114 | 추가: | |
| 115 | 추가: if BGRA { | |
| 116 | 추가: out[0] = clamp(b); | |
| 117 | 추가: out[1] = clamp(g); | |
| 118 | 추가: out[2] = clamp(r); | |
| 119 | 추가: } else { | |
| 120 | 추가: out[0] = clamp(r); | |
| 121 | 추가: out[1] = clamp(g); | |
| 122 | 추가: out[2] = clamp(b); | |
| 123 | 추가: } | |
| 124 | 추가: } | |
| 125 | 추가: | |
| 126 | 추가: // Increment pos | |
| 127 | 추가: *pos += 48; | |
| 128 | 추가: } | |
| 129 | 추가: | |
| 130 | 추가: pub fn ycbcr_to_grayscale(y: &[i16], width: usize, padded_width: usize, output: &mut [u8]) { | |
| 131 | 추가: for (y_in, out) in y | |
| 132 | 추가: .chunks_exact(padded_width) | |
| 133 | 추가: .zip(output.chunks_exact_mut(width)) | |
| 134 | 추가: { | |
| 135 | 추가: for (y, out) in y_in.iter().zip(out.iter_mut()) { | |
| 136 | 추가: *out = *y as u8; | |
| 137 | 추가: } | |
| 138 | 추가: } | |
| 139 | 추가: } |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기