Skip to content

Commit b382178

Browse files
donislawdevclaude
andauthored
A GIF cut short loses the share of its picture asked for (#238)
A file truncate will cut has its padding split into a comment in front of the first frame and one in front of the trailer, so the cut falls in the frames at the share asked for. Until now the whole padding stood behind the frames, so from 20 KiB up a cut at any share lost only padding. GIF89a lets a comment stand wherever a block can begin, but not in front of the colour table, so the comment goes after the head the encoder writes - screen descriptor, colour table and loop extension - and the writer reads that head back before the comment goes in. The map now counts the head as structure and the frames as content: with the colour table as content, a small picture cut at 90% kept the table and no pixel. png's insert after the head moved to format.AfterTheHead. png bytes and uncut gif bytes are unchanged. Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 25bf623 commit b382178

8 files changed

Lines changed: 280 additions & 65 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -80,10 +80,10 @@ because it turns other people's test suites red.
8080
the length of the content is known. A cut in the padding also gets the
8181
note `cut_in_padding`. In a compressed tar.gz a cut in the padding is
8282
reported as a cut in the content.
83-
- **`truncate` cuts the picture of a PNG, a JPEG or an icon by the
84-
percentage you set.** `--damage truncate:missing=90` on a 1 MB PNG used to
85-
cut only padding and leave the whole picture, and on a JPEG or a large
86-
icon it removed the whole picture whatever percentage you set. Now it
83+
- **`truncate` cuts the picture of a PNG, a GIF, a JPEG or an icon by the
84+
percentage you set.** `--damage truncate:missing=90` on a 1 MB PNG or GIF
85+
used to cut only padding and leave the whole picture, and on a JPEG or a
86+
large icon it removed the whole picture whatever percentage you set. Now it
8787
removes 90% of the picture's content, so a viewer that shows what is left
8888
shows the part of the picture that arrived, the way an interrupted upload
8989
leaves it. Files nothing cuts are unchanged.

‎internal/format/cut.go‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,45 @@ func PaddingInFront(before, content, cutAt, whole int64) int64 {
2525
return cutAt - before - int64(kept)
2626
}
2727

28+
// AfterTheHead passes a stream on and, once its first Head bytes have gone on,
29+
// calls Insert before the rest: padding a format puts between the headers an
30+
// encoder writes first and the content that follows them. Insert gets the head
31+
// as it went out, so a format can check that the encoder wrote the head it
32+
// counted before it trusts the length. An Insert that fails stops the stream
33+
// with its error.
34+
type AfterTheHead struct {
35+
W io.Writer
36+
Head int64
37+
Insert func(w io.Writer, head []byte) error
38+
// head is what has gone on of the first Head bytes, and done says Insert
39+
// has been called.
40+
head []byte
41+
done bool
42+
}
43+
44+
func (a *AfterTheHead) Write(p []byte) (int, error) {
45+
n := 0
46+
if !a.done {
47+
k := min(a.Head-int64(len(a.head)), int64(len(p)))
48+
written, err := a.W.Write(p[:k])
49+
a.head = append(a.head, p[:written]...)
50+
n = written
51+
if err != nil || int64(len(a.head)) < a.Head {
52+
return n, err
53+
}
54+
a.done = true
55+
if err := a.Insert(a.W, a.head); err != nil {
56+
return n, err
57+
}
58+
p = p[k:]
59+
}
60+
if len(p) == 0 {
61+
return n, nil
62+
}
63+
written, err := a.W.Write(p)
64+
return n + written, err
65+
}
66+
2867
// TailHolder passes a stream on while keeping its last Keep bytes back, so a
2968
// format can write something in front of them once the stream ends - padding
3069
// in front of the end marker an encoder writes last.

‎internal/format/gif/cut.go‎

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,187 @@
1+
package gif
2+
3+
import (
4+
"bytes"
5+
"context"
6+
"fmt"
7+
"io"
8+
9+
"github.com/donislawdev/TestingFilesGenerator/internal/core"
10+
"github.com/donislawdev/TestingFilesGenerator/internal/format"
11+
)
12+
13+
// loopExtensionSize is the application extension the encoder writes after the
14+
// colour table of a picture that moves: introducer, label, block size, the
15+
// eleven bytes of NETSCAPE2.0, a three byte sub block with the loop count, and
16+
// the terminator.
17+
const loopExtensionSize = 3 + 11 + 4 + 1
18+
19+
// loopExtensionStart is how that extension opens.
20+
var loopExtensionStart = []byte("\x21\xff\x0bNETSCAPE2.0")
21+
22+
// writeForACut writes a file a damage will cut after its first m.cutAt bytes,
23+
// with the padding split into a comment in front of the first frame and one in
24+
// front of the trailer, so that the cut keeps the share of the frames it keeps
25+
// of the whole file (format.Request.CutAt).
26+
//
27+
// With all of the padding behind the frames, as an uncut file has it, a large
28+
// file cut at any share kept the whole picture and lost only padding. GIF89a
29+
// lets a comment stand wherever a block can begin, the beginning of the data
30+
// stream included (section 24), but not in front of the colour table, which
31+
// belongs to the screen descriptor (appendix B). The comment in front goes after
32+
// the head the encoder writes - the descriptor, the colour table and, for a
33+
// picture that moves, the loop extension - where Pillow, FFmpeg, ImageMagick,
34+
// Go, the Windows Imaging Component, GDI+, exiftool, Tk and Chrome return the
35+
// same frames, the same loop count and the same pixels as for the file uncut
36+
// (docs/TRUNCATE-2026-11-11.md section 9.3).
37+
//
38+
// The frames stream out as the encoder writes them, so the cut stops the
39+
// encoder where it falls. The comment in front is sized from their length, so a
40+
// plan that did not encode the picture encodes it here first, which is what
41+
// every GIF below the ladder ceiling pays at planning today.
42+
func writeForACut(ctx context.Context, w io.Writer, m memo, whole int64) error {
43+
if !m.bodyKnown {
44+
body, err := encodedBodySize(m)
45+
if err != nil {
46+
return err
47+
}
48+
m.body, m.bodyKnown = body, true
49+
}
50+
if err := settlePadding(&m, whole, m.body+trailerSize); err != nil {
51+
return core.Defect(fmt.Errorf("gif: %w - ladderCeiling is wrong", err))
52+
}
53+
head := headBytes(m)
54+
pad := whole - m.body - trailerSize
55+
front := frontPadding(pad, m.body-head, head, m.cutAt, whole)
56+
markAroundThePicture(w, m.body, head, front, pad-front)
57+
58+
// Both comments draw from the file's seed. Nobody reads padding, and the
59+
// comment behind the frames lies past any cut.
60+
split := &format.AfterTheHead{W: w, Head: head, Insert: func(w io.Writer, got []byte) error {
61+
if err := checkHead(got, m); err != nil {
62+
return err
63+
}
64+
return writePadding(ctx, w, m.seed, front)
65+
}}
66+
holder := &format.TailHolder{W: split, Keep: trailerSize}
67+
if err := encode(holder, m); err != nil {
68+
return err
69+
}
70+
if holder.Written != m.body {
71+
return core.Defect(fmt.Errorf("gif: the picture encoded to %d B where planning said %d B", holder.Written, m.body))
72+
}
73+
if holder.Tail[0] != 0x3B {
74+
return core.Defect(fmt.Errorf("gif: the encoded stream does not end with the trailer"))
75+
}
76+
if err := writePadding(ctx, w, m.seed, pad-front); err != nil {
77+
return err
78+
}
79+
_, err := w.Write(holder.Tail)
80+
return err
81+
}
82+
83+
// headBytes is how long the head the encoder writes in front of the first
84+
// frame is: the signature and screen descriptor, the colour table, and the loop
85+
// extension when the picture moves. The map counts it as structure - the colour
86+
// table is a table the frames are read through, and the frames are what a
87+
// reader hands back (docs/TRUNCATE-2026-11-11.md section 9.4).
88+
func headBytes(m memo) int64 {
89+
n := int64(screenHeader + 3*paletteSize(m.width, m.height))
90+
if m.frames > 1 {
91+
n += loopExtensionSize
92+
}
93+
return n
94+
}
95+
96+
// checkHead is whether the head that went out before the comment is the head
97+
// the encoder wrote: the screen descriptor, the colour table its packed field
98+
// announces, of the size planning counted, and for a picture that moves the
99+
// loop extension right after it - nothing more and nothing less. A head of
100+
// another length puts the comment inside the colour table or a frame.
101+
func checkHead(got []byte, m memo) error {
102+
if len(got) < screenHeader {
103+
return core.Defect(fmt.Errorf("gif: %d B went out before the comment, less than the screen descriptor", len(got)))
104+
}
105+
table, packed := 0, got[10]
106+
if packed&0x80 != 0 {
107+
table = 3 << (packed&0x07 + 1)
108+
}
109+
if want := 3 * paletteSize(m.width, m.height); table != want {
110+
return core.Defect(fmt.Errorf("gif: the encoder's colour table is %d B where planning counted %d B", table, want))
111+
}
112+
head := screenHeader + table
113+
if m.frames > 1 {
114+
head += loopExtensionSize
115+
}
116+
if len(got) != head {
117+
return core.Defect(fmt.Errorf("gif: %d B went out before the comment where the encoder's head is %d B", len(got), head))
118+
}
119+
if m.frames > 1 {
120+
loop := got[screenHeader+table:]
121+
if !bytes.HasPrefix(loop, loopExtensionStart) || loop[len(loop)-1] != 0 {
122+
return core.Defect(fmt.Errorf("gif: the encoder did not write the loop extension right after the colour table"))
123+
}
124+
}
125+
return nil
126+
}
127+
128+
// frontPadding is how much of the padding, as a comment, goes in front of the
129+
// first frame, so that a cut after the first cutAt bytes of a whole file keeps
130+
// frames*cutAt/whole bytes of the frames.
131+
//
132+
// A comment is nothing, three bytes or at least five, so both sides are
133+
// rounded to that. Where they cannot land exactly, the front grows - at most
134+
// four bytes - which moves the frames later and cuts more of them, the "at
135+
// least" missing promises. The one way it can keep more is a padding too short
136+
// for the frames the cut should take: there all of it goes in front, and the cut
137+
// keeps at most one byte more than the share (docs/TRUNCATE-2026-11-11.md
138+
// section 9.5). The manifest's cut reports what was kept either way.
139+
func frontPadding(pad, frames, head, cutAt, whole int64) int64 {
140+
if pad == 0 || cutAt <= 0 || cutAt >= whole {
141+
return 0
142+
}
143+
front := format.PaddingInFront(head, frames, cutAt, whole)
144+
if front <= 0 {
145+
return 0
146+
}
147+
for ; front < pad; front++ {
148+
if isComment(front) && isComment(pad-front) {
149+
return front
150+
}
151+
}
152+
return pad
153+
}
154+
155+
// isComment is whether n bytes can be spent as one comment extension, or as
156+
// none at all.
157+
func isComment(n int64) bool {
158+
return n == 0 || n == emptyComment || n >= smallestCarryingComment
159+
}
160+
161+
// writePadding writes n bytes of padding as one comment, or nothing for n = 0.
162+
func writePadding(ctx context.Context, w io.Writer, seed uint64, n int64) error {
163+
if n == 0 {
164+
return nil
165+
}
166+
blocks, payload := commentShape(n)
167+
return writeComment(ctx, w, seed, blocks, payload)
168+
}
169+
170+
// markAroundThePicture marks the map of a file whose padding is split around
171+
// its frames: the head, the comment in front, the frames, the comment behind
172+
// and the trailer. A side with no padding has no comment and no region.
173+
func markAroundThePicture(w io.Writer, body, head, front, back int64) {
174+
format.Mark(w, format.RoleStructure, 0, head)
175+
at := head
176+
if front > 0 {
177+
format.Mark(w, format.RolePadding, at, front)
178+
at += front
179+
}
180+
format.Mark(w, format.RoleContent, at, body-head)
181+
at += body - head
182+
if back > 0 {
183+
format.Mark(w, format.RolePadding, at, back)
184+
at += back
185+
}
186+
format.Mark(w, format.RoleEnd, at, trailerSize)
187+
}

‎internal/format/gif/gif.go‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@
33
// A compressed format, so the size of the picture is whatever LZW decides and
44
// the last bytes come from a padding channel - the same shape as PNG. The
55
// channel here is the comment extension, a block the format sets aside for
6-
// arbitrary content.
6+
// arbitrary content. A file a damage will cut short has its padding split
7+
// into a comment in front of the frames and one behind them, so the cut takes
8+
// the share of the picture asked for (cut.go).
79
//
810
// It has one awkward property PNG does not, and it is measured rather than
911
// guessed: an empty comment costs three bytes and a comment carrying a single
@@ -166,6 +168,10 @@ type memo struct {
166168
payload int64
167169
blocks int64
168170
comment bool
171+
// cutAt is where a damage will cut the file, zero when nothing does
172+
// (format.Request.CutAt). writeForACut splits the padding around the
173+
// frames for it.
174+
cutAt int64
169175
}
170176

171177
func checkJointLimits(w, h int) error {
@@ -196,6 +202,7 @@ func (generator) Plan(r format.Request) (format.Plan, error) {
196202
if err != nil {
197203
return format.Plan{}, err
198204
}
205+
m.cutAt = r.CutAt
199206
w, h := m.width, m.height
200207
bare := m.body + trailerSize
201208

@@ -324,15 +331,19 @@ func (generator) Write(ctx context.Context, w io.Writer, p format.Plan) error {
324331
return ctx.Err()
325332
default:
326333
}
334+
if m.cutAt > 0 && m.cutAt < p.Bytes {
335+
return writeForACut(ctx, w, m, p.Bytes)
336+
}
327337

328338
// The map, before the bytes wherever planning measured the picture. The
329-
// palette counts to the content, with the frames it colours: the encoder
330-
// writes it, and a reader needs it to hand back a single pixel.
331-
format.Mark(w, format.RoleStructure, 0, screenHeader)
339+
// head the encoder writes in front of the first frame - the colour table
340+
// and the loop extension with it - is structure, and the frames are the
341+
// content (headBytes).
342+
format.Mark(w, format.RoleStructure, 0, headBytes(m))
332343
if m.bodyKnown {
333344
markAfterThePicture(w, m, p.Bytes, true)
334345
} else {
335-
format.Mark(w, format.RoleContent, screenHeader, -1)
346+
format.Mark(w, format.RoleContent, headBytes(m), -1)
336347
}
337348

338349
// The trailer is always the final byte, so hold it back and let the rest
@@ -373,12 +384,13 @@ func (generator) Write(ctx context.Context, w io.Writer, p format.Plan) error {
373384
// every GIF and are always this long.
374385
const screenHeader = 6 + 7
375386

376-
// markAfterThePicture marks the picture when its length is known, and what
377-
// follows it: the comment that makes up the size, if there is one, and the
387+
// markAfterThePicture marks the frames when their length is known, and what
388+
// follows them: the comment that makes up the size, if there is one, and the
378389
// trailer.
379390
func markAfterThePicture(w io.Writer, m memo, total int64, withPicture bool) {
380391
if withPicture {
381-
format.Mark(w, format.RoleContent, screenHeader, m.body-screenHeader)
392+
head := headBytes(m)
393+
format.Mark(w, format.RoleContent, head, m.body-head)
382394
}
383395
if m.comment {
384396
format.Mark(w, format.RolePadding, m.body, total-trailerSize-m.body)

‎internal/format/png/cut.go‎

Lines changed: 8 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,14 @@ func writeForACut(ctx context.Context, w io.Writer, m memo, whole int64) error {
4242
markAroundThePicture(w, m.body, front, pad-front)
4343

4444
// Both padding chunks draw from the file's seed. Nobody reads padding, and
45-
// the one behind the picture lies past any cut.
46-
split := &afterTheHead{ctx: ctx, w: w, seed: m.seed, head: headSize, front: front}
45+
// the one behind the picture lies past any cut. The padding in front goes
46+
// after the signature and the header chunk.
47+
split := &format.AfterTheHead{W: w, Head: headSize, Insert: func(w io.Writer, _ []byte) error {
48+
if front == 0 {
49+
return nil
50+
}
51+
return writePaddingChunk(ctx, w, paddingChunk, m.seed, front-chunkOverhead)
52+
}}
4753
holder := &format.TailHolder{W: split, Keep: iendSize}
4854
if err := encode(holder, m); err != nil {
4955
return err
@@ -63,45 +69,6 @@ func writeForACut(ctx context.Context, w io.Writer, m memo, whole int64) error {
6369
return err
6470
}
6571

66-
// afterTheHead passes the encoded picture on, and writes the padding that goes
67-
// in front of the picture's data once the first head bytes - the signature and
68-
// the header chunk - are out.
69-
type afterTheHead struct {
70-
ctx context.Context
71-
w io.Writer
72-
seed uint64
73-
// head is how many bytes are still to pass before the padding.
74-
head int64
75-
// front is the padding, its chunk's header and checksum included, and 0
76-
// once it is written or when there is none.
77-
front int64
78-
}
79-
80-
func (a *afterTheHead) Write(p []byte) (int, error) {
81-
n := 0
82-
if a.head > 0 {
83-
k := min(a.head, int64(len(p)))
84-
written, err := a.w.Write(p[:k])
85-
n, a.head = written, a.head-int64(written)
86-
if err != nil || a.head > 0 {
87-
return n, err
88-
}
89-
p = p[k:]
90-
}
91-
if a.front > 0 {
92-
front := a.front
93-
a.front = 0
94-
if err := writePaddingChunk(a.ctx, a.w, paddingChunk, a.seed, front-chunkOverhead); err != nil {
95-
return n, err
96-
}
97-
}
98-
if len(p) == 0 {
99-
return n, nil
100-
}
101-
written, err := a.w.Write(p)
102-
return n + written, err
103-
}
104-
10572
// frontPadding is how much of the padding, chunk headers included, goes in
10673
// front of the picture, so that a cut after the first cutAt bytes of a whole
10774
// file keeps content*cutAt/whole bytes of the picture's content.

0 commit comments

Comments
 (0)