# livecanvas

Adopt this skill: https://proskills.md/skills/other/pengchujin-livecanvas-livecanvas

Page: https://proskills.md/skills/other/pengchujin-livecanvas-livecanvas
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: livecanvas/SKILL.md
size: 10565
sha: 58915ae83dcaf2a9d1e55fdcf164565018d83bba
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/SKILL.md

```text
---
name: livecanvas
description: 将主题或材料经搜索核实制成苹果 Live Photo 信息动效卡。用 Remotion 编排图片、PNG、emoji、场景、时间线和可选图表，适用于知识解释、产品比较、变化过程及数据故事；制作可预览动效与配对实况资源，说明接收端兼容性。
---

# LiveCanvas · 实况画布

把用户的一句话变成有证据、静态可读、动态能讲清内容的实况动效卡。原名 LiveChart，现名 LiveCanvas（实况画布），覆盖图表、图片与场景叙事；默认主动设计与主题相关的图片/图标和场景动作，图表只是可选表达。默认中文、Remotion、1080×1440、30 fps、约 3 秒、无声。这些是起点，允许按内容调整；3 秒不是声称的苹果格式限制。

## 先定内容，再定动效

1. 从请求提取主体、指标、时间范围、比较关系、用途；给定文章或报告时先读完整材料，再提取关键事件、变化、能力、对比与场景。按内容重要性分配篇幅，不只挑价格或易展示的数字。具体需求优先，不把用户给的例子当成固定模板。
2. 搜索并核实数据，读 [数据与口径](references/data.md)。先保存原始证据、事实或结构化数据，再写标题、数字与注释。无时间序列的主题可以用事实卡、过程或场景解释；不能为了画图虚构数据。
3. 写简短制作说明：整套内容主线、每张的主体与结论、事实/数据口径、封面信息层级、分镜时间表及素材计划。张数依用户要求和内容决定，不固定为某个数量或主题组合。选出适合该主题的表达，不默认折线图加数字。直接做设计判断；仅当缺失信息会实质改变答案时提问。
4. 按 [封面与动效](references/design.md) 制作。吸收 Emil Kowalski animate 的有目的、克制、连续、节奏清晰原则；用户已指定 Remotion，不执行上游的工具替换步骤，也不把交互组件时长限制机械套到解释性视频。

## 文案：直接写事实与数据

- 标题优先写“主体 + 数字/变化/明确结论”，例如“输出上限 1M tokens”“首发任务成本低 39%”“Text Arena 暂列第一”。没有必要的数字时，直接写产品名、版本或具体事件，不硬凑数据。
- 用简短、直观的陈述，删掉空泛宣传、设问、比喻、对仗和装饰性英文标签。不要用“重新定义”“读懂三个变化”“让收益落到真实场景”等句子代替事实。正文与配图描述也遵循同一标准；来源写清机构名，如 Artificial Analysis，不只写 AA。写法示例与限定条件见 [封面与动效](references/design.md#标题与配图文案)。
- 用户说“AI 味太浓”“直接上数据”“不要花里胡哨”时，优先精简文案与无关装饰；保留原有主题、信息、必要素材和已选设计方向，不擅自删除主体封面、合并主题或把整套改成同一数据模板。
- 修改时保留已确认的主题、信息与视觉要求。用户改变张数或重点时重新分配内容，并说明合并、替换与复用关系；不靠机械拆页或重复主题凑数。按图编号核对改版前后内容，总包按不同内容去重。

## 视觉表达

- 封面以产品名、版本号或核心对象建立视觉主次。“登场感”“冲击力”等是效果描述，不直接当成画面文字；具体做法见 [封面与动效](references/design.md)。
- 整套统一配色、字体和图形语言，按内容选择构图。用图形解释事实与关系，避免堆文字、大数字、装饰卡片或机械复用同一模板。

- 默认让主题中的对象出现在画面中：产品 PNG、咖啡杯、汽车、列车、奖牌、城市照片、天气 emoji 等；挑选与内容有关的一组统一风格素材，不是给图表角落贴装饰。
- 设计对象的入场、运动、排列、替换或状态变化来解释内容。例如列车驶过年份节点、咖啡杯带出门店卡片、城市画面随季节切换。
- 按主题组合场景、图片对比、图标阵列、时间线、过程演示、重点文字和必要图表。纯图表只在确实最清楚或用户指定时采用。
- 使用图片或 emoji 时读 [图片与图标](references/visual-assets.md)，负责找素材、检查可用性并加入工程；无需让用户先提供素材才开始。

## 搜索默认值

- “最近 3 年”：截至最新可靠已完成观测日的滚动三年，注明首尾实际日期，不默认成三个年末值。月度图用已完成月末观测；最新未完成月只能单独注明。
- “全年温度”未给年份：采用最近一个完整自然年，默认月平均气温；在结果开头说明选择。若意图明显是常年气候，使用有明确基准期的气候平均值。
- 跨公司比较对齐观测日期、指标、币种，或明确使用同基期指数，保留原始绝对值。
- 允许涨、跌、持平、季节循环。不要因用户说“增长曲线”而把下降画成增长。
- 日期按用户时区解析，不用机器日期硬编码“今年”。

## 制作与封装

读 [运行与交付](references/production.md) 和 [直接交付](references/direct-delivery.md)。资源路径相对于本 skill 目录；称该绝对路径为 `SKILL_DIR`。

- 把 `assets/remotion/` 作为渲染工程起点复制到本次目录，使用随附锁文件 `npm ci`。其中折线图只是示例，应按分镜重写 composition，不是默认成品版式。不要在已安装 skill 内生成输出或安装依赖。
- 示例 `data.json` 为合成数据，只用于测试。正式制作需替换数据和文案，去掉示例标记前完成事实核查。
- 时间序列使用 `scripts/validate_data.py` 检查日期、来源引用、覆盖和范围；其他内容按 [数据与口径](references/data.md) 使用匹配的事实/比较结构，不硬套日期序列。校验通过不代表来源事实已核实。
- 所有动画由 `useCurrentFrame()` 驱动；禁止 CSS animation、墙钟、未固定随机数、网页图库自带动画。
- 将图片、emoji、文字、场景与图表纳入同一分镜，保留可追溯事实、静态封面、确定性渲染与验证流程。
- 从同一 composition 的完整停留帧导出 `cover.jpg`，记录 `coverFrame / fps`。封面画面必须出现在动画内，still-image-time 指向同一时间。
- 按生成环境选择配对器：macOS 可用 `scripts/pair_live_photo.swift`；Linux / Windows 使用 `scripts/pair_live_photo.py`，读 [跨平台 Apple Live Photo](references/portable-live-photo.md)。两条路径都将无声 H.264 与 JPEG 写成包含共享标识和 timed metadata 的 Apple 配对资源。这是中间步骤，不算交付完成；其他输入先转码，不默默丢弃用户音轨。
- 封装完成后禁止再次普通转码 paired MOV，否则可能丢失元数据轨道。
- 用 `scripts/package_live_photo.py` 生成命名明确的单个 `.pvt` 包；将其标为实况资源包，不承诺 iPhone「文件」App 可直接预览；不自动打开或导入「照片」App，不修改照片库。不得停在 JPG + MOV 配对资源。

## 验证与完成标准

先检查事实和素材，再预览封面和视频：抽查开始、主要动作中段、转场、数据极值（如有）和封面停留帧；检查图片加载、emoji 字形、透明边缘、中文字体、标签遮挡、数值同步、单位日期与裁切。确认动作在解释主题，而非只有数字和条形变化。真实曲线不使用引入虚假峰谷的平滑；缺测处断线。成套核对重要内容和比较关系是否保留、封面主体是否明确、风格是否统一；数字滚动检查中间帧与最终值，静态封面必须完整可读。

分别记录状态，不把前一项当作后一项成功：

1. 数据与来源核实；机器校验只是其中一部分。
2. 封面和 MP4 渲染完成，素材与主要动作可见，元数据及画面检查通过。
3. Live Photo 标识匹配、timed metadata 时间位置正确。
4. 有 Apple 环境时记录 `PHLivePhoto.request` 本机加载成功或具体失败；纯 Python 生成环境记为 `not_available`，不要伪造通过。
5. `.pvt` 包完整、配对资源哈希一致。
6. 相册导入、设备播放、第三方平台上传及锁屏兼容性均为可选事项，只有用户另外明确请求时才操作并记录，不作为文件交付的前置条件。

没有 macOS 时执行跨平台 Python 配对与打包，不能仅因操作系统退回 MP4 + 封面。元数据读回、视频解码和包完整性通过即可交付资源；Apple 本机加载、iPhone 导入/播放分别记录。缺少实际依赖且无法安装时才交付预览并明确阻塞项，不声称平台无法生成。生成文件不证明手机预览、保存或播放成功。

## 交付

每个主题独立目录，同时提供可直接观看的预览和 `主题名称.pvt` 实况资源包，保存 `delivery.json`。另保留 `data.json`、原始证据、`sources.md`、含本地素材的可编辑 Remotion 工程、素材清单 `assets.json`（使用素材时）、`cover.jpg`、`motion.mp4`、内部 `live/` 配对资源及 manifest、`qa.json`。压缩包只用于传输，不是可直接识别的 Live Photo。

优先展示可观看的封面/动态预览，另附 `.pvt` 资源包链接、数据截止日及验证状态。用户要求手机直接预览时，核实其接收路径；不能仅凭文件包生成或本机加载成功宣称已满足。传输界面不支持目录包时附 `.pvt.zip`，注明解压后得到资源包，仍需支持 Live Photo 的应用读取。网页 LivePhotosKit 预览与保存为原生实况照片是两项能力，未实现的能力不承诺。封面和 MP4 只能标作预览；聊天界面不能原生展示 Apple 实况时简短说明。不要把“直接交付 Live Photo”解释成导入相册，不索取照片库权限，也不自动打开可能触发导入的 .pvt。未经请求不发布到社交平台。

## 示例触发

- “用 LiveCanvas 做小米最近三年的市值变化。”
- “苹果和小米近三年市值做成两张实况图，风格统一。”
- “把北京去年的全年气温做成 Live 图，封面也设计好。”
- “把这份数据做成会动的信息图，导出苹果实况照片。”

- “用咖啡杯 PNG 和门店卡片，做瑞幸与星巴克的扩张故事。”
- “用列车、年份节点和里程数字，做中国高铁的实况动效。”
```

## File: livecanvas/scripts/package_live_photo.py
size: 3326
sha: fcea8c86f339305d4841e3ce386971f4f6f08735
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/package_live_photo.py

```text
#!/usr/bin/env python3
"""Wrap a validated Live Photo pair in a cross-platform .pvt package (no transcoding)."""
import argparse
import hashlib
import json
from pathlib import Path
import plistlib
import shutil
import tempfile

def digest(path):
    return hashlib.sha256(path.read_bytes()).hexdigest()

def package(pair_dir, output):
    pair_dir, output = Path(pair_dir).resolve(), Path(output).absolute()
    manifest = json.loads((pair_dir / 'manifest.json').read_text())
    if manifest.get('metadataVerified') is not True:
        raise ValueError('Pair must pass metadata validation first')
    load = manifest.get('localPHLivePhotoLoad')
    if manifest.get('backend') == 'portable-python':
        from pair_live_photo import verify_pair
        verify_pair(pair_dir, manifest)  # Re-read files; do not trust a manifest flag alone.
        if load not in ('passed', 'not_available'):
            raise ValueError('Known Apple loading failure blocks delivery')
    elif load != 'passed':
        raise ValueError('Native backend must pass PHLivePhoto validation first')
    if output.suffix.lower() != '.pvt':
        raise ValueError('Output must end in .pvt')
    resources = {}
    for key, suffix in [('photo', '.jpg'), ('video', '.mov')]:
        source = (pair_dir / manifest[key]).resolve()
        if source.parent != pair_dir or not source.is_file():
            raise ValueError('Invalid resource path: ' + str(source))
        resources[output.stem + suffix] = source
    metadata = {'PFVideoComplementMetadataVersionKey': '1'}
    reused = output.exists()
    if reused:
        if not output.is_dir() or set(p.name for p in output.iterdir()) != set(resources) | {'metadata.plist'}:
            raise ValueError('Existing output differs; choose a new name')
        if plistlib.loads((output / 'metadata.plist').read_bytes()) != metadata:
            raise ValueError('Existing metadata differs')
        for name, source in resources.items():
            if digest(output / name) != digest(source):
                raise ValueError('Existing resource differs: ' + name)
    else:
        output.parent.mkdir(parents=True, exist_ok=True)
        staging = Path(tempfile.mkdtemp(prefix='.livecanvas-', dir=output.parent))
        try:
            for name, source in resources.items():
                shutil.copyfile(source, staging / name)
                if digest(staging / name) != digest(source):
                    raise ValueError('Copy verification failed')
            (staging / 'metadata.plist').write_bytes(plistlib.dumps(metadata))
            staging.rename(output)
        finally:
            if staging.exists():
                shutil.rmtree(staging)
    return {'package': str(output), 'identifier': manifest['identifier'],
            'resourcesUnchanged': True, 'reused': reused,
            'metadataVerified': True, 'localPHLivePhotoLoad': load,
            'sha256': {name: digest(output / name) for name in resources},
            'photosImport': 'not_tested', 'iPhonePlayback': 'not_tested'}

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('pair_dir')
    parser.add_argument('output_pvt')
    args = parser.parse_args()
    print(json.dumps(package(args.pair_dir, args.output_pvt), ensure_ascii=False, indent=2))
```

## File: livecanvas/scripts/pair_live_photo.py
size: 6743
sha: d3abb921a39117ce626c26cd6aabc7f2076582c7
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/pair_live_photo.py

