+static int
+in_palette(i_color *c, i_quantize *quant, int size) {
+ int i;
+
+ for (i = 0; i < size; ++i) {
+ if (c->channel[0] == quant->mc_colors[i].channel[0]
+ && c->channel[1] == quant->mc_colors[i].channel[1]
+ && c->channel[2] == quant->mc_colors[i].channel[2]) {
+ return i;
+ }
+ }
+
+ return -1;
+}
+
+/*
+=item has_common_palette(imgs, count, quant, want_trans)
+
+Tests if all the given images are paletted and have a common palette,
+if they do it builds that palette.
+
+A possible improvement might be to eliminate unused colors in the
+images palettes.
+
+=cut */
+static int
+has_common_palette(i_img **imgs, int count, i_quantize *quant, int want_trans,
+ i_gif_opts *opts) {
+ int size = quant->mc_count;
+ int i, j;
+ int imgn;
+ int x, y;
+ char used[256];
+
+ /* we try to build a common palette here, if we can manage that, then
+ that's the palette we use */
+ for (imgn = 0; imgn < count; ++imgn) {
+ if (imgs[imgn]->type != i_palette_type)
+ return 0;
+
+ if (opts->eliminate_unused) {
+ i_palidx *line = mymalloc(sizeof(i_palidx) * imgs[imgn]->xsize);
+ int x, y;
+ memset(used, 0, sizeof(used));
+
+ for (y = 0; y < imgs[imgn]->ysize; ++y) {
+ i_gpal(imgs[imgn], 0, imgs[imgn]->xsize, y, line);
+ for (x = 0; x < imgs[imgn]->xsize; ++x)
+ used[line[x]] = 1;
+ }
+
+ myfree(line);
+ }
+ else {
+ /* assume all are in use */
+ memset(used, 1, sizeof(used));
+ }
+
+ for (i = 0; i < i_colorcount(imgs[imgn]); ++i) {
+ i_color c;
+
+ i_getcolors(imgs[imgn], i, &c, 1);
+ if (used[i]) {
+ if (in_palette(&c, quant, size) < 0) {
+ if (size < quant->mc_size) {
+ quant->mc_colors[size++] = c;
+ }
+ else {
+ /* oops, too many colors */
+ return 0;
+ }
+ }
+ }
+ }
+ }
+
+ quant->mc_count = size;
+
+ return 1;
+}
+
+static i_palidx *
+quant_paletted(i_quantize *quant, i_img *img) {
+ i_palidx *data = mymalloc(sizeof(i_palidx) * img->xsize * img->ysize);
+ i_palidx *p = data;
+ i_palidx trans[256];
+ int i;
+ int x, y;
+
+ /* build a translation table */
+ for (i = 0; i < i_colorcount(img); ++i) {
+ i_color c;
+ i_getcolors(img, i, &c, 1);
+ trans[i] = in_palette(&c, quant, quant->mc_count);
+ }
+
+ for (y = 0; y < img->ysize; ++y) {
+ i_gpal(img, 0, img->xsize, y, data+img->xsize * y);
+ for (x = 0; x < img->xsize; ++x) {
+ *p = trans[*p];
+ ++p;
+ }
+ }
+
+ return data;
+}
+