aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


tools/client/png_benchmark/worker.js (5958B)


      1 importScripts('decoder.js');
      2 
      3 async function run() {
      4   postMessage({status: 'Loading the decoder and 180 PNGs. Downloads are not timed.'});
      5   const module = await createPNG();
      6   const response = await fetch('corpus.json');
      7   if (!response.ok) throw Error(`Corpus download failed: ${response.status}`);
      8   const corpus = await response.json();
      9   const bytes = text => Uint8Array.from(atob(text), char => char.charCodeAt(0));
     10   const images = corpus.map(image => {
     11     const input = bytes(image.input);
     12     const pointer = module._malloc(input.length);
     13     module.HEAPU8.set(input, pointer);
     14     return {pointer, size: input.length, width: image.width, height: image.height,
     15       channels: image.bits / 8, expected: bytes(image.pixels)};
     16   });
     17   const groups = {RGB: images.filter(image => image.channels === 3),
     18     RGBA: images.filter(image => image.channels === 4)};
     19   const result = {date: new Date().toISOString(), userAgent: navigator.userAgent,
     20     hardwareConcurrency: navigator.hardwareConcurrency, images: images.length,
     21     method: 'One validation/warm-up pass, five measured passes, rotating decoder order. Inputs already in WASM; outputs packed BGR/BGRA in WASM. Downloads, validation, game stream calls and GPU upload excluded.',
     22     decoders: {}};
     23   const modes = ['wasm'];
     24   let canvas, context;
     25   if (typeof createImageBitmap === 'function' && typeof OffscreenCanvas !== 'undefined') {
     26     canvas = new OffscreenCanvas(1, 1);
     27     context = canvas.getContext('2d', {willReadFrequently: true});
     28     if (context) modes.push('bitmap');
     29   }
     30   if (!modes.includes('bitmap')) result.decoders.bitmap = {unsupported: true};
     31   if (typeof ImageDecoder !== 'undefined' && await ImageDecoder.isTypeSupported('image/png'))
     32     modes.push('imageDecoder');
     33   else result.decoders.imageDecoder = {unsupported: true};
     34 
     35   // Return equivalent guest-format pixels in WASM, including native readback costs.
     36   async function decode(mode, image) {
     37     if (mode === 'wasm') {
     38       const decoded = module._decode(image.pointer, image.size);
     39       if (!decoded) throw Error('libpng decode failed');
     40       const values = module.HEAPU32.subarray(decoded >>> 2, (decoded >>> 2) + 4);
     41       if (values[0] !== image.width || values[1] !== image.height || values[2] !== image.channels * 8)
     42         throw Error('libpng dimensions or format differ');
     43       return values[3];
     44     }
     45     const data = module.HEAPU8.slice(image.pointer, image.pointer + image.size);
     46     const output = module._malloc(image.width * image.height * 4);
     47     if (mode === 'bitmap') {
     48       const bitmap = await createImageBitmap(new Blob([data], {type: 'image/png'}),
     49         {premultiplyAlpha: 'none', colorSpaceConversion: 'none'});
     50       canvas.width = bitmap.width;
     51       canvas.height = bitmap.height;
     52       context.drawImage(bitmap, 0, 0);
     53       module.HEAPU8.set(context.getImageData(0, 0, bitmap.width, bitmap.height).data, output);
     54       bitmap.close();
     55     } else {
     56       const decoder = new ImageDecoder({data, type: 'image/png',
     57         colorSpaceConversion: 'none', premultiplyAlpha: 'none'});
     58       const {image: frame} = await decoder.decode();
     59       try {
     60         await frame.copyTo(module.HEAPU8.subarray(output, output + image.width * image.height * 4), {format: 'RGBA'});
     61       } finally {
     62         frame.close();
     63         decoder.close();
     64       }
     65     }
     66     module._pack_pixels(output, image.width * image.height, image.channels);
     67     return output;
     68   }
     69 
     70   // Validate once, outside measured passes, against the original guest decoder.
     71   for (const mode of modes) {
     72     postMessage({status: `Warming up and checking pixels: ${mode}`});
     73     result.decoders[mode] = {};
     74     try {
     75       for (const [group, members] of Object.entries(groups)) {
     76         const stats = {images: members.length, ms: [], mismatchedImages: 0,
     77           mismatchedBytes: 0, visiblePixelChanges: 0, maxDifference: 0};
     78         result.decoders[mode][group] = stats;
     79         for (const image of members) {
     80           const pointer = await decode(mode, image);
     81           let changed = false;
     82           for (let pixel = 0; pixel < image.width * image.height; ++pixel) {
     83             let pixelChanged = false;
     84             for (let channel = 0; channel < image.channels; ++channel) {
     85               const index = pixel * image.channels + channel;
     86               const difference = Math.abs(module.HEAPU8[pointer + index] - image.expected[index]);
     87               if (difference) {
     88                 changed = pixelChanged = true;
     89                 ++stats.mismatchedBytes;
     90                 stats.maxDifference = Math.max(stats.maxDifference, difference);
     91               }
     92             }
     93             if (pixelChanged && (image.channels === 3 || image.expected[pixel * 4 + 3] !== 0))
     94               ++stats.visiblePixelChanges;
     95           }
     96           if (changed) ++stats.mismatchedImages;
     97           module._free(pointer);
     98         }
     99       }
    100     } catch (error) {
    101       if (mode === 'wasm') throw error;
    102       result.decoders[mode] = {error: String(error)};
    103     }
    104   }
    105   if (result.decoders.wasm.RGB.mismatchedImages || result.decoders.wasm.RGBA.mismatchedImages)
    106     throw Error('WASM baseline differs from captured pixels; benchmark invalid');
    107 
    108   // Time whole batches, avoiding phone timer quantization on individual images.
    109   const supported = modes.filter(mode => !result.decoders[mode].error);
    110   for (let round = 0; round < 5; ++round) {
    111     const order = supported.slice(round % supported.length).concat(supported.slice(0, round % supported.length));
    112     for (const mode of order) {
    113       postMessage({status: `Measured round ${round + 1}/5: ${mode}`});
    114       for (const group of round % 2 ? ['RGBA', 'RGB'] : ['RGB', 'RGBA']) {
    115         const start = performance.now();
    116         for (const image of groups[group]) module._free(await decode(mode, image));
    117         result.decoders[mode][group].ms.push(performance.now() - start);
    118       }
    119     }
    120   }
    121   postMessage({result});
    122 }
    123 
    124 run().catch(error => postMessage({error: String(error)}));