```text
#!/usr/bin/env python3
"""Pair rendered JPEG + silent H.264 as Apple Live Photo on any desktop OS.
Requires Python >=3.10, Pillow >=10,<12, ffmpeg and ffprobe on PATH.
Never imports into Photos. Use verify_live_photo.swift for optional Apple validation.
"""
import argparse
from fractions import Fraction
import hashlib
import json
import math
from pathlib import Path
import shutil
import subprocess
import tempfile
import uuid

from PIL import Image
from portable_live_photo.apple import write_live_jpeg, write_live_mov, inspect_live_jpeg, inspect_live_mov

def digest(path):
    with Path(path).open('rb') as stream:
        return hashlib.file_digest(stream, 'sha256').hexdigest() if hasattr(hashlib, 'file_digest') else hashlib.sha256(stream.read()).hexdigest()

def probe(path):
    result = subprocess.run(['ffprobe', '-v', 'error', '-show_streams', '-show_format', '-of', 'json', str(path)], check=True, capture_output=True, text=True)
    return json.loads(result.stdout)

def check_inputs(photo, movie, seconds, fps):
    if not all(math.isfinite(n) for n in (seconds, fps)) or not 0 < fps <= 240:
        raise ValueError('Invalid cover time/fps')
    info = probe(movie)
    streams = info['streams']
    videos = [s for s in streams if s['codec_type'] == 'video']
    if len(videos) != 1 or videos[0]['codec_name'] != 'h264':
        raise ValueError('Expected one H.264 video stream')
    if any(s['codec_type'] == 'audio' for s in streams):
        raise ValueError('Silent-only input required; audio must not be silently discarded')
    video = videos[0]
    duration = float(video.get('duration', info['format']['duration']))
    if not math.isfinite(duration) or not 0 <= seconds or seconds + 1/fps > duration + 0.0001:
        raise ValueError('Cover time outside video')
    if abs(float(Fraction(video['avg_frame_rate'])) - fps) > 0.01 or abs(seconds*fps-round(seconds*fps)) > 0.0001:
        raise ValueError('FPS mismatch or cover time not aligned to frame')
    if abs(float(video.get('start_time', 0))) > 0.0001:
        raise ValueError('Expected zero-based render timeline')
    if any(float(d.get('rotation', 0)) != 0 for d in video.get('side_data_list', [])):
        raise ValueError('Render rotation into pixels before pairing')
    with Image.open(photo) as cover:
        if cover.format != 'JPEG' or cover.size != (video['width'], video['height']):
            raise ValueError('Expected JPEG matching video dimensions')
        if cover.getexif().get(274, 1) != 1:
            raise ValueError('Render EXIF orientation into pixels first')
        cover.load()
    return duration

def verify_pair(directory, manifest):
    directory = Path(directory).resolve()
    paths = []
    for key in ('photo', 'video'):
        path = (directory / manifest[key]).resolve()
        if path.parent != directory or not path.is_file():
            raise ValueError('Invalid pair resource path')
        if manifest.get('sha256', {}).get(key) != digest(path):
            raise ValueError('Pair hash mismatch: ' + key)
        paths.append(path)
    photo, movie = paths
    identifier = inspect_live_jpeg(photo)
    metadata = inspect_live_mov(movie)
    if identifier != manifest['identifier'] or metadata.asset_id != identifier or metadata.sample_value != 0:
        raise ValueError('Live Photo identifier or signed metadata sample mismatch')
    if abs(metadata.still_time - manifest['coverTime']) > 1/60000:
        raise ValueError('Timed metadata position mismatch')
    # Independent FFmpeg demuxer must find the metadata sample at the same timestamp.
    packets = json.loads(subprocess.run(['ffprobe', '-v', 'error', '-select_streams', 'd', '-show_packets', '-of', 'json', str(movie)], check=True, capture_output=True, text=True).stdout)['packets']
    if len(packets) != 1 or abs(float(packets[0]['pts_time']) - manifest['coverTime']) > 1/60000:
        raise ValueError('FFprobe timed sample readback failed')
    if abs(float(packets[0]['duration_time']) - 1/manifest['fps']) > 2/60000:
        raise ValueError('Timed sample duration mismatch')
    check_inputs(photo, movie, manifest['coverTime'], manifest['fps'])
    subprocess.run(['ffmpeg', '-v', 'error', '-xerror', '-i', str(movie), '-map', '0:v:0', '-f', 'null', '-'], check=True, capture_output=True)
    return metadata

def pair(photo, movie, output, seconds, fps):
    photo, movie, output = Path(photo).resolve(), Path(movie).resolve(), Path(output).absolute()
    if output.exists():
        raise ValueError('Output already exists; choose a new directory')
    duration = check_inputs(photo, movie, seconds, fps)
    output.parent.mkdir(parents=True, exist_ok=True)
    staging = Path(tempfile.mkdtemp(prefix='.livecanvas-pair-', dir=output.parent))
    try:
        identifier = str(uuid.uuid4()).upper()
        raw = staging / 'remux.mov'
        subprocess.run(['ffmpeg', '-v', 'error', '-nostdin', '-i', str(movie), '-map', '0:v:0', '-map_metadata', '-1', '-c:v', 'copy', '-movie_timescale', '60000', str(raw)], check=True, capture_output=True)
        write_live_jpeg(photo, staging / 'live.jpg', identifier)
        write_live_mov(raw, staging / 'live.mov', identifier, seconds, duration, fps)
        raw.unlink()
        manifest = {'identifier': identifier, 'photo': 'live.jpg', 'video': 'live.mov', 'coverTime': seconds, 'duration': duration, 'fps': fps,
                    'backend': 'portable-python', 'metadataVerified': False, 'localPHLivePhotoLoad': 'not_available',
                    'localLoadReason': 'Portable backend does not invoke Apple PhotoKit', 'iPhonePlayback': 'not_tested',
                    'photosImport': 'not_requested', 'wallpaper': 'not_tested', 'importedIntoPhotos': False,
                    'sha256': {'photo': digest(staging/'live.jpg'), 'video': digest(staging/'live.mov')}}
        actual = verify_pair(staging, manifest)
        manifest.update(metadataVerified=True, readbackStillTime=actual.still_time)
        (staging/'manifest.json').write_text(json.dumps(manifest, ensure_ascii=False, indent=2), encoding='utf-8')
        if output.exists():
            raise ValueError('Output appeared during generation; refusing to replace it')
        staging.rename(output)
        return manifest
    finally:
        if staging.exists():
            shutil.rmtree(staging)

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('photo')
    parser.add_argument('movie')
    parser.add_argument('output')
    parser.add_argument('cover_seconds', type=float)
    parser.add_argument('fps', type=float)
    args = parser.parse_args()
    print(json.dumps(pair(args.photo, args.movie, args.output, args.cover_seconds, args.fps), indent=2))
```

## File: livecanvas/scripts/pair_live_photo.swift
size: 10412
sha: 99f9b90475aa48c53197af962c81bb002f516756
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/pair_live_photo.swift

```text
// macOS, silent H.264 + JPEG only. Writes new files; never imports into Photos.
import Foundation
import AVFoundation
import ImageIO
import Photos
import AppKit
import UniformTypeIdentifiers

struct Failure: Error, CustomStringConvertible { let description: String }
func check(_ ok: Bool, _ message: String) throws { if !ok { throw Failure(description: message) } }
func writeJSON(_ object: [String: Any], _ url: URL) throws {
    try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]).write(to: url)
}
func waitReady(_ input: AVAssetWriterInput, writer: AVAssetWriter) throws {
    let deadline = Date().addingTimeInterval(30)
    while !input.isReadyForMoreMediaData {
        try check(writer.status == .writing, "Writer failed: \(String(describing: writer.error))")
        try check(Date() < deadline, "Writer readiness timed out")
        Thread.sleep(forTimeInterval: 0.002)
    }
}

func run() throws {
    let args = CommandLine.arguments
    guard args.count == 6 else {
        print("Usage: pair_live_photo COVER.jpg MOTION.mp4 NEW_OUTPUT_DIRECTORY COVER_SECONDS FPS")
        throw Failure(description: "Expected five arguments")
    }
    let photo = URL(fileURLWithPath: args[1]), movie = URL(fileURLWithPath: args[2])
    let output = URL(fileURLWithPath: args[3], isDirectory: true)
    guard let seconds = Double(args[4]), let fps = Double(args[5]) else { throw Failure(description: "Invalid time/fps") }
    try check(seconds.isFinite && fps.isFinite && fps > 0 && fps <= 240, "Invalid time/fps")
    try check(!FileManager.default.fileExists(atPath: output.path), "Output directory already exists; choose a new directory")
    let asset = AVURLAsset(url: movie)
    let duration = CMTimeGetSeconds(asset.duration)
    try check(duration.isFinite && seconds >= 0 && seconds + 1/fps <= duration + 0.0001, "Cover time outside video")
    try check(asset.tracks(withMediaType: .audio).isEmpty, "Audio present: this helper is silent-only; use an audio-preserving writer")
    guard let track = asset.tracks(withMediaType: .video).first,
          let rawFormat = track.formatDescriptions.first else { throw Failure(description: "Missing video track") }
    let format = rawFormat as! CMFormatDescription
    try check(CMFormatDescriptionGetMediaSubType(format) == kCMVideoCodecType_H264, "Expected H.264 input")
    try check(abs(Double(track.nominalFrameRate)-fps) < 0.1, "FPS does not match input")
    try check(abs(CMTimeGetSeconds(track.timeRange.start)) < 0.0001, "Expected a zero-based Remotion timeline")
    try check(abs(seconds*fps - (seconds*fps).rounded()) < 0.0001, "Cover time must align to a video frame")
    guard let source = CGImageSourceCreateWithURL(photo as CFURL, nil),
          let sourceType = CGImageSourceGetType(source),
          let image = CGImageSourceCreateImageAtIndex(source, 0, nil) else { throw Failure(description: "Cannot read cover") }
    try check(sourceType as String == UTType.jpeg.identifier, "Cover must be JPEG")
    let transformed = track.naturalSize.applying(track.preferredTransform)
    try check(image.width == Int(abs(transformed.width).rounded()) && image.height == Int(abs(transformed.height).rounded()), "Cover/video dimensions differ")
    try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)
    let imageURL = output.appendingPathComponent("live.jpg"), videoURL = output.appendingPathComponent("live.mov")
    let identifier = UUID().uuidString
    var properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [String: Any] ?? [:]
    var maker = properties[kCGImagePropertyMakerAppleDictionary as String] as? [String: Any] ?? [:]
    maker["17"] = identifier
    properties[kCGImagePropertyMakerAppleDictionary as String] = maker
    properties[kCGImageDestinationLossyCompressionQuality as String] = 1.0
    guard let dest = CGImageDestinationCreateWithURL(imageURL as CFURL, UTType.jpeg.identifier as CFString, 1, nil) else { throw Failure(description: "Cannot create JPEG") }
    CGImageDestinationAddImageFromSource(dest, source, 0, properties as CFDictionary)
    try check(CGImageDestinationFinalize(dest), "JPEG write failed")

    let reader = try AVAssetReader(asset: asset)
    let readVideo = AVAssetReaderTrackOutput(track: track, outputSettings: nil)
    readVideo.alwaysCopiesSampleData = false
    try check(reader.canAdd(readVideo), "Cannot add video reader")
    reader.add(readVideo)
    let writer = try AVAssetWriter(outputURL: videoURL, fileType: .mov)
    let content = AVMutableMetadataItem()
    content.keySpace = .quickTimeMetadata
    content.key = AVMetadataKey.quickTimeMetadataKeyContentIdentifier as NSString
    content.value = identifier as NSString
    content.dataType = kCMMetadataBaseDataType_UTF8 as String
    writer.metadata = [content]
    let videoInput = AVAssetWriterInput(mediaType: .video, outputSettings: nil, sourceFormatHint: format)
    videoInput.transform = track.preferredTransform
    videoInput.expectsMediaDataInRealTime = false
    try check(writer.canAdd(videoInput), "Cannot add video writer")
    writer.add(videoInput)
    let spec: [String: Any] = [kCMMetadataFormatDescriptionMetadataSpecificationKey_Identifier as String: "mdta/com.apple.quicktime.still-image-time", kCMMetadataFormatDescriptionMetadataSpecificationKey_DataType as String: kCMMetadataBaseDataType_SInt8 as String]
    var metadataFormat: CMFormatDescription?
    let status = CMMetadataFormatDescriptionCreateWithMetadataSpecifications(allocator: kCFAllocatorDefault, metadataType: kCMMetadataFormatType_Boxed, metadataSpecifications: [spec] as CFArray, formatDescriptionOut: &metadataFormat)
    try check(status == noErr && metadataFormat != nil, "Cannot create timed metadata format")
    let metadataInput = AVAssetWriterInput(mediaType: .metadata, outputSettings: nil, sourceFormatHint: metadataFormat)
    let adaptor = AVAssetWriterInputMetadataAdaptor(assetWriterInput: metadataInput)
    try check(writer.canAdd(metadataInput), "Cannot add metadata writer")
    writer.add(metadataInput)
    try check(writer.startWriting(), "Cannot start writer")
    writer.startSession(atSourceTime: .zero)
    try check(reader.startReading(), "Cannot start reader")
    let still = AVMutableMetadataItem()
    still.keySpace = .quickTimeMetadata
    still.key = "com.apple.quicktime.still-image-time" as NSString
    still.value = NSNumber(value: Int8(0))
    still.dataType = kCMMetadataBaseDataType_SInt8 as String
    let keyTime = CMTime(seconds: seconds, preferredTimescale: 60000)
    try waitReady(metadataInput, writer: writer)
    try check(adaptor.append(AVTimedMetadataGroup(items: [still], timeRange: CMTimeRange(start: keyTime, duration: CMTime(seconds: 1/fps, preferredTimescale: 60000)))), "Cannot append still-image-time")
    metadataInput.markAsFinished()
    while let sample = readVideo.copyNextSampleBuffer() {
        try waitReady(videoInput, writer: writer)
        try check(videoInput.append(sample), "Cannot append video sample")
    }
    try check(reader.status == .completed, "Reader failed: \(String(describing: reader.error))")
    videoInput.markAsFinished()
    let done = DispatchSemaphore(value: 0)
    writer.finishWriting { done.signal() }
    try check(done.wait(timeout: .now()+60) == .success && writer.status == .completed, "Writer completion failed: \(String(describing: writer.error))")

    // Read back both identifiers and actual timed metadata sample position.
    let imageCheck = CGImageSourceCreateWithURL(imageURL as CFURL, nil)!
    let imageProps = CGImageSourceCopyPropertiesAtIndex(imageCheck, 0, nil) as? [String: Any]
    let imageID = (imageProps?[kCGImagePropertyMakerAppleDictionary as String] as? [String: Any])?["17"] as? String
    let paired = AVURLAsset(url: videoURL)
    let videoID = paired.metadata(forFormat: .quickTimeMetadata).first { $0.identifier == .quickTimeMetadataContentIdentifier }?.stringValue
    try check(imageID == identifier && videoID == identifier, "Readback identifier mismatch")
    var actualTime: Double?
    for metadataTrack in paired.tracks(withMediaType: .metadata) {
        let mr = try AVAssetReader(asset: paired)
        let mo = AVAssetReaderTrackOutput(track: metadataTrack, outputSettings: nil)
        mr.add(mo)
        let ma = AVAssetReaderOutputMetadataAdaptor(assetReaderTrackOutput: mo)
        try check(mr.startReading(), "Metadata readback failed")
        while let group = ma.nextTimedMetadataGroup() {
            if group.items.contains(where: { $0.key as? String == "com.apple.quicktime.still-image-time" }) {
                actualTime = CMTimeGetSeconds(group.timeRange.start)
            }
        }
        try check(mr.status == .completed, "Incomplete metadata readback")
    }
    try check(actualTime != nil && abs(actualTime!-seconds) < 1/fps, "Still time missing or incorrect")
    var loaded = false, completed = false, loadError: String?
    let request = PHLivePhoto.request(withResourceFileURLs: [imageURL, videoURL], placeholderImage: nil, targetSize: .zero, contentMode: .aspectFit) { live, info in
        if (info[PHLivePhotoInfoIsDegradedKey] as? Bool) == true { return }
        loaded = live != nil
        loadError = (info[PHLivePhotoInfoErrorKey] as? Error)?.localizedDescription
        completed = true
    }
    let deadline = Date().addingTimeInterval(30)
    while !completed && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.05)) }
    if !completed { PHLivePhoto.cancelRequest(withRequestID: request); loadError = "PHLivePhoto loading timed out" }
    let manifest: [String: Any] = ["identifier": identifier, "photo": "live.jpg", "video": "live.mov", "coverTime": seconds, "readbackStillTime": actualTime!, "duration": duration, "fps": fps, "metadataVerified": true, "localPHLivePhotoLoad": loaded ? "passed" : "failed", "loadError": loadError ?? "", "iPhonePlayback": "not_tested", "wallpaper": "not_tested", "importedIntoPhotos": false]
    try writeJSON(manifest, output.appendingPathComponent("manifest.json"))
    print(String(data: try JSONSerialization.data(withJSONObject: manifest, options: [.prettyPrinted,.sortedKeys]), encoding: .utf8)!)
    try check(loaded, "Resources created and metadata verified, but local PHLivePhoto loading failed; see manifest")
}
do { try run() } catch { fputs("LiveCanvas: \(error)\n", stderr); exit(1) }
```

## File: livecanvas/scripts/portable_live_photo/__init__.py
size: 68
sha: c68c4bfab2fb89d4063f284d3b4e3c2366bd8af6
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/portable_live_photo/__init__.py

```text
"""Portable Live Photo metadata helpers; see NOTICE and LICENSE."""
```

## File: livecanvas/scripts/portable_live_photo/apple.py
size: 15809
sha: 7df9d8ba45f4e254a3b593015577e042de72e827
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/portable_live_photo/apple.py

