+ if (s->image || !avctx->frame_number) { /* GIF header */
+ const uint32_t *global_palette = palette ? palette : s->palette;
+ const AVRational sar = avctx->sample_aspect_ratio;
+ int64_t aspect = 0;
+
+ if (sar.num > 0 && sar.den > 0) {
+ aspect = sar.num * 64LL / sar.den - 15;
+ if (aspect < 0 || aspect > 255)
+ aspect = 0;
+ }
+
+ bytestream_put_buffer(bytestream, gif89a_sig, sizeof(gif89a_sig));
+ bytestream_put_le16(bytestream, avctx->width);
+ bytestream_put_le16(bytestream, avctx->height);
+
+ bcid = get_palette_transparency_index(global_palette);
+
+ bytestream_put_byte(bytestream, 0xf7); /* flags: global clut, 256 entries */
+ bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid); /* background color index */
+ bytestream_put_byte(bytestream, aspect);
+ for (int i = 0; i < 256; i++) {
+ const uint32_t v = global_palette[i] & 0xffffff;
+ bytestream_put_be24(bytestream, v);
+ }
+ }
+
+ if (honor_transparency && trans < 0) {
+ trans = pick_palette_entry(buf + y_start*linesize + x_start,
+ linesize, width, height);
+ if (trans < 0) // TODO, patch welcome
+ av_log(avctx, AV_LOG_DEBUG, "No available color, can not use transparency\n");
+ }
+
+ if (trans < 0)
+ honor_transparency = 0;
+
+ bcid = honor_transparency || disposal == GCE_DISPOSAL_BACKGROUND ? trans : get_palette_transparency_index(palette);
+
+ /* graphic control extension */
+ bytestream_put_byte(bytestream, GIF_EXTENSION_INTRODUCER);
+ bytestream_put_byte(bytestream, GIF_GCE_EXT_LABEL);
+ bytestream_put_byte(bytestream, 0x04); /* block size */
+ bytestream_put_byte(bytestream, disposal<<2 | (bcid >= 0));
+ bytestream_put_le16(bytestream, 5); // default delay
+ bytestream_put_byte(bytestream, bcid < 0 ? DEFAULT_TRANSPARENCY_INDEX : bcid);
+ bytestream_put_byte(bytestream, 0x00);
+