From 7881e4a7308a7d7f25b27511ba5c0125f9261f52 Mon Sep 17 00:00:00 2001 From: "L. Pereira" Date: Thu, 30 Jan 2025 14:25:42 -0800 Subject: [PATCH] Generate GIF from Forth Haiku This is using a hardcoded Haiku but this will eventually be something that users will be able to upload and edit and mix, similar to the Forth Salon website. --- src/samples/forthsalon/CMakeLists.txt | 13 + src/samples/forthsalon/forth.c | 34 +- src/samples/forthsalon/forth.h | 39 ++ src/samples/forthsalon/gif.h | 863 ++++++++++++++++++++++++++ src/samples/forthsalon/main.c | 81 ++- 5 files changed, 1015 insertions(+), 15 deletions(-) create mode 100644 src/samples/forthsalon/forth.h create mode 100644 src/samples/forthsalon/gif.h diff --git a/src/samples/forthsalon/CMakeLists.txt b/src/samples/forthsalon/CMakeLists.txt index 85671890b..e41d52402 100644 --- a/src/samples/forthsalon/CMakeLists.txt +++ b/src/samples/forthsalon/CMakeLists.txt @@ -9,3 +9,16 @@ target_link_libraries(forth ${ADDITIONAL_LIBRARIES} m ) + +add_executable(forthsalon + forth.c + main.c +) + +ADD_DEFINITIONS(-fstack-usage) + +target_link_libraries(forthsalon + ${LWAN_COMMON_LIBS} + ${ADDITIONAL_LIBRARIES} + m +) diff --git a/src/samples/forthsalon/forth.c b/src/samples/forthsalon/forth.c index 4b7e2d59a..2403f8361 100644 --- a/src/samples/forthsalon/forth.c +++ b/src/samples/forthsalon/forth.c @@ -14,7 +14,8 @@ * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. */ /* @@ -37,6 +38,8 @@ #include "lwan-array.h" #include "lwan-private.h" +#include "forth.h" + enum forth_opcode { OP_CALL_BUILTIN, OP_EVAL_CODE, @@ -65,7 +68,8 @@ DEFINE_ARRAY_TYPE(forth_code, struct forth_inst) struct forth_word { union { bool (*callback)(struct forth_ctx *ctx, struct forth_vars *vars); - const char *(*callback_compiler)(struct forth_ctx *ctx, const char *code); + const char *(*callback_compiler)(struct forth_ctx *ctx, + const char *code); struct forth_code code; }; bool is_builtin; @@ -89,11 +93,6 @@ struct forth_ctx { bool is_inside_word_def; }; -struct forth_vars { - double x, y; - int t, dt; -}; - #define PUSH_D(value_) \ ({ \ if (UNLIKELY(ctx->d_stack.pos >= N_ELEMENTS(ctx->d_stack.values))) \ @@ -126,7 +125,6 @@ static inline double pop_r(struct forth_ctx *ctx) return (double)NAN; } - #if DUMP_CODE static void dump_code(const struct forth_code *code) { @@ -181,7 +179,8 @@ static bool eval_code(struct forth_ctx *ctx, LWAN_ARRAY_FOREACH (code, inst) { switch (inst->opcode) { case OP_EVAL_CODE: - if (UNLIKELY(!eval_code(ctx, inst->code, vars, recursion_limit - 1))) + if (UNLIKELY( + !eval_code(ctx, inst->code, vars, recursion_limit - 1))) return false; break; case OP_CALL_BUILTIN: @@ -509,7 +508,8 @@ BUILTIN_COMPILER("if") return code; } -static const char* builtin_else_then(struct forth_ctx *ctx, const char *code, bool is_then) +static const char * +builtin_else_then(struct forth_ctx *ctx, const char *code, bool is_then) { double v = POP_R(); if (UNLIKELY(isnan(v))) { @@ -1034,6 +1034,16 @@ void forth_free(struct forth_ctx *ctx) free(ctx); } +size_t forth_d_stack_len(const struct forth_ctx *ctx) +{ + return ctx->d_stack.pos; +} + +double forth_d_stack_pop(struct forth_ctx *ctx) +{ + return POP_D(); +} + #if defined(FUZZ_TEST) int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { @@ -1069,7 +1079,9 @@ int main(int argc, char *argv[]) if (!ctx) return 1; - if (!forth_parse_string(ctx, ": nice 60 5 4 + + ; : juanita 400 10 5 5 + + + ; x if nice else juanita then 2 * 4 / 2 *")) { + if (!forth_parse_string(ctx, + ": nice 60 5 4 + + ; : juanita 400 10 5 5 + + + ; " + "x if nice else juanita then 2 * 4 / 2 *")) { lwan_status_critical("could not parse forth program"); forth_free(ctx); return 1; diff --git a/src/samples/forthsalon/forth.h b/src/samples/forthsalon/forth.h new file mode 100644 index 000000000..0d4fc63c6 --- /dev/null +++ b/src/samples/forthsalon/forth.h @@ -0,0 +1,39 @@ +/* + * lwan - web server + * Copyright (c) 2025 L. A. F. Pereira + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version 2 + * of the License, or any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, + * USA. + */ + +#pragma once + +struct forth_ctx; + +struct forth_vars { + double x, y; + double t, dt; +}; + +bool forth_run(struct forth_ctx *ctx, struct forth_vars *vars); +bool forth_parse_string(struct forth_ctx *ctx, const char *code); +void forth_free(struct forth_ctx *ctx); +struct forth_ctx *forth_new(void); +size_t forth_d_stack_len(const struct forth_ctx *ctx); +double forth_d_stack_pop(struct forth_ctx *ctx); + + + + diff --git a/src/samples/forthsalon/gif.h b/src/samples/forthsalon/gif.h new file mode 100644 index 000000000..2c52cfb1b --- /dev/null +++ b/src/samples/forthsalon/gif.h @@ -0,0 +1,863 @@ +// +// gif.h +// by Charlie Tangora +// Public domain. +// Email me : ctangora -at- gmail -dot- com +// +// This file offers a simple, very limited way to create animated GIFs directly in code. +// +// Those looking for particular cleverness are likely to be disappointed; it's pretty +// much a straight-ahead implementation of the GIF format with optional Floyd-Steinberg +// dithering. (It does at least use delta encoding - only the changed portions of each +// frame are saved.) +// +// So resulting files are often quite large. The hope is that it will be handy nonetheless +// as a quick and easily-integrated way for programs to spit out animations. +// +// Only RGBA8 is currently supported as an input format. (The alpha is ignored.) +// +// If capturing a buffer with a bottom-left origin (such as OpenGL), define GIF_FLIP_VERT +// to automatically flip the buffer data when writing the image (the buffer itself is +// unchanged. +// +// USAGE: +// Create a GifWriter struct. Pass it to GifBegin() to initialize and write the header. +// Pass subsequent frames to GifWriteFrame(). +// Finally, call GifEnd() to close the file handle and free memory. +// + +#ifndef gif_h +#define gif_h + +/* FIXME(lpereira): Someday I need to go through these warnings and fix them up. */ +#pragma GCC diagnostic ignored "-Wconversion" +#pragma GCC diagnostic ignored "-Wpointer-sign" +#pragma GCC diagnostic ignored "-Warith-conversion" + +#include // for memcpy and bzero +#include // for integer typedefs +#include // for bool macros + +// Define these macros to hook into a custom memory allocator. +// TEMP_MALLOC and TEMP_FREE will only be called in stack fashion - frees in the reverse order of mallocs +// and any temp memory allocated by a function will be freed before it exits. +// MALLOC and FREE are used only by GifBegin and GifEnd respectively (to allocate a buffer the size of the image, which +// is used to find changed pixels for delta-encoding.) + +#ifndef GIF_TEMP_MALLOC +#include +#define GIF_TEMP_MALLOC malloc +#endif + +#ifndef GIF_TEMP_FREE +#include +#define GIF_TEMP_FREE free +#endif + +#ifndef GIF_MALLOC +#include +#define GIF_MALLOC malloc +#endif + +#ifndef GIF_FREE +#include +#define GIF_FREE free +#endif + +const int kGifTransIndex = 0; + +typedef struct +{ + int bitDepth; + + uint8_t r[256]; + uint8_t g[256]; + uint8_t b[256]; + + // k-d tree over RGB space, organized in heap fashion + // i.e. left child of node i is node i*2, right child is node i*2+1 + // nodes 256-511 are implicitly the leaves, containing a color + uint8_t treeSplitElt[256]; + uint8_t treeSplit[256]; +} GifPalette; + +// max, min, and abs functions +int GifIMax(int l, int r) { return l>r?l:r; } +int GifIMin(int l, int r) { return l (1<bitDepth)-1) + { + int ind = treeRoot-(1<bitDepth); + if(ind == kGifTransIndex) return; + + // check whether this color is better than the current winner + int r_err = r - ((int32_t)pPal->r[ind]); + int g_err = g - ((int32_t)pPal->g[ind]); + int b_err = b - ((int32_t)pPal->b[ind]); + int diff = GifIAbs(r_err)+GifIAbs(g_err)+GifIAbs(b_err); + + if(diff < *bestDiff) + { + *bestInd = ind; + *bestDiff = diff; + } + + return; + } + + // take the appropriate color (r, g, or b) for this node of the k-d tree + int comps[3]; comps[0] = r; comps[1] = g; comps[2] = b; + int splitComp = comps[pPal->treeSplitElt[treeRoot]]; + + int splitPos = pPal->treeSplit[treeRoot]; + if(splitPos > splitComp) + { + // check the left subtree + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2); + if( *bestDiff > splitPos - splitComp ) + { + // cannot prove there's not a better value in the right subtree, check that too + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1); + } + } + else + { + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2+1); + if( *bestDiff > splitComp - splitPos ) + { + GifGetClosestPaletteColor(pPal, r, g, b, bestInd, bestDiff, treeRoot*2); + } + } +} + +void GifSwapPixels(uint8_t* image, int pixA, int pixB) +{ + uint8_t rA = image[pixA*4]; + uint8_t gA = image[pixA*4+1]; + uint8_t bA = image[pixA*4+2]; + uint8_t aA = image[pixA*4+3]; + + uint8_t rB = image[pixB*4]; + uint8_t gB = image[pixB*4+1]; + uint8_t bB = image[pixB*4+2]; + uint8_t aB = image[pixA*4+3]; + + image[pixA*4] = rB; + image[pixA*4+1] = gB; + image[pixA*4+2] = bB; + image[pixA*4+3] = aB; + + image[pixB*4] = rA; + image[pixB*4+1] = gA; + image[pixB*4+2] = bA; + image[pixB*4+3] = aA; +} + +// just the partition operation from quicksort +int GifPartition(uint8_t* image, const int left, const int right, const int elt, int pivotValue) +{ + int storeIndex = left; + bool split = 0; + for(int ii=left; ii neededCenter) + GifPartitionByMedian(image, left, pivotIndex, com, neededCenter); + + if(pivotIndex < neededCenter) + GifPartitionByMedian(image, pivotIndex+1, right, com, neededCenter); + } +} + +// Just partition around a given pivot, returning the split point +int GifPartitionByMean(uint8_t* image, int left, int right, int com, int neededMean) +{ + if(left < right-1) + { + return GifPartition(image, left, right-1, com, neededMean); + } + return left; +} + +// Builds a palette by creating a balanced k-d tree of all pixels in the image +void GifSplitPalette(uint8_t* image, int numPixels, int treeNode, int treeLevel, bool buildForDither, GifPalette* pal) +{ + if(numPixels == 0) + return; + + int numColors = (1 << pal->bitDepth); + + // base case, bottom of the tree + if(treeNode >= numColors) + { + int entry = treeNode - numColors; + + if(buildForDither) + { + // Dithering needs at least one color as dark as anything + // in the image and at least one brightest color - + // otherwise it builds up error and produces strange artifacts + if( entry == 1 ) + { + // special case: the darkest color in the image + uint32_t r=255, g=255, b=255; + for(int ii=0; iir[entry] = (uint8_t)r; + pal->g[entry] = (uint8_t)g; + pal->b[entry] = (uint8_t)b; + + return; + } + + if( entry == numColors-1 ) + { + // special case: the lightest color in the image + uint32_t r=0, g=0, b=0; + for(int ii=0; iir[entry] = (uint8_t)r; + pal->g[entry] = (uint8_t)g; + pal->b[entry] = (uint8_t)b; + + return; + } + } + + // otherwise, take the average of all colors in this subcube + uint64_t r=0, g=0, b=0; + for(int ii=0; iir[entry] = (uint8_t)r; + pal->g[entry] = (uint8_t)g; + pal->b[entry] = (uint8_t)b; + + return; + } + + // Find the axis with the largest range + int minR = 255, maxR = 0; + int minG = 255, maxG = 0; + int minB = 255, maxB = 0; + for(int ii=0; ii maxR) maxR = r; + if(r < minR) minR = r; + + if(g > maxG) maxG = g; + if(g < minG) minG = g; + + if(b > maxB) maxB = b; + if(b < minB) minB = b; + } + + int rRange = maxR - minR; + int gRange = maxG - minG; + int bRange = maxB - minB; + + // and split along that axis. (incidentally, this means this isn't a "proper" k-d tree but I don't know what else to call it) + int splitCom = 1; int rangeMin = minG; int rangeMax = maxG; + if(bRange > gRange) { splitCom = 2; rangeMin = minB; rangeMax = maxB; } + if(rRange > bRange && rRange > gRange) { splitCom = 0; rangeMin = minR; rangeMax = maxR; } + + int subPixelsA = numPixels / 2; + + GifPartitionByMedian(image, 0, numPixels, splitCom, subPixelsA); + int splitValue = image[subPixelsA*4+splitCom]; + + // if the split is very unbalanced, split at the mean instead of the median to preserve rare colors + int splitUnbalance = GifIAbs( (splitValue - rangeMin) - (rangeMax - splitValue) ); + if( splitUnbalance > (1536 >> treeLevel) ) + { + splitValue = rangeMin + (rangeMax-rangeMin) / 2; + subPixelsA = GifPartitionByMean(image, 0, numPixels, splitCom, splitValue); + } + + // add the bottom node for the transparency index + if( treeNode == numColors/2 ) + { + subPixelsA = 0; + splitValue = 0; + } + + int subPixelsB = numPixels-subPixelsA; + pal->treeSplitElt[treeNode] = (uint8_t)splitCom; + pal->treeSplit[treeNode] = (uint8_t)splitValue; + + GifSplitPalette(image, subPixelsA, treeNode*2, treeLevel+1, buildForDither, pal); + GifSplitPalette(image+subPixelsA*4, subPixelsB, treeNode*2+1, treeLevel+1, buildForDither, pal); +} + +// Finds all pixels that have changed from the previous image and +// moves them to the fromt of th buffer. +// This allows us to build a palette optimized for the colors of the +// changed pixels only. +int GifPickChangedPixels( const uint8_t* lastFrame, uint8_t* frame, int numPixels ) +{ + int numChanged = 0; + uint8_t* writeIter = frame; + + for (int ii=0; iibitDepth = bitDepth; + + // SplitPalette is destructive (it sorts the pixels by color) so + // we must create a copy of the image for it to destroy + size_t imageSize = (size_t)(width * height * 4 * sizeof(uint8_t)); + uint8_t* destroyableImage = (uint8_t*)GIF_TEMP_MALLOC(imageSize); + memcpy(destroyableImage, nextFrame, imageSize); + + int numPixels = (int)(width * height); + if(lastFrame) + numPixels = GifPickChangedPixels(lastFrame, destroyableImage, numPixels); + + GifSplitPalette(destroyableImage, numPixels, 1, 0, buildForDither, pPal); + + GIF_TEMP_FREE(destroyableImage); + + // add the bottom node for the transparency index + pPal->treeSplit[1 << (bitDepth-1)] = 0; + pPal->treeSplitElt[1 << (bitDepth-1)] = 0; + + pPal->r[0] = pPal->g[0] = pPal->b[0] = 0; +} + +// Implements Floyd-Steinberg dithering, writes palette value to alpha +void GifDitherImage( const uint8_t* lastFrame, const uint8_t* nextFrame, uint8_t* outFrame, uint32_t width, uint32_t height, GifPalette* pPal ) +{ + int numPixels = (int)(width * height); + + // quantPixels initially holds color*256 for all pixels + // The extra 8 bits of precision allow for sub-single-color error values + // to be propagated + int32_t *quantPixels = (int32_t *)GIF_TEMP_MALLOC(sizeof(int32_t) * (size_t)numPixels * 4); + + for( int ii=0; iir[bestInd]) * 256; + int32_t g_err = nextPix[1] - (int32_t)(pPal->g[bestInd]) * 256; + int32_t b_err = nextPix[2] - (int32_t)(pPal->b[bestInd]) * 256; + + nextPix[0] = pPal->r[bestInd]; + nextPix[1] = pPal->g[bestInd]; + nextPix[2] = pPal->b[bestInd]; + nextPix[3] = bestInd; + + // Propagate the error to the four adjacent locations + // that we haven't touched yet + int quantloc_7 = (int)(yy * width + xx + 1); + int quantloc_3 = (int)(yy * width + width + xx - 1); + int quantloc_5 = (int)(yy * width + width + xx); + int quantloc_1 = (int)(yy * width + width + xx + 1); + + if(quantloc_7 < numPixels) + { + int32_t* pix7 = quantPixels+4*quantloc_7; + pix7[0] += GifIMax( -pix7[0], r_err * 7 / 16 ); + pix7[1] += GifIMax( -pix7[1], g_err * 7 / 16 ); + pix7[2] += GifIMax( -pix7[2], b_err * 7 / 16 ); + } + + if(quantloc_3 < numPixels) + { + int32_t* pix3 = quantPixels+4*quantloc_3; + pix3[0] += GifIMax( -pix3[0], r_err * 3 / 16 ); + pix3[1] += GifIMax( -pix3[1], g_err * 3 / 16 ); + pix3[2] += GifIMax( -pix3[2], b_err * 3 / 16 ); + } + + if(quantloc_5 < numPixels) + { + int32_t* pix5 = quantPixels+4*quantloc_5; + pix5[0] += GifIMax( -pix5[0], r_err * 5 / 16 ); + pix5[1] += GifIMax( -pix5[1], g_err * 5 / 16 ); + pix5[2] += GifIMax( -pix5[2], b_err * 5 / 16 ); + } + + if(quantloc_1 < numPixels) + { + int32_t* pix1 = quantPixels+4*quantloc_1; + pix1[0] += GifIMax( -pix1[0], r_err / 16 ); + pix1[1] += GifIMax( -pix1[1], g_err / 16 ); + pix1[2] += GifIMax( -pix1[2], b_err / 16 ); + } + } + } + + // Copy the palettized result to the output buffer + for( int ii=0; iir[bestInd]; + outFrame[1] = pPal->g[bestInd]; + outFrame[2] = pPal->b[bestInd]; + outFrame[3] = (uint8_t)bestInd; + } + + if(lastFrame) lastFrame += 4; + outFrame += 4; + nextFrame += 4; + } +} + +// Simple structure to write out the LZW-compressed portion of the image +// one bit at a time +typedef struct +{ + uint32_t chunkIndex; + uint8_t chunk[256]; // bytes are written in here until we have 256 of them, then written to the file + + uint8_t bitIndex; // how many bits in the partial byte written so far + uint8_t byte; // current partial byte + + uint8_t padding[2]; // make padding explicit +} GifBitStatus; + +// insert a single bit +void GifWriteBit( GifBitStatus* stat, uint32_t bit ) +{ + bit = bit & 1; + bit = bit << stat->bitIndex; + stat->byte |= bit; + + ++stat->bitIndex; + if( stat->bitIndex > 7 ) + { + // move the newly-finished byte to the chunk buffer + stat->chunk[stat->chunkIndex++] = stat->byte; + // and start a new byte + stat->bitIndex = 0; + stat->byte = 0; + } +} + +// write all bytes so far to the file +void GifWriteChunk( struct lwan_strbuf* f, GifBitStatus* stat ) +{ + lwan_strbuf_append_char(f, (int)stat->chunkIndex); + lwan_strbuf_append_str(f, stat->chunk, stat->chunkIndex); + + stat->bitIndex = 0; + stat->byte = 0; + stat->chunkIndex = 0; +} + +void GifWriteCode( struct lwan_strbuf* f, GifBitStatus* stat, uint32_t code, uint32_t length ) +{ + for( uint32_t ii=0; ii> 1; + + if( stat->chunkIndex == 255 ) + { + GifWriteChunk(f, stat); + } + } +} + +// The LZW dictionary is a 256-ary tree constructed as the file is encoded, +// this is one node +typedef struct +{ + uint16_t m_next[256]; +} GifLzwNode; + +// write a 256-color (8-bit) image palette to the file +void GifWritePalette( const GifPalette* pPal, struct lwan_strbuf* f ) +{ + lwan_strbuf_append_char(f, 0); // first color: transparency + lwan_strbuf_append_char(f, 0); + lwan_strbuf_append_char(f, 0); + + for(int ii=1; ii<(1 << pPal->bitDepth); ++ii) + { + uint32_t r = pPal->r[ii]; + uint32_t g = pPal->g[ii]; + uint32_t b = pPal->b[ii]; + + lwan_strbuf_append_char(f, r); + lwan_strbuf_append_char(f, g); + lwan_strbuf_append_char(f, b); + } +} + +// write the image header, LZW-compress and write out the image +void GifWriteLzwImage(struct lwan_strbuf* f, uint8_t* image, uint32_t left, uint32_t top, uint32_t width, uint32_t height, uint32_t delay, GifPalette* pPal) +{ + // graphics control extension + lwan_strbuf_append_char(f, 0x21); + lwan_strbuf_append_char(f, 0xf9); + lwan_strbuf_append_char(f, 0x04); + lwan_strbuf_append_char(f, 0x05); // leave prev frame in place, this frame has transparency + lwan_strbuf_append_char(f, (delay & 0xff)); + lwan_strbuf_append_char(f, ((delay>>8) & 0xff)); + lwan_strbuf_append_char(f, kGifTransIndex); // transparent color index + lwan_strbuf_append_char(f, 0); + + lwan_strbuf_append_char(f, 0x2c); // image descriptor block + + lwan_strbuf_append_char(f, left & 0xff); // corner of image in canvas space + lwan_strbuf_append_char(f, (left >> 8) & 0xff); + lwan_strbuf_append_char(f, top & 0xff); + lwan_strbuf_append_char(f, (top >> 8) & 0xff); + + lwan_strbuf_append_char(f, width & 0xff); // width and height of image + lwan_strbuf_append_char(f, (width >> 8) & 0xff); + lwan_strbuf_append_char(f, height & 0xff); + lwan_strbuf_append_char(f, (height >> 8) & 0xff); + + //lwan_strbuf_append_char(f, 0); // no local color table, no transparency + //lwan_strbuf_append_char(f, 0x80); // no local color table, but transparency + + lwan_strbuf_append_char(f, 0x80 + pPal->bitDepth-1); // local color table present, 2 ^ bitDepth entries + GifWritePalette(pPal, f); + + const int minCodeSize = pPal->bitDepth; + const uint32_t clearCode = 1 << pPal->bitDepth; + + lwan_strbuf_append_char(f, minCodeSize); // min code size 8 bits + + GifLzwNode* codetree = (GifLzwNode*)GIF_TEMP_MALLOC(sizeof(GifLzwNode)*4096); + + memset(codetree, 0, sizeof(GifLzwNode)*4096); + int32_t curCode = -1; + uint32_t codeSize = (uint32_t)minCodeSize + 1; + uint32_t maxCode = clearCode+1; + + GifBitStatus stat; + stat.byte = 0; + stat.bitIndex = 0; + stat.chunkIndex = 0; + + GifWriteCode(f, &stat, clearCode, codeSize); // start with a fresh LZW dictionary + + for(uint32_t yy=0; yy= (1ul << codeSize) ) + { + // dictionary entry count has broken a size barrier, + // we need more bits for codes + codeSize++; + } + if( maxCode == 4095 ) + { + // the dictionary is full, clear it out and begin anew + GifWriteCode(f, &stat, clearCode, codeSize); // clear tree + + memset(codetree, 0, sizeof(GifLzwNode)*4096); + codeSize = (uint32_t)(minCodeSize + 1); + maxCode = clearCode+1; + } + + curCode = nextValue; + } + } + } + + // compression footer + GifWriteCode(f, &stat, (uint32_t)curCode, codeSize); + GifWriteCode(f, &stat, clearCode, codeSize); + GifWriteCode(f, &stat, clearCode + 1, (uint32_t)minCodeSize + 1); + + // write out the last partial chunk + while( stat.bitIndex ) GifWriteBit(&stat, 0); + if( stat.chunkIndex ) GifWriteChunk(f, &stat); + + lwan_strbuf_append_char(f, 0); // image block terminator + + GIF_TEMP_FREE(codetree); +} + +typedef struct +{ + struct lwan_strbuf* f; + uint8_t* oldImage; + bool firstFrame; + + uint8_t padding[7]; // make padding explicit +} GifWriter; + +// Creates a gif file. +// The input GIFWriter is assumed to be uninitialized. +// The delay value is the time between frames in hundredths of a second - note that not all viewers pay much attention to this value. +bool GifBegin( GifWriter* writer, struct lwan_strbuf *f, uint32_t width, uint32_t height, uint32_t delay, int32_t bitDepth, bool dither ) +{ + (void)bitDepth; (void)dither; // Mute "Unused argument" warnings + + if(!f) return false; + + writer->f = f; + writer->firstFrame = true; + + // allocate + writer->oldImage = (uint8_t*)GIF_MALLOC(width*height*4); + + lwan_strbuf_append_strz(writer->f, "GIF89a"); + + // screen descriptor + lwan_strbuf_append_char(writer->f, width & 0xff); + lwan_strbuf_append_char(writer->f, (width >> 8) & 0xff); + lwan_strbuf_append_char(writer->f, height & 0xff); + lwan_strbuf_append_char(writer->f, (height >> 8) & 0xff); + + lwan_strbuf_append_char(writer->f, 0xf0); // there is an unsorted global color table of 2 entries + lwan_strbuf_append_char(writer->f, 0); // background color + lwan_strbuf_append_char(writer->f, 0); // pixels are square (we need to specify this because it's 1989) + + // now the "global" palette (really just a dummy palette) + // color 0: black + lwan_strbuf_append_char(writer->f, 0); + lwan_strbuf_append_char(writer->f, 0); + lwan_strbuf_append_char(writer->f, 0); + // color 1: also black + lwan_strbuf_append_char(writer->f, 0); + lwan_strbuf_append_char(writer->f, 0); + lwan_strbuf_append_char(writer->f, 0); + + if( delay != 0 ) + { + // animation header + lwan_strbuf_append_char(writer->f, 0x21); // extension + lwan_strbuf_append_char(writer->f, 0xff); // application specific + lwan_strbuf_append_char(writer->f, 11); // length 11 + lwan_strbuf_append_strz(writer->f, "NETSCAPE2.0"); // yes, really + lwan_strbuf_append_char(writer->f, 3); // 3 bytes of NETSCAPE2.0 data + + lwan_strbuf_append_char(writer->f, 1); // this is the Netscape 2.0 sub-block ID and it must be 1, otherwise some viewers error + lwan_strbuf_append_char(writer->f, 0); // loop infinitely (byte 0) + lwan_strbuf_append_char(writer->f, 0); // loop infinitely (byte 1) + + lwan_strbuf_append_char(writer->f, 0); // block terminator + } + + return true; +} + +// Writes out a new frame to a GIF in progress. +// The GIFWriter should have been created by GIFBegin. +// AFAIK, it is legal to use different bit depths for different frames of an image - +// this may be handy to save bits in animations that don't change much. +bool GifWriteFrame( GifWriter* writer, const uint8_t* image, uint32_t width, uint32_t height, uint32_t delay, int bitDepth, bool dither) +{ + if(!writer->f) return false; + + const uint8_t* oldImage = writer->firstFrame? NULL : writer->oldImage; + writer->firstFrame = false; + + GifPalette pal; + GifMakePalette((dither? NULL : oldImage), image, width, height, bitDepth, dither, &pal); + + if(dither) + GifDitherImage(oldImage, image, writer->oldImage, width, height, &pal); + else + GifThresholdImage(oldImage, image, writer->oldImage, width, height, &pal); + + GifWriteLzwImage(writer->f, writer->oldImage, 0, 0, width, height, delay, &pal); + + return true; +} + +// Writes the EOF code, closes the file handle, and frees temp memory used by a GIF. +// Many if not most viewers will still display a GIF properly if the EOF code is missing, +// but it's still a good idea to write it out. +bool GifEnd( GifWriter* writer ) +{ + if(!writer->f) return false; + + lwan_strbuf_append_char(writer->f, 0x3b); // end of file + GIF_FREE(writer->oldImage); + + writer->f = NULL; + writer->oldImage = NULL; + + return true; +} + +#endif diff --git a/src/samples/forthsalon/main.c b/src/samples/forthsalon/main.c index 7a1117cad..ce0c571c5 100644 --- a/src/samples/forthsalon/main.c +++ b/src/samples/forthsalon/main.c @@ -17,14 +17,87 @@ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ +#include + #include "lwan.h" +#include "forth.h" +#include "gif.h" + +/* Twister by boomlinde + * https://forthsalon.appspot.com/haiku-view/ag5mb3J0aHNhbG9uLWhyZHISCxIFSGFpa3UYgICAvJXxgwsM + */ +static const char twister[] = ": t' t pi * 2 / ;\n" +": l * + sin ;\n" +": r t' 1 y t' + 4 l + 1.57 ;\n" +": x' x 4 * 2 - t' y 3 l + ;\n" +": v 2dup x' >= swap x' < * -rot swap - l ;\n" +": a r 4 l ; : b r 1 l ;\n" +": c r 2 l ; : d r 3 l ;\n" +"0 d a v a b v b c v c d v 0.1 0.2"; + +static void destroy_forth_ctx(void *p) { forth_free(p); } +static void destroy_gif_writer(void *p) { GifEnd(p); } -LWAN_HANDLER_ROUTE(hello_world, "/") +LWAN_HANDLER_ROUTE(twister, "/") { - static const char message[] = "Hello, World!"; + struct forth_ctx *f = forth_new(); + double current_time = (int32_t)time(NULL); + + coro_defer(request->conn->coro, destroy_forth_ctx, f); + + if (!forth_parse_string(f, twister)) + return HTTP_INTERNAL_ERROR; + + uint8_t *frame_buffer = coro_malloc(request->conn->coro, 64 * 64 * 4); + if (!frame_buffer) + return HTTP_INTERNAL_ERROR; + + response->mime_type = "image/gif"; + + if (!lwan_response_set_chunked(request, HTTP_OK)) + return HTTP_INTERNAL_ERROR; + + GifWriter writer = {}; + coro_defer(request->conn->coro, destroy_gif_writer, &writer); + + GifBegin(&writer, response->buffer, 64, 64, 2, 8, true); + + for (int frame = 0; frame < 1000; frame++) { + for (int x = 0; x < 64; x++) { + for (int y = 0; y < 64; y++) { + uint8_t *pixel = &frame_buffer[4 * (y * 64 + x)]; + + struct forth_vars vars = { + .x = x / 64., + .y = y / 64., + .t = current_time, + }; + if (!forth_run(f, &vars)) + return HTTP_INTERNAL_ERROR; + switch (forth_d_stack_len(f)) { + case 3: + pixel[3] = 0; + pixel[2] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + pixel[1] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + pixel[0] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + break; + case 4: + pixel[3] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + pixel[2] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + pixel[1] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + pixel[0] = (uint8_t)(round(forth_d_stack_pop(f) * 255.)); + break; + default: + return HTTP_INTERNAL_ERROR; + } + } + } - response->mime_type = "text/plain"; - lwan_strbuf_set_static(response->buffer, message, sizeof(message) - 1); + GifWriteFrame(&writer, frame_buffer, 64, 64, 2, 8, true); + lwan_response_send_chunk(request); + lwan_request_sleep(request, 16); + current_time += .016; + } return HTTP_OK; }