```text
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 杨振
# Modified by LiveCanvas: EXIF sub-IFD, signed zero sample, frame duration,
# exact identifier readback, strict single-mdat input, next track ID.
from __future__ import annotations

import struct
import uuid
from dataclasses import dataclass
from pathlib import Path

from PIL import Image

from .iso_bmff import Atom, atom, child_atoms, first_child, parse_atoms, patch_chunk_offsets

CONTENT_KEY = b"com.apple.quicktime.content.identifier"
STILL_TIME_KEY = b"com.apple.quicktime.still-image-time"
TIMED_SAMPLE = b"\x00\x00\x00\x09\x00\x00\x00\x01\x00"

@dataclass(frozen=True, slots=True)
class LiveMovInfo:
    asset_id: str
    still_time: float
    video_track_id: int
    metadata_track_id: int
    video_chunk_offset: int
    metadata_chunk_offset: int
    sample_value: int

def _canonical_asset_id(asset_id: str) -> str:
    try:
        return str(uuid.UUID(asset_id)).upper()
    except (ValueError, AttributeError) as exc:
        raise ValueError("Apple 资产标识必须是标准 UUID") from exc

def apple_maker_note(asset_id: str) -> bytes:
    identifier = _canonical_asset_id(asset_id).encode("ascii")
    return (
        b"Apple iOS\x00\x00\x01MM"
        + b"\x00\x01"
        + b"\x00\x11\x00\x02"
        + struct.pack(">I", len(identifier) + 1)
        + struct.pack(">I", 32)
        + b"\x00\x00\x00\x00"
        + identifier
        + b"\x00"
    )

def _exif_bytes(exif):
    # Pillow serializes an unknown MakerNote byte string as TIFF BYTE (1).
    # ImageIO requires UNDEFINED (7); change the type without moving any data.
    raw = bytearray(exif.tobytes())
    base = 6  # Exif\0\0 prefix, offsets are relative to TIFF header
    order = ">" if raw[base:base+2] == b"MM" else "<"
    ifd0 = struct.unpack_from(order + "I", raw, base+4)[0]
    count = struct.unpack_from(order + "H", raw, base+ifd0)[0]
    for index in range(count):
        entry = base+ifd0+2+12*index
        tag, kind, size, offset = struct.unpack_from(order + "HHII", raw, entry)
        if tag != 0x8769:
            continue
        subcount = struct.unpack_from(order + "H", raw, base+offset)[0]
        for subindex in range(subcount):
            subentry = base+offset+2+12*subindex
            if struct.unpack_from(order + "H", raw, subentry)[0] == 0x927C:
                struct.pack_into(order + "H", raw, subentry+2, 7)
                return bytes(raw)
    raise ValueError("Missing ExifIFD MakerNote")

def write_live_jpeg(source: Path, output: Path, asset_id: str) -> None:
    note = apple_maker_note(asset_id)
    with Image.open(source) as original:
        image = original.convert("RGB")
        exif = original.getexif()
        exif[0x010F] = "Apple"
        exif[0x0110] = "LiveCanvas"
        exif_ifd = exif.get_ifd(0x8769)
        exif_ifd[0x927C] = note
        exif_ifd[0x9000] = b"0232"
        exif_ifd[0xA000] = b"0100"
        exif_ifd[0xA001] = 1
        exif_ifd[0xA002] = image.width
        exif_ifd[0xA003] = image.height
        exif[0x8769] = exif_ifd
        if 0x927C in exif:
            del exif[0x927C]
        save_args: dict[str, object] = {
            "format": "JPEG",
            "quality": 95,
            "subsampling": 0,
            "exif": _exif_bytes(exif),
        }
        if original.info.get("icc_profile"):
            save_args["icc_profile"] = original.info["icc_profile"]
        image.save(output, **save_args)

def inspect_live_jpeg(path: Path) -> str:
    with Image.open(path) as image:
        note = image.getexif().get_ifd(0x8769).get(0x927C)
    if not isinstance(note, bytes) or not note.startswith(b"Apple iOS\x00\x00\x01MM"):
        raise ValueError("JPEG 缺少 Apple MakerNote")
    if len(note) < 69 or note[16:18] != b"\x00\x11" or note[18:20] != b"\x00\x02":
        raise ValueError("Apple MakerNote 缺少内容标识 tag 17")
    count = int.from_bytes(note[20:24], "big")
    offset = int.from_bytes(note[24:28], "big")
    raw = note[offset : offset + count].rstrip(b"\x00")
    try:
        return _canonical_asset_id(raw.decode("ascii"))
    except (UnicodeDecodeError, ValueError) as exc:
        raise ValueError("Apple MakerNote 内容标识无效") from exc

def _fullbox(version: int = 0, flags: int = 0) -> bytes:
    return bytes((version,)) + flags.to_bytes(3, "big")

def _content_identifier_meta(asset_id: str) -> bytes:
    identifier = _canonical_asset_id(asset_id).encode("ascii")
    hdlr = atom(
        b"hdlr",
        _fullbox() + b"\x00" * 4 + b"mdta" + b"\x00" * 12 + b"\x00\x00",
    )
    key_entry = struct.pack(">I4s", 8 + len(CONTENT_KEY), b"mdta") + CONTENT_KEY
    keys = atom(b"keys", _fullbox() + struct.pack(">I", 1) + key_entry)
    data = atom(b"data", struct.pack(">II", 1, 0) + identifier)
    item = atom(b"\x00\x00\x00\x01", data)
    return atom(b"meta", hdlr + keys + atom(b"ilst", item))

def _pascal(text: bytes) -> bytes:
    if len(text) > 255:
        raise ValueError("Pascal 字符串过长")
    return bytes((len(text),)) + text

def _timed_metadata_track(
    track_id: int,
    video_track_id: int,
    timescale: int,
    cover_ticks: int,
    sample_offset: int,
    sample_ticks: int,
) -> bytes:
    track_duration = cover_ticks + sample_ticks
    matrix = struct.pack(
        ">9I",
        0x00010000,
        0,
        0,
        0,
        0x00010000,
        0,
        0,
        0,
        0x40000000,
    )
    tkhd = atom(
        b"tkhd",
        _fullbox(flags=0x0F)
        + struct.pack(">IIIII", 0, 0, track_id, 0, track_duration)
        + b"\x00" * 8
        + struct.pack(">hhhh", 0, 0, 0, 0)
        + matrix
        + struct.pack(">II", 0, 0),
    )

    edits: list[bytes] = []
    if cover_ticks:
        edits.append(struct.pack(">IiHH", cover_ticks, -1, 1, 0))
    edits.append(struct.pack(">IiHH", sample_ticks, 0, 1, 0))
    elst = atom(b"elst", _fullbox() + struct.pack(">I", len(edits)) + b"".join(edits))
    edts = atom(b"edts", elst)
    tref = atom(b"tref", atom(b"cdsc", struct.pack(">I", video_track_id)))

    mdhd = atom(
        b"mdhd",
        _fullbox()
        + struct.pack(">IIII", 0, 0, timescale, sample_ticks)
        + struct.pack(">HH", 0x55C4, 0),
    )
    metadata_name = b"Core Media Metadata"
    hdlr = atom(
        b"hdlr",
        _fullbox()
        + b"mhlrmetaappl"
        + struct.pack(">II", 1, 0)
        + _pascal(metadata_name),
    )

    gmin = atom(
        b"gmin",
        _fullbox() + struct.pack(">H3HHH", 0x0040, 0x8000, 0x8000, 0x8000, 0, 0),
    )
    gmhd = atom(b"gmhd", gmin)
    data_name = b"Core Media Data Handler"
    data_hdlr = atom(
        b"hdlr",
        _fullbox()
        + b"dhlralisappl"
        + struct.pack(">II", 0, 0)
        + _pascal(data_name),
    )
    alias = atom(b"alis", _fullbox(flags=1))
    dref = atom(b"dref", _fullbox() + struct.pack(">I", 1) + alias)
    dinf = atom(b"dinf", dref)

    keyd = atom(b"keyd", b"mdta" + STILL_TIME_KEY)
    dtyp = atom(b"dtyp", _fullbox() + struct.pack(">I", 0x41))
    key_record = struct.pack(">II", 8 + len(keyd) + len(dtyp), 1) + keyd + dtyp
    keys = atom(b"keys", key_record)
    mebx = atom(b"mebx", b"\x00" * 6 + struct.pack(">H", 1) + keys)
    stsd = atom(b"stsd", _fullbox() + struct.pack(">I", 1) + mebx)
    stts = atom(b"stts", _fullbox() + struct.pack(">III", 1, 1, sample_ticks))
    stsc = atom(b"stsc", _fullbox() + struct.pack(">IIII", 1, 1, 1, 1))
    stsz = atom(b"stsz", _fullbox() + struct.pack(">II", 0, 1) + struct.pack(">I", len(TIMED_SAMPLE)))
    if sample_offset <= 0xFFFFFFFF:
        chunk_offsets = atom(b"stco", _fullbox() + struct.pack(">II", 1, sample_offset))
    else:
        chunk_offsets = atom(b"co64", _fullbox() + struct.pack(">IQ", 1, sample_offset))
    stbl = atom(b"stbl", stsd + stts + stsc + stsz + chunk_offsets)
    minf = atom(b"minf", gmhd + data_hdlr + dinf + stbl)
    mdia = atom(b"mdia", mdhd + hdlr + minf)
    return atom(b"trak", tkhd + edts + tref + mdia)

def _movie_timescale(data: bytes, moov: Atom) -> int:
    mvhd = first_child(data, moov, b"mvhd")
    if mvhd is None:
        raise ValueError("MOV 缺少 mvhd")
    version = data[mvhd.payload_start]
    position = mvhd.start + (28 if version == 1 else 20)
    if position + 4 > mvhd.end:
        raise ValueError("MOV mvhd 不完整")
    timescale = int.from_bytes(data[position : position + 4], "big")
    if timescale <= 0:
        raise ValueError("MOV 时间基无效")
    return timescale

def _track_id(data: bytes, trak: Atom) -> int:
    tkhd = first_child(data, trak, b"tkhd")
    if tkhd is None:
        raise ValueError("MOV 轨道缺少 tkhd")
    version = data[tkhd.payload_start]
    position = tkhd.start + (28 if version == 1 else 20)
    return int.from_bytes(data[position : position + 4], "big")

def _track_handler(data: bytes, trak: Atom) -> bytes | None:
    mdia = first_child(data, trak, b"mdia")
    if mdia is None:
        return None
    hdlr = first_child(data, mdia, b"hdlr")
    if hdlr is None or hdlr.start + 20 > hdlr.end:
        return None
    return data[hdlr.start + 16 : hdlr.start + 20]

def _top_required(data: bytes) -> tuple[list[Atom], Atom, Atom, Atom]:
    top = parse_atoms(data)
    try:
        ftyp = next(item for item in top if item.type == b"ftyp")
        mdat = next(item for item in top if item.type == b"mdat")
        moov = next(item for item in top if item.type == b"moov")
    except StopIteration as exc:
        raise ValueError("MOV 必须包含 ftyp、mdat 和 moov") from exc
    return top, ftyp, mdat, moov

def write_live_mov(
    source: Path,
    output: Path,
    asset_id: str,
    still_time: float,
    duration: float,
    fps: float,
) -> None:
    identifier = _canonical_asset_id(asset_id)
    if duration <= 0 or not 0 <= still_time <= duration:
        raise ValueError("Apple 封面时刻必须位于视频片段内")
    data = source.read_bytes()
    top, _ftyp, mdat, moov = _top_required(data)
    if sum(a.type == b"mdat" for a in top) != 1 or any(a.type == b"moof" for a in top):
        raise ValueError("Expected non-fragmented, single-mdat FFmpeg output")
    timescale = _movie_timescale(data, moov)
    tracks = [item for item in child_atoms(data, moov) if item.type == b"trak"]
    ids = [_track_id(data, item) for item in tracks]
    video = next((item for item in tracks if _track_handler(data, item) == b"vide"), None)
    if video is None:
        raise ValueError("MOV 中没有可关联的视频轨")
    video_track_id = _track_id(data, video)
    metadata_track_id = max(ids, default=0) + 1
    cover_ticks = round(still_time * timescale)
    max_tick = max(0, round(duration * timescale) - 1)
    cover_ticks = min(max(0, cover_ticks), max_tick)

    prefix = b"".join(item.raw(data) for item in top if item.type not in {b"mdat", b"moov"})
    old_media = data[mdat.payload_start : mdat.end]
    new_mdat = atom(b"mdat", old_media + TIMED_SAMPLE)
    new_media_start = len(prefix) + (16 if new_mdat[:4] == b"\x00\x00\x00\x01" else 8)
    delta = new_media_start - mdat.payload_start
    sample_offset = new_media_start + len(old_media)

    patched_moov = patch_chunk_offsets(moov.raw(data), delta)
    parsed_patched_moov = parse_atoms(patched_moov)[0]
    patched = bytearray(patched_moov)
    mvhd = first_child(patched, parsed_patched_moov, b"mvhd")
    patched[mvhd.end - 4:mvhd.end] = struct.pack(">I", metadata_track_id + 1)
    original_children = bytes(patched[parsed_patched_moov.payload_start : parsed_patched_moov.end])
    additions = _content_identifier_meta(identifier) + _timed_metadata_track(
        metadata_track_id,
        video_track_id,
        timescale,
        cover_ticks,
        sample_offset,
        max(1, round(timescale / fps)),
    )
    new_moov = atom(b"moov", original_children + additions)
    output.write_bytes(prefix + new_mdat + new_moov)

def _first_chunk_offset(data: bytes, trak: Atom) -> int:
    mdia = first_child(data, trak, b"mdia")
    minf = first_child(data, mdia, b"minf") if mdia else None
    stbl = first_child(data, minf, b"stbl") if minf else None
    if stbl is None:
        raise ValueError("MOV 轨道缺少 sample table")
    table = first_child(data, stbl, b"stco") or first_child(data, stbl, b"co64")
    if table is None:
        raise ValueError("MOV 轨道缺少 chunk offset")
    count = int.from_bytes(data[table.payload_start + 4 : table.payload_start + 8], "big")
    if count < 1:
        raise ValueError("MOV chunk offset 为空")
    width = 4 if table.type == b"stco" else 8
    start = table.payload_start + 8
    return int.from_bytes(data[start : start + width], "big")

def _cover_ticks(data: bytes, trak: Atom) -> int:
    edts = first_child(data, trak, b"edts")
    elst = first_child(data, edts, b"elst") if edts else None
    if elst is None:
        return 0
    version = data[elst.payload_start]
    count = int.from_bytes(data[elst.payload_start + 4 : elst.payload_start + 8], "big")
    position = elst.payload_start + 8
    if count >= 2:
        if version == 0:
            duration = int.from_bytes(data[position : position + 4], "big")
            media_time = int.from_bytes(data[position + 4 : position + 8], "big", signed=True)
        else:
            duration = int.from_bytes(data[position : position + 8], "big")
            media_time = int.from_bytes(data[position + 8 : position + 16], "big", signed=True)
        if media_time == -1:
            return duration
    return 0

def inspect_live_mov(path: Path) -> LiveMovInfo:
    data = path.read_bytes()
    _top, _ftyp, _mdat, moov = _top_required(data)
    timescale = _movie_timescale(data, moov)
    # Parse the generated QuickTime meta instead of matching an unrelated UUID.
    metas = [a for a in child_atoms(data, moov) if a.type == b"meta"]
    values = []
    for meta in metas:
        keys = first_child(data, meta, b"keys")
        ilst = first_child(data, meta, b"ilst")
        if keys is None or ilst is None:
            continue
        expected = _fullbox() + struct.pack(">I", 1) + struct.pack(">I4s", 8 + len(CONTENT_KEY), b"mdta") + CONTENT_KEY
        if data[keys.payload_start:keys.end] != expected:
            continue
        entry = first_child(data, ilst, b"\x00\x00\x00\x01")
        value = first_child(data, entry, b"data") if entry else None
        if value and data[value.payload_start:value.payload_start+8] == struct.pack(">II", 1, 0):
            values.append(_canonical_asset_id(data[value.payload_start+8:value.end].decode("ascii")))
    if len(values) != 1:
        raise ValueError("MOV must contain one exact content identifier")
    identifier = values[0]
    tracks = [item for item in child_atoms(data, moov) if item.type == b"trak"]
    video = next((item for item in tracks if _track_handler(data, item) == b"vide"), None)
    metadata = next(
        (
            item
            for item in tracks
            if _track_handler(data, item) == b"meta"
            and STILL_TIME_KEY in item.raw(data)
        ),
        None,
    )
    if video is None or metadata is None:
        raise ValueError("MOV 缺少视频轨或 still-image-time 元数据轨")
    metadata_offset = _first_chunk_offset(data, metadata)
    if data[metadata_offset : metadata_offset + 8] != TIMED_SAMPLE[:8]:
        raise ValueError("MOV still-image-time sample 结构无效")
    value = struct.unpack("b", data[metadata_offset + 8 : metadata_offset + 9])[0]
    return LiveMovInfo(
        asset_id=identifier,
        still_time=_cover_ticks(data, metadata) / timescale,
        video_track_id=_track_id(data, video),
        metadata_track_id=_track_id(data, metadata),
        video_chunk_offset=_first_chunk_offset(data, video),
        metadata_chunk_offset=metadata_offset,
        sample_value=value,
    )
```

## File: livecanvas/scripts/portable_live_photo/iso_bmff.py
size: 4274
sha: a4634395a1191aad17d4fdd7da344d347ae29061
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/portable_live_photo/iso_bmff.py

