@slidevideo/cli 0.3.1 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -7,7 +7,7 @@ import { ensureStampFonts, measureStampText } from './stamp-fonts.js';
7
7
  import { balancedSum, execute, executionSignal, ffmpegFilterScriptFlags, hashFile, saveJson } from './media.js';
8
8
  import { executable } from './executables.js';
9
9
  import { ProductionError, requireCondition } from './errors.js';
10
- import { activeViewTransform, effectPrimitives, evaluateLaserPosition, evaluateViewTransform, findTargetGeometry, forwardTransformRect, highlightPaint, inverseTransformPoint, laserDirtyBounds, laserDotSample, laserFadeFraction, laserPaint, laserVisible, paintLaser, paintStamp, pointInExpandedAperture, spotlightApertureBounds, spotlightAperturesVisible, spotlightFadeFraction, spotlightMaskSample, spotlightPaint, stampDirtyBounds, stampPaint, stampVisible, underlineFragmentPrimitives, underlineFragmentsVisible, underlinePaint, underlineWipeFractions, zoomPaint, zoomProgress, zoomTransformVisible, } from './annotation-paint.js';
10
+ import { activeViewTransform, arrowDirtyBounds, arrowMotionState, arrowPaint, arrowVisible, effectPrimitives, evaluateLaserPosition, evaluateViewTransform, findTargetGeometry, forwardTransformRect, highlightPaint, inverseTransformPoint, laserDirtyBounds, laserDotSample, laserFadeFraction, laserPaint, laserVisible, paintArrow, paintLaser, paintStamp, pointInExpandedAperture, spotlightApertureBounds, spotlightAperturesVisible, spotlightFadeFraction, spotlightMaskSample, spotlightPaint, stampDirtyBounds, stampPaint, stampVisible, underlineFragmentPrimitives, underlineFragmentsVisible, underlinePaint, underlineWipeFractions, zoomPaint, zoomProgress, zoomTransformVisible, } from './annotation-paint.js';
11
11
  function toRgbPrimitive(paint) {
12
12
  return {
13
13
  ...paint,
@@ -322,6 +322,12 @@ export function annotationApplications(video, schedule, visual, audioOrigin) {
322
322
  requireCondition(stampVisible(painted), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: stamp is clipped outside the slide-content rectangle`, 5, context);
323
323
  return { ...painted, id: annotation.id, first_frame, end_frame, geometry };
324
324
  }
325
+ if (annotation.effect === 'arrow') {
326
+ const slideGeometry = validateGeometry(annotation, { type: 'slide' }, context);
327
+ const painted = arrowPaint({ target: annotation.target, appearance: annotation.appearance, motion: annotation.motion, start_ms, end_ms }, slideGeometry, target => validateGeometry(annotation, target, { annotation: annotation.id, target }).fragments);
328
+ requireCondition(arrowVisible(painted), 'ANNOTATION_GEOMETRY', `Annotation ${annotation.id}: ${painted.degenerate_reason ?? 'arrow is clipped outside the slide-content rectangle'}`, 5, context);
329
+ return { ...painted, id: annotation.id, first_frame, end_frame, geometry: slideGeometry };
330
+ }
325
331
  const geometry = validateGeometry(annotation, annotation.target, context);
326
332
  switch (annotation.effect) {
327
333
  case 'highlight': {
@@ -1226,7 +1232,7 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1226
1232
  in_ms: 0,
1227
1233
  out_ms: 0,
1228
1234
  };
1229
- const measureLaserDisk = (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, sampleTimeMs, expectedActive, activeLasers, activeStamps) => {
1235
+ const measureLaserDisk = (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, sampleTimeMs, expectedActive, activeLasers, activeStamps, activeArrows) => {
1230
1236
  const laserForSample = expectedActive ? item : settledLaser;
1231
1237
  const pos = evaluateLaserPosition(laserForSample, sampleTimeMs);
1232
1238
  const r = Math.max(1, item.radius_px - (item.radius_px >= 5 ? 1.5 : 0.5));
@@ -1239,8 +1245,9 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1239
1245
  const rw = right - left;
1240
1246
  const rh = bottom - top;
1241
1247
  let stampRgba;
1242
- if (activeStamps.length > 0 && rw > 0 && rh > 0) {
1243
- ensureStampFonts();
1248
+ if ((activeArrows.length > 0 || activeStamps.length > 0) && rw > 0 && rh > 0) {
1249
+ if (activeStamps.length > 0)
1250
+ ensureStampFonts();
1244
1251
  const stampCanvas = createCanvas(rw, rh);
1245
1252
  const sctx = stampCanvas.getContext('2d');
1246
1253
  sctx.translate(-left, -top);
@@ -1253,6 +1260,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1253
1260
  sctx.scale(scale, scale);
1254
1261
  sctx.translate(-s.x, -s.y);
1255
1262
  }
1263
+ for (const entry of activeArrows)
1264
+ paintArrow(sctx, entry.effect, outputTimeMs);
1256
1265
  for (const entry of activeStamps)
1257
1266
  paintStamp(sctx, entry.effect, outputTimeMs);
1258
1267
  stampRgba = sctx.getImageData(0, 0, rw, rh).data;
@@ -1344,8 +1353,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1344
1353
  if (item.first_frame - 1 >= 0) {
1345
1354
  const clearStartIndex = item.first_frame - 1;
1346
1355
  const startSampleMs = activeStartFrame * 1000 / video.fps;
1347
- const order = enqueue(clearStartIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1348
- const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, startSampleMs, false, activeLasers, activeStamps);
1356
+ const order = enqueue(clearStartIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1357
+ const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, startSampleMs, false, activeLasers, activeStamps, activeArrows);
1349
1358
  orderedChecks.push({
1350
1359
  order,
1351
1360
  entry: {
@@ -1366,8 +1375,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1366
1375
  }
1367
1376
  {
1368
1377
  const activeIndex = activeStartFrame;
1369
- const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1370
- const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps);
1378
+ const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1379
+ const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1371
1380
  orderedChecks.push({
1372
1381
  order,
1373
1382
  entry: {
@@ -1393,8 +1402,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1393
1402
  else {
1394
1403
  {
1395
1404
  const activeIndex = activeEndFrame;
1396
- const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1397
- const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps);
1405
+ const order = enqueue(activeIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1406
+ const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1398
1407
  orderedChecks.push({
1399
1408
  order,
1400
1409
  entry: {
@@ -1416,8 +1425,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1416
1425
  {
1417
1426
  const clearEndIndex = item.end_frame;
1418
1427
  const endSampleMs = activeEndFrame * 1000 / video.fps;
1419
- const order = enqueue(clearEndIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1420
- const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, endSampleMs, false, activeLasers, activeStamps);
1428
+ const order = enqueue(clearEndIndex, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1429
+ const metrics = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, endSampleMs, false, activeLasers, activeStamps, activeArrows);
1421
1430
  orderedChecks.push({
1422
1431
  order,
1423
1432
  entry: {
@@ -1447,10 +1456,10 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1447
1456
  coverage.push(`${item.id}:movement:frame_${midFrame}`);
1448
1457
  const startTimeMs = activeStartFrame * 1000 / video.fps;
1449
1458
  const checkStartCleared = midTimeMs - startTimeMs > item.trail_ms + 1000 / video.fps;
1450
- const order = enqueue(midFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1451
- const atMid = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps);
1459
+ const order = enqueue(midFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1460
+ const atMid = measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1452
1461
  const atStart = checkStartCleared
1453
- ? measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, startTimeMs, false, activeLasers, activeStamps)
1462
+ ? measureLaserDisk(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, startTimeMs, false, activeLasers, activeStamps, activeArrows)
1454
1463
  : { passed: true, expected_error: null, opposite_error: null, contrast: null };
1455
1464
  const passed = atMid.passed && atStart.passed;
1456
1465
  orderedChecks.push({
@@ -1482,7 +1491,7 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1482
1491
  ? Math.min(item.end_frame - 1, Math.ceil((item.start_ms + item.in_ms) * video.fps / 1000 - 1e-9))
1483
1492
  : item.first_frame;
1484
1493
  const activeFrame = Math.max(item.first_frame, Math.min(item.end_frame - 1, settleFrame));
1485
- const measureStampPresence = (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, sampleTimeMs, expectedActive, activeLasers, activeStamps) => {
1494
+ const measureStampPresence = (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, sampleTimeMs, expectedActive, activeLasers, activeStamps, activeArrows) => {
1486
1495
  const bounds = stampDirtyBounds(item, sampleTimeMs);
1487
1496
  if (!bounds)
1488
1497
  return { passed: !expectedActive, expected_error: null, opposite_error: null, contrast: null };
@@ -1512,6 +1521,9 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1512
1521
  paintStamp(ctx, item, sampleTimeMs);
1513
1522
  }
1514
1523
  else {
1524
+ for (const entry of activeArrows) {
1525
+ paintArrow(ctx, entry.effect, outputTimeMs);
1526
+ }
1515
1527
  let paintedSelf = false;
1516
1528
  for (const entry of activeStamps) {
1517
1529
  if (entry.index === appIndex) {
@@ -1535,7 +1547,7 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1535
1547
  }
1536
1548
  return ctx.getImageData(0, 0, rw, rh).data;
1537
1549
  };
1538
- const hasOtherTop = activeLasers.length > 0 || activeStamps.some(entry => entry.index !== appIndex);
1550
+ const hasOtherTop = activeArrows.length > 0 || activeLasers.length > 0 || activeStamps.some(entry => entry.index !== appIndex);
1539
1551
  const selfRgba = renderTopLayer(true, true);
1540
1552
  const withRgba = hasOtherTop ? renderTopLayer(true) : selfRgba;
1541
1553
  const withoutRgba = hasOtherTop ? renderTopLayer(false) : undefined;
@@ -1598,8 +1610,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1598
1610
  const beforeFrame = item.first_frame - 1;
1599
1611
  const activeSampleTime = activeFrame * 1000 / video.fps;
1600
1612
  coverage.push(`${item.id}:before_start:frame_${beforeFrame}`);
1601
- const order = enqueue(beforeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1602
- const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps);
1613
+ const order = enqueue(beforeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1614
+ const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps, activeArrows);
1603
1615
  orderedChecks.push({
1604
1616
  order,
1605
1617
  entry: { annotation: item.id, part: 'stamp', boundary: 'before_start', frame_index: beforeFrame, encoded_ms: timestampMs, expected_active: false, ...metrics },
@@ -1609,8 +1621,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1609
1621
  }
1610
1622
  if (activeFrame < totalFrames) {
1611
1623
  coverage.push(`${item.id}:start:frame_${activeFrame}`);
1612
- const order = enqueue(activeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1613
- const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps);
1624
+ const order = enqueue(activeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1625
+ const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1614
1626
  orderedChecks.push({
1615
1627
  order,
1616
1628
  entry: { annotation: item.id, part: 'stamp', boundary: 'start', frame_index: activeFrame, encoded_ms: timestampMs, expected_active: true, ...metrics },
@@ -1622,8 +1634,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1622
1634
  if (item.end_frame < totalFrames) {
1623
1635
  const activeSampleTime = activeFrame * 1000 / video.fps;
1624
1636
  coverage.push(`${item.id}:end:frame_${item.end_frame}`);
1625
- const order = enqueue(item.end_frame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps) => {
1626
- const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps);
1637
+ const order = enqueue(item.end_frame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1638
+ const metrics = measureStampPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps, activeArrows);
1627
1639
  orderedChecks.push({
1628
1640
  order,
1629
1641
  entry: { annotation: item.id, part: 'stamp', boundary: 'end', frame_index: item.end_frame, encoded_ms: timestampMs, expected_active: false, ...metrics },
@@ -1634,6 +1646,203 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1634
1646
  }
1635
1647
  break;
1636
1648
  }
1649
+ case 'arrow': {
1650
+ requiredActiveParts.push({ id: item.id, part: 'arrow' });
1651
+ const settleFrame = item.motion_type !== 'none' && item.in_ms > 0
1652
+ ? Math.min(item.end_frame - 1, Math.ceil((item.start_ms + item.in_ms) * video.fps / 1000 - 1e-9))
1653
+ : item.first_frame;
1654
+ const activeFrame = Math.max(item.first_frame, Math.min(item.end_frame - 1, settleFrame));
1655
+ const measureArrowPresence = (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, sampleTimeMs, expectedActive, activeLasers, activeStamps, activeArrows) => {
1656
+ const bounds = arrowDirtyBounds(item, sampleTimeMs);
1657
+ if (!bounds)
1658
+ return { passed: !expectedActive, expected_error: null, opposite_error: null, contrast: null };
1659
+ const outputBounds = activeView ? forwardTransformRect(activeView, bounds) : bounds;
1660
+ const x0 = Math.max(0, Math.floor(outputBounds.x));
1661
+ const y0 = Math.max(0, Math.floor(outputBounds.y));
1662
+ const x1 = Math.min(video.width, Math.ceil(outputBounds.x + outputBounds.width));
1663
+ const y1 = Math.min(video.height, Math.ceil(outputBounds.y + outputBounds.height));
1664
+ const rw = x1 - x0;
1665
+ const rh = y1 - y0;
1666
+ if (rw < 2 || rh < 2)
1667
+ return { passed: false, expected_error: null, opposite_error: null, contrast: null };
1668
+ const renderTopLayer = (includeSelf, onlySelf = false) => {
1669
+ if (!onlySelf && activeStamps.length > 0)
1670
+ ensureStampFonts();
1671
+ const canvas = createCanvas(rw, rh);
1672
+ const ctx = canvas.getContext('2d');
1673
+ ctx.translate(-x0, -y0);
1674
+ if (activeView) {
1675
+ const { content: c, source: s, scale } = activeView;
1676
+ ctx.beginPath();
1677
+ ctx.rect(c.x, c.y, c.width, c.height);
1678
+ ctx.clip();
1679
+ ctx.translate(c.x, c.y);
1680
+ ctx.scale(scale, scale);
1681
+ ctx.translate(-s.x, -s.y);
1682
+ }
1683
+ if (onlySelf) {
1684
+ paintArrow(ctx, item, sampleTimeMs);
1685
+ }
1686
+ else {
1687
+ let paintedSelf = false;
1688
+ for (const entry of activeArrows) {
1689
+ if (entry.index === appIndex) {
1690
+ if (includeSelf) {
1691
+ paintArrow(ctx, item, sampleTimeMs);
1692
+ paintedSelf = true;
1693
+ }
1694
+ continue;
1695
+ }
1696
+ if (includeSelf && !paintedSelf && entry.index > appIndex) {
1697
+ paintArrow(ctx, item, sampleTimeMs);
1698
+ paintedSelf = true;
1699
+ }
1700
+ paintArrow(ctx, entry.effect, outputTimeMs);
1701
+ }
1702
+ if (includeSelf && !paintedSelf)
1703
+ paintArrow(ctx, item, sampleTimeMs);
1704
+ for (const entry of activeStamps) {
1705
+ paintStamp(ctx, entry.effect, outputTimeMs);
1706
+ }
1707
+ for (const entry of activeLasers) {
1708
+ paintLaser(ctx, entry.effect, outputTimeMs);
1709
+ }
1710
+ }
1711
+ return ctx.getImageData(0, 0, rw, rh).data;
1712
+ };
1713
+ const hasOtherTop = activeStamps.length > 0 || activeLasers.length > 0 || activeArrows.some(entry => entry.index !== appIndex);
1714
+ const selfRgba = renderTopLayer(true, true);
1715
+ const withRgba = hasOtherTop ? renderTopLayer(true) : selfRgba;
1716
+ const withoutRgba = hasOtherTop ? renderTopLayer(false) : undefined;
1717
+ const stepX = Math.max(1, Math.floor(rw / 96));
1718
+ const stepY = Math.max(1, Math.floor(rh / 64));
1719
+ let expectedError = 0;
1720
+ let oppositeError = 0;
1721
+ let contrast = 0;
1722
+ let count = 0;
1723
+ for (let ly = 0; ly < rh; ly += stepY) {
1724
+ for (let lx = 0; lx < rw; lx += stepX) {
1725
+ const pOffset = (ly * rw + lx) * 4;
1726
+ const selfAlpha = selfRgba[pOffset + 3] / 255;
1727
+ if (selfAlpha < 0.35)
1728
+ continue;
1729
+ const x = x0 + lx;
1730
+ const y = y0 + ly;
1731
+ const px = x + 0.5;
1732
+ const py = y + 0.5;
1733
+ if (covered.some(rect => inside(rect, px, py)))
1734
+ continue;
1735
+ const pt = activeView ? inverseTransformPoint(activeView, px, py) : { x: px, y: py };
1736
+ const mask = activeSpotlights.length > 0 ? spotlightMaskSample(activeSpotlights, outputTimeMs, pt.x, pt.y) : undefined;
1737
+ const offset = (y * video.width + x) * 3;
1738
+ const withAlpha = withRgba[pOffset + 3] / 255;
1739
+ const withoutAlpha = withoutRgba ? withoutRgba[pOffset + 3] / 255 : 0;
1740
+ for (const channel of [0, 1, 2]) {
1741
+ let under = activeView
1742
+ ? sampleBilinearChannel(baseFrame, video.width, video.height, pt.x - 0.5, pt.y - 0.5, channel)
1743
+ : baseFrame[offset + channel];
1744
+ if (mask && mask.alpha > 0)
1745
+ under = under * (1 - mask.alpha) + mask.rgb[channel] * mask.alpha;
1746
+ for (const list of appPrimitives) {
1747
+ for (const primitive of list) {
1748
+ if (inside(primitive.rectangle, pt.x, pt.y))
1749
+ under = blendChannel(under, primitive, channel);
1750
+ }
1751
+ }
1752
+ const overWith = under * (1 - withAlpha) + withRgba[pOffset + channel] * withAlpha;
1753
+ const overWithout = withoutRgba ? under * (1 - withoutAlpha) + withoutRgba[pOffset + channel] * withoutAlpha : under;
1754
+ const expected = expectedActive ? overWith : overWithout;
1755
+ const opposite = expectedActive ? overWithout : overWith;
1756
+ expectedError += Math.abs(finalFrame[offset + channel] - expected);
1757
+ oppositeError += Math.abs(finalFrame[offset + channel] - opposite);
1758
+ contrast += Math.abs(expected - opposite);
1759
+ count++;
1760
+ }
1761
+ }
1762
+ }
1763
+ const maxError = activeView ? 20 : 18;
1764
+ const passed = count > 0 && contrast / count >= 6 && expectedError / count <= maxError && expectedError < oppositeError * 0.72;
1765
+ return {
1766
+ passed,
1767
+ expected_error: count ? expectedError / count : null,
1768
+ opposite_error: count ? oppositeError / count : null,
1769
+ contrast: count ? contrast / count : null,
1770
+ };
1771
+ };
1772
+ if (item.first_frame > 0) {
1773
+ const beforeFrame = item.first_frame - 1;
1774
+ const activeSampleTime = activeFrame * 1000 / video.fps;
1775
+ coverage.push(`${item.id}:before_start:frame_${beforeFrame}`);
1776
+ const order = enqueue(beforeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1777
+ const metrics = measureArrowPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps, activeArrows);
1778
+ orderedChecks.push({
1779
+ order,
1780
+ entry: { annotation: item.id, part: 'arrow', boundary: 'before_start', frame_index: beforeFrame, encoded_ms: timestampMs, expected_active: false, ...metrics },
1781
+ gap: metrics.passed ? undefined : `${item.id}:arrow:before_start: frame ${beforeFrame} does not confirm arrow absent before start`,
1782
+ });
1783
+ });
1784
+ }
1785
+ if (activeFrame < totalFrames) {
1786
+ coverage.push(`${item.id}:start:frame_${activeFrame}`);
1787
+ const order = enqueue(activeFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1788
+ const metrics = measureArrowPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1789
+ orderedChecks.push({
1790
+ order,
1791
+ entry: { annotation: item.id, part: 'arrow', boundary: 'start', frame_index: activeFrame, encoded_ms: timestampMs, expected_active: true, ...metrics },
1792
+ gap: metrics.passed ? undefined : `${item.id}:arrow:start: frame ${activeFrame} does not confirm arrow appearance`,
1793
+ });
1794
+ });
1795
+ checkBoundaryTimestamp(item.id, 'start', item.first_frame, item.start_ms);
1796
+ }
1797
+ if (item.motion_type === 'draw' && item.in_ms > 0) {
1798
+ const lastAvailable = Math.min(item.end_frame, totalFrames) - 1;
1799
+ let midFrame;
1800
+ let bestDist = Infinity;
1801
+ for (let frame = item.first_frame; frame <= lastAvailable; frame++) {
1802
+ const t = frame * 1000 / video.fps;
1803
+ if (t >= item.start_ms + item.in_ms)
1804
+ break;
1805
+ const p = arrowMotionState(item, t).progress;
1806
+ if (p >= 0.2 && p <= 0.75) {
1807
+ const dist = Math.abs(p - 0.5);
1808
+ if (dist < bestDist) {
1809
+ bestDist = dist;
1810
+ midFrame = frame;
1811
+ }
1812
+ }
1813
+ }
1814
+ if (midFrame === undefined) {
1815
+ coverage.push(`${item.id}:draw_in:unobservable_at_${video.fps}fps`);
1816
+ gaps.push(`${item.id}:arrow:draw_in: draw_in (${item.in_ms} ms) has no observable partial frame at ${video.fps} fps`);
1817
+ }
1818
+ else {
1819
+ const drawFrame = midFrame;
1820
+ coverage.push(`${item.id}:draw_in:frame_${drawFrame}`);
1821
+ const order = enqueue(drawFrame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1822
+ const metrics = measureArrowPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, outputTimeMs, true, activeLasers, activeStamps, activeArrows);
1823
+ orderedChecks.push({
1824
+ order,
1825
+ entry: { annotation: item.id, part: 'arrow', boundary: 'draw_in', frame_index: drawFrame, encoded_ms: timestampMs, expected_active: 'partial', ...metrics },
1826
+ gap: metrics.passed ? undefined : `${item.id}:arrow:draw_in: frame ${drawFrame} does not confirm partial arrow draw progression`,
1827
+ });
1828
+ });
1829
+ }
1830
+ }
1831
+ if (item.end_frame < totalFrames) {
1832
+ const activeSampleTime = activeFrame * 1000 / video.fps;
1833
+ coverage.push(`${item.id}:end:frame_${item.end_frame}`);
1834
+ const order = enqueue(item.end_frame, (finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, timestampMs, activeLasers, activeStamps, activeArrows) => {
1835
+ const metrics = measureArrowPresence(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTimeMs, activeSampleTime, false, activeLasers, activeStamps, activeArrows);
1836
+ orderedChecks.push({
1837
+ order,
1838
+ entry: { annotation: item.id, part: 'arrow', boundary: 'end', frame_index: item.end_frame, encoded_ms: timestampMs, expected_active: false, ...metrics },
1839
+ gap: metrics.passed ? undefined : `${item.id}:arrow:end: frame ${item.end_frame} does not confirm arrow cleared after end`,
1840
+ });
1841
+ });
1842
+ checkBoundaryTimestamp(item.id, 'end', item.end_frame, item.end_ms);
1843
+ }
1844
+ break;
1845
+ }
1637
1846
  }
1638
1847
  }
1639
1848
  const indices = [...tasksByFrame.keys()].sort((a, b) => a - b);
@@ -1674,6 +1883,7 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1674
1883
  const activeSpotlights = activeApps.filter((app) => app.effect === 'spotlight');
1675
1884
  const activeLasers = [];
1676
1885
  const activeStamps = [];
1886
+ const activeArrows = [];
1677
1887
  for (let idx = 0; idx < applications.length; idx++) {
1678
1888
  const app = applications[idx];
1679
1889
  if (index >= app.first_frame && index < app.end_frame) {
@@ -1681,6 +1891,8 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1681
1891
  activeLasers.push({ index: idx, effect: app });
1682
1892
  else if (app.effect === 'stamp')
1683
1893
  activeStamps.push({ index: idx, effect: app });
1894
+ else if (app.effect === 'arrow')
1895
+ activeArrows.push({ index: idx, effect: app });
1684
1896
  }
1685
1897
  }
1686
1898
  const activeView = activeViewTransform(activeApps, outputTime);
@@ -1688,7 +1900,7 @@ export async function verifyAnnotations(file, base, baseFilter, applications, vi
1688
1900
  ? effectPrimitives([app], outputTime).map(toRgbPrimitive)
1689
1901
  : []);
1690
1902
  for (const task of tasksByFrame.get(index) ?? []) {
1691
- task.run(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTime, timestampMs, activeLasers, activeStamps);
1903
+ task.run(finalFrame, baseFrame, covered, appPrimitives, activeSpotlights, activeView, outputTime, timestampMs, activeLasers, activeStamps, activeArrows);
1692
1904
  }
1693
1905
  }
1694
1906
  const [finalEnded, baseEnded] = await Promise.all([
package/dist/assembly.js CHANGED
@@ -1,10 +1,107 @@
1
1
  import { join, dirname } from 'node:path';
2
+ import { spawn } from 'node:child_process';
3
+ import { createWriteStream } from 'node:fs';
2
4
  import { lstat, mkdir, mkdtemp, link, rm, copyFile, writeFile } from 'node:fs/promises';
3
5
  import { defaultVideoOutput } from './contracts.js';
4
- import { execute, ffmpegFilterScriptFlags, hashFile, probe, decode, saveJson } from './media.js';
5
- import { requireCondition } from './errors.js';
6
- import { configuredLicense } from './executables.js';
6
+ import { execute, executionScope, executionSignal, ffmpegFilterScriptFlags, hashFile, probe, decode, saveJson } from './media.js';
7
+ import { ProductionError, requireCondition } from './errors.js';
8
+ import { configuredLicense, executable } from './executables.js';
7
9
  import { annotationApplications, verifyAnnotations } from './annotations.js';
10
+ const NARRATION_SAMPLE_RATE = 48000;
11
+ const NARRATION_CHANNELS = 2;
12
+ const NARRATION_BYTES_PER_SAMPLE = 4 * NARRATION_CHANNELS; // f32le stereo
13
+ const ZERO_CHUNK = Buffer.alloc(65536);
14
+ async function writeChunk(stream, chunk) {
15
+ executionSignal()?.throwIfAborted();
16
+ if (stream.write(chunk))
17
+ return;
18
+ await new Promise((resolve, reject) => {
19
+ const onDrain = () => { cleanup(); resolve(); };
20
+ const onError = (error) => { cleanup(); reject(error); };
21
+ const cleanup = () => { stream.off('drain', onDrain); stream.off('error', onError); };
22
+ stream.once('drain', onDrain);
23
+ stream.once('error', onError);
24
+ });
25
+ }
26
+ async function appendDecodedNarration(stream, audioPath, maxBytes) {
27
+ const command = executable('ffmpeg');
28
+ const context = executionScope.getStore();
29
+ const signal = context?.signal;
30
+ signal?.throwIfAborted();
31
+ const child = spawn(command, ['-v', 'error', '-xerror', '-i', audioPath, '-vn', '-ac', String(NARRATION_CHANNELS), '-ar', String(NARRATION_SAMPLE_RATE), '-f', 'f32le', '-'], {
32
+ stdio: ['ignore', 'pipe', 'pipe'],
33
+ signal,
34
+ killSignal: 'SIGKILL',
35
+ windowsHide: true,
36
+ });
37
+ const err = [];
38
+ const limit = context?.bounded ? undefined : 120000;
39
+ const timer = limit !== undefined ? setTimeout(() => { child.kill('SIGKILL'); }, limit) : undefined;
40
+ child.stderr.on('data', data => err.push(data));
41
+ const exit = new Promise((resolve, reject) => {
42
+ child.on('error', error => { clearTimeout(timer); reject(new ProductionError('DEPENDENCY', `${command}: ${error.message}`, 3)); });
43
+ child.on('close', code => {
44
+ clearTimeout(timer);
45
+ if (code !== 0)
46
+ reject(new ProductionError('SUBPROCESS', `${command} exited ${code}: ${Buffer.concat(err).toString().slice(-4000)}`, 3));
47
+ else
48
+ resolve();
49
+ });
50
+ });
51
+ let written = 0;
52
+ try {
53
+ for await (const chunk of child.stdout) {
54
+ const remaining = maxBytes - written;
55
+ if (remaining <= 0)
56
+ continue;
57
+ const slice = chunk.length <= remaining ? chunk : chunk.subarray(0, remaining);
58
+ if (slice.length > 0) {
59
+ await writeChunk(stream, slice);
60
+ written += slice.length;
61
+ }
62
+ }
63
+ await exit;
64
+ }
65
+ catch (error) {
66
+ child.kill('SIGKILL');
67
+ await exit.catch(() => { });
68
+ throw error;
69
+ }
70
+ return written;
71
+ }
72
+ async function writeNarrationTrack(destination, items, audioOrigin) {
73
+ const stream = createWriteStream(destination);
74
+ let writtenSamples = 0;
75
+ try {
76
+ for (const { item, asset } of items) {
77
+ executionSignal()?.throwIfAborted();
78
+ const targetStartSample = Math.round(((item.start_ms + audioOrigin) * NARRATION_SAMPLE_RATE) / 1000);
79
+ requireCondition(targetStartSample >= writtenSamples, 'ASSEMBLY', `Narration segment ${item.id} overlaps an earlier segment`, 7);
80
+ let gapBytes = (targetStartSample - writtenSamples) * NARRATION_BYTES_PER_SAMPLE;
81
+ while (gapBytes > 0) {
82
+ const size = Math.min(gapBytes, ZERO_CHUNK.length);
83
+ await writeChunk(stream, size === ZERO_CHUNK.length ? ZERO_CHUNK : ZERO_CHUNK.subarray(0, size));
84
+ gapBytes -= size;
85
+ }
86
+ writtenSamples = targetStartSample;
87
+ const maxSamples = Math.round((asset.duration_ms * NARRATION_SAMPLE_RATE) / 1000);
88
+ const writtenBytes = await appendDecodedNarration(stream, asset.audio, maxSamples * NARRATION_BYTES_PER_SAMPLE);
89
+ const remainder = writtenBytes % NARRATION_BYTES_PER_SAMPLE;
90
+ if (remainder !== 0) {
91
+ await writeChunk(stream, ZERO_CHUNK.subarray(0, NARRATION_BYTES_PER_SAMPLE - remainder));
92
+ }
93
+ writtenSamples += Math.ceil(writtenBytes / NARRATION_BYTES_PER_SAMPLE);
94
+ }
95
+ await new Promise((resolve, reject) => {
96
+ stream.once('error', reject);
97
+ stream.end(() => resolve());
98
+ });
99
+ }
100
+ catch (error) {
101
+ stream.destroy();
102
+ throw error;
103
+ }
104
+ }
8
105
  export async function assemble(schedule, speech, visual, directory, output, options = { verify_timing: false, output: defaultVideoOutput }) {
9
106
  const video = options.output;
10
107
  const licensed = options.licensed ?? configuredLicense();
@@ -52,7 +149,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
52
149
  const frameCount = Math.ceil(duration * video.fps - 1e-9);
53
150
  const annotations = annotationApplications(video, schedule, visual, audioOrigin);
54
151
  const renderer = annotations.length || schedule.overlays?.length || !licensed ? await import('./compositor.js') : undefined;
55
- const layers = await renderer?.frameLayers(video, schedule, licensed, options.inputHashes) ?? [];
152
+ const layers = await renderer?.frameLayers(video, schedule, options.inputHashes) ?? [];
56
153
  const { canvasLayers, staticTopLayers } = renderer ? renderer.splitFrameLayers(layers) : { canvasLayers: [], staticTopLayers: [] };
57
154
  const plan = renderer ? renderer.planCompositor(frameCount, video.fps, audioOrigin, annotations, canvasLayers) : { kind: 'none' };
58
155
  let layerImage;
@@ -60,62 +157,69 @@ export async function assemble(schedule, speech, visual, directory, output, opti
60
157
  layerImage = join(temporaryDirectory, 'overlays.png');
61
158
  await renderer.writeStaticFrameLayers(layerImage, video, staticTopLayers);
62
159
  }
160
+ let watermarkImage;
161
+ let watermarkRect;
162
+ if (!licensed) {
163
+ watermarkImage = join(temporaryDirectory, 'watermark.png');
164
+ watermarkRect = await renderer.writeWatermarkMask(watermarkImage, video);
165
+ }
166
+ const hasPostLayers = Boolean(layerImage || watermarkImage);
167
+ const stageOut = hasPostLayers ? 'stage_v' : 'v';
63
168
  let input = 1;
64
169
  switch (plan.kind) {
65
170
  case 'none':
66
171
  args.push('-i', visual.file);
67
- if (layerImage) {
68
- args.push('-i', layerImage);
69
- filters.push(`[0:v]${baseFilter}[base]`, '[base][1:v]overlay=eof_action=repeat,format=yuv420p[v]');
70
- input = 2;
71
- }
72
- else {
73
- filters.push(`[0:v]${baseFilter}[v]`);
74
- input = 1;
75
- }
172
+ filters.push(`[0:v]${baseFilter}[${stageOut}]`);
173
+ input = 1;
76
174
  break;
77
175
  case 'sparse':
78
176
  args.push('-i', visual.file);
79
177
  args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${video.width}x${video.height}`, '-framerate', String(video.fps), '-i', 'pipe:0');
80
- if (layerImage) {
81
- args.push('-i', layerImage);
82
- filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}'[comp]`, '[comp][2:v]overlay=eof_action=repeat,format=yuv420p[v]');
83
- input = 3;
84
- }
85
- else {
86
- filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}',format=yuv420p[v]`);
87
- input = 2;
88
- }
178
+ filters.push(`[0:v]${baseFilter}[base]`, `[1:v]setpts='${plan.ptsExpr}'[comp_in]`, `[base][comp_in]overlay=eof_action=pass:format=rgb:enable='${plan.betweenExpr}',format=yuv420p[${stageOut}]`);
179
+ input = 2;
89
180
  break;
90
181
  case 'full':
91
182
  args.push('-f', 'rawvideo', '-pixel_format', 'rgba', '-video_size', `${video.width}x${video.height}`, '-framerate', String(video.fps), '-i', 'pipe:0');
92
- if (layerImage) {
93
- args.push('-i', layerImage);
94
- filters.push('[0:v]format=yuv420p[base]', '[base][1:v]overlay=eof_action=repeat,format=yuv420p[v]');
95
- input = 2;
96
- }
97
- else {
98
- filters.push('[0:v]format=yuv420p[v]');
99
- input = 1;
100
- }
183
+ filters.push(`[0:v]format=yuv420p[${stageOut}]`);
184
+ input = 1;
101
185
  break;
102
186
  default: {
103
187
  const _exhaustive = plan;
104
188
  throw new Error(`Unhandled compositor plan: ${String(_exhaustive)}`);
105
189
  }
106
190
  }
