team-ljyzipelo

공개

불완전한 JPEG 미리보기를 거부한다

작성자
시로사키 하나
작성 시각
커밋
eec6a778f9483e0b4d30e35896e37f5ebeca03bf
부모
f951b60
이 시점의 파일 보기

변경된 파일 47개

+2,746-12

변경 내용이 커서 일부 파일의 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 결함이나 향후 권고의 부재를 보장하지 않는다.
수정experiments/rust-archive-worker/Cargo.lock+8-10
@@ -341,9 +341,16 @@ dependencies = [
341341 "sha2 0.10.9",
342342 "subtle",
343343 "zeroize",
344추가: "zipelo-jpeg",
344345 "zlib-rs",
345346 "zune-core",
346삭제: "zune-jpeg",
347추가: ]
348추가:
349추가: [[package]]
350추가: name = "zipelo-jpeg"
351추가: version = "0.5.15"
352추가: dependencies = [
353추가: "zune-core",
347354]
348355
349356[[package]]
@@ -357,12 +364,3 @@ name = "zune-core"
357364version = "0.5.3"
358365source = "registry+https://github.com/rust-lang/crates.io-index"
359366checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b"
360삭제:
361삭제: [[package]]
362삭제: name = "zune-jpeg"
363삭제: version = "0.5.15"
364삭제: source = "registry+https://github.com/rust-lang/crates.io-index"
365삭제: checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296"
366삭제: dependencies = [
367삭제: "zune-core",
368삭제: ]
수정experiments/rust-archive-worker/Cargo.toml+2-1
@@ -8,7 +8,7 @@ autotests = false
88
99[dependencies]
1010png = "=0.18.1"
11삭제: zune-jpeg = { version = "=0.5.15", default-features = false, features = ["std"] }
11추가: zune-jpeg = { package = "zipelo-jpeg", path = "vendor/zune-jpeg", default-features = false, features = ["std"] }
1212zune-core = { version = "=0.5.3", default-features = false, features = ["std"] }
1313bzip2 = "=0.6.1"
1414lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] }
@@ -22,6 +22,7 @@ sha2 = "=0.10.9"
2222zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] }
2323
2424[workspace]
25추가: exclude = ["vendor/zune-jpeg"]
2526
2627[[test]]
2728name = "archive_worker"
수정experiments/rust-archive-worker/src/preview.rs+52-1
@@ -240,6 +240,9 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P
240240 let mut scanning = false;
241241 let mut info = None;
242242 let mut seen_scan = false;
243추가: let mut components = Vec::new();
244추가: let mut decoded_components = 0u8;
245추가: let mut progressive = false;
243246 while at < source.len() {
244247 check.check()?;
245248 if scanning {
@@ -258,7 +261,12 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P
258261 at += 1;
259262 match marker {
260263 0 | 0xd0..=0xd7 if scanning => continue,
261삭제: 0xd9 if at == source.len() && seen_scan => return info.ok_or(ErrorCode::Integrity),
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추가: }
262270 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity),
263271 1 => continue,
264272 _ => {}
@@ -277,6 +285,17 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P
277285 if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 {
278286 return Err(ErrorCode::UnsupportedFeature);
279287 }
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추가: }
280299 info = Some(rgba_info(
281300 entry_id,
282301 u32::from(u16::from_be_bytes(body[3..5].try_into().unwrap())),
@@ -287,6 +306,38 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P
287306 return Err(ErrorCode::UnsupportedFeature);
288307 }
289308 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추가: }
290341 seen_scan |= scanning;
291342 at = end;
292343 check.activity()?;
추가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+232-0
@@ -0,0 +1,232 @@
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추가: //! This module exports a single struct to store information about
10추가: //! JPEG image components
11추가: //!
12추가: //! The data is extracted from a SOF header.
13추가:
14추가: use alloc::vec::Vec;
15추가: use alloc::{format, vec};
16추가:
17추가: use zune_core::log::trace;
18추가:
19추가: use crate::alloc::string::ToString;
20추가: use crate::decoder::MAX_COMPONENTS;
21추가: use crate::errors::DecodeErrors;
22추가: use crate::upsampler::upsample_no_op;
23추가: const MAX_SAMP_FACTOR: usize = 4;
24추가:
25추가: /// Represents an up-sampler function, this function will be called to upsample
26추가: /// a down-sampled image
27추가:
28추가: pub type UpSampler = fn(
29추가: input: &[i16],
30추가: in_near: &[i16],
31추가: in_far: &[i16],
32추가: scratch_space: &mut [i16],
33추가: output: &mut [i16]
34추가: );
35추가:
36추가: /// Component Data from start of frame
37추가: #[derive(Clone)]
38추가: pub(crate) struct Components {
39추가: /// The type of component that has the metadata below, can be Y,Cb or Cr
40추가: pub component_id: ComponentID,
41추가: /// Sub-sampling ratio of this component in the x-plane
42추가: pub vertical_sample: usize,
43추가: /// Sub-sampling ratio of this component in the y-plane
44추가: pub horizontal_sample: usize,
45추가: /// DC huffman table position
46추가: pub dc_huff_table: usize,
47추가: /// AC huffman table position for this element.
48추가: pub ac_huff_table: usize,
49추가: /// Quantization table number
50추가: pub quantization_table_number: u8,
51추가: /// Specifies quantization table to use with this component
52추가: pub quantization_table: [i32; 64],
53추가: /// dc prediction for the component
54추가: pub dc_pred: i32,
55추가: /// An up-sampling function, can be basic or SSE, depending
56추가: /// on the platform
57추가: pub up_sampler: UpSampler,
58추가: /// How pixels do we need to go to get to the next line?
59추가: pub width_stride: usize,
60추가: /// Component ID for progressive
61추가: pub id: u8,
62추가: /// Whether we need to decode this image component.
63추가: pub needed: bool,
64추가: /// Upsample scanline
65추가: pub raw_coeff: Vec<i16>,
66추가: /// Upsample destination, stores a scanline worth of sub sampled data
67추가: pub upsample_dest: Vec<i16>,
68추가: /// previous row, used to handle MCU boundaries
69추가: pub row_up: Vec<i16>,
70추가: /// current row, used to handle MCU boundaries again
71추가: pub row: Vec<i16>,
72추가: pub first_row_upsample_dest: Vec<i16>,
73추가: pub idct_pos: usize,
74추가: pub x: usize,
75추가: pub w2: usize,
76추가: pub y: usize,
77추가: pub sample_ratio: SampleRatios,
78추가: // a very annoying bug
79추가: pub fix_an_annoying_bug: usize
80추가: }
81추가:
82추가: impl Components {
83추가: /// Create a new instance from three bytes from the start of frame
84추가: #[inline]
85추가: pub fn from(a: [u8; 3], pos: u8) -> Result<Components, DecodeErrors> {
86추가: // it's a unique identifier.
87추가: // doesn't have to be ascending
88추가: // see tests/inputs/huge_sof_number
89추가: //
90추가: // For such cases, use the position of the component
91추가: // to determine width
92추가:
93추가: let id = match pos {
94추가: 0 => ComponentID::Y,
95추가: 1 => ComponentID::Cb,
96추가: 2 => ComponentID::Cr,
97추가: 3 => ComponentID::Q,
98추가: _ => {
99추가: return Err(DecodeErrors::Format(format!(
100추가: "Unknown component id found,{pos}, expected value between 1 and 4"
101추가: )))
102추가: }
103추가: };
104추가:
105추가: let horizontal_sample = (a[1] >> 4) as usize;
106추가: let vertical_sample = (a[1] & 0x0f) as usize;
107추가: // Match libjpeg turbo on checking for sampling factors
108추가: // Reject anything above 4
109추가: if horizontal_sample > MAX_SAMP_FACTOR {
110추가: return Err(DecodeErrors::Format(format!(
111추가: "Bogus Horizontal Sampling Factor {horizontal_sample}"
112추가: )));
113추가: }
114추가: if vertical_sample > MAX_SAMP_FACTOR {
115추가: return Err(DecodeErrors::Format(format!(
116추가: "Bogus Vertical Sampling Factor {vertical_sample}"
117추가: )));
118추가: }
119추가:
120추가: let quantization_table_number = a[2];
121추가: // confirm quantization number is between 0 and MAX_COMPONENTS
122추가: if usize::from(quantization_table_number) >= MAX_COMPONENTS {
123추가: return Err(DecodeErrors::Format(format!(
124추가: "Too large quantization number :{quantization_table_number}, expected value between 0 and {MAX_COMPONENTS}"
125추가: )));
126추가: }
127추가: // check that upsampling ratios are powers of two
128추가: // if these fail, it's probably a corrupt image.
129추가: if !horizontal_sample.is_power_of_two() {
130추가: return Err(DecodeErrors::Format(format!(
131추가: "Horizontal sample is not a power of two({horizontal_sample}) cannot decode"
132추가: )));
133추가: }
134추가:
135추가: // if !vertical_sample.is_power_of_two() {
136추가: // return Err(DecodeErrors::Format(format!(
137추가: // "Vertical sub-sample is not power of two({vertical_sample}) cannot decode"
138추가: // )));
139추가: // }
140추가: if vertical_sample == 0 {
141추가: // Check for invalid vertical sample
142추가: return Err(DecodeErrors::Format("Vertical sample is zero".to_string()));
143추가: }
144추가: trace!(
145추가: "Component ID:{:?} \tHS:{} VS:{} QT:{}",
146추가: id,
147추가: horizontal_sample,
148추가: vertical_sample,
149추가: quantization_table_number
150추가: );
151추가:
152추가: Ok(Components {
153추가: component_id: id,
154추가: vertical_sample,
155추가: horizontal_sample,
156추가: quantization_table_number,
157추가: first_row_upsample_dest: vec![],
158추가: // These two will be set with sof marker
159추가: dc_huff_table: 0,
160추가: ac_huff_table: 0,
161추가: quantization_table: [0; 64],
162추가: dc_pred: 0,
163추가: up_sampler: upsample_no_op,
164추가: // set later
165추가: width_stride: horizontal_sample,
166추가: id: a[0],
167추가: needed: true,
168추가: raw_coeff: vec![],
169추가: upsample_dest: vec![],
170추가: row_up: vec![],
171추가: row: vec![],
172추가: idct_pos: 0,
173추가: x: 0,
174추가: y: 0,
175추가: w2: 0,
176추가: sample_ratio: SampleRatios::None,
177추가: fix_an_annoying_bug: 1
178추가: })
179추가: }
180추가: /// Setup space for upsampling
181추가: ///
182추가: /// During upsample, we need a reference of the last row so that upsampling can
183추가: /// proceed correctly,
184추가: /// so we store the last line of every scanline and use it for the next upsampling procedure
185추가: /// to store this, but since we don't need it for 1v1 upsampling,
186추가: /// we only call this for routines that need upsampling
187추가: ///
188추가: /// # Requirements
189추가: /// - width stride of this element is set for the component.
190추가: pub fn setup_upsample_scanline(&mut self) {
191추가: self.row = vec![0; self.width_stride * self.vertical_sample];
192추가: self.row_up = vec![0; self.width_stride * self.vertical_sample];
193추가: self.first_row_upsample_dest =
194추가: vec![128; self.vertical_sample * self.width_stride * self.sample_ratio.sample()];
195추가: self.upsample_dest =
196추가: vec![0; self.width_stride * self.sample_ratio.sample() * self.fix_an_annoying_bug * 8];
197추가: }
198추가: }
199추가:
200추가: /// Component ID's
201추가: #[derive(Copy, Debug, Clone, PartialEq, Eq)]
202추가: pub enum ComponentID {
203추가: /// Luminance channel
204추가: Y,
205추가: /// Blue chrominance
206추가: Cb,
207추가: /// Red chrominance
208추가: Cr,
209추가: /// Q or fourth component
210추가: Q
211추가: }
212추가:
213추가: #[derive(Copy, Debug, Clone, PartialEq, Eq, Default)]
214추가: pub enum SampleRatios {
215추가: HV,
216추가: V,
217추가: H,
218추가: Generic(usize, usize),
219추가: #[default]
220추가: None
221추가: }
222추가:
223추가: impl SampleRatios {
224추가: pub fn sample(self) -> usize {
225추가: match self {
226추가: SampleRatios::HV => 4,
227추가: SampleRatios::V | SampleRatios::H => 2,
228추가: SampleRatios::Generic(a, b) => a * b,
229추가: SampleRatios::None => 1
230추가: }
231추가: }
232추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/decoder.rs

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

Raw로 열기
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/errors.rs+167-0
@@ -0,0 +1,167 @@
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추가: //! Contains most common errors that may be encountered in decoding a Decoder
10추가: //! image
11추가:
12추가: use alloc::string::String;
13추가: use core::fmt::{Debug, Display, Formatter};
14추가:
15추가: use zune_core::bytestream::ZByteIoError;
16추가:
17추가: use crate::misc::{
18추가: START_OF_FRAME_EXT_AR, START_OF_FRAME_EXT_SEQ, START_OF_FRAME_LOS_SEQ,
19추가: START_OF_FRAME_LOS_SEQ_AR, START_OF_FRAME_PROG_DCT_AR
20추가: };
21추가:
22추가: /// Common Decode errors
23추가: #[allow(clippy::module_name_repetitions)]
24추가: pub enum DecodeErrors {
25추가: /// Any other thing we do not know
26추가: Format(String),
27추가: /// Any other thing we do not know but we
28추가: /// don't need to allocate space on the heap
29추가: FormatStatic(&'static str),
30추가: /// Illegal Magic Bytes
31추가: IllegalMagicBytes(u16),
32추가: /// problems with the Huffman Tables in a Decoder file
33추가: HuffmanDecode(String),
34추가: /// Image has zero width
35추가: ZeroError,
36추가: /// Discrete Quantization Tables error
37추가: DqtError(String),
38추가: /// Start of scan errors
39추가: SosError(String),
40추가: /// Start of frame errors
41추가: SofError(String),
42추가: /// UnsupportedImages
43추가: Unsupported(UnsupportedSchemes),
44추가: /// MCU errors
45추가: MCUError(String),
46추가: /// Exhausted data
47추가: ExhaustedData,
48추가: /// Large image dimensions(Corrupted data)?
49추가: LargeDimensions(usize),
50추가: /// Too small output for size
51추가: TooSmallOutput(usize, usize),
52추가:
53추가: IoErrors(ZByteIoError)
54추가: }
55추가:
56추가: #[cfg(feature = "std")]
57추가: impl std::error::Error for DecodeErrors {}
58추가:
59추가: impl From<&'static str> for DecodeErrors {
60추가: fn from(data: &'static str) -> Self {
61추가: return Self::FormatStatic(data);
62추가: }
63추가: }
64추가:
65추가: impl From<ZByteIoError> for DecodeErrors {
66추가: fn from(data: ZByteIoError) -> Self {
67추가: return Self::IoErrors(data);
68추가: }
69추가: }
70추가: impl Debug for DecodeErrors {
71추가: fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
72추가: match &self
73추가: {
74추가: Self::Format(ref a) => write!(f, "{a:?}"),
75추가: Self::FormatStatic(a) => write!(f, "{:?}", &a),
76추가:
77추가: Self::HuffmanDecode(ref reason) =>
78추가: {
79추가: write!(f, "Error decoding huffman values: {reason}")
80추가: }
81추가: Self::ZeroError => write!(f, "Image width or height is set to zero, cannot continue"),
82추가: Self::DqtError(ref reason) => write!(f, "Error parsing DQT segment. Reason:{reason}"),
83추가: Self::SosError(ref reason) => write!(f, "Error parsing SOS Segment. Reason:{reason}"),
84추가: Self::SofError(ref reason) => write!(f, "Error parsing SOF segment. Reason:{reason}"),
85추가: Self::IllegalMagicBytes(bytes) =>
86추가: {
87추가: write!(f, "Error parsing image. Illegal start bytes:{bytes:X}")
88추가: }
89추가: Self::MCUError(ref reason) => write!(f, "Error in decoding MCU. Reason {reason}"),
90추가: Self::Unsupported(ref image_type) =>
91추가: {
92추가: write!(f, "{image_type:?}")
93추가: }
94추가: Self::ExhaustedData => write!(f, "Exhausted data in the image"),
95추가: Self::LargeDimensions(ref dimensions) => write!(
96추가: f,
97추가: "Too large dimensions {dimensions},library supports up to {}", crate::decoder::MAX_DIMENSIONS
98추가: ),
99추가: Self::TooSmallOutput(expected, found) => write!(f, "Too small output, expected buffer with at least {expected} bytes but got one with {found} bytes"),
100추가: Self::IoErrors(error)=>write!(f,"I/O errors {error:?}"),
101추가: }
102추가: }
103추가: }
104추가:
105추가: impl Display for DecodeErrors {
106추가: fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
107추가: write!(f, "{self:?}")
108추가: }
109추가: }
110추가:
111추가: /// Contains Unsupported/Yet-to-be supported Decoder image encoding types.
112추가: #[derive(Eq, PartialEq, Copy, Clone)]
113추가: pub enum UnsupportedSchemes {
114추가: /// SOF_1 Extended sequential DCT,Huffman coding
115추가: ExtendedSequentialHuffman,
116추가: /// Lossless (sequential), huffman coding,
117추가: LosslessHuffman,
118추가: /// Extended sequential DEC, arithmetic coding
119추가: ExtendedSequentialDctArithmetic,
120추가: /// Progressive DCT, arithmetic coding,
121추가: ProgressiveDctArithmetic,
122추가: /// Lossless ( sequential), arithmetic coding
123추가: LosslessArithmetic
124추가: }
125추가:
126추가: impl Debug for UnsupportedSchemes {
127추가: fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
128추가: match &self {
129추가: Self::ExtendedSequentialHuffman => {
130추가: write!(f, "The library cannot yet decode images encoded using Extended Sequential Huffman encoding scheme yet.")
131추가: }
132추가: Self::LosslessHuffman => {
133추가: write!(f, "The library cannot yet decode images encoded with Lossless Huffman encoding scheme")
134추가: }
135추가: Self::ExtendedSequentialDctArithmetic => {
136추가: write!(f,"The library cannot yet decode Images Encoded with Extended Sequential DCT Arithmetic scheme")
137추가: }
138추가: Self::ProgressiveDctArithmetic => {
139추가: write!(f,"The library cannot yet decode images encoded with Progressive DCT Arithmetic scheme")
140추가: }
141추가: Self::LosslessArithmetic => {
142추가: write!(f,"The library cannot yet decode images encoded with Lossless Arithmetic encoding scheme")
143추가: }
144추가: }
145추가: }
146추가: }
147추가:
148추가: impl UnsupportedSchemes {
149추가: #[must_use]
150추가: /// Create an unsupported scheme from an integer
151추가: ///
152추가: /// # Returns
153추가: /// `Some(UnsupportedScheme)` if the int refers to a specific scheme,
154추가: /// otherwise returns `None`
155추가: pub fn from_int(int: u8) -> Option<UnsupportedSchemes> {
156추가: let int = u16::from_be_bytes([0xff, int]);
157추가:
158추가: match int {
159추가: START_OF_FRAME_PROG_DCT_AR => Some(Self::ProgressiveDctArithmetic),
160추가: START_OF_FRAME_LOS_SEQ => Some(Self::LosslessHuffman),
161추가: START_OF_FRAME_LOS_SEQ_AR => Some(Self::LosslessArithmetic),
162추가: START_OF_FRAME_EXT_SEQ => Some(Self::ExtendedSequentialHuffman),
163추가: START_OF_FRAME_EXT_AR => Some(Self::ExtendedSequentialDctArithmetic),
164추가: _ => None
165추가: }
166추가: }
167추가: }
추가experiments/rust-archive-worker/vendor/zune-jpeg/src/headers.rs+699-0
@@ -0,0 +1,699 @@
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추가: //! Decode Decoder markers/segments
10추가: //!
11추가: //! This file deals with decoding header information in a jpeg file
12추가: //!
13추가: use alloc::format;
14추가: use alloc::string::ToString;
15추가: use alloc::vec::Vec;
16추가:
17추가: use zune_core::bytestream::ZByteReaderTrait;
18추가: use zune_core::colorspace::ColorSpace;
19추가: use zune_core::log::{debug, trace, warn};
20추가:
21추가: use core::cmp::max;
22추가:
23추가: use crate::components::{Components, SampleRatios};
24추가: use crate::decoder::{ExtendedXmpSegment, GainMapInfo, ICCChunk, JpegDecoder, MAX_COMPONENTS};
25추가: use crate::errors::DecodeErrors;
26추가: use crate::huffman::HuffmanTable;
27추가: use crate::misc::{SOFMarkers, UN_ZIGZAG};
28추가:
29추가: ///**B.2.4.2 Huffman table-specification syntax**
30추가: #[allow(clippy::similar_names, clippy::cast_sign_loss)]
31추가: pub(crate) fn parse_huffman<T: ZByteReaderTrait>(
32추가: decoder: &mut JpegDecoder<T>
33추가: ) -> Result<(), DecodeErrors>
34추가: where
35추가: {
36추가: // Read the length of the Huffman table
37추가: let mut dht_length = i32::from(decoder.stream.get_u16_be_err()?.checked_sub(2).ok_or(
38추가: DecodeErrors::FormatStatic("Invalid Huffman length in image")
39추가: )?);
40추가:
41추가: while dht_length > 16 {
42추가: // HT information
43추가: let ht_info = decoder.stream.read_u8_err()?;
44추가: // third bit indicates whether the huffman encoding is DC or AC type
45추가: let dc_or_ac = (ht_info >> 4) & 0xF;
46추가: // Indicate the position of this table, should be less than 4;
47추가: let index = (ht_info & 0xF) as usize;
48추가: // read the number of symbols
49추가: let mut num_symbols: [u8; 17] = [0; 17];
50추가:
51추가: if index >= MAX_COMPONENTS {
52추가: return Err(DecodeErrors::HuffmanDecode(format!(
53추가: "Invalid DHT index {index}, expected between 0 and 3"
54추가: )));
55추가: }
56추가:
57추가: if dc_or_ac > 1 {
58추가: return Err(DecodeErrors::HuffmanDecode(format!(
59추가: "Invalid DHT position {dc_or_ac}, should be 0 or 1"
60추가: )));
61추가: }
62추가:
63추가: decoder.stream.read_exact_bytes(&mut num_symbols[1..17])?;
64추가:
65추가: dht_length -= 1 + 16;
66추가:
67추가: let symbols_sum: i32 = num_symbols.iter().map(|f| i32::from(*f)).sum();
68추가:
69추가: // The sum of the number of symbols cannot be greater than 256;
70추가: if symbols_sum > 256 {
71추가: return Err(DecodeErrors::FormatStatic(
72추가: "Encountered Huffman table with excessive length in DHT"
73추가: ));
74추가: }
75추가: if symbols_sum > dht_length {
76추가: return Err(DecodeErrors::HuffmanDecode(format!(
77추가: "Excessive Huffman table of length {symbols_sum} found when header length is {dht_length}"
78추가: )));
79추가: }
80추가: dht_length -= symbols_sum;
81추가: // A table containing symbols in increasing code length
82추가: let mut symbols = [0; 256];
83추가:
84추가: decoder
85추가: .stream
86추가: .read_exact_bytes(&mut symbols[0..(symbols_sum as usize)])?;
87추가: // store
88추가: match dc_or_ac {
89추가: 0 => {
90추가: decoder.dc_huffman_tables[index] = Some(HuffmanTable::new(
91추가: &num_symbols,
92추가: symbols,
93추가: true,
94추가: decoder.is_progressive
95추가: )?);
96추가: }
97추가: _ => {
98추가: decoder.ac_huffman_tables[index] = Some(HuffmanTable::new(
99추가: &num_symbols,
100추가: symbols,
101추가: false,
102추가: decoder.is_progressive
103추가: )?);
104추가: }
105추가: }
106추가: }
107추가:
108추가: if dht_length > 0 {
109추가: return Err(DecodeErrors::FormatStatic("Bogus Huffman table definition"));
110추가: }
111추가:
112추가: Ok(())
113추가: }
114추가:
115추가: ///**B.2.4.1 Quantization table-specification syntax**
116추가: #[allow(clippy::cast_possible_truncation, clippy::needless_range_loop)]
117추가: pub(crate) fn parse_dqt<T: ZByteReaderTrait>(img: &mut JpegDecoder<T>) -> Result<(), DecodeErrors> {
118추가: // read length
119추가: let mut qt_length =
120추가: img.stream
121추가: .get_u16_be_err()?
122추가: .checked_sub(2)
123추가: .ok_or(DecodeErrors::FormatStatic(
124추가: "Invalid DQT length. Length should be greater than 2"
125추가: ))?;
126추가: // A single DQT header may have multiple QT's
127추가: while qt_length > 0 {
128추가: let qt_info = img.stream.read_u8_err()?;
129추가: // 0 = 8 bit otherwise 16 bit dqt
130추가: let precision = (qt_info >> 4) as usize;
131추가: // last 4 bits give us position
132추가: let table_position = (qt_info & 0x0f) as usize;
133추가: let precision_value = 64 * (precision + 1);
134추가:
135추가: if (precision_value + 1) as u16 > qt_length {
136추가: return Err(DecodeErrors::DqtError(format!("Invalid QT table bytes left :{}. Too small to construct a valid qt table which should be {} long", qt_length, precision_value + 1)));
137추가: }
138추가:
139추가: let dct_table = match precision {
140추가: 0 => {
141추가: let mut qt_values = [0; 64];
142추가:
143추가: img.stream.read_exact_bytes(&mut qt_values)?;
144추가:
145추가: qt_length -= (precision_value as u16) + 1 /*QT BIT*/;
146추가: // carry out un zig-zag here
147추가: un_zig_zag(&qt_values)
148추가: }
149추가: 1 => {
150추가: // 16 bit quantization tables
151추가: let mut qt_values = [0_u16; 64];
152추가:
153추가: for i in 0..64 {
154추가: qt_values[i] = img.stream.get_u16_be_err()?;
155추가: }
156추가: qt_length -= (precision_value as u16) + 1;
157추가:
158추가: un_zig_zag(&qt_values)
159추가: }
160추가: _ => {
161추가: return Err(DecodeErrors::DqtError(format!(
162추가: "Expected QT precision value of either 0 or 1, found {precision:?}"
163추가: )));
164추가: }
165추가: };
166추가:
167추가: if table_position >= MAX_COMPONENTS {
168추가: return Err(DecodeErrors::DqtError(format!(
169추가: "Too large table position for QT :{table_position}, expected between 0 and 3"
170추가: )));
171추가: }
172추가:
173추가: trace!("Assigning qt table {table_position} with precision {precision}");
174추가: img.qt_tables[table_position] = Some(dct_table);
175추가: }
176추가:
177추가: return Ok(());
178추가: }
179추가:
180추가: /// Section:`B.2.2 Frame header syntax`
181추가:
182추가: pub(crate) fn parse_start_of_frame<T: ZByteReaderTrait>(
183추가: sof: SOFMarkers, img: &mut JpegDecoder<T>
184추가: ) -> Result<(), DecodeErrors> {
185추가: if img.seen_sof {
186추가: return Err(DecodeErrors::SofError(
187추가: "Two Start of Frame Markers".to_string()
188추가: ));
189추가: }
190추가: // Get length of the frame header
191추가: let length = img.stream.get_u16_be_err()?;
192추가: // usually 8, but can be 12 and 16, we currently support only 8
193추가: // so sorry about that 12 bit images
194추가: let dt_precision = img.stream.read_u8_err()?;
195추가:
196추가: if dt_precision != 8 {
197추가: return Err(DecodeErrors::SofError(format!(
198추가: "The library can only parse 8-bit images, the image has {dt_precision} bits of precision"
199추가: )));
200추가: }
201추가:
202추가: img.info.set_density(dt_precision);
203추가:
204추가: // read and set the image height.
205추가: let img_height = img.stream.get_u16_be_err()?;
206추가: img.info.set_height(img_height);
207추가:
208추가: // read and set the image width
209추가: let img_width = img.stream.get_u16_be_err()?;
210추가: img.info.set_width(img_width);
211추가:
212추가: trace!("Image width :{}", img_width);
213추가: trace!("Image height :{}", img_height);
214추가:
215추가: if usize::from(img_width) > img.options.max_width() {
216추가: return Err(DecodeErrors::Format(format!("Image width {} greater than width limit {}. If use `set_limits` if you want to support huge images", img_width, img.options.max_width())));
217추가: }
218추가:
219추가: if usize::from(img_height) > img.options.max_height() {
220추가: return Err(DecodeErrors::Format(format!("Image height {} greater than height limit {}. If use `set_limits` if you want to support huge images", img_height, img.options.max_height())));
221추가: }
222추가:
223추가: // Check image width or height is zero
224추가: if img_width == 0 || img_height == 0 {
225추가: return Err(DecodeErrors::ZeroError);
226추가: }
227추가:
228추가: // Number of components for the image.
229추가: let num_components = img.stream.read_u8_err()?;
230추가:
231추가: if num_components == 0 {
232추가: return Err(DecodeErrors::SofError(
233추가: "Number of components cannot be zero.".to_string()
234추가: ));
235추가: }
236추가:
237추가: let expected = 8 + 3 * u16::from(num_components);
238추가: // length should be equal to num components
239추가: if length != expected {
240추가: return Err(DecodeErrors::SofError(format!(
241추가: "Length of start of frame differs from expected {expected},value is {length}"
242추가: )));
243추가: }
244추가:
245추가: trace!("Image components : {}", num_components);
246추가:
247추가: if num_components == 1 {
248추가: // SOF sets the number of image components
249추가: // and that to us translates to setting input and output
250추가: // colorspaces to zero
251추가: img.input_colorspace = ColorSpace::Luma;
252추가: //img.options = img.options.jpeg_set_out_colorspace(ColorSpace::Luma);
253추가: debug!("Overriding default colorspace set to Luma");
254추가: }
255추가: if num_components == 4 && img.input_colorspace == ColorSpace::YCbCr {
256추가: trace!("Input image has 4 components, defaulting to CMYK colorspace");
257추가: // https://entropymine.wordpress.com/2018/10/22/how-is-a-jpeg-images-color-type-determined/
258추가: img.input_colorspace = ColorSpace::CMYK;
259추가: }
260추가:
261추가: // set number of components
262추가: img.info.components = num_components;
263추가:
264추가: let mut components = Vec::with_capacity(num_components as usize);
265추가: let mut temp = [0; 3];
266추가:
267추가: for pos in 0..num_components {
268추가: // read 3 bytes for each component
269추가: img.stream.read_exact_bytes(&mut temp)?;
270추가:
271추가: // create a component.
272추가: let component = Components::from(temp, pos)?;
273추가:
274추가: components.push(component);
275추가: }
276추가: img.seen_sof = true;
277추가:
278추가: img.info.set_sof_marker(sof);
279추가:
280추가: img.components = components;
281추가:
282추가: let mut h_max = 1;
283추가: let mut v_max = 1;
284추가:
285추가: for comp in &img.components {
286추가: h_max = max(h_max, comp.horizontal_sample);
287추가: v_max = max(v_max, comp.vertical_sample);
288추가: }
289추가:
290추가: img.info.sample_ratio = match (h_max, v_max) {
291추가: (1, 1) => SampleRatios::None,
292추가: (1, 2) => SampleRatios::V,
293추가: (2, 1) => SampleRatios::H,
294추가: (2, 2) => SampleRatios::HV,
295추가: (hs, vs) => SampleRatios::Generic(hs, vs)
296추가: };
297추가:
298추가: Ok(())
299추가: }
300추가:
301추가: /// Parse a start of scan data
302추가: pub(crate) fn parse_sos<T: ZByteReaderTrait>(
303추가: image: &mut JpegDecoder<T>
304추가: ) -> Result<(), DecodeErrors> {
305추가: // Scan header length
306추가: let ls = usize::from(image.stream.get_u16_be_err()?);
307추가: // Number of image components in scan
308추가: let ns = image.stream.read_u8_err()?;
309추가:
310추가: let mut seen: [_; 5] = [-1; { MAX_COMPONENTS + 1 }];
311추가:
312추가: image.num_scans = ns;
313추가: let smallest_size = 6 + 2 * usize::from(ns);
314추가:
315추가: if ls != smallest_size {
316추가: return Err(DecodeErrors::SosError(format!(
317추가: "Bad SOS length {ls},corrupt jpeg"
318추가: )));
319추가: }
320추가:
321추가: // Check number of components.
322추가: if !(1..5).contains(&ns) {
323추가: return Err(DecodeErrors::SosError(format!(
324추가: "Invalid number of components in start of scan {ns}, expected in range 1..5"
325추가: )));
326추가: }
327추가:
328추가: if image.info.components == 0 {
329추가: return Err(DecodeErrors::FormatStatic(
330추가: "Error decoding SOF Marker, Number of components cannot be zero."
331추가: ));
332추가: }
333추가:
334추가: // consume spec parameters
335추가: image.scan_subsampled = false;
336추가:
337추가: for i in 0..ns {
338추가: let id = image.stream.read_u8_err()?;
339추가:
340추가: if seen.contains(&i32::from(id)) {
341추가: return Err(DecodeErrors::SofError(format!(
342추가: "Duplicate ID {id} seen twice in the same component"
343추가: )));
344추가: }
345추가:
346추가: seen[usize::from(i)] = i32::from(id);
347추가: // DC and AC huffman table position
348추가: // top 4 bits contain dc huffman destination table
349추가: // lower four bits contain ac huffman destination table
350추가: let y = image.stream.read_u8_err()?;
351추가:
352추가: let mut j = 0;
353추가:
354추가: while j < image.info.components {
355추가: if image.components[j as usize].id == id {
356추가: break;
357추가: }
358추가:
359추가: j += 1;
360추가: }
361추가:
362추가: if j == image.info.components {
363추가: return Err(DecodeErrors::SofError(format!(
364추가: "Invalid component id {}, expected one one of {:?}",
365추가: id,
366추가: image.components.iter().map(|c| c.id).collect::<Vec<_>>()
367추가: )));
368추가: }
369추가:
370추가: let component = &mut image.components[usize::from(j)];
371추가: component.dc_huff_table = usize::from((y >> 4) & 0xF);
372추가: component.ac_huff_table = usize::from(y & 0xF);
373추가: image.z_order[i as usize] = j as usize;
374추가:
375추가: if component.vertical_sample != 1 || component.horizontal_sample != 1 {
376추가: image.scan_subsampled = true;
377추가: }
378추가:
379추가: trace!(
380추가: "Assigned huffman tables {}/{} to component {j}, id={}",
381추가: image.components[usize::from(j)].dc_huff_table,
382추가: image.components[usize::from(j)].ac_huff_table,
383추가: image.components[usize::from(j)].id,
384추가: );
385추가: }
386추가:
387추가: // Collect the component spec parameters
388추가: // This is only needed for progressive images but I'll read
389추가: // them in order to ensure they are correct according to the spec
390추가:
391추가: // Extract progressive information
392추가:
393추가: // https://www.w3.org/Graphics/JPEG/itu-t81.pdf
394추가: // Page 42
395추가:
396추가: // Start of spectral / predictor selection. (between 0 and 63)
397추가: image.spec_start = image.stream.read_u8_err()?;
398추가: // End of spectral selection
399추가: image.spec_end = image.stream.read_u8_err()?;
400추가:
401추가: let bit_approx = image.stream.read_u8_err()?;
402추가: // successive approximation bit position high
403추가: image.succ_high = bit_approx >> 4;
404추가:
405추가: if image.spec_end > 63 {
406추가: return Err(DecodeErrors::SosError(format!(
407추가: "Invalid Se parameter {}, range should be 0-63",
408추가: image.spec_end
409추가: )));
410추가: }
411추가: if image.spec_start > 63 {
412추가: return Err(DecodeErrors::SosError(format!(
413추가: "Invalid Ss parameter {}, range should be 0-63",
414추가: image.spec_start
415추가: )));
416추가: }
417추가: if image.succ_high > 13 {
418추가: return Err(DecodeErrors::SosError(format!(
419추가: "Invalid Ah parameter {}, range should be 0-13",
420추가: image.succ_low
421추가: )));
422추가: }
423추가: // successive approximation bit position low
424추가: image.succ_low = bit_approx & 0xF;
425추가:
426추가: if image.succ_low > 13 {
427추가: return Err(DecodeErrors::SosError(format!(
428추가: "Invalid Al parameter {}, range should be 0-13",
429추가: image.succ_low
430추가: )));
431추가: }
432추가: // skip any bytes not read
433추가: image.stream.skip(smallest_size.saturating_sub(ls))?;
434추가:
435추가: trace!(
436추가: "Ss={}, Se={} Ah={} Al={}",
437추가: image.spec_start,
438추가: image.spec_end,
439추가: image.succ_high,
440추가: image.succ_low
441추가: );
442추가:
443추가: Ok(())
444추가: }
445추가:
446추가: /// Parse the APP13 (IPTC) segment.
447추가: pub(crate) fn parse_app13<T: ZByteReaderTrait>(
448추가: decoder: &mut JpegDecoder<T>
449추가: ) -> Result<(), DecodeErrors> {
450추가: const IPTC_PREFIX: &[u8] = b"Photoshop 3.0\0";
451추가: // skip length.
452추가: let mut length = usize::from(decoder.stream.get_u16_be());
453추가:
454추가: if length < 2 {
455추가: return Err(DecodeErrors::FormatStatic("Too small APP13 length"));
456추가: }
457추가: // length bytes.
458추가: length -= 2;
459추가:
460추가: if length > IPTC_PREFIX.len() && decoder.stream.peek_at(0, IPTC_PREFIX.len())? == IPTC_PREFIX {
461추가: // skip bytes we read above.
462추가: decoder.stream.skip(IPTC_PREFIX.len())?;
463추가: length -= IPTC_PREFIX.len();
464추가:
465추가: let iptc_bytes = decoder.stream.peek_at(0, length)?.to_vec();
466추가:
467추가: decoder.info.iptc_data = Some(iptc_bytes);
468추가: }
469추가:
470추가: decoder.stream.skip(length)?;
471추가: Ok(())
472추가: }
473추가:
474추가: /// Parse Adobe App14 segment
475추가: pub(crate) fn parse_app14<T: ZByteReaderTrait>(
476추가: decoder: &mut JpegDecoder<T>
477추가: ) -> Result<(), DecodeErrors> {
478추가: // skip length
479추가: let mut length = usize::from(decoder.stream.get_u16_be());
480추가:
481추가: if length < 2 {
482추가: return Err(DecodeErrors::FormatStatic("Too small APP14 length"));
483추가: }
484추가:
485추가: if decoder.stream.peek_at(0, 5)? == b"Adobe" {
486추가: if length < 14 {
487추가: return Err(DecodeErrors::FormatStatic(
488추가: "Too short of a length for App14 segment"
489추가: ));
490추가: }
491추가: // move stream 6 bytes to remove adobe id
492추가: decoder.stream.skip(6)?;
493추가: // skip version, flags0 and flags1
494추가: decoder.stream.skip(5)?;
495추가: // get color transform
496추가: let transform = decoder.stream.read_u8();
497추가: // https://exiftool.org/TagNames/JPEG.html#Adobe
498추가: match transform {
499추가: 0 => decoder.input_colorspace = ColorSpace::CMYK,
500추가: 1 => decoder.input_colorspace = ColorSpace::YCbCr,
501추가: 2 => decoder.input_colorspace = ColorSpace::YCCK,
502추가: _ => {
503추가: return Err(DecodeErrors::Format(format!(
504추가: "Unknown Adobe colorspace {transform}"
505추가: )))
506추가: }
507추가: }
508추가: // length = 2
509추가: // adobe id = 6
510추가: // version = 5
511추가: // transform = 1
512추가: length = length.saturating_sub(14);
513추가: } else {
514추가: warn!("Not a valid Adobe APP14 Segment, skipping {} bytes", length);
515추가: length = length.saturating_sub(2);
516추가: }
517추가: // skip any proceeding lengths.
518추가: // we do not need them
519추가: decoder.stream.skip(length)?;
520추가:
521추가: Ok(())
522추가: }
523추가:
524추가: /// Parse the APP1 segment
525추가: ///
526추가: /// This contains the exif tag
527추가: pub(crate) fn parse_app1<T: ZByteReaderTrait>(
528추가: decoder: &mut JpegDecoder<T>
529추가: ) -> Result<(), DecodeErrors> {
530추가: const XMP_NAMESPACE_PREFIX: &[u8] = b"http://ns.adobe.com/xap/1.0/\0";
531추가: const EXTENDED_XMP_NAMESPACE_PREFIX: &[u8] = b"http://ns.adobe.com/xmp/extension/\0";
532추가: const EXTENDED_XMP_GUID_SIZE: usize = 32;
533추가: const EXTENDED_XMP_TOTAL_SIZE_SIZE: usize = 4;
534추가: const EXTENDED_XMP_OFFSET_SIZE: usize = 4;
535추가: const EXTENDED_XMP_HEADER_SIZE: usize =
536추가: EXTENDED_XMP_GUID_SIZE + EXTENDED_XMP_TOTAL_SIZE_SIZE + EXTENDED_XMP_OFFSET_SIZE;
537추가:
538추가: // contains exif data
539추가: let mut length = usize::from(decoder.stream.get_u16_be());
540추가:
541추가: if length < 2 {
542추가: return Err(DecodeErrors::FormatStatic("Too small app1 length"));
543추가: }
544추가: // length bytes
545추가: length -= 2;
546추가:
547추가: if length > 6 && decoder.stream.peek_at(0, 6)? == b"Exif\x00\x00" {
548추가: trace!("Exif segment present");
549추가: // skip bytes we read above
550추가: decoder.stream.skip(6)?;
551추가: length -= 6;
552추가:
553추가: let exif_bytes = decoder.stream.peek_at(0, length)?.to_vec();
554추가:
555추가: decoder.info.exif_data = Some(exif_bytes);
556추가: } else if length > XMP_NAMESPACE_PREFIX.len()
557추가: && decoder.stream.peek_at(0, XMP_NAMESPACE_PREFIX.len())? == XMP_NAMESPACE_PREFIX
558추가: {
559추가: trace!("XMP Data Present");
560추가: decoder.stream.skip(XMP_NAMESPACE_PREFIX.len())?;
561추가: length -= XMP_NAMESPACE_PREFIX.len();
562추가: let xmp_data = decoder.stream.peek_at(0, length)?.to_vec();
563추가: decoder.info.xmp_data = Some(xmp_data);
564추가: } else if length > EXTENDED_XMP_NAMESPACE_PREFIX.len()
565추가: && decoder.stream.peek_at(0, EXTENDED_XMP_NAMESPACE_PREFIX.len())?
566추가: == EXTENDED_XMP_NAMESPACE_PREFIX
567추가: {
568추가: trace!("Extended XMP Data Present");
569추가: decoder.stream.skip(EXTENDED_XMP_NAMESPACE_PREFIX.len())?;
570추가: length -= EXTENDED_XMP_NAMESPACE_PREFIX.len();
571추가:
572추가: if length < EXTENDED_XMP_HEADER_SIZE {
573추가: return Err(DecodeErrors::FormatStatic("Too small Extended XMP segment"));
574추가: }
575추가:
576추가: let header = decoder.stream.peek_at(0, EXTENDED_XMP_HEADER_SIZE)?;
577추가: let guid = header[0..EXTENDED_XMP_GUID_SIZE].to_vec();
578추가:
579추가: let total_size_start = EXTENDED_XMP_GUID_SIZE;
580추가: let total_size_end = total_size_start + EXTENDED_XMP_TOTAL_SIZE_SIZE;
581추가: let total_size =
582추가: u32::from_be_bytes(header[total_size_start..total_size_end].try_into().unwrap());
583추가:
584추가: let offset_start = total_size_end;
585추가: let offset_end = offset_start + EXTENDED_XMP_OFFSET_SIZE;
586추가: let offset = u32::from_be_bytes(header[offset_start..offset_end].try_into().unwrap());
587추가:
588추가: let data = decoder
589추가: .stream
590추가: .peek_at(EXTENDED_XMP_HEADER_SIZE, length - EXTENDED_XMP_HEADER_SIZE)?
591추가: .to_vec();
592추가:
593추가: decoder.extended_xmp_segments.push(ExtendedXmpSegment { offset, total_size, guid, data });
594추가: } else {
595추가: warn!("Unknown format for APP1 tag, skipping");
596추가: }
597추가:
598추가: decoder.stream.skip(length)?;
599추가: Ok(())
600추가: }
601추가:
602추가: pub(crate) fn parse_app2<T: ZByteReaderTrait>(
603추가: decoder: &mut JpegDecoder<T>
604추가: ) -> Result<(), DecodeErrors> {
605추가: static HDR_META: &[u8] = b"urn:iso:std:iso:ts:21496:-1\0";
606추가: static MPF_DATA: &[u8] = b"MPF\0";
607추가:
608추가: let mut length = usize::from(decoder.stream.get_u16_be());
609추가:
610추가: if length < 2 {
611추가: return Err(DecodeErrors::FormatStatic("Too small app2 segment"));
612추가: }
613추가: // length bytes
614추가: length -= 2;
615추가:
616추가: if length > 14 && decoder.stream.peek_at(0, 12)? == *b"ICC_PROFILE\0" {
617추가: trace!("ICC Profile present");
618추가: // skip 12 bytes which indicate ICC profile
619추가: length -= 12;
620추가: decoder.stream.skip(12)?;
621추가: let seq_no = decoder.stream.read_u8();
622추가: let num_markers = decoder.stream.read_u8();
623추가: // deduct the two bytes we read above
624추가: length -= 2;
625추가:
626추가: let data = decoder.stream.peek_at(0, length)?.to_vec();
627추가:
628추가: let icc_chunk = ICCChunk {
629추가: seq_no,
630추가: num_markers,
631추가: data
632추가: };
633추가: decoder.icc_data.push(icc_chunk);
634추가: } else if length > HDR_META.len() && decoder.stream.peek_at(0, HDR_META.len())? == HDR_META {
635추가: length = length.saturating_sub(HDR_META.len());
636추가: decoder.stream.skip(HDR_META.len())?;
637추가: trace!("Gain Map metadata found");
638추가: match length {
639추가: 4 => {
640추가: // If gain map metadata length == 4 then here it variables
641추가: // https://github.com/google/libultrahdr/blob/bf2aa439eea9ad5da483003fa44182f990f74091/lib/src/jpegr.cpp#L1076C1-L1077C35
642추가: // 2 bytes minimum_version: (00 00)
643추가: // 2 bytes writer_version: (00 00)
644추가: // Perhaps nothing to do with it ?
645추가: let _ = decoder.stream.get_u16_be();
646추가: let _ = decoder.stream.get_u16_be();
647추가: length -= 4;
648추가: decoder
649추가: .info
650추가: .gain_map_info
651추가: .push(GainMapInfo { data: Vec::new() });
652추가: }
653추가: n if n > 4 => {
654추가: // If there is perhaps useful gain map info
655추가: // we'll read this until end
656추가: // https://github.com/google/libultrahdr/blob/bf2aa439eea9ad5da483003fa44182f990f74091/lib/src/jpegr.cpp#L1323
657추가: let data = decoder.stream.peek_at(0, length)?.to_vec();
658추가: length -= data.len();
659추가: decoder.stream.skip(data.len())?;
660추가:
661추가: decoder.info.gain_map_info.push(GainMapInfo { data });
662추가: }
663추가: _ => {}
664추가: }
665추가: } else if length > MPF_DATA.len() && decoder.stream.peek_at(0, MPF_DATA.len())? == MPF_DATA {
666추가: trace!("MPF Signature present");
667추가: length = length.saturating_sub(MPF_DATA.len());
668추가: decoder.stream.skip(MPF_DATA.len())?;
669추가: decoder.info.multi_picture_information_offset = Some(decoder.stream.position()?);
670추가: // MPF signature taken from here
671추가: // https://github.com/google/libultrahdr/blob/bf2aa439eea9ad5da483003fa44182f990f74091/lib/include/ultrahdr/multipictureformat.h#L50
672추가: // https://github.com/google/libultrahdr/blob/bf2aa439eea9ad5da483003fa44182f990f74091/lib/src/multipictureformat.cpp#L36
673추가: // More info https://www.cipa.jp/std/documents/e/DC-X007-KEY_E.pdf
674추가: let data = decoder.stream.peek_at(0, length)?.to_vec();
675추가: length -= data.len();
676추가: decoder.stream.skip(data.len())?;
677추가: decoder.info.multi_picture_information = Some(data);
678추가: }
679추가:
680추가: decoder.stream.skip(length)?;
681추가:
682추가: Ok(())
683추가: }
684추가:
685추가: /// Small utility function to print Un-zig-zagged quantization tables
686추가:
687추가: fn un_zig_zag<T>(a: &[T]) -> [i32; 64]
688추가: where
689추가: T: Default + Copy,
690추가: i32: core::convert::From<T>
691추가: {
692추가: let mut output = [i32::default(); 64];
693추가:
694추가: for i in 0..64 {
695추가: output[UN_ZIGZAG[i]] = i32::from(a[i]);
696추가: }
697추가:
698추가: output
699추가: }
추가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로 열기
수정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-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/preview_decode.rs

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

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

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

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

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

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

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

Raw로 열기