接入在线 LUT 权限、登录与服务器帧预览初版,待正式验收

这个提交包含在:
mac 于 2026-11-11 18:25:35 +08:00 提交
1 父节点 f7d0a80a2e
当前提交 a2a8624dc0
12 个文件已更改
+938 -18

没有与搜索条件相匹配的文件

+85
查看文件
@@ -0,0 +1,85 @@
<?php
// Isolated WordPress contract tests. Never load production configuration or user data.
define('ABSPATH', __DIR__.'/'); define('ARRAY_A','ARRAY_A');
class WP_Error { public $code,$message,$data; function __construct($c,$m,$d=array()){$this->code=$c;$this->message=$m;$this->data=$d;} }
class WP_REST_Response { private $data; public $headers=array(); function __construct($d,$status=200){$this->data=$d;} function get_data(){return $this->data;} function header($k,$v){$this->headers[$k]=$v;} }
class Request implements ArrayAccess {
private $params,$headers;
function __construct($p=array(),$token=''){$this->params=$p;$this->headers=array('authorization'=>$token?'Bearer '.$token:'');}
function get_param($k){return $this->params[$k]??null;} function get_header($k){return $this->headers[$k]??'';} function get_body(){return json_encode($this->params);}
function offsetExists($k):bool{return isset($this->params[$k]);} function offsetGet($k):mixed{return $this->get_param($k);} function offsetSet($k,$v):void{$this->params[$k]=$v;} function offsetUnset($k):void{unset($this->params[$k]);}
}
$transients=array();$options=array();$meta=array();$purchase=array();$admin=false;$member=false;$bound=7;$rows=array();$checks=array();
function add_action(...$a){} function add_filter(...$a){} function register_rest_route(...$a){} function wp_schedule_single_event(...$a){}
function add_option($k,$v,...$a){global $options;if(isset($options[$k]))return false;$options[$k]=$v;return true;}
function delete_option($k){global $options;unset($options[$k]);}
function get_transient($k){global $transients;return $transients[$k]??false;} function set_transient($k,$v,$ttl){global $transients;$transients[$k]=$v;return true;} function delete_transient($k){global $transients;unset($transients[$k]);}
function sanitize_key($v){return preg_replace('/[^a-z0-9_\-]/','',strtolower($v));} function sanitize_text_field($v){return trim(strip_tags($v));}
function get_user_by($key,$id){return $id===7?(object)array('ID'=>7,'display_name'=>'测试用户'):false;}
function get_user_meta($id,$key,$single){global $meta;return $meta[$key]??'';} function user_can($id,$cap){global $admin;return $admin;}
function dayu_check_user_purchased_article($id,$post){global $purchase;return !empty($purchase[$post]);}
function is_boosvip_status($id){global $member;return $member;}
function is_wp_error($v){return $v instanceof WP_Error;}
class DB {
public $prefix='test_';
function prepare($sql,...$args){if(count($args)===1&&is_array($args[0]))$args=$args[0];return array($sql,$args);}
function get_var($q){global $bound;$sql=is_array($q)?$q[0]:$q;if(strpos($sql,'app_login_records')!==false)return $bound;if(strpos($sql,'COUNT(')!==false)return 1;return null;}
function get_results($q,$mode=null){global $rows;return array_map(function($r){return (array)$r;},array_values(array_filter($rows,function($r){return $r->status==='published';})));}
function get_col($q){return array('测试分类');} function esc_like($s){return addcslashes($s,'_%\\');}
function get_row($q){global $rows;$id=$q[1][0];$row=$rows[$id]??null;return $row&&$row->status==='published'&&$row->material_type==='lut'?$row:null;}
}
$wpdb=new DB;
require __DIR__.'/../wp-content/mu-plugins/dayu-color-online-luts.php';
function check($pass,$name){global $checks;$checks[]=array('name'=>$name,'pass'=>(bool)$pass);if(!$pass){fwrite(STDERR,'FAIL '.$name."\n");exit(1);}}
function denied($value,$status){return is_wp_error($value)&&($value->data['status']??0)===$status;}
function body($value){return $value instanceof WP_REST_Response?$value->get_data():null;}
check(!Dayu_Color_Online_LUTs::access(7),'ordinary account denied');
foreach(array(14421,15792) as $post){$purchase=array($post=>true);check(Dayu_Color_Online_LUTs::access(7),'either individual purchase grants '.$post);}
$purchase=array();$member=true;check(Dayu_Color_Online_LUTs::access(7),'active member allowed');$member=false;
$meta=array('cao_user_type'=>'vip','cao_vip_end_time'=>'9999-09-09');check(Dayu_Color_Online_LUTs::access(7),'lifetime member allowed');
$meta=array('cao_user_type'=>'vip','cao_vip_end_time'=>time()-1);check(!Dayu_Color_Online_LUTs::access(7),'expired member denied');
$meta=array('cao_vip_type'=>'year','cao_vip_expire'=>time()+100);check(Dayu_Color_Online_LUTs::access(7),'legacy active membership supported');$meta=array();
check(!Dayu_Color_Online_LUTs::access(8),'deleted user denied');
$device='00000000-0000-0000-0000-000000000001';$key=str_repeat('a',40);$login='dayu_app_login_'.hash('sha256',$key);
$session=array('app_name'=>'DayuColor','device_uuid'=>$device,'expires_at'=>time()+120,'status'=>'pending','user_id'=>7);
$transients[$login]=$session;
check(body(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))))['status']==='pending','pending login cannot mint a credential');
$transients[$login]['app_name']='FCPXSoundEffects';check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'another product login rejected');
$transients[$login]=$session;$transients[$login]['status']='approved';
$issued=Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device)));$token=body($issued)['token']??'';
check(strlen($token)===64,'approved product login exchanges a random token');check($issued->headers['Cache-Control']==='no-store, private','credential responses cannot be cached');
check(denied(Dayu_Color_Online_LUTs::exchange(new Request(array('session_key'=>$key,'device_uuid'=>$device))),401),'one-time login replay rejected');
check(denied(Dayu_Color_Online_LUTs::catalog(new Request()),401),'anonymous catalogue rejected');
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1))),401),'anonymous file rejected');
check(denied(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1))),401),'anonymous frame rejected before decoding');
check(body(Dayu_Color_Online_LUTs::status(new Request(array(),$token)))['allowed']===false,'signed-in unpaid account has no online permission');
check(denied(Dayu_Color_Online_LUTs::catalog(new Request(array(),$token)),403),'unpaid catalogue denied server-side');
$purchase=array(15792=>true);
check(body(Dayu_Color_Online_LUTs::status(new Request(array(),$token)))['allowed']===true,'new purchase is recognized without another login');
$bound=8;check(denied(Dayu_Color_Online_LUTs::status(new Request(array(),$token)),401),'device rebind revokes previous session');$bound=7;
$root=sys_get_temp_dir().'/dayu-color-lut-contract-'.bin2hex(random_bytes(8));mkdir($root);mkdir($root.'/materials');
class Storage {public $root;function material_storage_root(){return $this->root;}}
$storage=new Storage;$storage->root=$root;$GLOBALS['dayu_fcpx_sfx_api']=$storage;
$cube="TITLE test\nLUT_3D_SIZE 2\n";for($z=0;$z<2;$z++)for($y=0;$y<2;$y++)for($x=0;$x<2;$x++)$cube.=(1-$x).' '.(1-$y).' '.(1-$z)."\n";
$path=$root.'/materials/test.cube';file_put_contents($path,$cube);
$rows[1]=(object)array('id'=>1,'title'=>'测试 LUT','category'=>'测试分类','file_size'=>strlen($cube),'checksum'=>hash('sha256',$cube),'material_type'=>'lut','status'=>'published','relative_path'=>'test.cube');
$rows[2]=clone $rows[1];$rows[2]->id=2;$rows[2]->status='draft';
check(count(body(Dayu_Color_Online_LUTs::catalog(new Request(array(),$token)))['items'])===1,'catalogue excludes private drafts');
check(body(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token))) instanceof Dayu_Color_LUT_Binary,'authorized published LUT streams original bytes');
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>2),$token)),404),'private LUT cannot be downloaded by guessed ID');
$rows[1]->relative_path='../outside.cube';file_put_contents($root.'/outside.cube',$cube);
check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token)),503),'catalogue path traversal rejected');$rows[1]->relative_path='test.cube';
$rows[1]->checksum=str_repeat('0',64);check(denied(Dayu_Color_Online_LUTs::download(new Request(array('id'=>1),$token)),503),'server rejects modified LUT bytes');$rows[1]->checksum=hash('sha256',$cube);
$image=imagecreatetruecolor(3,2);imagesetpixel($image,0,0,0x204060);imagesetpixel($image,1,0,0xabcdef);ob_start();imagepng($image);$png=ob_get_clean();unset($image);
$render=Dayu_Color_LUT_Renderer::render($path,$png);check(is_string($render),'renderer returns a PNG');$out=imagecreatefromstring($render);
check(imagesx($out)===3&&imagesy($out)===2,'renderer preserves source aspect and size');check((imagecolorat($out,0,0)&0xffffff)===0xdfbf9f,'known inverse LUT transforms pixel values correctly');unset($out);
$preview=body(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1,'frame_png'=>base64_encode($png)),$token)));check($preview instanceof Dayu_Color_LUT_Binary&&$preview->bytes()===$render,'authorized frame route returns the actual LUT effect');
check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,'invalid')),'malformed image rejected');
$large=imagecreatetruecolor(641,1);ob_start();imagepng($large);$too_large=ob_get_clean();unset($large);check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,$too_large)),'over-limit image rejected');
file_put_contents($path,"LUT_3D_SIZE 2\n0 0 0\n");check(is_wp_error(Dayu_Color_LUT_Renderer::render($path,$png)),'truncated LUT rejected');
file_put_contents($path,"\xff\xfe".iconv('UTF-8','UTF-16LE',$cube));check(is_string(Dayu_Color_LUT_Renderer::render($path,$png)),'UTF-16 BOM LUT supported');
$purchase=array();check(denied(Dayu_Color_Online_LUTs::preview(new Request(array('id'=>1,'frame_png'=>base64_encode($png)),$token)),403),'permission revoked before another frame is processed');
check(body(Dayu_Color_Online_LUTs::logout(new Request(array(),$token)))['success']===true,'logout invalidates server credential');check(denied(Dayu_Color_Online_LUTs::status(new Request(array(),$token)),401),'logged-out token cannot be reused');
unlink($path);unlink($root.'/outside.cube');rmdir($root.'/materials');rmdir($root);
$report=array('pass'=>true,'count'=>count($checks),'scope'=>'Isolated PHP/GD contracts; synthetic users, purchases and frames; no production credentials or account data.','checks'=>$checks);
echo json_encode($report,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE)."\n";
@@ -0,0 +1,155 @@
<?php
/** Plugin Name: Dayu Color Online LUTs
* Product-scoped sessions and access to the existing published LUT catalogue.
*/
if (!defined('ABSPATH')) { exit; }
require_once __DIR__ . '/dayu-color-online-luts/renderer.php';
final class Dayu_Color_LUT_Binary {
private $path;
private $bytes;
private $mime;
public function __construct($path, $bytes, $mime) { $this->path=$path; $this->bytes=$bytes; $this->mime=$mime; }
public function send() {
header('Content-Type: ' . $this->mime);
header('Cache-Control: no-store, private');
header('X-Content-Type-Options: nosniff');
header('Content-Length: ' . ($this->path ? filesize($this->path) : strlen($this->bytes)));
if ($this->path) { readfile($this->path); } else { echo $this->bytes; }
}
public function bytes() { return $this->bytes; }
}
final class Dayu_Color_Online_LUTs {
const APP = 'DayuColor';
const TTL = 2592000;
public static function init() {
add_action('rest_api_init', array(__CLASS__, 'routes'));
add_filter('rest_pre_serve_request', array(__CLASS__, 'serve'), 10, 4);
add_action('dayu_color_lut_consumed_cleanup', 'delete_option');
}
public static function routes() {
foreach (array('session'=>'exchange', 'status'=>'status', 'logout'=>'logout', 'catalog'=>'catalog', '(?P<id>\d+)/download'=>'download', '(?P<id>\d+)/preview'=>'preview') as $path=>$handler) {
register_rest_route('dayu-color/v1', '/lut/' . $path, array('methods'=>'POST', 'callback'=>array(__CLASS__, $handler), 'permission_callback'=>'__return_true'));
}
}
public static function serve($served, $result, $request, $server) {
if (strpos($request->get_route(), '/dayu-color/v1/lut/') !== 0) { return $served; }
$data=$result->get_data();
if ($data instanceof Dayu_Color_LUT_Binary) { $data->send(); return true; }
return $served;
}
private static function response($data) {
$response=new WP_REST_Response($data, 200);
$response->header('Cache-Control', 'no-store, private');
return $response;
}
private static function error($code, $message, $status) { return new WP_Error('dayu_color_lut_' . $code, $message, array('status'=>$status)); }
private static function device($value) {
$value=strtoupper(trim((string)$value));
return preg_match('/^[A-F0-9]{8}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{4}-[A-F0-9]{12}$/D', $value) ? $value : '';
}
private static function bound_user($device) {
global $wpdb;
return intval($wpdb->get_var($wpdb->prepare("SELECT user_id FROM {$wpdb->prefix}app_login_records WHERE device_uuid=%s AND is_active=1 ORDER BY last_active DESC, id DESC LIMIT 1", $device)));
}
public static function access($user_id) {
if (!$user_id || !get_user_by('ID', $user_id)) { return false; }
if (user_can($user_id, 'manage_options')) { return true; }
if (class_exists('CaoUser')) { $user=new CaoUser($user_id); if (method_exists($user, 'vip_status') && $user->vip_status()) { return true; } }
if (function_exists('is_boosvip_status') && is_boosvip_status($user_id)) { return true; }
$type=get_user_meta($user_id, 'cao_user_type', true);
$end=get_user_meta($user_id, 'cao_vip_end_time', true);
$until=is_numeric($end) ? intval($end) : strtotime((string)$end);
if ($type === 'vip' && ($end === '9999-09-09' || ($until && $until > time()))) { return true; }
if (get_user_meta($user_id, 'cao_vip_type', true) && intval(get_user_meta($user_id, 'cao_vip_expire', true)) > time()) { return true; }
global $wpdb;
foreach (array(14421, 15792) as $post) {
if (function_exists('dayu_check_user_purchased_article') && dayu_check_user_purchased_article($user_id, $post)) { return true; }
if ($wpdb->get_var($wpdb->prepare("SELECT id FROM {$wpdb->prefix}cao_paylog WHERE user_id=%d AND post_id=%d AND status=1 LIMIT 1", $user_id, $post))) { return true; }
}
return false;
}
public static function exchange($request) {
$key=(string)$request->get_param('session_key'); $device=self::device($request->get_param('device_uuid'));
if (!$device || !preg_match('/^[A-Za-z0-9_-]{32,80}$/D', $key)) { return self::error('login', '登录会话无效,请重新登录。', 400); }
$transient='dayu_app_login_' . hash('sha256', $key); $session=get_transient($transient);
if (!is_array($session) || intval($session['expires_at'] ?? 0) < time() || ($session['app_name'] ?? '') !== self::APP || !hash_equals((string)($session['device_uuid'] ?? ''), $device)) { return self::error('expired', '登录会话已过期,请重新登录。', 401); }
if (($session['status'] ?? '') !== 'approved') { return self::response(array('status'=>sanitize_key($session['status'] ?? 'pending'), 'message'=>sanitize_text_field($session['message'] ?? '等待微信登录'))); }
$user_id=intval($session['user_id'] ?? 0);
if (!$user_id || self::bound_user($device) !== $user_id || !get_user_by('ID', $user_id)) { return self::error('binding', '账号绑定已变化,请重新登录。', 401); }
// Atomic one-time exchange; add_option is unique in the shared DB, unlike get/set transient pairs.
$once='dayu_color_lut_once_' . hash('sha256', $key);
if (!add_option($once, time(), '', false)) { return self::error('used', '登录会话已使用,请重新登录。', 401); }
delete_transient($transient);
$token=bin2hex(random_bytes(32)); $expires=time()+self::TTL;
set_transient('dayu_color_lut_' . hash('sha256', $token), array('user_id'=>$user_id, 'device'=>$device, 'expires'=>$expires), self::TTL);
// Keep the marker past the original login lifetime, including concurrent poll requests.
wp_schedule_single_event(time()+1200, 'dayu_color_lut_consumed_cleanup', array($once));
return self::response(array('status'=>'approved', 'token'=>$token, 'expires_at'=>$expires, 'allowed'=>self::access($user_id), 'username'=>get_user_by('ID', $user_id)->display_name));
}
private static function authentication($request, $paid=true) {
$header=trim((string)$request->get_header('authorization'));
if (!preg_match('/^Bearer ([a-f0-9]{64})$/D', $header, $match)) { return self::error('login_required', '请先在大鱼调色主 APP 登录。', 401); }
$key='dayu_color_lut_' . hash('sha256', $match[1]); $session=get_transient($key);
if (!is_array($session) || intval($session['expires'] ?? 0)<time() || self::bound_user($session['device']) !== intval($session['user_id']) || !get_user_by('ID', intval($session['user_id']))) { return self::error('login_required', '登录已失效,请在主 APP 重新登录。', 401); }
if ($paid && !self::access(intval($session['user_id']))) { return self::error('access_denied', '在线 LUT 需要有效会员,或已购买文章 14421 / 15792。', 403); }
$session['key']=$key; return $session;
}
public static function status($request) {
$session=self::authentication($request, false); if (is_wp_error($session)) { return $session; }
return self::response(array('allowed'=>self::access($session['user_id']), 'username'=>get_user_by('ID', $session['user_id'])->display_name, 'expires_at'=>$session['expires'], 'renderer'=>function_exists('imagecreatefromstring')));
}
public static function logout($request) {
$session=self::authentication($request, false); if (is_wp_error($session)) { return $session; }
delete_transient($session['key']); return self::response(array('success'=>true));
}
public static function catalog($request) {
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
global $wpdb; $table=$wpdb->prefix . 'dayu_sfx_materials';
$page=max(1, intval($request->get_param('page'))); $limit=60;
$category=mb_substr(sanitize_text_field((string)$request->get_param('category')), 0, 191);
$search=mb_substr(sanitize_text_field((string)$request->get_param('search')), 0, 100);
$where="material_type='lut' AND status='published'"; $values=array();
if ($category!=='') { $where.=' AND category=%s'; $values[]=$category; }
if ($search!=='') { $where.=' AND (title LIKE %s OR category LIKE %s)'; $like='%'.$wpdb->esc_like($search).'%'; array_push($values, $like, $like); }
$count="SELECT COUNT(*) FROM {$table} WHERE {$where}";
$total=intval($wpdb->get_var($values ? $wpdb->prepare($count, $values) : $count));
$rows=$wpdb->get_results($wpdb->prepare("SELECT id,title,category,file_size,checksum FROM {$table} WHERE {$where} ORDER BY title ASC,id ASC LIMIT %d OFFSET %d", array_merge($values, array($limit,($page-1)*$limit))), ARRAY_A);
$categories=$wpdb->get_col("SELECT DISTINCT category FROM {$table} WHERE material_type='lut' AND status='published' AND category<>'' ORDER BY category ASC");
foreach ((array)$rows as &$row) { $row['id']=intval($row['id']); $row['file_size']=intval($row['file_size']); } unset($row);
return self::response(array('items'=>(array)$rows, 'categories'=>array_values((array)$categories), 'page'=>$page, 'total'=>$total, 'per_page'=>$limit));
}
private static function material($id) {
global $wpdb;
$row=$wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->prefix}dayu_sfx_materials WHERE id=%d AND material_type='lut' AND status='published'", intval($id)));
if (!$row) { return self::error('missing', '此 LUT 已下架或不存在。', 404); }
$api=$GLOBALS['dayu_fcpx_sfx_api'] ?? null;
if (!$api || !method_exists($api, 'material_storage_root')) { return self::error('storage', '素材服务暂不可用。', 503); }
$root=realpath($api->material_storage_root().'/materials');
$path=$root ? realpath($root.'/'.ltrim($row->relative_path, '/\\')) : false;
if (!$root || !$path || strpos($path, $root.DIRECTORY_SEPARATOR)!==0 || strtolower(pathinfo($path,PATHINFO_EXTENSION))!=='cube' || !is_file($path) || !is_readable($path) || filesize($path)>67108864 || !hash_equals(strtolower($row->checksum), hash_file('sha256',$path))) { return self::error('file', 'LUT 文件未通过完整性检查。', 503); }
return $path;
}
public static function download($request) {
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
$path=self::material($request['id']); if (is_wp_error($path)) { return $path; }
return self::response(new Dayu_Color_LUT_Binary($path, null, 'application/octet-stream'));
}
public static function preview($request) {
$session=self::authentication($request); if (is_wp_error($session)) { return $session; }
if (strlen($request->get_body())>2100000) { return self::error('frame_size', '预览帧过大。', 413); }
$rate='dayu_color_lut_rate_' . $session['user_id'].'_'.intval(time()/60);
$count=intval(get_transient($rate)); if ($count>=120) { return self::error('rate', '预览请求较多,请稍后刷新。', 429); }
set_transient($rate, $count+1, 120);
$path=self::material($request['id']); if (is_wp_error($path)) { return $path; }
$encoded=$request->get_param('frame_png');
if (!is_string($encoded) || strlen($encoded)>2000000) { return self::error('frame', '预览帧无效。', 400); }
$bytes=base64_decode($encoded, true);
if (!is_string($bytes) || strlen($bytes)>1500000) { return self::error('frame', '预览帧无效。', 400); }
$result=Dayu_Color_LUT_Renderer::render($path, $bytes);
if (is_wp_error($result)) { return $result; }
return self::response(new Dayu_Color_LUT_Binary(null, $result, 'image/png'));
}
}
Dayu_Color_Online_LUTs::init();
@@ -0,0 +1,80 @@
<?php
if (!defined('ABSPATH')) { exit; }
/** Display-reference renderer. Uploaded PNGs and returned PNGs stay in request memory. */
final class Dayu_Color_LUT_Renderer {
private static function error($message) { return new WP_Error('dayu_color_lut_render', $message, array('status'=>422)); }
public static function read_cube($path) {
$text=file_get_contents($path);
if (!is_string($text) || strlen($text)>67108864) { return self::error('无法读取 LUT。'); }
foreach (array("\x00\x00\xfe\xff"=>'UTF-32BE', "\xff\xfe\x00\x00"=>'UTF-32LE', "\xfe\xff"=>'UTF-16BE', "\xff\xfe"=>'UTF-16LE') as $bom=>$encoding) {
if (strncmp($text, $bom, strlen($bom))===0) { $text=iconv($encoding, 'UTF-8', substr($text,strlen($bom))); break; }
}
if (!is_string($text) || strpos($text,"\0")!==false) { return self::error('LUT 编码无效。'); }
$text=preg_replace('/^\xEF\xBB\xBF/', '', $text);
$n=0; $rows=0; $packed=''; $min=array(0,0,0); $max=array(1,1,1);
$stream=fopen('php://memory', 'w+'); fwrite($stream,str_replace("\r","\n",$text)); rewind($stream); unset($text);
while (($line=fgets($stream))!==false) {
$line=trim(explode('#',$line,2)[0]); if ($line==='') { continue; }
if (preg_match('/^LUT_3D_SIZE\s+(\d+)\s*$/D',$line,$m)) {
if ($n || intval($m[1])<2 || intval($m[1])>128) { fclose($stream); return self::error('LUT 尺寸无效。'); }
$n=intval($m[1]); continue;
}
if (preg_match('/^(DOMAIN_MIN|DOMAIN_MAX)\s+(.+)$/D',$line,$m)) {
$parts=preg_split('/\s+/',trim($m[2]));
if (count($parts)!==3 || count(array_filter($parts,'is_numeric'))!==3) { fclose($stream); return self::error('LUT DOMAIN 无效。'); }
if ($m[1]==='DOMAIN_MIN') { $min=array_map('floatval',$parts); } else { $max=array_map('floatval',$parts); }
continue;
}
if (preg_match('/^(TITLE|LUT_3D_INPUT_RANGE)(?:\s|$)/',$line)) { continue; }
$parts=preg_split('/\s+/', $line);
if (!$n || count($parts)!==3 || count(array_filter($parts,'is_numeric'))!==3 || $rows>=$n*$n*$n) { fclose($stream); return self::error('LUT 数据格式无效。'); }
$rgb=array_map('floatval',$parts);
foreach ($rgb as $v) { if (!is_finite($v)) { fclose($stream); return self::error('LUT 含无效数字。'); } }
$packed.=pack('g3',$rgb[0],$rgb[1],$rgb[2]); $rows++;
}
fclose($stream);
for ($c=0;$c<3;$c++) { if (!is_finite($min[$c]) || !is_finite($max[$c]) || $max[$c]<=$min[$c]) { return self::error('LUT DOMAIN 无效。'); } }
if (!$n || $rows!==$n*$n*$n) { return self::error('LUT 数据不完整。'); }
return array($n,$packed,$min,$max);
}
public static function sample($table, $rgb) {
list($n,$packed,$min,$max)=$table; $index=array(); $fraction=array();
for ($c=0;$c<3;$c++) {
$s=max(0.,min(1.,($rgb[$c]-$min[$c])/($max[$c]-$min[$c])))*($n-1);
$index[$c]=min($n-2,intval($s)); $fraction[$c]=$s-$index[$c];
}
$out=array(0.,0.,0.);
for ($k=0;$k<8;$k++) {
$x=$k&1; $y=($k>>1)&1; $z=($k>>2)&1;
$offset=((($index[2]+$z)*$n+$index[1]+$y)*$n+$index[0]+$x)*12;
$v=unpack('g3',$packed,$offset);
$w=($x?$fraction[0]:1-$fraction[0])*($y?$fraction[1]:1-$fraction[1])*($z?$fraction[2]:1-$fraction[2]);
for ($c=0;$c<3;$c++) { $out[$c]+=$v[$c+1]*$w; }
}
return $out;
}
public static function render($path, $bytes) {
if (!function_exists('imagecreatefromstring')) { return self::error('服务器图像处理暂不可用。'); }
$size=@getimagesizefromstring($bytes);
if (!$size || $size[2]!==IMAGETYPE_PNG || $size[0]<1 || $size[1]<1 || max($size[0],$size[1])>640 || $size[0]*$size[1]>230400) { return self::error('请发送最长边不超过 640 像素的 PNG 预览帧。'); }
$table=self::read_cube($path); if (is_wp_error($table)) { return $table; }
$input=@imagecreatefromstring($bytes); if (!$input) { return self::error('无法解码预览帧。'); }
$output=imagecreatetruecolor($size[0],$size[1]); imagealphablending($output,false); imagesavealpha($output,true);
// Memoize repeated display pixels within this request only. No frame cache on disk or in WP.
$memo=array();
for ($y=0;$y<$size[1];$y++) { for ($x=0;$x<$size[0];$x++) {
$pixel=imagecolorat($input,$x,$y);
if (isset($memo[$pixel])) { $color=$memo[$pixel]; } else {
$rgba=imagecolorsforindex($input,$pixel);
$v=self::sample($table,array($rgba['red']/255,$rgba['green']/255,$rgba['blue']/255));
$color=($rgba['alpha']<<24)|(intval(round(max(0,min(1,$v[0]))*255))<<16)|(intval(round(max(0,min(1,$v[1]))*255))<<8)|intval(round(max(0,min(1,$v[2]))*255));
if (count($memo)<65536) { $memo[$pixel]=$color; }
}
imagesetpixel($output,$x,$y,$color);
} }
ob_start(); imagepng($output,null,3); $png=ob_get_clean();
unset($input, $output);
return $png;
}
}