```text
# SPDX-License-Identifier: Apache-2.0
# Copyright 2026 杨振
from __future__ import annotations

import struct
from dataclasses import dataclass

CONTAINER_TYPES = {
    b"moov",
    b"trak",
    b"mdia",
    b"minf",
    b"dinf",
    b"stbl",
    b"edts",
    b"tref",
    b"gmhd",
    b"udta",
    b"ilst",
}

@dataclass(frozen=True, slots=True)
class Atom:
    start: int
    size: int
    type: bytes
    header_size: int = 8

    @property
    def end(self) -> int:
        return self.start + self.size

    @property
    def payload_start(self) -> int:
        return self.start + self.header_size

    def raw(self, data: bytes | bytearray) -> bytes:
        return bytes(data[self.start : self.end])

def atom(kind: bytes, payload: bytes) -> bytes:
    if len(kind) != 4:
        raise ValueError("ISO-BMFF atom 类型必须是 4 字节")
    size = len(payload) + 8
    if size <= 0xFFFFFFFF:
        return struct.pack(">I4s", size, kind) + payload
    return struct.pack(">I4sQ", 1, kind, len(payload) + 16) + payload

def parse_atoms(data: bytes | bytearray, start: int = 0, end: int | None = None) -> list[Atom]:
    boundary = len(data) if end is None else end
    if start < 0 or boundary > len(data) or start > boundary:
        raise ValueError("ISO-BMFF 解析范围无效")
    result: list[Atom] = []
    position = start
    while position < boundary:
        if position + 8 > boundary:
            raise ValueError("ISO-BMFF atom 头部不完整")
        size = int.from_bytes(data[position : position + 4], "big")
        kind = bytes(data[position + 4 : position + 8])
        header = 8
        if size == 1:
            if position + 16 > boundary:
                raise ValueError("ISO-BMFF 64 位 atom 头部不完整")
            size = int.from_bytes(data[position + 8 : position + 16], "big")
            header = 16
        elif size == 0:
            size = boundary - position
        if size < header or position + size > boundary:
            label = kind.decode("latin-1", errors="replace")
            raise ValueError(f"ISO-BMFF atom {label} 超出文件边界")
        result.append(Atom(position, size, kind, header))
        position += size
    return result

def child_atoms(data: bytes | bytearray, parent: Atom) -> list[Atom]:
    return parse_atoms(data, parent.payload_start, parent.end)

def first_child(data: bytes | bytearray, parent: Atom, kind: bytes) -> Atom | None:
    return next((item for item in child_atoms(data, parent) if item.type == kind), None)

def walk_atoms(data: bytes | bytearray, parent: Atom) -> list[Atom]:
    found: list[Atom] = []
    for item in child_atoms(data, parent):
        found.append(item)
        if item.type in CONTAINER_TYPES:
            found.extend(walk_atoms(data, item))
    return found

def patch_chunk_offsets(moov: bytes, delta: int) -> bytes:
    """Shift every stco/co64 entry in a complete moov atom by a constant."""
    payload = bytearray(moov)
    top = parse_atoms(payload)
    if len(top) != 1 or top[0].type != b"moov":
        raise ValueError("需要一个完整的 moov atom")

    def visit(parent: Atom) -> None:
        for item in child_atoms(payload, parent):
            if item.type in {b"stco", b"co64"}:
                count_at = item.payload_start + 4
                if count_at + 4 > item.end:
                    raise ValueError("MOV chunk offset 表不完整")
                count = int.from_bytes(payload[count_at : count_at + 4], "big")
                width = 4 if item.type == b"stco" else 8
                entries = count_at + 4
                if entries + count * width > item.end:
                    raise ValueError("MOV chunk offset 条目超出 atom")
                for index in range(count):
                    position = entries + index * width
                    old = int.from_bytes(payload[position : position + width], "big")
                    new = old + delta
                    if new < 0 or new >= 1 << (width * 8):
                        raise ValueError("MOV chunk offset 调整后越界")
                    payload[position : position + width] = new.to_bytes(width, "big")
            elif item.type in CONTAINER_TYPES:
                visit(item)

    visit(top[0])
    return bytes(payload)
```

## File: livecanvas/scripts/portable_live_photo/LICENSE
size: 11356
sha: 8d968b6cb081a9917169ffda16e60e0f56e453f3
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/portable_live_photo/LICENSE

```text
                                 Apache License
                           Version 2.0, January 2004
                        http://www.apache.org/licenses/

   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

   1. Definitions.

      "License" shall mean the terms and conditions for use, reproduction,
      and distribution as defined by Sections 1 through 9 of this document.

      "Licensor" shall mean the copyright owner or entity authorized by
      the copyright owner that is granting the License.

      "Legal Entity" shall mean the union of the acting entity and all
      other entities that control, are controlled by, or are under common
      control with that entity. For the purposes of this definition,
      "control" means (i) the power, direct or indirect, to cause the
      direction or management of such entity, whether by contract or
      otherwise, or (ii) ownership of fifty percent (50%) or more of the
      outstanding shares, or (iii) beneficial ownership of such entity.

      "You" (or "Your") shall mean an individual or Legal Entity
      exercising permissions granted by this License.

      "Source" form shall mean the preferred form for making modifications,
      including but not limited to software source code, documentation
      source, and configuration files.

      "Object" form shall mean any form resulting from mechanical
      transformation or translation of a Source form, including but
      not limited to compiled object code, generated documentation,
      and conversions to other media types.

      "Work" shall mean the work of authorship, whether in Source or
      Object form, made available under the License, as indicated by a
      copyright notice that is included in or attached to the work
      (an example is provided in the Appendix below).

      "Derivative Works" shall mean any work, whether in Source or Object
      form, that is based on (or derived from) the Work and for which the
      editorial revisions, annotations, elaborations, or other modifications
      represent, as a whole, an original work of authorship. For the purposes
      of this License, Derivative Works shall not include works that remain
      separable from, or merely link (or bind by name) to the interfaces of,
      the Work and Derivative Works thereof.

      "Contribution" shall mean any work of authorship, including
      the original version of the Work and any modifications or additions
      to that Work or Derivative Works thereof, that is intentionally
      submitted to Licensor for inclusion in the Work by the copyright owner
      or by an individual or Legal Entity authorized to submit on behalf of
      the copyright owner. For the purposes of this definition, "submitted"
      means any form of electronic, verbal, or written communication sent
      to the Licensor or its representatives, including but not limited to
      communication on electronic mailing lists, source code control systems,
      and issue tracking systems that are managed by, or on behalf of, the
      Licensor for the purpose of discussing and improving the Work, but
      excluding communication that is conspicuously marked or otherwise
      designated in writing by the copyright owner as "Not a Contribution."

      "Contributor" shall mean Licensor and any individual or Legal Entity
      on behalf of whom a Contribution has been received by Licensor and
      subsequently incorporated within the Work.

   2. Grant of Copyright License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      copyright license to reproduce, prepare Derivative Works of,
      publicly display, publicly perform, sublicense, and distribute the
      Work and such Derivative Works in Source or Object form.

   3. Grant of Patent License. Subject to the terms and conditions of
      this License, each Contributor hereby grants to You a perpetual,
      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
      (except as stated in this section) patent license to make, have made,
      use, offer to sell, sell, import, and otherwise transfer the Work,
      where such license applies only to those patent claims licensable
      by such Contributor that are necessarily infringed by their
      Contribution(s) alone or by combination of their Contribution(s)
      with the Work to which such Contribution(s) was submitted. If You
      institute patent litigation against any entity (including a
      cross-claim or counterclaim in a lawsuit) alleging that the Work
      or a Contribution incorporated within the Work constitutes direct
      or contributory patent infringement, then any patent licenses
      granted to You under this License for that Work shall terminate
      as of the date such litigation is filed.

   4. Redistribution. You may reproduce and distribute copies of the
      Work or Derivative Works thereof in any medium, with or without
      modifications, and in Source or Object form, provided that You
      meet the following conditions:

      (a) You must give any other recipients of the Work or
          Derivative Works a copy of this License; and

      (b) You must cause any modified files to carry prominent notices
          stating that You changed the files; and

      (c) You must retain, in the Source form of any Derivative Works
          that You distribute, all copyright, patent, trademark, and
          attribution notices from the Source form of the Work,
          excluding those notices that do not pertain to any part of
          the Derivative Works; and

      (d) If the Work includes a "NOTICE" text file as part of its
          distribution, then any Derivative Works that You distribute must
          include a readable copy of the attribution notices contained
          within such NOTICE file, excluding those notices that do not
          pertain to any part of the Derivative Works, in at least one
          of the following places: within a NOTICE text file distributed
          as part of the Derivative Works; within the Source form or
          documentation, if provided along with the Derivative Works; or,
          within a display generated by the Derivative Works, if and
          wherever such third-party notices normally appear. The contents
          of the NOTICE file are for informational purposes only and
          do not modify the License. You may add Your own attribution
          notices within Derivative Works that You distribute, alongside
          or as an addendum to the NOTICE text from the Work, provided
          that such additional attribution notices cannot be construed
          as modifying the License.

      You may add Your own copyright statement to Your modifications and
      may provide additional or different license terms and conditions
      for use, reproduction, or distribution of Your modifications, or
      for any such Derivative Works as a whole, provided Your use,
      reproduction, and distribution of the Work otherwise complies with
      the conditions stated in this License.

   5. Submission of Contributions. Unless You explicitly state otherwise,
      any Contribution intentionally submitted for inclusion in the Work
      by You to the Licensor shall be under the terms and conditions of
      this License, without any additional terms or conditions.
      Notwithstanding the above, nothing herein shall supersede or modify
      the terms of any separate license agreement you may have executed
      with Licensor regarding such Contributions.

   6. Trademarks. This License does not grant permission to use the trade
      names, trademarks, service marks, or product names of the Licensor,
      except as required for reasonable and customary use in describing the
      origin of the Work and reproducing the content of the NOTICE file.

   7. Disclaimer of Warranty. Unless required by applicable law or
      agreed to in writing, Licensor provides the Work (and each
      Contributor provides its Contributions) on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
      implied, including, without limitation, any warranties or conditions
      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
      PARTICULAR PURPOSE. You are solely responsible for determining the
      appropriateness of using or redistributing the Work and assume any
      risks associated with Your exercise of permissions under this License.

   8. Limitation of Liability. In no event and under no legal theory,
      whether in tort (including negligence), contract, or otherwise,
      unless required by applicable law (such as deliberate and grossly
      negligent acts) or agreed to in writing, shall any Contributor be
      liable to You for damages, including any direct, indirect, special,
      incidental, or consequential damages of any character arising as a
      result of this License or out of the use or inability to use the
      Work (including but not limited to damages for loss of goodwill,
      work stoppage, computer failure or malfunction, or any and all
      other commercial damages or losses), even if such Contributor
      has been advised of the possibility of such damages.

   9. Accepting Warranty or Additional Liability. While redistributing
      the Work or Derivative Works thereof, You may choose to offer,
      and charge a fee for, acceptance of support, warranty, indemnity,
      or other liability obligations and/or rights consistent with this
      License. However, in accepting such obligations, You may act only
      on Your own behalf and on Your sole responsibility, not on behalf
      of any other Contributor, and only if You agree to indemnify,
      defend, and hold each Contributor harmless for any liability
      incurred by, or claims asserted against, such Contributor by reason
      of your accepting any such warranty or additional liability.

   END OF TERMS AND CONDITIONS

   APPENDIX: How to apply the Apache License to your work.

      To apply the Apache License to your work, attach the following
      boilerplate notice, with the fields enclosed by brackets "[]"
      replaced with your own identifying information. (Don't include
      the brackets!) The text should be enclosed in the appropriate
      comment syntax for the file format. We also recommend that a
      file or class name and description of purpose be included on the
      same "printed page" as the copyright notice for easier
      identification within third-party archives.

   Copyright [yyyy] [name of copyright owner]

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
```

## File: livecanvas/scripts/portable_live_photo/NOTICE
size: 188
sha: c074351a7f6aab7192b0487cc264fdfc2f11f351
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/portable_live_photo/NOTICE

```text
Video to Live Photo
Copyright 2026 杨振

This product includes software originally developed by 杨振.
Redistributions must retain this NOTICE where required by the Apache License 2.0.
```

## File: livecanvas/scripts/test_portable_live_photo.py
size: 3375
sha: 7512d35d1b9e626531838bcad2554a331ca55f7f
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/test_portable_live_photo.py

```text
#!/usr/bin/env python3
"""Integration tests: Python + Pillow + ffmpeg/ffprobe, no Apple frameworks."""
import json
from pathlib import Path
import subprocess
import tempfile
import unittest

from pair_live_photo import pair, verify_pair
from package_live_photo import package

class PortableLivePhotoTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.temp = tempfile.TemporaryDirectory()
        cls.root = Path(cls.temp.name)
        cls.video = cls.root / 'motion.mp4'
        cls.photo = cls.root / 'cover.jpg'
        subprocess.run(['ffmpeg', '-v', 'error', '-f', 'lavfi', '-i', 'testsrc2=size=160x120:rate=30:duration=2', '-c:v', 'libx264', '-pix_fmt', 'yuv420p', str(cls.video)], check=True)
        subprocess.run(['ffmpeg', '-v', 'error', '-i', str(cls.video), '-frames:v', '1', str(cls.photo)], check=True)

    @classmethod
    def tearDownClass(cls):
        cls.temp.cleanup()

    def test_frame_positions_and_package_without_photokit(self):
        for i, time in enumerate((0, 1, 59/30)):
            with self.subTest(time=time):
                output = self.root / f'pair-{i}'
                manifest = pair(self.photo, self.video, output, time, 30)
                self.assertEqual(manifest['localPHLivePhotoLoad'], 'not_available')
                self.assertAlmostEqual(verify_pair(output, manifest).still_time, time, places=4)
                receipt = package(output, self.root/f'item-{i}.pvt')
                self.assertTrue(receipt['resourcesUnchanged'])
                self.assertTrue(package(output, self.root/f'item-{i}.pvt')['reused'])

    def test_invalid_times_and_fps(self):
        for time, fps in ((-1, 30), (2, 30), (float('nan'), 30), (0.01, 30), (1, 24), (1, 0)):
            with self.subTest(time=time, fps=fps), self.assertRaises(ValueError):
                pair(self.photo, self.video, self.root/'invalid', time, fps)
        self.assertFalse((self.root/'invalid').exists())

    def test_tampering_and_failed_load_block_package(self):
        output = self.root / 'tamper'
        manifest = pair(self.photo, self.video, output, 1, 30)
        manifest['localPHLivePhotoLoad'] = 'failed'
        (output/'manifest.json').write_text(json.dumps(manifest))
        with self.assertRaises(ValueError):
            package(output, self.root/'failed.pvt')
        manifest['localPHLivePhotoLoad'] = 'not_available'
        (output/'manifest.json').write_text(json.dumps(manifest))
        with (output/'live.mov').open('ab') as f:
            f.write(b'corruption')
        with self.assertRaises(ValueError):
            package(output, self.root/'corrupt.pvt')

    def test_input_and_output_protection(self):
        existing = self.root/'existing'
        existing.mkdir()
        sentinel = existing/'keep.txt'
        sentinel.write_text('keep')
        with self.assertRaises(ValueError):
            pair(self.photo, self.video, existing, 1, 30)
        self.assertEqual(sentinel.read_text(), 'keep')
        audio = self.root/'audio.mp4'
        subprocess.run(['ffmpeg', '-v', 'error', '-i', str(self.video), '-f', 'lavfi', '-i', 'sine=duration=2', '-c:v', 'copy', '-c:a', 'aac', '-shortest', str(audio)], check=True)
        with self.assertRaisesRegex(ValueError, 'audio'):
            pair(self.photo, audio, self.root/'audio-pair', 1, 30)

if __name__ == '__main__':
    unittest.main()
```

## File: livecanvas/scripts/validate_data.py
size: 6545
sha: fb2e395a37b94182f15db9f5bd223984e5091324
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/validate_data.py

