불완전한 JPEG 미리보기를 거부한다
- 작성자
- 시로사키 하나
- 작성 시각
- 커밋
eec6a778f9483e0b4d30e35896e37f5ebeca03bf- 부모
- f951b60
변경된 파일 47개
+2,746-12변경 내용이 커서 일부 파일의 Diff를 생략했어요. 생략한 파일은 파일 보기나 Raw로 확인할 수 있어요.
| @@ -0,0 +1,24 @@ | ||
| 1 | 추가: # JPEG 스캔 완전성 패치 | |
| 2 | 추가: | |
| 3 | 추가: 미리보기 작업자는 `experiments/rust-archive-worker/vendor/zune-jpeg`의 `zipelo-jpeg 0.5.15`를 사용한다. 순수 Rust인 zune-jpeg 0.5.15의 MIT 조건을 선택한 로컬 패치이며, PNG와 통신 계약은 변경하지 않는다. | |
| 4 | 추가: | |
| 5 | 추가: 원본은 crates.io의 [zune-jpeg 0.5.15](https://crates.io/crates/zune-jpeg/0.5.15)이다. 원본 crate의 SHA-256은 `27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296`이다. `LICENSE-MIT` 원문과 소스의 저작권 고지를 보존했다. 패키지 이름을 구분하고 미리보기 작업자만 이 패치를 사용한다. 앱의 기존 이미지 의존성은 유지한다. | |
| 6 | 추가: | |
| 7 | 추가: ## 수정 이유와 범위 | |
| 8 | 추가: | |
| 9 | 추가: 원본은 strict 모드에서도 스캔 종료 마커 뒤에 비트를 보충한다. 헤더에 해당하는 앞 623바이트와 EOI만 있는 시험 JPEG도 이 보충 비트로 픽셀을 만들고 성공한다. 출력 버퍼 길이나 초기값 검사로는 실제 그림 데이터와 보충 데이터를 구분할 수 없다. | |
| 10 | 추가: | |
| 11 | 추가: - `bitstream.rs`는 실제 엔트로피 비트 수를 별도로 집계한다. Huffman 조회의 미리 읽기는 허용하고 실제 소비가 입력 비트를 넘을 때 오류를 기록한다. 보충 비트는 입력량으로 세지 않는다. | |
| 12 | 추가: - `mcu.rs`와 `mcu_prog.rs`는 MCU 행, progressive MCU 및 재시작 경계에서 오류를 확인한다. baseline의 직접 출력 경로는 기록한 픽셀 바이트 수도 확인한다. | |
| 13 | 추가: - 작업자의 `preview.rs`는 모든 색상 성분의 최초 DC 스캔을 요구하고, baseline에서 중복되거나 불완전한 성분 스캔을 거부한다. 원본과 결과 크기 상한, 암호, 자원 승인과 취소 정책은 유지한다. | |
| 14 | 추가: - Cargo manifest를 프로젝트 경로 의존성으로 바꿨고 사용하지 않는 upstream 시험 모듈과 주석 처리된 시험, 잘못된 crate 단위 `macro_use` 속성과 주석의 이모지를 제외했다. upstream 시험 코드는 복사하지 않았다. 회귀 시험과 새 표본은 루트 `tests/rust-archive-worker/`에만 둔다. | |
| 15 | 추가: | |
| 16 | 추가: `packaging/licenses.py`는 프로젝트 경로 패키지에 명시된 라이선스 원문을 해당 패키지 내부에서 읽으며, 경로 이탈과 라이선스 파일의 심볼릭 링크를 거부한다. 배포 고지에는 `zipelo-jpeg`의 upstream MIT 원문이 포함된다. 새 registry 버전이나 네이티브 라이브러리는 추가하지 않는다. | |
| 17 | 추가: | |
| 18 | 추가: ## 검증과 유지 | |
| 19 | 추가: | |
| 20 | 추가: 기존 baseline 표본의 앞 623바이트와 EOI, 이미지 높이만 늘린 불완전한 스캔, 각 progressive 스캔의 데이터 누락, 여러 MCU 행과 재시작 마커를 시험한다. PNG는 완전한 IEND와 올바른 CRC가 있지만 픽셀 행이 부족한 입력도 손상으로 거부해야 한다. 실제 ZIP 작업자는 오류 시 Begin/Chunk/End를 전송하지 않아야 한다. | |
| 21 | 추가: | |
| 22 | 추가: 여러 행의 JPEG 표본 5개는 시험용 RGB 그라데이션을 baseline, progressive, 회색조, CMYK와 재시작 마커 형식으로 직접 생성했다. upstream 버전을 바꾸거나 패치를 제거할 때 이 회귀와 `python3 tests/ci/run_rust.py local`, 라이선스 시험을 다시 실행한다. 동일한 스캔 완전성 보장이 확인된 upstream 릴리스가 있으면 경로 의존성을 제거할 수 있다. | |
| 23 | 추가: | |
| 24 | 추가: 로컬 패키지 이름은 `zipelo-jpeg`이므로 보안 권고를 확인할 때 원본 이름인 `zune-jpeg 0.5.15`도 대조해야 한다. 패치는 엔트로피 완전성만 보강하며 다른 upstream 결함이나 향후 권고의 부재를 보장하지 않는다. |
| @@ -341,9 +341,16 @@ dependencies = [ | ||
| 341 | 341 | "sha2 0.10.9", |
| 342 | 342 | "subtle", |
| 343 | 343 | "zeroize", |
| 344 | 추가: "zipelo-jpeg", | |
| 344 | 345 | "zlib-rs", |
| 345 | 346 | "zune-core", |
| 346 | 삭제: "zune-jpeg", | |
| 347 | 추가: ] | |
| 348 | 추가: | |
| 349 | 추가: [[package]] | |
| 350 | 추가: name = "zipelo-jpeg" | |
| 351 | 추가: version = "0.5.15" | |
| 352 | 추가: dependencies = [ | |
| 353 | 추가: "zune-core", | |
| 347 | 354 | ] |
| 348 | 355 | |
| 349 | 356 | [[package]] |
| @@ -357,12 +364,3 @@ name = "zune-core" | ||
| 357 | 364 | version = "0.5.3" |
| 358 | 365 | source = "registry+https://github.com/rust-lang/crates.io-index" |
| 359 | 366 | checksum = "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 | 삭제: ] |
| @@ -8,7 +8,7 @@ autotests = false | ||
| 8 | 8 | |
| 9 | 9 | [dependencies] |
| 10 | 10 | png = "=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"] } | |
| 12 | 12 | zune-core = { version = "=0.5.3", default-features = false, features = ["std"] } |
| 13 | 13 | bzip2 = "=0.6.1" |
| 14 | 14 | lzma-rust2 = { version = "=0.25.0", default-features = false, features = ["std", "xz"] } |
| @@ -22,6 +22,7 @@ sha2 = "=0.10.9" | ||
| 22 | 22 | zlib-rs = { version = "=0.6.8", default-features = false, features = ["rust-allocator"] } |
| 23 | 23 | |
| 24 | 24 | [workspace] |
| 25 | 추가: exclude = ["vendor/zune-jpeg"] | |
| 25 | 26 | |
| 26 | 27 | [[test]] |
| 27 | 28 | name = "archive_worker" |
| @@ -240,6 +240,9 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P | ||
| 240 | 240 | let mut scanning = false; |
| 241 | 241 | let mut info = None; |
| 242 | 242 | let mut seen_scan = false; |
| 243 | 추가: let mut components = Vec::new(); | |
| 244 | 추가: let mut decoded_components = 0u8; | |
| 245 | 추가: let mut progressive = false; | |
| 243 | 246 | while at < source.len() { |
| 244 | 247 | check.check()?; |
| 245 | 248 | if scanning { |
| @@ -258,7 +261,12 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P | ||
| 258 | 261 | at += 1; |
| 259 | 262 | match marker { |
| 260 | 263 | 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 | 추가: } | |
| 262 | 270 | 0 | 0xd0..=0xd9 => return Err(ErrorCode::Integrity), |
| 263 | 271 | 1 => continue, |
| 264 | 272 | _ => {} |
| @@ -277,6 +285,17 @@ fn jpeg_info(entry_id: u32, source: &[u8], check: &mut impl Monitor) -> Result<P | ||
| 277 | 285 | if !matches!(marker, 0xc0 | 0xc2) || body[0] != 8 { |
| 278 | 286 | return Err(ErrorCode::UnsupportedFeature); |
| 279 | 287 | } |
| 288 | 추가: progressive = marker == 0xc2; | |
| 289 | 추가: let count = usize::from(body[5]); | |
| 290 | 추가: if !(1..=4).contains(&count) || body.len() != 6 + count * 3 { | |
| 291 | 추가: return Err(ErrorCode::Integrity); | |
| 292 | 추가: } | |
| 293 | 추가: for component in body[6..].chunks_exact(3) { | |
| 294 | 추가: if components.contains(&component[0]) { | |
| 295 | 추가: return Err(ErrorCode::Integrity); | |
| 296 | 추가: } | |
| 297 | 추가: components.push(component[0]); | |
| 298 | 추가: } | |
| 280 | 299 | info = Some(rgba_info( |
| 281 | 300 | entry_id, |
| 282 | 301 | 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 | ||
| 287 | 306 | return Err(ErrorCode::UnsupportedFeature); |
| 288 | 307 | } |
| 289 | 308 | scanning = marker == 0xda; |
| 309 | 추가: if scanning { | |
| 310 | 추가: let count = usize::from(*body.first().ok_or(ErrorCode::Integrity)?); | |
| 311 | 추가: if info.is_none() | |
| 312 | 추가: || count == 0 | |
| 313 | 추가: || count > components.len() | |
| 314 | 추가: || body.len() != 4 + count * 2 | |
| 315 | 추가: { | |
| 316 | 추가: return Err(ErrorCode::Integrity); | |
| 317 | 추가: } | |
| 318 | 추가: let mut scan_components = 0u8; | |
| 319 | 추가: for component in body[1..1 + count * 2].chunks_exact(2) { | |
| 320 | 추가: let index = components | |
| 321 | 추가: .iter() | |
| 322 | 추가: .position(|id| *id == component[0]) | |
| 323 | 추가: .ok_or(ErrorCode::Integrity)?; | |
| 324 | 추가: let bit = 1 << index; | |
| 325 | 추가: if scan_components & bit != 0 { | |
| 326 | 추가: return Err(ErrorCode::Integrity); | |
| 327 | 추가: } | |
| 328 | 추가: scan_components |= bit; | |
| 329 | 추가: } | |
| 330 | 추가: if !progressive | |
| 331 | 추가: && (scan_components & decoded_components != 0 | |
| 332 | 추가: || body[1 + count * 2..] != [0, 63, 0]) | |
| 333 | 추가: { | |
| 334 | 추가: return Err(ErrorCode::Integrity); | |
| 335 | 추가: } | |
| 336 | 추가: // 모든 색상 성분의 최초 DC 스캔이 있어야 완전한 그림으로 처리함. | |
| 337 | 추가: if body[1 + count * 2] == 0 && body[3 + count * 2] >> 4 == 0 { | |
| 338 | 추가: decoded_components |= scan_components; | |
| 339 | 추가: } | |
| 340 | 추가: } | |
| 290 | 341 | seen_scan |= scanning; |
| 291 | 342 | at = end; |
| 292 | 343 | check.activity()?; |
| @@ -0,0 +1,28 @@ | ||
| 1 | 추가: [package] | |
| 2 | 추가: name = "zipelo-jpeg" | |
| 3 | 추가: version = "0.5.15" | |
| 4 | 추가: edition = "2021" | |
| 5 | 추가: license = "MIT" | |
| 6 | 추가: license-file = "LICENSE-MIT" | |
| 7 | 추가: authors = ["caleb <[email protected]>"] | |
| 8 | 추가: publish = false | |
| 9 | 추가: | |
| 10 | 추가: [lib] | |
| 11 | 추가: name = "zune_jpeg" | |
| 12 | 추가: path = "src/lib.rs" | |
| 13 | 추가: doctest = false | |
| 14 | 추가: | |
| 15 | 추가: [features] | |
| 16 | 추가: default = [] | |
| 17 | 추가: std = ["zune-core/std"] | |
| 18 | 추가: x86 = [] | |
| 19 | 추가: neon = [] | |
| 20 | 추가: portable_simd = [] | |
| 21 | 추가: log = ["zune-core/log"] | |
| 22 | 추가: | |
| 23 | 추가: [dependencies] | |
| 24 | 추가: zune-core = { version = "=0.5.3", default-features = false } | |
| 25 | 추가: | |
| 26 | 추가: [lints.rust.unexpected_cfgs] | |
| 27 | 추가: level = "warn" | |
| 28 | 추가: check-cfg = ["cfg(fuzzing)"] |
| @@ -0,0 +1,21 @@ | ||
| 1 | 추가: MIT License | |
| 2 | 추가: | |
| 3 | 추가: Copyright (c) zune-image developers | |
| 4 | 추가: | |
| 5 | 추가: Permission is hereby granted, free of charge, to any person obtaining a copy | |
| 6 | 추가: of this software and associated documentation files (the "Software"), to deal | |
| 7 | 추가: in the Software without restriction, including without limitation the rights | |
| 8 | 추가: to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
| 9 | 추가: copies of the Software, and to permit persons to whom the Software is | |
| 10 | 추가: furnished to do so, subject to the following conditions: | |
| 11 | 추가: | |
| 12 | 추가: The above copyright notice and this permission notice shall be included in all | |
| 13 | 추가: copies or substantial portions of the Software. | |
| 14 | 추가: | |
| 15 | 추가: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
| 16 | 추가: IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
| 17 | 추가: FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
| 18 | 추가: AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
| 19 | 추가: LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
| 20 | 추가: OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
| 21 | 추가: SOFTWARE. |
| @@ -0,0 +1,829 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: #![allow( | |
| 10 | 추가: clippy::if_not_else, | |
| 11 | 추가: clippy::similar_names, | |
| 12 | 추가: clippy::inline_always, | |
| 13 | 추가: clippy::doc_markdown, | |
| 14 | 추가: clippy::cast_sign_loss, | |
| 15 | 추가: clippy::cast_possible_truncation | |
| 16 | 추가: )] | |
| 17 | 추가: | |
| 18 | 추가: //! This file exposes a single struct that can decode a huffman encoded | |
| 19 | 추가: //! Bitstream in a JPEG file | |
| 20 | 추가: //! | |
| 21 | 추가: //! This code is optimized for speed. | |
| 22 | 추가: //! It's meant to be super duper super fast, because everyone else depends on this being fast. | |
| 23 | 추가: //! It's (annoyingly) serial hence we cant use parallel bitstreams(it's variable length coding.) | |
| 24 | 추가: //! | |
| 25 | 추가: //! Furthermore, on the case of refills, we have to do bytewise processing because the standard decided | |
| 26 | 추가: //! that we want to support markers in the middle of streams(seriously few people use RST markers). | |
| 27 | 추가: //! | |
| 28 | 추가: //! So we pull in all optimization steps: | |
| 29 | 추가: //! - use `inline[always]`? , | |
| 30 | 추가: //! - pre-execute most common cases , | |
| 31 | 추가: //! - add random comments | |
| 32 | 추가: //! - fast paths . | |
| 33 | 추가: //! | |
| 34 | 추가: //! Speed-wise: It is probably the fastest JPEG BitStream decoder to ever sail the seven seas because of | |
| 35 | 추가: //! a couple of optimization tricks. | |
| 36 | 추가: //! 1. Fast refills from libjpeg-turbo | |
| 37 | 추가: //! 2. As few as possible branches in decoder fast paths. | |
| 38 | 추가: //! 3. Accelerated AC table decoding borrowed from stb_image.h written by Fabian Gissen (@ rygorous), | |
| 39 | 추가: //! improved by me to handle more cases. | |
| 40 | 추가: //! 4. Safe and extensible routines(e.g. cool ways to eliminate bounds check) | |
| 41 | 추가: //! 5. No unsafe here | |
| 42 | 추가: //! | |
| 43 | 추가: //! Readability comes as a second priority(I tried with variable names this time, and we are wayy better than libjpeg). | |
| 44 | 추가: //! | |
| 45 | 추가: //! Anyway if you are reading this it means your cool and I hope you get whatever part of the code you are looking for | |
| 46 | 추가: //! (or learn something cool) | |
| 47 | 추가: //! | |
| 48 | 추가: //! Knock yourself out. | |
| 49 | 추가: use alloc::format; | |
| 50 | 추가: use alloc::string::ToString; | |
| 51 | 추가: use zune_core::log::warn; | |
| 52 | 추가: use core::cmp::min; | |
| 53 | 추가: | |
| 54 | 추가: use zune_core::bytestream::{ZByteReaderTrait, ZReader}; | |
| 55 | 추가: | |
| 56 | 추가: use crate::errors::DecodeErrors; | |
| 57 | 추가: use crate::huffman::{HuffmanTable, HUFF_LOOKAHEAD}; | |
| 58 | 추가: use crate::marker::Marker; | |
| 59 | 추가: use crate::mcu::DCT_BLOCK; | |
| 60 | 추가: use crate::misc::UN_ZIGZAG; | |
| 61 | 추가: | |
| 62 | 추가: macro_rules! decode_huff { | |
| 63 | 추가: ($stream:tt,$symbol:tt,$table:tt) => { | |
| 64 | 추가: let mut code_length = $symbol >> HUFF_LOOKAHEAD; | |
| 65 | 추가: | |
| 66 | 추가: ($symbol) &= (1 << HUFF_LOOKAHEAD) - 1; | |
| 67 | 추가: | |
| 68 | 추가: if code_length > i32::from(HUFF_LOOKAHEAD) | |
| 69 | 추가: { | |
| 70 | 추가: // if the symbol cannot be resolved in the first HUFF_LOOKAHEAD bits, | |
| 71 | 추가: // we know it lies somewhere between HUFF_LOOKAHEAD and 16 bits since jpeg imposes 16 bit | |
| 72 | 추가: // limit, we can therefore look 16 bits ahead and try to resolve the symbol | |
| 73 | 추가: // starting from 1+HUFF_LOOKAHEAD bits. | |
| 74 | 추가: $symbol = ($stream).peek_bits::<16>() as i32; | |
| 75 | 추가: // (Credits to Sean T. Barrett stb library for this optimization) | |
| 76 | 추가: // maxcode is pre-shifted 16 bytes long so that it has (16-code_length) | |
| 77 | 추가: // zeroes at the end hence we do not need to shift in the inner loop. | |
| 78 | 추가: while code_length < 17{ | |
| 79 | 추가: if $symbol < $table.maxcode[code_length as usize] { | |
| 80 | 추가: break; | |
| 81 | 추가: } | |
| 82 | 추가: code_length += 1; | |
| 83 | 추가: } | |
| 84 | 추가: | |
| 85 | 추가: if code_length == 17{ | |
| 86 | 추가: // symbol could not be decoded. | |
| 87 | 추가: // | |
| 88 | 추가: // We may think, lets fake zeroes, noo | |
| 89 | 추가: // panic, because Huffman codes are sensitive, probably everything | |
| 90 | 추가: // after this will be corrupt, so no need to continue. | |
| 91 | 추가: // panic!("Bad Huffman code length"); | |
| 92 | 추가: return Err(DecodeErrors::Format(format!("Bad Huffman Code 0x{:X}, corrupt JPEG",$symbol))) | |
| 93 | 추가: } | |
| 94 | 추가: | |
| 95 | 추가: $symbol >>= (16-code_length); | |
| 96 | 추가: ($symbol) = i32::from( | |
| 97 | 추가: ($table).values | |
| 98 | 추가: [(($symbol + ($table).offset[code_length as usize]) & 0xFF) as usize], | |
| 99 | 추가: ); | |
| 100 | 추가: } | |
| 101 | 추가: if code_length> i32::from(($stream).bits_left){ | |
| 102 | 추가: return Err(DecodeErrors::Format(format!("Code length {code_length} more than bits left {}",($stream).bits_left))) | |
| 103 | 추가: } | |
| 104 | 추가: // drop bits read | |
| 105 | 추가: ($stream).drop_bits(code_length as u8); | |
| 106 | 추가: }; | |
| 107 | 추가: } | |
| 108 | 추가: | |
| 109 | 추가: /// A `BitStream` struct, a bit by bit reader with super powers | |
| 110 | 추가: /// | |
| 111 | 추가: #[rustfmt::skip] | |
| 112 | 추가: pub(crate) struct BitStream { | |
| 113 | 추가: /// A MSB type buffer that is used for some certain operations | |
| 114 | 추가: pub buffer: u64, | |
| 115 | 추가: /// A TOP aligned MSB type buffer that is used to accelerate some operations like | |
| 116 | 추가: /// peek_bits and get_bits. | |
| 117 | 추가: /// | |
| 118 | 추가: /// By top aligned, I mean the top bit (63) represents the top bit in the buffer. | |
| 119 | 추가: aligned_buffer: u64, | |
| 120 | 추가: /// Tell us the bits left the two buffer | |
| 121 | 추가: pub(crate) bits_left: u8, | |
| 122 | 추가: /// Did we find a marker(RST/EOF) during decoding? | |
| 123 | 추가: pub marker: Option<Marker>, | |
| 124 | 추가: /// An i16 with the bit corresponding to successive_low set to 1, others 0. | |
| 125 | 추가: pub successive_low_mask: i16, | |
| 126 | 추가: spec_start: u8, | |
| 127 | 추가: spec_end: u8, | |
| 128 | 추가: pub eob_run: i32, | |
| 129 | 추가: pub overread_by: usize, | |
| 130 | 추가: /// True if we have seen end of image marker. | |
| 131 | 추가: /// Don't read anything after that. | |
| 132 | 추가: pub seen_eoi: bool, | |
| 133 | 추가: // 실제 입력 비트와 디코더가 보충한 비트의 소비를 구분함. | |
| 134 | 추가: input_bits: u8, | |
| 135 | 추가: exhausted_input: bool, | |
| 136 | 추가: } | |
| 137 | 추가: | |
| 138 | 추가: impl BitStream { | |
| 139 | 추가: /// Create a new BitStream | |
| 140 | 추가: #[rustfmt::skip] | |
| 141 | 추가: pub(crate) const fn new() -> BitStream { | |
| 142 | 추가: BitStream { | |
| 143 | 추가: buffer: 0, | |
| 144 | 추가: aligned_buffer: 0, | |
| 145 | 추가: bits_left: 0, | |
| 146 | 추가: marker: None, | |
| 147 | 추가: successive_low_mask: 1, | |
| 148 | 추가: spec_start: 0, | |
| 149 | 추가: spec_end: 0, | |
| 150 | 추가: eob_run: 0, | |
| 151 | 추가: overread_by: 0, | |
| 152 | 추가: seen_eoi: false, | |
| 153 | 추가: input_bits: 0, | |
| 154 | 추가: exhausted_input: false, | |
| 155 | 추가: } | |
| 156 | 추가: } | |
| 157 | 추가: | |
| 158 | 추가: /// Create a new Bitstream for progressive decoding | |
| 159 | 추가: #[allow(clippy::redundant_field_names)] | |
| 160 | 추가: #[rustfmt::skip] | |
| 161 | 추가: pub(crate) fn new_progressive(al: u8, spec_start: u8, spec_end: u8) -> BitStream { | |
| 162 | 추가: BitStream { | |
| 163 | 추가: buffer: 0, | |
| 164 | 추가: aligned_buffer: 0, | |
| 165 | 추가: bits_left: 0, | |
| 166 | 추가: marker: None, | |
| 167 | 추가: successive_low_mask: 1i16 << al, | |
| 168 | 추가: spec_start: spec_start, | |
| 169 | 추가: spec_end: spec_end, | |
| 170 | 추가: eob_run: 0, | |
| 171 | 추가: overread_by: 0, | |
| 172 | 추가: seen_eoi: false, | |
| 173 | 추가: input_bits: 0, | |
| 174 | 추가: exhausted_input: false, | |
| 175 | 추가: } | |
| 176 | 추가: } | |
| 177 | 추가: | |
| 178 | 추가: /// Refill the bit buffer by (a maximum of) 32 bits | |
| 179 | 추가: /// | |
| 180 | 추가: /// # Arguments | |
| 181 | 추가: /// - `reader`:`&mut BufReader<R>`: A mutable reference to an underlying | |
| 182 | 추가: /// File/Memory buffer containing a valid JPEG stream | |
| 183 | 추가: /// | |
| 184 | 추가: /// This function will only refill if `self.count` is less than 32 | |
| 185 | 추가: #[inline(always)] // to many call sites? ( perf improvement by 4%) | |
| 186 | 추가: pub fn refill<T>(&mut self, reader: &mut ZReader<T>) -> Result<bool, DecodeErrors> | |
| 187 | 추가: where | |
| 188 | 추가: T: ZByteReaderTrait | |
| 189 | 추가: { | |
| 190 | 추가: /// Macro version of a single byte refill. | |
| 191 | 추가: /// Arguments | |
| 192 | 추가: /// buffer-> our io buffer, because rust macros cannot get values from | |
| 193 | 추가: /// the surrounding environment bits_left-> number of bits left | |
| 194 | 추가: /// to full refill | |
| 195 | 추가: macro_rules! refill { | |
| 196 | 추가: ($buffer:expr,$byte:expr,$bits_left:expr) => { | |
| 197 | 추가: // read a byte from the stream | |
| 198 | 추가: $byte = u64::from(reader.read_u8()); | |
| 199 | 추가: self.overread_by += usize::from(reader.eof()?); | |
| 200 | 추가: // append to the buffer | |
| 201 | 추가: // JPEG is a MSB type buffer so that means we append this | |
| 202 | 추가: // to the lower end (0..8) of the buffer and push the rest bits above.. | |
| 203 | 추가: $buffer = ($buffer << 8) | $byte; | |
| 204 | 추가: // Increment bits left | |
| 205 | 추가: $bits_left += 8; | |
| 206 | 추가: // Check for special case of OxFF, to see if it's a stream or a marker | |
| 207 | 추가: if $byte == 0xff { | |
| 208 | 추가: // read next byte | |
| 209 | 추가: let mut next_byte = u64::from(reader.read_u8()); | |
| 210 | 추가: // Byte snuffing, if we encounter byte snuff, we skip the byte | |
| 211 | 추가: if next_byte != 0x00 { | |
| 212 | 추가: // skip that byte we read | |
| 213 | 추가: while next_byte == 0xFF { | |
| 214 | 추가: next_byte = u64::from(reader.read_u8()); | |
| 215 | 추가: } | |
| 216 | 추가: | |
| 217 | 추가: if next_byte != 0x00 { | |
| 218 | 추가: // Undo the byte append and return | |
| 219 | 추가: $buffer >>= 8; | |
| 220 | 추가: $bits_left -= 8; | |
| 221 | 추가: | |
| 222 | 추가: if $bits_left != 0 { | |
| 223 | 추가: self.aligned_buffer = $buffer << (64 - $bits_left); | |
| 224 | 추가: } | |
| 225 | 추가: | |
| 226 | 추가: let marker = Marker::from_u8(next_byte as u8); | |
| 227 | 추가: self.marker = marker; | |
| 228 | 추가: | |
| 229 | 추가: if let Some(Marker::UNKNOWN(_)) = marker{ | |
| 230 | 추가: return Err(DecodeErrors::Format("Unknown marker in bit stream".to_string())); | |
| 231 | 추가: } | |
| 232 | 추가: if next_byte == 0xD9 { | |
| 233 | 추가: // special handling for eoi, fill some bytes,even if its zero, | |
| 234 | 추가: // removes some panics | |
| 235 | 추가: self.buffer <<= 8; | |
| 236 | 추가: self.bits_left += 8; | |
| 237 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 238 | 추가: } | |
| 239 | 추가: | |
| 240 | 추가: return Ok(false); | |
| 241 | 추가: } | |
| 242 | 추가: } | |
| 243 | 추가: } | |
| 244 | 추가: if self.overread_by == 0 { | |
| 245 | 추가: self.input_bits += 8; | |
| 246 | 추가: } | |
| 247 | 추가: }; | |
| 248 | 추가: } | |
| 249 | 추가: | |
| 250 | 추가: self.require_input()?; | |
| 251 | 추가: // 32 bits is enough for a decode(16 bits) and receive_extend(max 16 bits) | |
| 252 | 추가: if self.bits_left < 32 { | |
| 253 | 추가: if self.marker.is_some() || self.seen_eoi { | |
| 254 | 추가: // found a marker, or we are in EOI | |
| 255 | 추가: // also we are in over-reading mode, where we fill it with zeroes | |
| 256 | 추가: | |
| 257 | 추가: // fill with zeroes | |
| 258 | 추가: self.buffer <<= 32; | |
| 259 | 추가: self.bits_left += 32; | |
| 260 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 261 | 추가: return Ok(true); | |
| 262 | 추가: } | |
| 263 | 추가: | |
| 264 | 추가: if self.overread_by > 0 { | |
| 265 | 추가: if self.bits_left == 0 { | |
| 266 | 추가: return Err(DecodeErrors::ExhaustedData); | |
| 267 | 추가: } | |
| 268 | 추가: // We already hit EOF while refilling. Continue consuming the buffered bits | |
| 269 | 추가: // but don't synthesize additional bytes from zero-fill. | |
| 270 | 추가: return Ok(true); | |
| 271 | 추가: } | |
| 272 | 추가: | |
| 273 | 추가: // we optimize for the case where we don't have 255 in the stream and have 4 bytes left | |
| 274 | 추가: // as it is the common case | |
| 275 | 추가: // | |
| 276 | 추가: // so we always read 4 bytes, if read_fixed_bytes errors out, the cursor is | |
| 277 | 추가: // guaranteed not to advance in case of failure (is this true), so | |
| 278 | 추가: // we revert the read later on (if we have 255), if this fails, we use the normal | |
| 279 | 추가: // byte at a time read | |
| 280 | 추가: | |
| 281 | 추가: if let Ok(bytes) = reader.read_fixed_bytes_or_error::<4>() { | |
| 282 | 추가: // we have 4 bytes to spare, read the 4 bytes into a temporary buffer | |
| 283 | 추가: // create buffer | |
| 284 | 추가: let msb_buf = u32::from_be_bytes(bytes); | |
| 285 | 추가: // check if we have 0xff | |
| 286 | 추가: if !has_byte(msb_buf, 255) { | |
| 287 | 추가: self.bits_left += 32; | |
| 288 | 추가: self.input_bits += 32; | |
| 289 | 추가: self.buffer <<= 32; | |
| 290 | 추가: self.buffer |= u64::from(msb_buf); | |
| 291 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 292 | 추가: return Ok(true); | |
| 293 | 추가: } | |
| 294 | 추가: | |
| 295 | 추가: reader.rewind(4)?; | |
| 296 | 추가: } | |
| 297 | 추가: // This serves two reasons, | |
| 298 | 추가: // 1: Make clippy shut up | |
| 299 | 추가: // 2: Favour register reuse | |
| 300 | 추가: let mut byte; | |
| 301 | 추가: // 4 refills, if all succeed the stream should contain enough bits to decode a | |
| 302 | 추가: // value | |
| 303 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 304 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 305 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 306 | 추가: refill!(self.buffer, byte, self.bits_left); | |
| 307 | 추가: // Construct an MSB buffer whose top bits are the bitstream we are currently holding. | |
| 308 | 추가: self.aligned_buffer = self.buffer << (64 - self.bits_left); | |
| 309 | 추가: } | |
| 310 | 추가: return Ok(true); | |
| 311 | 추가: } | |
| 312 | 추가: /// Decode the DC coefficient in a MCU block. | |
| 313 | 추가: /// | |
| 314 | 추가: /// The decoded coefficient is written to `dc_prediction` | |
| 315 | 추가: /// | |
| 316 | 추가: #[allow( | |
| 317 | 추가: clippy::cast_possible_truncation, | |
| 318 | 추가: clippy::cast_sign_loss, | |
| 319 | 추가: clippy::unwrap_used | |
| 320 | 추가: )] | |
| 321 | 추가: #[inline(always)] | |
| 322 | 추가: fn decode_dc<T>( | |
| 323 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, dc_prediction: &mut i32 | |
| 324 | 추가: ) -> Result<bool, DecodeErrors> | |
| 325 | 추가: where | |
| 326 | 추가: T: ZByteReaderTrait | |
| 327 | 추가: { | |
| 328 | 추가: let (mut symbol, r); | |
| 329 | 추가: | |
| 330 | 추가: if self.bits_left < 32 { | |
| 331 | 추가: self.refill(reader)?; | |
| 332 | 추가: }; | |
| 333 | 추가: // look a head HUFF_LOOKAHEAD bits into the bitstream | |
| 334 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 335 | 추가: symbol = dc_table.lookup[symbol as usize]; | |
| 336 | 추가: | |
| 337 | 추가: decode_huff!(self, symbol, dc_table); | |
| 338 | 추가: | |
| 339 | 추가: if symbol != 0 { | |
| 340 | 추가: r = self.get_bits(symbol as u8); | |
| 341 | 추가: symbol = huff_extend(r, symbol); | |
| 342 | 추가: } | |
| 343 | 추가: // Update DC prediction | |
| 344 | 추가: *dc_prediction = dc_prediction.wrapping_add(symbol); | |
| 345 | 추가: | |
| 346 | 추가: return Ok(true); | |
| 347 | 추가: } | |
| 348 | 추가: | |
| 349 | 추가: /// Like `decode_dc` but we do not need the result of the component, we only want to remove it | |
| 350 | 추가: /// from the bitstream of the MCU. | |
| 351 | 추가: fn discard_dc<T>( | |
| 352 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable | |
| 353 | 추가: ) -> Result<bool, DecodeErrors> | |
| 354 | 추가: where | |
| 355 | 추가: T: ZByteReaderTrait | |
| 356 | 추가: { | |
| 357 | 추가: let mut symbol; | |
| 358 | 추가: | |
| 359 | 추가: if self.bits_left < 32 { | |
| 360 | 추가: self.refill(reader)?; | |
| 361 | 추가: }; | |
| 362 | 추가: // look a head HUFF_LOOKAHEAD bits into the bitstream | |
| 363 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 364 | 추가: symbol = dc_table.lookup[symbol as usize]; | |
| 365 | 추가: | |
| 366 | 추가: decode_huff!(self, symbol, dc_table); | |
| 367 | 추가: | |
| 368 | 추가: if symbol != 0 { | |
| 369 | 추가: let _ = self.get_bits(symbol as u8); | |
| 370 | 추가: } | |
| 371 | 추가: | |
| 372 | 추가: return Ok(true); | |
| 373 | 추가: } | |
| 374 | 추가: | |
| 375 | 추가: /// Decode a Minimum Code Unit(MCU) as quickly as possible | |
| 376 | 추가: /// | |
| 377 | 추가: /// # Arguments | |
| 378 | 추가: /// - reader: The bitstream from where we read more bits. | |
| 379 | 추가: /// - dc_table: The Huffman table used to decode the DC coefficient | |
| 380 | 추가: /// - ac_table: The Huffman table used to decode AC values | |
| 381 | 추가: /// - block: A memory region where we will write out the decoded values | |
| 382 | 추가: /// - DC prediction: Last DC value for this component | |
| 383 | 추가: /// | |
| 384 | 추가: #[allow( | |
| 385 | 추가: clippy::many_single_char_names, | |
| 386 | 추가: clippy::cast_possible_truncation, | |
| 387 | 추가: clippy::cast_sign_loss | |
| 388 | 추가: )] | |
| 389 | 추가: #[inline(never)] | |
| 390 | 추가: pub fn decode_mcu_block<T>( | |
| 391 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable, | |
| 392 | 추가: qt_table: &[i32; DCT_BLOCK], block: &mut [i32; 64], dc_prediction: &mut i32 | |
| 393 | 추가: ) -> Result<u16, DecodeErrors> | |
| 394 | 추가: where | |
| 395 | 추가: T: ZByteReaderTrait | |
| 396 | 추가: { | |
| 397 | 추가: // Get fast AC table as a reference before we enter the hot path | |
| 398 | 추가: let ac_lookup = ac_table.ac_lookup.as_ref().unwrap(); | |
| 399 | 추가: | |
| 400 | 추가: let (mut symbol, mut r, mut fast_ac); | |
| 401 | 추가: // Decode AC coefficients | |
| 402 | 추가: let mut pos: usize = 1; | |
| 403 | 추가: if self.bits_left < 1 && self.marker.is_some() { | |
| 404 | 추가: return Err(DecodeErrors::Format( | |
| 405 | 추가: "No more bytes left in stream before marker".to_string() | |
| 406 | 추가: )); | |
| 407 | 추가: } | |
| 408 | 추가: // decode DC, dc prediction will contain the value | |
| 409 | 추가: self.decode_dc(reader, dc_table, dc_prediction)?; | |
| 410 | 추가: | |
| 411 | 추가: // set dc to be the dc prediction. | |
| 412 | 추가: block[0] = *dc_prediction * qt_table[0]; | |
| 413 | 추가: | |
| 414 | 추가: while pos < 64 { | |
| 415 | 추가: self.refill(reader)?; | |
| 416 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 417 | 추가: fast_ac = ac_lookup[symbol as usize]; | |
| 418 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 419 | 추가: | |
| 420 | 추가: if fast_ac != 0 { | |
| 421 | 추가: // FAST AC path | |
| 422 | 추가: pos += ((fast_ac >> 4) & 15) as usize; // run | |
| 423 | 추가: let t_pos = UN_ZIGZAG[min(pos, 63)] & 63; | |
| 424 | 추가: | |
| 425 | 추가: block[t_pos] = i32::from(fast_ac >> 8) * (qt_table[t_pos]); // Value | |
| 426 | 추가: self.drop_bits((fast_ac & 15) as u8); | |
| 427 | 추가: pos += 1; | |
| 428 | 추가: } else { | |
| 429 | 추가: decode_huff!(self, symbol, ac_table); | |
| 430 | 추가: | |
| 431 | 추가: r = symbol >> 4; | |
| 432 | 추가: symbol &= 15; | |
| 433 | 추가: | |
| 434 | 추가: if symbol != 0 { | |
| 435 | 추가: pos += r as usize; | |
| 436 | 추가: r = self.get_bits(symbol as u8); | |
| 437 | 추가: symbol = huff_extend(r, symbol); | |
| 438 | 추가: let t_pos = UN_ZIGZAG[pos & 63] & 63; | |
| 439 | 추가: | |
| 440 | 추가: block[t_pos] = symbol * qt_table[t_pos]; | |
| 441 | 추가: | |
| 442 | 추가: pos += 1; | |
| 443 | 추가: } else if r != 15 { | |
| 444 | 추가: return Ok(pos as u16); | |
| 445 | 추가: } else { | |
| 446 | 추가: pos += 16; | |
| 447 | 추가: } | |
| 448 | 추가: } | |
| 449 | 추가: } | |
| 450 | 추가: | |
| 451 | 추가: return Ok(64); | |
| 452 | 추가: } | |
| 453 | 추가: | |
| 454 | 추가: /// Advance the bitstream over a block but ignore the data contained. | |
| 455 | 추가: /// | |
| 456 | 추가: /// This updates DC prediction but we never dequantize and we never do any Zig-Zag translation | |
| 457 | 추가: /// either. Still returns the index of the last component read. | |
| 458 | 추가: pub fn discard_mcu_block<T>( | |
| 459 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, ac_table: &HuffmanTable | |
| 460 | 추가: ) -> Result<u16, DecodeErrors> | |
| 461 | 추가: where | |
| 462 | 추가: T: ZByteReaderTrait | |
| 463 | 추가: { | |
| 464 | 추가: // Get fast AC table as a reference before we enter the hot path | |
| 465 | 추가: let ac_lookup = ac_table.ac_lookup.as_ref().unwrap(); | |
| 466 | 추가: | |
| 467 | 추가: let (mut symbol, mut r, mut fast_ac); | |
| 468 | 추가: // Decode AC coefficients | |
| 469 | 추가: let mut pos: usize = 1; | |
| 470 | 추가: | |
| 471 | 추가: // decode DC, dc prediction will contain the value | |
| 472 | 추가: self.discard_dc(reader, dc_table)?; | |
| 473 | 추가: | |
| 474 | 추가: while pos < 64 { | |
| 475 | 추가: self.refill(reader)?; | |
| 476 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 477 | 추가: fast_ac = ac_lookup[symbol as usize]; | |
| 478 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 479 | 추가: | |
| 480 | 추가: if fast_ac != 0 { | |
| 481 | 추가: // FAST AC path | |
| 482 | 추가: pos += ((fast_ac >> 4) & 15) as usize; // run | |
| 483 | 추가: | |
| 484 | 추가: self.drop_bits((fast_ac & 15) as u8); | |
| 485 | 추가: pos += 1; | |
| 486 | 추가: } else { | |
| 487 | 추가: decode_huff!(self, symbol, ac_table); | |
| 488 | 추가: | |
| 489 | 추가: r = symbol >> 4; | |
| 490 | 추가: symbol &= 15; | |
| 491 | 추가: | |
| 492 | 추가: if symbol != 0 { | |
| 493 | 추가: pos += r as usize; | |
| 494 | 추가: // Advance over bits but ignore. | |
| 495 | 추가: let _ = self.get_bits(symbol as u8); | |
| 496 | 추가: | |
| 497 | 추가: pos += 1; | |
| 498 | 추가: } else if r != 15 { | |
| 499 | 추가: return Ok(pos as u16); | |
| 500 | 추가: } else { | |
| 501 | 추가: pos += 16; | |
| 502 | 추가: } | |
| 503 | 추가: } | |
| 504 | 추가: } | |
| 505 | 추가: | |
| 506 | 추가: return Ok(64); | |
| 507 | 추가: } | |
| 508 | 추가: | |
| 509 | 추가: /// Peek `look_ahead` bits ahead without discarding them from the buffer | |
| 510 | 추가: #[inline(always)] | |
| 511 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 512 | 추가: const fn peek_bits<const LOOKAHEAD: u8>(&self) -> i32 { | |
| 513 | 추가: (self.aligned_buffer >> (64 - LOOKAHEAD)) as i32 | |
| 514 | 추가: } | |
| 515 | 추가: | |
| 516 | 추가: /// Discard the next `N` bits without checking | |
| 517 | 추가: #[inline] | |
| 518 | 추가: fn drop_bits(&mut self, n: u8) { | |
| 519 | 추가: self.consume_input(n); | |
| 520 | 추가: // PS: Its a good check, but triggers fuzzer and a lot of false positives | |
| 521 | 추가: //debug_assert!(self.bits_left >= n); | |
| 522 | 추가: //self.bits_left -= n; | |
| 523 | 추가: self.bits_left = self.bits_left.saturating_sub(n); | |
| 524 | 추가: self.aligned_buffer <<= n; | |
| 525 | 추가: } | |
| 526 | 추가: | |
| 527 | 추가: /// Read `n_bits` from the buffer and discard them | |
| 528 | 추가: #[inline(always)] | |
| 529 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 530 | 추가: fn get_bits(&mut self, n_bits: u8) -> i32 { | |
| 531 | 추가: self.consume_input(n_bits); | |
| 532 | 추가: let mask = (1_u64 << n_bits) - 1; | |
| 533 | 추가: | |
| 534 | 추가: self.aligned_buffer = self.aligned_buffer.rotate_left(u32::from(n_bits)); | |
| 535 | 추가: let bits = (self.aligned_buffer & mask) as i32; | |
| 536 | 추가: self.bits_left = self.bits_left.wrapping_sub(n_bits); | |
| 537 | 추가: bits | |
| 538 | 추가: } | |
| 539 | 추가: | |
| 540 | 추가: /// Decode a DC block | |
| 541 | 추가: #[allow(clippy::cast_possible_truncation)] | |
| 542 | 추가: #[inline] | |
| 543 | 추가: pub(crate) fn decode_prog_dc_first<T>( | |
| 544 | 추가: &mut self, reader: &mut ZReader<T>, dc_table: &HuffmanTable, block: &mut i16, | |
| 545 | 추가: dc_prediction: &mut i32 | |
| 546 | 추가: ) -> Result<(), DecodeErrors> | |
| 547 | 추가: where | |
| 548 | 추가: T: ZByteReaderTrait | |
| 549 | 추가: { | |
| 550 | 추가: self.decode_dc(reader, dc_table, dc_prediction)?; | |
| 551 | 추가: *block = (*dc_prediction as i16).wrapping_mul(self.successive_low_mask); | |
| 552 | 추가: return Ok(()); | |
| 553 | 추가: } | |
| 554 | 추가: #[inline] | |
| 555 | 추가: pub(crate) fn decode_prog_dc_refine<T>( | |
| 556 | 추가: &mut self, reader: &mut ZReader<T>, block: &mut i16 | |
| 557 | 추가: ) -> Result<(), DecodeErrors> | |
| 558 | 추가: where | |
| 559 | 추가: T: ZByteReaderTrait | |
| 560 | 추가: { | |
| 561 | 추가: // refinement scan | |
| 562 | 추가: if self.bits_left < 1 { | |
| 563 | 추가: self.refill(reader)?; | |
| 564 | 추가: // if we find a marker, it may happens we don't refill. | |
| 565 | 추가: // So let's confirm again that refill worked | |
| 566 | 추가: if self.bits_left < 1 { | |
| 567 | 추가: return Err(DecodeErrors::Format( | |
| 568 | 추가: "Marker found where not expected in refine bit".to_string() | |
| 569 | 추가: )); | |
| 570 | 추가: } | |
| 571 | 추가: } | |
| 572 | 추가: | |
| 573 | 추가: if self.get_bit() == 1 { | |
| 574 | 추가: *block = block.wrapping_add(self.successive_low_mask); | |
| 575 | 추가: } | |
| 576 | 추가: | |
| 577 | 추가: Ok(()) | |
| 578 | 추가: } | |
| 579 | 추가: | |
| 580 | 추가: /// Get a single bit from the bitstream | |
| 581 | 추가: fn get_bit(&mut self) -> u8 { | |
| 582 | 추가: let k = (self.aligned_buffer >> 63) as u8; | |
| 583 | 추가: // discard a bit | |
| 584 | 추가: self.drop_bits(1); | |
| 585 | 추가: return k; | |
| 586 | 추가: } | |
| 587 | 추가: pub(crate) fn decode_mcu_ac_first<T>( | |
| 588 | 추가: &mut self, reader: &mut ZReader<T>, ac_table: &HuffmanTable, block: &mut [i16; 64] | |
| 589 | 추가: ) -> Result<bool, DecodeErrors> | |
| 590 | 추가: where | |
| 591 | 추가: T: ZByteReaderTrait | |
| 592 | 추가: { | |
| 593 | 추가: let fast_ac = ac_table.ac_lookup.as_ref().unwrap(); | |
| 594 | 추가: let bit = self.successive_low_mask; | |
| 595 | 추가: | |
| 596 | 추가: let mut k = self.spec_start as usize; | |
| 597 | 추가: let (mut symbol, mut r, mut fac); | |
| 598 | 추가: | |
| 599 | 추가: // EOB runs are handled in mcu_prog.rs | |
| 600 | 추가: 'block: loop { | |
| 601 | 추가: self.refill(reader)?; | |
| 602 | 추가: // Check for marker in the stream | |
| 603 | 추가: | |
| 604 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 605 | 추가: fac = fast_ac[symbol as usize]; | |
| 606 | 추가: symbol = ac_table.lookup[symbol as usize]; | |
| 607 | 추가: | |
| 608 | 추가: if fac != 0 { | |
| 609 | 추가: // fast ac path | |
| 610 | 추가: k += ((fac >> 4) & 15) as usize; // run | |
| 611 | 추가: block[UN_ZIGZAG[min(k, 63)] & 63] = (fac >> 8).wrapping_mul(bit); // value | |
| 612 | 추가: self.drop_bits((fac & 15) as u8); | |
| 613 | 추가: k += 1; | |
| 614 | 추가: } else { | |
| 615 | 추가: decode_huff!(self, symbol, ac_table); | |
| 616 | 추가: | |
| 617 | 추가: r = symbol >> 4; | |
| 618 | 추가: symbol &= 15; | |
| 619 | 추가: | |
| 620 | 추가: if symbol != 0 { | |
| 621 | 추가: k += r as usize; | |
| 622 | 추가: r = self.get_bits(symbol as u8); | |
| 623 | 추가: symbol = huff_extend(r, symbol); | |
| 624 | 추가: block[UN_ZIGZAG[k & 63] & 63] = (symbol as i16).wrapping_mul(bit); | |
| 625 | 추가: k += 1; | |
| 626 | 추가: } else { | |
| 627 | 추가: if r != 15 { | |
| 628 | 추가: self.eob_run = 1 << r; | |
| 629 | 추가: self.eob_run += self.get_bits(r as u8); | |
| 630 | 추가: self.eob_run -= 1; | |
| 631 | 추가: break; | |
| 632 | 추가: } | |
| 633 | 추가: | |
| 634 | 추가: k += 16; | |
| 635 | 추가: } | |
| 636 | 추가: } | |
| 637 | 추가: | |
| 638 | 추가: if k > self.spec_end as usize { | |
| 639 | 추가: break 'block; | |
| 640 | 추가: } | |
| 641 | 추가: } | |
| 642 | 추가: return Ok(true); | |
| 643 | 추가: } | |
| 644 | 추가: #[allow(clippy::too_many_lines, clippy::op_ref)] | |
| 645 | 추가: pub(crate) fn decode_mcu_ac_refine<T>( | |
| 646 | 추가: &mut self, reader: &mut ZReader<T>, table: &HuffmanTable, block: &mut [i16; 64] | |
| 647 | 추가: ) -> Result<bool, DecodeErrors> | |
| 648 | 추가: where | |
| 649 | 추가: T: ZByteReaderTrait | |
| 650 | 추가: { | |
| 651 | 추가: let bit = self.successive_low_mask; | |
| 652 | 추가: | |
| 653 | 추가: let mut k = self.spec_start; | |
| 654 | 추가: let (mut symbol, mut r); | |
| 655 | 추가: | |
| 656 | 추가: if self.eob_run == 0 { | |
| 657 | 추가: 'no_eob: loop { | |
| 658 | 추가: // Decode a coefficient from the bit stream | |
| 659 | 추가: self.refill(reader)?; | |
| 660 | 추가: | |
| 661 | 추가: symbol = self.peek_bits::<HUFF_LOOKAHEAD>(); | |
| 662 | 추가: symbol = table.lookup[symbol as usize]; | |
| 663 | 추가: | |
| 664 | 추가: decode_huff!(self, symbol, table); | |
| 665 | 추가: | |
| 666 | 추가: r = symbol >> 4; | |
| 667 | 추가: symbol &= 15; | |
| 668 | 추가: | |
| 669 | 추가: if symbol == 0 { | |
| 670 | 추가: if r != 15 { | |
| 671 | 추가: // EOB run is 2^r + bits | |
| 672 | 추가: self.eob_run = 1 << r; | |
| 673 | 추가: self.eob_run += self.get_bits(r as u8); | |
| 674 | 추가: // EOB runs are handled by the eob logic | |
| 675 | 추가: break 'no_eob; | |
| 676 | 추가: } | |
| 677 | 추가: } else { | |
| 678 | 추가: // libjpeg-turbo also doesn't return an error here, so let's also warn. | |
| 679 | 추가: if symbol != 1 { | |
| 680 | 추가: warn!("Bad Huffman code, corrupt JPEG?"); | |
| 681 | 추가: } | |
| 682 | 추가: // get sign bit | |
| 683 | 추가: // We assume we have enough bits, which should be correct for sane images | |
| 684 | 추가: // since we refill by 32 above | |
| 685 | 추가: if self.get_bit() == 1 { | |
| 686 | 추가: symbol = i32::from(bit); | |
| 687 | 추가: } else { | |
| 688 | 추가: symbol = i32::from(-bit); | |
| 689 | 추가: } | |
| 690 | 추가: } | |
| 691 | 추가: | |
| 692 | 추가: // Advance over already nonzero coefficients appending | |
| 693 | 추가: // correction bits to the non-zeroes. | |
| 694 | 추가: // A correction bit is 1 if the absolute value of the coefficient must be increased | |
| 695 | 추가: | |
| 696 | 추가: if k <= self.spec_end { | |
| 697 | 추가: 'advance_nonzero: loop { | |
| 698 | 추가: let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63]; | |
| 699 | 추가: | |
| 700 | 추가: if *coefficient != 0 { | |
| 701 | 추가: if self.bits_left < 1 { | |
| 702 | 추가: self.refill(reader)?; | |
| 703 | 추가: if self.bits_left < 1 && self.marker.is_some() { | |
| 704 | 추가: return Err(DecodeErrors::Format( | |
| 705 | 추가: "Marker found where not expected in refine bit".to_string() | |
| 706 | 추가: )); | |
| 707 | 추가: } | |
| 708 | 추가: } | |
| 709 | 추가: if self.get_bit() == 1 && (*coefficient & bit) == 0 { | |
| 710 | 추가: if *coefficient > 0 { | |
| 711 | 추가: *coefficient = coefficient.wrapping_add(bit); | |
| 712 | 추가: } else { | |
| 713 | 추가: *coefficient = coefficient.wrapping_sub(bit); | |
| 714 | 추가: } | |
| 715 | 추가: } | |
| 716 | 추가: } else { | |
| 717 | 추가: r -= 1; | |
| 718 | 추가: | |
| 719 | 추가: if r < 0 { | |
| 720 | 추가: // reached target zero coefficient. | |
| 721 | 추가: break 'advance_nonzero; | |
| 722 | 추가: } | |
| 723 | 추가: }; | |
| 724 | 추가: | |
| 725 | 추가: if k == self.spec_end { | |
| 726 | 추가: break 'advance_nonzero; | |
| 727 | 추가: } | |
| 728 | 추가: | |
| 729 | 추가: k += 1; | |
| 730 | 추가: } | |
| 731 | 추가: } | |
| 732 | 추가: | |
| 733 | 추가: if symbol != 0 { | |
| 734 | 추가: let pos = UN_ZIGZAG[k as usize & 63]; | |
| 735 | 추가: // output new non-zero coefficient. | |
| 736 | 추가: block[pos & 63] = symbol as i16; | |
| 737 | 추가: } | |
| 738 | 추가: | |
| 739 | 추가: k += 1; | |
| 740 | 추가: | |
| 741 | 추가: if k > self.spec_end { | |
| 742 | 추가: break 'no_eob; | |
| 743 | 추가: } | |
| 744 | 추가: } | |
| 745 | 추가: } | |
| 746 | 추가: if self.eob_run > 0 { | |
| 747 | 추가: // only run if block does not consists of purely zeroes | |
| 748 | 추가: if &block[1..] != &[0; 63] { | |
| 749 | 추가: self.refill(reader)?; | |
| 750 | 추가: | |
| 751 | 추가: while k <= self.spec_end { | |
| 752 | 추가: let coefficient = &mut block[UN_ZIGZAG[k as usize & 63] & 63]; | |
| 753 | 추가: | |
| 754 | 추가: if *coefficient != 0 && self.get_bit() == 1 { | |
| 755 | 추가: // check if we already modified it, if so do nothing, otherwise | |
| 756 | 추가: // append the correction bit. | |
| 757 | 추가: if (*coefficient & bit) == 0 { | |
| 758 | 추가: if *coefficient >= 0 { | |
| 759 | 추가: *coefficient = coefficient.wrapping_add(bit); | |
| 760 | 추가: } else { | |
| 761 | 추가: *coefficient = coefficient.wrapping_sub(bit); | |
| 762 | 추가: } | |
| 763 | 추가: } | |
| 764 | 추가: } | |
| 765 | 추가: if self.bits_left < 1 { | |
| 766 | 추가: // refill at the last possible moment | |
| 767 | 추가: self.refill(reader)?; | |
| 768 | 추가: } | |
| 769 | 추가: k += 1; | |
| 770 | 추가: } | |
| 771 | 추가: } | |
| 772 | 추가: // count a block completed in EOB run | |
| 773 | 추가: self.eob_run -= 1; | |
| 774 | 추가: } | |
| 775 | 추가: return Ok(true); | |
| 776 | 추가: } | |
| 777 | 추가: | |
| 778 | 추가: pub fn update_progressive_params(&mut self, _ah: u8, al: u8, spec_start: u8, spec_end: u8) { | |
| 779 | 추가: self.successive_low_mask = 1i16 << al; | |
| 780 | 추가: self.spec_start = spec_start; | |
| 781 | 추가: self.spec_end = spec_end; | |
| 782 | 추가: } | |
| 783 | 추가: | |
| 784 | 추가: fn consume_input(&mut self, bits: u8) { | |
| 785 | 추가: self.exhausted_input |= bits > self.input_bits; | |
| 786 | 추가: self.input_bits = self.input_bits.saturating_sub(bits); | |
| 787 | 추가: } | |
| 788 | 추가: | |
| 789 | 추가: pub(crate) fn require_input(&self) -> Result<(), DecodeErrors> { | |
| 790 | 추가: if self.exhausted_input { | |
| 791 | 추가: return Err(DecodeErrors::FormatStatic("Incomplete entropy-coded image data")); | |
| 792 | 추가: } | |
| 793 | 추가: Ok(()) | |
| 794 | 추가: } | |
| 795 | 추가: | |
| 796 | 추가: /// Reset the stream if we have a restart marker | |
| 797 | 추가: /// | |
| 798 | 추가: /// Restart markers indicate drop those bits in the stream and zero out | |
| 799 | 추가: /// everything | |
| 800 | 추가: #[cold] | |
| 801 | 추가: pub fn reset(&mut self) { | |
| 802 | 추가: self.bits_left = 0; | |
| 803 | 추가: self.input_bits = 0; | |
| 804 | 추가: self.exhausted_input = false; | |
| 805 | 추가: self.marker = None; | |
| 806 | 추가: self.buffer = 0; | |
| 807 | 추가: self.aligned_buffer = 0; | |
| 808 | 추가: self.eob_run = 0; | |
| 809 | 추가: } | |
| 810 | 추가: } | |
| 811 | 추가: | |
| 812 | 추가: /// Do the equivalent of JPEG HUFF_EXTEND | |
| 813 | 추가: #[inline(always)] | |
| 814 | 추가: fn huff_extend(x: i32, s: i32) -> i32 { | |
| 815 | 추가: // if x<s return x else return x+offset[s] where offset[s] = ( (-1<<s)+1) | |
| 816 | 추가: (x) + ((((x) - (1 << ((s) - 1))) >> 31) & (((-1) << (s)) + 1)) | |
| 817 | 추가: } | |
| 818 | 추가: | |
| 819 | 추가: const fn has_zero(v: u32) -> bool { | |
| 820 | 추가: // Retrieved from Stanford bithacks | |
| 821 | 추가: // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord | |
| 822 | 추가: return !((((v & 0x7F7F_7F7F) + 0x7F7F_7F7F) | v) | 0x7F7F_7F7F) != 0; | |
| 823 | 추가: } | |
| 824 | 추가: | |
| 825 | 추가: const fn has_byte(b: u32, val: u8) -> bool { | |
| 826 | 추가: // Retrieved from Stanford bithacks | |
| 827 | 추가: // @ https://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord | |
| 828 | 추가: has_zero(b ^ ((!0_u32 / 255) * (val as u32))) | |
| 829 | 추가: } |
| @@ -0,0 +1,102 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: #![allow( | |
| 10 | 추가: clippy::many_single_char_names, | |
| 11 | 추가: clippy::similar_names, | |
| 12 | 추가: clippy::cast_possible_truncation, | |
| 13 | 추가: clippy::cast_sign_loss, | |
| 14 | 추가: clippy::cast_possible_wrap, | |
| 15 | 추가: clippy::too_many_arguments, | |
| 16 | 추가: clippy::doc_markdown | |
| 17 | 추가: )] | |
| 18 | 추가: | |
| 19 | 추가: //! Color space conversion routines | |
| 20 | 추가: //! | |
| 21 | 추가: //! This files exposes functions to convert one colorspace to another in a jpeg | |
| 22 | 추가: //! image | |
| 23 | 추가: //! | |
| 24 | 추가: //! Currently supported conversions are | |
| 25 | 추가: //! | |
| 26 | 추가: //! - `YCbCr` to `RGB,RGBA,GRAYSCALE,RGBX`. | |
| 27 | 추가: //! | |
| 28 | 추가: //! | |
| 29 | 추가: //! Hey there, if your reading this it means you probably need something, so let me help you. | |
| 30 | 추가: //! | |
| 31 | 추가: //! There are 3 supported cpu extensions here. | |
| 32 | 추가: //! 1. Scalar | |
| 33 | 추가: //! 2. SSE | |
| 34 | 추가: //! 3. AVX | |
| 35 | 추가: //! | |
| 36 | 추가: //! There are two types of the color convert functions | |
| 37 | 추가: //! | |
| 38 | 추가: //! 1. Acts on 16 pixels. | |
| 39 | 추가: //! 2. Acts on 8 pixels. | |
| 40 | 추가: //! | |
| 41 | 추가: //! The reason for this is because when implementing the AVX part it occurred to me that we can actually | |
| 42 | 추가: //! do better and process 2 MCU's if we change IDCT return type to be `i16's`, since a lot of | |
| 43 | 추가: //! CPU's these days support AVX extensions, it becomes nice if we optimize for that path , | |
| 44 | 추가: //! therefore AVX routines can process 16 pixels directly and SSE and Scalar just compensate. | |
| 45 | 추가: //! | |
| 46 | 추가: //! By compensating, I mean I wrote the 16 pixels version operating on the 8 pixel version twice. | |
| 47 | 추가: //! | |
| 48 | 추가: //! Therefore if your looking to optimize some routines, probably start there. | |
| 49 | 추가: | |
| 50 | 추가: pub use scalar::ycbcr_to_grayscale; | |
| 51 | 추가: use zune_core::colorspace::ColorSpace; | |
| 52 | 추가: use zune_core::options::DecoderOptions; | |
| 53 | 추가: | |
| 54 | 추가: #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 55 | 추가: #[cfg(feature = "x86")] | |
| 56 | 추가: pub use crate::color_convert::avx::{ycbcr_to_rgb_avx2, ycbcr_to_rgba_avx2}; | |
| 57 | 추가: use crate::decoder::ColorConvert16Ptr; | |
| 58 | 추가: | |
| 59 | 추가: mod avx; | |
| 60 | 추가: mod neon64; | |
| 61 | 추가: mod scalar; | |
| 62 | 추가: | |
| 63 | 추가: #[allow(unused_variables)] | |
| 64 | 추가: pub fn choose_ycbcr_to_rgb_convert_func( | |
| 65 | 추가: type_need: ColorSpace, options: &DecoderOptions | |
| 66 | 추가: ) -> Option<ColorConvert16Ptr> { | |
| 67 | 추가: #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 68 | 추가: #[cfg(feature = "x86")] | |
| 69 | 추가: { | |
| 70 | 추가: use zune_core::log::debug; | |
| 71 | 추가: if options.use_avx2() { | |
| 72 | 추가: debug!("Using AVX optimised color conversion functions"); | |
| 73 | 추가: | |
| 74 | 추가: // I believe avx2 means sse4 is also available | |
| 75 | 추가: // match colorspace | |
| 76 | 추가: match type_need { | |
| 77 | 추가: ColorSpace::RGB => return Some(ycbcr_to_rgb_avx2), | |
| 78 | 추가: ColorSpace::RGBA => return Some(ycbcr_to_rgba_avx2), | |
| 79 | 추가: _ => () // fall through to scalar, which has more types | |
| 80 | 추가: }; | |
| 81 | 추가: } | |
| 82 | 추가: } | |
| 83 | 추가: #[cfg(all(feature = "neon", target_arch = "aarch64"))] | |
| 84 | 추가: { | |
| 85 | 추가: if options.use_neon() { | |
| 86 | 추가: use crate::color_convert::neon64::{ycbcr_to_rgb_neon, ycbcr_to_rgba_neon}; | |
| 87 | 추가: match type_need { | |
| 88 | 추가: ColorSpace::RGB => return Some(ycbcr_to_rgb_neon), | |
| 89 | 추가: ColorSpace::RGBA => return Some(ycbcr_to_rgba_neon), | |
| 90 | 추가: _ => () // fall through to scalar, which has more types | |
| 91 | 추가: }; | |
| 92 | 추가: } | |
| 93 | 추가: } | |
| 94 | 추가: // when there is no x86 or we haven't returned by here, resort to scalar | |
| 95 | 추가: return match type_need { | |
| 96 | 추가: ColorSpace::RGB => Some(scalar::ycbcr_to_rgb_inner_16_scalar::<false>), | |
| 97 | 추가: ColorSpace::RGBA => Some(scalar::ycbcr_to_rgba_inner_16_scalar::<false>), | |
| 98 | 추가: ColorSpace::BGRA => Some(scalar::ycbcr_to_rgba_inner_16_scalar::<true>), | |
| 99 | 추가: ColorSpace::BGR => Some(scalar::ycbcr_to_rgb_inner_16_scalar::<true>), | |
| 100 | 추가: _ => None | |
| 101 | 추가: }; | |
| 102 | 추가: } |
| @@ -0,0 +1,297 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: //! AVX color conversion routines | |
| 10 | 추가: //! | |
| 11 | 추가: //! Okay these codes are cool | |
| 12 | 추가: //! | |
| 13 | 추가: //! Herein lies super optimized codes to do color conversions. | |
| 14 | 추가: //! | |
| 15 | 추가: //! | |
| 16 | 추가: //! 1. The YCbCr to RGB use integer approximations and not the floating point equivalent. | |
| 17 | 추가: //! That means we may be +- 2 of pixels generated by libjpeg-turbo jpeg decoding | |
| 18 | 추가: //! (also libjpeg uses routines like `Y = 0.29900 * R + 0.33700 * G + 0.11400 * B + 0.25000 * G`) | |
| 19 | 추가: //! | |
| 20 | 추가: //! Firstly, we use integers (fun fact:there is no part of this code base where were dealing with | |
| 21 | 추가: //! floating points.., fun fact: the first fun fact wasn't even fun.) | |
| 22 | 추가: //! | |
| 23 | 추가: //! Secondly ,we have cool clamping code, especially for rgba , where we don't need clamping and we | |
| 24 | 추가: //! spend our time cursing that Intel decided permute instructions to work like 2 128 bit vectors(the compiler opitmizes | |
| 25 | 추가: //! it out to something cool). | |
| 26 | 추가: //! | |
| 27 | 추가: //! There isn't a lot here (not as fun as bitstream ) but I hope you find what you're looking for. | |
| 28 | 추가: //! | |
| 29 | 추가: //! O and ~~subscribe to my youtube channel~~ | |
| 30 | 추가: | |
| 31 | 추가: #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] | |
| 32 | 추가: #![cfg(feature = "x86")] | |
| 33 | 추가: #![allow( | |
| 34 | 추가: clippy::wildcard_imports, | |
| 35 | 추가: clippy::cast_possible_truncation, | |
| 36 | 추가: clippy::too_many_arguments, | |
| 37 | 추가: clippy::inline_always, | |
| 38 | 추가: clippy::doc_markdown, | |
| 39 | 추가: dead_code | |
| 40 | 추가: )] | |
| 41 | 추가: | |
| 42 | 추가: #[cfg(target_arch = "x86")] | |
| 43 | 추가: use core::arch::x86::*; | |
| 44 | 추가: #[cfg(target_arch = "x86_64")] | |
| 45 | 추가: use core::arch::x86_64::*; | |
| 46 | 추가: | |
| 47 | 추가: use crate::color_convert::scalar::{CB_CF, CR_CF, C_G_CB_COEF_2, C_G_CR_COEF_1, YUV_RND, Y_CF}; | |
| 48 | 추가: | |
| 49 | 추가: pub union YmmRegister { | |
| 50 | 추가: // both are 32 when using std::mem::size_of | |
| 51 | 추가: mm256: __m256i, | |
| 52 | 추가: // for avx color conversion | |
| 53 | 추가: array: [i16; 16] | |
| 54 | 추가: } | |
| 55 | 추가: | |
| 56 | 추가: const R_AVX_COEF: i32 = i32::from_ne_bytes([CR_CF.to_ne_bytes()[0], CR_CF.to_ne_bytes()[1], 0, 0]); | |
| 57 | 추가: const B_AVX_COEF: i32 = i32::from_ne_bytes([0, 0, CB_CF.to_ne_bytes()[0], CB_CF.to_ne_bytes()[1]]); | |
| 58 | 추가: const G_COEF_AVX_COEF: i32 = i32::from_ne_bytes([ | |
| 59 | 추가: C_G_CR_COEF_1.to_ne_bytes()[0], | |
| 60 | 추가: C_G_CR_COEF_1.to_ne_bytes()[1], | |
| 61 | 추가: C_G_CB_COEF_2.to_ne_bytes()[0], | |
| 62 | 추가: C_G_CB_COEF_2.to_ne_bytes()[1] | |
| 63 | 추가: ]); | |
| 64 | 추가: | |
| 65 | 추가: //-------------------------------------------------------------------------------------------------- | |
| 66 | 추가: // AVX conversion routines | |
| 67 | 추가: //-------------------------------------------------------------------------------------------------- | |
| 68 | 추가: | |
| 69 | 추가: /// | |
| 70 | 추가: /// Convert YCBCR to RGB using AVX instructions | |
| 71 | 추가: /// | |
| 72 | 추가: /// # Note | |
| 73 | 추가: ///**IT IS THE RESPONSIBILITY OF THE CALLER TO CALL THIS IN CPUS SUPPORTING | |
| 74 | 추가: /// AVX2 OTHERWISE THIS IS UB** | |
| 75 | 추가: /// | |
| 76 | 추가: /// *Peace* | |
| 77 | 추가: /// | |
| 78 | 추가: /// This library itself will ensure that it's never called in CPU's not | |
| 79 | 추가: /// supporting AVX2 | |
| 80 | 추가: /// | |
| 81 | 추가: /// # Arguments | |
| 82 | 추가: /// - `y`,`cb`,`cr`: A reference of 8 i32's | |
| 83 | 추가: /// - `out`: The output array where we store our converted items | |
| 84 | 추가: /// - `offset`: The position from 0 where we write these RGB values | |
| 85 | 추가: #[inline(always)] | |
| 86 | 추가: pub fn ycbcr_to_rgb_avx2( | |
| 87 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 88 | 추가: ) { | |
| 89 | 추가: // call this in another function to tell RUST to vectorize this | |
| 90 | 추가: // storing | |
| 91 | 추가: unsafe { | |
| 92 | 추가: ycbcr_to_rgb_avx2_1(y, cb, cr, out, offset); | |
| 93 | 추가: } | |
| 94 | 추가: } | |
| 95 | 추가: | |
| 96 | 추가: #[inline] | |
| 97 | 추가: #[target_feature(enable = "avx2")] | |
| 98 | 추가: unsafe fn ycbcr_to_rgb_avx2_1( | |
| 99 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 100 | 추가: ) { | |
| 101 | 추가: let (mut r, mut g, mut b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 102 | 추가: | |
| 103 | 추가: r = _mm256_packus_epi16(r, _mm256_setzero_si256()); | |
| 104 | 추가: g = _mm256_packus_epi16(g, _mm256_setzero_si256()); | |
| 105 | 추가: b = _mm256_packus_epi16(b, _mm256_setzero_si256()); | |
| 106 | 추가: | |
| 107 | 추가: r = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(r); | |
| 108 | 추가: g = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(g); | |
| 109 | 추가: b = _mm256_permute4x64_epi64::<{ shuffle(3, 1, 2, 0) }>(b); | |
| 110 | 추가: | |
| 111 | 추가: let sh_r = _mm256_setr_epi8( | |
| 112 | 추가: 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, | |
| 113 | 추가: 9, 4, 15, 10, 5 | |
| 114 | 추가: ); | |
| 115 | 추가: let sh_g = _mm256_setr_epi8( | |
| 116 | 추가: 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, | |
| 117 | 추가: 14, 9, 4, 15, 10 | |
| 118 | 추가: ); | |
| 119 | 추가: let sh_b = _mm256_setr_epi8( | |
| 120 | 추가: 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, 3, 14, 9, 4, 15, 10, 5, 0, 11, 6, 1, 12, 7, 2, 13, 8, | |
| 121 | 추가: 3, 14, 9, 4, 15 | |
| 122 | 추가: ); | |
| 123 | 추가: | |
| 124 | 추가: let r0 = _mm256_shuffle_epi8(r, sh_r); | |
| 125 | 추가: let g0 = _mm256_shuffle_epi8(g, sh_g); | |
| 126 | 추가: let b0 = _mm256_shuffle_epi8(b, sh_b); | |
| 127 | 추가: | |
| 128 | 추가: let m0 = _mm256_setr_epi8( | |
| 129 | 추가: 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, | |
| 130 | 추가: 0, 0, -1, 0, 0 | |
| 131 | 추가: ); | |
| 132 | 추가: let m1 = _mm256_setr_epi8( | |
| 133 | 추가: 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, | |
| 134 | 추가: -1, 0, 0, -1, 0 | |
| 135 | 추가: ); | |
| 136 | 추가: | |
| 137 | 추가: let p0 = _mm256_blendv_epi8(_mm256_blendv_epi8(r0, g0, m0), b0, m1); | |
| 138 | 추가: let p1 = _mm256_blendv_epi8(_mm256_blendv_epi8(g0, b0, m0), r0, m1); | |
| 139 | 추가: let p2 = _mm256_blendv_epi8(_mm256_blendv_epi8(b0, r0, m0), g0, m1); | |
| 140 | 추가: | |
| 141 | 추가: let rgb0 = _mm256_permute2x128_si256::<32>(p0, p1); | |
| 142 | 추가: let rgb1 = _mm256_permute2x128_si256::<48>(p2, p0); | |
| 143 | 추가: | |
| 144 | 추가: _mm256_storeu_si256(out.as_mut_ptr().cast(), rgb0); | |
| 145 | 추가: _mm_storeu_si128(out[32..].as_mut_ptr().cast(), _mm256_castsi256_si128(rgb1)); | |
| 146 | 추가: | |
| 147 | 추가: *offset += 48; | |
| 148 | 추가: } | |
| 149 | 추가: | |
| 150 | 추가: // Enabled avx2 automatically enables avx. | |
| 151 | 추가: #[inline] | |
| 152 | 추가: #[target_feature(enable = "avx2")] | |
| 153 | 추가: /// A baseline implementation of YCbCr to RGB conversion which does not carry | |
| 154 | 추가: /// out clamping | |
| 155 | 추가: /// | |
| 156 | 추가: /// This is used by the `ycbcr_to_rgba_avx` and `ycbcr_to_rgbx` conversion | |
| 157 | 추가: /// routines | |
| 158 | 추가: unsafe fn ycbcr_to_rgb_baseline_no_clamp( | |
| 159 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16] | |
| 160 | 추가: ) -> (__m256i, __m256i, __m256i) { | |
| 161 | 추가: // Load values into a register | |
| 162 | 추가: // | |
| 163 | 추가: let y_c = _mm256_loadu_si256(y.as_ptr().cast()); | |
| 164 | 추가: let cb_c = _mm256_loadu_si256(cb.as_ptr().cast()); | |
| 165 | 추가: let cr_c = _mm256_loadu_si256(cr.as_ptr().cast()); | |
| 166 | 추가: | |
| 167 | 추가: // Here we want to use _mm256_madd_epi16 to perform 2 multiplications | |
| 168 | 추가: // and one addition per instruction. | |
| 169 | 추가: | |
| 170 | 추가: // At first, we have to pack i16 U and V that stores u8 into one u8 [U,V] | |
| 171 | 추가: // then zero extend, and keep in mind that lanes is already been permuted. | |
| 172 | 추가: | |
| 173 | 추가: let y_coeff = _mm256_set1_epi32(i32::from(Y_CF)); | |
| 174 | 추가: let cr_coeff = _mm256_set1_epi32(R_AVX_COEF); | |
| 175 | 추가: let cb_coeff = _mm256_set1_epi32(B_AVX_COEF); | |
| 176 | 추가: let cg_coeff = _mm256_set1_epi32(G_COEF_AVX_COEF); | |
| 177 | 추가: let v_rnd = _mm256_set1_epi32(i32::from(YUV_RND)); | |
| 178 | 추가: let uv_bias = _mm256_set1_epi16(128); | |
| 179 | 추가: | |
| 180 | 추가: // UV in memory because x86/x86_64 is always little endian | |
| 181 | 추가: let v_0 = _mm256_slli_epi16::<8>(cb_c); | |
| 182 | 추가: let u_v_8 = _mm256_or_si256(v_0, cr_c); | |
| 183 | 추가: | |
| 184 | 추가: let mut u_v_lo = _mm256_unpacklo_epi8(u_v_8, _mm256_setzero_si256()); | |
| 185 | 추가: let mut u_v_hi = _mm256_unpackhi_epi8(u_v_8, _mm256_setzero_si256()); | |
| 186 | 추가: | |
| 187 | 추가: let mut y_lo = _mm256_unpacklo_epi16(y_c, _mm256_setzero_si256()); | |
| 188 | 추가: let mut y_hi = _mm256_unpackhi_epi16(y_c, _mm256_setzero_si256()); | |
| 189 | 추가: | |
| 190 | 추가: u_v_lo = _mm256_sub_epi16(u_v_lo, uv_bias); | |
| 191 | 추가: u_v_hi = _mm256_sub_epi16(u_v_hi, uv_bias); | |
| 192 | 추가: | |
| 193 | 추가: y_lo = _mm256_madd_epi16(y_lo, y_coeff); | |
| 194 | 추가: y_hi = _mm256_madd_epi16(y_hi, y_coeff); | |
| 195 | 추가: | |
| 196 | 추가: let mut r_lo = _mm256_madd_epi16(u_v_lo, cr_coeff); | |
| 197 | 추가: let mut r_hi = _mm256_madd_epi16(u_v_hi, cr_coeff); | |
| 198 | 추가: | |
| 199 | 추가: let mut g_lo = _mm256_madd_epi16(u_v_lo, cg_coeff); | |
| 200 | 추가: let mut g_hi = _mm256_madd_epi16(u_v_hi, cg_coeff); | |
| 201 | 추가: | |
| 202 | 추가: // This ordering is preferred to reduce register file pressure. | |
| 203 | 추가: | |
| 204 | 추가: y_lo = _mm256_add_epi32(y_lo, v_rnd); | |
| 205 | 추가: y_hi = _mm256_add_epi32(y_hi, v_rnd); | |
| 206 | 추가: | |
| 207 | 추가: let mut b_lo = _mm256_madd_epi16(u_v_lo, cb_coeff); | |
| 208 | 추가: let mut b_hi = _mm256_madd_epi16(u_v_hi, cb_coeff); | |
| 209 | 추가: | |
| 210 | 추가: r_lo = _mm256_add_epi32(r_lo, y_lo); | |
| 211 | 추가: r_hi = _mm256_add_epi32(r_hi, y_hi); | |
| 212 | 추가: | |
| 213 | 추가: g_lo = _mm256_add_epi32(g_lo, y_lo); | |
| 214 | 추가: g_hi = _mm256_add_epi32(g_hi, y_hi); | |
| 215 | 추가: | |
| 216 | 추가: b_lo = _mm256_add_epi32(b_lo, y_lo); | |
| 217 | 추가: b_hi = _mm256_add_epi32(b_hi, y_hi); | |
| 218 | 추가: | |
| 219 | 추가: r_lo = _mm256_srai_epi32::<14>(r_lo); | |
| 220 | 추가: r_hi = _mm256_srai_epi32::<14>(r_hi); | |
| 221 | 추가: | |
| 222 | 추가: g_lo = _mm256_srai_epi32::<14>(g_lo); | |
| 223 | 추가: g_hi = _mm256_srai_epi32::<14>(g_hi); | |
| 224 | 추가: | |
| 225 | 추가: b_lo = _mm256_srai_epi32::<14>(b_lo); | |
| 226 | 추가: b_hi = _mm256_srai_epi32::<14>(b_hi); | |
| 227 | 추가: | |
| 228 | 추가: let r = _mm256_packus_epi32(r_lo, r_hi); | |
| 229 | 추가: let g = _mm256_packus_epi32(g_lo, g_hi); | |
| 230 | 추가: let b = _mm256_packus_epi32(b_lo, b_hi); | |
| 231 | 추가: | |
| 232 | 추가: return (r, g, b); | |
| 233 | 추가: } | |
| 234 | 추가: | |
| 235 | 추가: #[inline(always)] | |
| 236 | 추가: pub fn ycbcr_to_rgba_avx2( | |
| 237 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 238 | 추가: ) { | |
| 239 | 추가: unsafe { | |
| 240 | 추가: ycbcr_to_rgba_unsafe(y, cb, cr, out, offset); | |
| 241 | 추가: } | |
| 242 | 추가: } | |
| 243 | 추가: | |
| 244 | 추가: #[inline] | |
| 245 | 추가: #[target_feature(enable = "avx2")] | |
| 246 | 추가: #[rustfmt::skip] | |
| 247 | 추가: unsafe fn ycbcr_to_rgba_unsafe( | |
| 248 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], | |
| 249 | 추가: out: &mut [u8], | |
| 250 | 추가: offset: &mut usize, | |
| 251 | 추가: ) | |
| 252 | 추가: { | |
| 253 | 추가: // check if we have enough space to write. | |
| 254 | 추가: let tmp:& mut [u8; 64] = out.get_mut(*offset..*offset + 64).expect("Slice to small cannot write").try_into().unwrap(); | |
| 255 | 추가: | |
| 256 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 257 | 추가: | |
| 258 | 추가: // set alpha channel to 255 for opaque | |
| 259 | 추가: | |
| 260 | 추가: // And no these comments were not from me pressing the keyboard | |
| 261 | 추가: | |
| 262 | 추가: // Pack the integers into u8's using unsigned saturation. | |
| 263 | 추가: let c = _mm256_packus_epi16(r, g); //aaaaa_bbbbb_aaaaa_bbbbbb | |
| 264 | 추가: let d = _mm256_packus_epi16(b, _mm256_set1_epi16(255)); // cccccc_dddddd_ccccccc_ddddd | |
| 265 | 추가: // transpose_u16 and interleave channels | |
| 266 | 추가: let e = _mm256_unpacklo_epi8(c, d); //ab_ab_ab_ab_ab_ab_ab_ab | |
| 267 | 추가: let f = _mm256_unpackhi_epi8(c, d); //cd_cd_cd_cd_cd_cd_cd_cd | |
| 268 | 추가: // final transpose_u16 | |
| 269 | 추가: let g = _mm256_unpacklo_epi8(e, f); //abcd_abcd_abcd_abcd_abcd | |
| 270 | 추가: let h = _mm256_unpackhi_epi8(e, f); | |
| 271 | 추가: | |
| 272 | 추가: // undo packus shuffling... | |
| 273 | 추가: let i = _mm256_permute2x128_si256::<{ shuffle(3, 2, 1, 0) }>(g, h); | |
| 274 | 추가: | |
| 275 | 추가: let j = _mm256_permute2x128_si256::<{ shuffle(1, 2, 3, 0) }>(g, h); | |
| 276 | 추가: | |
| 277 | 추가: let k = _mm256_permute2x128_si256::<{ shuffle(3, 2, 0, 1) }>(g, h); | |
| 278 | 추가: | |
| 279 | 추가: let l = _mm256_permute2x128_si256::<{ shuffle(0, 3, 2, 1) }>(g, h); | |
| 280 | 추가: | |
| 281 | 추가: let m = _mm256_blend_epi32::<0b1111_0000>(i, j); | |
| 282 | 추가: | |
| 283 | 추가: let n = _mm256_blend_epi32::<0b1111_0000>(k, l); | |
| 284 | 추가: | |
| 285 | 추가: // Store | |
| 286 | 추가: // Use streaming instructions to prevent polluting the cache? | |
| 287 | 추가: _mm256_storeu_si256(tmp.as_mut_ptr().cast(), m); | |
| 288 | 추가: | |
| 289 | 추가: _mm256_storeu_si256(tmp[32..].as_mut_ptr().cast(), n); | |
| 290 | 추가: | |
| 291 | 추가: *offset += 64; | |
| 292 | 추가: } | |
| 293 | 추가: | |
| 294 | 추가: #[inline] | |
| 295 | 추가: const fn shuffle(z: i32, y: i32, x: i32, w: i32) -> i32 { | |
| 296 | 추가: (z << 6) | (y << 4) | (x << 2) | w | |
| 297 | 추가: } |
| @@ -0,0 +1,146 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2025. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: //! Aarch64 color conversion routines | |
| 10 | 추가: //! NEON is mandatory on aarch64. | |
| 11 | 추가: | |
| 12 | 추가: #![cfg(all(feature = "neon", target_arch = "aarch64"))] | |
| 13 | 추가: use core::arch::aarch64::*; | |
| 14 | 추가: | |
| 15 | 추가: use crate::color_convert::scalar::{CB_CF, CR_CF, C_G_CB_COEF_2, C_G_CR_COEF_1, YUV_RND, Y_CF}; | |
| 16 | 추가: | |
| 17 | 추가: const C_1: u64 = u64::from_ne_bytes([ | |
| 18 | 추가: Y_CF.to_ne_bytes()[0], | |
| 19 | 추가: Y_CF.to_ne_bytes()[1], | |
| 20 | 추가: CR_CF.to_ne_bytes()[0], | |
| 21 | 추가: CR_CF.to_ne_bytes()[1], | |
| 22 | 추가: CB_CF.to_ne_bytes()[0], | |
| 23 | 추가: CB_CF.to_ne_bytes()[1], | |
| 24 | 추가: C_G_CR_COEF_1.to_ne_bytes()[0], | |
| 25 | 추가: C_G_CR_COEF_1.to_ne_bytes()[1] | |
| 26 | 추가: ]); | |
| 27 | 추가: const C_2: u64 = u64::from_ne_bytes([ | |
| 28 | 추가: C_G_CB_COEF_2.to_ne_bytes()[0], | |
| 29 | 추가: C_G_CB_COEF_2.to_ne_bytes()[1], | |
| 30 | 추가: 0, | |
| 31 | 추가: 0, | |
| 32 | 추가: 0, | |
| 33 | 추가: 0, | |
| 34 | 추가: 0, | |
| 35 | 추가: 0 | |
| 36 | 추가: ]); | |
| 37 | 추가: | |
| 38 | 추가: #[inline(always)] | |
| 39 | 추가: unsafe fn ycbcr_to_rgb_baseline_no_clamp( | |
| 40 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16] | |
| 41 | 추가: ) -> (uint8x16_t, uint8x16_t, uint8x16_t) { | |
| 42 | 추가: unsafe { | |
| 43 | 추가: // NEON has 32 registers, so it is good idea to utilize a lot of variables at once | |
| 44 | 추가: | |
| 45 | 추가: let cb_cr_bias = vdupq_n_s16(128); | |
| 46 | 추가: // 0 - Y coeff, 1 - Cr, 2 - Cb, 3 - G1, 4 - G2 | |
| 47 | 추가: let coefficients = vcombine_s16(vcreate_s16(C_1), vcreate_s16(C_2)); | |
| 48 | 추가: | |
| 49 | 추가: let y0 = vld1q_s16(y.as_ptr().cast()); | |
| 50 | 추가: let y1 = vld1q_s16(y[8..].as_ptr().cast()); | |
| 51 | 추가: | |
| 52 | 추가: let mut cb0 = vld1q_s16(cb.as_ptr().cast()); | |
| 53 | 추가: let mut cb1 = vld1q_s16(cb[8..].as_ptr().cast()); | |
| 54 | 추가: | |
| 55 | 추가: let mut cr0 = vld1q_s16(cr.as_ptr().cast()); | |
| 56 | 추가: let mut cr1 = vld1q_s16(cr[8..].as_ptr().cast()); | |
| 57 | 추가: | |
| 58 | 추가: cb0 = vsubq_s16(cb0, cb_cr_bias); | |
| 59 | 추가: cb1 = vsubq_s16(cb1, cb_cr_bias); | |
| 60 | 추가: | |
| 61 | 추가: cr0 = vsubq_s16(cr0, cb_cr_bias); | |
| 62 | 추가: cr1 = vsubq_s16(cr1, cb_cr_bias); | |
| 63 | 추가: | |
| 64 | 추가: let bias = vdupq_n_s32(i32::from(YUV_RND)); | |
| 65 | 추가: | |
| 66 | 추가: let acc0 = vmlal_laneq_s16::<0>(bias, vget_low_s16(y0), coefficients); | |
| 67 | 추가: let acc1 = vmlal_high_laneq_s16::<0>(bias, y0, coefficients); | |
| 68 | 추가: let acc2 = vmlal_laneq_s16::<0>(bias, vget_low_s16(y1), coefficients); | |
| 69 | 추가: let acc3 = vmlal_high_laneq_s16::<0>(bias, y1, coefficients); | |
| 70 | 추가: | |
| 71 | 추가: let r0 = vmlal_laneq_s16::<1>(acc0, vget_low_s16(cr0), coefficients); | |
| 72 | 추가: let r1 = vmlal_high_laneq_s16::<1>(acc1, cr0, coefficients); | |
| 73 | 추가: let r2 = vmlal_laneq_s16::<1>(acc2, vget_low_s16(cr1), coefficients); | |
| 74 | 추가: let r3 = vmlal_high_laneq_s16::<1>(acc3, cr1, coefficients); | |
| 75 | 추가: | |
| 76 | 추가: let b0 = vmlal_laneq_s16::<2>(acc0, vget_low_s16(cb0), coefficients); | |
| 77 | 추가: let b1 = vmlal_high_laneq_s16::<2>(acc1, cb0, coefficients); | |
| 78 | 추가: let b2 = vmlal_laneq_s16::<2>(acc2, vget_low_s16(cb1), coefficients); | |
| 79 | 추가: let b3 = vmlal_high_laneq_s16::<2>(acc3, cb1, coefficients); | |
| 80 | 추가: | |
| 81 | 추가: // Saturating shift right with signed -> unsigned saturation | |
| 82 | 추가: let qr0 = vqshrun_n_s32::<14>(r0); | |
| 83 | 추가: let qr1 = vqshrun_n_s32::<14>(r1); | |
| 84 | 추가: let qr2 = vqshrun_n_s32::<14>(r2); | |
| 85 | 추가: let qr3 = vqshrun_n_s32::<14>(r3); | |
| 86 | 추가: | |
| 87 | 추가: let mut g0 = vmlal_laneq_s16::<4>(acc0, vget_low_s16(cb0), coefficients); | |
| 88 | 추가: let mut g1 = vmlal_high_laneq_s16::<4>(acc1, cb0, coefficients); | |
| 89 | 추가: let mut g2 = vmlal_laneq_s16::<4>(acc2, vget_low_s16(cb1), coefficients); | |
| 90 | 추가: let mut g3 = vmlal_high_laneq_s16::<4>(acc3, cb1, coefficients); | |
| 91 | 추가: | |
| 92 | 추가: let qb0 = vqshrun_n_s32::<14>(b0); | |
| 93 | 추가: let qb1 = vqshrun_n_s32::<14>(b1); | |
| 94 | 추가: let qb2 = vqshrun_n_s32::<14>(b2); | |
| 95 | 추가: let qb3 = vqshrun_n_s32::<14>(b3); | |
| 96 | 추가: | |
| 97 | 추가: let r0 = vqmovn_u16(vcombine_u16(qr0, qr1)); | |
| 98 | 추가: let r1 = vqmovn_u16(vcombine_u16(qr2, qr3)); | |
| 99 | 추가: | |
| 100 | 추가: let b0 = vqmovn_u16(vcombine_u16(qb0, qb1)); | |
| 101 | 추가: let b1 = vqmovn_u16(vcombine_u16(qb2, qb3)); | |
| 102 | 추가: | |
| 103 | 추가: g0 = vmlal_laneq_s16::<3>(g0, vget_low_s16(cr0), coefficients); | |
| 104 | 추가: g1 = vmlal_high_laneq_s16::<3>(g1, cr0, coefficients); | |
| 105 | 추가: g2 = vmlal_laneq_s16::<3>(g2, vget_low_s16(cr1), coefficients); | |
| 106 | 추가: g3 = vmlal_high_laneq_s16::<3>(g3, cr1, coefficients); | |
| 107 | 추가: | |
| 108 | 추가: let qg0 = vqshrun_n_s32::<14>(g0); | |
| 109 | 추가: let qg1 = vqshrun_n_s32::<14>(g1); | |
| 110 | 추가: let qg2 = vqshrun_n_s32::<14>(g2); | |
| 111 | 추가: let qg3 = vqshrun_n_s32::<14>(g3); | |
| 112 | 추가: | |
| 113 | 추가: let g0 = vqmovn_u16(vcombine_u16(qg0, qg1)); | |
| 114 | 추가: let g1 = vqmovn_u16(vcombine_u16(qg2, qg3)); | |
| 115 | 추가: | |
| 116 | 추가: ( | |
| 117 | 추가: vcombine_u8(r0, r1), | |
| 118 | 추가: vcombine_u8(g0, g1), | |
| 119 | 추가: vcombine_u8(b0, b1) | |
| 120 | 추가: ) | |
| 121 | 추가: } | |
| 122 | 추가: } | |
| 123 | 추가: | |
| 124 | 추가: #[inline(always)] | |
| 125 | 추가: pub fn ycbcr_to_rgb_neon( | |
| 126 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 127 | 추가: ) { | |
| 128 | 추가: // call this in another function to tell RUST to vectorize this | |
| 129 | 추가: // storing | |
| 130 | 추가: unsafe { | |
| 131 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 132 | 추가: vst3q_u8(out.as_mut_ptr(), uint8x16x3_t(r, g, b)); | |
| 133 | 추가: *offset += 48; | |
| 134 | 추가: } | |
| 135 | 추가: } | |
| 136 | 추가: | |
| 137 | 추가: #[inline(always)] | |
| 138 | 추가: pub fn ycbcr_to_rgba_neon( | |
| 139 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], out: &mut [u8], offset: &mut usize | |
| 140 | 추가: ) { | |
| 141 | 추가: unsafe { | |
| 142 | 추가: let (r, g, b) = ycbcr_to_rgb_baseline_no_clamp(y, cb, cr); | |
| 143 | 추가: vst4q_u8(out.as_mut_ptr(), uint8x16x4_t(r, g, b, vdupq_n_u8(255))); | |
| 144 | 추가: *offset += 64; | |
| 145 | 추가: } | |
| 146 | 추가: } |
| @@ -0,0 +1,139 @@ | ||
| 1 | 추가: /* | |
| 2 | 추가: * Copyright (c) 2023. | |
| 3 | 추가: * | |
| 4 | 추가: * This software is free software; | |
| 5 | 추가: * | |
| 6 | 추가: * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license | |
| 7 | 추가: */ | |
| 8 | 추가: | |
| 9 | 추가: use core::convert::TryInto; | |
| 10 | 추가: | |
| 11 | 추가: // Bt.601 Full Range inverse coefficients computed with 14 bits of precision with MPFR. | |
| 12 | 추가: // This is important to keep them in i16. | |
| 13 | 추가: // In most cases LLVM will detect what we're doing i16 widening to i32 math and will use | |
| 14 | 추가: // appropriate optimizations. | |
| 15 | 추가: pub(crate) const Y_CF: i16 = 16384; | |
| 16 | 추가: pub(crate) const CR_CF: i16 = 22970; | |
| 17 | 추가: pub(crate) const CB_CF: i16 = 29032; | |
| 18 | 추가: pub(crate) const C_G_CR_COEF_1: i16 = -11700; | |
| 19 | 추가: pub(crate) const C_G_CB_COEF_2: i16 = -5638; | |
| 20 | 추가: pub(crate) const YUV_PREC: i16 = 14; | |
| 21 | 추가: // Rounding const for YUV -> RGB conversion: floating equivalent 0.499(9). | |
| 22 | 추가: pub(crate) const YUV_RND: i16 = (1 << (YUV_PREC - 1)) - 1; | |
| 23 | 추가: | |
| 24 | 추가: /// Limit values to 0 and 255 | |
| 25 | 추가: #[inline] | |
| 26 | 추가: #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss, dead_code)] | |
| 27 | 추가: fn clamp(a: i32) -> u8 { | |
| 28 | 추가: a.clamp(0, 255) as u8 | |
| 29 | 추가: } | |
| 30 | 추가: | |
| 31 | 추가: /// YCbCr to RGBA color conversion | |
| 32 | 추가: | |
| 33 | 추가: /// Convert YCbCr to RGB/BGR | |
| 34 | 추가: /// | |
| 35 | 추가: /// Converts to RGB if const BGRA is false | |
| 36 | 추가: /// | |
| 37 | 추가: /// Converts to BGR if const BGRA is true | |
| 38 | 추가: pub fn ycbcr_to_rgba_inner_16_scalar<const BGRA: bool>( | |
| 39 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], output: &mut [u8], pos: &mut usize | |
| 40 | 추가: ) { | |
| 41 | 추가: let (_, output_position) = output.split_at_mut(*pos); | |
| 42 | 추가: | |
| 43 | 추가: // Convert into a slice with 64 elements for Rust to see we won't go out of bounds. | |
| 44 | 추가: let opt: &mut [u8; 64] = output_position | |
| 45 | 추가: .get_mut(0..64) | |
| 46 | 추가: .expect("Slice to small cannot write") | |
| 47 | 추가: .try_into() | |
| 48 | 추가: .unwrap(); | |
| 49 | 추가: for ((&y, (cb, cr)), out) in y | |
| 50 | 추가: .iter() | |
| 51 | 추가: .zip(cb.iter().zip(cr.iter())) | |
| 52 | 추가: .zip(opt.chunks_exact_mut(4)) | |
| 53 | 추가: { | |
| 54 | 추가: let cr = cr - 128; | |
| 55 | 추가: let cb = cb - 128; | |
| 56 | 추가: | |
| 57 | 추가: let y0 = i32::from(y) * i32::from(Y_CF) + i32::from(YUV_RND); | |
| 58 | 추가: | |
| 59 | 추가: let r = (y0 + i32::from(cr) * i32::from(CR_CF)) >> YUV_PREC; | |
| 60 | 추가: let g = (y0 | |
| 61 | 추가: + i32::from(cr) * i32::from(C_G_CR_COEF_1) | |
| 62 | 추가: + i32::from(cb) * i32::from(C_G_CB_COEF_2)) | |
| 63 | 추가: >> YUV_PREC; | |
| 64 | 추가: let b = (y0 + i32::from(cb) * i32::from(CB_CF)) >> YUV_PREC; | |
| 65 | 추가: | |
| 66 | 추가: if BGRA { | |
| 67 | 추가: out[0] = clamp(b); | |
| 68 | 추가: out[1] = clamp(g); | |
| 69 | 추가: out[2] = clamp(r); | |
| 70 | 추가: out[3] = 255; | |
| 71 | 추가: } else { | |
| 72 | 추가: out[0] = clamp(r); | |
| 73 | 추가: out[1] = clamp(g); | |
| 74 | 추가: out[2] = clamp(b); | |
| 75 | 추가: out[3] = 255; | |
| 76 | 추가: } | |
| 77 | 추가: } | |
| 78 | 추가: *pos += 64; | |
| 79 | 추가: } | |
| 80 | 추가: | |
| 81 | 추가: /// Convert YCbCr to RGB/BGR | |
| 82 | 추가: /// | |
| 83 | 추가: /// Converts to RGB if const BGRA is false | |
| 84 | 추가: /// | |
| 85 | 추가: /// Converts to BGR if const BGRA is true | |
| 86 | 추가: pub fn ycbcr_to_rgb_inner_16_scalar<const BGRA: bool>( | |
| 87 | 추가: y: &[i16; 16], cb: &[i16; 16], cr: &[i16; 16], output: &mut [u8], pos: &mut usize | |
| 88 | 추가: ) { | |
| 89 | 추가: let (_, output_position) = output.split_at_mut(*pos); | |
| 90 | 추가: | |
| 91 | 추가: // Convert into a slice with 48 elements | |
| 92 | 추가: let opt: &mut [u8; 48] = output_position | |
| 93 | 추가: .get_mut(0..48) | |
| 94 | 추가: .expect("Slice to small cannot write") | |
| 95 | 추가: .try_into() | |
| 96 | 추가: .unwrap(); | |
| 97 | 추가: | |
| 98 | 추가: for ((&y, (cb, cr)), out) in y | |
| 99 | 추가: .iter() | |
| 100 | 추가: .zip(cb.iter().zip(cr.iter())) | |
| 101 | 추가: .zip(opt.chunks_exact_mut(3)) | |
| 102 | 추가: { | |
| 103 | 추가: let cr = cr - 128; | |
| 104 | 추가: let cb = cb - 128; | |
| 105 | 추가: | |
| 106 | 추가: let y0 = i32::from(y) * i32::from(Y_CF) + i32::from(YUV_RND); | |
| 107 | 추가: | |
| 108 | 추가: let r = (y0 + i32::from(cr) * i32::from(CR_CF)) >> YUV_PREC; | |
| 109 | 추가: let g = (y0 | |
| 110 | 추가: + i32::from(cr) * i32::from(C_G_CR_COEF_1) | |
| 111 | 추가: + i32::from(cb) * i32::from(C_G_CB_COEF_2)) | |
| 112 | 추가: >> YUV_PREC; | |
| 113 | 추가: let b = (y0 + i32::from(cb) * i32::from(CB_CF)) >> YUV_PREC; | |
| 114 | 추가: | |
| 115 | 추가: if BGRA { | |
| 116 | 추가: out[0] = clamp(b); | |
| 117 | 추가: out[1] = clamp(g); | |
| 118 | 추가: out[2] = clamp(r); | |
| 119 | 추가: } else { | |
| 120 | 추가: out[0] = clamp(r); | |
| 121 | 추가: out[1] = clamp(g); | |
| 122 | 추가: out[2] = clamp(b); | |
| 123 | 추가: } | |
| 124 | 추가: } | |
| 125 | 추가: | |
| 126 | 추가: // Increment pos | |
| 127 | 추가: *pos += 48; | |
| 128 | 추가: } | |
| 129 | 추가: | |
| 130 | 추가: pub fn ycbcr_to_grayscale(y: &[i16], width: usize, padded_width: usize, output: &mut [u8]) { | |
| 131 | 추가: for (y_in, out) in y | |
| 132 | 추가: .chunks_exact(padded_width) | |
| 133 | 추가: .zip(output.chunks_exact_mut(width)) | |
| 134 | 추가: { | |
| 135 | 추가: for (y, out) in y_in.iter().zip(out.iter_mut()) { | |
| 136 | 추가: *out = *y as u8; | |
| 137 | 추가: } | |
| 138 | 추가: } | |
| 139 | 추가: } |
| @@ -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 | 추가: } |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기| @@ -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 | 추가: } |
| @@ -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 | 추가: } |
Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기바이너리 파일이라 Diff를 표시하지 않아요.
파일 내려받기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기Diff가 표시 한도를 넘어서 생략했어요.
Raw로 열기