mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-12-02 05:54:44 +00:00
fix(search): preview matched video chunks on hover (#540)
* fix(search): preview matched video chunks on hover * fix(search): show chunk covers before hover * fix(search): reuse sprites for whole-video matches
This commit is contained in:
@@ -12,6 +12,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **search**: Video segment matches in Semantic Search and Find Similar show the segment’s first frame and let you scrub through it on hover. Matches that span the entire video reuse its full preview when available.
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
|
- **transcode**: Offload video chunk slicing for search embeddings to the transcode worker queue.
|
||||||
|
|||||||
@@ -96,6 +96,7 @@ apps/web/e2e/
|
|||||||
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
|
| Owner searches the file list by Chinese, Japanese, and Korean name keywords | `tests/project/search-file-list.spec.ts` |
|
||||||
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
|
| Owner searches the file list with a keyword and a filter condition | `tests/project/search-file-list.spec.ts` |
|
||||||
| Owner finds similar media and filters the results by type | `tests/project/search-file-list.spec.ts` |
|
| Owner finds similar media and filters the results by type | `tests/project/search-file-list.spec.ts` |
|
||||||
|
| Owner previews matched video ranges in both search dialogs | `tests/project/search-file-list.spec.ts` |
|
||||||
| Owner submits a resized image with filters and can remove the attachment | `tests/project/search-file-list.spec.ts` |
|
| Owner submits a resized image with filters and can remove the attachment | `tests/project/search-file-list.spec.ts` |
|
||||||
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
|
| Owner saves a search result as a collection | `tests/project/save-search-collection.spec.ts` |
|
||||||
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
| Image share with watermark + download disabled: no download buttons on public list/detail pages, watermarked proxy served, download-url rejected | `tests/project/share-watermark-no-download.spec.ts` |
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { APIRequestContext } from '@playwright/test'
|
import type { APIRequestContext, Locator } from '@playwright/test'
|
||||||
import type { AssetInfo, ImageSearchRequest } from '@shumai/dtos'
|
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
|
||||||
import { expect, test } from '../../fixtures'
|
import { expect, test } from '../../fixtures'
|
||||||
import { apiUploadFile, fileCard } from '../../helpers/files'
|
import { apiUploadFile, fileCard } from '../../helpers/files'
|
||||||
|
|
||||||
@@ -165,6 +165,104 @@ test('owner searches the file list with a keyword and a filter condition', async
|
|||||||
test.describe('image search', () => {
|
test.describe('image search', () => {
|
||||||
test.use({ fileOptions: { mediaType: 'image' } })
|
test.use({ fileOptions: { mediaType: 'image' } })
|
||||||
|
|
||||||
|
test('owner previews matched video ranges in both search dialogs', async ({ file }) => {
|
||||||
|
const { page, teamId, projectId, rootFolderId, fileName } = file
|
||||||
|
const layout = { columns: 5, rows: 2, frameCount: 7 }
|
||||||
|
const video: AssetInfo = {
|
||||||
|
id: 'video-result',
|
||||||
|
name: 'result.mp4',
|
||||||
|
type: 'file',
|
||||||
|
sizeByte: 100,
|
||||||
|
fileCount: 1,
|
||||||
|
status: 'processed',
|
||||||
|
createdAt: '2026-01-01T00:00:00.000Z',
|
||||||
|
updatedAt: '2026-01-01T00:00:00.000Z',
|
||||||
|
proxyType: 'video',
|
||||||
|
preview: {
|
||||||
|
thumbnailUrl: '/test-sprites/poster.svg',
|
||||||
|
spriteUrl: '/test-sprites/full.svg',
|
||||||
|
originalWidth: 100,
|
||||||
|
originalHeight: 40,
|
||||||
|
},
|
||||||
|
startTime: 0,
|
||||||
|
endTime: 30,
|
||||||
|
matchedSprite: { ...layout, url: '/test-sprites/chunk.svg' },
|
||||||
|
}
|
||||||
|
const brokenMatch: AssetInfo = {
|
||||||
|
...video,
|
||||||
|
startTime: 55,
|
||||||
|
endTime: 85,
|
||||||
|
matchedSprite: { ...layout, url: '/test-sprites/broken.svg' },
|
||||||
|
}
|
||||||
|
const secondMatch: AssetInfo = {
|
||||||
|
...video,
|
||||||
|
startTime: 25,
|
||||||
|
endTime: 55,
|
||||||
|
matchedSprite: { ...layout, url: '/test-sprites/second.svg' },
|
||||||
|
}
|
||||||
|
await page.route(`**/api/teams/${teamId}/settings`, async (route) => {
|
||||||
|
const response = await route.fetch()
|
||||||
|
await route.fulfill({
|
||||||
|
response,
|
||||||
|
json: { ...(await response.json()), semanticSearchEnabled: true },
|
||||||
|
})
|
||||||
|
})
|
||||||
|
const results = { json: { data: [video, secondMatch, brokenMatch], pageInfo: { total: 3 } } }
|
||||||
|
await page.route(`**/api/folders/${rootFolderId}/image-search`, (route) =>
|
||||||
|
route.fulfill(results),
|
||||||
|
)
|
||||||
|
await page.route(`**/api/folders/${rootFolderId}/search`, (route) => {
|
||||||
|
const request = route.request().postDataJSON() as SearchRequest | null
|
||||||
|
return request?.isSemantic ? route.fulfill(results) : route.continue()
|
||||||
|
})
|
||||||
|
await page.route('**/test-sprites/*.svg', (route) =>
|
||||||
|
route.request().url().endsWith('/broken.svg')
|
||||||
|
? route.fulfill({ status: 404 })
|
||||||
|
: route.fulfill({
|
||||||
|
contentType: 'image/svg+xml',
|
||||||
|
body: '<svg xmlns="http://www.w3.org/2000/svg" width="100" height="40"/>',
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
async function verifyPreviews(dialog: Locator) {
|
||||||
|
const heading = dialog.getByRole('heading').first()
|
||||||
|
await heading.hover()
|
||||||
|
const cards = dialog.getByTestId('sprite-scrubber')
|
||||||
|
const firstFrame = cards.nth(0).locator('.opacity-100 > [style*="/test-sprites/chunk.svg"]')
|
||||||
|
const secondFrame = cards.nth(1).locator('.opacity-100 > [style*="/test-sprites/second.svg"]')
|
||||||
|
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
|
||||||
|
await expect(secondFrame).toHaveCSS('background-position', '0px 0px')
|
||||||
|
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
|
||||||
|
await expect(dialog.locator('[style*="/test-sprites/full.svg"]')).toHaveCount(0)
|
||||||
|
|
||||||
|
await cards.nth(0).hover()
|
||||||
|
await expect(cards.nth(0)).not.toHaveAttribute('data-frame', '0')
|
||||||
|
await heading.hover()
|
||||||
|
await expect(firstFrame).toHaveCSS('background-position', '0px 0px')
|
||||||
|
|
||||||
|
await cards.nth(2).hover()
|
||||||
|
await expect(
|
||||||
|
cards.nth(2).locator('.opacity-100 > [style*="/test-sprites/full.svg"]'),
|
||||||
|
).toBeVisible()
|
||||||
|
await heading.hover()
|
||||||
|
await expect(cards.nth(2).getByAltText('Thumbnail')).toHaveClass(/opacity-100/)
|
||||||
|
}
|
||||||
|
|
||||||
|
await page.goto(`/projects/${projectId}`)
|
||||||
|
await fileCard(page, fileName).click({ button: 'right' })
|
||||||
|
await page.getByRole('menuitem', { name: 'Find similar' }).click()
|
||||||
|
await verifyPreviews(page.getByRole('dialog', { name: 'Find similar' }))
|
||||||
|
|
||||||
|
await page.keyboard.press('Escape')
|
||||||
|
await page.getByRole('button', { name: 'Search' }).click()
|
||||||
|
const semanticSearch = page.getByRole('dialog', { name: 'Search', exact: true })
|
||||||
|
await semanticSearch.getByRole('switch', { name: 'Semantic Search' }).click()
|
||||||
|
const searchInput = semanticSearch.getByPlaceholder('Search records by content...')
|
||||||
|
await searchInput.fill('video scene')
|
||||||
|
await searchInput.press('Enter')
|
||||||
|
await verifyPreviews(semanticSearch)
|
||||||
|
})
|
||||||
|
|
||||||
test('owner finds similar media and filters the results by type', async ({ file }) => {
|
test('owner finds similar media and filters the results by type', async ({ file }) => {
|
||||||
const { page, teamId, projectId, rootFolderId, fileId, fileName } = file
|
const { page, teamId, projectId, rootFolderId, fileId, fileName } = file
|
||||||
const source = fileCard(page, fileName)
|
const source = fileCard(page, fileName)
|
||||||
|
|||||||
@@ -251,6 +251,7 @@ export const saveAssetEmbeddingsActivity = defineStep(
|
|||||||
embedding: number[]
|
embedding: number[]
|
||||||
startTime?: number
|
startTime?: number
|
||||||
endTime?: number
|
endTime?: number
|
||||||
|
sprite?: PrismaJson.VideoChunkSprite
|
||||||
}>
|
}>
|
||||||
}) {
|
}) {
|
||||||
for (const item of params.embeddings) {
|
for (const item of params.embeddings) {
|
||||||
@@ -258,15 +259,16 @@ export const saveAssetEmbeddingsActivity = defineStep(
|
|||||||
const is768 = item.embedding.length === 768
|
const is768 = item.embedding.length === 768
|
||||||
|
|
||||||
if (item.startTime !== undefined && item.endTime !== undefined) {
|
if (item.startTime !== undefined && item.endTime !== undefined) {
|
||||||
|
const sprite = item.sprite ? JSON.stringify(item.sprite) : null
|
||||||
if (is768) {
|
if (is768) {
|
||||||
await prisma.$executeRaw`
|
await prisma.$executeRaw`
|
||||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, updated_at)
|
INSERT INTO asset_embeddings (id, asset_id, embedding_768, start_time, end_time, sprite, updated_at)
|
||||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
|
||||||
`
|
`
|
||||||
} else {
|
} else {
|
||||||
await prisma.$executeRaw`
|
await prisma.$executeRaw`
|
||||||
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, updated_at)
|
INSERT INTO asset_embeddings (id, asset_id, embedding, start_time, end_time, sprite, updated_at)
|
||||||
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, NOW())
|
VALUES (gen_random_uuid()::text, ${params.assetId}, ${embVec}::vector, ${item.startTime}, ${item.endTime}, ${sprite}::jsonb, NOW())
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
@@ -512,6 +514,7 @@ export interface VideoChunkRange {
|
|||||||
|
|
||||||
export interface TranscodedVideoChunk extends VideoChunkRange {
|
export interface TranscodedVideoChunk extends VideoChunkRange {
|
||||||
chunkKey: string
|
chunkKey: string
|
||||||
|
sprite?: PrismaJson.VideoChunkSprite
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface TranscodeVideoChunksParams {
|
export interface TranscodeVideoChunksParams {
|
||||||
|
|||||||
@@ -206,6 +206,7 @@ export async function agentEmbeddingMedia(task: WorkflowTask): Promise<void> {
|
|||||||
embedding: chunkResult.embedding,
|
embedding: chunkResult.embedding,
|
||||||
startTime: chunk.startTime,
|
startTime: chunk.startTime,
|
||||||
endTime: chunk.endTime,
|
endTime: chunk.endTime,
|
||||||
|
...(chunk.sprite && { sprite: chunk.sprite }),
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { prisma, Prisma } from '@shumai/db'
|
|||||||
import { setupTestDbHooks } from '@shumai/db/test'
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
import { imageSearchRequestSchema } from '@shumai/dtos'
|
import { imageSearchRequestSchema } from '@shumai/dtos'
|
||||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
import { imageEmbeddingService } from './image-embedding'
|
import { imageEmbeddingService } from './image-embedding'
|
||||||
import { searchService } from './search'
|
import { searchService } from './search'
|
||||||
|
|
||||||
@@ -14,12 +15,13 @@ async function insertEmbedding(
|
|||||||
embedding: number[],
|
embedding: number[],
|
||||||
startTime: number | null = null,
|
startTime: number | null = null,
|
||||||
endTime: number | null = null,
|
endTime: number | null = null,
|
||||||
|
sprite?: PrismaJson.VideoChunkSprite,
|
||||||
) {
|
) {
|
||||||
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
const column = embedding.length === 768 ? Prisma.sql`embedding_768` : Prisma.sql`embedding`
|
||||||
await prisma.$executeRaw`
|
await prisma.$executeRaw`
|
||||||
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, created_at, updated_at)
|
INSERT INTO asset_embeddings (id, asset_id, ${column}, start_time, end_time, sprite, created_at, updated_at)
|
||||||
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
|
VALUES (gen_random_uuid()::text, ${assetId}, ${JSON.stringify(embedding)}::vector,
|
||||||
${startTime}, ${endTime}, NOW(), NOW())
|
${startTime}, ${endTime}, ${sprite ? JSON.stringify(sprite) : null}::jsonb, NOW(), NOW())
|
||||||
`
|
`
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,8 +82,10 @@ describe('image search', () => {
|
|||||||
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
|
await prisma.asset.update({ where: { id: deleted.id }, data: { isDeleted: true } })
|
||||||
|
|
||||||
await insertEmbedding(source.id, vector(1536, 1))
|
await insertEmbedding(source.id, vector(1536, 1))
|
||||||
await insertEmbedding(video.id, vector(1536, 1), 4, 12)
|
const firstSprite = { key: 'files/video/chunk-4-12.webp', columns: 5, rows: 2, frameCount: 8 }
|
||||||
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20)
|
const secondSprite = { ...firstSprite, key: 'files/video/chunk-12-20.webp' }
|
||||||
|
await insertEmbedding(video.id, vector(1536, 1), 4, 12, firstSprite)
|
||||||
|
await insertEmbedding(video.id, vector(1536, 0, 1), 12, 20, secondSprite)
|
||||||
await insertEmbedding(image.id, vector(1536, 1, 1))
|
await insertEmbedding(image.id, vector(1536, 1, 1))
|
||||||
await insertEmbedding(deleted.id, vector(1536, 1))
|
await insertEmbedding(deleted.id, vector(1536, 1))
|
||||||
await insertEmbedding(audio.id, vector(1536, 1))
|
await insertEmbedding(audio.id, vector(1536, 1))
|
||||||
@@ -93,13 +97,25 @@ describe('image search', () => {
|
|||||||
imageSearchRequestSchema.parse({ ...request, first: 2 }),
|
imageSearchRequestSchema.parse({ ...request, first: 2 }),
|
||||||
)
|
)
|
||||||
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
|
expect(first.data.map((item) => item.id)).toEqual([video.id, image.id])
|
||||||
expect(first.data[0]).toMatchObject({ startTime: 4, endTime: 12 })
|
expect(first.data[0]).toMatchObject({
|
||||||
|
startTime: 4,
|
||||||
|
endTime: 12,
|
||||||
|
matchedSprite: { url: expect.stringContaining(firstSprite.key) },
|
||||||
|
})
|
||||||
|
expect(first.data[1].matchedSprite).toBeUndefined()
|
||||||
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
|
expect(first.pageInfo).toMatchObject({ total: 3, cursor: expect.any(String) })
|
||||||
const next = await searchService.searchByImage(
|
const next = await searchService.searchByImage(
|
||||||
root.id,
|
root.id,
|
||||||
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
|
imageSearchRequestSchema.parse({ ...request, first: 2, after: first.pageInfo.cursor }),
|
||||||
)
|
)
|
||||||
expect(next.data).toMatchObject([{ id: video.id, startTime: 12, endTime: 20 }])
|
expect(next.data).toMatchObject([
|
||||||
|
{
|
||||||
|
id: video.id,
|
||||||
|
startTime: 12,
|
||||||
|
endTime: 20,
|
||||||
|
matchedSprite: { url: expect.stringContaining(secondSprite.key) },
|
||||||
|
},
|
||||||
|
])
|
||||||
expect(next.pageInfo.cursor).toBeUndefined()
|
expect(next.pageInfo.cursor).toBeUndefined()
|
||||||
|
|
||||||
const images = await searchService.searchByImage(
|
const images = await searchService.searchByImage(
|
||||||
@@ -129,6 +145,60 @@ describe('image search', () => {
|
|||||||
expect(result.data.map((item) => item.id)).toEqual([image.id])
|
expect(result.data.map((item) => item.id)).toEqual([image.id])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it.each([
|
||||||
|
{ startTime: 0, endTime: 10, stored: true, useFullSprite: true },
|
||||||
|
{ startTime: 0, endTime: 10, stored: false, useFullSprite: false },
|
||||||
|
{ startTime: 0, endTime: 5, stored: true, useFullSprite: false },
|
||||||
|
{ startTime: 5, endTime: 10, stored: true, useFullSprite: false },
|
||||||
|
])(
|
||||||
|
'picks the preview for $startTime–$endTime when full sprite availability is $stored',
|
||||||
|
async ({ startTime, endTime, stored, useFullSprite }) => {
|
||||||
|
const { root, source, file } = await createProjectAssets()
|
||||||
|
const video = await file('result.mp4', 'video/mp4')
|
||||||
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
|
const fullKey = `files/${video.id}/sprite.webp`
|
||||||
|
const chunkKey = `files/${video.id}/chunk.webp`
|
||||||
|
await prisma.asset.update({
|
||||||
|
where: { id: video.id },
|
||||||
|
data: {
|
||||||
|
media: {
|
||||||
|
duration: 10,
|
||||||
|
proxyType: 'video',
|
||||||
|
sprite: { key: fullKey, frames: 100, tileX: 10, tileY: 10 },
|
||||||
|
} as PrismaJson.MediaInfo,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
if (stored) await s3Service.putObject(bucket, fullKey, 'sprite', 6, 'image/webp')
|
||||||
|
try {
|
||||||
|
await insertEmbedding(source.id, vector(1536, 1))
|
||||||
|
await insertEmbedding(video.id, vector(1536, 1), startTime, endTime, {
|
||||||
|
key: chunkKey,
|
||||||
|
columns: 5,
|
||||||
|
rows: 2,
|
||||||
|
frameCount: 10,
|
||||||
|
})
|
||||||
|
|
||||||
|
const result = await searchService.searchByImage(
|
||||||
|
root.id,
|
||||||
|
imageSearchRequestSchema.parse({ sourceAssetId: source.id }),
|
||||||
|
)
|
||||||
|
expect(result.data).toHaveLength(1)
|
||||||
|
expect(result.data[0]).toMatchObject({
|
||||||
|
startTime,
|
||||||
|
endTime,
|
||||||
|
preview: { spriteUrl: expect.stringContaining(fullKey) },
|
||||||
|
})
|
||||||
|
if (useFullSprite) {
|
||||||
|
expect(result.data[0].matchedSprite).toBeUndefined()
|
||||||
|
} else {
|
||||||
|
expect(result.data[0].matchedSprite?.url).toContain(chunkKey)
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
if (stored) await s3Service.deleteObject(bucket, fullKey)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
|
it('limits an uploaded-image search to the folder and applies metadata filters', async () => {
|
||||||
const { team, subfolder, source, file } = await createProjectAssets()
|
const { team, subfolder, source, file } = await createProjectAssets()
|
||||||
const match = await file('approved.png', 'image/png', subfolder.id)
|
const match = await file('approved.png', 'image/png', subfolder.id)
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import { textEmbeddingService } from './text-embedding'
|
|||||||
|
|
||||||
import { AssetType } from '@shumai/db'
|
import { AssetType } from '@shumai/db'
|
||||||
import { assetService } from '@shumai/core/src/asset/asset'
|
import { assetService } from '@shumai/core/src/asset/asset'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
|
||||||
describe('SearchService', () => {
|
describe('SearchService', () => {
|
||||||
setupTestDbHooks()
|
setupTestDbHooks()
|
||||||
@@ -805,6 +806,22 @@ describe('SearchService', () => {
|
|||||||
)
|
)
|
||||||
`
|
`
|
||||||
|
|
||||||
|
const sprite = { key: 'files/video-a/chunk-0-10.webp', columns: 5, rows: 2, frameCount: 7 }
|
||||||
|
await prisma.assetEmbedding.update({ where: { id: 'chunk-a1' }, data: { sprite } })
|
||||||
|
const unsignedKey = 'files/video-b/chunk-5-15.webp'
|
||||||
|
await prisma.assetEmbedding.update({
|
||||||
|
where: { id: 'chunk-b1' },
|
||||||
|
data: { sprite: { ...sprite, key: unsignedKey } },
|
||||||
|
})
|
||||||
|
const presign = s3Service.presign.bind(s3Service)
|
||||||
|
const signSprite = vi
|
||||||
|
.spyOn(s3Service, 'presign')
|
||||||
|
.mockImplementation((bucket, key, method) =>
|
||||||
|
key === unsignedKey
|
||||||
|
? Promise.reject(new Error('Signing failed'))
|
||||||
|
: presign(bucket, key, method),
|
||||||
|
)
|
||||||
|
|
||||||
// Mock the embedding generation
|
// Mock the embedding generation
|
||||||
// Our query vector points along the first dimension [1, 0, 0...]
|
// Our query vector points along the first dimension [1, 0, 0...]
|
||||||
const queryVector = Array(1536).fill(0)
|
const queryVector = Array(1536).fill(0)
|
||||||
@@ -838,17 +855,26 @@ describe('SearchService', () => {
|
|||||||
expect(result.data[0].id).toBe(videoAssetA.id)
|
expect(result.data[0].id).toBe(videoAssetA.id)
|
||||||
expect(result.data[0].startTime).toBe(0)
|
expect(result.data[0].startTime).toBe(0)
|
||||||
expect(result.data[0].endTime).toBe(10)
|
expect(result.data[0].endTime).toBe(10)
|
||||||
|
expect(result.data[0].matchedSprite).toEqual({
|
||||||
|
url: expect.stringContaining(sprite.key),
|
||||||
|
columns: 5,
|
||||||
|
rows: 2,
|
||||||
|
frameCount: 7,
|
||||||
|
})
|
||||||
|
|
||||||
// 2nd: Chunk B1
|
// 2nd: Chunk B1
|
||||||
expect(result.data[1].id).toBe(videoAssetB.id)
|
expect(result.data[1].id).toBe(videoAssetB.id)
|
||||||
expect(result.data[1].startTime).toBe(5)
|
expect(result.data[1].startTime).toBe(5)
|
||||||
expect(result.data[1].endTime).toBe(15)
|
expect(result.data[1].endTime).toBe(15)
|
||||||
|
expect(result.data[1].matchedSprite).toBeUndefined()
|
||||||
|
|
||||||
// 3rd: Chunk A2
|
// 3rd: Chunk A2
|
||||||
expect(result.data[2].id).toBe(videoAssetA.id)
|
expect(result.data[2].id).toBe(videoAssetA.id)
|
||||||
expect(result.data[2].startTime).toBe(10)
|
expect(result.data[2].startTime).toBe(10)
|
||||||
expect(result.data[2].endTime).toBe(20)
|
expect(result.data[2].endTime).toBe(20)
|
||||||
|
expect(result.data[2].matchedSprite).toBeUndefined()
|
||||||
|
|
||||||
|
signSprite.mockRestore()
|
||||||
mockGenerateEmbedding.mockRestore()
|
mockGenerateEmbedding.mockRestore()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,9 @@ import { prisma } from '@shumai/db'
|
|||||||
import { Prisma, AssetType } from '@shumai/db'
|
import { Prisma, AssetType } from '@shumai/db'
|
||||||
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
import { AssetService, assetService } from '@shumai/core/src/asset/asset'
|
||||||
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
|
import type { AssetInfo, ImageSearchRequest, SearchRequest } from '@shumai/dtos'
|
||||||
|
import { logger } from '@shumai/core/src/logger'
|
||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
import { hasStoredVideoSprite, isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
|
||||||
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
import { PaginatedData, decodeCursor, encodeCursor, PageInfo } from '@shumai/core/src/pagination'
|
||||||
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
import { generateSearchNgrams } from '@shumai/core/src/utils/ngram'
|
||||||
import { HTTPException } from 'hono/http-exception'
|
import { HTTPException } from 'hono/http-exception'
|
||||||
@@ -416,25 +419,68 @@ export class SearchService {
|
|||||||
const offset = req.after ? decodeCursor(req.after) : 0
|
const offset = req.after ? decodeCursor(req.after) : 0
|
||||||
const resultQuery = builder
|
const resultQuery = builder
|
||||||
.select(
|
.select(
|
||||||
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ${distance} as "distance"`,
|
Prisma.sql`a.id as "assetId", ae.start_time as "startTime", ae.end_time as "endTime", ae.sprite,
|
||||||
|
a.media -> 'duration' as "videoDuration", a.media #>> '{sprite,key}' as "fullSpriteKey",
|
||||||
|
${distance} as "distance"`,
|
||||||
)
|
)
|
||||||
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
|
.orderBy(visual ? Prisma.sql`distance ASC, ae.id ASC` : Prisma.sql`distance ASC`)
|
||||||
.limit(limit + 1)
|
.limit(limit + 1)
|
||||||
.offset(offset)
|
.offset(offset)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
const matches =
|
const matches = await this.prismaClient.$queryRaw<
|
||||||
await this.prismaClient.$queryRaw<
|
{
|
||||||
{ assetId: string; startTime: number | null; endTime: number | null }[]
|
assetId: string
|
||||||
>(resultQuery)
|
startTime: number | null
|
||||||
|
endTime: number | null
|
||||||
|
sprite: PrismaJson.VideoChunkSprite | null
|
||||||
|
videoDuration: unknown
|
||||||
|
fullSpriteKey: string | null
|
||||||
|
}[]
|
||||||
|
>(resultQuery)
|
||||||
const page = matches.slice(0, limit)
|
const page = matches.slice(0, limit)
|
||||||
const assetIds = [...new Set(page.map((match) => match.assetId))]
|
const assetIds = [...new Set(page.map((match) => match.assetId))]
|
||||||
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
|
const infos = await this.assetSvc.listAssetsByIds(assetIds, req.previewFormat)
|
||||||
const byId = new Map(infos.map((item) => [item.id, item]))
|
const byId = new Map(infos.map((item) => [item.id, item]))
|
||||||
const data = page.flatMap(({ assetId, startTime, endTime }) => {
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
const item = byId.get(assetId)
|
const results = await Promise.all(
|
||||||
return item ? [{ ...item, startTime, endTime }] : []
|
page.map(
|
||||||
})
|
async ({
|
||||||
|
assetId,
|
||||||
|
startTime,
|
||||||
|
endTime,
|
||||||
|
sprite,
|
||||||
|
videoDuration,
|
||||||
|
fullSpriteKey,
|
||||||
|
}): Promise<AssetInfo | undefined> => {
|
||||||
|
const item = byId.get(assetId)
|
||||||
|
if (!item) return
|
||||||
|
const match = { ...item, startTime, endTime }
|
||||||
|
if (!sprite) return match
|
||||||
|
|
||||||
|
// A stack or symlink can get its preview from a different asset.
|
||||||
|
if (
|
||||||
|
item.type === AssetType.file &&
|
||||||
|
item.preview?.spriteUrl &&
|
||||||
|
fullSpriteKey &&
|
||||||
|
isFullVideoRange(startTime, endTime, videoDuration) &&
|
||||||
|
(await hasStoredVideoSprite(bucket, fullSpriteKey))
|
||||||
|
) {
|
||||||
|
return match
|
||||||
|
}
|
||||||
|
|
||||||
|
const { key, ...layout } = sprite
|
||||||
|
try {
|
||||||
|
const url = await s3Service.presign(bucket, key, 'GET')
|
||||||
|
return { ...match, matchedSprite: { ...layout, url } }
|
||||||
|
} catch (err) {
|
||||||
|
logger.warn({ err, assetId, key }, 'Failed to sign video chunk sprite')
|
||||||
|
return match
|
||||||
|
}
|
||||||
|
},
|
||||||
|
),
|
||||||
|
)
|
||||||
|
const data = results.filter((item) => item !== undefined)
|
||||||
|
|
||||||
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
|
const counts = await this.prismaClient.$queryRaw<{ count: bigint }[]>(countQuery)
|
||||||
const total = Number(counts[0]?.count ?? 0)
|
const total = Number(counts[0]?.count ?? 0)
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { mkdtemp, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { composeVideoChunkSprite } from './video-chunk-sprite'
|
||||||
|
|
||||||
|
describe('composeVideoChunkSprite', () => {
|
||||||
|
it('fills tiles in frame order and counts only the tiles with frames', async () => {
|
||||||
|
const directory = await mkdtemp(join(tmpdir(), 'chunk-sprite-test-'))
|
||||||
|
try {
|
||||||
|
const colors = ['red', 'red', 'red', 'red', 'red', 'blue']
|
||||||
|
const frames = await Promise.all(
|
||||||
|
colors.map(async (background, index) => {
|
||||||
|
const frame = join(directory, `frame-${index}.png`)
|
||||||
|
await sharp({ create: { width: 48, height: 32, channels: 3, background } }).toFile(frame)
|
||||||
|
return frame
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
|
||||||
|
const sprite = await composeVideoChunkSprite(frames)
|
||||||
|
expect(sprite).toMatchObject({ columns: 5, rows: 2, frameCount: 6 })
|
||||||
|
const { data, info } = await sharp(sprite!.image).raw().toBuffer({ resolveWithObject: true })
|
||||||
|
expect(info).toMatchObject({ width: 240, height: 64, channels: 3 })
|
||||||
|
const pixel = (x: number, y: number) => (y * info.width + x) * info.channels
|
||||||
|
expect(data[pixel(24, 16)]).toBeGreaterThan(200)
|
||||||
|
expect(data[pixel(24, 48) + 2]).toBeGreaterThan(200)
|
||||||
|
expect(data[pixel(72, 48) + 2]).toBeLessThan(10)
|
||||||
|
} finally {
|
||||||
|
await rm(directory, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('omits preview metadata when the chunk contains no frames', async () => {
|
||||||
|
await expect(composeVideoChunkSprite([])).resolves.toBeUndefined()
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { execFile } from 'node:child_process'
|
||||||
|
import { mkdtemp, readdir, rm } from 'node:fs/promises'
|
||||||
|
import { tmpdir } from 'node:os'
|
||||||
|
import { join } from 'node:path'
|
||||||
|
import { promisify } from 'node:util'
|
||||||
|
import type { SpriteLayout } from '@shumai/dtos'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
|
const execFileAsync = promisify(execFile)
|
||||||
|
const MAX_TILE_SIDE = 240
|
||||||
|
const MAX_COLUMNS = 5
|
||||||
|
const MAX_SAMPLED_FRAMES = 15
|
||||||
|
|
||||||
|
export async function composeVideoChunkSprite(
|
||||||
|
frames: string[],
|
||||||
|
): Promise<(SpriteLayout & { image: Buffer }) | undefined> {
|
||||||
|
if (!frames.length) return
|
||||||
|
|
||||||
|
const { width, height } = await sharp(frames[0]).metadata()
|
||||||
|
const scale = Math.min(1, MAX_TILE_SIDE / Math.max(width, height))
|
||||||
|
const tileWidth = Math.max(1, Math.round(width * scale))
|
||||||
|
const tileHeight = Math.max(1, Math.round(height * scale))
|
||||||
|
const frameCount = frames.length
|
||||||
|
const columns = Math.min(MAX_COLUMNS, frameCount)
|
||||||
|
const rows = Math.ceil(frameCount / columns)
|
||||||
|
const tiles = await Promise.all(
|
||||||
|
frames.map(async (frame, index) => ({
|
||||||
|
input: await sharp(frame)
|
||||||
|
.resize(tileWidth, tileHeight, { fit: 'contain', background: 'black' })
|
||||||
|
.png()
|
||||||
|
.toBuffer(),
|
||||||
|
left: (index % columns) * tileWidth,
|
||||||
|
top: Math.floor(index / columns) * tileHeight,
|
||||||
|
})),
|
||||||
|
)
|
||||||
|
const image = await sharp({
|
||||||
|
create: {
|
||||||
|
width: columns * tileWidth,
|
||||||
|
height: rows * tileHeight,
|
||||||
|
channels: 3,
|
||||||
|
background: 'black',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.composite(tiles)
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
return { image, columns, rows, frameCount }
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function sampleVideoChunkSprite(
|
||||||
|
clip: string,
|
||||||
|
duration: number,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): ReturnType<typeof composeVideoChunkSprite> {
|
||||||
|
const dir = await mkdtemp(join(tmpdir(), 'video-chunk-sprite-'))
|
||||||
|
try {
|
||||||
|
const fps = Math.min(1, MAX_SAMPLED_FRAMES / duration)
|
||||||
|
await execFileAsync(
|
||||||
|
'ffmpeg',
|
||||||
|
[
|
||||||
|
'-loglevel',
|
||||||
|
'error',
|
||||||
|
'-i',
|
||||||
|
clip,
|
||||||
|
'-vf',
|
||||||
|
`fps=${fps}:round=up,scale=w='min(iw,240)':h='min(ih,240)':force_original_aspect_ratio=decrease`,
|
||||||
|
'-frames:v',
|
||||||
|
String(MAX_SAMPLED_FRAMES),
|
||||||
|
join(dir, 'frame_%04d.jpg'),
|
||||||
|
],
|
||||||
|
{ signal },
|
||||||
|
)
|
||||||
|
const files = (await readdir(dir)).sort()
|
||||||
|
return await composeVideoChunkSprite(files.map((file) => join(dir, file)))
|
||||||
|
} finally {
|
||||||
|
await rm(dir, { recursive: true, force: true })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { s3Service } from '@shumai/core/src/s3/s3'
|
||||||
|
|
||||||
|
export function isFullVideoRange(
|
||||||
|
startTime: number | null,
|
||||||
|
endTime: number | null,
|
||||||
|
duration: unknown,
|
||||||
|
): boolean {
|
||||||
|
return (
|
||||||
|
startTime === 0 &&
|
||||||
|
typeof duration === 'number' &&
|
||||||
|
Number.isFinite(duration) &&
|
||||||
|
duration > 0 &&
|
||||||
|
endTime === duration
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function hasStoredVideoSprite(bucket: string, key: string): Promise<boolean> {
|
||||||
|
const size = await s3Service.getObjectSize(bucket, key).catch(() => 0)
|
||||||
|
return size > 0
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
-- AlterTable
|
||||||
|
ALTER TABLE "asset_embeddings" ADD COLUMN "sprite" JSONB;
|
||||||
@@ -733,6 +733,8 @@ model AssetEmbedding {
|
|||||||
embedding768 Unsupported("vector(768)")? @map("embedding_768")
|
embedding768 Unsupported("vector(768)")? @map("embedding_768")
|
||||||
startTime Float? @map("start_time")
|
startTime Float? @map("start_time")
|
||||||
endTime Float? @map("end_time")
|
endTime Float? @map("end_time")
|
||||||
|
/// [VideoChunkSprite]
|
||||||
|
sprite Json?
|
||||||
createdAt DateTime @default(now()) @map("created_at")
|
createdAt DateTime @default(now()) @map("created_at")
|
||||||
updatedAt DateTime @updatedAt @map("updated_at")
|
updatedAt DateTime @updatedAt @map("updated_at")
|
||||||
|
|
||||||
|
|||||||
+4
-4
File diff suppressed because one or more lines are too long
@@ -5356,6 +5356,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
|||||||
id: 'id',
|
id: 'id',
|
||||||
startTime: 'startTime',
|
startTime: 'startTime',
|
||||||
endTime: 'endTime',
|
endTime: 'endTime',
|
||||||
|
sprite: 'sprite',
|
||||||
createdAt: 'createdAt',
|
createdAt: 'createdAt',
|
||||||
updatedAt: 'updatedAt',
|
updatedAt: 'updatedAt',
|
||||||
assetId: 'assetId'
|
assetId: 'assetId'
|
||||||
|
|||||||
@@ -456,6 +456,7 @@ export const AssetEmbeddingScalarFieldEnum = {
|
|||||||
id: 'id',
|
id: 'id',
|
||||||
startTime: 'startTime',
|
startTime: 'startTime',
|
||||||
endTime: 'endTime',
|
endTime: 'endTime',
|
||||||
|
sprite: 'sprite',
|
||||||
createdAt: 'createdAt',
|
createdAt: 'createdAt',
|
||||||
updatedAt: 'updatedAt',
|
updatedAt: 'updatedAt',
|
||||||
assetId: 'assetId'
|
assetId: 'assetId'
|
||||||
|
|||||||
+33
-1
@@ -60,6 +60,7 @@ export type AssetEmbeddingCountAggregateOutputType = {
|
|||||||
id: number
|
id: number
|
||||||
startTime: number
|
startTime: number
|
||||||
endTime: number
|
endTime: number
|
||||||
|
sprite: number
|
||||||
createdAt: number
|
createdAt: number
|
||||||
updatedAt: number
|
updatedAt: number
|
||||||
assetId: number
|
assetId: number
|
||||||
@@ -99,6 +100,7 @@ export type AssetEmbeddingCountAggregateInputType = {
|
|||||||
id?: true
|
id?: true
|
||||||
startTime?: true
|
startTime?: true
|
||||||
endTime?: true
|
endTime?: true
|
||||||
|
sprite?: true
|
||||||
createdAt?: true
|
createdAt?: true
|
||||||
updatedAt?: true
|
updatedAt?: true
|
||||||
assetId?: true
|
assetId?: true
|
||||||
@@ -195,6 +197,7 @@ export type AssetEmbeddingGroupByOutputType = {
|
|||||||
id: string
|
id: string
|
||||||
startTime: number | null
|
startTime: number | null
|
||||||
endTime: number | null
|
endTime: number | null
|
||||||
|
sprite:PrismaJson.VideoChunkSprite | null
|
||||||
createdAt: Date
|
createdAt: Date
|
||||||
updatedAt: Date
|
updatedAt: Date
|
||||||
assetId: string
|
assetId: string
|
||||||
@@ -227,6 +230,7 @@ export type AssetEmbeddingWhereInput = {
|
|||||||
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
|
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||||
@@ -237,6 +241,7 @@ export type AssetEmbeddingOrderByWithRelationInput = {
|
|||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
@@ -250,6 +255,7 @@ export type AssetEmbeddingWhereUniqueInput = Prisma.AtLeast<{
|
|||||||
NOT?: Prisma.AssetEmbeddingWhereInput | Prisma.AssetEmbeddingWhereInput[]
|
NOT?: Prisma.AssetEmbeddingWhereInput | Prisma.AssetEmbeddingWhereInput[]
|
||||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
|
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||||
@@ -260,6 +266,7 @@ export type AssetEmbeddingOrderByWithAggregationInput = {
|
|||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
startTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
endTime?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
|
sprite?: Prisma.SortOrderInput | Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
@@ -277,6 +284,7 @@ export type AssetEmbeddingScalarWhereWithAggregatesInput = {
|
|||||||
id?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
id?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
||||||
startTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
startTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
||||||
endTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
endTime?: Prisma.FloatNullableWithAggregatesFilter<"AssetEmbedding"> | number | null
|
||||||
|
sprite?: Prisma.JsonNullableWithAggregatesFilter<"AssetEmbedding">
|
||||||
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
createdAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
updatedAt?: Prisma.DateTimeWithAggregatesFilter<"AssetEmbedding"> | Date | string
|
||||||
assetId?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
assetId?: Prisma.StringWithAggregatesFilter<"AssetEmbedding"> | string
|
||||||
@@ -286,6 +294,7 @@ export type AssetEmbeddingCreateInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
asset: Prisma.AssetCreateNestedOneWithoutEmbeddingsInput
|
asset: Prisma.AssetCreateNestedOneWithoutEmbeddingsInput
|
||||||
@@ -295,6 +304,7 @@ export type AssetEmbeddingUncheckedCreateInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
assetId: string
|
assetId: string
|
||||||
@@ -304,6 +314,7 @@ export type AssetEmbeddingUpdateInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
asset?: Prisma.AssetUpdateOneRequiredWithoutEmbeddingsNestedInput
|
asset?: Prisma.AssetUpdateOneRequiredWithoutEmbeddingsNestedInput
|
||||||
@@ -313,6 +324,7 @@ export type AssetEmbeddingUncheckedUpdateInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -322,6 +334,7 @@ export type AssetEmbeddingCreateManyInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
assetId: string
|
assetId: string
|
||||||
@@ -331,6 +344,7 @@ export type AssetEmbeddingUpdateManyMutationInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
@@ -339,6 +353,7 @@ export type AssetEmbeddingUncheckedUpdateManyInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
assetId?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
@@ -358,6 +373,7 @@ export type AssetEmbeddingCountOrderByAggregateInput = {
|
|||||||
id?: Prisma.SortOrder
|
id?: Prisma.SortOrder
|
||||||
startTime?: Prisma.SortOrder
|
startTime?: Prisma.SortOrder
|
||||||
endTime?: Prisma.SortOrder
|
endTime?: Prisma.SortOrder
|
||||||
|
sprite?: Prisma.SortOrder
|
||||||
createdAt?: Prisma.SortOrder
|
createdAt?: Prisma.SortOrder
|
||||||
updatedAt?: Prisma.SortOrder
|
updatedAt?: Prisma.SortOrder
|
||||||
assetId?: Prisma.SortOrder
|
assetId?: Prisma.SortOrder
|
||||||
@@ -437,6 +453,7 @@ export type AssetEmbeddingCreateWithoutAssetInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
}
|
}
|
||||||
@@ -445,6 +462,7 @@ export type AssetEmbeddingUncheckedCreateWithoutAssetInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
}
|
}
|
||||||
@@ -482,6 +500,7 @@ export type AssetEmbeddingScalarWhereInput = {
|
|||||||
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
id?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||||
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
startTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
endTime?: Prisma.FloatNullableFilter<"AssetEmbedding"> | number | null
|
||||||
|
sprite?: Prisma.JsonNullableFilter<"AssetEmbedding">
|
||||||
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
createdAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
updatedAt?: Prisma.DateTimeFilter<"AssetEmbedding"> | Date | string
|
||||||
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
assetId?: Prisma.StringFilter<"AssetEmbedding"> | string
|
||||||
@@ -491,6 +510,7 @@ export type AssetEmbeddingCreateManyAssetInput = {
|
|||||||
id?: string
|
id?: string
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Date | string
|
createdAt?: Date | string
|
||||||
updatedAt?: Date | string
|
updatedAt?: Date | string
|
||||||
}
|
}
|
||||||
@@ -499,6 +519,7 @@ export type AssetEmbeddingUpdateWithoutAssetInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
@@ -507,6 +528,7 @@ export type AssetEmbeddingUncheckedUpdateWithoutAssetInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
@@ -515,6 +537,7 @@ export type AssetEmbeddingUncheckedUpdateManyWithoutAssetInput = {
|
|||||||
id?: Prisma.StringFieldUpdateOperationsInput | string
|
id?: Prisma.StringFieldUpdateOperationsInput | string
|
||||||
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
startTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
endTime?: Prisma.NullableFloatFieldUpdateOperationsInput | number | null
|
||||||
|
sprite?:PrismaJson.VideoChunkSprite | Prisma.NullableJsonNullValueInput
|
||||||
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
createdAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
updatedAt?: Prisma.DateTimeFieldUpdateOperationsInput | Date | string
|
||||||
}
|
}
|
||||||
@@ -525,6 +548,7 @@ export type AssetEmbeddingSelect<ExtArgs extends runtime.Types.Extensions.Intern
|
|||||||
id?: boolean
|
id?: boolean
|
||||||
startTime?: boolean
|
startTime?: boolean
|
||||||
endTime?: boolean
|
endTime?: boolean
|
||||||
|
sprite?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
@@ -535,6 +559,7 @@ export type AssetEmbeddingSelectCreateManyAndReturn<ExtArgs extends runtime.Type
|
|||||||
id?: boolean
|
id?: boolean
|
||||||
startTime?: boolean
|
startTime?: boolean
|
||||||
endTime?: boolean
|
endTime?: boolean
|
||||||
|
sprite?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
@@ -545,6 +570,7 @@ export type AssetEmbeddingSelectUpdateManyAndReturn<ExtArgs extends runtime.Type
|
|||||||
id?: boolean
|
id?: boolean
|
||||||
startTime?: boolean
|
startTime?: boolean
|
||||||
endTime?: boolean
|
endTime?: boolean
|
||||||
|
sprite?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
@@ -555,12 +581,13 @@ export type AssetEmbeddingSelectScalar = {
|
|||||||
id?: boolean
|
id?: boolean
|
||||||
startTime?: boolean
|
startTime?: boolean
|
||||||
endTime?: boolean
|
endTime?: boolean
|
||||||
|
sprite?: boolean
|
||||||
createdAt?: boolean
|
createdAt?: boolean
|
||||||
updatedAt?: boolean
|
updatedAt?: boolean
|
||||||
assetId?: boolean
|
assetId?: boolean
|
||||||
}
|
}
|
||||||
|
|
||||||
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
|
export type AssetEmbeddingOmit<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = runtime.Types.Extensions.GetOmit<"id" | "startTime" | "endTime" | "sprite" | "createdAt" | "updatedAt" | "assetId", ExtArgs["result"]["assetEmbedding"]>
|
||||||
export type AssetEmbeddingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
export type AssetEmbeddingInclude<ExtArgs extends runtime.Types.Extensions.InternalArgs = runtime.Types.Extensions.DefaultArgs> = {
|
||||||
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
asset?: boolean | Prisma.AssetDefaultArgs<ExtArgs>
|
||||||
}
|
}
|
||||||
@@ -580,6 +607,10 @@ export type $AssetEmbeddingPayload<ExtArgs extends runtime.Types.Extensions.Inte
|
|||||||
id: string
|
id: string
|
||||||
startTime: number | null
|
startTime: number | null
|
||||||
endTime: number | null
|
endTime: number | null
|
||||||
|
/**
|
||||||
|
* [VideoChunkSprite]
|
||||||
|
*/
|
||||||
|
sprite:PrismaJson.VideoChunkSprite | null
|
||||||
createdAt: Date
|
createdAt: Date
|
||||||
updatedAt: Date
|
updatedAt: Date
|
||||||
assetId: string
|
assetId: string
|
||||||
@@ -1010,6 +1041,7 @@ export interface AssetEmbeddingFieldRefs {
|
|||||||
readonly id: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
readonly id: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
||||||
readonly startTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
readonly startTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
||||||
readonly endTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
readonly endTime: Prisma.FieldRef<"AssetEmbedding", 'Float'>
|
||||||
|
readonly sprite: Prisma.FieldRef<"AssetEmbedding", 'Json'>
|
||||||
readonly createdAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
readonly createdAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
||||||
readonly updatedAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
readonly updatedAt: Prisma.FieldRef<"AssetEmbedding", 'DateTime'>
|
||||||
readonly assetId: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
readonly assetId: Prisma.FieldRef<"AssetEmbedding", 'String'>
|
||||||
|
|||||||
@@ -217,6 +217,8 @@ declare global {
|
|||||||
resolutions: VideoTranscode[]
|
resolutions: VideoTranscode[]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type VideoChunkSprite = import('@shumai/dtos').SpriteLayout & { key: string }
|
||||||
|
|
||||||
export interface MediaInfo {
|
export interface MediaInfo {
|
||||||
duration: number
|
duration: number
|
||||||
filesize: number
|
filesize: number
|
||||||
|
|||||||
@@ -25,6 +25,16 @@ export const previewInfoSchema = z.object({
|
|||||||
})
|
})
|
||||||
export type PreviewInfo = z.infer<typeof previewInfoSchema>
|
export type PreviewInfo = z.infer<typeof previewInfoSchema>
|
||||||
|
|
||||||
|
const spriteLayoutSchema = z.object({
|
||||||
|
columns: z.number().int().positive(),
|
||||||
|
rows: z.number().int().positive(),
|
||||||
|
frameCount: z.number().int().positive(),
|
||||||
|
})
|
||||||
|
export type SpriteLayout = z.infer<typeof spriteLayoutSchema>
|
||||||
|
|
||||||
|
const matchedSpriteSchema = spriteLayoutSchema.extend({ url: z.string() })
|
||||||
|
export type MatchedSprite = z.infer<typeof matchedSpriteSchema>
|
||||||
|
|
||||||
export const childPreviewSchema = z.object({
|
export const childPreviewSchema = z.object({
|
||||||
type: z.string().nullable(),
|
type: z.string().nullable(),
|
||||||
preview: previewInfoSchema.nullable(),
|
preview: previewInfoSchema.nullable(),
|
||||||
@@ -90,6 +100,7 @@ export const assetInfoSchema = z.object({
|
|||||||
sortIndex: z.string().optional().nullable(),
|
sortIndex: z.string().optional().nullable(),
|
||||||
startTime: z.number().optional().nullable(),
|
startTime: z.number().optional().nullable(),
|
||||||
endTime: z.number().optional().nullable(),
|
endTime: z.number().optional().nullable(),
|
||||||
|
matchedSprite: matchedSpriteSchema.optional(),
|
||||||
hasAgentsMd: z.boolean().optional(),
|
hasAgentsMd: z.boolean().optional(),
|
||||||
commentsCount: z.number().optional(),
|
commentsCount: z.number().optional(),
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'
|
import { describe, it, expect, beforeAll, afterEach, afterAll, vi } from 'vitest'
|
||||||
import { prisma, WorkflowTaskStatus } from '@shumai/db'
|
import { prisma, WorkflowTaskStatus } from '@shumai/db'
|
||||||
import { setupTestDbHooks } from '@shumai/db/test'
|
import { setupTestDbHooks } from '@shumai/db/test'
|
||||||
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
import { workflowService, TaskQueueAgent, TaskQueueTranscode } from '@shumai/workflow-core'
|
||||||
@@ -8,6 +8,7 @@ import { s3Service } from '@shumai/core/src/s3/s3'
|
|||||||
import { fileURLToPath } from 'url'
|
import { fileURLToPath } from 'url'
|
||||||
import * as path from 'path'
|
import * as path from 'path'
|
||||||
import * as fs from 'fs'
|
import * as fs from 'fs'
|
||||||
|
import sharp from 'sharp'
|
||||||
|
|
||||||
const mockEmbedContent = vi.fn().mockResolvedValue({
|
const mockEmbedContent = vi.fn().mockResolvedValue({
|
||||||
embeddings: [
|
embeddings: [
|
||||||
@@ -46,6 +47,11 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
|
|||||||
await workflowService.startWorkers([TaskQueueAgent, TaskQueueTranscode])
|
await workflowService.startWorkers([TaskQueueAgent, TaskQueueTranscode])
|
||||||
})
|
})
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.restoreAllMocks()
|
||||||
|
vi.unstubAllEnvs()
|
||||||
|
})
|
||||||
|
|
||||||
afterAll(async () => {
|
afterAll(async () => {
|
||||||
await workflowService.shutdownWorkers()
|
await workflowService.shutdownWorkers()
|
||||||
workflowService.close()
|
workflowService.close()
|
||||||
@@ -196,152 +202,216 @@ describe('Workflow E2E - agentEmbeddingMedia', () => {
|
|||||||
expect(dbEmbeddings[0].endTime).toBeNull()
|
expect(dbEmbeddings[0].endTime).toBeNull()
|
||||||
}, 50000)
|
}, 50000)
|
||||||
|
|
||||||
it('should run agentEmbeddingMedia workflow for a video asset successfully', async () => {
|
it.each([
|
||||||
// 1. Seed Database
|
['gemini-embedding-2', 'no sprite metadata'],
|
||||||
const team = await prisma.team.create({
|
['gemma-embedding-2-openai', 'no sprite metadata'],
|
||||||
data: { name: 'E2E Video Embedding Team' },
|
['gemini-embedding-2', 'available full sprite'],
|
||||||
})
|
['gemma-embedding-2-openai', 'available full sprite'],
|
||||||
|
['gemma-embedding-2-openai', 'missing full sprite object'],
|
||||||
|
])(
|
||||||
|
'indexes an entire video with %s and %s',
|
||||||
|
async (embeddingProvider, fullSpriteState) => {
|
||||||
|
vi.stubEnv('EMBEDDING_PROVIDER', embeddingProvider)
|
||||||
|
if (embeddingProvider === 'gemma-embedding-2-openai') {
|
||||||
|
const endpoint = 'https://embedding.example.com/v1/embeddings'
|
||||||
|
vi.stubEnv('GEMMA_EMBEDDING_OPENAI_BASE_URL', endpoint)
|
||||||
|
const fetch = globalThis.fetch
|
||||||
|
vi.spyOn(globalThis, 'fetch').mockImplementation((input, init) =>
|
||||||
|
input === endpoint
|
||||||
|
? Promise.resolve(
|
||||||
|
Response.json({ data: [{ embedding: Array<number>(768).fill(0.2) }] }),
|
||||||
|
)
|
||||||
|
: fetch(input, init),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
// 1. Seed Database
|
||||||
|
const team = await prisma.team.create({
|
||||||
|
data: { name: 'E2E Video Embedding Team' },
|
||||||
|
})
|
||||||
|
|
||||||
const project = await prisma.project.create({
|
const project = await prisma.project.create({
|
||||||
data: { name: 'E2E Video Embedding Project', teamId: team.id },
|
data: { name: 'E2E Video Embedding Project', teamId: team.id },
|
||||||
})
|
})
|
||||||
|
|
||||||
const agentUser = await prisma.user.create({
|
const agentUser = await prisma.user.create({
|
||||||
data: {
|
data: {
|
||||||
name: 'E2E Video Embedding Agent User',
|
name: 'E2E Video Embedding Agent User',
|
||||||
email: 'e2e-vid-emb-agent@shumai.ai',
|
email: 'e2e-vid-emb-agent@shumai.ai',
|
||||||
type: 'agent',
|
type: 'agent',
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
await prisma.teamMember.create({
|
|
||||||
data: {
|
|
||||||
teamId: team.id,
|
|
||||||
userId: agentUser.id,
|
|
||||||
role: 'editor',
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const provider = await prisma.provider.create({
|
|
||||||
data: {
|
|
||||||
name: 'google',
|
|
||||||
teamId: team.id,
|
|
||||||
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
|
|
||||||
},
|
|
||||||
})
|
|
||||||
|
|
||||||
const model = await prisma.model.create({
|
|
||||||
data: {
|
|
||||||
modelId: 'gemini',
|
|
||||||
name: 'Gemini',
|
|
||||||
providerId: provider.id,
|
|
||||||
config: {
|
|
||||||
input: ['text', 'image'],
|
|
||||||
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
|
||||||
contextWindow: 8192,
|
|
||||||
maxTokens: 2048,
|
|
||||||
reasoning: false,
|
|
||||||
},
|
},
|
||||||
},
|
})
|
||||||
})
|
|
||||||
|
|
||||||
await prisma.agent.create({
|
await prisma.teamMember.create({
|
||||||
data: {
|
data: {
|
||||||
id: agentUser.id,
|
teamId: team.id,
|
||||||
teamId: team.id,
|
userId: agentUser.id,
|
||||||
type: 'embedding',
|
role: 'editor',
|
||||||
enabled: true,
|
|
||||||
providerId: provider.id,
|
|
||||||
modelId: model.id,
|
|
||||||
config: {
|
|
||||||
provider: 'google',
|
|
||||||
model: 'gemini',
|
|
||||||
},
|
},
|
||||||
},
|
})
|
||||||
})
|
|
||||||
|
|
||||||
const storageKey = await prisma.storageKey.create({
|
const provider = await prisma.provider.create({
|
||||||
data: {
|
data: {
|
||||||
key: 'projects/e2e/test-video.mp4',
|
name: 'google',
|
||||||
},
|
teamId: team.id,
|
||||||
})
|
config: { api: 'google-generative-ai', apiKey: 'dummy-google-api-key' },
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
const asset = await prisma.asset.create({
|
const model = await prisma.model.create({
|
||||||
data: {
|
data: {
|
||||||
name: 'test-video.mp4',
|
modelId: 'gemini',
|
||||||
type: 'file',
|
name: 'Gemini',
|
||||||
status: 'uploaded',
|
providerId: provider.id,
|
||||||
mediaType: 'video/mp4',
|
config: {
|
||||||
media: { duration: 1.0 } as unknown as PrismaJson.MediaInfo, // 1-second video
|
input: ['text', 'image'],
|
||||||
projectId: project.id,
|
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
|
||||||
storageKeyId: storageKey.id,
|
contextWindow: 8192,
|
||||||
},
|
maxTokens: 2048,
|
||||||
})
|
reasoning: false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
// 2. Seed S3 Storage from Fixture
|
await prisma.agent.create({
|
||||||
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
data: {
|
||||||
const mp4Buffer = fs.readFileSync(mp4Path)
|
id: agentUser.id,
|
||||||
await s3Service.putObject(
|
teamId: team.id,
|
||||||
'shumai-e2e-test-bucket-embedding',
|
type: 'embedding',
|
||||||
'projects/e2e/test-video.mp4',
|
enabled: true,
|
||||||
mp4Buffer,
|
providerId: provider.id,
|
||||||
mp4Buffer.length,
|
modelId: model.id,
|
||||||
'video/mp4',
|
config: {
|
||||||
)
|
provider: 'google',
|
||||||
|
model: 'gemini',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
// 3. Create Workflow Task (ai_embedding, pending)
|
const storageKey = await prisma.storageKey.create({
|
||||||
const task = await prisma.workflowTask.create({
|
data: {
|
||||||
data: {
|
key: 'projects/e2e/test-video.mp4',
|
||||||
type: 'ai_embedding',
|
},
|
||||||
status: 'pending',
|
})
|
||||||
assetId: asset.id,
|
|
||||||
projectId: project.id,
|
const bucket = 'shumai-e2e-test-bucket-embedding'
|
||||||
teamId: team.id,
|
const fullSpriteKey = `projects/e2e/${storageKey.id}-full.webp`
|
||||||
payload: {
|
const hasFullSprite = fullSpriteState === 'available full sprite'
|
||||||
|
if (hasFullSprite) {
|
||||||
|
const fullSprite = await sharp({
|
||||||
|
create: { width: 640, height: 640, channels: 3, background: 'blue' },
|
||||||
|
})
|
||||||
|
.webp()
|
||||||
|
.toBuffer()
|
||||||
|
await s3Service.putObject(
|
||||||
|
bucket,
|
||||||
|
fullSpriteKey,
|
||||||
|
fullSprite,
|
||||||
|
fullSprite.length,
|
||||||
|
'image/webp',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const asset = await prisma.asset.create({
|
||||||
|
data: {
|
||||||
|
name: 'test-video.mp4',
|
||||||
|
type: 'file',
|
||||||
|
status: 'uploaded',
|
||||||
|
mediaType: 'video/mp4',
|
||||||
|
media: {
|
||||||
|
duration: 1,
|
||||||
|
proxyType: 'video',
|
||||||
|
...(fullSpriteState !== 'no sprite metadata' && {
|
||||||
|
sprite: { key: fullSpriteKey, frames: 100, tileX: 10, tileY: 10 },
|
||||||
|
}),
|
||||||
|
} as PrismaJson.MediaInfo,
|
||||||
projectId: project.id,
|
projectId: project.id,
|
||||||
agent: { agentId: agentUser.id },
|
storageKeyId: storageKey.id,
|
||||||
},
|
},
|
||||||
},
|
})
|
||||||
})
|
|
||||||
|
|
||||||
// 4. Wait for workflow to complete
|
// 2. Seed S3 Storage from Fixture
|
||||||
console.log(
|
const mp4Path = path.join(fixturesDir, 'small.mp4')
|
||||||
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
const mp4Buffer = fs.readFileSync(mp4Path)
|
||||||
)
|
await s3Service.putObject(
|
||||||
const completedTask = await workflowService.executeWait(task, 45000)
|
'shumai-e2e-test-bucket-embedding',
|
||||||
|
'projects/e2e/test-video.mp4',
|
||||||
|
mp4Buffer,
|
||||||
|
mp4Buffer.length,
|
||||||
|
'video/mp4',
|
||||||
|
)
|
||||||
|
|
||||||
// 5. Verification
|
// 3. Create Workflow Task (ai_embedding, pending)
|
||||||
expect(completedTask.status).toBe('completed')
|
const task = await prisma.workflowTask.create({
|
||||||
|
data: {
|
||||||
|
type: 'ai_embedding',
|
||||||
|
status: 'pending',
|
||||||
|
assetId: asset.id,
|
||||||
|
projectId: project.id,
|
||||||
|
teamId: team.id,
|
||||||
|
payload: {
|
||||||
|
projectId: project.id,
|
||||||
|
agent: { agentId: agentUser.id },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
|
// 4. Wait for workflow to complete
|
||||||
const chunkTasks = await prisma.workflowTask.findMany({
|
console.log(
|
||||||
where: {
|
`Submitted E2E Video Embedding Workflow Task. ID: ${task.id}. Awaiting completion...`,
|
||||||
assetId: asset.id,
|
)
|
||||||
type: 'transcode_video_chunks',
|
const completedTask = await workflowService.executeWait(task, 45000)
|
||||||
},
|
|
||||||
})
|
|
||||||
expect(chunkTasks).toHaveLength(1)
|
|
||||||
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
|
|
||||||
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
|
|
||||||
|
|
||||||
// Verify raw embedding is saved in DB with start and end times
|
// 5. Verification
|
||||||
const dbEmbeddings = (await prisma.$queryRaw`
|
expect(completedTask.status).toBe('completed')
|
||||||
SELECT id, asset_id as "assetId", start_time as "startTime", end_time as "endTime"
|
|
||||||
FROM asset_embeddings
|
|
||||||
WHERE asset_id = ${asset.id}
|
|
||||||
ORDER BY start_time ASC
|
|
||||||
`) as { id: string; startTime: number | null; endTime: number | null }[]
|
|
||||||
expect(dbEmbeddings.length).toBeGreaterThan(0)
|
|
||||||
expect(dbEmbeddings[0].startTime).toBe(0)
|
|
||||||
expect(dbEmbeddings[0].endTime).toBe(1)
|
|
||||||
|
|
||||||
// Verify all temporary embedding chunk files were cleaned up from S3
|
// Verify batch transcode_video_chunks task was created and completed on TaskQueueTranscode
|
||||||
const remainingTmpChunks = await s3Service.listObjects(
|
const chunkTasks = await prisma.workflowTask.findMany({
|
||||||
'shumai-e2e-test-bucket-embedding',
|
where: {
|
||||||
`files/${asset.id}/tmp-embedding-chunks/`,
|
assetId: asset.id,
|
||||||
)
|
type: 'transcode_video_chunks',
|
||||||
expect(remainingTmpChunks).toEqual([])
|
},
|
||||||
}, 50000)
|
})
|
||||||
|
expect(chunkTasks).toHaveLength(1)
|
||||||
|
expect(chunkTasks[0].status).toBe(WorkflowTaskStatus.completed)
|
||||||
|
expect(chunkTasks[0].payload?.videoChunks?.parentTaskId).toBe(task.id)
|
||||||
|
const dbEmbeddings = await prisma.assetEmbedding.findMany({ where: { assetId: asset.id } })
|
||||||
|
expect(dbEmbeddings).toHaveLength(1)
|
||||||
|
expect(dbEmbeddings[0].startTime).toBe(0)
|
||||||
|
expect(dbEmbeddings[0].endTime).toBe(1)
|
||||||
|
const sprite = dbEmbeddings[0].sprite
|
||||||
|
const format = embeddingProvider === 'gemma-embedding-2-openai' ? 'frames' : 'video'
|
||||||
|
if (hasFullSprite) {
|
||||||
|
expect(sprite).toBeNull()
|
||||||
|
expect(
|
||||||
|
await s3Service.listObjects(bucket, `projects/e2e/chunk-sprites/${asset.id}/`),
|
||||||
|
).toEqual([])
|
||||||
|
await s3Service.deleteObject(bucket, fullSpriteKey)
|
||||||
|
} else {
|
||||||
|
expect(chunkTasks[0].output).toMatchObject({
|
||||||
|
chunks: [{ sprite: { columns: 1, rows: 1, frameCount: 1 } }],
|
||||||
|
})
|
||||||
|
expect(sprite).toEqual({
|
||||||
|
key: `projects/e2e/chunk-sprites/${asset.id}/${format}-0-1.webp`,
|
||||||
|
columns: 1,
|
||||||
|
rows: 1,
|
||||||
|
frameCount: 1,
|
||||||
|
})
|
||||||
|
const { buffer } = await s3Service.getObject(bucket, sprite!.key)
|
||||||
|
expect(await sharp(buffer).metadata()).toMatchObject({
|
||||||
|
format: 'webp',
|
||||||
|
width: 64,
|
||||||
|
height: 64,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify all temporary embedding chunk files were cleaned up from S3
|
||||||
|
const remainingTmpChunks = await s3Service.listObjects(
|
||||||
|
'shumai-e2e-test-bucket-embedding',
|
||||||
|
`files/${asset.id}/tmp-embedding-chunks/`,
|
||||||
|
)
|
||||||
|
expect(remainingTmpChunks).toEqual([])
|
||||||
|
},
|
||||||
|
50000,
|
||||||
|
)
|
||||||
|
|
||||||
it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => {
|
it('should fail agentEmbeddingMedia workflow for an unsupported audio asset', async () => {
|
||||||
// 1. Seed Database
|
// 1. Seed Database
|
||||||
|
|||||||
@@ -9,12 +9,17 @@ import {
|
|||||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
import { gotenbergService } from '@shumai/core/src/gotenberg/gotenberg'
|
||||||
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
import { transcodeService } from '@shumai/core/src/transcode/transcode'
|
||||||
|
import { sampleVideoChunkSprite } from '@shumai/core/src/transcode/video-chunk-sprite'
|
||||||
import * as child_process from 'child_process'
|
import * as child_process from 'child_process'
|
||||||
import * as fs from 'fs'
|
import * as fs from 'fs'
|
||||||
|
|
||||||
vi.mock('child_process', () => ({
|
vi.mock('child_process', () => ({
|
||||||
execFile: vi.fn(),
|
execFile: vi.fn(),
|
||||||
}))
|
}))
|
||||||
|
vi.mock('@shumai/core/src/transcode/video-chunk-sprite', () => ({
|
||||||
|
composeVideoChunkSprite: vi.fn(),
|
||||||
|
sampleVideoChunkSprite: vi.fn(),
|
||||||
|
}))
|
||||||
import {
|
import {
|
||||||
ensureLocalMediaFile,
|
ensureLocalMediaFile,
|
||||||
getMediaInfoActivity,
|
getMediaInfoActivity,
|
||||||
@@ -1238,6 +1243,42 @@ describe('Transcode Activities', () => {
|
|||||||
})
|
})
|
||||||
|
|
||||||
describe('Video Chunk Activities', () => {
|
describe('Video Chunk Activities', () => {
|
||||||
|
it('returns the embedding clip when the optional sprite upload fails', async () => {
|
||||||
|
vi.mocked(child_process.execFile).mockImplementation(
|
||||||
|
// The activity awaits the promisified callback overload.
|
||||||
|
((_file: string, _args: string[], callback: (err: null) => void) => {
|
||||||
|
callback(null)
|
||||||
|
}) as typeof child_process.execFile,
|
||||||
|
)
|
||||||
|
vi.mocked(sampleVideoChunkSprite).mockResolvedValueOnce({
|
||||||
|
image: Buffer.from('mock sprite'),
|
||||||
|
columns: 1,
|
||||||
|
rows: 1,
|
||||||
|
frameCount: 1,
|
||||||
|
})
|
||||||
|
vi.mocked(s3Service.putObject)
|
||||||
|
.mockResolvedValueOnce(undefined)
|
||||||
|
.mockRejectedValueOnce(new Error('Sprite storage unavailable'))
|
||||||
|
|
||||||
|
const chunk = await transcodeVideoChunkActivity({
|
||||||
|
assetId: 'asset-abc',
|
||||||
|
assetKey: 'files/storage-id/proxy.mp4',
|
||||||
|
originalKey: 'files/storage-id/original.mp4',
|
||||||
|
startTime: 0,
|
||||||
|
endTime: 1,
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(chunk.chunkKey).toMatch(/\.mp4$/)
|
||||||
|
expect(chunk.sprite).toBeUndefined()
|
||||||
|
expect(s3Service.putObject).toHaveBeenLastCalledWith(
|
||||||
|
'shumai',
|
||||||
|
'files/storage-id/chunk-sprites/asset-abc/video-0-1.webp',
|
||||||
|
expect.any(Buffer),
|
||||||
|
expect.any(Number),
|
||||||
|
'image/webp',
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
|
it('should transcode video chunk using ffmpeg and upload to S3', async () => {
|
||||||
// Mock child_process.execFile to simulate ffmpeg succeeding
|
// Mock child_process.execFile to simulate ffmpeg succeeding
|
||||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
|||||||
@@ -8,6 +8,11 @@ import {
|
|||||||
} from '@shumai/core/src/transcode/transcode'
|
} from '@shumai/core/src/transcode/transcode'
|
||||||
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
import { metadataService } from '@shumai/core/src/metadata/metadata'
|
||||||
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
import { getDerivedArtifactDirectory, stemFromKey } from '@shumai/core/src/utils/filename'
|
||||||
|
import {
|
||||||
|
composeVideoChunkSprite,
|
||||||
|
sampleVideoChunkSprite,
|
||||||
|
} from '@shumai/core/src/transcode/video-chunk-sprite'
|
||||||
|
import { hasStoredVideoSprite } from '@shumai/core/src/transcode/video-sprite'
|
||||||
import {
|
import {
|
||||||
gotenbergService,
|
gotenbergService,
|
||||||
type GotenbergConvertOptions,
|
type GotenbergConvertOptions,
|
||||||
@@ -1603,15 +1608,49 @@ export interface TranscodeVideoChunkParams {
|
|||||||
taskId?: string
|
taskId?: string
|
||||||
assetId: string
|
assetId: string
|
||||||
assetKey?: string
|
assetKey?: string
|
||||||
|
originalKey?: string
|
||||||
filePath?: string
|
filePath?: string
|
||||||
startTime: number
|
startTime: number
|
||||||
endTime: number
|
endTime: number
|
||||||
format?: 'video' | 'frames'
|
format?: 'video' | 'frames'
|
||||||
|
fullSpriteKey?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
async function uploadVideoChunkSprite(
|
||||||
|
params: TranscodeVideoChunkParams,
|
||||||
|
render: () => ReturnType<typeof composeVideoChunkSprite>,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
): Promise<PrismaJson.VideoChunkSprite | undefined> {
|
||||||
|
if (signal?.aborted) return
|
||||||
|
try {
|
||||||
|
const bucket = process.env.S3_BUCKET || 'shumai'
|
||||||
|
if (params.fullSpriteKey && (await hasStoredVideoSprite(bucket, params.fullSpriteKey))) return
|
||||||
|
|
||||||
|
if (signal?.aborted) return
|
||||||
|
const sprite = await render()
|
||||||
|
if (!sprite || signal?.aborted) return
|
||||||
|
|
||||||
|
const originalKey = params.originalKey ?? params.assetKey
|
||||||
|
const directory = getDerivedArtifactDirectory(originalKey ?? '', params.assetId)
|
||||||
|
const format = params.format ?? 'video'
|
||||||
|
const key = `${directory}/chunk-sprites/${params.assetId}/${format}-${params.startTime}-${params.endTime}.webp`
|
||||||
|
await ensureAssetNotPurgingByIdOrKey(params.assetId, originalKey)
|
||||||
|
const { image, ...layout } = sprite
|
||||||
|
await s3Service.putObject(bucket, key, image, image.length, 'image/webp')
|
||||||
|
return { key, ...layout }
|
||||||
|
} catch (err) {
|
||||||
|
if (!signal?.aborted) {
|
||||||
|
logger.warn(
|
||||||
|
{ err, assetId: params.assetId, startTime: params.startTime, endTime: params.endTime },
|
||||||
|
'Failed to generate video chunk sprite',
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
export const transcodeVideoChunkActivity = defineStep(async function transcodeVideoChunkActivity(
|
||||||
params: TranscodeVideoChunkParams,
|
params: TranscodeVideoChunkParams,
|
||||||
): Promise<{ chunkKey: string }> {
|
): Promise<{ chunkKey: string; sprite?: PrismaJson.VideoChunkSprite }> {
|
||||||
if (!params.filePath && !params.assetKey) {
|
if (!params.filePath && !params.assetKey) {
|
||||||
throw ApplicationFailure.create({
|
throw ApplicationFailure.create({
|
||||||
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
message: 'Neither filePath nor assetKey was provided for video chunk transcoding',
|
||||||
@@ -1704,7 +1743,12 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
|||||||
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
|
const key = `files/${params.assetId}/tmp-embedding-chunks/frames-${params.startTime}-${params.endTime}-${ulid()}.tar`
|
||||||
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
|
await s3Service.putObject(bucket, key, archiveData, archiveData.length, 'application/x-tar')
|
||||||
|
|
||||||
return { chunkKey: key }
|
const sprite = await uploadVideoChunkSprite(
|
||||||
|
params,
|
||||||
|
() => composeVideoChunkSprite(frameFiles.map((file) => path.join(tmpDir, file))),
|
||||||
|
signal,
|
||||||
|
)
|
||||||
|
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ApplicationFailure) {
|
if (err instanceof ApplicationFailure) {
|
||||||
throw err
|
throw err
|
||||||
@@ -1777,7 +1821,12 @@ export const transcodeVideoChunkActivity = defineStep(async function transcodeVi
|
|||||||
|
|
||||||
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
|
await s3Service.putObject(bucket, key, chunkData, chunkData.length, 'video/mp4')
|
||||||
|
|
||||||
return { chunkKey: key }
|
const sprite = await uploadVideoChunkSprite(
|
||||||
|
params,
|
||||||
|
() => sampleVideoChunkSprite(chunkTmp, params.endTime - params.startTime, signal),
|
||||||
|
signal,
|
||||||
|
)
|
||||||
|
return sprite ? { chunkKey: key, sprite } : { chunkKey: key }
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
if (err instanceof ApplicationFailure) {
|
if (err instanceof ApplicationFailure) {
|
||||||
throw err
|
throw err
|
||||||
|
|||||||
@@ -73,11 +73,19 @@ describe('transcodeVideoChunksWorkflow', () => {
|
|||||||
status: 'processed',
|
status: 'processed',
|
||||||
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
|
storageKey: { key: 'files/asset-video/raw.mp4', isArchived: false },
|
||||||
mediaType: 'video/mp4',
|
mediaType: 'video/mp4',
|
||||||
|
media: { duration: 110, sprite: { key: 'files/asset-video/sprite.webp' } },
|
||||||
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
} as unknown as Awaited<ReturnType<typeof getAssetActivity>>)
|
||||||
|
|
||||||
|
const sprite = {
|
||||||
|
key: 'files/asset-video/chunk-sprites/asset-video/video-0-60.webp',
|
||||||
|
columns: 5,
|
||||||
|
rows: 3,
|
||||||
|
frameCount: 15,
|
||||||
|
}
|
||||||
mockActivities.transcodeVideoChunkActivity
|
mockActivities.transcodeVideoChunkActivity
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||||
|
sprite,
|
||||||
})
|
})
|
||||||
.mockResolvedValueOnce({
|
.mockResolvedValueOnce({
|
||||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
|
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-55-110.mp4',
|
||||||
@@ -90,6 +98,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
|||||||
taskId: 'task-video-chunks',
|
taskId: 'task-video-chunks',
|
||||||
assetId: 'asset-video',
|
assetId: 'asset-video',
|
||||||
assetKey: 'files/asset-video/proxy.mp4',
|
assetKey: 'files/asset-video/proxy.mp4',
|
||||||
|
originalKey: 'files/asset-video/raw.mp4',
|
||||||
startTime: 0,
|
startTime: 0,
|
||||||
endTime: 60,
|
endTime: 60,
|
||||||
format: 'video',
|
format: 'video',
|
||||||
@@ -98,6 +107,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
|||||||
taskId: 'task-video-chunks',
|
taskId: 'task-video-chunks',
|
||||||
assetId: 'asset-video',
|
assetId: 'asset-video',
|
||||||
assetKey: 'files/asset-video/proxy.mp4',
|
assetKey: 'files/asset-video/proxy.mp4',
|
||||||
|
originalKey: 'files/asset-video/raw.mp4',
|
||||||
startTime: 55,
|
startTime: 55,
|
||||||
endTime: 110,
|
endTime: 110,
|
||||||
format: 'video',
|
format: 'video',
|
||||||
@@ -112,6 +122,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
|||||||
startTime: 0,
|
startTime: 0,
|
||||||
endTime: 60,
|
endTime: 60,
|
||||||
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
chunkKey: 'files/asset-video/tmp-embedding-chunks/chunk-0-60.mp4',
|
||||||
|
sprite,
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
startTime: 55,
|
startTime: 55,
|
||||||
@@ -155,6 +166,7 @@ describe('transcodeVideoChunksWorkflow', () => {
|
|||||||
taskId: 'task-video-chunks',
|
taskId: 'task-video-chunks',
|
||||||
assetId: 'asset-video',
|
assetId: 'asset-video',
|
||||||
assetKey: 'files/asset-video/proxy-720p.mp4',
|
assetKey: 'files/asset-video/proxy-720p.mp4',
|
||||||
|
originalKey: 'files/asset-video/raw.mp4',
|
||||||
startTime: 0,
|
startTime: 0,
|
||||||
endTime: 30,
|
endTime: 30,
|
||||||
format: 'frames',
|
format: 'frames',
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { logger } from '@shumai/core/src/logger'
|
import { logger } from '@shumai/core/src/logger'
|
||||||
|
import { isFullVideoRange } from '@shumai/core/src/transcode/video-sprite'
|
||||||
import type { WorkflowTask } from '@shumai/db'
|
import type { WorkflowTask } from '@shumai/db'
|
||||||
import { ApplicationFailure } from '@shumai/workflow-core'
|
import { ApplicationFailure } from '@shumai/workflow-core'
|
||||||
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
|
import { deleteS3ObjectActivity, transcodeVideoChunkActivity } from '../activities/transcode'
|
||||||
@@ -8,6 +9,7 @@ export interface TranscodedVideoChunkItem {
|
|||||||
startTime: number
|
startTime: number
|
||||||
endTime: number
|
endTime: number
|
||||||
chunkKey: string
|
chunkKey: string
|
||||||
|
sprite?: PrismaJson.VideoChunkSprite
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
|
export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<void> {
|
||||||
@@ -47,20 +49,21 @@ export async function transcodeVideoChunksWorkflow(task: WorkflowTask): Promise<
|
|||||||
|
|
||||||
const chunks: TranscodedVideoChunkItem[] = []
|
const chunks: TranscodedVideoChunkItem[] = []
|
||||||
for (const range of payload.videoChunks.chunks) {
|
for (const range of payload.videoChunks.chunks) {
|
||||||
const { chunkKey } = await transcodeVideoChunkActivity({
|
const fullSpriteKey = isFullVideoRange(range.startTime, range.endTime, asset.media?.duration)
|
||||||
|
? asset.media?.sprite?.key
|
||||||
|
: undefined
|
||||||
|
const chunk = await transcodeVideoChunkActivity({
|
||||||
taskId: task.id,
|
taskId: task.id,
|
||||||
assetId: asset.id,
|
assetId: asset.id,
|
||||||
assetKey: targetKey,
|
assetKey: targetKey,
|
||||||
|
originalKey: key,
|
||||||
startTime: range.startTime,
|
startTime: range.startTime,
|
||||||
endTime: range.endTime,
|
endTime: range.endTime,
|
||||||
format: payload.videoChunks.format,
|
format: payload.videoChunks.format,
|
||||||
|
...(fullSpriteKey && { fullSpriteKey }),
|
||||||
})
|
})
|
||||||
uploadedChunkKeys.push(chunkKey)
|
uploadedChunkKeys.push(chunk.chunkKey)
|
||||||
chunks.push({
|
chunks.push({ ...range, ...chunk })
|
||||||
startTime: range.startTime,
|
|
||||||
endTime: range.endTime,
|
|
||||||
chunkKey,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
await completeTask(task.id, { chunks })
|
await completeTask(task.id, { chunks })
|
||||||
|
|||||||
@@ -308,7 +308,9 @@ export function FileCard({
|
|||||||
|
|
||||||
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
|
// A preview (poster thumbnail and/or sprite) can be available before transcoding finishes,
|
||||||
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
// since the poster/sprite are generated and persisted ahead of the proxy transcodes.
|
||||||
const hasPreview = Boolean(displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl)
|
const hasPreview = Boolean(
|
||||||
|
item.matchedSprite || displayItem.preview?.thumbnailUrl || displayItem.preview?.spriteUrl,
|
||||||
|
)
|
||||||
const isFailed = displayItem.status === 'failed'
|
const isFailed = displayItem.status === 'failed'
|
||||||
const isLocalUploader = Boolean(fileUploadState)
|
const isLocalUploader = Boolean(fileUploadState)
|
||||||
const isUploadFailed = fileUploadState?.status === 'failed'
|
const isUploadFailed = fileUploadState?.status === 'failed'
|
||||||
@@ -520,9 +522,10 @@ export function FileCard({
|
|||||||
<FilePreview
|
<FilePreview
|
||||||
item={displayItem}
|
item={displayItem}
|
||||||
showDuration={!isProcessing && !isFailed}
|
showDuration={!isProcessing && !isFailed}
|
||||||
|
matchedSprite={item.matchedSprite}
|
||||||
matchDuration={
|
matchDuration={
|
||||||
displayItem.startTime != null && displayItem.endTime != null
|
item.startTime != null && item.endTime != null
|
||||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
? { startTime: item.startTime, endTime: item.endTime }
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
@@ -569,8 +572,8 @@ export function FileCard({
|
|||||||
item={displayItem}
|
item={displayItem}
|
||||||
showDuration
|
showDuration
|
||||||
matchDuration={
|
matchDuration={
|
||||||
displayItem.startTime != null && displayItem.endTime != null
|
item.startTime != null && item.endTime != null
|
||||||
? { startTime: displayItem.startTime, endTime: displayItem.endTime }
|
? { startTime: item.startTime, endTime: item.endTime }
|
||||||
: null
|
: null
|
||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,4 +1,5 @@
|
|||||||
import { File, Folder, AudioLines } from 'lucide-react'
|
import { File, Folder, AudioLines } from 'lucide-react'
|
||||||
|
import type { MatchedSprite } from '@shumai/dtos'
|
||||||
import { SpriteScrubber } from '../sprite-scrubber'
|
import { SpriteScrubber } from '../sprite-scrubber'
|
||||||
import { formatTime } from '../viewers/video/utils'
|
import { formatTime } from '../viewers/video/utils'
|
||||||
|
|
||||||
@@ -20,13 +21,19 @@ type FilePreviewItem = {
|
|||||||
interface FilePreviewProps {
|
interface FilePreviewProps {
|
||||||
item: FilePreviewItem
|
item: FilePreviewItem
|
||||||
showDuration?: boolean
|
showDuration?: boolean
|
||||||
|
matchedSprite?: MatchedSprite
|
||||||
matchDuration?: {
|
matchDuration?: {
|
||||||
startTime?: number | null
|
startTime?: number | null
|
||||||
endTime?: number | null
|
endTime?: number | null
|
||||||
} | null
|
} | null
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FilePreview = ({ item, showDuration = false, matchDuration }: FilePreviewProps) => {
|
export const FilePreview = ({
|
||||||
|
item,
|
||||||
|
showDuration = false,
|
||||||
|
matchedSprite,
|
||||||
|
matchDuration,
|
||||||
|
}: FilePreviewProps) => {
|
||||||
const proxyType = item.preview?.proxyType || item.proxyType
|
const proxyType = item.preview?.proxyType || item.proxyType
|
||||||
const isVideo = proxyType === 'video'
|
const isVideo = proxyType === 'video'
|
||||||
const isAudio = proxyType === 'audio'
|
const isAudio = proxyType === 'audio'
|
||||||
@@ -56,21 +63,27 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
|
|||||||
</span>
|
</span>
|
||||||
) : null
|
) : null
|
||||||
|
|
||||||
const isMediaWithSprite =
|
const chunkSprite = hasMatchedChunk ? matchedSprite : undefined
|
||||||
(isVideo || isPdf || is3D) &&
|
const canShowFullSprite =
|
||||||
item.preview?.spriteUrl &&
|
hasMatchedChunk ||
|
||||||
item.preview.thumbnailUrl &&
|
((isVideo || isPdf || is3D) &&
|
||||||
item.preview.originalWidth &&
|
item.preview?.thumbnailUrl &&
|
||||||
item.preview.originalHeight
|
item.preview.originalWidth &&
|
||||||
|
item.preview.originalHeight)
|
||||||
|
const fullSpriteUrl = canShowFullSprite ? item.preview?.spriteUrl : undefined
|
||||||
|
const spriteUrl = chunkSprite?.url || fullSpriteUrl
|
||||||
|
|
||||||
if (isMediaWithSprite && item.preview) {
|
if (spriteUrl) {
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<SpriteScrubber
|
<SpriteScrubber
|
||||||
spriteUrl={item.preview.spriteUrl!}
|
spriteUrl={spriteUrl}
|
||||||
thumbnailUrl={item.preview.thumbnailUrl!}
|
spriteLayout={chunkSprite}
|
||||||
videoWidth={item.preview.originalWidth!}
|
showFirstFrame={Boolean(chunkSprite)}
|
||||||
videoHeight={item.preview.originalHeight!}
|
fallbackSpriteUrl={chunkSprite && fullSpriteUrl ? fullSpriteUrl : undefined}
|
||||||
|
thumbnailUrl={item.preview?.thumbnailUrl}
|
||||||
|
videoWidth={item.preview?.originalWidth}
|
||||||
|
videoHeight={item.preview?.originalHeight}
|
||||||
reverse={is3D}
|
reverse={is3D}
|
||||||
/>
|
/>
|
||||||
{overlay}
|
{overlay}
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
// @vitest-environment happy-dom
|
// @vitest-environment happy-dom
|
||||||
import { cleanup, fireEvent, render } from '@testing-library/react'
|
import { act, cleanup, fireEvent, render } from '@testing-library/react'
|
||||||
import React from 'react'
|
import React from 'react'
|
||||||
|
import {
|
||||||
|
mockIsIntersecting,
|
||||||
|
resetIntersectionMocking,
|
||||||
|
setupIntersectionMocking,
|
||||||
|
} from 'react-intersection-observer/test-utils'
|
||||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||||
import { SpriteScrubber } from './sprite-scrubber'
|
import { SpriteScrubber } from './sprite-scrubber'
|
||||||
import { FilePreview } from './file-browser/file-preview'
|
import { FilePreview } from './file-browser/file-preview'
|
||||||
@@ -15,8 +20,116 @@ globalThis.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserv
|
|||||||
describe('SpriteScrubber', () => {
|
describe('SpriteScrubber', () => {
|
||||||
afterEach(() => {
|
afterEach(() => {
|
||||||
cleanup()
|
cleanup()
|
||||||
|
resetIntersectionMocking()
|
||||||
|
vi.unstubAllGlobals()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
it.each(['chunk', 'full video', 'thumbnail'])('uses the %s preview on hover', (expected) => {
|
||||||
|
setupIntersectionMocking(vi.fn)
|
||||||
|
const chunkUrl = 'https://example.com/match.webp'
|
||||||
|
const fullUrl = 'https://example.com/full.webp'
|
||||||
|
const requests: string[] = []
|
||||||
|
const image = {
|
||||||
|
naturalWidth: 500,
|
||||||
|
naturalHeight: 200,
|
||||||
|
onload: null as (() => void) | null,
|
||||||
|
onerror: null as (() => void) | null,
|
||||||
|
set src(url: string) {
|
||||||
|
requests.push(url)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
vi.stubGlobal(
|
||||||
|
'Image',
|
||||||
|
class {
|
||||||
|
constructor() {
|
||||||
|
return image
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
const { getByTestId, getByAltText, queryByAltText, container } = render(
|
||||||
|
<FilePreview
|
||||||
|
item={{
|
||||||
|
preview: { proxyType: 'video', spriteUrl: fullUrl, thumbnailUrl: '/poster.webp' },
|
||||||
|
}}
|
||||||
|
matchDuration={{ startTime: 0, endTime: 7 }}
|
||||||
|
matchedSprite={{ url: chunkUrl, columns: 5, rows: 2, frameCount: 7 }}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
const scrubber = getByTestId('sprite-scrubber')
|
||||||
|
vi.spyOn(scrubber, 'getBoundingClientRect').mockReturnValue(new DOMRect(0, 0, 100, 100))
|
||||||
|
expect(requests).toEqual([])
|
||||||
|
act(() => mockIsIntersecting(scrubber, true))
|
||||||
|
expect(requests).toEqual([chunkUrl])
|
||||||
|
|
||||||
|
if (expected === 'chunk') {
|
||||||
|
act(() => image.onload?.())
|
||||||
|
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||||
|
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||||
|
} else {
|
||||||
|
act(() => image.onerror?.())
|
||||||
|
expect(requests).toEqual([chunkUrl])
|
||||||
|
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||||
|
}
|
||||||
|
|
||||||
|
fireEvent.mouseEnter(scrubber)
|
||||||
|
fireEvent.mouseMove(scrubber, { clientX: 100 })
|
||||||
|
expect(scrubber).toHaveProperty('dataset.frame', '6')
|
||||||
|
|
||||||
|
if (expected === 'chunk') {
|
||||||
|
expect(requests).toEqual([chunkUrl])
|
||||||
|
} else {
|
||||||
|
expect(requests).toEqual([chunkUrl, fullUrl])
|
||||||
|
}
|
||||||
|
|
||||||
|
if (expected === 'thumbnail') {
|
||||||
|
act(() => image.onerror?.())
|
||||||
|
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||||
|
expect(container.querySelector('.animate-spin')).toBeNull()
|
||||||
|
} else if (expected === 'full video') {
|
||||||
|
act(() => image.onload?.())
|
||||||
|
expect(getByAltText('Thumbnail').className).toContain('opacity-0')
|
||||||
|
expect(scrubber).toHaveProperty('dataset.frame', '99')
|
||||||
|
}
|
||||||
|
|
||||||
|
fireEvent.mouseLeave(scrubber)
|
||||||
|
expect(scrubber).toHaveProperty('dataset.frame', '0')
|
||||||
|
if (expected === 'chunk') {
|
||||||
|
expect(queryByAltText('Thumbnail')).toBeNull()
|
||||||
|
} else {
|
||||||
|
expect(getByAltText('Thumbnail').className).toContain('opacity-100')
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
it('keeps the regular cover and waits for hover when a match has no chunk sprite', () => {
|
||||||
|
const load = vi.fn()
|
||||||
|
vi.stubGlobal('Image', load)
|
||||||
|
const { getByAltText } = render(
|
||||||
|
<FilePreview
|
||||||
|
item={{
|
||||||
|
preview: { proxyType: 'video', spriteUrl: '/full.webp', thumbnailUrl: '/poster.webp' },
|
||||||
|
}}
|
||||||
|
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(getByAltText('Thumbnail').getAttribute('src')).toBe('/poster.webp')
|
||||||
|
expect(load).not.toHaveBeenCalled()
|
||||||
|
})
|
||||||
|
|
||||||
|
it.each(['video', undefined] as const)(
|
||||||
|
'uses the full sprite for a legacy video match with proxy type %s and no poster or dimensions',
|
||||||
|
(proxyType) => {
|
||||||
|
const { getByTestId } = render(
|
||||||
|
<FilePreview
|
||||||
|
item={{ preview: { proxyType, spriteUrl: '/full.webp' } }}
|
||||||
|
matchDuration={{ startTime: 0, endTime: 10 }}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
|
||||||
|
expect(getByTestId('sprite-scrubber')).toBeTruthy()
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
it('scrubs forward by default when hovering from left to right', () => {
|
it('scrubs forward by default when hovering from left to right', () => {
|
||||||
const { getByTestId } = render(
|
const { getByTestId } = render(
|
||||||
<SpriteScrubber
|
<SpriteScrubber
|
||||||
|
|||||||
@@ -1,14 +1,20 @@
|
|||||||
|
import type { SpriteLayout } from '@shumai/dtos'
|
||||||
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
|
import { useInView } from 'react-intersection-observer'
|
||||||
|
|
||||||
interface SpriteScrubberProps {
|
interface SpriteScrubberProps {
|
||||||
/** The URL of the 10x10 sprite sheet */
|
|
||||||
spriteUrl: string
|
spriteUrl: string
|
||||||
|
spriteLayout?: SpriteLayout
|
||||||
|
/** Load the primary sprite when visible and show its first frame at rest. */
|
||||||
|
showFirstFrame?: boolean
|
||||||
|
/** A full-asset 10x10 sprite to try when the primary sprite fails. */
|
||||||
|
fallbackSpriteUrl?: string
|
||||||
/** The URL of the static thumbnail */
|
/** The URL of the static thumbnail */
|
||||||
thumbnailUrl: string
|
thumbnailUrl?: string
|
||||||
/** The width of the original video source */
|
/** The width of the original video source */
|
||||||
videoWidth: number
|
videoWidth?: number
|
||||||
/** The height of the original video source */
|
/** The height of the original video source */
|
||||||
videoHeight: number
|
videoHeight?: number
|
||||||
/** The fixed width of a single frame in the sprite sheet (default 480) */
|
/** The fixed width of a single frame in the sprite sheet (default 480) */
|
||||||
frameWidth?: number
|
frameWidth?: number
|
||||||
/** Optional custom class name for the container */
|
/** Optional custom class name for the container */
|
||||||
@@ -22,33 +28,79 @@ interface Dimensions {
|
|||||||
height: number
|
height: number
|
||||||
}
|
}
|
||||||
|
|
||||||
const GRID_COLS = 10
|
const FULL_SPRITE_LAYOUT: SpriteLayout = { columns: 10, rows: 10, frameCount: 100 }
|
||||||
const GRID_ROWS = 10
|
|
||||||
const TOTAL_FRAMES = GRID_COLS * GRID_ROWS
|
interface SpriteImage extends Dimensions {
|
||||||
|
url: string
|
||||||
|
}
|
||||||
|
|
||||||
|
function useSpriteImage(url: string | undefined) {
|
||||||
|
const [result, setResult] = useState<{ url: string; image: SpriteImage | null }>()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!url) return
|
||||||
|
const img = new Image()
|
||||||
|
img.onload = () =>
|
||||||
|
setResult({ url, image: { url, width: img.naturalWidth, height: img.naturalHeight } })
|
||||||
|
img.onerror = () => setResult({ url, image: null })
|
||||||
|
img.src = url
|
||||||
|
return () => {
|
||||||
|
img.onload = null
|
||||||
|
img.onerror = null
|
||||||
|
}
|
||||||
|
}, [url])
|
||||||
|
|
||||||
|
return result?.url === url ? result?.image : undefined
|
||||||
|
}
|
||||||
|
|
||||||
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
||||||
spriteUrl,
|
spriteUrl,
|
||||||
|
spriteLayout = FULL_SPRITE_LAYOUT,
|
||||||
|
showFirstFrame = false,
|
||||||
|
fallbackSpriteUrl,
|
||||||
thumbnailUrl,
|
thumbnailUrl,
|
||||||
videoWidth,
|
videoWidth = 1,
|
||||||
videoHeight,
|
videoHeight = 1,
|
||||||
className = '',
|
className = '',
|
||||||
reverse = false,
|
reverse = false,
|
||||||
}) => {
|
}) => {
|
||||||
const containerRef = useRef<HTMLDivElement>(null)
|
const containerRef = useRef<HTMLDivElement>(null)
|
||||||
|
const { ref: observeVisibility, inView } = useInView({
|
||||||
|
skip: !showFirstFrame,
|
||||||
|
triggerOnce: true,
|
||||||
|
fallbackInView: true,
|
||||||
|
})
|
||||||
|
const setContainerRef = useCallback(
|
||||||
|
(element: HTMLDivElement | null) => {
|
||||||
|
containerRef.current = element
|
||||||
|
observeVisibility(element)
|
||||||
|
},
|
||||||
|
[observeVisibility],
|
||||||
|
)
|
||||||
const [containerSize, setContainerSize] = useState<Dimensions>({
|
const [containerSize, setContainerSize] = useState<Dimensions>({
|
||||||
width: 0,
|
width: 0,
|
||||||
height: 0,
|
height: 0,
|
||||||
})
|
})
|
||||||
const [naturalSize, setNaturalSize] = useState<Dimensions>({
|
|
||||||
width: 0,
|
|
||||||
height: 0,
|
|
||||||
})
|
|
||||||
|
|
||||||
const [isHovering, setIsHovering] = useState(false)
|
const [isHovering, setIsHovering] = useState(false)
|
||||||
const [spriteLoaded, setSpriteLoaded] = useState(false)
|
const [hasHovered, setHasHovered] = useState(false)
|
||||||
const [loadingSprite, setLoadingSprite] = useState(false)
|
|
||||||
const [currentFrame, setCurrentFrame] = useState(0)
|
|
||||||
const [cursorX, setCursorX] = useState(0)
|
const [cursorX, setCursorX] = useState(0)
|
||||||
|
const [progress, setProgress] = useState<number>()
|
||||||
|
|
||||||
|
const loadPrimary = hasHovered || (showFirstFrame && inView)
|
||||||
|
const primary = useSpriteImage(loadPrimary ? spriteUrl : undefined)
|
||||||
|
const fallbackUrl =
|
||||||
|
hasHovered && primary === null && fallbackSpriteUrl !== spriteUrl
|
||||||
|
? fallbackSpriteUrl
|
||||||
|
: undefined
|
||||||
|
const fallback = useSpriteImage(fallbackUrl)
|
||||||
|
const sprite = primary ?? fallback
|
||||||
|
const spriteVisible = Boolean(sprite && (isHovering || (showFirstFrame && primary)))
|
||||||
|
const spriteLoading =
|
||||||
|
primary === undefined || (fallbackUrl !== undefined && fallback === undefined)
|
||||||
|
const { columns, rows, frameCount } = fallback ? FULL_SPRITE_LAYOUT : spriteLayout
|
||||||
|
const frame = Math.min(Math.floor((progress ?? 0) * frameCount), frameCount - 1)
|
||||||
|
const cursorFrame = reverse && progress !== undefined ? frameCount - 1 - frame : frame
|
||||||
|
const currentFrame = showFirstFrame && !isHovering ? 0 : cursorFrame
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!containerRef.current) return
|
if (!containerRef.current) return
|
||||||
@@ -66,26 +118,9 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
|||||||
return () => observer.disconnect()
|
return () => observer.disconnect()
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const loadSprite = useCallback(() => {
|
|
||||||
if (spriteLoaded || loadingSprite) return
|
|
||||||
|
|
||||||
setLoadingSprite(true)
|
|
||||||
const img = new Image()
|
|
||||||
img.src = spriteUrl
|
|
||||||
img.onload = () => {
|
|
||||||
setNaturalSize({ width: img.naturalWidth, height: img.naturalHeight })
|
|
||||||
setSpriteLoaded(true)
|
|
||||||
setLoadingSprite(false)
|
|
||||||
}
|
|
||||||
img.onerror = () => {
|
|
||||||
console.error('Failed to load sprite image')
|
|
||||||
setLoadingSprite(false)
|
|
||||||
}
|
|
||||||
}, [spriteUrl, spriteLoaded, loadingSprite])
|
|
||||||
|
|
||||||
const handleMouseEnter = () => {
|
const handleMouseEnter = () => {
|
||||||
setIsHovering(true)
|
setIsHovering(true)
|
||||||
loadSprite()
|
setHasHovered(true)
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleMouseLeave = () => {
|
const handleMouseLeave = () => {
|
||||||
@@ -100,22 +135,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
|||||||
|
|
||||||
const clampedX = Math.max(0, Math.min(x, rect.width))
|
const clampedX = Math.max(0, Math.min(x, rect.width))
|
||||||
setCursorX(clampedX)
|
setCursorX(clampedX)
|
||||||
|
setProgress(rect.width > 0 ? clampedX / rect.width : 0)
|
||||||
const percentage = clampedX / rect.width
|
|
||||||
const rawFrame = Math.min(Math.floor(percentage * TOTAL_FRAMES), TOTAL_FRAMES - 1)
|
|
||||||
const frameIndex = reverse ? TOTAL_FRAMES - 1 - rawFrame : rawFrame
|
|
||||||
|
|
||||||
setCurrentFrame(frameIndex)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Calculate styles for the inner sprite frame box
|
// Calculate styles for the inner sprite frame box
|
||||||
const spriteStyle: React.CSSProperties = useMemo(() => {
|
const spriteStyle: React.CSSProperties = useMemo(() => {
|
||||||
if (containerSize.width === 0 || containerSize.height === 0) return {}
|
if (!sprite || containerSize.width === 0 || containerSize.height === 0) return {}
|
||||||
|
|
||||||
let sourceAspect = videoWidth / videoHeight
|
let sourceAspect = videoWidth / videoHeight
|
||||||
if (naturalSize.width > 0 && naturalSize.height > 0) {
|
if (sprite.width > 0 && sprite.height > 0) {
|
||||||
const singleFrameNaturalW = naturalSize.width / GRID_COLS
|
const singleFrameNaturalW = sprite.width / columns
|
||||||
const singleFrameNaturalH = naturalSize.height / GRID_ROWS
|
const singleFrameNaturalH = sprite.height / rows
|
||||||
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
|
sourceAspect = singleFrameNaturalW / singleFrameNaturalH
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -139,17 +169,17 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
|||||||
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
|
// IMPORTANT: We calculate the sheet size based on the SNAPPED frame size.
|
||||||
// This slightly stretches the sprite if needed but ensures that every frame
|
// This slightly stretches the sprite if needed but ensures that every frame
|
||||||
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
|
// falls exactly on an integer pixel boundary, preventing "shaking" during playback.
|
||||||
const bgWidth = finalW * GRID_COLS
|
const bgWidth = finalW * columns
|
||||||
const bgHeight = finalH * GRID_ROWS
|
const bgHeight = finalH * rows
|
||||||
|
|
||||||
const colIndex = currentFrame % GRID_COLS
|
const colIndex = currentFrame % columns
|
||||||
const rowIndex = Math.floor(currentFrame / GRID_COLS)
|
const rowIndex = Math.floor(currentFrame / columns)
|
||||||
|
|
||||||
const bgPosX = -(colIndex * finalW)
|
const bgPosX = -(colIndex * finalW)
|
||||||
const bgPosY = -(rowIndex * finalH)
|
const bgPosY = -(rowIndex * finalH)
|
||||||
|
|
||||||
return {
|
return {
|
||||||
backgroundImage: `url(${spriteUrl})`,
|
backgroundImage: `url(${sprite.url})`,
|
||||||
backgroundSize: `${bgWidth}px ${bgHeight}px`,
|
backgroundSize: `${bgWidth}px ${bgHeight}px`,
|
||||||
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
|
backgroundPosition: `${bgPosX}px ${bgPosY}px`,
|
||||||
backgroundRepeat: 'no-repeat',
|
backgroundRepeat: 'no-repeat',
|
||||||
@@ -158,11 +188,11 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
|||||||
// Optional: helps with crisp edges on some screens, though default is usually fine
|
// Optional: helps with crisp edges on some screens, though default is usually fine
|
||||||
imageRendering: 'auto',
|
imageRendering: 'auto',
|
||||||
}
|
}
|
||||||
}, [containerSize, videoWidth, videoHeight, currentFrame, spriteUrl, naturalSize])
|
}, [containerSize, videoWidth, videoHeight, currentFrame, sprite, columns, rows])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
ref={containerRef}
|
ref={setContainerRef}
|
||||||
data-testid="sprite-scrubber"
|
data-testid="sprite-scrubber"
|
||||||
data-frame={currentFrame}
|
data-frame={currentFrame}
|
||||||
className={`relative w-full h-full overflow-hidden cursor-pointer group bg-black select-none ${className}`}
|
className={`relative w-full h-full overflow-hidden cursor-pointer group bg-black select-none ${className}`}
|
||||||
@@ -170,32 +200,34 @@ export const SpriteScrubber: React.FC<SpriteScrubberProps> = ({
|
|||||||
onMouseLeave={handleMouseLeave}
|
onMouseLeave={handleMouseLeave}
|
||||||
onMouseMove={handleMouseMove}
|
onMouseMove={handleMouseMove}
|
||||||
>
|
>
|
||||||
<img
|
{thumbnailUrl && (!showFirstFrame || primary === null) && (
|
||||||
src={thumbnailUrl}
|
<img
|
||||||
alt="Thumbnail"
|
src={thumbnailUrl}
|
||||||
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
alt="Thumbnail"
|
||||||
isHovering && spriteLoaded ? 'opacity-0' : 'opacity-100'
|
className={`absolute inset-0 w-full h-full object-contain transition-opacity duration-200 ${
|
||||||
}`}
|
spriteVisible ? 'opacity-0' : 'opacity-100'
|
||||||
draggable={false}
|
}`}
|
||||||
/>
|
draggable={false}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
{isHovering && !spriteLoaded && (
|
{isHovering && spriteLoading && (
|
||||||
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
|
<div className="absolute inset-0 flex items-center justify-center bg-black/50 z-10 pointer-events-none">
|
||||||
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
<div className="w-6 h-6 border-2 border-white/30 border-t-white rounded-full animate-spin" />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{spriteLoaded && (
|
{sprite && (
|
||||||
<div
|
<div
|
||||||
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
|
className={`absolute inset-0 flex items-center justify-center transition-opacity duration-75 ${
|
||||||
isHovering ? 'opacity-100' : 'opacity-0'
|
spriteVisible ? 'opacity-100' : 'opacity-0'
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
<div style={spriteStyle} />
|
<div style={spriteStyle} />
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{isHovering && (
|
{isHovering && (spriteLoading || sprite) && (
|
||||||
<div
|
<div
|
||||||
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
|
className="absolute top-0 bottom-0 w-0.5 bg-red-500 shadow-[0_0_4px_rgba(255,0,0,0.8)] z-20 pointer-events-none"
|
||||||
style={{ transform: `translateX(${cursorX}px)` }}
|
style={{ transform: `translateX(${cursorX}px)` }}
|
||||||
|
|||||||
Reference in New Issue
Block a user