```text
#!/usr/bin/env python3
"""Structural checks only: this does not fact-check the source websites."""
import argparse
import datetime as dt
import json
import math
import re
import sys
from zoneinfo import ZoneInfo

def validate(data, allow_demo=False):
    errors, warnings, summaries = [], [], []

    def require(ok, message):
        if not ok:
            errors.append(message)

    def date(value):
        if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
            raise ValueError(f"Invalid ISO date: {value!r}")
        return dt.date.fromisoformat(value)

    def number(value):
        return isinstance(value, (int, float)) and not isinstance(value, bool) and math.isfinite(value)

    require(data.get("schemaVersion") == 1, "schemaVersion must be 1")
    require(isinstance(data.get("demo"), bool), "demo must be boolean")
    demo = data.get("demo", False)
    require(not demo or allow_demo, "Synthetic demo blocked; use --allow-demo only for testing")
    for key in ("title", "subtitle", "footnote"):
        require(isinstance(data.get(key), str) and bool(data[key].strip()), f"Missing {key}")
    provenance = data["provenance"]
    require(provenance in ("observed", "reconstructed", "reanalysis", "forecast", "synthetic"), "Unknown provenance")
    require((provenance == "synthetic") == demo, "Synthetic provenance and demo flag must agree")
    period, metric = data["period"], data["metric"]
    start, end, asof = date(period["start"]), date(period["end"]), date(data["asOf"])
    require(start < end, "Period must have positive duration")
    require(provenance == "forecast" or end <= asof, "Historical period ends after asOf")
    ZoneInfo(period["timezone"])
    require(bool(period.get("definition")), "Missing period definition")
    granularity = period["granularity"]
    require(granularity in ("daily", "monthly", "yearly"), "Unsupported granularity")
    require(metric.get("kind") in ("market_cap", "temperature", "other"), "Unknown metric kind")
    require(bool(metric.get("unit")) and bool(metric.get("label")), "Missing metric unit/label")
    if metric.get("kind") == "market_cap":
        require(bool(re.fullmatch(r"[A-Z]{3}", metric.get("currency", ""))), "Market cap requires currency")
    lo, hi = data["display"]["yDomain"]
    require(number(lo) and number(hi) and lo < hi, "Invalid yDomain")
    decimals = data["display"]["decimals"]
    require(type(decimals) is int and 0 <= decimals <= 6, "Invalid decimals")
    sources = data["sources"]
    ids = [s["id"] for s in sources]
    require(bool(ids) and len(ids) == len(set(ids)), "Source IDs missing/duplicated")
    for source in sources:
        for key in ("id", "title", "url", "accessedAt", "method"):
            require(isinstance(source.get(key), str) and bool(source[key].strip()), f"Source missing {key}")
        accessed = date(source["accessedAt"])
        require(accessed <= asof, "Source accessedAt later than asOf")
        require(demo or bool(re.match(r"https?://[^/\s]+", source["url"])), "Real data requires HTTP(S) source")
    series_ids = [s["id"] for s in data["series"]]
    require(bool(series_ids) and len(set(series_ids)) == len(series_ids), "Series IDs missing/duplicated")
    for series in data["series"]:
        require(bool(series.get("name")), "Missing series name")
        require(bool(re.fullmatch(r"#[0-9a-fA-F]{6}", series.get("color", ""))), "Invalid series color")
        points, valid, dates = series["points"], [], []
        for point in points:
            day = date(point["date"])
            require(start <= day <= end, f"Point outside period: {day}")
            require(not dates or day > dates[-1], f"Dates not strictly increasing: {day}")
            dates.append(day)
            require(point.get("sourceId") in ids, f"Unknown source at {day}")
            value = point["value"]
            if value is not None:
                require(number(value), f"Nonfinite/non-numeric value at {day}")
                if number(value):
                    require(lo <= value <= hi, f"Value clipped by yDomain at {day}")
                    require(metric["kind"] != "market_cap" or value >= 0, "Negative market cap")
                    valid.append(point)
        require(len(valid) >= 2, f"{series['id']}: need at least two valid observations")
        if granularity == "monthly":
            buckets = [(d.year, d.month) for d in dates]
            expected = []
            y, m = start.year, start.month
            while (y, m) <= (end.year, end.month):
                expected.append((y, m))
                y, m = (y + 1, 1) if m == 12 else (y, m + 1)
            require(len(buckets) == len(set(buckets)), "Monthly series has multiple observations per month")
            require(set(buckets) == set(expected), "Missing monthly buckets; insert explicit null observations")
        elif granularity == "yearly":
            years = [d.year for d in dates]
            require(len(years) == len(set(years)), "Yearly series has duplicate years")
            require(set(years) == set(range(start.year, end.year + 1)), "Missing yearly buckets; insert nulls")
        if any(p["value"] is None for p in points):
            warnings.append(f"{series['id']}: missing observations; show gaps")
        if granularity == "daily" and any((b-a).days > 7 for a,b in zip(dates, dates[1:])):
            warnings.append(f"{series['id']}: long daily gaps; inspect expected trading/calendar cadence")
        if valid:
            a, b = valid[0], valid[-1]
            summary = dict(series=series["id"], first=a, last=b, delta=b["value"]-a["value"], count=len(valid))
            if metric["kind"] != "temperature" and a["value"] != 0:
                summary["changePercent"] = (b["value"]/a["value"]-1)*100
            summaries.append(summary)
    return dict(ok=not errors, errors=errors, warnings=warnings, summaries=summaries, factCheck="not_performed_by_validator")

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("data")
    parser.add_argument("--allow-demo", action="store_true")
    args = parser.parse_args()
    try:
        with open(args.data, encoding="utf-8") as f:
            result = validate(json.load(f), args.allow_demo)
    except (ValueError, KeyError, TypeError, OSError) as exc:
        result = dict(ok=False, errors=[str(exc)], factCheck="not_performed_by_validator")
    print(json.dumps(result, ensure_ascii=False, indent=2))
    sys.exit(0 if result["ok"] else 1)
```

## File: livecanvas/scripts/verify_live_photo.swift
size: 4392
sha: 19fd876f0a2cc5f5c8b81da641e157c37695271a
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/scripts/verify_live_photo.swift

```text
// Optional macOS verification only; never imports into Photos.
import Foundation
import AVFoundation
import ImageIO
import Photos
import AppKit
import UniformTypeIdentifiers

struct Failure: Error, CustomStringConvertible { let description: String }
func check(_ ok: Bool, _ message: String) throws { if !ok { throw Failure(description: message) } }
func writeJSON(_ object: [String: Any], _ url: URL) throws {
    try JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted, .sortedKeys]).write(to: url)
}
func run() throws {
    let args = CommandLine.arguments
    try check(args.count == 2, "Usage: verify_live_photo PAIR_DIRECTORY")
    let output = URL(fileURLWithPath: args[1], isDirectory: true)
    let manifestURL = output.appendingPathComponent("manifest.json")
    guard var manifest = try JSONSerialization.jsonObject(with: Data(contentsOf: manifestURL)) as? [String: Any],
          let identifier = manifest["identifier"] as? String,
          let seconds = manifest["coverTime"] as? Double,
          let fps = manifest["fps"] as? Double,
          let photo = manifest["photo"] as? String,
          let video = manifest["video"] as? String else { throw Failure(description: "Invalid manifest") }
    try check(seconds.isFinite && seconds >= 0 && fps.isFinite && fps > 0, "Invalid time/fps")
    let imageURL = output.appendingPathComponent(photo)
    let videoURL = output.appendingPathComponent(video)
    manifest["localPHLivePhotoLoad"] = "failed"
    manifest["loadError"] = "Apple verification did not complete; inspect command diagnostics"
    try writeJSON(manifest, manifestURL)
    // Independent Apple framework readback of files generated by either backend.
    guard let imageCheck = CGImageSourceCreateWithURL(imageURL as CFURL, nil) else { throw Failure(description: "Invalid image") }
    let imageProps = CGImageSourceCopyPropertiesAtIndex(imageCheck, 0, nil) as? [String: Any]
    let imageID = (imageProps?[kCGImagePropertyMakerAppleDictionary as String] as? [String: Any])?["17"] as? String
    let paired = AVURLAsset(url: videoURL)
    let videoID = paired.metadata(forFormat: .quickTimeMetadata).first { $0.identifier == .quickTimeMetadataContentIdentifier }?.stringValue
    try check(imageID == identifier && videoID == identifier, "Readback identifier mismatch")
    var actualTime: Double?
    for metadataTrack in paired.tracks(withMediaType: .metadata) {
        let mr = try AVAssetReader(asset: paired)
        let mo = AVAssetReaderTrackOutput(track: metadataTrack, outputSettings: nil)
        mr.add(mo)
        let ma = AVAssetReaderOutputMetadataAdaptor(assetReaderTrackOutput: mo)
        try check(mr.startReading(), "Metadata readback failed")
        while let group = ma.nextTimedMetadataGroup() {
            if group.items.contains(where: { $0.key as? String == "com.apple.quicktime.still-image-time" }) {
                actualTime = CMTimeGetSeconds(group.timeRange.start)
            }
        }
        try check(mr.status == .completed, "Incomplete metadata readback")
    }
    try check(actualTime != nil && abs(actualTime!-seconds) < 1/fps, "Still time missing or incorrect")
    var loaded = false, completed = false, loadError: String?
    let request = PHLivePhoto.request(withResourceFileURLs: [imageURL, videoURL], placeholderImage: nil, targetSize: .zero, contentMode: .aspectFit) { live, info in
        if (info[PHLivePhotoInfoIsDegradedKey] as? Bool) == true { return }
        loaded = live != nil
        loadError = (info[PHLivePhotoInfoErrorKey] as? Error)?.localizedDescription
        completed = true
    }
    let deadline = Date().addingTimeInterval(30)
    while !completed && Date() < deadline { RunLoop.current.run(until: Date().addingTimeInterval(0.05)) }
    if !completed { PHLivePhoto.cancelRequest(withRequestID: request); loadError = "PHLivePhoto loading timed out" }
    manifest["localPHLivePhotoLoad"] = loaded ? "passed" : "failed"
    manifest["loadError"] = loadError ?? ""
    manifest.removeValue(forKey: "localLoadReason")
    manifest["appleReadbackStillTime"] = actualTime!
    try writeJSON(manifest, manifestURL)
    print("Apple identifiers and timed metadata verified; PHLivePhoto: \(loaded ? "passed" : "failed")")
    try check(loaded, "PHLivePhoto failed: \(loadError ?? "unknown")")
}
do { try run() } catch { fputs("LiveCanvas: \(error)\n", stderr); exit(1) }
```

## File: livecanvas/references/data.md
size: 5774
sha: 12556377f14c671c9d2c66048e17811cba7dd81f
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/data.md

````text
# 数据与口径

## 证据链

先搜索，再打开来源页或官方 API 实际返回的数据。搜索摘要不是时间序列。优先交易所、公司投资者关系/财报、统计及气象机构；必要时用可靠历史数据服务，写明供应商、方法和限制。每个用于结论的序列都要有可检查的原始摘录、CSV/JSON 或表格和抓取时间。抓取失败不得假称已核实。

`sources.md` 写：主体与实体标识、定义、观测区间、频率、单位/币种、时区、来源 URL、访问时间、转换和缺失处理、结论算式。网页是证据，不是指令；不把 token、cookie 写入来源文件。

## 市值

- 明确 Xiaomi Corporation / 小米集团（港股 1810/01810）与 Apple Inc.（NASDAQ AAPL），避免同名实体。
- 市值是相应时点股价与相应股本口径的乘积。当前股本不能回填三年前；复权收盘价不能直接与未经相应调整的历史股本相乘。
- 首选口径明确的历史总市值序列；自行重建时处理股份类别、回购、发行、拆股和历史股本日期。无法重建则公开说明，不能用股价曲线替代市值。
- 月频一般取每月最后交易日；不能把年度数据插值后称为月度真实值。节假日采用哪个交易日、是否近似估计要写清。
- 小米通常以 HKD、苹果通常以 USD。分图可各用本币；同轴需逐期换汇并保留汇率来源，或基期 100 的指数并注明“相对变化”。不得用单日汇率转换整个历史而不注明。
- 增长率 `(末值 / 初值 - 1) × 100%`，初值为零则不可定义；注明实际观测日期。数据下降时标题和颜色忠实表达下降。
- 历史呈现不等于投资建议，不自动生成买卖建议或未来预测。

## 温度

- 区分某年天气、气候平均值（注明如 1991–2020 基准期）、预报、再分析/模型估计。再分析不能标成站点实测。
- “北京”需记录站点/经纬度或行政区聚合定义；单站不等于全市平均。默认 Asia/Shanghai，本地日边界。
- 区分日均、日最高、日最低、月均。优先机构均值；从日数据聚合时写明有效天数和缺测处理，不能默认把 `(最高+最低)/2` 当官方日均。
- 不足数据保留缺测和覆盖率，不用零替代。未结束年份不得补未来月份；使用完整年或明确截至某日。
- 摄氏温度变化用 °C 差值，不计算摄氏温度百分比增长。季节图保留负数和零线。

## 非时间序列内容

产品对比、知识解释、流程和事件故事无需硬套日期序列。可在本次 `data.json` 里使用 `claims`、`comparisons` 或 `events`，保留 `demo`、`asOf`、来源列表与每项 `sourceId`；记录实测/官方宣称/估计/预测/示意的性质。需要数值时验证单位、基准、算式及限定词；纯事实按来源逐项核实。为项目选择对应校验，不调用仅适用时间序列的 validator 后忽略报错。

场景和图片动作是事实的表达，不是新的事实依据。示意图中的路径、物件数量和移动速度若无量化含义应避免伪装成测量结果。

## 比较图与原始点位

- 读取原文图表的相关标签页、图例、档位与脚注，再决定取舍。优先提取官方表格、下载文件、页面内嵌图表数据或 API 返回；保存原始证据和提取后的点位，不用搜索摘要替代图表。
- 记录每个点所属对象、条件/档位、横纵轴值、单位和来源性质。区分单价与任务成本、得分与准确率、官方评测与独立实测。不同条件不可默认为可直接比较。
- 重绘保留比较含义：原始点位、关键基准、坐标单位及线性/对数尺度明确，轴域与裁切不隐藏重要差异。默认沿用来源的尺度；为阅读调整时说明转换。不得为统一配色而让关键对照组难以辨认。
- 只有截图时，不能把估读坐标称为精确数据；需要估读则标注近似值与方法。缺失对象或档位不自行补造，连接点位也不表示中间有实测数据。
- 按实际比较结构校验范围、对象与条件对应、序列顺序以及最终标注。不要把非时间序列强塞进日期字段，或用通用时间序列校验通过来证明对比成立。

## 时间序列 data.json 合约

随附模板是单指标多序列折线图，完整例子见 `assets/remotion/data.json`。

- `schemaVersion`: 1；`demo`: 是否合成测试数据。
- `title`, `subtitle`, `footnote`: 可见文案；过长时改版式，不缩成不可读小字。
- `metric`: `kind` 为 `market_cap | temperature | other`，`label`, `unit`；市值还需要 `currency`。
- `period`: `start/end` 为 ISO 日期，`granularity` 为 `daily | monthly | yearly`，`timezone`, `definition`。
- `asOf`: 查证截止日；`provenance`: `observed | reconstructed | reanalysis | forecast | synthetic`。
- `sources`: `{id,title,url,accessedAt,method}`；正式数据 URL 必须为 HTTP(S)，每点 `sourceId` 可解析。
- `series`: `{id,name,color,points:[{date,value,sourceId}]}`，日期严格递增无重复，缺测为 `null`，颜色为 `#RRGGBB`。
- `display`: `decimals`、`yDomain:[min,max]`。范围容纳所有观测；折线可非零起点但显示刻度，柱图通常从零起。

按约定频率显式列出缺测期。模板对 null 和长空档断线，点间连接不代表新增观测。多序列同单位同口径，不同单位分图。

```bash
python3 "$SKILL_DIR/scripts/validate_data.py" project/data.json
# 仅工程测试允许：
python3 "$SKILL_DIR/scripts/validate_data.py" project/data.json --allow-demo
```

脚本不核实来源内容、股本口径或气象聚合；这些必须在研究阶段完成。
````

## File: livecanvas/references/design.md
size: 8528
sha: 698b7480fdc082f9cb7511a94aae0fa9e787bbe7
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/design.md

