Repository: python-pillow/Pillow

Issue:
gif frame deduplication on existing files without directly specifying duration results in incorrectly altered gif frame durations
In relation to @radarhere's comment [here](https://github.com/python-pillow/Pillow/issues/5928#issuecomment-1005279381), I've discovered an edge case that does not fall into the behavior described.

### What did you do?

> But what you might notice in the above is that Pillow combines the duration of the frames. So if you add in duration to your code, then when opening the image back up again, you can detect the duration and use that to determine the original binary string.

I'm running into a similar issue as the reporter of #5928 and I believe I've found an edge case that doesn't follow the desired frame deduplication behavior.

First, let's presume we have a pre-existing animated gif file we open with `Image.open`.  This gif already has durations specified and has duplicate frames, each with their own durations.  Now, in the process of attempting to generate a thumbnail and perform some operations on the file, let's assume we save the file with `save_all=True`, but *without* specifying a duration because we want to leave the original file/frame durations unaltered.

Going by the state of main (currently `6a2545f6`) and following the code, we're able to set the original frame's durations by falling back on the `im_frame.info["duration"]` as seen here:

https://github.com/python-pillow/Pillow/blob/6a2545f628b13bc4888f687c1028482fc93fafcf/src/PIL/GifImagePlugin.py#L592-L593

...but when the deduplication check is performed, the same pattern of falling back on the frame's duration is *not* used:

https://github.com/python-pillow/Pillow/blob/6a2545f628b13bc4888f687c1028482fc93fafcf/src/PIL/GifImagePlugin.py#L621-L622

As `duration` is none during the frame deduplication, it drops the duplicates *but it never combines the durations into the prior frames*.  This ultimately results in an altered animation with notably different timings than the original.

At best guess, a fix might be to check `if encoderinfo["duration"]` instead of `if duration`, but I'm very unfamiliar with the codebase and don't have much confidence in that recommendation.

(Apologies, I cannot currently provide a sample of the image to help reproduce this bug.  If I have time later, I'll try to mock one out with another tool to help reproduce the issue.)

### What are your OS, Python and Pillow versions?

* OS: Ubuntu 22.04
* Python: 3.10.6
* Pillow: 9.3.0



Discussion:
For others, my workaround when saving -

```py
durations = []
for i in range(0, img.n_frames):
    img.seek(i)
    durations.append(img.info['duration'])
img.save(dest, save_all=True, duration=durations)
```

Resolving patch:
diff --git a/src/PIL/GifImagePlugin.py b/src/PIL/GifImagePlugin.py
--- a/src/PIL/GifImagePlugin.py
+++ b/src/PIL/GifImagePlugin.py
@@ -618,7 +618,7 @@ def _write_multiple_frames(im, fp, palette):
                 bbox = delta.getbbox()
                 if not bbox:
                     # This frame is identical to the previous frame
-                    if duration:
+                    if encoderinfo.get("duration"):
                         previous["encoderinfo"]["duration"] += encoderinfo["duration"]
                     continue
             else:


Test patch:
diff --git a/Tests/images/duplicate_frame.gif b/Tests/images/duplicate_frame.gif
new file mode 100644
Binary files /dev/null and b/Tests/images/duplicate_frame.gif differ
diff --git a/Tests/test_file_gif.py b/Tests/test_file_gif.py
--- a/Tests/test_file_gif.py
+++ b/Tests/test_file_gif.py
@@ -791,6 +791,22 @@ def test_roundtrip_info_duration(tmp_path):
         ] == duration_list
 
 
+def test_roundtrip_info_duration_combined(tmp_path):
+    out = str(tmp_path / "temp.gif")
+    with Image.open("Tests/images/duplicate_frame.gif") as im:
+        assert [frame.info["duration"] for frame in ImageSequence.Iterator(im)] == [
+            1000,
+            1000,
+            1000,
+        ]
+        im.save(out, save_all=True)
+
+    with Image.open(out) as reloaded:
+        assert [
+            frame.info["duration"] for frame in ImageSequence.Iterator(reloaded)
+        ] == [1000, 2000]
+
+
 def test_identical_frames(tmp_path):
     duration_list = [1000, 1500, 2000, 4000]