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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
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
/**
 * Server-side preparation of the portable browser render payload.
 *
 * This is deliberately a preparation step, not a render: it never spawns Manim,
 * FFmpeg or a sandbox process. The worker still owns AI generation and narration;
 * the browser runtime owns pixels and playback. Cue timing keeps its native source
 * (the narration manifest) and is transferred without any filesystem location.
 */

import fs from 'node:fs'
import type { NarrationAssets, NarrationConfig } from '../../workflow/narration/types'
import type {
  BrowserRenderNarrationPayload,
  BrowserRenderPreparedPayload,
  OutputMode,
  PortableNarrationManifest,
  RenderTarget,
  VideoQuality,
} from '../../types'
import { parseImageCodeBlocks } from '../manim/image-code-blocks'
import { cleanManimCode } from '../../utils/manim-code-cleaner'
import { publishNarrationForReuse } from '../manim/narration-reuse'
import { createLogger } from '../../shared/logging/logger'
import {
  browserRenderNarrationUrl,
  writeBrowserRenderNarration,
} from './browser-render-assets'
import {
  browserPreparationFailure,
  BrowserRenderPreparationError,
} from './browser-render-errors'
import type { RenderResult } from '../queue/processors/steps/render-step-types'

const MAX_SOURCE_BYTES = 1024 * 1024
const MAX_MANIFEST_BYTES = 1024 * 1024
const MAX_NARRATION_SECONDS = 60 * 60
const MAX_CUES = 4096
const MAX_SEGMENTS = 256
const MAX_CUE_ID_LENGTH = 128
const CUE_EPS = 1 / 1_000_000

const logger = createLogger('BrowserRenderStep')

const QUALITY_RESOLUTION: Record<VideoQuality, { width: number; height: number }> = {
  low: { width: 854, height: 480 },
  medium: { width: 1280, height: 720 },
  high: { width: 1920, height: 1080 },
}

