4343//! - Frame differencing. After the first frame, a frame is only the rectangle
4444//! around the pixels that moved past `UNCHANGED_TOLERANCE` since they were
4545//! last drawn (`take_change`), with the others in it set to
46- //! `TRANSPARENT_INDEX`, so what the screen already shows stays. A frame where
46+ //! `TRANSPARENT_INDEX`, so what the screen already shows stays. With the
47+ //! dither on, a change is redrawn by whole `DITHER_TILE` tiles, so error
48+ //! diffusion only runs across pixels drawn together. A frame where
4749//! nothing moved is not written: its delay goes to the image before it. The
4850//! palette is rebuilt on its schedule and as soon as most of the picture moves
4951//! (a cut, a zoom); one that changed redraws the whole frame, so nothing an
@@ -154,54 +156,75 @@ fn moved(drawn: &[u8], now: &[u8]) -> bool {
154156 ( 0 ..3 ) . any ( |c| drawn[ c] . abs_diff ( now[ c] ) > UNCHANGED_TOLERANCE )
155157}
156158
157- /// What a frame redraws: the rectangle around the pixels that moved, and for
158- /// each pixel in it, whether to draw it (row by row) or let the GIF screen
159- /// show what is already there.
159+ /// With the dither on, a change is redrawn by whole tiles this many pixels a
160+ /// side. Error diffusion hands each pixel's error to its neighbours: a pixel
161+ /// redrawn among ones left as they were would round on its own, against
162+ /// neighbours the screen does not show, and a dithered area would drift. A
163+ /// whole tile is dithered together; a tile left as it was neither takes nor
164+ /// passes on any error.
165+ const DITHER_TILE : usize = 8 ;
166+
167+ /// What a frame redraws: the rectangle around the pixels that moved, for each
168+ /// pixel in it whether to draw it (row by row) or let the GIF screen show what
169+ /// is already there, and how many pixels moved.
160170struct Change {
161171 rect : Rect ,
162172 draw : Vec < bool > ,
173+ moved : usize ,
163174}
164175
165176/// The change from `canvas` to `frame`, both RGBA `width`×`height`, or `None`
166- /// when nothing moved. `canvas` holds each pixel as it was last drawn, not the
167- /// previous frame, so a slow drift is redrawn once it has moved past the
168- /// tolerance and the picture never strays further than that. The pixels drawn
169- /// take their new value in it.
170- fn take_change ( canvas : & mut [ u8 ] , frame : & [ u8 ] , width : u32 , height : u32 ) -> Option < Change > {
177+ /// when nothing moved. It redraws by `tile`×`tile` blocks: whole blocks around
178+ /// what moved, or, with 1, the moved pixels alone. `canvas` holds each pixel as
179+ /// it was last drawn, not the previous frame, so a slow drift is redrawn once it
180+ /// has moved past the tolerance and the picture never strays further than that.
181+ /// The pixels drawn take their new value in it.
182+ fn take_change (
183+ canvas : & mut [ u8 ] ,
184+ frame : & [ u8 ] ,
185+ width : u32 ,
186+ height : u32 ,
187+ tile : usize ,
188+ ) -> Option < Change > {
171189 let ( w, h) = ( width as usize , height as usize ) ;
172190 debug_assert ! ( canvas. len( ) == w * h * 4 && frame. len( ) == canvas. len( ) ) ;
173191 let px = |i : usize | i * 4 ..i * 4 + 4 ;
192+ let tiles_across = w. div_ceil ( tile) ;
193+ let tile_of = |x : usize , y : usize | ( y / tile) * tiles_across + x / tile;
194+ let mut dirty = vec ! [ false ; tiles_across * h. div_ceil( tile) ] ;
174195 let ( mut left, mut top, mut right, mut bottom) = ( w, h, 0 , 0 ) ;
196+ let mut count = 0 ;
175197 for y in 0 ..h {
176198 for x in 0 ..w {
177- let i = y * w + x;
178- if moved ( & canvas[ px ( i) ] , & frame[ px ( i) ] ) {
179- ( left, right) = ( left. min ( x) , right. max ( x) ) ;
180- ( top, bottom) = ( top. min ( y) , bottom. max ( y) ) ;
199+ if moved ( & canvas[ px ( y * w + x) ] , & frame[ px ( y * w + x) ] ) {
200+ dirty[ tile_of ( x, y) ] = true ;
201+ count += 1 ;
202+ ( left, right) = ( left. min ( x / tile * tile) , right. max ( ( x / tile + 1 ) * tile) ) ;
203+ ( top, bottom) = ( top. min ( y / tile * tile) , bottom. max ( ( y / tile + 1 ) * tile) ) ;
181204 }
182205 }
183206 }
184- if left > right {
207+ if count == 0 {
185208 return None ;
186209 }
187- let mut draw = Vec :: with_capacity ( ( right - left + 1 ) * ( bottom - top + 1 ) ) ;
188- for y in top..= bottom {
189- for x in left..=right {
190- let i = y * w + x ;
191- let redraw = moved ( & canvas [ px ( i ) ] , & frame [ px ( i ) ] ) ;
210+ let ( right , bottom ) = ( right. min ( w ) , bottom. min ( h ) ) ;
211+ let mut draw = Vec :: with_capacity ( ( right - left ) * ( bottom - top ) ) ;
212+ for y in top..bottom {
213+ for x in left..right {
214+ let redraw = dirty [ tile_of ( x , y ) ] ;
192215 if redraw {
193- canvas[ px ( i ) ] . copy_from_slice ( & frame[ px ( i ) ] ) ;
216+ canvas[ px ( y * w + x ) ] . copy_from_slice ( & frame[ px ( y * w + x ) ] ) ;
194217 }
195218 draw. push ( redraw) ;
196219 }
197220 }
198221 let rect = Rect {
199222 left : left as u32 ,
200223 top : top as u32 ,
201- width : ( right - left + 1 ) as u32 ,
202- height : ( bottom - top + 1 ) as u32 ,
224+ width : ( right - left) as u32 ,
225+ height : ( bottom - top) as u32 ,
203226 } ;
204- Some ( Change { rect, draw } )
227+ Some ( Change { rect, draw, moved : count } )
205228}
206229
207230/// The palette for `rgba`: 255 colours by median cut, then `TRANSPARENT_INDEX`.
@@ -435,20 +458,19 @@ fn export_gif_inner(
435458 debug_assert_eq ! ( rh, height) ;
436459
437460 // What this frame redraws: what moved since it was last drawn.
461+ // Dithered, by whole tiles (`DITHER_TILE`); plain, by the pixel.
462+ let tile = if dither { DITHER_TILE } else { 1 } ;
438463 let change = canvas
439464 . as_mut ( )
440- . and_then ( |canvas| take_change ( canvas, & rgba, width, height) ) ;
441- let mut redraw = change. map ( |Change { rect, draw } | ( rect, Some ( draw) ) ) ;
465+ . and_then ( |canvas| take_change ( canvas, & rgba, width, height, tile) ) ;
466+ let moved = change. as_ref ( ) . map_or ( 0 , |c| c. moved ) ;
467+ let mut redraw = change. map ( |Change { rect, draw, .. } | ( rect, Some ( draw) ) ) ;
442468 // The palette is rebuilt on a schedule, and at once when most of
443469 // the picture moved (a cut, a zoom): a new picture mapped to the
444470 // old one's palette gets the wrong colours. A palette that changed
445471 // redraws the whole frame, opaque, or what an older one drew would
446472 // stay on screen wherever the picture then stands still. Building
447473 // it is O(unique colors), cheap next to the mapping.
448- let moved = redraw
449- . as_ref ( )
450- . and_then ( |( _, draw) | draw. as_ref ( ) )
451- . map_or ( 0 , |draw| draw. iter ( ) . filter ( |& & d| d) . count ( ) ) ;
452474 if canvas. is_none ( )
453475 || frame_index - palette_at >= PALETTE_REQUANTIZE_EVERY
454476 || moved * 2 >= ( width * height) as usize
@@ -639,7 +661,7 @@ impl FrameEncoder {
639661 let indices = & mut self . indices [ ..w * h] ;
640662 // The dither pass diffuses the error against the CHOSEN palette
641663 // entry, so it runs fused with the mapping — see
642- // `map_to_indices_dithered`.
664+ // `map_to_indices_dithered`. What is not drawn takes no part in it.
643665 if self . dither {
644666 map_to_indices_dithered (
645667 & job. palette_rgb ,
@@ -649,6 +671,7 @@ impl FrameEncoder {
649671 & mut self . err_cur [ ..w * 3 ] ,
650672 & mut self . err_next [ ..w * 3 ] ,
651673 indices,
674+ job. draw . as_deref ( ) ,
652675 ) ;
653676 } else {
654677 map_to_indices ( & job. palette_rgb , & self . rect_rgba , indices) ;
@@ -1276,6 +1299,10 @@ impl SortedPalette {
12761299///
12771300/// Kernel is the standard 7/16 right, 3/16 below-left, 5/16 below,
12781301/// 1/16 below-right. Two row buffers keep the working set at O(width).
1302+ ///
1303+ /// `drawn`, when given, marks the pixels to map: the others are left as the
1304+ /// screen already shows them, so they neither take the error spread into them
1305+ /// nor pass any on, and their index is left for the caller to set.
12791306#[ allow( clippy:: too_many_arguments) ]
12801307fn map_to_indices_dithered (
12811308 palette_rgb : & [ u8 ] ,
@@ -1285,6 +1312,7 @@ fn map_to_indices_dithered(
12851312 err_cur : & mut [ f32 ] ,
12861313 err_next : & mut [ f32 ] ,
12871314 indices : & mut [ u8 ] ,
1315+ drawn : Option < & [ bool ] > ,
12881316) {
12891317 let w = width as usize ;
12901318 let h = height as usize ;
@@ -1298,6 +1326,9 @@ fn map_to_indices_dithered(
12981326
12991327 for y in 0 ..h {
13001328 for x in 0 ..w {
1329+ if drawn. is_some_and ( |drawn| !drawn[ y * w + x] ) {
1330+ continue ;
1331+ }
13011332 let base = ( y * w + x) * 4 ;
13021333 let e = x * 3 ;
13031334 // Channel value carrying the error diffused into this pixel.
@@ -1768,6 +1799,7 @@ mod tests {
17681799 & mut err_cur,
17691800 & mut err_next,
17701801 & mut indices,
1802+ None ,
17711803 ) ;
17721804 assert ! ( ( indices[ 0 ] as usize ) < PALETTE_COLORS ) ;
17731805 }
@@ -1799,6 +1831,7 @@ mod tests {
17991831 & mut err_cur,
18001832 & mut err_next,
18011833 & mut dithered,
1834+ None ,
18021835 ) ;
18031836
18041837 // RMS distance between the ramp and a 16-px moving average of what a row maps to: the
@@ -1874,6 +1907,7 @@ mod tests {
18741907 & mut err_cur,
18751908 & mut err_next,
18761909 & mut dithered,
1910+ None ,
18771911 ) ;
18781912 let ( mut cur, mut nxt) = ( vec ! [ 0.0f32 ; w * 3 ] , vec ! [ 0.0f32 ; w * 3 ] ) ;
18791913 for y in 0 ..h {
@@ -1955,22 +1989,22 @@ mod tests {
19551989 let px = |x : u32 , y : u32 | ( ( y * w + x) * 4 ) as usize ;
19561990 let first = ramp ( w, h) ;
19571991 let mut canvas = first. clone ( ) ;
1958- assert ! ( take_change( & mut canvas, & first, w, h) . is_none( ) ) ;
1992+ assert ! ( take_change( & mut canvas, & first, w, h, 1 ) . is_none( ) ) ;
19591993
19601994 // Codec noise, within the tolerance: nothing to redraw.
19611995 let mut frame = first. clone ( ) ;
19621996 frame[ px ( 2 , 2 ) + 1 ] = UNCHANGED_TOLERANCE ;
1963- assert ! ( take_change( & mut canvas, & frame, w, h) . is_none( ) ) ;
1997+ assert ! ( take_change( & mut canvas, & frame, w, h, 1 ) . is_none( ) ) ;
19641998
19651999 // Two pixels moved for real: the box takes both in, and only they are drawn.
19662000 frame[ px ( 4 , 1 ) + 2 ] = 200 ;
19672001 frame[ px ( 1 , 3 ) ] = 200 ;
1968- let change = take_change ( & mut canvas, & frame, w, h) . expect ( "a change" ) ;
2002+ let change = take_change ( & mut canvas, & frame, w, h, 1 ) . expect ( "a change" ) ;
19692003 assert_eq ! ( change. rect, Rect { left: 1 , top: 1 , width: 4 , height: 3 } ) ;
19702004 assert_eq ! ( change. draw. iter( ) . filter( |&&d| d) . count( ) , 2 ) ;
19712005 assert ! ( change. draw[ 3 ] && change. draw[ 8 ] ) ; // (4, 1) and (1, 3) in the box
19722006 assert_eq ! ( canvas[ px( 4 , 1 ) ..px( 4 , 1 ) + 4 ] , frame[ px( 4 , 1 ) ..px( 4 , 1 ) + 4 ] ) ;
1973- assert ! ( take_change( & mut canvas, & frame, w, h) . is_none( ) , "drawn, so settled" ) ;
2007+ assert ! ( take_change( & mut canvas, & frame, w, h, 1 ) . is_none( ) , "drawn, so settled" ) ;
19742008 }
19752009
19762010 #[ test]
@@ -1979,8 +2013,8 @@ mod tests {
19792013 let mut canvas = vec ! [ 100u8 , 100 , 100 , 255 , 0 , 0 , 0 , 255 ] ;
19802014 let step = |v : u8 | vec ! [ v, 100 , 100 , 255 , 0 , 0 , 0 , 255 ] ;
19812015 // Each step is within the tolerance of the last frame, not of what was drawn.
1982- assert ! ( take_change( & mut canvas, & step( 103 ) , w, h) . is_none( ) ) ;
1983- let change = take_change ( & mut canvas, & step ( 106 ) , w, h) . expect ( "drifted too far" ) ;
2016+ assert ! ( take_change( & mut canvas, & step( 103 ) , w, h, 1 ) . is_none( ) ) ;
2017+ let change = take_change ( & mut canvas, & step ( 106 ) , w, h, 1 ) . expect ( "drifted too far" ) ;
19842018 assert_eq ! ( change. rect, Rect { left: 0 , top: 0 , width: 1 , height: 1 } ) ;
19852019 assert_eq ! ( canvas[ 0 ] , 106 ) ;
19862020 }
@@ -1997,7 +2031,7 @@ mod tests {
19972031 map_to_indices ( & palette, & rgba, & mut indices) ;
19982032 assert ! ( !indices. contains( & TRANSPARENT_INDEX ) ) ;
19992033 let ( mut cur, mut next) = ( vec ! [ 0f32 ; w as usize * 3 ] , vec ! [ 0f32 ; w as usize * 3 ] ) ;
2000- map_to_indices_dithered ( & palette, & rgba, w, h, & mut cur, & mut next, & mut indices) ;
2034+ map_to_indices_dithered ( & palette, & rgba, w, h, & mut cur, & mut next, & mut indices, None ) ;
20012035 assert ! ( !indices. contains( & TRANSPARENT_INDEX ) ) ;
20022036 }
20032037
@@ -2010,7 +2044,7 @@ mod tests {
20102044 let px = |x : u32 , y : u32 | ( ( y * w + x) * 4 ) as usize ;
20112045 cur[ px ( 1 , 1 ) ] = 250 ;
20122046 cur[ px ( 3 , 1 ) ] = 250 ;
2013- let Change { rect, draw } = take_change ( & mut prev. clone ( ) , & cur, w, h) . expect ( "a change" ) ;
2047+ let Change { rect, draw, .. } = take_change ( & mut prev. clone ( ) , & cur, w, h, 1 ) . expect ( "a change" ) ;
20142048 assert_eq ! ( rect, Rect { left: 1 , top: 1 , width: 3 , height: 1 } ) ;
20152049 let palette = Arc :: new ( build_palette ( & cur) ) ;
20162050 for dither in [ false , true ] {
@@ -2063,6 +2097,84 @@ mod tests {
20632097 assert_eq ! ( ( last. lzw, delay) , ( vec![ 2 ] , 7 ) ) ;
20642098 }
20652099
2100+ #[ test]
2101+ fn a_dithered_change_redraws_whole_tiles ( ) {
2102+ let ( w, h) = ( 40u32 , 20u32 ) ;
2103+ let first = ramp ( w, h) ;
2104+ let mut canvas = first. clone ( ) ;
2105+ let mut frame = first. clone ( ) ;
2106+ let px = |x : u32 , y : u32 | ( ( y * w + x) * 4 ) as usize ;
2107+ frame[ px ( 20 , 5 ) ] = frame[ px ( 20 , 5 ) ] . wrapping_add ( 100 ) ;
2108+ frame[ px ( 22 , 5 ) + 1 ] = UNCHANGED_TOLERANCE - 1 ; // too small to move on its own
2109+ let change = take_change ( & mut canvas, & frame, w, h, DITHER_TILE ) . expect ( "a change" ) ;
2110+ // The pixel's tile, drawn whole.
2111+ let tile = DITHER_TILE as u32 ;
2112+ let tile_of_pixel = Rect { left : 20 / tile * tile, top : 5 / tile * tile, width : tile, height : tile } ;
2113+ assert_eq ! ( change. rect, tile_of_pixel) ;
2114+ assert ! ( change. draw. iter( ) . all( |& d| d) ) ;
2115+ assert_eq ! ( change. moved, 1 ) ;
2116+ assert_eq ! ( canvas[ px( 22 , 5 ) + 1 ] , UNCHANGED_TOLERANCE - 1 , "the whole tile takes its new value" ) ;
2117+ // A tile clipped by the frame's edge.
2118+ frame[ px ( 39 , 19 ) ] = frame[ px ( 39 , 19 ) ] . wrapping_add ( 100 ) ;
2119+ let change = take_change ( & mut canvas, & frame, w, h, DITHER_TILE ) . expect ( "a change" ) ;
2120+ let ( left, top) = ( 39 / tile * tile, 19 / tile * tile) ;
2121+ assert_eq ! ( change. rect, Rect { left, top, width: w - left, height: h - top } ) ;
2122+ }
2123+
2124+ #[ test]
2125+ fn pixels_not_drawn_pass_no_error_to_those_drawn ( ) {
2126+ // A grey row against a black and white palette: what is drawn must be
2127+ // dithered as if what is not drawn were not there.
2128+ let mut palette = vec ! [ 0u8 ; PALETTE_COLORS * 3 ] ;
2129+ palette[ 3 ..6 ] . copy_from_slice ( & [ 255 , 255 , 255 ] ) ;
2130+ let grey: Vec < u8 > = ( 0 ..8 ) . flat_map ( |_| [ 128u8 , 128 , 128 , 255 ] ) . collect ( ) ;
2131+ let drawn: Vec < bool > = ( 0 ..8 ) . map ( |i| i >= 4 ) . collect ( ) ;
2132+ let ( mut cur, mut next) = ( vec ! [ 0f32 ; 8 * 3 ] , vec ! [ 0f32 ; 8 * 3 ] ) ;
2133+ let mut indices = vec ! [ 7u8 ; 8 ] ;
2134+ map_to_indices_dithered ( & palette, & grey, 8 , 1 , & mut cur, & mut next, & mut indices, Some ( & drawn) ) ;
2135+ let mut alone = vec ! [ 0u8 ; 4 ] ;
2136+ map_to_indices_dithered ( & palette, & grey[ 16 ..] , 4 , 1 , & mut cur[ ..12 ] , & mut next[ ..12 ] , & mut alone, None ) ;
2137+ assert_eq ! ( indices[ 4 ..] , alone[ ..] ) ;
2138+ assert_eq ! ( indices[ ..4 ] , [ 7 , 7 , 7 , 7 ] , "the caller sets what is not drawn" ) ;
2139+ }
2140+
2141+ #[ test]
2142+ fn a_dithered_patch_keeps_its_balance_when_part_of_it_moves ( ) {
2143+ // Grey 128 dithers to white, black, white, black. Pixels 1 and 3 then move
2144+ // to 133. Redrawn alone, they came out white beside the white the screen
2145+ // still showed at 0 and 2: four whites for a grey. Their tile is redrawn
2146+ // together instead.
2147+ let mut palette = vec ! [ 0u8 ; PALETTE_COLORS * 3 ] ;
2148+ palette[ 3 ..6 ] . copy_from_slice ( & [ 255 , 255 , 255 ] ) ;
2149+ let palette = Arc :: new ( palette) ;
2150+ let row = |values : [ u8 ; 4 ] | -> Vec < u8 > { values. iter ( ) . flat_map ( |& v| [ v, v, v, 255 ] ) . collect ( ) } ;
2151+ let first = row ( [ 128 , 128 , 128 , 128 ] ) ;
2152+ let mut canvas = first. clone ( ) ;
2153+ let job = |rgba : Vec < u8 > , rect : Rect , draw : Option < Vec < bool > > | FrameJob {
2154+ index : 0 ,
2155+ rgba,
2156+ rect,
2157+ draw,
2158+ palette_rgb : palette. clone ( ) ,
2159+ } ;
2160+ let shown = FrameEncoder :: new ( 4 , 1 , true )
2161+ . encode ( job ( first, Rect :: full ( 4 , 1 ) , None ) )
2162+ . image
2163+ . expect ( "an image" ) ;
2164+ assert_eq ! ( lzw_decompress( & shown. lzw, 8 ) , vec![ 1 , 0 , 1 , 0 ] ) ;
2165+
2166+ let moved = row ( [ 128 , 133 , 128 , 133 ] ) ;
2167+ let Change { rect, draw, .. } =
2168+ take_change ( & mut canvas, & moved, 4 , 1 , DITHER_TILE ) . expect ( "a change" ) ;
2169+ let redrawn = FrameEncoder :: new ( 4 , 1 , true )
2170+ . encode ( job ( moved, rect, Some ( draw) ) )
2171+ . image
2172+ . expect ( "an image" ) ;
2173+ assert_eq ! ( redrawn. rect, Rect :: full( 4 , 1 ) ) ;
2174+ let whites = lzw_decompress ( & redrawn. lzw , 8 ) . iter ( ) . filter ( |& & i| i == 1 ) . count ( ) ;
2175+ assert_eq ! ( whites, 2 ) ;
2176+ }
2177+
20662178 #[ test]
20672179 fn a_still_stretch_past_the_longest_gif_delay_loses_none_of_it ( ) {
20682180 let mut hold = DelayHold :: default ( ) ;
0 commit comments