File size: 13,040 Bytes
5afd2f7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
"""Explicit observation bindings and byte-range access to verified original MP4s."""
from dataclasses import dataclass
import copy
import hashlib
import json
from pathlib import Path
import re
from urllib.parse import quote, unquote

from .segment_import import MANIFEST
from .errors import require


@dataclass(frozen=True)
class VideoFile:
    path: Path
    root: Path
    sha256: str
    size: int


class MediaCatalog:
    def __init__(self, registry, path_mapping, index=None, expected_sha256=None):
        self.registry, self.path_mapping = registry, path_mapping
        self.bindings, self.values, self.files, self.batches, self.payload_bytes = {}, {}, {}, {}, {}
        self.render_errors, self.source_dirs = {}, {}
        self.question_urls = {}
        self.version = 0
        self.generator_ids = None
        if isinstance(index, (list, tuple)):
            require(isinstance(expected_sha256, (list, tuple)) and len(index) == len(expected_sha256),
                    'MEDIA_INDEX_INVALID', '媒体索引与SHA分母不一致')
            for path, sha in zip(index, expected_sha256):
                self._register_index(path, sha)
            return
        if index is None:
            require(expected_sha256 is None, 'MEDIA_INDEX_INVALID', '媒体索引缺失')
            return
        self._register_index(index, expected_sha256)

    def _register_index(self, index, expected_sha256):
        from embodied_pipeline.artifacts import digest
        path = Path(index).resolve(strict=True)
        require(path.stat().st_size <= 1_000_000 and re.fullmatch('[0-9a-f]{64}', expected_sha256 or ''),
                'MEDIA_INDEX_INVALID', '须显式提供媒体索引SHA256,索引至多1MB')
        require(digest(path) == expected_sha256, 'MEDIA_INDEX_INVALID', '媒体索引指纹不符')
        value = json.loads(path.read_text())
        require(set(value) == {'schema', 'batch_id', 'bindings'} and value['schema'] == 'console-media-index/1',
                'MEDIA_INDEX_INVALID', '不支持的媒体索引')
        batch = value['batch_id']
        require(isinstance(batch, str) and re.fullmatch('[A-Za-z0-9_-]+', batch)
                and batch not in self.batches and batch not in {r['alias'] for r in self.registry.roots},
                'MEDIA_INDEX_INVALID', '渲染批号无效或重复')
        require(isinstance(value['bindings'], list) and len(value['bindings']) <= 1000,
                'MEDIA_INDEX_INVALID', '媒体绑定分母须为0–1000')
        members = []
        for row in value['bindings']:
            require(set(row) in ({'segment_id', 'observation', 'sha256'},
                                {'segment_id', 'observation', 'sha256', 'source_dir'},
                                {'segment_id', 'render_error'}), 'MEDIA_INDEX_INVALID', '媒体绑定字段无效')
            sid = self._segment_id(row['segment_id'])
            require(sid not in self.bindings and sid not in self.render_errors,
                    'MEDIA_BINDING_INVALID', '媒体段号未登记或重复')
            members.append(sid)
            if 'render_error' in row:
                require(isinstance(row['render_error'], str) and row['render_error'].strip(),
                        'MEDIA_INDEX_INVALID', '渲染失败须有错误摘要')
                self.render_errors[sid] = row['render_error'][:2000]
                continue
            require(re.fullmatch('[0-9a-f]{64}', row['sha256'] or ''), 'MEDIA_INDEX_INVALID', '观测包SHA无效')
            if 'source_dir' in row:
                self.source_dirs[sid] = Path(row['source_dir']).resolve(strict=True)
            self.bindings[sid] = (Path(row['observation']).resolve(strict=True), row['sha256'])
            self.values[sid] = self._build(sid, batch)
            self.payload_bytes[sid] = len(json.dumps(self.values[sid], ensure_ascii=False, separators=(',', ':'), allow_nan=False).encode())
        self.batches[batch] = members
        self.version += 1

    def extended(self, index, expected_sha256):
        """Validate a candidate snapshot without changing the published catalog."""
        candidate = copy.copy(self)
        for name in ('bindings', 'values', 'files', 'batches', 'payload_bytes',
                     'render_errors', 'source_dirs', 'question_urls'):
            setattr(candidate, name, getattr(self, name).copy())
        candidate.generator_ids = None
        candidate._register_index(index, expected_sha256)
        return candidate

    def _segment_id(self, ident):
        if ident in self.registry.entries:
            return ident
        # Generator indexes use script_id; the registry uses alias/directory.
        # Resolve only a unique, verified import, never a basename guess.
        from .segment_import import read_import, verify_import
        if self.generator_ids is None:
            self.generator_ids = {}
            for sid, entry in self.registry.entries.items():
                if (entry.directory / MANIFEST).is_file():
                    read_import(entry.directory)
                    manifest = verify_import(entry.directory)
                    source = json.loads(Path(manifest['inputs']['case.json']['path']).read_text())
                    self.generator_ids.setdefault(source.get('script_id'), []).append(sid)
        matches = self.generator_ids.get(ident, [])
        require(len(matches) == 1, 'MEDIA_BINDING_INVALID', '媒体段号未登记或存在歧义:' + str(ident))
        return matches[0]

    def _build(self, segment_id, batch):
        from embodied_pipeline.artifacts import digest, read_json
        from embodied_pipeline.rendering.media_adapter import build_media
        path, expected = self.bindings[segment_id]
        require(path.name == 'artifact.json' and digest(path) == expected,
                'MEDIA_BINDING_INVALID', '观测包封套与登记SHA不符')
        entry = self.registry.entries[segment_id]
        source = self.source_dirs.get(segment_id)
        imported = None
        if source is None:
            script, _, _, _ = self.path_mapping.read(entry.directory)
            script_id = script.script_id
            source = entry.directory
        else:
            script_id = read_json(source / 'script.json')['script_id']
            if (entry.directory / MANIFEST).is_file():
                from .segment_import import read_import, verify_import
                read_import(entry.directory)
                imported = verify_import(entry.directory)['inputs']
        # The public adapter verifies the complete observation closure. Never
        # repair paths or accept a hand-built substitute for its media object.
        package = read_json(path)
        obs_id = package['data']['obs_id']
        require(re.fullmatch('[0-9a-f]{64}', obs_id or ''), 'MEDIA_BINDING_INVALID', '观测身份无效')
        # Logical obs_id can recur in byte-identical rerenders. Keep the
        # original package's path even when another batch registers it later.
        base = '/api/v1/media/' + obs_id + '/' + expected + '/'
        # 观测包按渲染时的绝对路径记输入;runner 工作目录作业后即删,按 --path-map 找输入(10-22 GPU 审阅台起不来)
        media = build_media(path, base, path_resolver=self.path_mapping)
        provenance = read_json(path.parent / 'provenance.json')
        require(media['source_group_id'] == script_id,
                'MEDIA_SCRIPT_MISMATCH', '观测包与该段剧本身份不同')
        for name, filename in (('script', 'script.json'), ('curves', 'curves.npz')):
            actual = digest(source / filename)
            require(provenance['source_refs'][name]['sha256'] == actual,
                    'MEDIA_SCRIPT_MISMATCH', '观测包实际输入字节与该段不同:' + filename)
            if imported is not None:
                key = 'case.json' if name == 'script' else 'private20hz.npz'
                require(imported[key]['sha256'] == actual, 'MEDIA_SCRIPT_MISMATCH',
                        '媒体源与审阅导入输入不同:' + filename)
            elif segment_id in self.source_dirs:
                require(digest(entry.directory / filename) == actual, 'MEDIA_SCRIPT_MISMATCH',
                        '媒体源与登记段输入不同:' + filename)
        for route in media['routes']:
            relative = 'videos/' + route['observer_id'] + '.mp4'
            require(route['url'] == base + 'videos/' + quote(route['observer_id'], safe='') + '.mp4',
                    'MEDIA_BINDING_INVALID', '录像URL未使用登记目录')
            file = package['files'][relative]
            target = (path.parent / relative).resolve(strict=True)
            require(target.is_relative_to(path.parent), 'MEDIA_BINDING_INVALID', '录像越出观测包')
            item = VideoFile(target, path.parent, file, target.stat().st_size)
            self.files[unquote(route['url'])] = item
            url = '/media/v/' + '/'.join(quote(part, safe='') for part in
                    (batch, source.name, route['observer_id'])) + '.mp4'
            key = unquote(url)
            require(key not in self.files, 'MEDIA_BINDING_INVALID', '题目录像地址重复')
            self.files[key] = item
            self.question_urls[segment_id, route['observer_id']] = url
        return media

    def get(self, segment_id):
        if segment_id not in self.bindings:
            return None
        from embodied_pipeline.artifacts import digest
        path, expected = self.bindings[segment_id]
        require(digest(path) == expected, 'MEDIA_BINDING_INVALID', '已登记观测包封套变化')
        # This is the complete, verified registration snapshot produced by the
        # public adapter, not a new reading of mutable raw tables. Original
        # observations are frozen; each video request separately hashes MP4.
        return self.values[segment_id]

    def reference(self, segment_id):
        value = self.values.get(segment_id)
        if value is None: return None
        return dict(schema='render-media-reference/1', obs_id=value['obs_id'],
                    source_group_id=value['source_group_id'],
                    url='/api/v1/segments/' + quote(segment_id,safe='') + '/media',
                    payload_bytes=self.payload_bytes[segment_id],
                    routes=[{k:r[k] for k in ('observer_id','width','height')} for r in value['routes']])

    def frames(self, segment_id, world_s):
        from embodied_pipeline.rendering.media_adapter import frame_at_world
        require(segment_id in self.values, 'MEDIA_NOT_FOUND', '本段未登记观测包')
        value = self.values[segment_id]
        return {'schema': 'render-media-frames/1', 'obs_id': value['obs_id'], 'world_s': world_s,
                'routes': [frame_at_world(value, r['observer_id'], world_s) for r in value['routes']]}

    def video(self, url, method, range_header):
        from .http_app import Response, error_response
        item = self.files.get(url)
        if item is None:
            return error_response(404, 'MEDIA_NOT_FOUND', '录像未登记')
        stream = None
        try:
            require(item.path.resolve(strict=True) == item.path and item.path.is_relative_to(item.root),
                    'MEDIA_INTEGRITY', '录像路径已变化')
            stream = item.path.open('rb')
            # Verify and stream the same descriptor, including for a tiny Range.
            check = hashlib.sha256()
            for block in iter(lambda: stream.read(1024 * 1024), b''):
                check.update(block)
            size = stream.tell()
            require(size == item.size and check.hexdigest() == item.sha256,
                    'MEDIA_INTEGRITY', '录像字节与发布封套不符')
            headers = {'Content-Type': 'video/mp4', 'Accept-Ranges': 'bytes'}
            start, end, status = 0, size - 1, 200
            if method != 'HEAD' and range_header and range_header.startswith('bytes='):
                match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header)
                if not match or not any(match.groups()):
                    stream.close()
                    return Response(416, {**headers, 'Content-Range': 'bytes */' + str(size)}, b'')
                left, right = match.groups()
                if left:
                    start = int(left); end = min(size - 1, int(right)) if right else size - 1
                else:
                    start = max(0, size - int(right))
                if start > end or start >= size:
                    stream.close()
                    return Response(416, {**headers, 'Content-Range': 'bytes */' + str(size)}, b'')
                status = 206; headers['Content-Range'] = f'bytes {start}-{end}/{size}'
            stream.seek(start)
            return Response(status, headers, b'', stream, end - start + 1)
        except (ValueError, KeyError, TypeError, OSError) as exc:
            if stream: stream.close()
            return error_response(409, 'MEDIA_INTEGRITY', str(exc))