team-ljyzipelo

공개

Merge pull request #125 from Team-LJY/features/archive-preview

압축파일 미리보기를 추가한다
작성자
LeeJunyoung
작성 시각
커밋
ecad460b2d3eba5c039fd557c174062fd7edd02c
이 시점의 파일 보기

변경된 파일 78개

+2,550-18

변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.

추가docs/jpeg-decoder-patch.md+24-0
@@ -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 결함이나 향후 권고의 부재를 보장하지 않는다.
수정docs/ui-scenario-guide.md+21-0
@@ -147,3 +147,24 @@ Windows NSIS 제거 프로그램은 앱과 별도의 실행 파일입니다. 이
147147실제 검증은 전용 Windows VM에서 설치와 기본 앱 지정 후 Uninstall.exe를 실행합니다. 설정에서 ZIP의 다른 기본 앱을 선택하고 제거한 뒤 ZIP을 열어야 합니다. 설정을 열지 않고 제거한 경우의 [연결 프로그램] 경로, 취소 시 앱 유지, /S 무인 제거의 창 생략, 사용자가 바꾼 등록 값 보존도 확인합니다. NSIS 컴파일 시험은 이 운영체제 화면 검증을 대신하지 않습니다.
148148
149149Ubuntu 제거 안내는 패키지 관리자 터미널 출력입니다. 이전 기본 앱이 있는 경우, 삭제된 경우, 기록이 없는 경우, 설치 후 다른 앱으로 바꾼 경우와 다른 사용자의 제거를 구분해 확인합니다. 사용자 홈 전체나 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추가: 시나리오의 텍스트와 이미지는 화면 점검용이며 디코더 검증은 실제 압축파일로 별도 수행한다.
수정experiments/rust-archive-worker/Cargo.lock+96-0
@@ -2,6 +2,12 @@
22# It is not intended for manual editing.
33version = 4
44
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추가:
511[[package]]
612name = "aes"
713version = "0.8.4"
@@ -14,6 +20,12 @@ dependencies = [
1420 "zeroize",
1521]
1622
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추가:
1729[[package]]
1830name = "block-buffer"
1931version = "0.10.4"
@@ -81,6 +93,15 @@ dependencies = [
8193 "libc",
8294]
8395
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추가:
84105[[package]]
85106name = "crypto-common"
86107version = "0.1.7"
@@ -122,6 +143,26 @@ dependencies = [
122143 "crypto-common 0.2.2",
123144]
124145
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추가:
125166[[package]]
126167name = "generic-array"
127168version = "0.14.7"
@@ -180,6 +221,26 @@ dependencies = [
180221 "sha2 0.11.1",
181222]
182223
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추가:
183244[[package]]
184245name = "pbkdf2"
185246version = "0.12.2"
@@ -190,6 +251,19 @@ dependencies = [
190251 "hmac",
191252]
192253
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추가:
193267[[package]]
194268name = "sha1"
195269version = "0.10.7"
@@ -223,6 +297,12 @@ dependencies = [
223297 "digest 0.11.3",
224298]
225299
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추가:
226306[[package]]
227307name = "subtle"
228308version = "2.6.1"
@@ -256,11 +336,21 @@ dependencies = [
256336 "hmac",
257337 "lzma-rust2",
258338 "pbkdf2",
339추가: "png",
259340 "sha1",
260341 "sha2 0.10.9",
261342 "subtle",
262343 "zeroize",
344추가: "zipelo-jpeg",
263345 "zlib-rs",
346추가: "zune-core",
347추가: ]
348추가:
349추가: [[package]]
350추가: name = "zipelo-jpeg"
351추가: version = "0.5.15"
352추가: dependencies = [
353추가: "zune-core",
264354]
265355
266356[[package]]
@@ -268,3 +358,9 @@ name = "zlib-rs"
268358version = "0.6.8"
269359source = "registry+https://github.com/rust-lang/crates.io-index"
270360checksum = "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"
수정experiments/rust-archive-worker/Cargo.toml+4-0
@@ -7,6 +7,9 @@ publish = false
77autotests = false
88
99[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"] }
1013bzip2 = "=0.6.1"
1114lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] }
1215aes = { version = "=0.8.4", features = ["zeroize"] }
@@ -19,6 +22,7 @@ sha2 = "=0.10.9"
1922zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] }
2023
2124[workspace]
25추가: exclude = ["vendor/zune-jpeg"]
2226
2327[[test]]
2428name = "archive_worker"
수정experiments/rust-archive-worker/README.md+46-0
@@ -129,3 +129,49 @@ Python 표준 bz2, lzma와 tarfile로 독립 생성 및 해제한 결과의 SHA2
129129직접 의존성은 기존 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을 수정 버전으로 명시합니다. 선택 버전은 이 수정 범위에 들어갑니다. 이는 전체 전이 의존성의 취약점 부재나 완전한 보안 감사를 의미하지 않습니다.
130130
131131암호 구현에 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개 큐 역압과 디코딩 및 전송 중 취소, 늦은 완료 폐기와 정리 및 원본 해시 보존을 포함한다.
수정experiments/rust-archive-worker/src/lib.rs+1-0
@@ -6,6 +6,7 @@ mod crypto;
66pub mod filesystem;
77mod lzma;
88mod parent;
9추가: mod preview;
910pub mod protocol;
1011pub mod resources;
1112pub mod runtime;
추가experiments/rust-archive-worker/src/preview.rs+399-0
@@ -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;
수정experiments/rust-archive-worker/src/protocol.rs+64-1
@@ -1,5 +1,12 @@
11use std::path::{Path, PathBuf};
22
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추가:
310#[derive(Clone, Debug, PartialEq, Eq)]
411pub enum NativePath {
512 Unix(Vec<u8>),
@@ -96,7 +103,12 @@ impl GuardedStart {
96103 && self.ceiling.output <= 64 * 1024 * 1024 * 1024
97104 && self.ceiling.entries >= self.start.limits.entries
98105 && 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)
100112 }
101113}
102114#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -185,12 +197,18 @@ pub enum Action {
185197 method: Method,
186198 encryption: Encryption,
187199 },
200추가: Preview {
201추가: archive: NativePath,
202추가: entry_id: u32,
203추가: list_id: ListId,
204추가: },
188205}
189206#[derive(Clone, Copy, Debug, PartialEq, Eq)]
190207pub enum ActionKind {
191208 List,
192209 Extract,
193210 CreateZip,
211추가: Preview,
194212}
195213impl Action {
196214 pub fn kind(&self) -> ActionKind {
@@ -198,6 +216,7 @@ impl Action {
198216 Self::List { .. } => ActionKind::List,
199217 Self::Extract { .. } => ActionKind::Extract,
200218 Self::CreateZip { .. } => ActionKind::CreateZip,
219추가: Self::Preview { .. } => ActionKind::Preview,
201220 }
202221 }
203222}
@@ -223,6 +242,39 @@ pub struct Entry {
223242 pub encrypted: bool,
224243}
225244#[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)]
226278pub enum Stage {
227279 Scan,
228280 Read,
@@ -374,6 +426,17 @@ pub enum Message {
374426 relative_name: String,
375427 disposition: Disposition,
376428 },
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추가: },
377440 Terminal(Terminal),
378441 CancelAck {
379442 request_sequence: u64,
수정experiments/rust-archive-worker/src/runtime.rs+141-0
@@ -352,6 +352,140 @@ impl<W: Write> Job<W> {
352352 }
353353 Ok(())
354354 }
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추가: }
355489 fn run(&mut self, start: Start) -> Result<()> {
356490 if !start.limits.valid() {
357491 return Err(ErrorCode::InvalidRequest);
@@ -649,6 +783,13 @@ impl<W: Write> Job<W> {
649783 }
650784 }
651785 }
786추가: Action::Preview {
787추가: archive,
788추가: entry_id,
789추가: list_id,
790추가: } => {
791추가: self.preview(archive, entry_id, list_id, limits)?;
792추가: }
652793 Action::CreateZip {
653794 sources,
654795 output_file,
수정experiments/rust-archive-worker/src/seven_zip.rs+38-11
@@ -306,18 +306,28 @@ impl Streams {
306306 input: &mut std::fs::File,
307307 ranges: &[(u64, u64)],
308308 output: &mut std::fs::File,
309추가: selected: Option<usize>,
309310 check: &mut impl crate::resources::Monitor,
310311 ) -> Result<()> {
311312 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추가: })?;
318324 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() {
320326 check.check()?;
327추가: if selected.is_some_and(|id| id != index) {
328추가: crate::resources::completed(Ok(()), check)?;
329추가: continue;
330추가: }
321331 let base = output.stream_position().map_err(crate::space::io_error)?;
322332 check.observe(
323333 ResourceUsage {
@@ -584,6 +594,16 @@ pub(crate) fn open(
584594 limits: Limits,
585595 decode: bool,
586596 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,
587607) -> Result<crate::streaming::Catalog> {
588608 use std::io::{Read, Seek, SeekFrom};
589609 check.check()?;
@@ -652,6 +672,7 @@ pub(crate) fn open(
652672 input,
653673 &ranges,
654674 &mut data,
675추가: None,
655676 &mut crate::resources::MetadataMonitor(check),
656677 )?;
657678 data_end = 32u64
@@ -725,9 +746,15 @@ pub(crate) fn open(
725746 let ranges = streams.ranges(input, data_end, check)?;
726747 let mut at = 0u64;
727748 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;
729752 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추가: }
731758 at = at.checked_add(*size as u64).ok_or(ErrorCode::Limit)?;
732759 crate::resources::completed(Ok(()), check)?;
733760 }
@@ -735,8 +762,8 @@ pub(crate) fn open(
735762 if at > limits.output {
736763 return Err(ErrorCode::Limit);
737764 }
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)?;
740767 }
741768 }
742769 Ok(crate::streaming::Catalog {
수정experiments/rust-archive-worker/src/streaming.rs+35-4
@@ -53,18 +53,39 @@ impl Catalog {
5353 decode: bool,
5454 password: Option<&[u8]>,
5555 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,
5677 ) -> Result<Self> {
5778 let mut magic = [0; 6];
5879 let n = len.min(6) as usize;
5980 at(source, 0, &mut magic[..n])?;
6081 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);
6283 }
6384 if magic.starts_with(b"PK\x03\x04")
6485 || magic.starts_with(b"PK\x05\x06")
6586 || magic.starts_with(b"PK\x06\x06")
6687 {
67삭제: return zip(source, len, limits, decode, password, check);
88추가: return zip(source, len, limits, decode, password, selected, check);
6889 }
6990 let compression = if magic.starts_with(b"BZh") {
7091 Some(crate::compressed_tar::Compression::Bzip2)
@@ -425,6 +446,7 @@ fn zip(
425446 limits: Limits,
426447 decode: bool,
427448 password: Option<&[u8]>,
449추가: selected: Option<u32>,
428450 check: &mut impl crate::resources::Monitor,
429451) -> Result<Catalog> {
430452 if len < 22 {
@@ -712,13 +734,22 @@ fn zip(
712734 )?;
713735 let mut data = spool::temporary()?;
714736 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)?;
716747 }
717748 let mut offsets = Vec::new();
718749 for (member, packed) in members.iter().zip(packed) {
719750 check.check()?;
720751 offsets.push(io(data.stream_position())?);
721삭제: if !decode {
752추가: if !decode || selected.is_some_and(|id| id != member.entry.entry_id) {
722753 crate::resources::completed(Ok(()), check)?;
723754 continue;
724755 }
수정experiments/rust-archive-worker/src/wire.rs+119-2
@@ -138,7 +138,8 @@ macro_rules! enumeration { ($t:ident {$($v:ident=$n:expr),*$(,)?}) => { impl Wir
138138enumeration!(Format{Zip=0,Tar=1,Gzip=2,TarGzip=3,SevenZip=4});
139139enumeration!(Method{Store=0,Deflate=1});
140140enumeration!(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});
142143enumeration!(EntryKind{File=0,Directory=1,Link=2,Other=3});
143144enumeration!(Stage{Scan=0,Read=1,Decode=2,Write=3,Verify=4,Commit=5});
144145enumeration!(Disposition{Created=0,PartialRetained=1,Removed=2,CommitUncertain=3});
@@ -166,6 +167,31 @@ structure!(ListId {
166167 archive_bytes,
167168 archive_sha256
168169});
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추가: }
169195structure!(Source { path, archive_name });
170196structure!(Start { action, limits });
171197structure!(GuardedStart {
@@ -309,6 +335,16 @@ impl Wire for Action {
309335 method.enc(e)?;
310336 encryption.enc(e)
311337 }
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추가: }
312348 }
313349 }
314350 fn dec(d: &mut Decoder<'_>) -> io::Result<Self> {
@@ -329,10 +365,21 @@ impl Wire for Action {
329365 method: Wire::dec(d)?,
330366 encryption: Wire::dec(d)?,
331367 }),
368추가: 3 => Ok(Self::Preview {
369추가: archive: Wire::dec(d)?,
370추가: entry_id: Wire::dec(d)?,
371추가: list_id: Wire::dec(d)?,
372추가: }),
332373 _ => Err(invalid()),
333374 }
334375 }
335376}
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추가: }
336383impl Message {
337384 fn encode(&self) -> io::Result<(u16, Vec<u8>)> {
338385 let mut e = Encoder {
@@ -341,6 +388,9 @@ impl Message {
341388 };
342389 let kind = match self {
343390 Self::Start(v) => {
391추가: if matches!(v.action, Action::Preview { .. }) {
392추가: return Err(invalid());
393추가: }
344394 v.enc(&mut e)?;
345395 1
346396 }
@@ -456,6 +506,37 @@ impl Message {
456506 disposition.enc(&mut e)?;
457507 105
458508 }
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추가: }
459540 Self::Terminal(v) => {
460541 if v.detail.len() > 4096 {
461542 return Err(invalid());
@@ -509,7 +590,13 @@ impl Message {
509590 },
510591 };
511592 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추가: }
513600 2 => {
514601 let challenge_id = Wire::dec(&mut d)?;
515602 let secret = Secret(Vec::<u8>::dec(&mut d)?);
@@ -585,6 +672,36 @@ impl Message {
585672 relative_name: Wire::dec(&mut d)?,
586673 disposition: Wire::dec(&mut d)?,
587674 },
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추가: }
588705 106 => {
589706 let t = Terminal::dec(&mut d)?;
590707 if t.detail.len() > 4096 {
추가experiments/rust-archive-worker/vendor/zune-jpeg/Cargo.toml+28-0
@@ -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)"]
추가experiments/rust-archive-worker/vendor/zune-jpeg/LICENSE-MIT+21-0
@@ -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.
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/bitstream.rs+829-0
@@ -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추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/color_convert.rs+102-0
@@ -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추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/color_convert/avx.rs+297-0
@@ -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추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/color_convert/neon64.rs+146-0
@@ -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추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/color_convert/scalar.rs+139-0
@@ -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추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/components.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/decoder.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/errors.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/headers.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/huffman.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/idct.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/idct/avx2.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/idct/neon.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/idct/scalar.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/lib.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/marker.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/mcu.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/mcu_prog.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/misc.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/unsafe_utils.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/unsafe_utils_avx2.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/unsafe_utils_neon.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/upsampler.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/upsampler/avx2.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/upsampler/neon.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/upsampler/portable_simd.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/upsampler/scalar.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/worker.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/Cargo.toml

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_process.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_screen.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_theme.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정experiments/rust-ui-memory-app/src/archive_ui.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가experiments/rust-ui-memory-app/src/assets/icons/preview-file.svg

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정packaging/licenses.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/release-packages/test_preview_licenses.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-real-worker/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-real-worker/flows.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-real-worker/preview_catalog.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/capture.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/fake.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-app-ui/preview.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/regressions.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/scenario_tests.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/scenarios.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-app-ui/toolbar.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/fixtures/preview-baseline.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-cmyk.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-gray.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-progressive.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-rows-baseline.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-rows-cmyk.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-rows-gray.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-rows-progressive.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
추가tests/rust-archive-worker/fixtures/preview-rows-restart.jpg

바이너리 파일이라 Diff를 표시하지 않아요.

파일 내려받기
수정tests/rust-archive-worker/guarded.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-archive-worker/main.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/preview_cases.py

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/preview_decode.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/preview_runtime.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
추가tests/rust-archive-worker/preview_wire.rs

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-large-archive-fixtures/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기
수정tests/rust-zip64-compat/Cargo.lock

Diff가 표시 한도를 넘어서 생략했어요.

Raw로 열기