From: Kostya Shishkov Date: Tue, 14 May 2019 11:08:05 +0000 (+0200) Subject: core: fix most clippy warnings X-Git-Url: https://git.nihav.org/?a=commitdiff_plain;h=e243ceb4d694cc08767ad70027bb6963f4cefea3;p=nihav.git core: fix most clippy warnings --- diff --git a/nihav-core/src/codecs/blockdsp.rs b/nihav-core/src/codecs/blockdsp.rs index ccd44cb..70b8420 100644 --- a/nihav-core/src/codecs/blockdsp.rs +++ b/nihav-core/src/codecs/blockdsp.rs @@ -14,12 +14,12 @@ pub fn put_blocks(buf: &mut NAVideoBuffer, xpos: usize, ypos: usize, blk: &[ for j in 0..8 { for k in 0..8 { let mut v = blk[0][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k] = v as u8; } for k in 0..8 { let mut v = blk[1][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k + 8] = v as u8; } idxy += stridey; @@ -27,12 +27,12 @@ pub fn put_blocks(buf: &mut NAVideoBuffer, xpos: usize, ypos: usize, blk: &[ for j in 0..8 { for k in 0..8 { let mut v = blk[2][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k] = v as u8; } for k in 0..8 { let mut v = blk[3][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k + 8] = v as u8; } idxy += stridey; @@ -41,12 +41,12 @@ pub fn put_blocks(buf: &mut NAVideoBuffer, xpos: usize, ypos: usize, blk: &[ for j in 0..8 { for k in 0..8 { let mut v = blk[4][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxu + k] = v as u8; } for k in 0..8 { let mut v = blk[5][k + j * 8]; - if v < 0 { v = 0; } if v > 255 { v = 255; } + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxv + k] = v as u8; } idxu += strideu; @@ -67,26 +67,26 @@ pub fn add_blocks(buf: &mut NAVideoBuffer, xpos: usize, ypos: usize, blk: &[ for j in 0..8 { for k in 0..8 { - let mut v = blk[0][k + j * 8] + (framebuf[idxy + k] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[0][k + j * 8] + i16::from(framebuf[idxy + k]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k] = v as u8; } for k in 0..8 { - let mut v = blk[1][k + j * 8] + (framebuf[idxy + k + 8] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[1][k + j * 8] + i16::from(framebuf[idxy + k + 8]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k + 8] = v as u8; } idxy += stridey; } for j in 0..8 { for k in 0..8 { - let mut v = blk[2][k + j * 8] + (framebuf[idxy + k] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[2][k + j * 8] + i16::from(framebuf[idxy + k]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k] = v as u8; } for k in 0..8 { - let mut v = blk[3][k + j * 8] + (framebuf[idxy + k + 8] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[3][k + j * 8] + i16::from(framebuf[idxy + k + 8]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxy + k + 8] = v as u8; } idxy += stridey; @@ -94,13 +94,13 @@ pub fn add_blocks(buf: &mut NAVideoBuffer, xpos: usize, ypos: usize, blk: &[ for j in 0..8 { for k in 0..8 { - let mut v = blk[4][k + j * 8] + (framebuf[idxu + k] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[4][k + j * 8] + i16::from(framebuf[idxu + k]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxu + k] = v as u8; } for k in 0..8 { - let mut v = blk[5][k + j * 8] + (framebuf[idxv + k] as i16); - if v < 0 { v = 0; } if v > 255 { v = 255; } + let mut v = blk[5][k + j * 8] + i16::from(framebuf[idxv + k]); + if v < 0 { v = 0; } else if v > 255 { v = 255; } framebuf[idxv + k] = v as u8; } idxu += strideu; @@ -143,8 +143,7 @@ pub fn copy_blocks(dst: &mut NAVideoBuffer, src: &NAVideoBuffer, if (sx - pre < 0) || ((sx >> 1) - pre < 0) || (sx + (bw as isize) + post > (w as isize)) || (sy - pre < 0) || ((sy >> 1) - pre < 0) || (sy + (bh as isize) + post > (h as isize)) { let ebuf_stride: usize = 32; - let mut ebuf: Vec = Vec::with_capacity(ebuf_stride * (bh + ((pre + post) as usize))); - ebuf.resize((((pre + post) as usize) + bh) * ebuf_stride, 0); + let mut ebuf: Vec = vec![0; ebuf_stride * (bh + ((pre + post) as usize))]; for comp in 0..3 { let dstride = dst.get_stride(comp); diff --git a/nihav-core/src/codecs/h263/code.rs b/nihav-core/src/codecs/h263/code.rs index c18a9ea..fa02e4e 100644 --- a/nihav-core/src/codecs/h263/code.rs +++ b/nihav-core/src/codecs/h263/code.rs @@ -121,15 +121,16 @@ const W8: i32 = 181; const ROW_SHIFT: u8 = 8; const COL_SHIFT: u8 = 14; +#[allow(clippy::erasing_op)] fn idct_row(row: &mut [i16]) { - let in0 = ((row[0] as i32) << 11) + (1 << (ROW_SHIFT - 1)); - let in1 = (row[4] as i32) << 11; - let in2 = row[6] as i32; - let in3 = row[2] as i32; - let in4 = row[1] as i32; - let in5 = row[7] as i32; - let in6 = row[5] as i32; - let in7 = row[3] as i32; + let in0 = ((i32::from(row[0])) << 11) + (1 << (ROW_SHIFT - 1)); + let in1 = (i32::from(row[4])) << 11; + let in2 = i32::from(row[6]); + let in3 = i32::from(row[2]); + let in4 = i32::from(row[1]); + let in5 = i32::from(row[7]); + let in6 = i32::from(row[5]); + let in7 = i32::from(row[3]); let tmp = W7 * (in4 + in5); let a4 = tmp + (W1 - W7) * in4; @@ -167,15 +168,16 @@ fn idct_row(row: &mut [i16]) { row[4] = ((b5 - b6) >> ROW_SHIFT) as i16; } +#[allow(clippy::erasing_op)] fn idct_col(blk: &mut [i16; 64], off: usize) { - let in0 = ((blk[off + 0*8] as i32) << 8) + (1 << (COL_SHIFT - 1)); - let in1 = (blk[off + 4*8] as i32) << 8; - let in2 = blk[off + 6*8] as i32; - let in3 = blk[off + 2*8] as i32; - let in4 = blk[off + 1*8] as i32; - let in5 = blk[off + 7*8] as i32; - let in6 = blk[off + 5*8] as i32; - let in7 = blk[off + 3*8] as i32; + let in0 = ((i32::from(blk[off + 0*8])) << 8) + (1 << (COL_SHIFT - 1)); + let in1 = (i32::from(blk[off + 4*8])) << 8; + let in2 = i32::from(blk[off + 6*8]); + let in3 = i32::from(blk[off + 2*8]); + let in4 = i32::from(blk[off + 1*8]); + let in5 = i32::from(blk[off + 7*8]); + let in6 = i32::from(blk[off + 5*8]); + let in7 = i32::from(blk[off + 3*8]); let tmp = W7 * (in4 + in5); let a4 = (tmp + (W1 - W7) * in4) >> 3; @@ -345,6 +347,7 @@ impl H263BlockDSP { } } +#[allow(clippy::erasing_op)] fn deblock_hor(buf: &mut NAVideoBuffer, comp: usize, q: u8, off: usize) { let stride = buf.get_stride(comp); let dptr = buf.get_data_mut().unwrap(); diff --git a/nihav-core/src/codecs/h263/data.rs b/nihav-core/src/codecs/h263/data.rs index 029c5bb..36b22e1 100644 --- a/nihav-core/src/codecs/h263/data.rs +++ b/nihav-core/src/codecs/h263/data.rs @@ -114,7 +114,7 @@ pub const H263_CHROMA_QUANT: [u8; 32] = [ pub struct H263ShortCodeReader { tab: &'static [(u8, u8)] } impl H263ShortCodeReader { - pub fn new(tab: &'static [(u8, u8)]) -> Self { H263ShortCodeReader { tab: tab } } + pub fn new(tab: &'static [(u8, u8)]) -> Self { H263ShortCodeReader { tab } } } impl CodebookDescReader for H263ShortCodeReader { @@ -202,7 +202,7 @@ pub const H263_RL_CODES_AIC: &[H263RLCodeDesc] = rlcodes!( pub struct H263RLCodeReader { tab: &'static [H263RLCodeDesc] } impl H263RLCodeReader { - pub fn new(tab: &'static [H263RLCodeDesc]) -> Self { H263RLCodeReader { tab: tab } } + pub fn new(tab: &'static [H263RLCodeDesc]) -> Self { H263RLCodeReader { tab } } } impl CodebookDescReader for H263RLCodeReader { diff --git a/nihav-core/src/codecs/h263/decoder.rs b/nihav-core/src/codecs/h263/decoder.rs index a0e7ce4..502187d 100644 --- a/nihav-core/src/codecs/h263/decoder.rs +++ b/nihav-core/src/codecs/h263/decoder.rs @@ -162,8 +162,8 @@ impl H263BaseDecoder { last_ts: 0, next_ts: 0, tsdiff: 0, has_b: false, b_data: Vec::new(), pred_coeffs: Vec::new(), - is_gob: is_gob, slice_reset: slice_reset, - may_have_b_frames: may_have_b_frames, + is_gob, slice_reset, + may_have_b_frames, mv_data: Vec::new(), } } @@ -219,9 +219,7 @@ impl H263BaseDecoder { let fmt = formats::YUV420_FORMAT; let vinfo = NAVideoInfo::new(self.w, self.h, false, fmt); - let bufret = alloc_video_buffer(vinfo, 4); - if let Err(_) = bufret { return Err(DecoderError::InvalidData); } - let bufinfo = bufret.unwrap(); + let bufinfo = alloc_video_buffer(vinfo, 4)?; let mut buf = bufinfo.get_vbuf().unwrap(); let mut slice = if self.is_gob { @@ -531,9 +529,7 @@ impl H263BaseDecoder { let fmt = formats::YUV420_FORMAT; let vinfo = NAVideoInfo::new(self.w, self.h, false, fmt); - let bufret = alloc_video_buffer(vinfo, 4); - if let Err(_) = bufret { return Err(DecoderError::InvalidData); } - let bufinfo = bufret.unwrap(); + let bufinfo = alloc_video_buffer(vinfo, 4)?; let mut b_buf = bufinfo.get_vbuf().unwrap(); if let (Some(ref bck_buf), Some(ref fwd_buf)) = (self.ipbs.get_nextref(), self.ipbs.get_lastref()) { diff --git a/nihav-core/src/codecs/h263/mod.rs b/nihav-core/src/codecs/h263/mod.rs index 1cd10a2..76cd7a1 100644 --- a/nihav-core/src/codecs/h263/mod.rs +++ b/nihav-core/src/codecs/h263/mod.rs @@ -1,6 +1,7 @@ use super::{DecoderResult, MV, ZERO_MV}; use crate::frame::NAVideoBuffer; +#[allow(clippy::many_single_char_names)] pub mod code; pub mod data; pub mod decoder; @@ -46,7 +47,7 @@ pub struct PBInfo { impl PBInfo { pub fn new(trb: u8, dbquant: u8, improved: bool) -> Self { - PBInfo{ trb: trb, dbquant: dbquant, improved: improved } + PBInfo{ trb, dbquant, improved } } pub fn get_trb(&self) -> u8 { self.trb } pub fn get_dbquant(&self) -> u8 { self.dbquant } @@ -72,9 +73,9 @@ pub struct PicInfo { impl PicInfo { pub fn new(w: usize, h: usize, mode: Type, mvmode: MVMode, umv: bool, apm: bool, quant: u8, ts: u16, pb: Option, plusinfo: Option) -> Self { PicInfo { - w: w, h: h, mode: mode, mvmode: mvmode, - umv: umv, apm: apm, quant: quant, - pb: pb, ts: ts, plusinfo: plusinfo + w, h, mode, mvmode, + umv, apm, quant, + pb, ts, plusinfo } } pub fn get_width(&self) -> usize { self.w } @@ -107,7 +108,7 @@ pub struct PlusInfo { impl PlusInfo { pub fn new(aic: bool, deblock: bool, aiv_mode: bool, mq_mode: bool) -> Self { - PlusInfo { aic: aic, deblock: deblock, aiv_mode: aiv_mode, mq_mode: mq_mode } + PlusInfo { aic, deblock, aiv_mode, mq_mode } } } @@ -137,10 +138,10 @@ const SLICE_NO_END: usize = 99999999; impl SliceInfo { pub fn new(mb_x: usize, mb_y: usize, mb_end: usize, quant: u8) -> Self { - SliceInfo{ mb_x: mb_x, mb_y: mb_y, mb_end: mb_end, quant: quant } + SliceInfo{ mb_x, mb_y, mb_end, quant } } pub fn new_gob(mb_x: usize, mb_y: usize, quant: u8) -> Self { - SliceInfo{ mb_x: mb_x, mb_y: mb_y, mb_end: SLICE_NO_END, quant: quant } + SliceInfo{ mb_x, mb_y, mb_end: SLICE_NO_END, quant } } pub fn get_default_slice(pinfo: &PicInfo) -> Self { SliceInfo{ mb_x: 0, mb_y: 0, mb_end: SLICE_NO_END, quant: pinfo.get_quant() } @@ -153,7 +154,7 @@ impl SliceInfo { impl SliceState { pub fn new(is_iframe: bool) -> Self { SliceState { - is_iframe: is_iframe, mb_x: 0, mb_y: 0, first_line: true, first_mb: true, + is_iframe, mb_x: 0, mb_y: 0, first_line: true, first_mb: true, slice_mb_x: 0, slice_mb_y: 0, quant: 0 } } @@ -227,9 +228,9 @@ impl BlockInfo { BlockInfo { intra: mode == Type::I, skip: (cbp == 0) && (mode != Type::I), - mode: mode, - cbp: cbp, - q: q, + mode, + cbp, + q, mv: [MV::new(0, 0), MV::new(0, 0), MV::new(0, 0), MV::new(0, 0)], num_mv: 0, bpart: false, @@ -279,10 +280,10 @@ impl BlockInfo { impl BBlockInfo { pub fn new(present: bool, cbp: u8, num_mv: usize, fwd: bool) -> Self { BBlockInfo { - present: present, - cbp: cbp, - num_mv: num_mv, - fwd: fwd, + present, + cbp, + num_mv, + fwd, } } pub fn get_num_mv(&self) -> usize { self.num_mv } @@ -337,7 +338,7 @@ impl H263MVTrait for MV { let bscale = (trb as i32) - (trd as i32); let x = if bvec.x != 0 { fwdvec.x - pvec.x } else if trd != 0 { (bscale * (pvec.x as i32) / (trd as i32)) as i16 } else { 0 }; let y = if bvec.y != 0 { fwdvec.y - pvec.y } else if trd != 0 { (bscale * (pvec.y as i32) / (trd as i32)) as i16 } else { 0 }; - MV { x: x, y: y } + MV { x, y } } } diff --git a/nihav-core/src/codecs/mod.rs b/nihav-core/src/codecs/mod.rs index 4ea379d..311a45e 100644 --- a/nihav-core/src/codecs/mod.rs +++ b/nihav-core/src/codecs/mod.rs @@ -168,8 +168,10 @@ pub struct MV { pub y: i16, } +#[allow(clippy::many_single_char_names)] +#[allow(clippy::collapsible_if)] impl MV { - pub fn new(x: i16, y: i16) -> Self { MV{ x: x, y: y } } + pub fn new(x: i16, y: i16) -> Self { MV{ x, y } } pub fn pred(a: MV, b: MV, c: MV) -> Self { let x; if a.x < b.x { @@ -199,7 +201,7 @@ impl MV { y = b.y; } } - MV { x: x, y: y } + MV { x, y } } } @@ -245,6 +247,10 @@ impl NADecoderSupport { } } +impl Default for NADecoderSupport { + fn default() -> Self { Self::new() } +} + pub trait NADecoder { fn init(&mut self, supp: &mut NADecoderSupport, info: NACodecInfoRef) -> DecoderResult<()>; @@ -263,6 +269,7 @@ pub mod blockdsp; #[cfg(feature="h263")] pub mod h263; +#[derive(Default)] pub struct RegisteredDecoders { decs: Vec, } diff --git a/nihav-core/src/demuxers/mod.rs b/nihav-core/src/demuxers/mod.rs index 8470edd..902fbba 100644 --- a/nihav-core/src/demuxers/mod.rs +++ b/nihav-core/src/demuxers/mod.rs @@ -31,20 +31,19 @@ impl<'a> NAPacketReader for ByteReader<'a> { let mut buf: Vec = Vec::with_capacity(size); if buf.capacity() < size { return Err(DemuxerError::MemoryError); } buf.resize(size, 0); - let res = self.read_buf(buf.as_mut_slice()); - if let Err(_) = res { return Err(DemuxerError::IOError); } + self.read_buf(buf.as_mut_slice())?; let pkt = NAPacket::new(str, ts, kf, buf); Ok(pkt) } fn fill_packet(&mut self, pkt: &mut NAPacket) -> DemuxerResult<()> { let mut refbuf = pkt.get_buffer(); let buf = refbuf.as_mut().unwrap(); - let res = self.read_buf(buf.as_mut_slice()); - if let Err(_) = res { return Err(DemuxerError::IOError); } + self.read_buf(buf.as_mut_slice())?; Ok(()) } } +#[derive(Default)] pub struct StreamManager { streams: Vec, ignored: Vec, @@ -116,13 +115,13 @@ impl StreamManager { } pub struct StreamIter<'a> { - streams: &'a Vec, + streams: &'a [NAStreamRef], pos: usize, } impl<'a> StreamIter<'a> { - pub fn new(streams: &'a Vec) -> Self { - StreamIter { streams: streams, pos: 0 } + pub fn new(streams: &'a [NAStreamRef]) -> Self { + StreamIter { streams, pos: 0 } } } @@ -145,7 +144,7 @@ pub struct Demuxer<'a> { impl<'a> Demuxer<'a> { fn new(dmx: Box + 'a>, str: StreamManager) -> Self { Demuxer { - dmx: dmx, + dmx, streams: str, } } @@ -206,6 +205,7 @@ pub fn create_demuxer<'a>(dmxcr: &DemuxerCreator, br: &'a mut ByteReader<'a>) -> Ok(Demuxer::new(dmx, str)) } +#[derive(Default)] pub struct RegisteredDemuxers { dmxs: Vec<&'static DemuxerCreator>, } diff --git a/nihav-core/src/detect.rs b/nihav-core/src/detect.rs index a6d0f13..926348a 100644 --- a/nihav-core/src/detect.rs +++ b/nihav-core/src/detect.rs @@ -9,8 +9,8 @@ pub enum DetectionScore { } impl DetectionScore { - pub fn less(&self, other: DetectionScore) -> bool { - (*self as i32) < (other as i32) + pub fn less(self, other: DetectionScore) -> bool { + (self as i32) < (other as i32) } } @@ -30,13 +30,13 @@ enum Arg { impl Arg { fn val(&self) -> u64 { match *self { - Arg::Byte(b) => { b as u64 } - Arg::U16BE(v) => { v as u64 } - Arg::U16LE(v) => { v as u64 } - Arg::U24BE(v) => { v as u64 } - Arg::U24LE(v) => { v as u64 } - Arg::U32BE(v) => { v as u64 } - Arg::U32LE(v) => { v as u64 } + Arg::Byte(b) => { u64::from(b) } + Arg::U16BE(v) => { u64::from(v) } + Arg::U16LE(v) => { u64::from(v) } + Arg::U24BE(v) => { u64::from(v) } + Arg::U24LE(v) => { u64::from(v) } + Arg::U32BE(v) => { u64::from(v) } + Arg::U32LE(v) => { u64::from(v) } Arg::U64BE(v) => { v } Arg::U64LE(v) => { v } } @@ -45,74 +45,74 @@ impl Arg { match *self { Arg::Byte(_) => { let res = src.peek_byte(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U16BE(_) => { let res = src.peek_u16be(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U16LE(_) => { let res = src.peek_u16le(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U24BE(_) => { let res = src.peek_u24be(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U24LE(_) => { let res = src.peek_u24le(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U32BE(_) => { let res = src.peek_u32be(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U32LE(_) => { let res = src.peek_u32le(); - if let Err(_) = res { return None; } - Some(res.unwrap() as u64) + if res.is_err() { return None; } + Some(u64::from(res.unwrap())) } Arg::U64BE(_) => { let res = src.peek_u64be(); - if let Err(_) = res { return None; } + if res.is_err() { return None; } Some(res.unwrap()) } Arg::U64LE(_) => { let res = src.peek_u64le(); - if let Err(_) = res { return None; } + if res.is_err() { return None; } Some(res.unwrap()) } } } fn eq(&self, src: &mut ByteReader) -> bool { let val = self.read_val(src); - if let None = val { false } + if val.is_none() { false } else { val.unwrap() == self.val() } } fn ge(&self, src: &mut ByteReader) -> bool { let val = self.read_val(src); - if let None = val { false } + if val.is_none() { false } else { val.unwrap() >= self.val() } } fn gt(&self, src: &mut ByteReader) -> bool { let val = self.read_val(src); - if let None = val { false } + if val.is_none() { false } else { val.unwrap() > self.val() } } fn le(&self, src: &mut ByteReader) -> bool { let val = self.read_val(src); - if let None = val { false } + if val.is_none() { false } else { val.unwrap() <= self.val() } } fn lt(&self, src: &mut ByteReader) -> bool { let val = self.read_val(src); - if let None = val { false } + if val.is_none() { false } else { val.unwrap() < self.val() } } } @@ -140,10 +140,9 @@ impl<'a> CC<'a> { CC::Gt(ref arg) => { arg.gt(src) }, CC::Ge(ref arg) => { arg.ge(src) }, CC::Str(str) => { - let mut val: Vec = Vec::with_capacity(str.len()); - val.resize(str.len(), 0); + let mut val: Vec = vec![0; str.len()]; let res = src.peek_buf(val.as_mut_slice()); - if let Err(_) = res { return false; } + if res.is_err() { return false; } val == str } } @@ -229,7 +228,7 @@ pub fn detect_format(name: &str, src: &mut ByteReader) -> Option<(&'static str, let lname = name.to_lowercase(); for detector in DETECTORS { let mut score = DetectionScore::No; - if name.len() > 0 { + if !name.is_empty() { for ext in detector.extensions.split(',') { if lname.ends_with(ext) { score = DetectionScore::ExtensionMatches; @@ -237,10 +236,10 @@ pub fn detect_format(name: &str, src: &mut ByteReader) -> Option<(&'static str, } } } - let mut passed = detector.conditions.len() > 0; + let mut passed = !detector.conditions.is_empty(); for ck in detector.conditions { - let ret = src.seek(SeekFrom::Start(ck.offs as u64)); - if let Err(_) = ret { + let ret = src.seek(SeekFrom::Start(u64::from(ck.offs))); + if ret.is_err() { passed = false; break; } diff --git a/nihav-core/src/dsp/dct.rs b/nihav-core/src/dsp/dct.rs index 1131ff6..ae04e8e 100644 --- a/nihav-core/src/dsp/dct.rs +++ b/nihav-core/src/dsp/dct.rs @@ -163,7 +163,7 @@ fn swp_idx(idx: usize, bits: u32) -> usize { s >> (32 - bits) } -fn gen_swaps_for_perm(swaps: &mut Vec, perms: &Vec) { +fn gen_swaps_for_perm(swaps: &mut Vec, perms: &[usize]) { let mut idx_arr: Vec = Vec::with_capacity(perms.len()); for i in 0..perms.len() { idx_arr.push(i); } let mut run_size = 0; @@ -186,12 +186,10 @@ fn gen_swaps_for_perm(swaps: &mut Vec, perms: &Vec) { } } -fn swap_buf(buf: &mut [f32], swaps: &Vec) { +fn swap_buf(buf: &mut [f32], swaps: &[usize]) { for (idx, nidx) in swaps.iter().enumerate() { if idx != *nidx { - let t = buf[*nidx]; - buf[*nidx] = buf[idx]; - buf[idx] = t; + buf.swap(*nidx, idx); } } } @@ -395,9 +393,7 @@ fn dst_II_inplace(buf: &mut [f32], size: usize, step: usize, tab: &[f32], perm_t for i in 0..hsize { let idx0 = i * step; let idx1 = (size - 1 - i) * step; - let t = buf[idx1]; - buf[idx1] = buf[idx0]; - buf[idx0] = t; + buf.swap(idx0, idx1); } } @@ -408,9 +404,7 @@ fn dct_III_inplace(buf: &mut [f32], size: usize, step: usize, tab: &[f32], perm_ dct_III_inplace(buf, hsize, step, tab, perm_tab); dct_IV_inplace(&mut buf[step*hsize..], hsize, step, tab, perm_tab); for i in 0..(size >> 2) { - let t = buf[(size - 1 - i) * step]; - buf[(size - 1 - i) * step] = buf[(hsize + i) * step]; - buf[(hsize + i) * step] = t; + buf.swap((size - 1 - i) * step, (hsize + i) * step); } for i in 0..hsize { let i0 = buf[i * step] / consts::SQRT_2; @@ -427,9 +421,7 @@ fn dst_III_inplace(buf: &mut [f32], size: usize, step: usize, tab: &[f32], perm_ for i in 0..hsize { let idx0 = i * step; let idx1 = (size - 1 - i) * step; - let t = buf[idx1]; - buf[idx1] = buf[idx0]; - buf[idx0] = t; + buf.swap(idx0, idx1); } dct_III_inplace(buf, size, step, tab, perm_tab); for i in 0..hsize { buf[i * 2 * step + step] = -buf[i * 2 * step + step]; } @@ -456,9 +448,7 @@ fn dct_IV_inplace(buf: &mut [f32], size: usize, step: usize, tab: &[f32], perm_t dct_II_inplace(buf, hsize, step * 2, tab, perm_tab); dct_II_inplace(&mut buf[step..], hsize, step * 2, tab, perm_tab); for i in 0..(size >> 2) { - let t = buf[(size - 1 - i * 2) * step]; - buf[(size - 1 - i * 2) * step] = buf[(i * 2 + 1) * step]; - buf[(i * 2 + 1) * step] = t; + buf.swap((size - 1 - i * 2) * step, (i * 2 + 1) * step); } for i in (3..size).step_by(4) { buf[i] = -buf[i]; diff --git a/nihav-core/src/dsp/fft.rs b/nihav-core/src/dsp/fft.rs index 1255f6c..ee4ab7c 100644 --- a/nihav-core/src/dsp/fft.rs +++ b/nihav-core/src/dsp/fft.rs @@ -542,9 +542,7 @@ impl FFT { for idx in 0..self.swaps.len() { let nidx = self.swaps[idx]; if idx != nidx { - let t = data[nidx]; - data[nidx] = data[idx]; - data[idx] = t; + data.swap(nidx, idx); } } self.do_fft_core(data); @@ -553,9 +551,7 @@ impl FFT { for idx in 0..self.swaps.len() { let nidx = self.swaps[idx]; if idx != nidx { - let t = data[nidx]; - data[nidx] = data[idx]; - data[idx] = t; + data.swap(nidx, idx); } } self.do_ifft_core(data); diff --git a/nihav-core/src/dsp/mod.rs b/nihav-core/src/dsp/mod.rs index 9f62c75..8e8e6af 100644 --- a/nihav-core/src/dsp/mod.rs +++ b/nihav-core/src/dsp/mod.rs @@ -1,6 +1,8 @@ #[cfg(feature="dct")] +#[allow(clippy::erasing_op)] pub mod dct; #[cfg(feature="fft")] +#[allow(clippy::erasing_op)] pub mod fft; #[cfg(feature="mdct")] pub mod mdct; diff --git a/nihav-core/src/formats.rs b/nihav-core/src/formats.rs index f7ef8d8..9a1d4e8 100644 --- a/nihav-core/src/formats.rs +++ b/nihav-core/src/formats.rs @@ -30,21 +30,21 @@ impl NASoniton { let is_pl = (flags & SONITON_FLAG_PLANAR) != 0; let is_fl = (flags & SONITON_FLAG_FLOAT) != 0; let is_sg = (flags & SONITON_FLAG_SIGNED) != 0; - NASoniton { bits: bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg } + NASoniton { bits, be: is_be, packed: is_pk, planar: is_pl, float: is_fl, signed: is_sg } } - pub fn get_bits(&self) -> u8 { self.bits } - pub fn is_be(&self) -> bool { self.be } - pub fn is_packed(&self) -> bool { self.packed } - pub fn is_planar(&self) -> bool { self.planar } - pub fn is_float(&self) -> bool { self.float } - pub fn is_signed(&self) -> bool { self.signed } + pub fn get_bits(self) -> u8 { self.bits } + pub fn is_be(self) -> bool { self.be } + pub fn is_packed(self) -> bool { self.packed } + pub fn is_planar(self) -> bool { self.planar } + pub fn is_float(self) -> bool { self.float } + pub fn is_signed(self) -> bool { self.signed } - pub fn get_audio_size(&self, length: u64) -> usize { + pub fn get_audio_size(self, length: u64) -> usize { if self.packed { - ((length * (self.bits as u64) + 7) >> 3) as usize + ((length * u64::from(self.bits) + 7) >> 3) as usize } else { - (length * (((self.bits + 7) >> 3) as u64)) as usize + (length * u64::from((self.bits + 7) >> 3)) as usize } } } @@ -63,8 +63,8 @@ pub enum NAChannelType { } impl NAChannelType { - pub fn is_center(&self) -> bool { - match *self { + pub fn is_center(self) -> bool { + match self { NAChannelType::C => true, NAChannelType::Ch => true, NAChannelType::Cl => true, NAChannelType::Ov => true, NAChannelType::LFE => true, NAChannelType::LFE2 => true, @@ -72,8 +72,8 @@ impl NAChannelType { _ => false, } } - pub fn is_left(&self) -> bool { - match *self { + pub fn is_left(self) -> bool { + match self { NAChannelType::L => true, NAChannelType::Ls => true, NAChannelType::Lss => true, NAChannelType::Lc => true, NAChannelType::Lh => true, NAChannelType::Lw => true, @@ -82,8 +82,8 @@ impl NAChannelType { _ => false, } } - pub fn is_right(&self) -> bool { - match *self { + pub fn is_right(self) -> bool { + match self { NAChannelType::R => true, NAChannelType::Rs => true, NAChannelType::Rss => true, NAChannelType::Rc => true, NAChannelType::Rh => true, NAChannelType::Rw => true, @@ -171,7 +171,7 @@ impl fmt::Display for NAChannelType { } } -#[derive(Clone)] +#[derive(Clone,Default)] pub struct NAChannelMap { ids: Vec, } @@ -196,8 +196,8 @@ impl NAChannelMap { self.ids.push(ch); } pub fn add_channels(&mut self, chs: &[NAChannelType]) { - for i in 0..chs.len() { - self.ids.push(chs[i]); + for e in chs.iter() { + self.ids.push(*e); } } pub fn num_channels(&self) -> usize { @@ -214,9 +214,9 @@ impl NAChannelMap { } pub fn from_ms_mapping(chmap: u32) -> Self { let mut cm = NAChannelMap::new(); - for i in 0..MS_CHANNEL_MAP.len() { + for (i, ch) in MS_CHANNEL_MAP.iter().enumerate() { if ((chmap >> i) & 1) != 0 { - cm.add_channel(MS_CHANNEL_MAP[i]); + cm.add_channel(*ch); } } cm @@ -227,7 +227,7 @@ impl fmt::Display for NAChannelMap { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut map = String::new(); for el in self.ids.iter() { - if map.len() > 0 { map.push(','); } + if !map.is_empty() { map.push(','); } map.push_str(&*el.to_string()); } write!(f, "{}", map) @@ -291,26 +291,26 @@ pub enum ColorModel { } impl ColorModel { - pub fn get_default_components(&self) -> usize { - match *self { + pub fn get_default_components(self) -> usize { + match self { ColorModel::CMYK => 4, _ => 3, } } - pub fn is_rgb(&self) -> bool { - match *self { + pub fn is_rgb(self) -> bool { + match self { ColorModel::RGB(_) => true, _ => false, } } - pub fn is_yuv(&self) -> bool { - match *self { + pub fn is_yuv(self) -> bool { + match self { ColorModel::YUV(_) => true, _ => false, } } - pub fn get_short_name(&self) -> &'static str { - match *self { + pub fn get_short_name(self) -> &'static str { + match self { ColorModel::RGB(_) => "rgb", ColorModel::YUV(_) => "yuv", ColorModel::CMYK => "cmyk", @@ -430,20 +430,20 @@ impl NAPixelChromaton { pub fn new(h_ss: u8, v_ss: u8, packed: bool, depth: u8, shift: u8, comp_offs: u8, next_elem: u8) -> Self { Self { h_ss, v_ss, packed, depth, shift, comp_offs, next_elem } } - pub fn get_subsampling(&self) -> (u8, u8) { (self.h_ss, self.v_ss) } - pub fn is_packed(&self) -> bool { self.packed } - pub fn get_depth(&self) -> u8 { self.depth } - pub fn get_shift(&self) -> u8 { self.shift } - pub fn get_offset(&self) -> u8 { self.comp_offs } - pub fn get_step(&self) -> u8 { self.next_elem } + pub fn get_subsampling(self) -> (u8, u8) { (self.h_ss, self.v_ss) } + pub fn is_packed(self) -> bool { self.packed } + pub fn get_depth(self) -> u8 { self.depth } + pub fn get_shift(self) -> u8 { self.shift } + pub fn get_offset(self) -> u8 { self.comp_offs } + pub fn get_step(self) -> u8 { self.next_elem } - pub fn get_width(&self, width: usize) -> usize { + pub fn get_width(self, width: usize) -> usize { (width + ((1 << self.h_ss) - 1)) >> self.h_ss } - pub fn get_height(&self, height: usize) -> usize { + pub fn get_height(self, height: usize) -> usize { (height + ((1 << self.v_ss) - 1)) >> self.v_ss } - pub fn get_linesize(&self, width: usize) -> usize { + pub fn get_linesize(self, width: usize) -> usize { let d = self.depth as usize; if self.packed { (self.get_width(width) * d + d - 1) >> 3 @@ -451,7 +451,7 @@ impl NAPixelChromaton { self.get_width(width) } } - pub fn get_data_size(&self, width: usize, height: usize) -> usize { + pub fn get_data_size(self, width: usize, height: usize) -> usize { let nh = (height + ((1 << self.v_ss) - 1)) >> self.v_ss; self.get_linesize(width) * nh } @@ -487,11 +487,11 @@ impl NAPixelFormaton { if let Some(c) = comp3 { chromatons[2] = Some(c); ncomp += 1; } if let Some(c) = comp4 { chromatons[3] = Some(c); ncomp += 1; } if let Some(c) = comp5 { chromatons[4] = Some(c); ncomp += 1; } - NAPixelFormaton { model: model, + NAPixelFormaton { model, components: ncomp, comp_info: chromatons, - elem_size: elem_size, - be: be, alpha: alpha, palette: palette } + elem_size, + be, alpha, palette } } pub fn get_model(&self) -> ColorModel { self.model } @@ -500,10 +500,10 @@ impl NAPixelFormaton { if idx < self.comp_info.len() { return self.comp_info[idx]; } None } - pub fn is_be(&self) -> bool { self.be } - pub fn has_alpha(&self) -> bool { self.alpha } - pub fn is_paletted(&self) -> bool { self.palette } - pub fn get_elem_size(&self) -> u8 { self.elem_size } + pub fn is_be(self) -> bool { self.be } + pub fn has_alpha(self) -> bool { self.alpha } + pub fn is_paletted(self) -> bool { self.palette } + pub fn get_elem_size(self) -> u8 { self.elem_size } pub fn is_unpacked(&self) -> bool { if self.palette { return false; } for chr in self.comp_info.iter() { diff --git a/nihav-core/src/frame.rs b/nihav-core/src/frame.rs index af7b498..14e5b63 100644 --- a/nihav-core/src/frame.rs +++ b/nihav-core/src/frame.rs @@ -94,7 +94,7 @@ impl NACodecTypeInfo { impl fmt::Display for NACodecTypeInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let ret = match *self { - NACodecTypeInfo::None => format!(""), + NACodecTypeInfo::None => "".to_string(), NACodecTypeInfo::Audio(fmt) => format!("{}", fmt), NACodecTypeInfo::Video(fmt) => format!("{}", fmt), }; @@ -125,7 +125,7 @@ impl NAVideoBuffer { offs.clone_from(&self.offs); let mut strides: Vec = Vec::with_capacity(self.strides.len()); strides.clone_from(&self.strides); - NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, strides: strides } + NAVideoBuffer { info: self.info, data: NABufferRef::new(data), offs, strides } } pub fn get_stride(&self, idx: usize) -> usize { if idx >= self.strides.len() { return 0; } @@ -164,7 +164,7 @@ impl NAAudioBuffer { data.clone_from(self.data.as_ref()); let mut offs: Vec = Vec::with_capacity(self.offs.len()); offs.clone_from(&self.offs); - NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs: offs, chmap: self.get_chmap(), len: self.len } + NAAudioBuffer { info: self.info, data: NABufferRef::new(data), offs, chmap: self.get_chmap(), len: self.len } } pub fn get_length(&self) -> usize { self.len } } @@ -172,7 +172,7 @@ impl NAAudioBuffer { impl NAAudioBuffer { pub fn new_from_buf(info: NAAudioInfo, data: NABufferRef>, chmap: NAChannelMap) -> Self { let len = data.len(); - NAAudioBuffer { info: info, data: data, chmap: chmap, offs: Vec::new(), len: len } + NAAudioBuffer { info, data, chmap, offs: Vec::new(), len } } } @@ -326,7 +326,7 @@ pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result Result = Vec::with_capacity(new_size.unwrap()); - data.resize(new_size.unwrap(), 0); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let data: Vec = vec![0; new_size.unwrap()]; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video(buf.into_ref())) } else if !all_packed { for i in 0..fmt.get_num_comp() { let ochr = fmt.get_chromaton(i); - if let None = ochr { continue; } + if ochr.is_none() { continue; } let chr = ochr.unwrap(); if !vinfo.is_flipped() { offs.push(new_size as usize); @@ -377,19 +376,16 @@ pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result = Vec::with_capacity(new_size); - data.resize(new_size, 0); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let data: Vec = vec![0; new_size]; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video(buf.into_ref())) } else if max_depth <= 16 { - let mut data: Vec = Vec::with_capacity(new_size); - data.resize(new_size, 0); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let data: Vec = vec![0; new_size]; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video16(buf.into_ref())) } else { - let mut data: Vec = Vec::with_capacity(new_size); - data.resize(new_size, 0); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let data: Vec = vec![0; new_size]; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video32(buf.into_ref())) } } else if all_bytealigned || unfit_elem_size { @@ -399,10 +395,9 @@ pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result = Vec::with_capacity(new_size); - data.resize(new_size, 0); + let data: Vec = vec![0; new_size]; strides.push(line_sz.unwrap()); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::VideoPacked(buf.into_ref())) } else { let elem_sz = fmt.get_elem_size(); @@ -411,17 +406,15 @@ pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result { - let mut data: Vec = Vec::with_capacity(new_size); - data.resize(new_size, 0); + let data: Vec = vec![0; new_size]; strides.push(width); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video16(buf.into_ref())) }, 4 => { - let mut data: Vec = Vec::with_capacity(new_size); - data.resize(new_size, 0); + let data: Vec = vec![0; new_size]; strides.push(width); - let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs: offs, strides: strides }; + let buf: NAVideoBuffer = NAVideoBuffer { data: NABufferRef::new(data), info: vinfo, offs, strides }; Ok(NABufferType::Video32(buf.into_ref())) }, _ => unreachable!(), @@ -429,6 +422,7 @@ pub fn alloc_video_buffer(vinfo: NAVideoInfo, align: u8) -> Result Result { let mut offs: Vec = Vec::new(); if ainfo.format.is_planar() || (ainfo.channels == 1 && (ainfo.format.get_bits() % 8) == 0) { @@ -440,23 +434,20 @@ pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelM } if ainfo.format.is_float() { if ainfo.format.get_bits() == 32 { - let mut data: Vec = Vec::with_capacity(length); - data.resize(length, 0.0); - let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples }; + let data: Vec = vec![0.0; length]; + let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples }; Ok(NABufferType::AudioF32(buf)) } else { Err(AllocatorError::TooLargeDimensions) } } else { if ainfo.format.get_bits() == 8 && !ainfo.format.is_signed() { - let mut data: Vec = Vec::with_capacity(length); - data.resize(length, 0); - let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples }; + let data: Vec = vec![0; length]; + let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples }; Ok(NABufferType::AudioU8(buf)) } else if ainfo.format.get_bits() == 16 && ainfo.format.is_signed() { - let mut data: Vec = Vec::with_capacity(length); - data.resize(length, 0); - let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples }; + let data: Vec = vec![0; length]; + let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples }; Ok(NABufferType::AudioI16(buf)) } else { Err(AllocatorError::TooLargeDimensions) @@ -466,16 +457,14 @@ pub fn alloc_audio_buffer(ainfo: NAAudioInfo, nsamples: usize, chmap: NAChannelM let len = nsamples.checked_mul(ainfo.channels as usize); if len == None { return Err(AllocatorError::TooLargeDimensions); } let length = ainfo.format.get_audio_size(len.unwrap() as u64); - let mut data: Vec = Vec::with_capacity(length); - data.resize(length, 0); - let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs: offs, chmap: chmap, len: nsamples }; + let data: Vec = vec![0; length]; + let buf: NAAudioBuffer = NAAudioBuffer { data: NABufferRef::new(data), info: ainfo, offs, chmap, len: nsamples }; Ok(NABufferType::AudioPacked(buf)) } } pub fn alloc_data_buffer(size: usize) -> Result { - let mut data: Vec = Vec::with_capacity(size); - data.resize(size, 0); + let data: Vec = vec![0; size]; let buf: NABufferRef> = NABufferRef::new(data); Ok(NABufferType::Data(buf)) } @@ -510,11 +499,7 @@ impl NAVideoBufferPool { None } pub fn get_copy(&mut self, rbuf: &NAVideoBufferRef) -> Option> { - let res = self.get_free(); - if res.is_none() { - return None; - } - let mut dbuf = res.unwrap(); + let mut dbuf = self.get_free()?; dbuf.data.copy_from_slice(&rbuf.data); Some(dbuf) } @@ -527,7 +512,7 @@ impl NAVideoBufferPool { pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { let nbufs = self.max_len + self.add_len - self.pool.len(); for _ in 0..nbufs { - let vbuf = alloc_video_buffer(vinfo.clone(), align)?; + let vbuf = alloc_video_buffer(vinfo, align)?; if let NABufferType::Video(buf) = vbuf { self.pool.push(buf); } else if let NABufferType::VideoPacked(buf) = vbuf { @@ -544,7 +529,7 @@ impl NAVideoBufferPool { pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { let nbufs = self.max_len + self.add_len - self.pool.len(); for _ in 0..nbufs { - let vbuf = alloc_video_buffer(vinfo.clone(), align)?; + let vbuf = alloc_video_buffer(vinfo, align)?; if let NABufferType::Video16(buf) = vbuf { self.pool.push(buf); } else { @@ -559,7 +544,7 @@ impl NAVideoBufferPool { pub fn prealloc_video(&mut self, vinfo: NAVideoInfo, align: u8) -> Result<(), AllocatorError> { let nbufs = self.max_len + self.add_len - self.pool.len(); for _ in 0..nbufs { - let vbuf = alloc_video_buffer(vinfo.clone(), align)?; + let vbuf = alloc_video_buffer(vinfo, align)?; if let NABufferType::Video32(buf) = vbuf { self.pool.push(buf); } else { @@ -586,10 +571,10 @@ impl NACodecInfo { None => None, Some(vec) => Some(Arc::new(vec)), }; - NACodecInfo { name: name, properties: p, extradata: extradata } + NACodecInfo { name, properties: p, extradata } } pub fn new_ref(name: &'static str, p: NACodecTypeInfo, edata: Option>>) -> Self { - NACodecInfo { name: name, properties: p, extradata: edata } + NACodecInfo { name, properties: p, extradata: edata } } pub fn into_ref(self) -> NACodecInfoRef { Arc::new(self) } pub fn get_properties(&self) -> NACodecTypeInfo { self.properties } @@ -621,7 +606,7 @@ impl Default for NACodecInfo { impl fmt::Display for NACodecInfo { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let edata = match self.extradata.clone() { - None => format!("no extradata"), + None => "no extradata".to_string(), Some(v) => format!("{} byte(s) of extradata", v.len()), }; write!(f, "{}: {} {}", self.name, self.properties, edata) @@ -675,7 +660,7 @@ pub struct NATimeInfo { impl NATimeInfo { pub fn new(pts: Option, dts: Option, duration: Option, tb_num: u32, tb_den: u32) -> Self { - NATimeInfo { pts: pts, dts: dts, duration: duration, tb_num: tb_num, tb_den: tb_den } + NATimeInfo { pts, dts, duration, tb_num, tb_den } } pub fn get_pts(&self) -> Option { self.pts } pub fn get_dts(&self) -> Option { self.dts } @@ -700,7 +685,7 @@ pub type NAFrameRef = Arc; fn get_plane_size(info: &NAVideoInfo, idx: usize) -> (usize, usize) { let chromaton = info.get_format().get_chromaton(idx); - if let None = chromaton { return (0, 0); } + if chromaton.is_none() { return (0, 0); } let (hs, vs) = chromaton.unwrap().get_subsampling(); let w = (info.get_width() + ((1 << hs) - 1)) >> hs; let h = (info.get_height() + ((1 << vs) - 1)) >> vs; @@ -714,7 +699,7 @@ impl NAFrame { info: NACodecInfoRef, options: HashMap, buffer: NABufferType) -> Self { - NAFrame { ts: ts, buffer: buffer, info: info, ftype: ftype, key: keyframe, options: options } + NAFrame { ts, buffer, info, ftype, key: keyframe, options } } pub fn get_info(&self) -> NACodecInfoRef { self.info.clone() } pub fn get_frame_type(&self) -> FrameType { self.ftype } @@ -736,12 +721,12 @@ impl NAFrame { impl fmt::Display for NAFrame { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut foo = format!("frame type {}", self.ftype); - if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); } - if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); } - if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); } - if self.key { foo = format!("{} kf", foo); } - write!(f, "[{}]", foo) + let mut ostr = format!("frame type {}", self.ftype); + if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); } + if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); } + if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); } + if self.key { ostr = format!("{} kf", ostr); } + write!(f, "[{}]", ostr) } } @@ -804,7 +789,7 @@ pub fn reduce_timebase(tb_num: u32, tb_den: u32) -> (u32, u32) { impl NAStream { pub fn new(mt: StreamType, id: u32, info: NACodecInfo, tb_num: u32, tb_den: u32) -> Self { let (n, d) = reduce_timebase(tb_num, tb_den); - NAStream { media_type: mt, id: id, num: 0, info: info.into_ref(), tb_num: n, tb_den: d } + NAStream { media_type: mt, id, num: 0, info: info.into_ref(), tb_num: n, tb_den: d } } pub fn get_id(&self) -> u32 { self.id } pub fn get_num(&self) -> usize { self.num } @@ -838,7 +823,7 @@ impl NAPacket { pub fn new(str: NAStreamRef, ts: NATimeInfo, kf: bool, vec: Vec) -> Self { // let mut vec: Vec = Vec::new(); // vec.resize(size, 0); - NAPacket { stream: str, ts: ts, keyframe: kf, buffer: NABufferRef::new(vec) } + NAPacket { stream: str, ts, keyframe: kf, buffer: NABufferRef::new(vec) } } pub fn get_stream(&self) -> NAStreamRef { self.stream.clone() } pub fn get_time_information(&self) -> NATimeInfo { self.ts } @@ -855,13 +840,13 @@ impl Drop for NAPacket { impl fmt::Display for NAPacket { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut foo = format!("[pkt for {} size {}", self.stream, self.buffer.len()); - if let Some(pts) = self.ts.pts { foo = format!("{} pts {}", foo, pts); } - if let Some(dts) = self.ts.dts { foo = format!("{} dts {}", foo, dts); } - if let Some(dur) = self.ts.duration { foo = format!("{} duration {}", foo, dur); } - if self.keyframe { foo = format!("{} kf", foo); } - foo = foo + "]"; - write!(f, "{}", foo) + let mut ostr = format!("[pkt for {} size {}", self.stream, self.buffer.len()); + if let Some(pts) = self.ts.pts { ostr = format!("{} pts {}", ostr, pts); } + if let Some(dts) = self.ts.dts { ostr = format!("{} dts {}", ostr, dts); } + if let Some(dur) = self.ts.duration { ostr = format!("{} duration {}", ostr, dur); } + if self.keyframe { ostr = format!("{} kf", ostr); } + ostr += "]"; + write!(f, "{}", ostr) } } diff --git a/nihav-core/src/io/bitreader.rs b/nihav-core/src/io/bitreader.rs index ea5f27c..faa1d87 100644 --- a/nihav-core/src/io/bitreader.rs +++ b/nihav-core/src/io/bitreader.rs @@ -27,11 +27,12 @@ pub struct BitReader<'a> { mode: BitReaderMode, } +#[allow(clippy::identity_op)] impl<'a> BitReader<'a> { pub fn new(src: &'a [u8], size: usize, mode: BitReaderMode) -> Self { if src.len() < size { panic!("size is less than needed"); } - BitReader{ cache: 0, pos: 0, bits: 0, end: size, src: src, mode: mode } + BitReader{ cache: 0, pos: 0, bits: 0, end: size, src, mode } } pub fn tell(&self) -> usize { @@ -43,30 +44,30 @@ impl<'a> BitReader<'a> { } fn fill32be(&mut self, src: &[u8]) { - let nw = (((src[0] as u32) << 24) | - ((src[1] as u32) << 16) | - ((src[2] as u32) << 8) | - ((src[3] as u32) << 0)) as u64; - self.cache |= nw << (32 - self.bits); + let nw = (u32::from(src[0]) << 24) | + (u32::from(src[1]) << 16) | + (u32::from(src[2]) << 8) | + (u32::from(src[3]) << 0); + self.cache |= u64::from(nw) << (32 - self.bits); } fn fill32le16(&mut self, src: &[u8]) { - let nw = (((src[1] as u32) << 24) | - ((src[0] as u32) << 16) | - ((src[3] as u32) << 8) | - ((src[2] as u32) << 0)) as u64; - self.cache |= nw << (32 - self.bits); + let nw = (u32::from(src[1]) << 24) | + (u32::from(src[0]) << 16) | + (u32::from(src[3]) << 8) | + (u32::from(src[2]) << 0); + self.cache |= u64::from(nw) << (32 - self.bits); } fn fill32le32(&mut self, src: &[u8], lsb: bool) { - let nw = (((src[3] as u32) << 24) | - ((src[2] as u32) << 16) | - ((src[1] as u32) << 8) | - ((src[0] as u32) << 0)) as u64; + let nw = (u32::from(src[3]) << 24) | + (u32::from(src[2]) << 16) | + (u32::from(src[1]) << 8) | + (u32::from(src[0]) << 0); if lsb { - self.cache |= nw << self.bits; + self.cache |= u64::from(nw) << self.bits; } else { - self.cache |= nw << (32 - self.bits); + self.cache |= u64::from(nw) << (32 - self.bits); } } @@ -87,10 +88,10 @@ impl<'a> BitReader<'a> { } else { let mut buf: [u8; 4] = [0, 0, 0, 0]; let mut newbits: u8 = 0; - for i in 0..3 { + for out in buf.iter_mut().take(3) { if self.pos < self.end { - buf[i] = self.src[self.pos]; - self.pos = self.pos + 1; + *out = self.src[self.pos]; + self.pos += 1; newbits += 8; } } @@ -111,7 +112,7 @@ impl<'a> BitReader<'a> { fn read_cache(&mut self, nbits: u8) -> u32 { let res = match self.mode { BitReaderMode::LE => ((1u64 << nbits) - 1) & self.cache, - _ => (self.cache as u64) >> (64 - nbits), + _ => self.cache >> (64 - nbits), }; res as u32 } @@ -183,14 +184,14 @@ impl<'a> BitReader<'a> { #[inline(always)] pub fn skip(&mut self, nbits: u32) -> BitReaderResult<()> { - if self.bits as u32 >= nbits { + if u32::from(self.bits) >= nbits { self.skip_cache(nbits as u8); return Ok(()); } - let mut skip_bits = nbits - (self.bits as u32); + let mut skip_bits = nbits - u32::from(self.bits); self.reset_cache(); self.pos += ((skip_bits / 32) * 4) as usize; - skip_bits = skip_bits & 0x1F; + skip_bits &= 0x1F; self.refill()?; if skip_bits > 0 { self.skip_cache(skip_bits as u8); @@ -223,8 +224,8 @@ pub fn reverse_bits(inval: u32, len: u8) -> u32 { let mut ret = 0; let mut val = inval; for _ in 0..8 { - ret = (ret << 4) | (REV_TAB[(val & 0xF) as usize] as u32); - val = val >> 4; + ret = (ret << 4) | u32::from(REV_TAB[(val & 0xF) as usize]); + val >>= 4; } ret >> (32 - len) } diff --git a/nihav-core/src/io/byteio.rs b/nihav-core/src/io/byteio.rs index 286a117..545bff5 100644 --- a/nihav-core/src/io/byteio.rs +++ b/nihav-core/src/io/byteio.rs @@ -1,6 +1,7 @@ use std::io::SeekFrom; use std::fs::File; use std::io::prelude::*; +use std::ptr; #[derive(Debug)] pub enum ByteIOError { @@ -24,7 +25,7 @@ pub trait ByteIO { fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()>; fn tell(&mut self) -> u64; fn seek(&mut self, pos: SeekFrom) -> ByteIOResult; - fn is_eof(&mut self) -> bool; + fn is_eof(&self) -> bool; fn is_seekable(&mut self) -> bool; fn size(&mut self) -> i64; } @@ -47,20 +48,20 @@ pub struct FileReader<'a> { macro_rules! read_int { ($s: ident, $inttype: ty, $size: expr, $which: ident) => ({ - let mut buf = [0; $size]; - $s.read_buf(&mut buf)?; unsafe { - Ok((*(buf.as_ptr() as *const $inttype)).$which()) + let mut buf: $inttype = 0; + $s.read_buf(&mut *(&mut buf as *mut $inttype as *mut [u8; $size]))?; + Ok(buf.$which()) } }) } macro_rules! peek_int { ($s: ident, $inttype: ty, $size: expr, $which: ident) => ({ - let mut buf = [0; $size]; - $s.peek_buf(&mut buf)?; unsafe { - Ok((*(buf.as_ptr() as *const $inttype)).$which()) + let mut buf: $inttype = 0; + $s.peek_buf(&mut *(&mut buf as *mut $inttype as *mut [u8; $size]))?; + Ok(buf.$which()) } }) } @@ -70,7 +71,9 @@ macro_rules! read_int_func { pub fn $s(src: &[u8]) -> ByteIOResult<$inttype> { if src.len() < $size { return Err(ByteIOError::ReadError); } unsafe { - Ok((*(src.as_ptr() as *const $inttype)).$which()) + let mut buf: $inttype = 0; + ptr::copy_nonoverlapping(src.as_ptr(), &mut buf as *mut $inttype as *mut u8, 1); + Ok(buf.$which()) } } } @@ -85,15 +88,15 @@ read_int_func!(read_u64le, u64, 8, to_le); pub fn read_u24be(src: &[u8]) -> ByteIOResult { if src.len() < 3 { return Err(ByteIOError::ReadError); } - Ok(((src[0] as u32) << 16) | ((src[1] as u32) << 8) | (src[2] as u32)) + Ok((u32::from(src[0]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[2])) } pub fn read_u24le(src: &[u8]) -> ByteIOResult { if src.len() < 3 { return Err(ByteIOError::ReadError); } - Ok(((src[2] as u32) << 16) | ((src[1] as u32) << 8) | (src[0] as u32)) + Ok((u32::from(src[2]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[0])) } impl<'a> ByteReader<'a> { - pub fn new(io: &'a mut ByteIO) -> Self { ByteReader { io: io } } + pub fn new(io: &'a mut ByteIO) -> Self { ByteReader { io } } pub fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult { self.io.read_buf(buf) @@ -126,13 +129,13 @@ impl<'a> ByteReader<'a> { pub fn read_u24be(&mut self) -> ByteIOResult { let p16 = self.read_u16be()?; let p8 = self.read_byte()?; - Ok(((p16 as u32) << 8) | (p8 as u32)) + Ok((u32::from(p16) << 8) | u32::from(p8)) } pub fn peek_u24be(&mut self) -> ByteIOResult { let mut src: [u8; 3] = [0; 3]; self.peek_buf(&mut src)?; - Ok(((src[0] as u32) << 16) | ((src[1] as u32) << 8) | (src[2] as u32)) + Ok((u32::from(src[0]) << 16) | (u32::from(src[1]) << 8) | u32::from(src[2])) } pub fn read_u32be(&mut self) -> ByteIOResult { @@ -162,13 +165,13 @@ impl<'a> ByteReader<'a> { pub fn read_u24le(&mut self) -> ByteIOResult { let p8 = self.read_byte()?; let p16 = self.read_u16le()?; - Ok(((p16 as u32) << 8) | (p8 as u32)) + Ok((u32::from(p16) << 8) | u32::from(p8)) } pub fn peek_u24le(&mut self) -> ByteIOResult { let mut src: [u8; 3] = [0; 3]; self.peek_buf(&mut src)?; - Ok((src[0] as u32) | ((src[1] as u32) << 8) | ((src[2] as u32) << 16)) + Ok(u32::from(src[0]) | (u32::from(src[1]) << 8) | (u32::from(src[2]) << 16)) } pub fn read_u32le(&mut self) -> ByteIOResult { @@ -200,7 +203,7 @@ impl<'a> ByteReader<'a> { } while ssize > 0 { self.io.read_byte()?; - ssize = ssize - 1; + ssize -= 1; } } Ok(()) @@ -214,7 +217,7 @@ impl<'a> ByteReader<'a> { self.io.seek(pos) } - pub fn is_eof(&mut self) -> bool { + pub fn is_eof(&self) -> bool { self.io.is_eof() } @@ -225,19 +228,19 @@ impl<'a> ByteReader<'a> { pub fn left(&mut self) -> i64 { let size = self.io.size(); if size == -1 { return -1; } - return size - (self.io.tell() as i64) + size - (self.io.tell() as i64) } } impl<'a> MemoryReader<'a> { pub fn new_read(buf: &'a [u8]) -> Self { - MemoryReader { buf: buf, size: buf.len(), pos: 0 } + MemoryReader { buf, size: buf.len(), pos: 0 } } fn real_seek(&mut self, pos: i64) -> ByteIOResult { if pos < 0 || (pos as usize) > self.size { - return Err(ByteIOError::WrongRange) + return Err(ByteIOError::WrongRange); } self.pos = pos as usize; Ok(pos as u64) @@ -248,7 +251,7 @@ impl<'a> ByteIO for MemoryReader<'a> { fn read_byte(&mut self) -> ByteIOResult { if self.is_eof() { return Err(ByteIOError::EOF); } let res = self.buf[self.pos]; - self.pos = self.pos + 1; + self.pos += 1; Ok(res) } @@ -260,9 +263,8 @@ impl<'a> ByteIO for MemoryReader<'a> { fn peek_buf(&mut self, buf: &mut [u8]) -> ByteIOResult { let copy_size = if self.size - self.pos < buf.len() { self.size } else { buf.len() }; if copy_size == 0 { return Err(ByteIOError::EOF); } - for i in 0..copy_size { - buf[i] = self.buf[self.pos + i]; - } + let dst = &mut buf[0..copy_size]; + dst.copy_from_slice(&self.buf[self.pos..][..copy_size]); Ok(copy_size) } @@ -298,7 +300,7 @@ impl<'a> ByteIO for MemoryReader<'a> { } } - fn is_eof(&mut self) -> bool { + fn is_eof(&self) -> bool { self.pos >= self.size } @@ -314,16 +316,16 @@ impl<'a> ByteIO for MemoryReader<'a> { impl<'a> FileReader<'a> { pub fn new_read(file: &'a mut File) -> Self { - FileReader { file: file, eof : false } + FileReader { file, eof : false } } } impl<'a> ByteIO for FileReader<'a> { fn read_byte(&mut self) -> ByteIOResult { let mut byte : [u8; 1] = [0]; - let err = self.file.read(&mut byte); - if let Err(_) = err { return Err(ByteIOError::ReadError); } - let sz = err.unwrap(); + let ret = self.file.read(&mut byte); + if ret.is_err() { return Err(ByteIOError::ReadError); } + let sz = ret.unwrap(); if sz == 0 { self.eof = true; return Err(ByteIOError::EOF); } Ok (byte[0]) } @@ -335,17 +337,17 @@ impl<'a> ByteIO for FileReader<'a> { } fn read_buf(&mut self, buf: &mut [u8]) -> ByteIOResult { - let res = self.file.read(buf); - if let Err(_) = res { return Err(ByteIOError::ReadError); } - let sz = res.unwrap(); + let ret = self.file.read(buf); + if ret.is_err() { return Err(ByteIOError::ReadError); } + let sz = ret.unwrap(); if sz < buf.len() { self.eof = true; return Err(ByteIOError::EOF); } Ok(sz) } fn read_buf_some(&mut self, buf: &mut [u8]) -> ByteIOResult { - let res = self.file.read(buf); - if let Err(_) = res { return Err(ByteIOError::ReadError); } - let sz = res.unwrap(); + let ret = self.file.read(buf); + if ret.is_err() { return Err(ByteIOError::ReadError); } + let sz = ret.unwrap(); if sz < buf.len() { self.eof = true; } Ok(sz) } @@ -373,7 +375,7 @@ impl<'a> ByteIO for FileReader<'a> { } } - fn is_eof(&mut self) -> bool { + fn is_eof(&self) -> bool { self.eof } @@ -402,7 +404,7 @@ pub struct FileWriter { } impl<'a> ByteWriter<'a> { - pub fn new(io: &'a mut ByteIO) -> Self { ByteWriter { io: io } } + pub fn new(io: &'a mut ByteIO) -> Self { ByteWriter { io } } pub fn write_buf(&mut self, buf: &[u8]) -> ByteIOResult<()> { self.io.write_buf(buf) @@ -444,13 +446,13 @@ impl<'a> ByteWriter<'a> { } pub fn write_u64be(&mut self, val: u64) -> ByteIOResult<()> { - self.write_u32be(((val >> 32) & 0xFFFFFFFF) as u32)?; - self.write_u32be((val & 0xFFFFFFFF) as u32) + self.write_u32be((val >> 32) as u32)?; + self.write_u32be(val as u32) } pub fn write_u64le(&mut self, val: u64) -> ByteIOResult<()> { - self.write_u32le((val & 0xFFFFFFFF) as u32)?; - self.write_u32le(((val >> 32) & 0xFFFFFFFF) as u32) + self.write_u32le(val as u32)?; + self.write_u32le((val >> 32) as u32) } pub fn tell(&mut self) -> u64 { @@ -472,7 +474,7 @@ impl<'a> MemoryWriter<'a> { pub fn new_write(buf: &'a mut [u8]) -> Self { let len = buf.len(); - MemoryWriter { buf: buf, size: len, pos: 0 } + MemoryWriter { buf, size: len, pos: 0 } } fn real_seek(&mut self, pos: i64) -> ByteIOResult { @@ -533,7 +535,7 @@ impl<'a> ByteIO for MemoryWriter<'a> { } } - fn is_eof(&mut self) -> bool { + fn is_eof(&self) -> bool { self.pos >= self.size } @@ -548,7 +550,7 @@ impl<'a> ByteIO for MemoryWriter<'a> { impl FileWriter { pub fn new_write(file: File) -> Self { - FileWriter { file: file } + FileWriter { file } } } @@ -597,7 +599,7 @@ impl ByteIO for FileWriter { } } - fn is_eof(&mut self) -> bool { + fn is_eof(&self) -> bool { false } diff --git a/nihav-core/src/io/codebook.rs b/nihav-core/src/io/codebook.rs index b86d0c1..4f041c6 100644 --- a/nihav-core/src/io/codebook.rs +++ b/nihav-core/src/io/codebook.rs @@ -55,14 +55,14 @@ fn fill_lut_msb(table: &mut Vec, off: usize, let fill_len = lut_bits - bits; let fill_size = 1 << fill_len; let fill_code = code << (lut_bits - bits); - let lut_value = (symidx << 8) | (bits as u32); + let lut_value = (symidx << 8) | u32::from(bits); for j in 0..fill_size { let idx = (fill_code + j) as usize; table[idx + off] = lut_value; } } else { let idx = (code as usize) + off; - table[idx] = (symidx << 8) | 0x80 | (bits as u32); + table[idx] = (symidx << 8) | 0x80 | u32::from(bits); } } @@ -75,11 +75,11 @@ fn fill_lut_lsb(table: &mut Vec, off: usize, let step = lut_bits - fill_len; for j in 0..fill_size { let idx = (fill_code + (j << step)) as usize; - table[idx + off] = (symidx << 8) | (bits as u32); + table[idx + off] = (symidx << 8) | u32::from(bits); } } else { let idx = (code as usize) + off; - table[idx] = (symidx << 8) | 0x80 | (bits as u32); + table[idx] = (symidx << 8) | 0x80 | u32::from(bits); } } @@ -143,10 +143,10 @@ impl CodeBucket { type EscapeCodes = HashMap; fn add_esc_code(cc: &mut EscapeCodes, key: u32, code: u32, bits: u8, idx: usize) { - if !cc.contains_key(&key) { cc.insert(key, CodeBucket::new()); } + cc.entry(key).or_insert_with(CodeBucket::new); let b = cc.get_mut(&key); if let Some(bucket) = b { - bucket.add_code(Code {code: code, bits: bits, idx: idx }); + bucket.add_code(Code {code, bits, idx }); } else { panic!("no bucket when expected!"); } } @@ -178,7 +178,7 @@ fn build_esc_lut(table: &mut Vec, sec_bucket.offset = new_off as usize; } - for (_, sec_bucket) in &escape_list { + for sec_bucket in escape_list.values() { build_esc_lut(table, mode, sec_bucket)?; } @@ -196,7 +196,7 @@ impl Codebook { for i in 0..cb.len() { let bits = cb.bits(i); if bits > 0 { - nnz = nnz + 1; + nnz += 1; if cb.code(i) >= (1 << bits) { return Err(CodebookError::InvalidCodebook); } @@ -208,7 +208,7 @@ impl Codebook { let cval = extract_esc_part(code, bits, MAX_LUT_BITS, mode); add_esc_code(&mut escape_list, ckey, cval, bits - MAX_LUT_BITS, symidx); } - if bits > 0 { symidx = symidx + 1; } + if bits > 0 { symidx += 1; } } if maxbits == 0 { return Err(CodebookError::InvalidCodebook); } @@ -240,10 +240,10 @@ impl Codebook { } } } - symidx = symidx + 1; + symidx += 1; } - for (_, bucket) in &escape_list { + for bucket in escape_list.values() { build_esc_lut(&mut table, mode, &bucket)?; } @@ -253,7 +253,7 @@ impl Codebook { } } - Ok(Codebook { table: table, syms: syms, lut_bits: maxbits }) + Ok(Codebook { table, syms, lut_bits: maxbits }) } } @@ -272,8 +272,8 @@ impl<'a, S: Copy> CodebookReader for BitReader<'a> { if (bits as isize) > self.left() { return Err(CodebookError::InvalidCode); } - let skip_bits = if esc { lut_bits as u32 } else { bits }; - if let Err(_) = self.skip(skip_bits as u32) {} + let skip_bits = if esc { u32::from(lut_bits) } else { bits }; + self.skip(skip_bits as u32).unwrap(); lut_bits = bits as u8; } Ok(cb.syms[idx]) @@ -286,7 +286,7 @@ pub struct FullCodebookDescReader { impl FullCodebookDescReader { pub fn new(data: Vec>) -> Self { - FullCodebookDescReader { data: data } + FullCodebookDescReader { data } } } @@ -303,7 +303,7 @@ pub struct ShortCodebookDescReader { impl ShortCodebookDescReader { pub fn new(data: Vec>) -> Self { - ShortCodebookDescReader { data: data } + ShortCodebookDescReader { data } } } diff --git a/nihav-core/src/io/intcode.rs b/nihav-core/src/io/intcode.rs index 8d87920..1c52d81 100644 --- a/nihav-core/src/io/intcode.rs +++ b/nihav-core/src/io/intcode.rs @@ -29,7 +29,7 @@ fn read_unary(br: &mut BitReader, terminator: u32) -> BitReaderResult { let mut res: u32 = 0; loop { if br.read(1)? == terminator { return Ok(res); } - res = res + 1; + res += 1; } } @@ -37,7 +37,7 @@ fn read_unary_lim(br: &mut BitReader, len: u32, terminator: u32) -> BitReaderRes let mut res: u32 = 0; loop { if br.read(1)? == terminator { return Ok(res); } - res = res + 1; + res += 1; if res == len { return Ok(res); } } } @@ -51,15 +51,15 @@ fn read_golomb(br: &mut BitReader, m: u8) -> BitReaderResult { if m == 0 { return Err(BitReaderError::InvalidValue); } let nbits = (8 - m.leading_zeros()) as u8; if (m & (m - 1)) == 0 { return read_rice(br, nbits); } - let cutoff = ((1 << nbits) - m) as u32; + let cutoff = u32::from((1 << nbits) - m); let pfx = read_unary(br, 0)?; let tail = br.read(nbits - 1)?; if tail < cutoff { - let res = pfx * (m as u32) + tail; + let res = pfx * u32::from(m) + tail; Ok (res) } else { let add = br.read(1)?; - let res = pfx * (m as u32) + (tail - cutoff) * 2 + add + cutoff; + let res = pfx * u32::from(m) + (tail - cutoff) * 2 + add + cutoff; Ok (res) } } diff --git a/nihav-core/src/lib.rs b/nihav-core/src/lib.rs index d36297f..08e7134 100644 --- a/nihav-core/src/lib.rs +++ b/nihav-core/src/lib.rs @@ -1,4 +1,5 @@ #[cfg(feature="decoders")] +#[allow(clippy::unreadable_literal)] pub mod codecs; #[cfg(feature="demuxers")] @@ -9,10 +10,12 @@ pub mod frame; pub mod io; pub mod refs; pub mod register; +#[allow(clippy::unreadable_literal)] pub mod detect; pub mod scale; #[cfg(feature="dsp")] +#[allow(clippy::unreadable_literal)] pub mod dsp; pub mod test; diff --git a/nihav-core/src/refs.rs b/nihav-core/src/refs.rs index b83aa25..de1c4fc 100644 --- a/nihav-core/src/refs.rs +++ b/nihav-core/src/refs.rs @@ -1,4 +1,5 @@ use std::ops::{Deref, DerefMut}; +use std::convert::AsRef; use std::sync::atomic::*; struct NABufferData { @@ -9,17 +10,15 @@ struct NABufferData { impl NABufferData { fn new(data: T) -> Self { Self { - data: data, + data, refs: AtomicUsize::new(1), } } fn inc_refs(obj: &mut Self) { obj.refs.fetch_add(1, Ordering::SeqCst); } - fn dec_refs(obj: &mut Self) { - if obj.refs.fetch_sub(1, Ordering::SeqCst) == 0 { - std::mem::forget(obj); - } + fn dec_refs(obj: &mut Self) -> bool { + obj.refs.fetch_sub(1, Ordering::SeqCst) == 0 } fn get_num_refs(obj: &Self) -> usize { obj.refs.load(Ordering::Relaxed) @@ -47,14 +46,17 @@ impl NABufferRef { NABufferData::get_num_refs(self.ptr.as_mut().unwrap()) } } - pub fn as_ref(&self) -> &T { + pub fn as_mut(&mut self) -> Option<&mut T> { unsafe { - NABufferData::get_read_ptr(self.ptr.as_mut().unwrap()) + NABufferData::get_write_ptr(self.ptr.as_mut().unwrap()) } } - pub fn as_mut(&mut self) -> Option<&mut T> { +} + +impl AsRef for NABufferRef { + fn as_ref(&self) -> &T { unsafe { - NABufferData::get_write_ptr(self.ptr.as_mut().unwrap()) + NABufferData::get_read_ptr(self.ptr.as_mut().unwrap()) } } } @@ -80,7 +82,9 @@ impl Clone for NABufferRef { impl Drop for NABufferRef { fn drop(&mut self) { unsafe { - NABufferData::dec_refs(self.ptr.as_mut().unwrap()); + if NABufferData::dec_refs(self.ptr.as_mut().unwrap()) { + std::ptr::drop_in_place(self.ptr); + } } } } diff --git a/nihav-core/src/register.rs b/nihav-core/src/register.rs index a03d7ca..de93015 100644 --- a/nihav-core/src/register.rs +++ b/nihav-core/src/register.rs @@ -22,11 +22,11 @@ impl fmt::Display for CodecType { } } -const CODEC_CAP_INTRAONLY:u32 = 0x000001; -const CODEC_CAP_LOSSLESS:u32 = 0x000002; -const CODEC_CAP_REORDER:u32 = 0x000004; -const CODEC_CAP_HYBRID:u32 = 0x000008; -const CODEC_CAP_SCALABLE:u32 = 0x000010; +const CODEC_CAP_INTRAONLY:u32 = 0x0001; +const CODEC_CAP_LOSSLESS:u32 = 0x0002; +const CODEC_CAP_REORDER:u32 = 0x0004; +const CODEC_CAP_HYBRID:u32 = 0x0008; +const CODEC_CAP_SCALABLE:u32 = 0x0010; #[derive(Clone)] pub struct CodecDescription { @@ -49,7 +49,7 @@ impl CodecDescription { impl fmt::Display for CodecDescription { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let mut out = format!("{}", self.fname); + let mut out = self.fname.to_string(); if self.caps != 0 { let mut capfmt = "".to_string(); if (self.caps & CODEC_CAP_INTRAONLY) != 0 { @@ -217,17 +217,15 @@ static WAV_CODEC_REGISTER: &'static [(u16, &str)] = &[ ]; pub fn find_codec_from_avi_fourcc(fcc: &[u8;4]) -> Option<&'static str> { - for i in 0..AVI_VIDEO_CODEC_REGISTER.len() { - let (fourcc, name) = AVI_VIDEO_CODEC_REGISTER[i]; - if fourcc == fcc { return Some(name); } + for (fourcc, name) in AVI_VIDEO_CODEC_REGISTER.iter() { + if *fourcc == fcc { return Some(name); } } None } pub fn find_codec_from_wav_twocc(tcc: u16) -> Option<&'static str> { - for i in 0..WAV_CODEC_REGISTER.len() { - let (twocc, name) = WAV_CODEC_REGISTER[i]; - if twocc == tcc { return Some(name); } + for (twocc, name) in WAV_CODEC_REGISTER.iter() { + if *twocc == tcc { return Some(name); } } None } diff --git a/nihav-core/src/scale/colorcvt.rs b/nihav-core/src/scale/colorcvt.rs index efe3ebc..d29b234 100644 --- a/nihav-core/src/scale/colorcvt.rs +++ b/nihav-core/src/scale/colorcvt.rs @@ -167,6 +167,7 @@ impl RgbToYuv { fn new() -> Self { Self::default() } } +#[allow(clippy::many_single_char_names)] impl Kernel for RgbToYuv { fn init(&mut self, in_fmt: &ScaleInfo, dest_fmt: &ScaleInfo) -> ScaleResult { let mut df = dest_fmt.fmt; @@ -210,9 +211,9 @@ println!(" [intermediate format {}]", df); let dst = dbuf.get_data_mut().unwrap(); for _y in 0..h { for x in 0..w { - let r = src[roff + x] as f32; - let g = src[goff + x] as f32; - let b = src[boff + x] as f32; + let r = f32::from(src[roff + x]); + let g = f32::from(src[goff + x]); + let b = f32::from(src[boff + x]); let (y, u, v) = matrix_mul(&self.matrix, r, g, b); dst[yoff + x] = (y as i16).max(0).min(255) as u8; @@ -243,6 +244,7 @@ impl YuvToRgb { fn new() -> Self { Self::default() } } +#[allow(clippy::many_single_char_names)] impl Kernel for YuvToRgb { fn init(&mut self, in_fmt: &ScaleInfo, dest_fmt: &ScaleInfo) -> ScaleResult { let mut df = dest_fmt.fmt; @@ -294,9 +296,9 @@ println!(" [intermediate format {}]", df); let dst = dbuf.get_data_mut().unwrap(); for y in 0..h { for x in 0..w { - let y = src[yoff + x] as f32; - let u = ((src[uoff + (x >> sv0)] as i16) - 128) as f32; - let v = ((src[voff + (x >> sv1)] as i16) - 128) as f32; + let y = f32::from(src[yoff + x]); + let u = f32::from(i16::from(src[uoff + (x >> sv0)]) - 128); + let v = f32::from(i16::from(src[voff + (x >> sv1)]) - 128); let (r, g, b) = matrix_mul(&self.matrix, y, u, v); dst[roff + x] = (r as i16).max(0).min(255) as u8; diff --git a/nihav-core/src/scale/mod.rs b/nihav-core/src/scale/mod.rs index e49fecb..9cd6b8d 100644 --- a/nihav-core/src/scale/mod.rs +++ b/nihav-core/src/scale/mod.rs @@ -157,17 +157,15 @@ fn build_pipeline(ifmt: &ScaleInfo, ofmt: &ScaleInfo, just_convert: bool) -> Sca let outname = ofmt.fmt.get_model().get_short_name(); println!("convert {} -> {}", ifmt, ofmt); - let mut needs_scale = !just_convert; - if (ofmt.fmt.get_max_subsampling() > 0) && + let needs_scale = if (ofmt.fmt.get_max_subsampling() > 0) && (ofmt.fmt.get_max_subsampling() != ifmt.fmt.get_max_subsampling()) { - needs_scale = true; - } + true + } else { + !just_convert + }; let needs_unpack = needs_scale || !ifmt.fmt.is_unpacked(); let needs_pack = !ofmt.fmt.is_unpacked(); - let mut needs_convert = false; - if inname != outname { - needs_convert = true; - } + let needs_convert = inname != outname; let scale_before_cvt = is_better_fmt(&ifmt, &ofmt) && needs_convert && (ofmt.fmt.get_max_subsampling() == 0); //todo stages for model and gamma conversion @@ -177,12 +175,11 @@ println!("convert {} -> {}", ifmt, ofmt); if needs_unpack { println!("[adding unpack]"); - let new_stage; - if !cur_fmt.fmt.is_paletted() { - new_stage = Stage::new("unpack", &cur_fmt, &ofmt)?; - } else { - new_stage = Stage::new("depal", &cur_fmt, &ofmt)?; - } + let new_stage = if !cur_fmt.fmt.is_paletted() { + Stage::new("unpack", &cur_fmt, &ofmt)? + } else { + Stage::new("depal", &cur_fmt, &ofmt)? + }; cur_fmt = new_stage.fmt_out; add_stage!(stages, new_stage); } diff --git a/nihav-core/src/scale/repack.rs b/nihav-core/src/scale/repack.rs index 350ddf4..fd59e78 100644 --- a/nihav-core/src/scale/repack.rs +++ b/nihav-core/src/scale/repack.rs @@ -61,7 +61,7 @@ impl Kernel for PackKernel { let ddata = dbuf.get_data_mut().unwrap(); for (src, dst) in sdata.chunks(istride).zip(ddata.chunks_mut(dstride)).take(h) { for x in 0..w { - dst[x * step + self.ooff[comp]] = convert_depth(src[x] as u32, self.depths[comp], self.osize[comp]) as u8; + dst[x * step + self.ooff[comp]] = convert_depth(u32::from(src[x]), self.depths[comp], self.osize[comp]) as u8; } } } @@ -80,7 +80,7 @@ impl Kernel for PackKernel { for x in 0..w { let mut elem: u32 = 0; for comp in 0..self.ncomps { - let c = src[ioff[comp] + x] as u32; + let c = u32::from(src[ioff[comp] + x]); elem |= convert_depth(c, self.depths[comp], self.osize[comp]) << self.shifts[comp]; } dst[x] = elem as u16; @@ -198,7 +198,7 @@ unimplemented!(); let dst = dbuf.get_data_mut().unwrap(); for src in sdata.chunks(istride).take(h) { for x in 0..w { - let elem = src[x] as u32; + let elem = u32::from(src[x]); for i in 0..self.ncomps { dst[offs[i] + x] = convert_depth((elem >> self.shifts[i]) & self.masks[i], self.depths[i], self.osize[i]) as u8; } @@ -281,7 +281,7 @@ println!(" [intermediate format {}]", df); for x in 0..w { let palidx = src[x] as usize; for i in 0..self.ncomps { - let elem = pal[palidx * self.palstep + self.coffs[i]] as u32; + let elem = u32::from(pal[palidx * self.palstep + self.coffs[i]]); dst[offs[i] + x] = convert_depth(elem, self.depths[i], 8) as u8; } } diff --git a/nihav-core/src/test/dec_video.rs b/nihav-core/src/test/dec_video.rs index 62672b3..dfefdc4 100644 --- a/nihav-core/src/test/dec_video.rs +++ b/nihav-core/src/test/dec_video.rs @@ -35,8 +35,7 @@ fn write_pgmyuv(pfx: &str, strno: usize, num: u64, frm: NAFrameRef) { idx2 += ls; } if w2 <= w/2 { - let mut pad: Vec = Vec::with_capacity((w - w2 * 2) / 2); - pad.resize((w - w2 * 2) / 2, 0xFF); + let pad: Vec = vec![0xFF; (w - w2 * 2) / 2]; let mut base1 = buf.get_offset(1); let stride1 = buf.get_stride(1); let mut base2 = buf.get_offset(2); @@ -56,8 +55,7 @@ fn write_pgmyuv(pfx: &str, strno: usize, num: u64, frm: NAFrameRef) { base2 += stride2; } } else { - let mut pad: Vec = Vec::with_capacity(w - w2); - pad.resize(w - w2, 0xFF); + let pad: Vec = vec![0xFF; w - w2]; let mut base1 = buf.get_offset(1); let stride1 = buf.get_stride(1); for _ in 0..h2 { @@ -106,8 +104,7 @@ fn write_palppm(pfx: &str, strno: usize, num: u64, frm: NAFrameRef) { buf.get_info().get_format().get_chromaton(2).unwrap().get_offset() as usize ]; let mut idx = 0; - let mut line: Vec = Vec::with_capacity(w * 3); - line.resize(w * 3, 0); + let mut line: Vec = vec![0; w * 3]; for _ in 0..h { let src = &dta[idx..(idx+w)]; for x in 0..w { @@ -136,8 +133,6 @@ fn write_ppm(pfx: &str, strno: usize, num: u64, frm: NAFrameRef) { ofile.write_all(hdr.as_bytes()).unwrap(); let dta = buf.get_data(); let stride = buf.get_stride(0); - let mut line: Vec = Vec::with_capacity(w * 3); - line.resize(w * 3, 0); for src in dta.chunks(stride) { ofile.write_all(&src[0..w*3]).unwrap(); } @@ -187,15 +182,15 @@ pub fn test_file_decoding(demuxer: &str, name: &str, limit: Option, panic!("error"); } let pkt = pktres.unwrap(); - if limit.is_some() && pkt.get_pts().is_some() { - if pkt.get_pts().unwrap() > limit.unwrap() { break; } + if let (Some(lim), Some(ppts)) = (limit, pkt.get_pts()) { + if ppts > lim { break; } } let streamno = pkt.get_stream().get_id() as usize; if let Some((ref mut dsupp, ref mut dec)) = decs[streamno] { let frm = dec.decode(dsupp, &pkt).unwrap(); if pkt.get_stream().get_info().is_video() && video_pfx.is_some() && frm.get_frame_type() != FrameType::Skip { let pfx = video_pfx.unwrap(); - let pts = if let Some(fpts) = frm.get_pts() { fpts } else { pkt.get_pts().unwrap() }; + let pts = if let Some(fpts) = frm.get_pts() { fpts } else { pkt.get_pts().unwrap() }; let vinfo = frm.get_buffer().get_video_info().unwrap(); if vinfo.get_format().is_paletted() { write_palppm(pfx, streamno, pts, frm); @@ -252,8 +247,8 @@ pub fn test_decode_audio(demuxer: &str, name: &str, limit: Option, audio_pf panic!("error"); } let pkt = pktres.unwrap(); - if limit.is_some() && pkt.get_pts().is_some() { - if pkt.get_pts().unwrap() > limit.unwrap() { break; } + if limit.is_some() && pkt.get_pts().is_some() && pkt.get_pts().unwrap() > limit.unwrap() { + break; } let streamno = pkt.get_stream().get_id() as usize; if let Some((ref mut dsupp, ref mut dec)) = decs[streamno] { diff --git a/nihav-core/src/test/wavwriter.rs b/nihav-core/src/test/wavwriter.rs index 1cd9541..0c32430 100644 --- a/nihav-core/src/test/wavwriter.rs +++ b/nihav-core/src/test/wavwriter.rs @@ -47,7 +47,7 @@ macro_rules! write_data { impl<'a> WavWriter<'a> { pub fn new(io: &'a mut ByteWriter<'a>) -> Self { - WavWriter { io: io, data_pos: 0 } + WavWriter { io, data_pos: 0 } } pub fn write_header(&mut self, ainfo: NAAudioInfo) -> ByteIOResult<()> { let bits = ainfo.get_format().get_bits() as usize; @@ -59,16 +59,16 @@ impl<'a> WavWriter<'a> { self.io.write_buf(b"fmt ")?; self.io.write_u32le(16)?; self.io.write_u16le(0x0001)?; // PCM - self.io.write_u16le(ainfo.get_channels() as u16)?; - self.io.write_u32le(ainfo.get_sample_rate() as u32)?; + self.io.write_u16le(u16::from(ainfo.get_channels()))?; + self.io.write_u32le(ainfo.get_sample_rate())?; if bits < 16 { - self.io.write_u32le((ainfo.get_channels() as u32) * (ainfo.get_sample_rate() as u32))?; - self.io.write_u16le(ainfo.get_channels() as u16)?; // block align + self.io.write_u32le(u32::from(ainfo.get_channels()) * ainfo.get_sample_rate())?; + self.io.write_u16le(u16::from(ainfo.get_channels()))?; // block align self.io.write_u16le(8)?; } else { - self.io.write_u32le(2 * (ainfo.get_channels() as u32) * (ainfo.get_sample_rate() as u32))?; - self.io.write_u16le((2 * ainfo.get_channels()) as u16)?; // block align + self.io.write_u32le(2 * u32::from(ainfo.get_channels()) * ainfo.get_sample_rate())?; + self.io.write_u16le(u16::from(2 * ainfo.get_channels()))?; // block align self.io.write_u16le(16)?; }