191
+ let currentStream = stageOut;
192
+ if (layerImage) {
193
+ args.push('-i', layerImage);
194
+ const nextStream = watermarkImage ? 'topped_v' : 'v';
195
+ filters.push(`[${currentStream}][${input}:v]overlay=eof_action=repeat,format=yuv420p[${nextStream}]`);
196
+ currentStream = nextStream;
197
+ input++;
198
+ }
199
+ if (watermarkImage && watermarkRect) {
200
+ args.push('-i', watermarkImage);
201
+ filters.push(...renderer.watermarkFilters(currentStream, input, 'v', watermarkRect));
202
+ input++;
203
+ }
107
204
  if (annotations.length)
108
205
  await saveJson(join(directory, 'annotations-applied.json'), { version: 1, annotations });
206
+ const narrationItems = [];
109
207
  for (const item of schedule.actions) {
110
208
  if (item.action.type === 'speak') {
111
209
  const segment = item.action.segment;
112
210
  const asset = speech.assets.find(a => a.id === segment);
113
- args.push('-i', asset.audio);
114
- filters.push(`[${input}:a]atrim=duration=${asset.duration_ms / 1000},asetpts=PTS-STARTPTS,adelay=${item.start_ms + audioOrigin}:all=1[a${input}]`);
115
- tracks.push(`[a${input}]`);
211
+ narrationItems.push({ item, asset });
116
212
  transformations.push({ id: item.id, kind: 'narration', start_ms: item.start_ms, duration_ms: asset.duration_ms });
117
- input++;
118
213
  }
214
+ }
215
+ if (narrationItems.length) {
216
+ const narrationPath = join(temporaryDirectory, 'narration.pcm');
217
+ await writeNarrationTrack(narrationPath, narrationItems, audioOrigin);
218
+ args.push('-f', 'f32le', '-ar', String(NARRATION_SAMPLE_RATE), '-ac', String(NARRATION_CHANNELS), '-i', narrationPath);
219
+ tracks.push(`[${input}:a]`);
220
+ input++;
221
+ }
222
+ for (const item of schedule.actions) {
119
223
  if (item.action.type === 'play' && item.action.audio === 'source') {
120
224
  const action = item.action;
121
225
  const media = schedule.media.find(m => m.id === action.media);
@@ -126,7 +230,9 @@ export async function assemble(schedule, speech, visual, directory, output, opti
126
230
  input++;
127
231
  }
128
232
  }
129
- if (tracks.length)
233
+ if (tracks.length === 1)
234
+ filters.push(`${tracks[0]}apad,atrim=duration=${duration}[a]`);
235
+ else if (tracks.length > 1)
130
236
  filters.push(`${tracks.join('')}amix=inputs=${tracks.length}:normalize=0,apad,atrim=duration=${duration}[a]`);
131
237
  const filterScript = join(temporaryDirectory, 'filter-complex.txt');
132
238
  await writeFile(filterScript, filters.join(';'));
@@ -152,7 +258,7 @@ export async function assemble(schedule, speech, visual, directory, output, opti
152
258
  let annotationEvidence;
153
259
  if (annotations.length && options.verify_timing) {
154
260
  try {
155
- annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin), outputSha256);
261
+ annotationEvidence = await verifyAnnotations(temporary, visual.file, baseFilter, annotations, video, directory, output, frame => renderer.visibleFrameLayerBounds(layers, frame, video.fps, audioOrigin, watermarkRect), outputSha256);
156
262
  }
157
263
  catch (error) {
158
264
  await copyFile(temporary, join(directory, 'failed-composite.mp4'));