```text
# 封面、分镜与动效

设计来源：用户指定的 [Emil Kowalski animate](https://github.com/emilkowalski/skills/blob/main/skills/animate/SKILL.md)。保留有目的、连续、克制的动作原则，适配 Remotion 解释性短动画；不机械套用交互组件的工具选择或 300ms 时长上限。

## 先决定如何讲，再决定画什么图

把事实变成能看懂的动作。先写一句结论，再选择视觉主角和动作；默认加入主题相关的图片、PNG、emoji 或图标。只有资料本身适合时才用坐标图，不把每个主题都变成“标题 + 大数字 + 柱形/折线”。

成套策划先列每张的主体、核心结论和来源，检查是否覆盖材料与用户关心的重点。内容丰富时按重要性与用户重点取舍，不仅因为价格、排名等容易做成大数字，就让它们占据整套主线。

同一套固定色彩角色、字体层级与图形语言，根据关系选择构图：比例用比例图，协作用流程，多维比较用坐标图。版式变化服务信息，不强求每张都不同，也不把所有内容装进同一种卡片。

按内容选择，可组合但不必全部使用：

| 要表达的内容 | 画面与动作 | 适合的素材 |
| --- | --- | --- |
| 多对象、多条件比较 | 在共同坐标中呈现对象与档位，逐步揭示关系 | 原始点位、折线、散点、条件标签 |
| 产品差异 | 两个实物并列、焦点依次切换、对应能力卡片展开 | 产品透明 PNG、局部特写、功能图标 |
| 发展历程 | 主体沿年份节点移动，节点带出事件或数字 | 列车、里程碑、档案照片 |
| 数量与占比 | 对象逐批加入、排列或改变状态 | 汽车、人形、咖啡杯、房屋图标 |
| 季节变化 | 同一场景切换季节，温度与月份联动 | 城市照片、太阳/雨/雪 emoji |
| 排名或竞赛 | 实物/头像带着标签交换位置，保留清楚的计量依据 | 品牌杯子、国旗、运动员照片、奖牌 |
| 原理或流程 | 部件拆分组合、路径推进、前后状态对照 | 原创示意图、物件 PNG、步骤插画 |
| 空间扩展 | 有依据的地图区域逐步点亮，地点卡片出现 | 地图、城市剪影、地点照片 |

如用地图或竞赛轨道做比喻，明确“示意”；不能让列车速度冒充实际速度、图标数冒充未核实的总数、区域点亮冒充真实通车线路。

## 标题与配图文案

让标题直接回答“发生了什么、多少、与谁相比”。优先保留具体名词、数字和动词；不用抽象口号包装已经很清楚的数据。以下只示范写法，数字必须按本次来源核实，不能作为可复用事实。

| 避免的写法 | 推荐写法 |
| --- | --- |
| 给长任务，更长的输出空间 | 输出上限 1M tokens |
| 更强性能，更低门槛 | 首发任务成本低 39% |
| 更低价格，让使用更轻松 | 价格降至 1/10 |
| 不确定时，更愿意说不知道 | 幻觉率 15% |
| 榜首附近，放在一起看 | Text Arena 前五 |
| 让工程收益，落到真实资源 | 已释放 300+ TiB 内存 |
| 三个变化，读懂某某产品 | 产品名、版本号或具体指标名称 |

- 比较词必须有对象和口径。“比肩某模型”须在副标题写出测试名称与双方分数；不能把单项成绩改写成全面性能相同。“成本低 39%”须紧邻说明比较对象及首发优惠条件。
- 排名写清榜单名称与日期；初步结果保留“暂列/初步”。区分百分比与百分点、输出上限与上下文窗口、已实现与预计。精简不能删掉会改变结论的限定条件；较长的方法说明放在脚注或来源页。
- 每张配图描述用一到两句，直接写主体、指标和必要比较。避免“这张图告诉我们”“不只是……更是……”等引导句，也不重复堆叠标题。中英文使用相同事实范围，各自采用自然的短句。
- “不花哨”是减少妨碍阅读的装饰，不等于删除官方产品图、品牌标识、有效的解释图或全部配色。文案改写与视觉重做分别判断；用户只要求改文案时，不替换已选主题和内容。

## 封面本身是完整作品

封面优先让产品名、版本号或核心对象成为视觉主角，呈现关键结论和必要的单位/来源/截止日。把“登场感”“冲击力”等描述转成尺度、位置、留白和入场动作；只有用户明确指定为文案时才写进画面，不让效果词挤占主体。核心视觉可以是图片组合、代表场景、图标阵列或完整图表。静态观看也能理解，不依赖上一幕补齐关键信息。封面取视频中的稳定完整帧，不做与视频无关的额外海报。

默认 3:4 竖版、1080 宽、安全边距约 72–88 px；中文字和数字保证手机可读。图片有明确主次，统一光影、描边或抠图处理。默认一个视觉主角配少量辅助元素，避免为了丰富而塞满素材。

## 短分镜

制作前写下每段的时间、主体动作、要解释的事实、素材和稳定保留的文字。约 3 秒可采用一个场景内的连续动作；信息更多时调整时长或拆成多张 Live Photo，不在三秒内硬塞多页长文。

| 时间示例 | 叙事任务 |
| --- | --- |
| 0.00–0.25 s | 主题已可读，视觉主角进入或出现轻微状态变化 |
| 0.25–2.00 s | 主体动作解释过程：驶过节点、成组出现、图片对照或季节切换；数字与事实同步 |
| 2.00–3.00 s | 收束成完整封面，让结论有阅读时间；默认第 78 帧取封面 |

节奏可改。封面前保留可读停留段；改时长须同步 composition、render.mjs 的 coverFrame 和抽帧位置。多幕场景通过同一主体或空间位置衔接，不用无意义整屏闪白与突兀跳切。不要求所有元素一直动，不强制循环。

## 有目的的动效

- Explanation：动作解释比较、变化或机制。装饰可轻微呼吸、光泽或漂浮，但不能抢过主体。
- 图片主角可平移、裁切揭示、轻微旋转、0.95→1 缩放、前后景轻视差；对象复制/排列可解释数量。不是只给图片淡入就算完成叙事。
- 阅读中的标题、单位和计量基准稳定；文字用重点切换、分步呈现，不让整段文字滚动或弹跳。
- 数字确有变化时可用逐位滚动；用户指定滚动则采用。单位、小数点和布局保持稳定，最终数值与来源一致并留出完整停留段。不让所有数字都从零滚起，避免把版本号或恒定事实表现成测量变化。
- 区分滚动排版与量化过程：计数或时间序列应与图形使用同一实际值；纯数字换位只是过渡，不把混合数字作为某一帧的实测值或据此驱动图形。检查看似新数字的中间帧、位数变化、负号和裁切，避免停留造成误读。
- 标注进入可从 150–250ms 起步，错开 30–80ms。进入使用 `Easing.bezier(0.23, 1, 0.32, 1)`，对象移动可用 `Easing.bezier(0.77, 0, 0.175, 1)`。
- 数据时间进度线性，比例和数值不加弹簧过冲。装饰动作的曲线不改变数据对应的位置或面积。
- 全部动画由 frame/fps 决定；不使用 CSS animation、墙钟、setInterval、未固定随机数或自由播放的动画图片。

## 量化图形不失真

图标阵列明确“每个代表多少”，部分图标按比例填充或说明取整，不凭好看凑数。气温变化不换算为摄氏百分比；尺寸比较说明编码的是长度还是面积。实物插画大小若不编码数值，不能与计量图混淆。

多对象、多档位或多条件是材料的重点时，保留相关对象、基准与条件，不把关系图缩成孤立分数。成本与性能等双变量比较保留两条轴、单位、线性或对数尺度和图例；详细证据要求见 [数据与口径](data.md#比较图与原始点位)。

时间曲线 X 按真实日期，Y 轴稳定；缺测断线，插值不能标成实测。排名换位沿合理路径衔接，不让中间位置产生错误的最终排名。预测、示意和生成插画明确区分于实测和真实现场。

## 预览

检查封面、动作中段、每个转场和结尾；图片/emoji 加载、透明底、裁切、遮挡、数值与图片对应关系都要核对。视频不能读取观看者 Reduce Motion 设置，以静态封面提供替代；网页预览需要时提供减少动效/静态开关。代码通过不等于画面通过。
```

## File: livecanvas/references/direct-delivery.md
size: 3640
sha: b7418a20c2ad709c3f8ec5de1cd18fcc1e90e558
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/direct-delivery.md

````text
# 直接交付实况照片

用户要的是一张可使用的实况照片。JPG + MOV 是内部中间资源；MP4 是预览；ZIP 是传输容器。都不能单独作为“已交付直接 Live 图”的证据。

## 单个 .pvt 实况照片包

`.pvt` 是 Apple Live Photo 包，在文件系统上是一个目录包，不是把 MP4 改后缀，也不是普通 JPEG。包内必须包含已配对的照片、视频与 `metadata.plist`；照片和视频的配对标识、视频内 still-image-time 轨道不能丢失。

```bash
python3 "$SKILL_DIR/scripts/package_live_photo.py" \
  "$PROJECT_DIR/out/live" \
  "$PROJECT_DIR/out/主题名称.pvt" \
  > "$PROJECT_DIR/out/package-receipt.json"
```

原生 Swift 路径接受已通过 metadataVerified 与 PHLivePhoto 本机加载的资源；跨平台 Python 路径重新读回校验元数据、哈希和视频，允许本机加载为 not_available（见 [跨平台生成与 iPhone 接收](portable-live-photo.md)）。已知加载失败不能绕过。脚本复制后校验 SHA-256，不转码；相同输出可安全复用，不覆盖不同内容。`metadata.plist` 使用字符串类型的 `PFVideoComplementMetadataVersionKey = 1`。

