Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions src/rust/src/decoder/output.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::os::windows::io::{FromRawHandle, IntoRawHandle};
use std::{fs::File, io::Write};

use crate::{bindings::*, utils::is_true};
use encoding_rs::{Encoding, BIG5, EUC_JP, EUC_KR, GBK, SHIFT_JIS, WINDOWS_874};

use log::{debug, warn};

Expand Down Expand Up @@ -124,6 +125,26 @@ pub fn is_utf16_charset(charset: &str) -> bool {
|| upper.contains("UCS_2")
}

/// Find the encoding for a CEA-708 service charset name (`--service "1[name]"`).
///
/// The name was already accepted by `iconv_open()` in `dtvcc_writer_init()`, so it
/// can be an iconv name that encoding_rs does not know as a label. Map the iconv
/// names of the encodings encoding_rs does support to that encoding.
pub fn find_charset_encoding(charset: &str) -> Option<&'static Encoding> {
Encoding::for_label(charset.as_bytes()).or_else(|| {
match charset.to_ascii_uppercase().as_str() {
"CP949" | "UHC" | "EUCKR" => Some(EUC_KR),
"CP936" | "WINDOWS-936" | "MS936" => Some(GBK),
"CP950" => Some(BIG5),
"EUCJP" => Some(EUC_JP),
// encoding_rs's Shift_JIS is the Windows variant (windows-31j)
"CP932" => Some(SHIFT_JIS),
"CP874" => Some(WINDOWS_874),
_ => None,
}
})
}

