31 行
1.3 KiB
Objective-C
31 行
1.3 KiB
Objective-C
#pragma once
|
||
#import <Foundation/Foundation.h>
|
||
#include <cmath>
|
||
#include <cstdint>
|
||
|
||
// Immutable renderer-owned snapshot. Channel 0 uses Rec.709 weights after
|
||
// any signal encoding, as luma is weighted from R′G′B′.
|
||
struct DYHistogram {
|
||
uint32_t bins[4][256]{};
|
||
uint32_t samples=0;
|
||
uint32_t rec709VideoLevels=0;
|
||
};
|
||
static inline NSData *DYHistogramFromRGBA(NSData *rgba, bool premultiplied=false, bool encodeRec709=false) {
|
||
DYHistogram h;
|
||
if(rgba.length%sizeof(float[4]))return nil;
|
||
h.rec709VideoLevels=encodeRec709;
|
||
const float *p=(const float *)rgba.bytes;
|
||
auto bin=[](double v){return (int)std::lround(std::fmax(0.,std::fmin(1.,v))*255.);};
|
||
auto rec709=[](double linear){return linear<.018?4.5*linear:1.099*std::pow(linear,.45)-.099;};
|
||
for(NSUInteger i=0;i<rgba.length/sizeof(float[4]);i++,p+=4){
|
||
if(!std::isfinite(p[0])||!std::isfinite(p[1])||!std::isfinite(p[2])||!std::isfinite(p[3])||p[3]<=(premultiplied?1e-6f:0))continue;
|
||
double alpha=premultiplied?p[3]:1.;
|
||
double rgb[]={p[0]/alpha,p[1]/alpha,p[2]/alpha};
|
||
if(encodeRec709)for(double &component:rgb)component=rec709(component);
|
||
h.bins[0][bin(.2126*rgb[0]+.7152*rgb[1]+.0722*rgb[2])]++;
|
||
for(int c=0;c<3;c++)h.bins[c+1][bin(rgb[c])]++;
|
||
h.samples++;
|
||
}
|
||
return [NSData dataWithBytes:&h length:sizeof(h)];
|
||
}
|