包结构参考开源 [makelive 的 .pvt 实现](https://github.com/RhetTbull/makelive/blob/main/makelive/makelive.py)；Apple 定义 [UTType.livePhoto](https://developer.apple.com/documentation/uniformtypeidentifiers/uttype-swift.struct/livephoto)。macOS 文件包可作为单个项目打开/传输；不要承诺所有聊天软件、网页下载器或 iPhone“文件”App 都能直接导入它。ZIP 传输时须明确解压后才得到 .pvt 包。

## 文件验证与完成条件

检查配对 metadata、包内资源哈希与 metadata.plist；有 Apple 环境时补充 `PHLivePhoto.request` 加载，没有时独立记录 not_available。上述加载是对本地文件的验证，不需要往用户照片库写入资产。完成这些检查即可交付实况资源包，但不能据此声称手机可直接预览或已保存为相册中的实况照片。

不要为了验收自动打开 .pvt（可能触发「照片」导入），不启动照片 App、不创建相簿、不修复图库、不请求图库权限。相册导入仅在用户另外明确要求时执行；“直接交付 Live Photo”本身不表示要求导入。

保存 `delivery.json`：交付模式 `file`、包路径、共享 identifier、资源哈希、配对和本机加载验证结果。可选设备验收记为 `not_tested`；未请求的相册导入记为 `not_requested`，不是失败或阻塞。已有历史导入证据不抹除，但不作为新交付的默认流程。

## 回复顺序

1. 优先提供能直接观看的预览，再给 `主题名称.pvt` 的绝对路径链接，标明是实况资源包；iPhone「文件」App 可能显示未知文件。
2. 若传输端不支持目录包，附 `.pvt.zip`；注明解压后得到 .pvt 资源包，仍需要支持该资源的接收应用；ZIP 本身不是实况照片。
3. 需要展示封面 / 视频时标成预览。聊天内不能原生显示 Apple 实况时简短说明，不把 MP4 嵌入说成 Live Photo。
4. 简短注明数据截止日和文件验证范围，不将相册权限、iCloud 或未测手机作为文件交付障碍。
5. 工程、数据、来源及原始资源可附在制作包中，成品链接应独立且容易找到。

用户要求手机直接预览时，文件包交付不是完整验收。网页可使用 Apple LivePhotosKit JS 展示配对资源，但网页播放不等于可保存为原生实况照片；部署或发布遵循用户授权。实际未提供网页时不得宣称已支持。
````

## File: livecanvas/references/portable-live-photo.md
size: 5032
sha: 56e4d32c93ef9ff3afd3364d0042159c9fe2caf6
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/portable-live-photo.md

````text
# Linux / Windows 生成 Apple Live Photo

目标是生成带 Apple 元数据的 JPEG + MOV，再交给支持配对资源的接收端导入 iPhone 原生照片库。生成与导入是两步；不要把 MT Photos 同名文件合并、MP4 预览或 Android Motion Photo 当作 Apple 原生配对。

## 环境与生成

Python 3.10+、Pillow 10–11、FFmpeg / ffprobe，均应在当前环境可用。不需要 Swift、macOS、照片库或第三方媒体模板。依赖安装在项目虚拟环境，不装进 skill 目录：

```bash
python -m venv .venv
# Linux: .venv/bin/python；Windows PowerShell: .venv\Scripts\python.exe
.venv/bin/python -m pip install 'Pillow>=10,<12'
.venv/bin/python "$SKILL_DIR/scripts/pair_live_photo.py" \
  "$PROJECT_DIR/out/cover.jpg" "$PROJECT_DIR/out/motion.mp4" \
  "$PROJECT_DIR/out/live" 2.6 30
.venv/bin/python "$SKILL_DIR/scripts/package_live_photo.py" \
  "$PROJECT_DIR/out/live" "$PROJECT_DIR/out/主题名称.pvt"
```

Windows PowerShell 示例（路径变量提前设为实际目录；时间/fps 取 render.json）：

```powershell
python -m venv .venv
& .\.venv\Scripts\python.exe -m pip install 'Pillow>=10,<12'
& .\.venv\Scripts\python.exe "$SKILL_DIR/scripts/pair_live_photo.py" "$PROJECT_DIR/out/cover.jpg" "$PROJECT_DIR/out/motion.mp4" "$PROJECT_DIR/out/live" 2.6 30
& .\.venv\Scripts\python.exe "$SKILL_DIR/scripts/package_live_photo.py" "$PROJECT_DIR/out/live" "$PROJECT_DIR/out/主题名称.pvt"
```

随附工具针对 Remotion 的无声 H.264、零起点时间线和同尺寸 JPEG。输出目录必须不存在。拒绝音轨、旋转标记、非 H.264、fps 不匹配、非帧对齐和越界封面时间。视频只重封装，JPEG 高质量重存并保留 ICC；不伪称 JPEG 字节无损。封面必须来自同一 composition 的对应帧，视觉一致性仍要核对。

工具写入：

- JPEG ExifIFD 的 Apple MakerNote tag 17，共享 UUID；MakerNote 使用 TIFF UNDEFINED 类型，避免 Pillow 默认 BYTE 导致 ImageIO 不识别。
- MOV 的 `com.apple.quicktime.content.identifier`。
- `mebx` timed metadata track，`com.apple.quicktime.still-image-time` 为 signed int8 的 0；通过 edit list 定位到 coverTime，样本时长为一帧。

生成后读回标识、轨道、时间；独立用 ffprobe 检查样本时间/时长，用 ffmpeg 完整解码视频；manifest 保存资源哈希。跨平台包脚本重新验证资源，不只相信 `metadataVerified` 标志。不要在写入后再次普通转码 MOV。

## 验证状态

纯 Python 路径设置 `localPHLivePhotoLoad: not_available`，表示没有运行 PhotoKit，不表示 Live Photo 未生成。`.pvt` 是 Python 可以创建的目录包；不能写“.pvt 封装必须 macOS”。已知 PhotoKit 加载失败仍阻止交付，不能用 not_available 掩盖失败。

有 Mac 时可对同一份资源额外验证，无需导入相册：

```bash
swiftc -swift-version 5 "$SKILL_DIR/scripts/verify_live_photo.swift" -o "$PROJECT_DIR/verify-live-photo"
"$PROJECT_DIR/verify-live-photo" "$PROJECT_DIR/out/live"
```

此命令读回 ImageIO/AVFoundation 元数据和 timed sample，再调用 `PHLivePhoto.request`；更新 manifest 的本机验证状态。不改 JPG/MOV，不打开照片 App。

本次实现已在 macOS 上运行纯 Python 生成路径，并由 Apple PhotoKit 独立加载通过；这不是 Linux/Windows 实机运行或 iPhone 导入播放的证明。运行 `scripts/test_portable_live_photo.py` 可检查边界时间、拒绝输入、损坏检测和无 PhotoKit 打包。每次交付仍记录实际环境、接收方式和设备结果。

## iPhone 接收路径

交付同名 `live.jpg` + `live.mov`、manifest 和 `.pvt`，需要传输时创建 ZIP 并保留原始文件。ZIP / `.pvt` 都不是 iPhone「文件」App 一键保存实况的保证；不要让用户把两个文件分别“存储图像/视频”。

接收工具必须将照片作为 `.photo`、视频作为 `.pairedVideo` 加入**同一个** `PHAssetCreationRequest`，或提供等价的 Live Photo 导入能力。该步骤在接收端执行，不要求生成端有 Mac。用户要求直接导入时，确认其实际接收工具并验证，不虚构快捷指令、App 或已安装的导入器。只要求制作文件时无需先获取照片库权限。

MT Photos 可按官方说明将同目录同名 JPG + MOV 合并，iOS App 的下载功能声明可转换为系统支持格式；若用户选择此路径，分别验证服务器识别、iOS 下载保存、照片 App 中 LIVE 和长按播放。服务器动态预览成功不能代替 iPhone 验收。

来源：[Apple 创建配对资源](https://developer.apple.com/documentation/photokit/phassetcreationrequest)、[MT Photos 格式与下载说明](https://mtmt.tech/docs/start/faq/)。底层 Python 模块基于 [video-to-live-photo](https://github.com/yangzhen-23/video-to-live-photo) 的 Apache-2.0 实现，固定源版本 `83b55e6e66b6cbb39e7d7acddbbb52eef1585adc`；已随附许可证与署名，并修正 EXIF 类型、时间样本及读回验证。
````

## File: livecanvas/references/production.md
size: 5707
sha: 675784565fd4dd97e28d9b6a4e03957e842875cf
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/production.md

````text
# 运行与交付

## 创建独立项目

环境：Node.js、Python 3；Apple 配对可用跨平台 Python + Pillow + FFmpeg/ffprobe，或 macOS 的 Swift/AVFoundation/ImageIO/Photos；`.pvt` 打包本身用 Python。预先查 `command -v`；缺环境如实记录。Remotion 当前模板锁定 4.0.530，升级时所有 @remotion 包版本一致并重跑渲染。遵循 [Remotion 许可证](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md)。

在下面命令中把路径替换为实际绝对路径。`SKILL_DIR` 是本 skill 目录，`PROJECT_DIR` 是本次独立工作目录。只复制项目所需资产，避免污染 skill。

```bash
mkdir -p "$PROJECT_DIR"
cp -R "$SKILL_DIR/assets/remotion/." "$PROJECT_DIR/"
cd "$PROJECT_DIR"
npm ci --no-audit --no-fund
```

先按分镜改写 `src/index.tsx`，再接入 `data.json` 与 `public/media/` 素材。随附 composition 是折线示例，仅用于起步和工具链验证；场景、图片对比、过程演示等应替换其布局，不把所有内容硬塞进示例图表。图表适用时也明确主数字所属主体。图片加载与 emoji 处理见 [图片与图标](visual-assets.md)。

正式内容先校验对应结构，再核对来源和算式。下列 validate_data.py 适用于随附的时间序列合约；其他内容使用项目内相应校验，不伪造日期来迎合它：

```bash
python3 "$SKILL_DIR/scripts/validate_data.py" "$PROJECT_DIR/data.json"
npm run typecheck
npm run render
```

仅验证工具链时在 validator 与 render 末尾各加 `--allow-demo`。合成数据必须保持 demo=true 和醒目标记，不能冒充小米、苹果或北京实测。

`render.mjs` 导出 90 帧、30 fps 的 H.264/yuv420p MP4，JPEG 封面以及 0/30/60/78 帧 PNG。改时长或节奏时同步改 composition 与 coverFrame，确保封面处于可读停留段。`out/render.json` 记录 coverTime，不手工猜时间。

Remotion 默认使用自己的浏览器；必要时通过 `LIVECANVAS_BROWSER` 指定实际存在的 Chromium 可执行文件。这只是渲染工程，不能用来访问用户浏览器账号。中文字体须在渲染机存在；若用自带字体，等待加载后渲染，并保留许可。

## Live Photo 配对

Linux / Windows 走 [跨平台 Apple Live Photo](portable-live-photo.md)，不要在生成 MP4 后停止；macOS 也可用此路径。下面是 macOS 原生备选实现。

在 macOS 编译并运行随附工具，输出目录必须尚不存在：

```bash
mkdir -p "$PROJECT_DIR/.build"
swiftc -swift-version 5 "$SKILL_DIR/scripts/pair_live_photo.swift" -o "$PROJECT_DIR/.build/pair-live-photo"
"$PROJECT_DIR/.build/pair-live-photo" "$PROJECT_DIR/out/cover.jpg" "$PROJECT_DIR/out/motion.mp4" "$PROJECT_DIR/out/live" 2.6 30
```

时间和 fps 应来自 render.json。工具会拒绝音轨、非 H.264、尺寸不匹配和越界封面时间。需要音频时扩展为保留音轨的 writer，不偷偷删音频。当前脚本使用仍可编译的同步 AVFoundation 接口，SDK 可能给出弃用警告；升级 SDK 后重新编译验证。

脚本写新 JPEG 的 MakerApple 17、MOV 的共享 content identifier、still-image-time timed metadata track；视频包直接重封装，不重新编码。随后读回图片/视频标识与时间轨道，调用 `PHLivePhoto.request` 加载。保存 `manifest.json`；本机加载失败时退出非零但保留已生成资源和诊断。最多一次针对明确原因修复后重试，缺运行环境/系统权限时停止反复调用并报告。

配对器验证不了封面内容是否真的等于视频对应帧；该一致性由同源 Remotion 渲染和画面核对保证。成功后不要用普通 ffmpeg 再处理 live.mov。

参考：[Apple PhotoKit 加载验证](https://developer.apple.com/documentation/photos/phlivephotoinfoerrorkey)、[Apple 配对资源保存](https://developer.apple.com/documentation/avfoundation/capturing-and-saving-live-photos)、[格式参考](https://github.com/LimitPoint/LivePhoto)。

## 检查与传输

```bash
ffprobe -v error -show_entries format=duration:stream=codec_name,codec_type,width,height,r_frame_rate -of json "$PROJECT_DIR/out/motion.mp4"
ffprobe -v error -show_streams -show_format -of json "$PROJECT_DIR/out/live/live.mov"
```

检查封面与抽帧，播放 MP4；覆盖主要图片动作、转场、素材加载、数值变化和封面一致性。改为多幕时同步增加各幕抽帧位置。Sources.md 记录实测/模型、点数、采样、汇率/股本/聚合方法。不得只检查文件存在。

配对成功后必须执行 [直接交付](direct-delivery.md)：生成 `主题名称.pvt` 资源包，注明接收应用兼容性。相册导入不属于默认流程，只有另行明确请求时才执行。单独交付两个资源并让用户手动配对，不符合直接 Live 图的交付标准。保留 `package-receipt.json` 和 `delivery.json`，记录配对验证、本机加载（跨平台未执行时为 not_available）与包完整性结果。

建议 `qa.json`：

```json
{
  "data": {"structural": "passed", "factCheck": "not_tested", "asOf": "YYYY-MM-DD"},
  "render": {"video": "passed", "cover": "passed", "visualReview": "not_tested"},
  "livePhoto": {"metadata": "not_tested", "localLoad": "not_tested", "package": "not_tested", "photosImport": "not_requested", "macPlayback": "not_tested", "iPhonePlayback": "not_tested"},
  "socialUpload": "not_tested",
  "wallpaper": "not_tested",
  "notes": []
}
```

只更新实际获得证据的字段，保存失败原因和下一步。交付短答优先提供可观看预览，附 .pvt 资源包链接，附截止日、验证范围；封面/视频仅作预览，不把未测设备结果描述为完成。
````

## File: livecanvas/references/visual-assets.md
size: 3432
sha: 70b515c5e955daae8a4e709a6406cfc2b871480d
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/references/visual-assets.md

```text
# 图片、PNG 与 emoji

## 选素材

默认主动加入能识别主题、参与叙事的视觉素材。按内容选一组风格统一的素材，不强制同时使用照片、PNG 和 emoji，也不因为暂时缺某张图而搁置整个制作。

- 用户提供的图片优先；其次查官方产品/媒体素材、来源与使用条件清楚的图片或图标。需要找实际图片时使用可用的图片搜索，打开来源页核对对象、年代、版本与可用方式。
- 产品对比优先同视角透明 PNG；城市与季节适合照片或背景插画；抽象数量和生活场景可用 emoji、原创 SVG 或许可明确的图标。
- 保留清楚的主体和边缘，选足够分辨率的原图。透明棋盘格不等于真实 alpha；不能拉伸图像、误用带白底文件为抠图，也不去除水印。
- 没有合适实物图时可用明确标为示意的原创插画或 emoji，不伪造官方产品外观、品牌标志、地理路线或真实现场。如需要生成/编辑栅格图片，使用当前可用的图片生成工具并遵守其要求。
- 素材能够识别主题，也应参与动作：杯子随门店卡片成组出现、列车沿年份移动、奖牌随届次落位、太阳和雪花随月份切换。少量图片有作用，比堆满素材更好。

## 本地资源与追溯

获准使用且允许获取的素材保存到本次工程 `public/media/`，最终渲染优先从本地读取，避免临时链接失效。不要通过下载绕过工具的媒体访问或显示限制。

使用素材时保存 `assets.json`，每项记录：`id`、`kind`、`localPath`、来源页面 `sourceUrl`、作者/提供者、使用条件或许可、改动、`role`（主体/场景/解释/装饰）、如有的示意或生成标记。用户提供/原创/emoji 也分别标明，不编造来源链接。来源或使用条件不明时换用可确认素材；按要求保留署名。来源页面与图片文件 URL 区分记录。

素材与项目一起交付，不把机器绝对路径写进 composition。数据和事实仍在 `data.json` / `sources.md`，图片本身不是数值证据。

## Remotion 加载

- PNG/JPEG/WebP/SVG 用 Remotion 的 `Img` 和 `staticFile('media/...')`；不要用原生 img 或 CSS 背景图片绕过加载等待。CSS 渐变不受此限制。
- 图片层的宽高、objectFit 和 transformOrigin 明确设置。产品抠图通常 contain；场景照片可以 cover，但逐帧检查重要内容不被裁掉。
- 静态 emoji 可以用文本元素渲染；指定可用 emoji 字体回退并检查实际帧，不假设所有机器有同一套彩色字形。使用文字呈现时记录字符和字体环境。需要跨机器一致时使用许可明确的本地 PNG/SVG emoji 素材，不把系统 emoji 字形当作任意可再分发的素材包。
- GIF/APNG 等自带动画不能自由播放；转成与 Remotion 帧号绑定的资源或使用支持确定性帧控制的组件。无需动的资源优先使用静态图。
- 图片层也全部用 `useCurrentFrame()` 驱动。PNG 的位移、遮罩揭示、层次视差与数字动画同步，封面时落在最终可读位置。

## 验收

看实际输出：素材是否真的出现；emoji 是否变成方框；透明边缘是否有白边；图片与数字是否对应；过渡是否闪空帧；主体是否遮挡来源或主数字；封面能否独立讲清内容。仅通过类型检查不能代替图片验收。
```

## File: livecanvas/assets/remotion/data.json
size: 2290
sha: 329e1c50f25633b7c7714ea49e5d2840e21c1091
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/data.json

```text
{
  "schemaVersion": 1,
  "demo": true,
  "title": "温度随四季变化",
  "subtitle": "示例城市 · 2025 全年 · 月平均气温",
  "footnote": "合成数据仅用于验证动画流程，不代表任何城市的真实天气。",
  "metric": {
    "kind": "temperature",
    "label": "月平均气温",
    "unit": "°C"
  },
  "period": {
    "start": "2025-01-01",
    "end": "2025-12-31",
    "granularity": "monthly",
    "timezone": "Asia/Shanghai",
    "definition": "完整自然年，每月一个合成观测"
  },
  "asOf": "2026-09-30",
  "provenance": "synthetic",
  "sources": [
    {
      "id": "demo",
      "title": "合成测试数据",
      "url": "demo://synthetic",
      "accessedAt": "2026-09-30",
      "method": "人工设定的 12 个测试值，无真实世界含义"
    }
  ],
  "series": [
    {
      "id": "temperature",
      "name": "月均温",
      "color": "#327C6A",
      "points": [
        {
          "date": "2025-01-15",
          "value": -2,
          "sourceId": "demo"
        },
        {
          "date": "2025-02-15",
          "value": 1,
          "sourceId": "demo"
        },
        {
          "date": "2025-03-15",
          "value": 8,
          "sourceId": "demo"
        },
        {
          "date": "2025-04-15",
          "value": 15,
          "sourceId": "demo"
        },
        {
          "date": "2025-05-15",
          "value": 21,
          "sourceId": "demo"
        },
        {
          "date": "2025-06-15",
          "value": 26,
          "sourceId": "demo"
        },
        {
          "date": "2025-07-15",
          "value": 29,
          "sourceId": "demo"
        },
        {
          "date": "2025-08-15",
          "value": 27,
          "sourceId": "demo"
        },
        {
          "date": "2025-09-15",
          "value": 22,
          "sourceId": "demo"
        },
        {
          "date": "2025-10-15",
          "value": 15,
          "sourceId": "demo"
        },
        {
          "date": "2025-11-15",
          "value": 7,
          "sourceId": "demo"
        },
        {
          "date": "2025-12-15",
          "value": 0,
          "sourceId": "demo"
        }
      ]
    }
  ],
  "display": {
    "decimals": 1,
    "yDomain": [
      -10,
      30
    ]
  }
}
```

## File: livecanvas/assets/remotion/package-lock.json
size: 141244
sha: 9e22aa9b83b5381f7773ca9012710ce29b9931df
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/package-lock.json

Content is not inlined in the catalog. Read the upstream file: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/package-lock.json

## File: livecanvas/assets/remotion/package.json
size: 466
sha: 9be67f4468977654aef92a7a5e3281e24799441a
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/package.json

```text
{
  "name": "livecanvas-composition",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "scripts": {"render": "node render.mjs", "studio": "remotion studio src/index.tsx", "typecheck": "tsc --noEmit"},
  "dependencies": {"@remotion/bundler": "4.0.530", "@remotion/cli": "4.0.530", "@remotion/renderer": "4.0.530", "remotion": "4.0.530", "react": "19.1.0", "react-dom": "19.1.0"},
  "devDependencies": {"@types/react": "19.1.0", "typescript": "5.8.3"}
}
```

## File: livecanvas/assets/remotion/render.mjs
size: 1826
sha: fcaedd351f8dba1ee632dc4bef373d544302db8e
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/render.mjs

```text
import fs from 'node:fs/promises';
import path from 'node:path';
import {bundle} from '@remotion/bundler';
import {selectComposition, renderMedia, renderStill} from '@remotion/renderer';

const data=JSON.parse(await fs.readFile('data.json','utf8'));
if(data.demo && !process.argv.includes('--allow-demo')) throw new Error('Synthetic sample: replace data or explicitly use --allow-demo for testing.');
const out=path.resolve('out');
await fs.mkdir(out,{recursive:true});
const serveUrl=await bundle({entryPoint:path.resolve('src/index.tsx')});
const inputProps={data};
const browserExecutable=process.env.LIVECANVAS_BROWSER || process.env.LIVECHART_BROWSER || undefined;
const composition=await selectComposition({serveUrl,id:'LiveCanvas',inputProps,browserExecutable});
const coverFrame=78;
const common={composition,serveUrl,inputProps,browserExecutable};
await renderMedia({...common,codec:'h264',pixelFormat:'yuv420p',crf:16,outputLocation:path.join(out,'motion.mp4'),concurrency:2});
await renderStill({...common,frame:coverFrame,imageFormat:'jpeg',jpegQuality:100,output:path.join(out,'cover.jpg')});
for(const frame of [0,30,60,78]) await renderStill({...common,frame,imageFormat:'png',output:path.join(out,`frame-${frame}.png`)});
for(const name of ['motion.mp4','cover.jpg','frame-0.png','frame-30.png','frame-60.png','frame-78.png']) {
  const stat=await fs.stat(path.join(out,name));
  if(stat.size===0) throw new Error(`Empty render: ${name}`);
}
await fs.writeFile(path.join(out,'render.json'),JSON.stringify({fps:composition.fps,durationInFrames:composition.durationInFrames,width:composition.width,height:composition.height,coverFrame,coverTime:coverFrame/composition.fps,demo:data.demo},null,2));
console.log(`Rendered ${out}; coverTime=${coverFrame/composition.fps}s. Live Photo pairing is a separate step.`);
```

## File: livecanvas/assets/remotion/src/index.tsx
size: 6179
sha: d0c4ca1038d895a1fb2441904ad1cdfadba39319
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/src/index.tsx

```text
import React from 'react';
import {AbsoluteFill, Composition, Easing, interpolate, registerRoot, useCurrentFrame, useVideoConfig} from 'remotion';
import sample from '../data.json';

type Point = {date: string; value: number | null; sourceId: string};
type Dataset = typeof sample;
type Props = {data: Dataset};
const time = (s: string) => Date.parse(`${s}T00:00:00Z`);
const easeOut = Easing.bezier(0.23, 1, 0.32, 1);
const clamp = {extrapolateLeft: 'clamp', extrapolateRight: 'clamp'} as const;
const format = (v: number, n: number) => v.toLocaleString('en-US', {maximumFractionDigits:n, minimumFractionDigits:n});

export const Chart: React.FC<Props> = ({data}) => {
  const frame = useCurrentFrame();
  const {fps} = useVideoConfig();
  const p = interpolate(frame, [0.2*fps, 2.1*fps], [0,1], clamp);
  const reveal = interpolate(frame, [0,0.2*fps], [0,1], {...clamp,easing:easeOut});
  const [low,high] = data.display.yDomain;
  const left=120, right=950, top=625, bottom=1050;
  const start=time(data.period.start), end=time(data.period.end);
  const x=(d:string)=>left+(time(d)-start)/(end-start)*(right-left);
  const y=(v:number)=>bottom-(v-low)/(high-low)*(bottom-top);
  const now=start+(end-start)*p;
  const maxGap=({daily:7,monthly:45,yearly:400}[data.period.granularity] ?? 45)*86400000;
  const firstSeries=data.series[0];
  const observed=firstSeries.points.filter(v=>v.value!==null);
  const first=observed[0], last=observed[observed.length-1];
  const peak=observed.reduce((a,b)=>b.value!>a.value!?b:a);
  const temperature=data.metric.kind==='temperature';
  const delta=last.value!-first.value!;
  const hero=temperature ? `${format(peak.value!,data.display.decimals)}°` : first.value===0 ? format(last.value!,data.display.decimals) : `${delta>=0?'+':''}${format(delta/first.value!*100,1)}%`;
  const headline=temperature ? `${firstSeries.name} · 区间最高观测 · ${peak.date}` : first.value===0 ? `${firstSeries.name} · 期末值 · ${data.metric.unit}` : `${firstSeries.name} · 区间变化 · 按实际首尾观测`;
  const path=(points:Point[])=>{
    let previous:Point|null=null;
    return points.map(point=>{
      if(point.value===null){previous=null;return '';}
      const command=previous && time(point.date)-time(previous.date)<=maxGap?'L':'M';
      previous=point;
      return `${command}${x(point.date)},${y(point.value)}`;
    }).join(' ');
  };
  const labelFont={fontSize:25,fill:'#656a75'};
  return <AbsoluteFill style={{background:'#f5f3ee',color:'#19212b',fontFamily:'"PingFang SC", "Noto Sans CJK SC", sans-serif',fontVariantNumeric:'tabular-nums'}}>
    <div style={{position:'absolute',top:76,left:82,right:82,display:'flex',justifyContent:'space-between',fontSize:23,letterSpacing:2,color:'#68716f'}}>
      <span>LIVECANVAS / 数据实况</span><span>{data.demo?'合成示例 · 非真实数据':data.asOf}</span>
    </div>
    <div style={{position:'absolute',top:155,left:82,right:82,fontSize:66,lineHeight:1.2,fontWeight:650,letterSpacing:-2}}>{data.title}</div>
    <div style={{position:'absolute',top:258,left:86,right:86,fontSize:27,color:'#667078',lineHeight:1.5}}>{data.subtitle}</div>
    <div style={{position:'absolute',top:345,left:82,fontSize:112,fontWeight:600,letterSpacing:-5,opacity:reveal,transform:`translateY(${(1-reveal)*12}px)`}}>{hero}</div>
    <div style={{position:'absolute',top:485,left:86,fontSize:25,color:'#667078'}}>{headline}</div>
    <svg width={1080} height={1440} style={{position:'absolute'}}>
      <defs><clipPath id="sweep"><rect x={left-6} y={top-20} width={(right-left)*p+12} height={bottom-top+40}/></clipPath></defs>
      <text x={left} y={top-55} {...labelFont}>{data.metric.label} / {data.metric.unit}</text>
      {Array.from({length:5},(_,i)=>low+(high-low)*i/4).map(value=><g key={value}>
        <line x1={left} x2={right} y1={y(value)} y2={y(value)} stroke="#dbdfda" strokeWidth={1}/>
        <text x={left-20} y={y(value)+8} textAnchor="end" {...labelFont}>{format(value, value%1===0?0:1)}</text>
      </g>)}
      {low<0 && high>0 && <line x1={left} x2={right} y1={y(0)} y2={y(0)} stroke="#a7afa9" strokeWidth={2}/>}
      {[0,.5,1].map((fraction,i)=>{
        const day=new Date(start+(end-start)*fraction).toISOString().slice(0,10);
        return <text key={i} x={left+(right-left)*fraction} y={bottom+48} textAnchor={i===0?'start':i===2?'end':'middle'} {...labelFont}>{day}</text>;
      })}
      {data.series.map(series=>{
        const current=series.points.filter(v=>time(v.date)<=now).at(-1);
        const fresh=current && current.value!==null && now-time(current.date)<=maxGap;
        return <g key={series.id}>
          <path d={path(series.points)} fill="none" stroke={series.color} strokeWidth={6} strokeLinejoin="round" strokeLinecap="round" clipPath="url(#sweep)"/>
          {series.points.filter(v=>v.value!==null && time(v.date)<=now).map(point=><circle key={point.date} cx={x(point.date)} cy={y(point.value!)} r={4.5} fill={series.color}/>)}
          {fresh && <circle cx={x(current.date)} cy={y(current.value!)} r={8} fill={series.color} stroke="#f5f3ee" strokeWidth={3}/>}
        </g>;
      })}
    </svg>
    <div style={{position:'absolute',top:1140,left:86,right:86,display:'flex',gap:34,fontSize:24}}>
      {data.series.map(series=>{
        const current=series.points.filter(v=>time(v.date)<=now).at(-1);
        const fresh=current && current.value!==null && now-time(current.date)<=maxGap;
        return <div key={series.id} style={{color:series.color}}>{series.name}<br/><span style={{fontSize:22,color:'#667078'}}>{fresh?`${current.date} · ${format(current.value!,data.display.decimals)} ${data.metric.unit}`:'暂无观测'}</span></div>;
      })}
    </div>
    <div style={{position:'absolute',left:86,right:86,bottom:80,borderTop:'1px solid #d3d9d3',paddingTop:23,fontSize:22,lineHeight:1.55,color:'#737a78'}}>
      <div>{data.footnote}</div><div>来源：{data.sources.map(s=>s.title).join(' / ')} · 截至 {data.asOf}</div>
    </div>
  </AbsoluteFill>;
};
registerRoot(()=> <Composition id="LiveCanvas" component={Chart} width={1080} height={1440} fps={30} durationInFrames={90} defaultProps={{data:sample}}/>);
```

## File: livecanvas/assets/remotion/tsconfig.json
size: 242
sha: fcd5192f54ef67d9205e00cc733be71729384b40
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/assets/remotion/tsconfig.json

```text
{"compilerOptions":{"target":"ES2022","lib":["ES2022","DOM"],"module":"ESNext","moduleResolution":"Bundler","jsx":"react-jsx","strict":true,"esModuleInterop":true,"resolveJsonModule":true,"skipLibCheck":true,"noEmit":true},"include":["src"]}
```

## File: livecanvas/agents/openai.yaml
size: 408
sha: b9fe26f45fdad774883f8f57f9bc39271bcfd467
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/agents/openai.yaml

```text
interface:
  display_name: "LiveCanvas · 实况画布"
  short_description: "搜索核实内容，用 Remotion 制作图片、emoji 与场景动画，提供预览及实况资源"
  default_prompt: "使用 $livecanvas 将我的主题制作成有完整封面、图片或 emoji 和场景动画的实况画布，提供可观看预览及 Live Photo 资源，说明手机兼容性，不自动导入照片 App。"
```

## File: livecanvas/LICENSE
size: 1067
sha: 4cec4ee355a54271d06034fb661cffd14432e6d6
upstream: https://github.com/pengchujin/livecanvas/blob/main/livecanvas/LICENSE

```text
MIT License

Copyright (c) 2026 pengchujin

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

## File: README.md
upstream: https://github.com/pengchujin/livecanvas/blob/main/README.md

````text
# LiveCanvas · 实况画布

**简体中文** | [English](README.en.md)

**一句话，做成有封面、有动画的 Live 图**

一个适用于 Codex、Claude Code 等 AI 编程助手的 skill：**搜索核实 → 设计分镜 → Remotion 动画 → 预览与 Apple Live Photo 资源**。支持图片、emoji、场景、时间线和图表。

## 作品演示

15 张 GIF 动态预览，点击图片放大。

[下载与说明](#下载与说明) · [安装方法](#安装) · [English](README.en.md#demos)

<p align="center">
  <a href="docs/demos/zh/xiaomi.gif"><img src="docs/demos/zh/xiaomi.gif" width="260" alt="小米市值" /></a>
  <a href="docs/demos/zh/a20-pro.gif"><img src="docs/demos/zh/a20-pro.gif" width="260" alt="A20 Pro vs A19 Pro" /></a>
  <a href="docs/demos/zh/gemini-argon-intro.gif"><img src="docs/demos/zh/gemini-argon-intro.gif" width="260" alt="Gemini 4 Argon 登场" /></a>
</p>

<p align="center">
  <a href="docs/demos/zh/gemini-argon-output.gif"><img src="docs/demos/zh/gemini-argon-output.gif" width="260" alt="1M 输出上限" /></a>
  <a href="docs/demos/zh/gemini-argon-performance.gif"><img src="docs/demos/zh/gemini-argon-performance.gif" width="260" alt="比肩 GPT-6.1 Sol" /></a>
  <a href="docs/demos/zh/gemini-argon-hallucination.gif"><img src="docs/demos/zh/gemini-argon-hallucination.gif" width="260" alt="更少幻觉：15%" /></a>
</p>

<p align="center">
  <a href="docs/demos/zh/gemini-argon-arena.gif"><img src="docs/demos/zh/gemini-argon-arena.gif" width="260" alt="Text Arena 第一" /></a>
  <a href="docs/demos/zh/gemini-argon-terminal.gif"><img src="docs/demos/zh/gemini-argon-terminal.gif" width="260" alt="终端任务 57%" /></a>
  <a href="docs/demos/zh/population.gif"><img src="docs/demos/zh/population.gif" width="260" alt="全球人口" /></a>
</p>

<p align="center">
  <a href="docs/demos/zh/coffee.gif"><img src="docs/demos/zh/coffee.gif" width="260" alt="咖啡门店" /></a>
  <a href="docs/demos/zh/nev.gif"><img src="docs/demos/zh/nev.gif" width="260" alt="新能源车" /></a>
  <a href="docs/demos/zh/rail.gif"><img src="docs/demos/zh/rail.gif" width="260" alt="中国高铁" /></a>
</p>

<p align="center">
  <a href="docs/demos/zh/weather.gif"><img src="docs/demos/zh/weather.gif" width="260" alt="双城气温" /></a>
  <a href="docs/demos/zh/olympics.gif"><img src="docs/demos/zh/olympics.gif" width="260" alt="奥运金牌" /></a>
  <a href="docs/demos/zh/energy.gif"><img src="docs/demos/zh/energy.gif" width="260" alt="发电结构" /></a>
</p>

## 下载与说明

<details>
<summary>展开查看作品说明、高清 MP4 和 Live Photo</summary>

### 小米市值

[高清 MP4](docs/demos/zh/xiaomi.mp4)

### A20 Pro vs A19 Pro

[高清 MP4](docs/demos/zh/a20-pro.mp4)

### Gemini 4 Argon 登场

软件工程、知识工作与安全防御；分阶段开放给受信任测试者。

[高清 MP4](docs/demos/zh/gemini-argon-intro.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-intro.pvt.zip)

### 1M 输出上限

单次输出上限从 64K 提高到 1M tokens。

[高清 MP4](docs/demos/zh/gemini-argon-output.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-output.pvt.zip)

### 比肩 GPT-6.1 Sol

Artificial Analysis 智能指数：Argon 53 分，Astra 53 分，Sol 52 分。

[高清 MP4](docs/demos/zh/gemini-argon-performance.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-performance.pvt.zip)

### 更少幻觉：15%

Artificial Analysis Omniscience：Argon 15%，Astra 51%，Sol 54%。

[高清 MP4](docs/demos/zh/gemini-argon-hallucination.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-hallucination.pvt.zip)

### Text Arena 第一

1525 分、4,942 票，暂列第一；目前为初步结果。

[高清 MP4](docs/demos/zh/gemini-argon-arena.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-arena.pvt.zip)

### 终端任务 57%

Terminal-Bench 4.0：Argon 57%，此前 Gemini 3.1 Pro Preview 为 4%。

[高清 MP4](docs/demos/zh/gemini-argon-terminal.mp4) · [下载 Live Photo](docs/demos/zh/gemini-argon-terminal.pvt.zip)

### 全球人口

[高清 MP4](docs/demos/zh/population.mp4)

### 咖啡门店

[高清 MP4](docs/demos/zh/coffee.mp4)

### 新能源车

[高清 MP4](docs/demos/zh/nev.mp4)

### 中国高铁

[高清 MP4](docs/demos/zh/rail.mp4)

### 双城气温

[高清 MP4](docs/demos/zh/weather.mp4)

### 奥运金牌

[高清 MP4](docs/demos/zh/olympics.mp4)

### 发电结构

[高清 MP4](docs/demos/zh/energy.mp4)

数据为制作时的快照，不会自动更新。Gemini 图卡核对日期为 2026-10-01，Text Arena 榜单日期为 2026-09-30。来源与口径见 [演示说明](docs/DEMOS.md)。

</details>

## 安装

需要 Node.js / npm。使用 [Skills CLI](https://github.com/vercel-labs/skills) 安装，并选择你的 AI 助手：

```bash
npx skills add pengchujin/livecanvas --skill livecanvas -g
```

只装到 Codex：

```bash
npx skills add pengchujin/livecanvas --skill livecanvas -g -a codex
```

安装后新建对话，输入：

```text
用 LiveCanvas 做北京和上海去年全年气温变化。
加入城市插画和季节 emoji，设计完整封面，并提供动态预览。
```

<details>
<summary>手动安装到 Codex</summary>

下载或克隆本仓库，把整个 `livecanvas/` 文件夹放入 `~/.codex/skills/`；若设置了 `CODEX_HOME`，则放入该目录下的 `skills/`。不要只复制 SKILL.md。随后新建对话。

需要兼容旧的 `$livechart` 调用时，再把 `livechart/` 文件夹放到同一位置。

</details>

## 运行与交付

- **动画：** 助手需能联网搜索和执行代码；需 Node.js、Python 3、FFmpeg，以及内容对应的字体。项目用 `npm ci` 安装依赖。
- **Live Photo：** Linux / Windows / macOS 可使用 Python 3.10+、Pillow 和 FFmpeg 生成 Apple 配对资源；macOS 另有 Swift 原生路径及 PhotoKit 验证。当前工具支持无声 H.264 + JPEG。见 [跨平台生成与 iPhone 导入](livecanvas/references/portable-live-photo.md)。
- **交付：** 封面、MP4、数据来源、可编辑工程，以及支持环境下的 `.pvt` 资源包；不自动导入相册。

`.pvt` 包含配对照片、视频及元数据，iPhone「文件」App 未必能直接预览。README 使用 GIF 展示动效，GIF 不是原生 Live Photo。

模板使用 Remotion 4.0.530。手动渲染与封装步骤见 [运行指南](livecanvas/references/production.md)。

## 许可与致谢

代码及 skill 文档采用 [MIT](LICENSE)；演示媒体与第三方素材许可见 [署名说明](THIRD_PARTY_NOTICES.md)。Remotion 适用其[自身许可证](https://github.com/remotion-dev/remotion/blob/main/LICENSE.md)。

动效设计参考 [Emil Kowalski / animate](https://github.com/emilkowalski/skills/blob/main/skills/animate/SKILL.md)，图标采用 [Twemoji](https://github.com/twitter/twemoji)。
````
