{"record":{"id":"0bd2a7b3a32e86e4","repo":"d2phap/ImageGlass","slug":"encoding-error-error-code","errorCode":null,"errorMessage":"Encoding error: {error_code}","messagePattern":"Encoding error: (.+?)","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"v9/Components/ImageGlass.WebP/WebPWrapper.cs","lineNumber":933,"sourceCode":"                ptrStats = Marshal.AllocHGlobal(Marshal.SizeOf(stats));\n                Marshal.StructureToPtr(stats, ptrStats, false);\n                wpic.stats = ptrStats;\n            }\n\n            // Memory for WebP output\n            if (dataWebpSize > 2_147_483_591) dataWebpSize = 2_147_483_591;\n            dataWebp = new byte[bmp.Width * bmp.Height * 32];\n            pinnedArrayHandle = GCHandle.Alloc(dataWebp, GCHandleType.Pinned);\n            var initPtr = pinnedArrayHandle.AddrOfPinnedObject();\n            wpic.custom_ptr = initPtr;\n\n            // Set up a byte-writing method (write-to-memory, in this case)\n            LibWebp.OnCallback = new LibWebp.WebPMemoryWrite(MyWriter);\n            wpic.writer = Marshal.GetFunctionPointerForDelegate(LibWebp.OnCallback);\n\n            // compress the input samples\n            if (LibWebp.WebPEncode(ref config, ref wpic) != 1)\n                throw new Exception(\"Encoding error: \" + ((WebPEncodingError)wpic.error_code).ToString());\n\n            // Remove OnCallback\n            LibWebp.OnCallback = null;\n\n            // Unlock the pixels\n            bmp.UnlockBits(bmpData);\n            bmpData = null;\n\n            // Copy webpData to rawWebP\n            int size = (int)((long)wpic.custom_ptr - (long)initPtr);\n            rawWebP = new byte[size];\n            Array.Copy(dataWebp, rawWebP, size);\n\n            // Remove compression data\n            pinnedArrayHandle.Free();\n            dataWebp = null;\n\n            // Show statistics","sourceCodeStart":915,"sourceCodeEnd":951,"githubUrl":"https://github.com/d2phap/ImageGlass/blob/4a3c4feceffc5a8bb5e56ba836509634aaae47a9/v9/Components/ImageGlass.WebP/WebPWrapper.cs#L915-L951","documentation":"Thrown by AdvancedEncode when LibWebp.WebPEncode returns != 1. Unlike the simple encoder, this path surfaces the native error via wpic.error_code, cast to WebPEncodingError. The message appends the symbolic error name (e.g. VP8_ENC_ERROR_OUT_OF_MEMORY, VP8_ENC_ERROR_BITSTREAM_FINISHED), which is the key diagnostic for why encoding failed.","triggerScenarios":"Reaching the final LibWebp.WebPEncode call in AdvancedEncode with a config + picture that the native encoder rejects. Triggers include out-of-memory, picture too large, invalid configuration, aborted encoding, or a write-callback failure (the wrapper's MyWriter copies into a pinned managed buffer).","commonSituations":"The pinned output buffer (bmp.Width*Height*32 bytes) overflowing or being undersized; very large pictures exhausting memory; a corrupt/aborted encode; thread-level encoding on a build without threading; a custom writer returning 0.","solutions":["Read the appended WebPEncodingError name to find the root cause (out-of-memory vs. bitstream vs. configuration).","For out-of-memory: reduce dimensions or run 64-bit.","For bitstream/config errors: simplify config (use the simple API) or update libwebp.","Ensure the output buffer is large enough; the wrapper allocates Width*Height*32 which can overflow Int32 for huge images — downscale first."],"exampleFix":"// before\ntry { var bytes = webp.EncodeLossy(bmp, quality, speed, info: true); }\ncatch (Exception ex) { /* generic 'Encoding error: ...' */ }\n\n// after\ntry { var bytes = webp.EncodeLossy(bmp, quality, speed); }\ncatch (Exception ex) when (ex.Message.StartsWith(\"Encoding error:\"))\n{\n    var errName = ex.Message.Substring(\"Encoding error:\".Length).Trim();\n    if (errName.Contains(\"OUT_OF_MEMORY\")) { bmp = Downscale(bmp); /* retry */ }\n    else throw;\n}","handlingStrategy":"try-catch","validationCode":"// Reduce risk before encoding: clamp args and bound working set\nint s = Math.Clamp(speed, 0, 9); int q = Math.Clamp(quality, 0, 100);\nif ((long)bmp.Width * bmp.Height * 32 > int.MaxValue) bmp = DownscaleTo(bmp, 16383, 16383, bmp.PixelFormat);","typeGuard":null,"tryCatchPattern":"try { var bytes = webp.EncodeLossy(bmp, quality, speed); }\ncatch (Exception ex) when (ex.Message.StartsWith(\"Encoding error:\"))\n{\n    var err = ex.Message.Substring(\"Encoding error:\".Length).Trim();\n    if (err.Contains(\"OUT_OF_MEMORY\")) { bmp = DownscaleTo(bmp, bmp.Width / 2, bmp.Height / 2, bmp.PixelFormat); /* retry once */ }\n    else throw;\n}","preventionTips":["Parse the WebPEncodingError name from the message to drive the response.","For OUT_OF_MEMORY, downscale or run 64-bit before retrying once.","Ensure the output buffer math (Width*Height*32) cannot overflow Int32 for your largest inputs.","Use the simple encoder when you do not need the advanced config surface."],"tags":["webp","encoding","advanced-api","native-error","out-of-memory","error-code"],"backgroundTag":null,"analyzedSha":"4a3c4feceffc5a8bb5e56ba836509634aaae47a9","analyzedAt":"2026-08-13T16:58:15.523Z","schemaVersion":2},"datasetVersion":"2026-08-13T19:17:28.613Z"}