Files
mars_nwe_pcab/browser/media.mjs

7 lines
1.9 KiB
JavaScript

import {spawn} from 'node:child_process';
import {rle565} from './protocol.mjs';
export function convert(jpeg,w,h,codec){if(codec==='jpeg')return Promise.resolve(jpeg);return new Promise((resolve,reject)=>{const p=spawn('/usr/bin/ffmpeg',['-hide_banner','-loglevel','error','-threads','1','-f','mjpeg','-i','pipe:0','-frames:v','1','-f','rawvideo','-pix_fmt','rgb565le','-threads','1','pipe:1'],{stdio:['pipe','pipe','ignore']});let chunks=[],n=0;const timer=setTimeout(()=>p.kill('SIGKILL'),5000);p.on('error',reject);p.stdin.on('error',()=>{});p.stdout.on('data',b=>{n+=b.length;if(n>w*h*2)p.kill('SIGKILL');else chunks.push(b);});p.on('close',code=>{clearTimeout(timer);if(code||n!==w*h*2)return reject(Error('FFmpeg frame'));const raw=Buffer.concat(chunks);if(codec==='rle565')return resolve(rle565(raw));raw.swap16();resolve(raw);});p.stdin.end(jpeg);});}
// Independent IMA blocks, predictor/index header per channel, low nibble first.
const steps=[7,8,9,10,11,12,13,14,16,17,19,21,23,25,28,31,34,37,41,45,50,55,60,66,73,80,88,97,107,118,130,143,157,173,190,209,230,253,279,307,337,371,408,449,494,544,598,658,724,796,876,963,1060,1166,1282,1411,1552,1707,1878,2066,2272,2499,2749,3024,3327,3660,4026,4428,4871,5358,5894,6484,7132,7845,8630,9493,10442,11487,12635,13899,15289,16818,18500,20350,22385,24623,27086,29794,32767];const adj=[-1,-1,-1,-1,2,4,6,8];
export function adpcm(pcm,ch){const frames=pcm.length/(2*ch);const out=Buffer.alloc(ch*4+Math.ceil((frames-1)*ch/2));let pred=[],idx=[],k=0;for(let c=0;c<ch;c++){pred[c]=pcm.readInt16LE(c*2);idx[c]=0;out.writeInt16BE(pred[c],c*4);}for(let i=1;i<frames;i++)for(let c=0;c<ch;c++){let d=pcm.readInt16LE((i*ch+c)*2)-pred[c],s=steps[idx[c]],v=s>>3,n=0;if(d<0){n=8;d=-d;}if(d>=s){n|=4;d-=s;v+=s;}if(d>=s>>1){n|=2;d-=s>>1;v+=s>>1;}if(d>=s>>2){n|=1;v+=s>>2;}pred[c]=Math.max(-32768,Math.min(32767,pred[c]+(n&8?-v:v)));idx[c]=Math.max(0,Math.min(88,idx[c]+adj[n&7]));out[ch*4+(k>>1)]|=n<<((k&1)*4);k++;}return out;}