// Concept reference images remain AI input. A scene file that expects a local image/SVG
// file has no portable counterpart in this phase, so reject the obvious literal form
// instead of preparing a payload that could only fail (or, worse, appear successful).
const EXTERNAL_ASSET_REFERENCE =
  /\b(?:ImageMobject|SVGMobject)\s*\(\s*(?:r|u|f)?["'][^"'\n]+\.(?:png|jpe?g|webp|gif|svg|pdf)["']/i

const EXTERNAL_IMAGE_REFERENCE =
  /\bImage\.open\s*\(\s*(?:r|u|f)?["'][^"'\n]+\.(?:png|jpe?g|webp|gif)["']/i

interface PrepareBrowserRenderArgs {
  jobId: string
  concept: string
  quality: string
  outputMode: OutputMode
  renderTarget: RenderTarget | undefined
  codeResult: {
    code: string
    usedAI: boolean
    generationType: string
    narration?: NarrationAssets
  }
  sceneName?: string
  videoConfig?: { frameRate?: number; narration?: NarrationConfig }
  renderCacheKey?: string
}

function isRecord(value: unknown): value is Record<string, unknown> {
  return typeof value === 'object' && value !== null && !Array.isArray(value)
}

function finite(value: unknown, label: string): number {
  if (typeof value !== 'number' || !Number.isFinite(value)) {
    throw new Error(`${label} must be a finite number`)
  }
  return value
}

function normalizeQuality(value: string): VideoQuality {
  return value === 'low' || value === 'medium' || value === 'high' ? value : 'medium'
}

function normalizeFrameRate(value: number | undefined): number {
  if (value === undefined) return 60
  if (!Number.isInteger(value) || value < 1 || value > 120) {
    throw new Error('Browser render frame rate must be an integer between 1 and 120')
  }
  return value
}

function readCueMap(
  value: unknown,
  label: string,
  limitSeconds: number
): Record<string, number> {
  if (!isRecord(value)) {
    throw new Error(`${label} must be an object of cue ids to seconds`)
  }
  const entries = Object.entries(value)
  if (entries.length > MAX_CUES) {
    throw new Error(`${label} has more than ${MAX_CUES} cues`)
  }
  // Null prototype keeps ids such as "__proto__" as ordinary own cues.
  const cues = Object.create(null) as Record<string, number>
  for (const [id, raw] of entries) {
    if (id.length === 0 || id.length > MAX_CUE_ID_LENGTH) {
      throw new Error(`${label} contains an invalid cue id`)
    }
    const seconds = finite(raw, `${label}[${JSON.stringify(id)}]`)
    if (seconds < 0 || seconds > limitSeconds + CUE_EPS) {
      throw new Error(`${label}[${JSON.stringify(id)}] is outside its duration`)
    }
    cues[id] = seconds
  }
  return cues
}

function toPortableManifest(value: unknown): PortableNarrationManifest {
  if (!isRecord(value)) {
    throw new Error('Narration manifest is not an object')
  }
  if (value.version !== 1) {
    throw new Error('Narration manifest is not a supported v1 manifest')
  }
  const duration = finite(value.duration, 'Narration manifest duration')
  if (duration <= 0 || duration > MAX_NARRATION_SECONDS) {
    throw new Error('Narration manifest duration is outside the browser runtime limits')
  }
  const cues = readCueMap(value.cues, 'Narration manifest cues', duration)
  const manifest: PortableNarrationManifest = { version: 1, duration, cues }

  if (value.segments !== undefined) {
    if (!Array.isArray(value.segments)) {
      throw new Error('Narration manifest segments must be an array')
    }
    if (value.segments.length > MAX_SEGMENTS) {
      throw new Error(`Narration manifest has more than ${MAX_SEGMENTS} segments`)
    }
    const seen = new Set<string>()
    manifest.segments = value.segments.map((raw, index) => {
      if (!isRecord(raw)) {
        throw new Error(`Narration manifest segments[${index}] is not an object`)
      }
      if (typeof raw.id !== 'string' || raw.id.length === 0 || raw.id.length > MAX_CUE_ID_LENGTH) {
        throw new Error(`Narration manifest segments[${index}].id is invalid`)
      }
      if (seen.has(raw.id)) {
        throw new Error(`Narration manifest contains duplicate segment id ${raw.id}`)
      }
      seen.add(raw.id)
      const start = finite(raw.start, `Narration manifest segments[${index}].start`)
      const segmentDuration = finite(
        raw.duration,
        `Narration manifest segments[${index}].duration`
      )
      if (start < 0 || segmentDuration < 0 || start + segmentDuration > duration + CUE_EPS) {
        throw new Error(`Narration manifest segments[${index}] is outside the audio duration`)
      }
      return {
        id: raw.id,
        start,
        duration: segmentDuration,
        ...(raw.cues === undefined
          ? {}
          : {
              cues: readCueMap(
                raw.cues,
                `Narration manifest segments[${index}].cues`,
                segmentDuration
              ),
            }),
      }
    })
  }
  return manifest
}

function readPortableManifest(manifestPath: string): PortableNarrationManifest {
  let stat: fs.Stats
  try {
    stat = fs.statSync(manifestPath)
  } catch (error) {
    throw browserPreparationFailure(
      'narration-unavailable',
      'Narration manifest is unavailable for browser rendering',
      error,
      { operation: 'manifest-stat' }
    )
  }
  if (!stat.isFile() || stat.size <= 0 || stat.size > MAX_MANIFEST_BYTES) {
    throw new BrowserRenderPreparationError(
      'narration-unavailable',
      'Narration manifest has an invalid size for browser rendering'
    )
  }
  let raw: unknown
  try {
    raw = JSON.parse(fs.readFileSync(manifestPath, 'utf8'))
  } catch (error) {
    if (error instanceof SyntaxError) {
      throw new BrowserRenderPreparationError(
        'narration-unavailable',
        'Narration manifest is not valid JSON',
        { cause: error }
      )
    }
    throw browserPreparationFailure(
      'narration-unavailable',
      'Narration manifest could not be read for browser rendering',
      error,
      { operation: 'manifest-read' }
    )
  }
  try {
    return toPortableManifest(raw)
  } catch (error) {
    if (error instanceof BrowserRenderPreparationError) throw error
    throw new BrowserRenderPreparationError(
      'narration-unavailable',
      error instanceof Error ? error.message : 'Narration manifest is invalid',
      { cause: error }
    )
  }
}

function buildNarrationPayload(
  jobId: string,
  assets: NarrationAssets
): BrowserRenderNarrationPayload {
  if (!assets.manifestPath || !assets.audioPath) {
    throw new BrowserRenderPreparationError(
      'narration-unavailable',
      'Narration assets are incomplete for browser rendering'
    )
  }
  const manifest = readPortableManifest(assets.manifestPath)
  const published = writeBrowserRenderNarration(jobId, assets.audioPath)
  return {
    manifest,
    audioUrl: browserRenderNarrationUrl(jobId, published.sha256),
    mimeType: 'audio/wav',
    byteLength: published.byteLength,
    sha256: published.sha256,
  }
}

function assertNoUnsupportedExternalAssets(source: string): void {
  if (EXTERNAL_ASSET_REFERENCE.test(source) || EXTERNAL_IMAGE_REFERENCE.test(source)) {
    throw new Error(
      '浏览器本地渲染不会传输外部场景资源文件;需要读取图片或 SVG 文件的场景请改用云端渲染。' +
        ' Browser local rendering does not transfer external scene asset files; use cloud rendering for such scenes.'
    )
  }
}

/**
 * Builds the typed "prepared" result. No videoUrl, hardsubUrl or native render is
 * produced; a browser job is complete only when this payload has been stored. The
 * client-side readiness state is separate and is never inferred from this record.
 */
export function prepareBrowserRenderResult(
  args: PrepareBrowserRenderArgs
): RenderResult {
  if (args.renderTarget !== 'browser') {
    throw new Error('Browser render preparation requires the browser render target')
  }

  const quality = normalizeQuality(args.quality)
  const frameRate = normalizeFrameRate(args.videoConfig?.frameRate)
  const resolution = QUALITY_RESOLUTION[quality]

  if (args.outputMode === 'image') {
    let blocks: Array<{ index: number; source: string }>
    try {
      blocks = parseImageCodeBlocks(args.codeResult.code).map((block) => {
        const cleaned = cleanManimCode(block.code)
        const source = cleaned.code
        if (source.trim().length === 0) {
          throw new Error(`Image block ${block.index} is empty after cleaning`)
        }
        if (Buffer.byteLength(source, 'utf8') > MAX_SOURCE_BYTES) {
          throw new Error(
            `Image block ${block.index} exceeds ${MAX_SOURCE_BYTES} bytes and cannot be transferred`
          )
        }
        assertNoUnsupportedExternalAssets(source)
        return { index: block.index, source }
      })
    } catch (error) {
      if (error instanceof BrowserRenderPreparationError) throw error
      throw new BrowserRenderPreparationError(
        'invalid-source',
        error instanceof Error ? error.message : 'Image mode source is invalid',
        { cause: error }
      )
    }

    const browserRender: BrowserRenderPreparedPayload = {
      outputMode: 'image',
      blocks,
      frameRate,
      resolution,
      quality,
    }

    logger.info('Prepared browser image render payload', {
      jobId: args.jobId,
      renderTarget: 'browser',
      outputMode: 'image',
      blockCount: blocks.length,
      frameRate,
      width: resolution.width,
      height: resolution.height,
      sourceBytes: blocks.reduce((total, block) => total + Buffer.byteLength(block.source, 'utf8'), 0),
    })

    return {
      jobId: args.jobId,
      concept: args.concept,
      outputMode: 'image',
      // Keep the anchored image-mode source for edit/rerender; the cleaned per-block
      // sources travel separately in the browser payload.
      code: args.codeResult.code,
      codeLanguage: 'manim-python',
      usedAI: args.codeResult.usedAI,
      generationType: args.codeResult.generationType,
      quality,
      renderTarget: 'browser',
      browserRender,
    }
  }

  const cleaned = cleanManimCode(args.codeResult.code)
  const source = cleaned.code
  if (source.trim().length === 0) {
    throw new Error('Browser render source is empty')
  }
  if (Buffer.byteLength(source, 'utf8') > MAX_SOURCE_BYTES) {
    throw new Error(
      `Browser render source exceeds ${MAX_SOURCE_BYTES} bytes and cannot be transferred`
    )
  }
  assertNoUnsupportedExternalAssets(source)

  const sceneName =
    typeof args.sceneName === 'string' && /^[A-Za-z_][A-Za-z0-9_]{0,199}$/.test(args.sceneName)
      ? args.sceneName
      : undefined

  const narrationConfig = args.videoConfig?.narration
  const narrationEnabled = narrationConfig?.enabled === true
  if (narrationEnabled && !args.codeResult.narration) {
    logger.warn('Narration was requested but no narration assets are available for browser rendering', {
      jobId: args.jobId,
      generationType: args.codeResult.generationType,
    })
    throw new BrowserRenderPreparationError(
      'narration-unavailable',
      '旁白已开启,但浏览器渲染所需的旁白资源不可用。请重新生成。 Narration is enabled, but the browser render has no usable narration assets. Generate the video again.'
    )
  }

  let narration: BrowserRenderNarrationPayload | undefined
  if (narrationEnabled && args.codeResult.narration) {
    try {
      narration = buildNarrationPayload(args.jobId, args.codeResult.narration)
    } catch (error) {
      throw browserPreparationFailure(
        'narration-unavailable',
        'Narration could not be prepared for browser rendering',
        error,
        { jobId: args.jobId, operation: 'build-narration-payload' }
      )
    }
  }

  if (narration && narrationConfig && args.renderCacheKey) {
    publishNarrationForReuse({
      renderCacheKey: args.renderCacheKey,
      jobId: args.jobId,
      config: narrationConfig,
      assets: args.codeResult.narration!,
    })
  }

  const browserRender: BrowserRenderPreparedPayload = {
    outputMode: 'video',
    source,
    ...(sceneName ? { sceneName } : {}),
    frameRate,
    resolution,
    quality,
    ...(narration ? { narration } : {}),
  }

  logger.info('Prepared browser render payload', {
    jobId: args.jobId,
    renderTarget: 'browser',
    outputMode: 'video',
    frameRate,
    width: resolution.width,
    height: resolution.height,
    hasNarration: Boolean(narration),
    sourceBytes: Buffer.byteLength(source, 'utf8'),
  })

  return {
    jobId: args.jobId,
    concept: args.concept,
    outputMode: 'video',
    code: source,
    codeLanguage: 'manim-python',
    usedAI: args.codeResult.usedAI,
    generationType: args.codeResult.generationType,
    quality,
    renderTarget: 'browser',
    browserRender,
  }
}