"""Independent native decoding of original RGB samples, matrix tags, timing and alpha."""
from pathlib import Path
import argparse,datetime,hashlib,json,math,re,subprocess,sys
import numpy as np
from PIL import Image

ap=argparse.ArgumentParser();ap.add_argument('downloads',type=Path);ap.add_argument('out',type=Path);ap.add_argument('--browsers',nargs='*',default=[]);ap.add_argument('--targets',nargs='+',default=['mp4','webm','mov','mkv']);args=ap.parse_args();args.out.mkdir(exist_ok=False)
fixtures=Path('benchmarks/fixtures/video-rgb1');rawManifest=(fixtures/'manifest.json').read_bytes();manifest=json.loads(rawManifest);sha=lambda b:hashlib.sha256(b).hexdigest();checks=[];rows=[];missing=[]
def check(file,name,passed,**details):checks.append(dict(file=file,check=name,passed=bool(passed),**details))
def run(argv):return subprocess.check_output(argv,stderr=subprocess.PIPE)
def inspect(file):
 return json.loads(run(['ffprobe','-v','error','-show_streams','-show_format','-show_frames','-show_entries','frame=best_effort_timestamp_time,duration_time','-of','json',str(file)]))
def decode(file,pixel,decoder=None):return run(['ffmpeg','-v','error','-xerror',*(['-c:v',decoder]if decoder else[]),'-i',str(file),'-map','0:v:0','-fps_mode','passthrough','-pix_fmt',pixel,'-f','rawvideo','-'])
for item in manifest['rows']:
 name=item['name'];source=fixtures/item['file'];sourceBytes=source.read_bytes();assert sha(sourceBytes)==item['sha256'];sourceProbe=inspect(source);stream=next(s for s in sourceProbe['streams']if s['codec_type']=='video');w,h=stream['width'],stream['height'];sourceTimes=[float(f['best_effort_timestamp_time'])for f in sourceProbe['frames']]
 if item.get('originalCorpus')is False:
  rgba=np.frombuffer(decode(source,'rgba'),'uint8').reshape(-1,h,w,4).astype('float64')/255
 else:
  data=(fixtures/item['raw']).read_bytes();assert sha(data)==item['rawSha256'];count=4 if item['alpha']else 3
  planes=np.frombuffer(data,'<u2').reshape(item['frames'],count,h,w);rgb=planes[:,[2,0,1]].transpose(0,2,3,1)/((1<<item['bits'])-1)
  a=planes[:,3,:,:,None]/((1<<item['bits'])-1)if item['alpha']else np.ones((*rgb.shape[:3],1));rgba=np.concatenate([rgb,a],axis=3)
 reference=rgba[:,:,:,:3]*rgba[:,:,:,3:]+1-rgba[:,:,:,3:];sourcePng=args.out/(name+'-source-first.png');Image.fromarray(np.rint(reference[0]*255).astype('uint8')).save(sourcePng)
 for browser in args.browsers or['']:
  for target in args.targets:
   file=args.downloads/((browser+'-'if browser else'')+name+'.'+target)
   if not file.exists():missing.append(str(file));check(str(file),'complete expected download',False);continue
   pin=dict(path=str(file),bytes=file.stat().st_size,sha256=sha(file.read_bytes()));info=inspect(file);video=next(s for s in info['streams']if s['codec_type']=='video');times=[float(f['best_effort_timestamp_time'])for f in info['frames']]
   check(file.name,'native dimensions',video['width']==w and video['height']==h,actual=[video['width'],video['height']],expected=[w,h])
   check(file.name,'native frame count',len(times)==len(sourceTimes),actual=len(times),expected=len(sourceTimes));check(file.name,'native picture timing',len(times)==len(sourceTimes)and np.allclose(times,sourceTimes,atol=.000001,rtol=0),actual=times,expected=sourceTimes)
   check(file.name,'no spurious audio',not any(s['codec_type']=='audio'for s in info['streams']))
   expectedMatrix='gbr'if target=='mkv'else'bt709';expectedRange='pc'if target=='mkv'else'tv'
   for prop,wanted in [('color_space',expectedMatrix),('color_range',expectedRange),('color_primaries','bt709'),('color_transfer','iec61966-2-1')]:
    # MOV nclc carries primaries/transfer/matrix, not a full-range flag. Verify
    # ProRes nominal-range sample codes instead of inventing a missing tag.
    if prop=='color_range'and target=='mov'and video['codec_name']=='prores'and video.get(prop)is None:
     yuv=np.frombuffer(decode(file,'yuv444p12le'),'<u2').reshape(-1,3,h,w);black=float(np.median(yuv[:,0,8:26,4:w//8-4]));white=float(np.median(yuv[:,0,8:26,w//8+4:2*(w//8)-4]))
     check(file.name,'ProRes nominal limited-range black/white codes',abs(black-256)<=32 and abs(white-3760)<=32,black=black,white=white,expectedBlack=256,expectedWhite=3760,tolerance=32,rangeTag=None)
    else:check(file.name,'declared '+prop,video.get(prop)==wanted,actual=video.get(prop),expected=wanted)
   decoder='libvpx-vp9'if target=='webm'and video.get('tags',{}).get('alpha_mode')=='1'else None
   # Read visible metrics at explicit8-bit display precision. FFmpeg's8→16
   # alpha expansion can use a left shift rather than scaling255→65535; dividing
   # that intermediate by65535 invents opacity loss. Full-depth archival samples
   # are independently checked below without any expansion or quantization.
   decoded=decode(file,'rgba',decoder);actual=np.frombuffer(decoded,'uint8').reshape(-1,h,w,4).astype('float64')/255
   check(file.name,'independent full decoded dimensions',actual.shape==rgba.shape,actual=list(actual.shape),expected=list(rgba.shape))
   if actual.shape!=rgba.shape:continue
   preserve=item.get('alpha',False)and target in ['webm','mov','mkv'];wantAlpha=rgba[:,:,:,3]if preserve else np.ones(rgba.shape[:3]);displayAlphaError=float(np.max(np.abs(actual[:,:,:,3]-wantAlpha)))
   alphaDepth=8
   if preserve:
    match=re.search(r'(\d+)(?:le|be)$',video['pix_fmt']);alphaDepth=int(match[1])if match else 8;gray='gray'if alphaDepth==8 else f'gray{alphaDepth}le'
    # Extract the native alpha plane before any RGBA display expansion/truncation.
    alphaBytes=run(['ffmpeg','-v','error','-xerror',*(['-c:v',decoder]if decoder else[]),'-i',str(file),'-map','0:v:0','-vf','alphaextract','-fps_mode','passthrough','-pix_fmt',gray,'-f','rawvideo','-'])
    alphaSamples=np.frombuffer(alphaBytes,'uint8'if alphaDepth==8 else'<u2').reshape(rgba.shape[:3])/((1<<alphaDepth)-1)
   else:alphaSamples=actual[:,:,:,3]
   alphaError=float(np.max(np.abs(alphaSamples-wantAlpha)));alphaLimit=0 if preserve and target=='mkv'else 1/((1<<min(alphaDepth,item.get('bits',8)))-1)+.0001
   check(file.name,'native source alpha or explicit white composite',alphaError<=alphaLimit,maximumAlphaError=alphaError,limit=alphaLimit,preserved=preserve,nativeAlphaDepth=alphaDepth,nativeRgba8DisplayAlphaDifference=displayAlphaError)
   visible=actual[:,:,:,:3]*alphaSamples[:,:,:,None]+1-alphaSamples[:,:,:,None];rmse=float(np.sqrt(np.mean((visible-reference)**2)));psnr=-20*math.log10(rmse)if rmse else None
   patches=[]
   for i in range(8):
    x=i*w//8;end=x+w//8;delta=visible[:,8:26,x+4:end-4]-reference[:,8:26,x+4:end-4];patches.append(float(np.sqrt(np.mean(delta**2))))
   check(file.name,'interior source-color patch fidelity',max(patches)<.025,patchRmse=patches,limit=.025)
   if target=='mkv':
    pixel=item.get('pixelFormat','bgr0');native=decode(file,pixel);original=(fixtures/item['raw']).read_bytes()if'raw'in item else decode(source,pixel)
    check(file.name,'archival exact original decoded samples',native==original,pixelFormat=pixel,decodedSha256=sha(native),sourceSampleSha256=sha(original))
   png=args.out/(file.name+'-first.png');Image.fromarray(np.rint(np.clip(visible[0],0,1)*255).astype('uint8')).save(png)
   rows.append(dict(**pin,source=dict(path=str(source),sha256=sha(sourceBytes)),nativeProperties=info,decoder=decoder or'FFmpeg native default decoder',decodedRgba8Sha256=sha(decoded),rgbRMSE=rmse,rgbPSNR=psnr,interiorPatchRMSE=patches,alphaMaxError=alphaError,nativeAlphaDepth=alphaDepth,nativeRgba8DisplayAlphaDifference=displayAlphaError,firstFramePng=dict(path=png.name,sha256=sha(png.read_bytes()))))
report=dict(checkedAt=datetime.datetime.now(datetime.timezone.utc).isoformat(),producerSha256=sha(Path(__file__).read_bytes()),fixtureManifestSha256=sha(rawManifest),completeScope=not missing,expectedDownloads=4*len(args.targets)*(len(args.browsers)or 1),missing=missing,rows=rows,checks=checks,failures=[c for c in checks if not c['passed']],nativeVersion=run(['ffmpeg','-version']).decode().splitlines()[0],method='Original planar channel arrays are authoritative. Native FFmpeg independently decodes all pictures at explicitRGBA8 display precision without gain, alignment or resampling; native metadata/timestamps, interior patches, visible RGB on white, alpha and exact full-depth FFV1 archival samples are separate controls. MOV ProRes range uses nominal decoded luma codes because nclc does not carry a range flag. Native RGB interpolation and codec/chroma loss remain in full-image metrics, not normalized away. No claim of lossless high-depth display quantization.',competitiveQuality='UNVERIFIED for these inputs; no same-file CloudConvert output. The retained motion reference is a separate original fixture and must not be relabeled as one of these corpora.')
(args.out/'report.json').write_text(json.dumps(report,indent=2)+'\n');print(dict(files=len(rows),expected=report['expectedDownloads'],checks=len(checks),failures=len(report['failures']),missing=len(missing)));sys.exit(1 if report['failures']else 0)