/// Convert from CEA-708 color representation to hex code
///
/// Two bits are specified for each red, green, and blue color value which defines the
Expand All @@ -142,6 +163,27 @@ pub fn color_to_hex(color: u8) -> (u8, u8, u8) {
mod tests {
use super::*;

#[test]
fn test_find_charset_encoding_iconv_names() {
// Names iconv accepts that are not encoding_rs labels
assert_eq!(find_charset_encoding("CP949"), Some(EUC_KR));
assert_eq!(find_charset_encoding("cp949"), Some(EUC_KR));
assert_eq!(find_charset_encoding("UHC"), Some(EUC_KR));
assert_eq!(find_charset_encoding("EUCKR"), Some(EUC_KR));
assert_eq!(find_charset_encoding("CP936"), Some(GBK));
assert_eq!(find_charset_encoding("WINDOWS-936"), Some(GBK));
assert_eq!(find_charset_encoding("MS936"), Some(GBK));
assert_eq!(find_charset_encoding("CP950"), Some(BIG5));
assert_eq!(find_charset_encoding("EUCJP"), Some(EUC_JP));
assert_eq!(find_charset_encoding("CP932"), Some(SHIFT_JIS));
assert_eq!(find_charset_encoding("CP874"), Some(WINDOWS_874));
// Labels encoding_rs already knows are unchanged
assert_eq!(find_charset_encoding("EUC-KR"), Some(EUC_KR));
assert_eq!(find_charset_encoding("SHIFT_JIS"), Some(SHIFT_JIS));
// An encoding encoding_rs doesn't have
assert_eq!(find_charset_encoding("JOHAB"), None);
}

#[test]
fn test_write_char_utf16_mode() {
let mut buf = Vec::new();
Expand Down
89 changes: 86 additions & 3 deletions src/rust/src/decoder/tv_screen.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,14 @@ use std::{ffi::CStr, fs::File};
#[cfg(windows)]
use crate::bindings::_get_osfhandle;

use super::output::{color_to_hex, is_utf16_charset, write_char, Writer};
use super::output::{color_to_hex, find_charset_encoding, is_utf16_charset, write_char, Writer};
use super::timing::{get_scc_time_str, get_time_str};
use super::{CCX_DTVCC_SCREENGRID_COLUMNS, CCX_DTVCC_SCREENGRID_ROWS};
use crate::{
bindings::*,
current_fps,
utils::{is_false, is_true},
};
use encoding_rs::Encoding;

use log::{debug, warn};

Expand Down Expand Up @@ -273,7 +272,7 @@ impl dtvcc_tv_screen {
debug!("Charset: {charset}");

// Look up the encoding by label (name)
if let Some(encoding) = Encoding::for_label(charset.as_bytes()) {
if let Some(encoding) = find_charset_encoding(charset) {
let (cow, _encoding_used, had_errors) = encoding.decode(&buf);
if had_errors {
println!("Warning: Had errors during encoding from {charset} to UTF-8");
Expand All @@ -282,6 +281,18 @@ impl dtvcc_tv_screen {
println!("Warning: Encoding specified ({}) does not match encoding detected ({})",charset,_encoding_used.name());
}
writer.write_to_file(cow.as_bytes())?;
} else {
// iconv accepted the name but encoding_rs can't convert from it:
// write the text unconverted instead of dropping it.
static WARNED: std::sync::Once = std::sync::Once::new();
WARNED.call_once(|| {
if let Some(logger) = lib_ccxr::util::log::logger() {
logger.log_info(&format_args!(
"[CEA-708] Can't convert from charset \"{charset}\", writing the text unconverted\n"
));
}
});
writer.write_to_file(&buf)?;
}
}
} else {
Expand Down Expand Up @@ -916,6 +927,78 @@ mod test {
);
}

/// Runs write_row on row 0 of `screen` with a --service charset and
/// returns what was written.
#[cfg(unix)]
fn write_row_with_charset(screen: &dtvcc_tv_screen, charset: &str) -> Vec<u8> {
use std::ffi::CString;
use std::io::{Read, Seek, SeekFrom};
use std::os::unix::io::AsRawFd;
use tempfile::tempfile;

let charset = CString::new(charset).unwrap();
let mut writer_ctx = get_zero_allocated_obj::<dtvcc_writer_ctx>();
let transcript_settings = get_zero_allocated_obj::<ccx_encoders_transcript_format>();
let mut temp_file = tempfile().expect("Failed to create temp file");
writer_ctx.fd = temp_file.as_raw_fd();
writer_ctx.filename = std::ptr::null_mut();
writer_ctx.charset = charset.as_ptr() as *mut _;
// dtvcc_writer_init() opened an iconv descriptor for the charset
writer_ctx.cd = 1 as iconv_t;

let mut counter = 0u32;
let mut writer = Writer::new(
&mut counter,
0,
ccx_output_format::CCX_OF_SRT,
&mut writer_ctx,
1,
&transcript_settings,
0,
b"\r\n",
);
screen
.write_row(&mut writer, 0, false)
.expect("write_row should succeed");

temp_file.seek(SeekFrom::Start(0)).unwrap();
let mut output = Vec::new();
temp_file.read_to_end(&mut output).unwrap();
output
}

#[test]
#[cfg(unix)]
fn test_write_row_iconv_charset_name() {
// "Hi 가" in EUC-KR / CP949: 가 is 0xB0A1
let mut screen = get_zero_allocated_obj::<dtvcc_tv_screen>();
screen.chars[0][0] = dtvcc_symbol::new(b'H' as u16);
screen.chars[0][1] = dtvcc_symbol::new(b'i' as u16);
screen.chars[0][2] = dtvcc_symbol::new(b' ' as u16);
screen.chars[0][3] = dtvcc_symbol::new(0xB0A1);

for charset in ["EUC-KR", "CP949", "UHC", "EUCKR"] {
let output = write_row_with_charset(&screen, charset);
assert_eq!(
String::from_utf8_lossy(&output),
"Hi 가",
"charset {charset}"
);
}
}

#[test]
#[cfg(unix)]
fn test_write_row_unknown_charset_keeps_text() {
let mut screen = get_zero_allocated_obj::<dtvcc_tv_screen>();
screen.chars[0][0] = dtvcc_symbol::new(b'H' as u16);
screen.chars[0][1] = dtvcc_symbol::new(b'i' as u16);

// iconv knows JOHAB, encoding_rs doesn't
let output = write_row_with_charset(&screen, "JOHAB");
assert_eq!(output, b"Hi");
}

#[test]
#[cfg(unix)]
fn test_writer_output_with_valid_fd() {
Expand Down
Loading