Skip to content

A full-featured download manager.

fix(media): calculate progress across the full segment plan (#2158)

Dr_rOotadc9414da10c
diff --git a/.github/pr-assets/media-progress-compact.png b/.github/pr-assets/media-progress-compact.png
new file mode 100644
index 00000000..af54827b
Binary files /dev/null and b/.github/pr-assets/media-progress-compact.png differ
diff --git a/.github/pr-assets/media-progress-wide.png b/.github/pr-assets/media-progress-wide.png
new file mode 100644
index 00000000..eb5fbb3c
Binary files /dev/null and b/.github/pr-assets/media-progress-wide.png differ
diff --git a/e2e/downloads-visibility.spec.ts b/e2e/downloads-visibility.spec.ts
index e5ce78c5..6ffc1aa1 100644
--- a/e2e/downloads-visibility.spec.ts
+++ b/e2e/downloads-visibility.spec.ts
@@ -9,6 +9,7 @@ import {
TaskStatus,
TaskType,
} from '@shared/types/task'
+import { makeMediaProgress } from '../src/test-utils/media-progress'
import { makeDownloadTask } from '../src/test-utils/task'
import {
expect,
@@ -98,6 +99,115 @@ async function expectDrawerSettled(drawer: Locator) {
.toBe(true)
}
+test('media task progress follows segments, then the processing stage, until the output is saved', async ({
+ electronApp,
+ mainWindow,
+}, testInfo) => {
+ await mainWindow.emulateMedia({ reducedMotion: 'reduce' })
+ await waitForEngineReady(mainWindow)
+ await setTaskInspectorContentSize(electronApp, mainWindow, 1280, 900)
+ await mainWindow.getByRole('link', { name: 'Downloads', exact: true }).click()
+ await expect(mainWindow.getByTestId('downloads-loading')).toHaveCount(0)
+ const task = makeDownloadTask({
+ id: 'media-progress',
+ name: 'Progress.mp4',
+ kind: TaskKind.Hls,
+ status: TaskStatus.Downloading,
+ progress: 1,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ mediaProgress: makeMediaProgress(),
+ })
+ await publish(electronApp, [task])
+ const row = mainWindow.locator('[data-task-id="media-progress"]')
+ await expect(row.getByText('Downloading 0.1%', { exact: true })).toBeVisible()
+ await expect(row.getByRole('progressbar')).toHaveAttribute(
+ 'aria-valuenow',
+ '0.1'
+ )
+ await mainWindow
+ .getByRole('button', { name: 'List View', exact: true })
+ .click()
+ await mainWindow
+ .getByRole('menuitemcheckbox', { name: 'Status', exact: true })
+ .click()
+ await mainWindow.keyboard.press('Escape')
+ await expect(row.getByText('Downloading 0.1%', { exact: true })).toBeVisible()
+ const completeDownload = {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ }
+ task.mediaProgress = makeMediaProgress({
+ phase: 'muxing',
+ download: completeDownload,
+ })
+ await publish(electronApp, [task])
+ await expect(row.getByText('Merging —', { exact: true })).toBeVisible()
+ await expect(row.getByRole('progressbar')).not.toHaveAttribute(
+ 'aria-valuenow'
+ )
+ task.mediaProgress = { ...task.mediaProgress, muxProgress: 0.42 }
+ await publish(electronApp, [task])
+ await expect(row.getByText('Merging 42%', { exact: true })).toBeVisible()
+ await row.dblclick()
+ const inspector = mainWindow.getByRole('dialog', { name: 'Task Inspector' })
+ await expect(
+ inspector.getByText('Download progress', { exact: true })
+ ).toBeVisible()
+ await expect(inspector.getByText('100%', { exact: true })).toBeVisible()
+ await expect(inspector.getByText('42%', { exact: true })).toBeVisible()
+ await expect(
+ inspector.getByText('1000 / 1000 segments', { exact: true })
+ ).toBeVisible()
+ await expect(
+ inspector.getByRole('button', { name: 'Pause', exact: true })
+ ).toHaveCount(0)
+ await inspector
+ .getByRole('separator', { name: 'Resize Inspector' })
+ .press('End')
+ await expectDrawerSettled(inspector)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('media-mux-progress.png'),
+ animations: 'disabled',
+ })
+ await setTaskInspectorContentSize(electronApp, mainWindow, 914, 640)
+ await expectDrawerSettled(inspector)
+ await inspector
+ .getByText('Download progress', { exact: true })
+ .scrollIntoViewIfNeeded()
+ expect(
+ await mainWindow.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ )
+ ).toBe(true)
+ await mainWindow.screenshot({
+ path: testInfo.outputPath('media-mux-progress-compact.png'),
+ animations: 'disabled',
+ })
+
+ task.status = TaskStatus.Finalizing
+ task.mediaProgress = {
+ ...task.mediaProgress,
+ phase: 'renaming',
+ muxProgress: 1,
+ }
+ await publish(electronApp, [task])
+ await expect(
+ inspector.getByText('Saving', { exact: true }).first()
+ ).toBeVisible()
+ await expect(inspector.getByText('Completed', { exact: true })).toHaveCount(0)
+ task.status = TaskStatus.Completed
+ task.mediaProgress = { ...task.mediaProgress, outputBytes: 2_000_000 }
+ task.sizeWhenDone = 2_000_000
+ await publish(electronApp, [task])
+ await expect(
+ inspector.getByText('Completed', { exact: true }).first()
+ ).toBeVisible()
+ await expect(inspector.getByText('2.00 MB', { exact: true })).toBeVisible()
+})
+
test('media file list shows every segment through virtual scrolling and stays read-only', async ({
electronApp,
mainWindow,
@@ -295,9 +405,12 @@ test('download columns sort live tasks without losing selection or filter state'
await mainWindow
.getByRole('button', { name: 'List View', exact: true })
.click()
- await mainWindow
- .getByRole('menuitemcheckbox', { name: 'ETA', exact: true })
- .click()
+ const etaColumn = mainWindow.getByRole('menuitemcheckbox', {
+ name: 'ETA',
+ exact: true,
+ })
+ if ((await etaColumn.getAttribute('aria-checked')) !== 'true')
+ await etaColumn.click()
await mainWindow.keyboard.press('Escape')
await list.getByRole('button', { name: 'ETA', exact: true }).click()
await expectOrder([1, 2, 10])
diff --git a/src/core/bridge-receiver/progress-mapping.ts b/src/core/bridge-receiver/progress-mapping.ts
index 16784168..063d45ea 100644
--- a/src/core/bridge-receiver/progress-mapping.ts
+++ b/src/core/bridge-receiver/progress-mapping.ts
@@ -7,6 +7,10 @@ import type {
import type { GlobalStats } from '@shared/types/stats'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
+import {
+ getTransferMetrics,
+ isMediaProcessing,
+} from '@shared/utils/media-progress'
import type { BridgeErrorCode } from './errors'
/**
@@ -18,8 +22,8 @@ import type { BridgeErrorCode } from './errors'
*/
/** Domain `TaskStatus` → the lossy 4-value `$/task/progress.phase` enum.
- * (Distinct from the richer `MdxpTaskStatus` used by `task/get`.) Motrix has no
- * `muxing` status in v1, so that value is never emitted. */
+ * (Distinct from the richer `MdxpTaskStatus` used by `task/get`.) Media tasks
+ * additionally project their processing phase in taskToProgressParams. */
export function mapStatusToPhase(
s: TaskStatus
): 'queued' | 'downloading' | 'muxing' | 'finalizing' {
@@ -50,10 +54,12 @@ export function taskToProgressParams(task: DownloadTask): TaskProgressParams {
return {
taskId: task.id,
bytesDone: task.downloadedBytes,
- bytesTotal: task.totalBytes > 0 ? task.totalBytes : null,
- speedBps: task.downloadSpeed,
- etaSec: task.etaSeconds > 0 ? task.etaSeconds : null,
- phase: mapStatusToPhase(task.status),
+ ...getTransferMetrics(task),
+ phase: isMediaProcessing(task)
+ ? task.mediaProgress?.phase === 'muxing'
+ ? 'muxing'
+ : 'finalizing'
+ : mapStatusToPhase(task.status),
}
}
diff --git a/src/core/bridge/mappers/download-task-to-mdxp.test.ts b/src/core/bridge/mappers/download-task-to-mdxp.test.ts
index 7c3bcb85..4b7cc286 100644
--- a/src/core/bridge/mappers/download-task-to-mdxp.test.ts
+++ b/src/core/bridge/mappers/download-task-to-mdxp.test.ts
@@ -1,10 +1,13 @@
+import { taskToProgressParams } from '@core/bridge-receiver/progress-mapping'
import { MdxpTaskSchema } from '@motrix/mdxp'
import { DownloadErrorCode } from '@shared/errors'
import {
makeDefaultBtExtension,
+ TaskKind,
TaskStatus,
TaskType,
} from '@shared/types/task'
+import { makeMediaProgress } from '@test-utils/media-progress'
import { makeDownloadTask } from '@test-utils/task'
import { describe, expect, it } from 'vitest'
import { toMdxpTask, toMdxpTaskStatus } from './download-task-to-mdxp'
@@ -300,3 +303,66 @@ describe('toMdxpTask', () => {
expectValidMdxpTask(dto)
})
})
+
+describe('media query and push agreement', () => {
+ it.each(['decrypting', 'assembling', 'muxing', 'renaming'] as const)(
+ 'projects %s as processing without changing the core lifecycle',
+ (phase) => {
+ const task = makeDownloadTask({
+ kind: TaskKind.Hls,
+ status: TaskStatus.Downloading,
+ progress: 1,
+ downloadSpeed: 500,
+ etaSeconds: 10,
+ totalBytes: 100,
+ mediaProgress: makeMediaProgress({
+ phase,
+ download: {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ muxProgress: 0.4,
+ }),
+ })
+ const dto = toMdxpTask(task)
+ expectValidMdxpTask(dto)
+ expect(dto).toMatchObject({
+ status: 'finalizing',
+ progress: 1,
+ bytesTotal: null,
+ speedBps: 0,
+ etaSec: null,
+ })
+ expect(taskToProgressParams(task)).toMatchObject({
+ phase: phase === 'muxing' ? 'muxing' : 'finalizing',
+ bytesTotal: null,
+ speedBps: 0,
+ etaSec: null,
+ })
+ expect(task.status).toBe(TaskStatus.Downloading)
+ expect(toMdxpTask({ ...task, status: TaskStatus.Paused }).status).toBe(
+ 'paused'
+ )
+ expect(toMdxpTask({ ...task, status: TaskStatus.Error }).status).toBe(
+ 'error'
+ )
+ }
+ )
+
+ it('returns the fixed segment fraction even when completed bytes equal known bytes', () => {
+ const task = makeDownloadTask({
+ kind: TaskKind.Hls,
+ progress: 1,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ mediaProgress: makeMediaProgress(),
+ })
+ expect(toMdxpTask(task)).toMatchObject({
+ progress: 0.001,
+ bytesTotal: null,
+ })
+ expect(taskToProgressParams(task).bytesTotal).toBeNull()
+ })
+})
diff --git a/src/core/bridge/mappers/download-task-to-mdxp.ts b/src/core/bridge/mappers/download-task-to-mdxp.ts
index 48ba3dc5..89629976 100644
--- a/src/core/bridge/mappers/download-task-to-mdxp.ts
+++ b/src/core/bridge/mappers/download-task-to-mdxp.ts
@@ -1,6 +1,11 @@
import type { MdxpTask, MdxpTaskStatus, MdxpTaskType } from '@motrix/mdxp'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
+import {
+ getDownloadProgress,
+ getTransferMetrics,
+ isMediaProcessing,
+} from '@shared/utils/media-progress'
/**
* Pure projection of the host-domain `DownloadTask` onto the public
@@ -18,13 +23,13 @@ export function toMdxpTask(task: DownloadTask): MdxpTask {
id: task.id,
type: TASK_TYPE_MAP[task.type],
name: task.name,
- status: toMdxpTaskStatus(task.status),
- // progress is identity — DownloadTask.progress is already a [0,1] fraction
- progress: task.progress,
+ status: isMediaProcessing(task)
+ ? 'finalizing'
+ : toMdxpTaskStatus(task.status),
+ // Media progress remains the transfer fraction during post-processing.
+ progress: getDownloadProgress(task) ?? 0,
bytesDone: task.downloadedBytes,
- bytesTotal: task.totalBytes > 0 ? task.totalBytes : null,
- speedBps: task.downloadSpeed,
- etaSec: task.etaSeconds > 0 ? task.etaSeconds : null,
+ ...getTransferMetrics(task),
saveDir: task.saveDir,
// Recovery-path failures (e.g. a startup re-add mismatch) carry no raw
// engine errorMessage, only an i18n errorDetailKey — fall back to that so
diff --git a/src/core/download/segment-downloader.test.ts b/src/core/download/segment-downloader.test.ts
index a531d604..51f88f48 100644
--- a/src/core/download/segment-downloader.test.ts
+++ b/src/core/download/segment-downloader.test.ts
@@ -5,6 +5,7 @@ import type {
PollScheduler,
SegmentAria2,
SegmentFileProgress,
+ SegmentProgress,
} from './segment-downloader'
import { SegmentDownloader } from './segment-downloader'
@@ -146,6 +147,135 @@ const TMP = '/tmp/test-seg'
// ---------------------------------------------------------------------------
describe('SegmentDownloader', () => {
+ it('counts init and active fractions, rolls back retries and keeps totals unknown until every size is known', async () => {
+ const fake = makeFakeAria2()
+ const clock = makeManualScheduler()
+ const dl = new SegmentDownloader({
+ aria2: fake.aria2,
+ tmpDir: TMP,
+ concurrency: 2,
+ pollScheduler: clock.scheduler,
+ })
+ const updates: SegmentProgress[] = []
+ const run = dl
+ .run(
+ makePlan({
+ init: { url: 'https://cdn/init' },
+ segments: [{ url: 'https://cdn/1' }, { url: 'https://cdn/2' }],
+ }),
+ {},
+ (p) => updates.push(p)
+ )
+ .catch(() => {})
+ await new Promise((resolve) => setImmediate(resolve))
+ fake.setBytes('gid1', 50, 100)
+ fake.setBytes('gid2', 700, 0)
+ await clock.tick()
+ expect(updates.at(-1)).toMatchObject({
+ fraction: 0.5 / 3,
+ completedParts: 0,
+ totalParts: 3,
+ totalBytes: 0,
+ })
+ fake.fireError('gid1')
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(updates.at(-1)?.fraction).toBe(0)
+ fake.setBytes('gid3', 100, 100)
+ await clock.tick()
+ expect(updates.at(-1)?.fraction).toBeLessThan(1 / 3)
+ fake.fireComplete('gid3')
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(updates.at(-1)?.fraction).toBe(1 / 3)
+ fake.setBytes('gid2', 700, 700)
+ fake.setBytes('gid4', 25, 50)
+ await clock.tick()
+ expect(updates.at(-1)?.totalBytes).toBe(850)
+ fake.fireComplete('gid2')
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(updates.at(-1)?.fraction).toBeCloseTo(2.5 / 3)
+ await dl.cancel()
+ await run
+ })
+
+ it('serializes polls and discards a response for a job completed during the request', async () => {
+ const fake = makeFakeAria2()
+ const clock = makeManualScheduler()
+ const response = Promise.withResolvers<{
+ completedLength: number
+ totalLength: number
+ }>()
+ let requests = 0
+ fake.aria2.tellStatus = async () => {
+ requests++
+ return response.promise
+ }
+ const dl = new SegmentDownloader({
+ aria2: fake.aria2,
+ tmpDir: TMP,
+ concurrency: 1,
+ pollScheduler: clock.scheduler,
+ })
+ const updates: SegmentProgress[] = []
+ const run = dl
+ .run(
+ makePlan({
+ segments: [{ url: 'https://cdn/1' }, { url: 'https://cdn/2' }],
+ }),
+ {},
+ (p) => updates.push(p)
+ )
+ .catch(() => {})
+ await new Promise((resolve) => setImmediate(resolve))
+ const first = clock.tick()
+ await clock.tick()
+ expect(requests).toBe(1)
+ fake.fireComplete('gid1')
+ response.resolve({ completedLength: 50, totalLength: 100 })
+ await first
+ await new Promise((resolve) => setImmediate(resolve))
+ expect(updates.at(-1)).toMatchObject({
+ fraction: 0.5,
+ completedParts: 1,
+ downloadedBytes: 100,
+ })
+ await dl.cancel()
+ await run
+ })
+
+ it('knows the full byte-range denominator before queued jobs begin', async () => {
+ const fake = makeFakeAria2()
+ const clock = makeManualScheduler()
+ const dl = new SegmentDownloader({
+ aria2: fake.aria2,
+ tmpDir: TMP,
+ concurrency: 1,
+ pollScheduler: clock.scheduler,
+ })
+ const updates: SegmentProgress[] = []
+ const run = dl
+ .run(
+ makePlan({
+ segments: [
+ { url: 'https://cdn/1', byteRange: { offset: 0, length: 100 } },
+ { url: 'https://cdn/2', byteRange: { offset: 100, length: 300 } },
+ ],
+ }),
+ {},
+ (p) => updates.push(p)
+ )
+ .catch(() => {})
+ await new Promise((resolve) => setImmediate(resolve))
+ fake.setBytes('gid1', 50, 100)
+ await clock.tick()
+ expect(updates.at(-1)).toMatchObject({
+ fraction: 0.25,
+ totalBytes: 400,
+ downloadedBytes: 50,
+ })
+ await dl.cancel()
+ await run
+ })
+
it('reports file progress by plan index across polling, retries and out-of-order completion', async () => {
const fake = makeFakeAria2()
const clock = makeManualScheduler()
@@ -607,6 +737,7 @@ describe('SegmentDownloader', () => {
// seg0 finishes: its last-seen total (1000) is retained as a finished
// segment; the total must never shrink when a segment leaves the active set.
fake.fireComplete('gid1')
+ await new Promise((resolve) => setImmediate(resolve))
const afterComplete = reports[reports.length - 1]
expect(afterComplete.totalBytes).toBe(1500) // 1000 finished + 500 active
expect(afterComplete.downloadedBytes).toBe(1200) // 1000 finished + 200 live
diff --git a/src/core/download/segment-downloader.ts b/src/core/download/segment-downloader.ts
index d8eb62b0..fe93a17e 100644
--- a/src/core/download/segment-downloader.ts
+++ b/src/core/download/segment-downloader.ts
@@ -4,6 +4,7 @@ import type {
MediaPart,
SegmentPlan,
} from '@core/media/segment-plan'
+import { segmentFraction } from '@shared/utils/media-progress'
// ---------------------------------------------------------------------------
// Public interface — narrow aria2 client (injected by T15 adapter)
@@ -54,15 +55,17 @@ export interface SegmentAria2 {
/** Byte-accurate progress emitted by {@link SegmentDownloader.run}. */
export interface SegmentProgress {
- /** Segment-count fraction (completed jobs / total jobs), 0..1. */
+ /** All planned jobs, including partial contributions from active jobs. */
fraction: number
+ completedParts: number
+ totalParts: number
/**
* Summed `completedLength` of finished + in-flight segments, in bytes.
* Finished segments count their full size; in-flight ones count aria2's
* live `completedLength` from the most recent poll.
*/
downloadedBytes: number
- /** Summed `totalLength` of finished + in-flight segments, in bytes. */
+ /** Full plan size, or zero until every job has a known size. */
totalBytes: number
}
@@ -96,6 +99,7 @@ interface Job {
outPath: string
/** How many re-add attempts remain after the first failure. */
retriesLeft: number
+ knownSize?: number
}
// ---------------------------------------------------------------------------
@@ -268,21 +272,19 @@ export class SegmentDownloader {
const total = jobs.length
let completed = 0
- // ── Byte accounting ──────────────────────────────────────────────────
- // `finished*` accumulates the final size of completed segments (a completed
- // segment is 100% downloaded). Live in-flight bytes are recomputed on every
- // report from `lastSeen` (the most recent tellStatus per active gid) summed
- // over the CURRENT active gids — so a segment leaving the set never causes a
- // double-count, and a poll that transiently returns null keeps the prior
- // value instead of dropping bytes.
const lastSeen = new Map<string, { completed: number; total: number }>()
- // A completed segment counts its full size toward BOTH downloaded and total
- // (completed === total once done), so ONE accumulator serves both. Live
- // in-flight bytes are recomputed on every report from `lastSeen` over the
- // CURRENT active gids — so a segment leaving the set never double-counts,
- // and a poll that transiently returns null keeps the prior value instead of
- // dropping bytes.
let finishedBytes = 0
+ let knownBytes = 0
+ let knownParts = 0
+ const recordSize = (job: Job, size: number) => {
+ if (!Number.isFinite(size) || size <= 0) return
+ if (job.knownSize === undefined) knownParts++
+ knownBytes += size - (job.knownSize ?? 0)
+ job.knownSize = size
+ }
+ for (const job of jobs) recordSize(job, job.part.byteRange?.length ?? 0)
+ const safeBytes = (value: number) =>
+ Number.isFinite(value) ? Math.max(0, value) : 0
return new Promise<{ initPath?: string; partPaths: string[] }>(
(resolve, reject) => {
if (total === 0) {
@@ -299,29 +301,25 @@ export class SegmentDownloader {
}
const report = () => {
+ if (this.cancelled) return
let activeCompleted = 0
- let activeTotal = 0
- for (const gid of this.activeGids) {
- const ls = lastSeen.get(gid)
- if (ls) {
- activeCompleted += ls.completed
- activeTotal += ls.total
- }
+ let partialParts = 0
+ // Keep settling jobs here until their contribution is atomically
+ // transferred to completed. Work per report is bounded by concurrency.
+ for (const ls of lastSeen.values()) {
+ activeCompleted += ls.completed
+ partialParts += segmentFraction(ls.completed, ls.total, false)
}
onProgress({
- fraction: total > 0 ? completed / total : 0,
+ fraction:
+ completed === total ? 1 : (completed + partialParts) / total,
+ completedParts: completed,
+ totalParts: total,
downloadedBytes: finishedBytes + activeCompleted,
- totalBytes: finishedBytes + activeTotal,
+ totalBytes: knownParts === total ? knownBytes : 0,
})
}
- // Retain a finished segment's full size (so the total never shrinks when
- // its gid leaves the active set), then re-report.
- const addFinished = (bytes: number) => {
- finishedBytes += bytes
- report()
- }
-
const buildResult = () => {
const sorted = jobs.slice().sort((a, b) => a.jobIndex - b.jobIndex)
let initPath: string | undefined
@@ -356,23 +354,27 @@ export class SegmentDownloader {
const status = ls?.total
? null
: await this.aria2.tellStatus(gid).catch(() => null)
- const size =
+ const size = safeBytes(
status?.totalLength ||
- ls?.total ||
- job.part.byteRange?.length ||
- 0
+ ls?.total ||
+ job.knownSize ||
+ status?.completedLength ||
+ ls?.completed ||
+ 0
+ )
+ recordSize(job, size)
+ await this.purgeResult(gid)
+ this.settlingGids.delete(gid)
+ if (this.cancelled) return
lastSeen.delete(gid)
+ finishedBytes += size
+ completed++
onFileProgress?.({
index: job.jobIndex,
downloadedBytes: size,
totalBytes: size,
completed: true,
})
- if (size > 0) addFinished(size)
-
- await this.purgeResult(gid)
- this.settlingGids.delete(gid)
- completed++
report()
releaseSlot()
resolveWhenDone()
@@ -392,7 +394,7 @@ export class SegmentDownloader {
onFileProgress?.({
index: job.jobIndex,
downloadedBytes: 0,
- totalBytes: job.part.byteRange?.length ?? 0,
+ totalBytes: job.knownSize ?? 0,
completed: false,
})
report()
@@ -419,44 +421,56 @@ export class SegmentDownloader {
// ── Byte poll ────────────────────────────────────────────────────
// Refresh the live-byte cache for every in-flight gid, then report.
// Never throws: tellStatus null-guards and the tick is fire-and-forget.
+ let polling = false
const pollOnce = async () => {
- const gids = [...this.activeGids]
- if (gids.length > 0) {
- const results = await Promise.all(
- gids.map((g) =>
- this.aria2.tellStatus(g).then(
- (s) => ({ gid: g, s }),
- () => ({ gid: g, s: null })
+ if (polling || this.cancelled) return
+ polling = true
+ try {
+ const gids = [...this.activeGids]
+ if (gids.length > 0) {
+ const results = await Promise.all(
+ gids.map((g) =>
+ this.aria2.tellStatus(g).then(
+ (s) => ({ gid: g, s }),
+ () => ({ gid: g, s: null })
+ )
)
)
- )
- for (const { gid, s } of results) {
- // A gid that completed/errored during the await is no longer
- // active — skip it so we don't resurrect a stale cache entry.
- if (!this.activeGids.has(gid)) continue
- if (s) {
- lastSeen.set(gid, {
- completed: s.completedLength,
- total: s.totalLength,
- })
- const job = this.activeJobs.get(gid)
- if (job) {
+ for (const { gid, s } of results) {
+ // A gid that completed/errored during the await is no longer
+ // active — skip it so we don't resurrect a stale cache entry.
+ if (!this.activeGids.has(gid)) continue
+ if (s) {
+ const job = this.activeJobs.get(gid)
+ if (!job || this.cancelled) continue
+ recordSize(job, s.totalLength)
+ const totalBytes = job.knownSize ?? 0
+ const downloadedBytes =
+ totalBytes > 0
+ ? Math.min(totalBytes, safeBytes(s.completedLength))
+ : safeBytes(s.completedLength)
+ lastSeen.set(gid, {
+ completed: downloadedBytes,
+ total: totalBytes,
+ })
onFileProgress?.({
index: job.jobIndex,
- downloadedBytes: s.completedLength,
- totalBytes: s.totalLength,
+ downloadedBytes,
+ totalBytes,
completed: false,
})
}
}
}
+ report()
+ } finally {
+ polling = false
}
- report()
}
// Semaphore implementation
let running = 0
- const jobQueue = jobs.slice()
+ let nextJob = 0
const submitJob = (job: Job) => {
if (this.cancelled) {
@@ -502,8 +516,8 @@ export class SegmentDownloader {
}
const drain = () => {
- while (running < this.concurrency && jobQueue.length > 0) {
- const next = jobQueue.shift()
+ while (running < this.concurrency && nextJob < jobs.length) {
+ const next = jobs[nextJob++]
if (next !== undefined) submitJob(next)
}
}
diff --git a/src/core/ffmpeg/ffmpeg-service.test.ts b/src/core/ffmpeg/ffmpeg-service.test.ts
index c3b83ced..253084a2 100644
--- a/src/core/ffmpeg/ffmpeg-service.test.ts
+++ b/src/core/ffmpeg/ffmpeg-service.test.ts
@@ -103,7 +103,7 @@ describe('FfmpegService', () => {
it('(d) progress fraction from out_time_ms / duration', async () => {
const child = fakeChild()
const svc = new FfmpegService()
- const seen: number[] = []
+ const seen: (number | null)[] = []
const p = svc.run(
VIDEO_ONLY_TS_JOB,
(pr) => seen.push(pr.progress),
@@ -116,7 +116,77 @@ describe('FfmpegService', () => {
)
child.emit('close', 0)
await p
- expect(seen.at(-1)).toBeCloseTo(0.5, 1)
+ expect(seen).toEqual([0.5, 1])
+ })
+
+ it('parses fragmented lines and multiple records, but progress=end is not success', async () => {
+ const child = fakeChild()
+ const seen: (number | null)[] = []
+ const run = new FfmpegService().run(
+ VIDEO_ONLY_TS_JOB,
+ (p) => seen.push(p.progress),
+ (() => child) as never
+ )
+ child.stdout.emit('data', Buffer.from('out_time_'))
+ child.stdout.emit('data', Buffer.from('ms=2500000\nprogress=cont'))
+ child.stdout.emit(
+ 'data',
+ Buffer.from('inue\nout_time_ms=10000000\nprogress=end\n')
+ )
+ expect(seen).toEqual([0.25, 0.9999])
+ child.emit('close', 1)
+ await expect(run).rejects.toThrow('mux-failed')
+ child.stdout.emit(
+ 'data',
+ Buffer.from('out_time_ms=10000000\nprogress=end\n')
+ )
+ expect(seen).toEqual([0.25, 0.9999])
+ })
+
+ it.each([undefined, 0, Number.NaN, Number.POSITIVE_INFINITY])(
+ 'shows indeterminate mux progress for duration %s until successful exit',
+ async (durationSec) => {
+ const child = fakeChild()
+ const seen: (number | null)[] = []
+ const run = new FfmpegService().run(
+ { ...VIDEO_ONLY_TS_JOB, durationSec },
+ (p) => seen.push(p.progress),
+ (() => child) as never
+ )
+ child.stdout.emit(
+ 'data',
+ Buffer.from('out_time_ms=5000000\nprogress=end\n')
+ )
+ expect(seen).toEqual([null])
+ child.emit('close', 0)
+ await run
+ expect(seen).toEqual([null, 1])
+ }
+ )
+
+ it('drops overlong lines and ignores output after cancellation', async () => {
+ const child = fakeChild()
+ const seen: (number | null)[] = []
+ const svc = new FfmpegService()
+ const run = svc.run(
+ VIDEO_ONLY_TS_JOB,
+ (p) => seen.push(p.progress),
+ (() => child) as never
+ )
+ child.stdout.emit('data', Buffer.from(`out_time_ms=${'9'.repeat(10000)}`))
+ child.stdout.emit(
+ 'data',
+ Buffer.from('\nout_time_ms=2500000\nprogress=continue\n')
+ )
+ expect(seen).toEqual([0.25])
+ svc.kill()
+ child.stdout.emit(
+ 'data',
+ Buffer.from('out_time_ms=10000000\nprogress=end\n')
+ )
+ child.emit('close', 0)
+ await expect(run).rejects.toThrow('mux-aborted')
+ expect(seen).toEqual([0.25])
})
it('(e) non-zero exit rejects with mux-failed', async () => {
diff --git a/src/core/ffmpeg/ffmpeg-service.ts b/src/core/ffmpeg/ffmpeg-service.ts
index a6c669bc..8698fa74 100644
--- a/src/core/ffmpeg/ffmpeg-service.ts
+++ b/src/core/ffmpeg/ffmpeg-service.ts
@@ -1,5 +1,9 @@
import { type ChildProcess, spawn as nodeSpawn } from 'node:child_process'
+export interface FfmpegProgress {
+ progress: number | null
+}
+
export interface RemuxJob {
binaryPath: string
videoPath: string
@@ -76,7 +80,7 @@ export class FfmpegService {
run(
job: RemuxJob,
- onProgress: (p: { progress: number }) => void,
+ onProgress: (p: FfmpegProgress) => void,
spawnImpl: SpawnImpl = nodeSpawn as SpawnImpl
): Promise<void> {
this.aborted = false
@@ -99,26 +103,67 @@ export class FfmpegService {
}
})
+ let closed = false
+ let pending = ''
+ let droppingLine = false
+ let outTimeUs = 0
+ const MAX_PROGRESS_LINE = 4096
+ const acceptLine = (line: string) => {
+ const eq = line.indexOf('=')
+ if (eq < 0) return
+ const key = line.slice(0, eq)
+ const value = line.slice(eq + 1).trim()
+ if (key === 'out_time_ms') {
+ const time = Number(value)
+ if (Number.isFinite(time) && time >= 0)
+ outTimeUs = Math.max(outTimeUs, time)
+ }
+ if (key === 'progress' && (value === 'continue' || value === 'end')) {
+ onProgress({
+ progress:
+ Number.isFinite(durMs) && durMs > 0
+ ? Math.min(0.9999, outTimeUs / 1000 / durMs)
+ : null,
+ })
+ }
+ }
child.stdout?.on('data', (chunk: Buffer) => {
- const fields = parseProgressBlock(chunk.toString())
- const outTimeUs = fields.out_time_ms ?? 0
- const done = fields.progress === 'end'
- const progress = done
- ? 1
- : durMs > 0
- ? Math.min(0.999, outTimeUs / 1000 / durMs)
- : 0
- onProgress({ progress })
+ if (closed || this.aborted) return
+ const text = chunk.toString()
+ let start = 0
+ for (let index = 0; index < text.length; index++) {
+ if (text[index] !== '\n') continue
+ const part = text.slice(start, index)
+ if (!droppingLine && pending.length + part.length <= MAX_PROGRESS_LINE)
+ acceptLine(pending + part)
+ pending = ''
+ droppingLine = false
+ start = index + 1
+ }
+ if (!droppingLine) {
+ const tail = text.slice(start)
+ if (pending.length + tail.length <= MAX_PROGRESS_LINE) pending += tail
+ else {
+ pending = ''
+ droppingLine = true
+ }
+ }
})
return new Promise<void>((resolve, reject) => {
- child.on('error', (err) =>
+ child.on('error', (err) => {
+ closed = true
reject(new Error(`mux-failed: ${err.message}`))
- )
+ })
child.on('close', (code) => {
+ if (closed) return
+ closed = true
this.child = null
if (this.aborted) return reject(new Error('mux-aborted'))
- if (code === 0) return resolve()
+ if (code === 0) {
+ onProgress({ progress: 1 })
+ return resolve()
+ }
// Append the last few non-empty stderr lines — ffmpeg names the
// offending input/stream here. The message MUST still start with
// "mux-failed" (MediaTaskCoordinator.mapError matches that prefix to
@@ -140,22 +185,3 @@ export class FfmpegService {
this.child?.kill('SIGKILL')
}
}
-
-function parseProgressBlock(text: string): {
- out_time_ms?: number
- total_size?: number
- progress?: string
-} {
- const out: { out_time_ms?: number; total_size?: number; progress?: string } =
- {}
- for (const line of text.split(/\r?\n/)) {
- const eq = line.indexOf('=')
- if (eq < 0) continue
- const key = line.slice(0, eq)
- const val = line.slice(eq + 1)
- if (key === 'out_time_ms') out.out_time_ms = Number(val)
- else if (key === 'total_size') out.total_size = Number(val)
- else if (key === 'progress') out.progress = val
- }
- return out
-}
diff --git a/src/core/session/session-manager.test.ts b/src/core/session/session-manager.test.ts
index 349154bd..624575dd 100644
--- a/src/core/session/session-manager.test.ts
+++ b/src/core/session/session-manager.test.ts
@@ -14,6 +14,7 @@ import {
} from '@shared/types/task'
import type { TaskTerminalOccurrence } from '@shared/types/task-occurrence'
import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'
+import { makeMediaProgress } from '@test-utils/media-progress'
import { makeDownloadTask } from '@test-utils/task'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { Aria2RpcClient } from '../engine/aria2/aria2-rpc-client'
@@ -3297,6 +3298,33 @@ describe('SessionManager', () => {
expect(restored?.progress).toBe(1)
})
+ it('retains the bounded media checkpoint when restart interrupts a pipeline', async () => {
+ seedAsPair(db, {
+ motrixId: 'media-checkpoint',
+ gid: '',
+ kind: TaskKind.Hls,
+ status: TaskStatus.Downloading,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ })
+ const pair = db.getTask('media-checkpoint')!
+ pair.instances[0].phase = TaskInstancePhase.HlsSegment
+ pair.instances[0].payload.mediaProgress = makeMediaProgress()
+ db.saveTaskWithInstances(pair)
+ rpc.tellActive = vi.fn(async () => [])
+ rpc.tellStopped = vi.fn(async () => [])
+ await sessionManager.restore()
+ const restored = taskManager.getById('media-checkpoint')!
+ expect(restored.status).toBe(TaskStatus.Error)
+ expect(restored.progress).toBe(0.001)
+ expect(restored.mediaProgress?.download.completedParts).toBe(1)
+ expect(restored.totalBytes).toBe(0)
+ expect(adapter.createDownload).not.toHaveBeenCalled()
+ expect(
+ db.getTask('media-checkpoint')?.instances[0].payload.mediaProgress
+ ).toEqual(makeMediaProgress())
+ })
+
it('marks an in-progress media task Error on restart (cannot resume; not re-added)', async () => {
seedAsPair(db, {
motrixId: 'm-mux-live',
diff --git a/src/core/session/session-manager.ts b/src/core/session/session-manager.ts
index 7e54f946..54c97287 100644
--- a/src/core/session/session-manager.ts
+++ b/src/core/session/session-manager.ts
@@ -67,6 +67,7 @@ import {
type DirectResourceProxyOptionsProvider,
DirectResourceValidatorService,
} from '../task/direct-resource-validator'
+import { restoreMediaProgress } from '../task/media-task-progress'
import { isTempPath } from '../task/paths'
import { setTaskTransitionPhase } from '../task/task-instance'
import type { TaskManager } from '../task/task-manager'
@@ -1385,7 +1386,7 @@ export class SessionManager {
)
const retainedIdentity = newGid === primary?.gid
- return {
+ return restoreMediaProgress({
id: taskPart.motrixId,
engineTaskId: newGid,
name: taskPart.name,
@@ -1445,7 +1446,7 @@ export class SessionManager {
}
: inst
),
- }
+ })
}
private async reAddOrMarkErrorFromPair(
diff --git a/src/core/task/media-task-coordinator.test.ts b/src/core/task/media-task-coordinator.test.ts
index 9e46051c..f7ec6110 100644
--- a/src/core/task/media-task-coordinator.test.ts
+++ b/src/core/task/media-task-coordinator.test.ts
@@ -3,7 +3,13 @@ import type {
SegmentFileProgress,
SegmentProgress,
} from '@core/download/segment-downloader'
+import {
+ type SegmentAria2,
+ SegmentDownloader,
+} from '@core/download/segment-downloader'
+import type { SegmentPlan } from '@core/media/segment-plan'
import { Events } from '@shared/protocol/events'
+import { MediaProgressSchema } from '@shared/schemas/media-progress'
import type { DownloadTask } from '@shared/types/task'
import {
TaskInstancePhase,
@@ -11,6 +17,7 @@ import {
TaskStatus,
TransitionPhase,
} from '@shared/types/task'
+import { canPause } from '@shared/types/task-actions'
import { makeMediaMetaStoreStub } from '@test-utils/media-meta-store'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { MediaCoordinatorDeps, MediaJob } from './media-task-coordinator'
@@ -28,7 +35,7 @@ function makeDownloaderFake(opts?: {
partPaths?: string[]
hang?: boolean
/** Progress sequence to emit; defaults to a byte-less 0.5 → 1 fraction. */
- report?: SegmentProgress[]
+ report?: Omit<SegmentProgress, 'completedParts' | 'totalParts'>[]
fileReports?: SegmentFileProgress[]
/** Active segment gids this stream reports (Bug B). */
activeGids?: string[]
@@ -39,7 +46,7 @@ function makeDownloaderFake(opts?: {
const runFn = vi.fn(
async (
- _plan: unknown,
+ plan: SegmentPlan,
_headers: unknown,
onProgress: (p: SegmentProgress) => void,
onFileProgress?: (p: SegmentFileProgress) => void
@@ -61,7 +68,13 @@ function makeDownloaderFake(opts?: {
{ fraction: 0.5, downloadedBytes: 0, totalBytes: 0 },
{ fraction: 1, downloadedBytes: 0, totalBytes: 0 },
]
- for (const r of reports) onProgress(r)
+ const totalParts = plan.segments.length + (plan.init ? 1 : 0)
+ for (const r of reports)
+ onProgress({
+ ...r,
+ totalParts,
+ completedParts: Math.floor(r.fraction * totalParts),
+ })
return {
initPath: opts?.initPath,
partPaths: opts?.partPaths ?? ['/tmp/000001.seg'],
@@ -272,6 +285,170 @@ describe('MediaTaskCoordinator.start', () => {
await coordinator.stopAndDrain()
})
+ it.each(['video', 'audio'] as const)(
+ 'rejects an empty %s plan before creating a task or files',
+ async (stream) => {
+ const { deps, taskManager } = makeDeps()
+ const job = baseJob()
+ job[stream] = { ...job.video, segments: [] }
+ await expect(new MediaTaskCoordinator(deps).start(job)).rejects.toThrow(
+ 'Media plan has no segments'
+ )
+ expect(taskManager.getAll()).toHaveLength(0)
+ expect(deps.persist).not.toHaveBeenCalled()
+ expect(fs.promises.mkdir).not.toHaveBeenCalled()
+ }
+ )
+
+ it('uses the real downloader denominator across 1000 unstarted segments', async () => {
+ let complete!: (gid: string) => void
+ let poll!: () => void | Promise<void>
+ let nextGid = 0
+ const engine: SegmentAria2 = {
+ addUri: async () => `part-${++nextGid}`,
+ tellStatus: async () => ({ completedLength: 100, totalLength: 100 }),
+ forceRemove: async () => {},
+ removeDownloadResult: async () => {},
+ onComplete: (cb) => {
+ complete = cb
+ },
+ onError: () => {},
+ }
+ const { deps, taskManager } = makeDeps({
+ makeDownloader: (tmpDir) =>
+ new SegmentDownloader({
+ aria2: engine,
+ tmpDir,
+ concurrency: 1,
+ pollScheduler: (cb) => {
+ poll = cb
+ return () => {}
+ },
+ }),
+ })
+ const job = baseJob()
+ job.video.segments = Array.from({ length: 1000 }, (_, index) => ({
+ index,
+ url: `https://cdn/${index}.ts`,
+ }))
+ const coordinator = new MediaTaskCoordinator(deps)
+ const { taskId } = await coordinator.submit(job)
+ await vi.waitFor(() => expect(nextGid).toBe(1))
+ await poll()
+ let task = taskManager.getById(taskId)!
+ expect(task.progress).toBeLessThan(0.001)
+ expect(task.totalBytes).toBe(0)
+ complete('part-1')
+ complete('part-1') // Duplicate engine notifications must not double count.
+ await vi.waitFor(() =>
+ expect(
+ taskManager.getById(taskId)?.mediaProgress?.download.completedParts
+ ).toBe(1)
+ )
+ task = taskManager.getById(taskId)!
+ expect(task.progress).toBe(0.001)
+ expect(task.mediaProgress?.download).toEqual({
+ progress: 0.001,
+ completedParts: 1,
+ totalParts: 1000,
+ totalBytes: null,
+ })
+ expect(task.sizeWhenDone).toBe(0)
+ expect(task.etaSeconds).toBe(0)
+ expect(MediaProgressSchema.safeParse(task.mediaProgress).success).toBe(true)
+ await coordinator.stopAndDrain()
+ const cancelled = structuredClone(taskManager.getById(taskId))
+ complete('part-2')
+ await poll()
+ expect(taskManager.getById(taskId)).toEqual(cancelled)
+ })
+
+ it('weights unequal video/audio plans including both initialization segments', async () => {
+ const { deps, taskManager } = makeDeps({
+ makeDownloader: (dir) =>
+ makeDownloaderFake({ hang: dir.endsWith('audio') }) as never,
+ })
+ const job = baseJob()
+ job.video.init = { url: 'https://cdn/video-init' }
+ job.video.segments = [0, 1, 2].map((index) => ({
+ index,
+ url: `https://cdn/video-${index}`,
+ }))
+ job.audio = { ...baseJob().video, init: { url: 'https://cdn/audio-init' } }
+ const coordinator = new MediaTaskCoordinator(deps)
+ const { taskId } = await coordinator.submit(job)
+ await vi.waitFor(() =>
+ expect(
+ taskManager.getById(taskId)?.mediaProgress?.download.completedParts
+ ).toBe(4)
+ )
+ expect(taskManager.getById(taskId)?.mediaProgress?.download).toEqual({
+ progress: 4 / 6,
+ completedParts: 4,
+ totalParts: 6,
+ totalBytes: null,
+ })
+ await coordinator.stopAndDrain()
+ })
+
+ it('preserves completed downloads throughout mux and measures output after rename', async () => {
+ let muxTick!: (p: { progress: number | null }) => void
+ let finishMux!: () => void
+ const ffmpeg = {
+ run: vi.fn((_job: unknown, cb: typeof muxTick) => {
+ muxTick = cb
+ return new Promise<void>((resolve) => {
+ finishMux = resolve
+ })
+ }),
+ kill: vi.fn(),
+ buildArgs: () => [],
+ }
+ const stat = vi
+ .spyOn(fs.promises, 'stat')
+ .mockResolvedValue({ size: 999 } as fs.Stats)
+ const { deps, taskManager } = makeDeps({
+ makeFfmpeg: () => ffmpeg as never,
+ })
+ const snapshots: DownloadTask[] = []
+ deps.eventBus.emit = (_event, payload) => {
+ snapshots.push(...structuredClone(payload as DownloadTask[]))
+ }
+ const coordinator = new MediaTaskCoordinator(deps)
+ const run = coordinator.start(baseJob())
+ await vi.waitFor(() => expect(ffmpeg.run).toHaveBeenCalled())
+ muxTick({ progress: 0.42 })
+ let task = taskManager.getById('stable-task-id')!
+ expect(task.status).toBe(TaskStatus.Downloading)
+ expect(task.progress).toBe(1)
+ expect(task.mediaProgress?.muxProgress).toBe(0.42)
+ expect(task.mediaProgress?.outputBytes).toBeNull()
+ expect(canPause(task)).toBe(false)
+ muxTick({ progress: null })
+ expect(taskManager.getById(task.id)?.mediaProgress?.muxProgress).toBeNull()
+ finishMux()
+ await run
+ task = taskManager.getById(task.id)!
+ expect(task.status).toBe(TaskStatus.Completed)
+ expect(task.sizeWhenDone).toBe(999)
+ expect(task.mediaProgress?.outputBytes).toBe(999)
+ expect(stat).toHaveBeenCalledWith('/save/video.mp4')
+ expect(snapshots.map((t) => t.mediaProgress?.phase)).toEqual(
+ expect.arrayContaining([
+ 'preparing',
+ 'downloading',
+ 'assembling',
+ 'muxing',
+ 'renaming',
+ ])
+ )
+ expect(
+ snapshots
+ .filter((t) => t.mediaProgress?.phase === 'muxing')
+ .every((t) => t.progress === 1 && t.status === TaskStatus.Downloading)
+ ).toBe(true)
+ })
+
it('keeps a ten-thousand-segment task small enough for database snapshots', async () => {
const { deps, taskManager } = makeDeps({
makeDownloader: () => makeDownloaderFake({ hang: true }) as never,
@@ -284,7 +461,7 @@ describe('MediaTaskCoordinator.start', () => {
}))
const { taskId } = await coordinator.submit(job)
const task = taskManager.getById(taskId)
- expect(task?.instances[0].payload).toEqual({
+ expect(task?.instances[0].payload).toMatchObject({
mediaMetaPath: `/metadata/media/${taskId}/files.json`,
})
expect(JSON.stringify(task).length).toBeLessThan(4_000)
@@ -646,17 +823,35 @@ describe('MediaTaskCoordinator.start', () => {
expect(task?.errorMessage).toBe('mux-aborted')
})
- it.each(['metadata', 'ffmpeg-location'] as const)(
+ it.each(['metadata', 'decrypting', 'assembling', 'ffmpeg-location'] as const)(
'does not resume media work after cancellation during %s IO',
async (phase) => {
const gate = Promise.withResolvers<void>()
const entered = Promise.withResolvers<void>()
const { deps, taskManager, assembleFake, ffmpegFakes } = makeDeps()
+ const job = baseJob()
if (phase === 'metadata') {
vi.mocked(deps.mediaMetaStore.release).mockImplementation(async () => {
entered.resolve()
await gate.promise
})
+ } else if (phase === 'assembling') {
+ assembleFake.mockImplementation(async () => {
+ entered.resolve()
+ await gate.promise
+ })
+ } else if (phase === 'decrypting') {
+ job.video.segments[0].key = {
+ method: 'AES-128',
+ uri: 'https://cdn/key',
+ iv: new Uint8Array(16),
+ }
+ vi.spyOn(fs.promises, 'readFile').mockResolvedValue(Buffer.alloc(16))
+ vi.mocked(deps.decryptor.getKey).mockImplementation(async () => {
+ entered.resolve()
+ await gate.promise
+ return new Uint8Array(16)
+ })
} else {
vi.mocked(deps.resolveFfmpegBinaryPath).mockImplementation(async () => {
entered.resolve()
@@ -665,7 +860,7 @@ describe('MediaTaskCoordinator.start', () => {
})
}
const coordinator = new MediaTaskCoordinator(deps)
- const run = coordinator.start(baseJob()).catch((error) => error)
+ const run = coordinator.start(job).catch((error) => error)
await entered.promise
const cancel = coordinator.cancel('stable-task-id')
gate.resolve()
@@ -678,7 +873,8 @@ describe('MediaTaskCoordinator.start', () => {
ffmpegFakes.every((ffmpeg) => ffmpeg.run.mock.calls.length === 0)
).toBe(true)
expect(fs.promises.rename).not.toHaveBeenCalled()
- if (phase === 'metadata') expect(assembleFake).not.toHaveBeenCalled()
+ if (phase === 'metadata' || phase === 'decrypting')
+ expect(assembleFake).not.toHaveBeenCalled()
}
)
@@ -769,8 +965,7 @@ describe('MediaTaskCoordinator.start', () => {
).resolves.toBeUndefined()
await startPromise
- expect(persist).toHaveBeenCalledTimes(1)
- expect(snapshots).toEqual([
+ expect(snapshots.filter((s) => s.status === TaskStatus.Error)).toEqual([
{
status: TaskStatus.Error,
errorMessage: 'mux-aborted',
@@ -1029,7 +1224,8 @@ describe('MediaTaskCoordinator.start', () => {
expect(task?.status).toBe(TaskStatus.Completed)
// The UI reads sizeWhenDone (list "size" column + detail "Total size"), not
// totalBytes — the coordinator must mirror it or the size renders 0 B.
- expect(task?.sizeWhenDone).toBe(16)
+ expect(task?.sizeWhenDone).toBe(0)
+ expect(task?.mediaProgress?.outputBytes).toBeNull()
// A completed task has no segment in flight → 0 speed / 0 connections.
expect(task?.connections).toBe(0)
expect(task?.downloadSpeed).toBe(0)
@@ -1061,10 +1257,9 @@ describe('MediaTaskCoordinator.start', () => {
// The many progress updateTask calls (3 stream reports + ffmpeg ticks +
// instance-status tweaks) are coalesced away by the constant-clock throttle;
- // only forced status transitions (add, Downloading, Finalizing, Completed)
- // get through — far fewer than the un-throttled ~10.
+ // status and media phase transitions are forced through the throttle.
expect(snapshots.length).toBeGreaterThanOrEqual(2)
- expect(snapshots.length).toBeLessThanOrEqual(5)
+ expect(snapshots.length).toBeLessThanOrEqual(6)
// Terminal state was emitted despite the throttle.
expect(snapshots.at(-1)?.[0]?.status).toBe(TaskStatus.Completed)
})
@@ -1072,7 +1267,7 @@ describe('MediaTaskCoordinator.start', () => {
// Bug A follow-up: the UI reads the aria2-task display fields (sizeWhenDone,
// downloadSpeed, connections). A coordinator task must populate them during
// download too, or the detail panel shows 0 B / 0 B/s / 0 connections.
- it('populates sizeWhenDone + connections + downloadSpeed during the download phase', async () => {
+ it('reports transfer metrics without presenting input bytes as output size', async () => {
let clock = 0
const now = () => {
clock += 1000 // advance 1s per read so the speed sampler has a delta
@@ -1091,11 +1286,15 @@ describe('MediaTaskCoordinator.start', () => {
) => {
onProgress({
fraction: 0.25,
+ completedParts: 0,
+ totalParts: 1,
downloadedBytes: 1_000_000,
totalBytes: 4_000_000,
})
onProgress({
fraction: 0.5,
+ completedParts: 0,
+ totalParts: 1,
downloadedBytes: 2_000_000,
totalBytes: 4_000_000,
})
@@ -1117,7 +1316,8 @@ describe('MediaTaskCoordinator.start', () => {
await new Promise((r) => setTimeout(r, 10))
const task = taskManager.getById('ui-live')
- expect(task?.sizeWhenDone).toBe(4_000_000) // == totalBytes, not 0 B
+ expect(task?.sizeWhenDone).toBe(0)
+ expect(task?.totalBytes).toBe(4_000_000)
expect(task?.connections).toBe(2) // two segment gids in flight
expect(task?.downloadSpeed).toBeGreaterThan(0)
@@ -1455,14 +1655,13 @@ describe('MediaTaskCoordinator .motrix placeholder contract', () => {
const { deps } = makeDeps({ persist })
await new MediaTaskCoordinator(deps).start(baseJob())
- expect(persist).toHaveBeenCalledTimes(2)
- expect(persisted[0]).toEqual({
+ expect(persisted.at(-2)).toEqual({
status: TaskStatus.Finalizing,
diskPath: TEMP,
instancePhases: [TransitionPhase.Renaming, TransitionPhase.Renaming],
instanceStatuses: [TaskStatus.Downloading, TaskStatus.Downloading],
})
- expect(persisted[1]).toEqual({
+ expect(persisted.at(-1)).toEqual({
status: TaskStatus.Completed,
diskPath: FINAL,
instancePhases: [TransitionPhase.Idle, TransitionPhase.Idle],
@@ -1496,6 +1695,8 @@ describe('MediaTaskCoordinator .motrix placeholder contract', () => {
expect(persistedStatuses).toEqual([
TaskStatus.Queued,
TaskStatus.Downloading,
+ TaskStatus.Downloading, // assembling
+ TaskStatus.Downloading, // muxing
TaskStatus.Finalizing,
TaskStatus.Completed,
])
@@ -1611,15 +1812,14 @@ describe('MediaTaskCoordinator .motrix placeholder contract', () => {
Number.POSITIVE_INFINITY
)
expect(recordDownloadCompleted.mock.invocationCallOrder[0]).toBeLessThan(
- persist.mock.invocationCallOrder[1] ?? Number.POSITIVE_INFINITY
+ persist.mock.invocationCallOrder.at(-1) ?? Number.POSITIVE_INFINITY
)
})
it('a failing post-rename persist hook does not fail the completed task', async () => {
- const persist = vi
- .fn<(task: DownloadTask) => Promise<void>>()
- .mockResolvedValueOnce(undefined)
- .mockRejectedValueOnce(new Error('db locked'))
+ const persist = vi.fn(async (task: DownloadTask) => {
+ if (task.status === TaskStatus.Completed) throw new Error('db locked')
+ })
const { deps, taskManager } = makeDeps({ persist })
await new MediaTaskCoordinator(deps).start(baseJob())
@@ -1632,10 +1832,8 @@ describe('MediaTaskCoordinator .motrix placeholder contract', () => {
// The type promises Promise<void>, but a sync throw before the promise
// exists would land in start()'s outer catch and flip an already-renamed,
// Completed task to Error — guard against convention violations.
- let calls = 0
- const persist = vi.fn(() => {
- calls += 1
- if (calls === 1) return Promise.resolve()
+ const persist = vi.fn((task: DownloadTask) => {
+ if (task.status !== TaskStatus.Completed) return Promise.resolve()
throw new Error('sync boom')
}) as MediaCoordinatorDeps['persist']
const { deps, taskManager } = makeDeps({ persist })
@@ -1715,8 +1913,7 @@ describe('MediaTaskCoordinator .motrix placeholder contract', () => {
new MediaTaskCoordinator(deps).start(baseJob())
).rejects.toThrow('mux-failed: original ffmpeg failure')
- expect(persist).toHaveBeenCalledTimes(1)
- expect(snapshots).toEqual([
+ expect(snapshots.filter((s) => s.status === TaskStatus.Error)).toEqual([
{
status: TaskStatus.Error,
errorMessage: 'mux-failed',
diff --git a/src/core/task/media-task-coordinator.ts b/src/core/task/media-task-coordinator.ts
index 801867fb..b348772e 100644
--- a/src/core/task/media-task-coordinator.ts
+++ b/src/core/task/media-task-coordinator.ts
@@ -15,6 +15,7 @@ import { getLogger } from '@core/logger'
import type { assembleSegments } from '@core/media/segment-assembler'
import type { SegmentDecryptor } from '@core/media/segment-decryptor'
import type { SegmentPlan } from '@core/media/segment-plan'
+import type { MediaPhase } from '@shared/schemas/media-progress'
import type { SourceMeta } from '@shared/types/task'
import {
type DownloadTask,
@@ -28,6 +29,7 @@ import {
} from '@shared/types/task'
import type { TaskActivityRecorder } from '@shared/types/task-activity'
import type { TaskOccurrence } from '@shared/types/task-occurrence'
+import { finiteProgress } from '@shared/utils/media-progress'
import {
buildTerminalOccurrence,
persistWithOccurrenceOrWarn,
@@ -37,6 +39,7 @@ import {
import { applyTerminalTransition } from './apply-terminal-transition'
import type { CreateRequestReceipt } from './create-request-id'
import type { MediaManifest, MediaMetaStore } from './media-meta-store'
+import { setMediaProgress } from './media-task-progress'
import type { OccurrenceDispatcher } from './occurrences/occurrence-dispatcher'
import { toTempPath } from './paths'
import { admitHttpSource } from './source-admission'
@@ -255,6 +258,24 @@ export class MediaTaskCoordinator {
video: admitPlan(job.video),
audio: job.audio ? admitPlan(job.audio) : undefined,
}
+ if (job.video.segments.length === 0 || job.audio?.segments.length === 0) {
+ throw new Error('Media plan has no segments')
+ }
+ const countParts = (plan: SegmentPlan) =>
+ plan.segments.length + (plan.init ? 1 : 0)
+ const videoTotal = countParts(job.video)
+ const audioTotal = job.audio ? countParts(job.audio) : 0
+ const grandTotal = videoTotal + audioTotal
+ const declaredSize = (plan: SegmentPlan): number => {
+ const parts = plan.init ? [plan.init, ...plan.segments] : plan.segments
+ return parts.every(
+ (part) =>
+ Number.isFinite(part.byteRange?.length) &&
+ (part.byteRange?.length ?? 0) > 0
+ )
+ ? parts.reduce((sum, part) => sum + (part.byteRange?.length ?? 0), 0)
+ : 0
+ }
const now = Date.now()
// Reserve the final name by creating the `.motrix` placeholder in saveDir —
@@ -358,6 +379,23 @@ export class MediaTaskCoordinator {
instances,
now
)
+ const initialVideoBytes = declaredSize(job.video)
+ const initialAudioBytes = job.audio ? declaredSize(job.audio) : 0
+ setMediaProgress(task, {
+ version: 1,
+ phase: 'preparing',
+ download: {
+ progress: 0,
+ completedParts: 0,
+ totalParts: grandTotal,
+ totalBytes:
+ initialVideoBytes > 0 && (!job.audio || initialAudioBytes > 0)
+ ? initialVideoBytes + initialAudioBytes
+ : null,
+ },
+ muxProgress: null,
+ outputBytes: null,
+ })
// Prepare task-owned IO before publication. Once visible, every task must
// already have cancellation ownership; a failed temp-directory setup must
// not leave a durable queued task or metadata without a runnable pipeline.
@@ -417,6 +455,26 @@ export class MediaTaskCoordinator {
}
}
+ const changePhase = async (phase: MediaPhase) => {
+ assertActive()
+ this.updateTask(taskId, (t) => {
+ if (!t.mediaProgress) return
+ setMediaProgress(t, { ...t.mediaProgress, phase })
+ t.downloadSpeed = 0
+ t.etaSeconds = 0
+ t.connections = 0
+ if (phase === 'muxing') {
+ setInstanceStatus(
+ t.instances,
+ TaskInstancePhase.FfmpegMux,
+ TaskStatus.Downloading
+ )
+ }
+ })
+ await this.persistBestEffort(taskId, 'phase')
+ assertActive()
+ }
+
try {
assertActive()
// -----------------------------------------------------------------------
@@ -430,6 +488,8 @@ export class MediaTaskCoordinator {
// empty downloader list and the segment run would start uncancellable.
const toDownloading = (t: DownloadTask): void => {
t.status = TaskStatus.Downloading
+ if (t.mediaProgress)
+ setMediaProgress(t, { ...t.mediaProgress, phase: 'downloading' })
setInstanceStatus(
t.instances,
TaskInstancePhase.HlsSegment,
@@ -443,24 +503,19 @@ export class MediaTaskCoordinator {
}
assertActive()
- // Total segment count across video + audio — the fallback for aggregate
- // progress when byte counts are not yet known (e.g. before the first
- // poll, or if aria2 reports no lengths).
- const videoTotal = (job.video.init ? 1 : 0) + job.video.segments.length
- const audioTotal = job.audio
- ? (job.audio.init ? 1 : 0) + job.audio.segments.length
- : 0
- const grandTotal = videoTotal + audioTotal
-
- // Live per-stream state, updated by each downloader's progress callback.
- // The two streams download CONCURRENTLY (see below), so both totals are
- // known once each stream has been polled once — the task's totalBytes is
- // correct up front and the bar climbs smoothly end-to-end, instead of the
- // total growing (and progress jumping back) when audio starts under a
- // sequential model. `completed` is the per-stream segment count feeding
- // the fraction fallback; `downloaded`/`total` are bytes.
- const videoBytes = { downloaded: 0, total: 0, completed: 0 }
- const audioBytes = { downloaded: 0, total: 0, completed: 0 }
+ // The plan denominator is fixed, including streams not yet polled.
+ const videoBytes = {
+ downloaded: 0,
+ total: initialVideoBytes,
+ completed: 0,
+ fraction: 0,
+ }
+ const audioBytes = {
+ downloaded: 0,
+ total: initialAudioBytes,
+ completed: 0,
+ fraction: 0,
+ }
// Download-speed sampler: bytes/s from the downloaded delta over a ≥0.5s
// window (the two stream callbacks interleave, so a coarse window avoids
@@ -469,26 +524,35 @@ export class MediaTaskCoordinator {
let speedSampleTime = clock()
let speedSampleBytes = 0
- // Derive real byte progress; fall back to the segment-count fraction only
- // while totalBytes is still 0 (never NaN, never a shrinking total). Also
- // populate the aria2-task display fields the UI reads — sizeWhenDone (the
- // list "size" column + detail "Total size"), connections, downloadSpeed,
- // etaSeconds — which a coordinator task would otherwise leave at 0.
+ // Bytes describe transfer volume; only the complete plan can supply a
+ // byte denominator. Main progress always uses all planned segments.
const applyBytes = (t: DownloadTask) => {
const downloadedBytes = videoBytes.downloaded + audioBytes.downloaded
- const totalBytes = videoBytes.total + audioBytes.total
+ const totalBytes =
+ videoBytes.total > 0 && (!job.audio || audioBytes.total > 0)
+ ? videoBytes.total + audioBytes.total
+ : 0
const overallFrac =
grandTotal > 0
- ? (videoBytes.completed + audioBytes.completed) / grandTotal
+ ? (videoBytes.fraction * videoTotal +
+ audioBytes.fraction * audioTotal) /
+ grandTotal
: 0
const connections = state.downloaders.reduce(
(n, d) => n + d.getActiveGidCount(),
0
)
t.downloadedBytes = downloadedBytes
- t.totalBytes = totalBytes
- t.sizeWhenDone = totalBytes
- t.progress = totalBytes > 0 ? downloadedBytes / totalBytes : overallFrac
+ if (t.mediaProgress)
+ setMediaProgress(t, {
+ ...t.mediaProgress,
+ download: {
+ progress: overallFrac,
+ completedParts: videoBytes.completed + audioBytes.completed,
+ totalParts: grandTotal,
+ totalBytes: totalBytes > 0 ? totalBytes : null,
+ },
+ })
t.connections = connections
if (connections === 0) {
@@ -507,8 +571,11 @@ export class MediaTaskCoordinator {
speedSampleBytes = downloadedBytes
}
t.etaSeconds =
- t.downloadSpeed > 0
- ? Math.round((totalBytes - downloadedBytes) / t.downloadSpeed)
+ totalBytes > 0 && t.downloadSpeed > 0
+ ? Math.max(
+ 0,
+ Math.round((totalBytes - downloadedBytes) / t.downloadSpeed)
+ )
: 0
}
@@ -516,16 +583,22 @@ export class MediaTaskCoordinator {
// state it writes and which instance phase it advances.
const onStreamProgress =
(
- streamBytes: { downloaded: number; total: number; completed: number },
- phase: TaskInstancePhase,
- segTotal: number
+ streamBytes: {
+ downloaded: number
+ total: number
+ completed: number
+ fraction: number
+ },
+ phase: TaskInstancePhase
) =>
(p: SegmentProgress) => {
- if (state.cancelled) return
+ if (state.cancelled || !this.running.has(taskId)) return
streamBytes.downloaded = p.downloadedBytes
streamBytes.total = p.totalBytes
- streamBytes.completed = Math.round(p.fraction * segTotal)
+ streamBytes.completed = p.completedParts
+ streamBytes.fraction = p.fraction
this.updateTask(taskId, (t) => {
+ if (t.mediaProgress?.phase !== 'downloading') return
setInstanceProgress(t.instances, phase, p.fraction)
applyBytes(t)
})
@@ -565,7 +638,7 @@ export class MediaTaskCoordinator {
const runVideo = videoDownloader.run(
job.video,
job.headers,
- onStreamProgress(videoBytes, TaskInstancePhase.HlsSegment, videoTotal),
+ onStreamProgress(videoBytes, TaskInstancePhase.HlsSegment),
onFileProgress('video')
)
@@ -577,11 +650,7 @@ export class MediaTaskCoordinator {
? audioDownloader.run(
audioPlan,
job.headers,
- onStreamProgress(
- audioBytes,
- TaskInstancePhase.HlsAudio,
- audioTotal
- ),
+ onStreamProgress(audioBytes, TaskInstancePhase.HlsAudio),
onFileProgress('audio')
)
: Promise.resolve(null)
@@ -595,6 +664,14 @@ export class MediaTaskCoordinator {
// -----------------------------------------------------------------------
// Phase: decrypt
// -----------------------------------------------------------------------
+ if (
+ [job.video, job.audio].some(
+ (plan) =>
+ plan && (plan.init?.key || plan.segments.some((part) => part.key))
+ )
+ ) {
+ await changePhase('decrypting')
+ }
await decryptPlan(job.video, videoResult, this.deps.decryptor)
assertActive()
if (job.audio && audioResult) {
@@ -609,6 +686,7 @@ export class MediaTaskCoordinator {
// (bilibili/DASH fragmented-MP4) are MP4-family — use .mp4 so the
// extension matches the content (ffmpeg also probes, but the hint should
// not lie).
+ await changePhase('assembling')
const ext = job.video.container === 'mpegts' ? 'ts' : 'mp4'
const videoAssembled = path.join(tmpDir, `video.${ext}`)
await this.deps.assemble({
@@ -633,15 +711,7 @@ export class MediaTaskCoordinator {
// -----------------------------------------------------------------------
// Phase: muxing
// -----------------------------------------------------------------------
- this.updateTask(taskId, (t) => {
- t.progress = 0
- t.status = TaskStatus.Downloading // keep as Downloading until mux done
- setInstanceStatus(
- t.instances,
- TaskInstancePhase.FfmpegMux,
- TaskStatus.Downloading
- )
- })
+ await changePhase('muxing')
// saveDir was already created at reservation time; re-ensure it here in
// case the user deleted it during a long download — ffmpeg does NOT
@@ -687,12 +757,22 @@ export class MediaTaskCoordinator {
durationSec: job.durationSec,
},
(p) => {
+ if (state.cancelled) return
this.updateTask(taskId, (t) => {
- t.progress = p.progress
+ if (
+ t.status !== TaskStatus.Downloading ||
+ t.mediaProgress?.phase !== 'muxing'
+ )
+ return
+ const progress =
+ p.progress === null
+ ? null
+ : Math.min(0.9999, finiteProgress(p.progress))
+ setMediaProgress(t, { ...t.mediaProgress, muxProgress: progress })
setInstanceProgress(
t.instances,
TaskInstancePhase.FfmpegMux,
- p.progress
+ progress ?? 0
)
})
}
@@ -707,7 +787,12 @@ export class MediaTaskCoordinator {
await this.transition(
taskId,
(t) => {
- t.progress = 1
+ if (t.mediaProgress)
+ setMediaProgress(t, {
+ ...t.mediaProgress,
+ phase: 'renaming',
+ muxProgress: 1,
+ })
assertActive()
Object.assign(t, applyTerminalTransition(t, TaskStatus.Finalizing))
setTaskTransitionPhase(t, TransitionPhase.Renaming)
@@ -722,11 +807,21 @@ export class MediaTaskCoordinator {
assertActive()
await fs.promises.rename(diskPath, finalPath)
assertActive()
+ const outputBytes = await fs.promises
+ .stat(finalPath)
+ .then((stat) => stat.size)
+ .catch((err) => {
+ log.warn({ err, taskId }, 'Final media size unavailable')
+ return null
+ })
+ assertActive()
const completedAt = this.now()
await this.transition(
taskId,
(t) => {
+ if (t.mediaProgress)
+ setMediaProgress(t, { ...t.mediaProgress, outputBytes })
t.progress = 1
completeTaskAfterRename(
t,
@@ -867,6 +962,7 @@ export class MediaTaskCoordinator {
const task = this.deps.taskManager.getById(taskId)
if (!task) return
const prevStatus = task.status
+ const prevPhase = task.mediaProgress?.phase
mut(task)
task.updatedAt = Date.now()
this.deps.taskManager.set(taskId, task)
@@ -874,12 +970,14 @@ export class MediaTaskCoordinator {
// terminal Completed/Error must never be dropped by the throttle (bridge
// consumers derive terminal notifications from the status in the payload).
// Pure byte-progress updates are throttled.
- this.emitUpdate(task.status !== prevStatus)
+ this.emitUpdate(
+ task.status !== prevStatus || task.mediaProgress?.phase !== prevPhase
+ )
}
private async persistBestEffort(
taskId: string,
- context: 'completion' | 'failure' | 'cancellation'
+ context: 'completion' | 'failure' | 'cancellation' | 'phase'
): Promise<void> {
const task = this.deps.taskManager.getById(taskId)
if (!task) return
diff --git a/src/core/task/media-task-files.ts b/src/core/task/media-task-files.ts
index 55986639..ebdb0e6b 100644
--- a/src/core/task/media-task-files.ts
+++ b/src/core/task/media-task-files.ts
@@ -5,6 +5,7 @@ import {
type TaskFile,
TaskInstancePhase,
} from '@shared/types/task'
+import { segmentFraction } from '@shared/utils/media-progress'
import { z } from 'zod'
// Display metadata only; source manifests live in the central media store.
@@ -47,11 +48,7 @@ export function updateMediaTaskFile(
...file,
size,
completedBytes: update.completed ? size : update.downloadedBytes,
- progress: update.completed
- ? 1
- : size > 0
- ? Math.min(update.downloadedBytes / size, 1)
- : 0,
+ progress: segmentFraction(update.downloadedBytes, size, update.completed),
} satisfies MediaFile
}
diff --git a/src/core/task/media-task-progress.ts b/src/core/task/media-task-progress.ts
new file mode 100644
index 00000000..96631d79
--- /dev/null
+++ b/src/core/task/media-task-progress.ts
@@ -0,0 +1,44 @@
+import {
+ MediaProgressSchema,
+ type MediaProgressSnapshot,
+} from '@shared/schemas/media-progress'
+import {
+ type DownloadTask,
+ TaskInstancePhase,
+ TaskStatus,
+} from '@shared/types/task'
+import { isMediaTask } from '@shared/utils/media-progress'
+
+export function setMediaProgress(
+ task: DownloadTask,
+ snapshot: MediaProgressSnapshot
+): void {
+ task.mediaProgress = snapshot
+ task.progress = snapshot.download.progress
+ task.totalBytes = snapshot.download.totalBytes ?? 0
+ task.sizeWhenDone = snapshot.outputBytes ?? 0
+ const instance = task.instances.find(
+ (i) => i.phase === TaskInstancePhase.HlsSegment
+ )
+ if (instance)
+ instance.payload = { ...instance.payload, mediaProgress: snapshot }
+}
+
+/** Restore only the bounded summary, without reading every segment file. */
+export function restoreMediaProgress(task: DownloadTask): DownloadTask {
+ if (!isMediaTask(task)) return task
+ const payload = task.instances.find(
+ (i) => i.phase === TaskInstancePhase.HlsSegment
+ )?.payload.mediaProgress
+ const parsed = MediaProgressSchema.safeParse(payload)
+ if (parsed.success) {
+ setMediaProgress(task, parsed.data)
+ } else {
+ task.mediaProgress = undefined
+ task.progress = 0
+ task.totalBytes = 0
+ task.sizeWhenDone = 0
+ }
+ if (task.status === TaskStatus.Completed) task.progress = 1
+ return task
+}
diff --git a/src/core/task/task-row-to-download-task.test.ts b/src/core/task/task-row-to-download-task.test.ts
index c37a13f8..0d5f0b16 100644
--- a/src/core/task/task-row-to-download-task.test.ts
+++ b/src/core/task/task-row-to-download-task.test.ts
@@ -8,6 +8,7 @@ import {
TransitionPhase,
} from '@shared/types/task'
import { createBtStoragePlan } from '@test-utils/legacy-bt-storage'
+import { makeMediaProgress } from '@test-utils/media-progress'
import { describe, expect, it } from 'vitest'
import { btStoragePayload } from './bt-storage-layout'
import { taskRowToDownloadTask } from './task-row-to-download-task'
@@ -70,6 +71,48 @@ function makeInstance(phase: TaskInstancePhase): TaskInstanceRow {
}
describe('taskRowToDownloadTask', () => {
+ it('restores media progress from the phase payload even when instance order differs', () => {
+ const primary = makeInstance(TaskInstancePhase.HlsSegment)
+ primary.payload.mediaProgress = makeMediaProgress()
+ const task = taskRowToDownloadTask(
+ makeTaskRow({
+ kind: TaskKind.Hls,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ }),
+ [makeInstance(TaskInstancePhase.FfmpegMux), primary]
+ )
+ expect(task.progress).toBe(0.001)
+ expect(task.totalBytes).toBe(0)
+ expect(task.sizeWhenDone).toBe(0)
+ expect(task.mediaProgress?.download.completedParts).toBe(1)
+ })
+
+ it.each([
+ undefined,
+ { version: 2 },
+ { version: 1, download: { progress: 1 } },
+ ])(
+ 'does not restore false 100 percent from legacy/corrupt media bytes: %s',
+ (mediaProgress) => {
+ const primary = makeInstance(TaskInstancePhase.HlsSegment)
+ primary.payload.mediaProgress = mediaProgress
+ const task = taskRowToDownloadTask(
+ makeTaskRow({
+ kind: TaskKind.Hls,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ sizeWhenDone: 100,
+ }),
+ [primary]
+ )
+ expect(task.mediaProgress).toBeUndefined()
+ expect(task.progress).toBe(0)
+ expect(task.totalBytes).toBe(0)
+ expect(task.sizeWhenDone).toBe(0)
+ }
+ )
+
it.each([
['g1', 25, 125],
['reseed-gid', 10, 135],
diff --git a/src/core/task/task-row-to-download-task.ts b/src/core/task/task-row-to-download-task.ts
index e54adab5..abd89ed4 100644
--- a/src/core/task/task-row-to-download-task.ts
+++ b/src/core/task/task-row-to-download-task.ts
@@ -8,6 +8,7 @@ import {
import { isTorrentLikeType } from '@shared/types/task-actions'
import { shareRatio } from '@shared/utils/share-ratio'
import { unsettledBtUpload } from './bt-upload-settlement'
+import { restoreMediaProgress } from './media-task-progress'
import { restoreTaskSaveDirectory } from './task-save-directory'
/** Build a generic DownloadTask domain object from canonical TaskRow data.
@@ -43,7 +44,7 @@ export function taskRowToDownloadTask(
})
: undefined
- return {
+ return restoreMediaProgress({
id: task.motrixId,
engineTaskId: primary?.gid ?? '',
name: task.name,
@@ -88,5 +89,5 @@ export function taskRowToDownloadTask(
torrentMetaPath: task.torrentMetaPath,
bt,
instances: instances.map((i) => ({ ...i })),
- }
+ })
}
diff --git a/src/renderer/components/ui/progress.tsx b/src/renderer/components/ui/progress.tsx
index fd53afe6..88ddfd30 100644
--- a/src/renderer/components/ui/progress.tsx
+++ b/src/renderer/components/ui/progress.tsx
@@ -4,9 +4,15 @@ import { cn } from '@renderer/lib/utils'
export interface ProgressProps
extends Omit<ProgressPrimitive.Root.Props, 'value'> {
value?: number
+ indicatorClassName?: string
}
-export function Progress({ className, value, ...props }: ProgressProps) {
+export function Progress({
+ className,
+ value,
+ indicatorClassName,
+ ...props
+}: ProgressProps) {
return (
<ProgressPrimitive.Root
data-slot="progress"
@@ -18,7 +24,13 @@ export function Progress({ className, value, ...props }: ProgressProps) {
{...props}
>
<ProgressPrimitive.Track className="size-full">
- <ProgressPrimitive.Indicator className="h-full bg-primary transition-all" />
+ <ProgressPrimitive.Indicator
+ className={cn(
+ 'h-full bg-primary transition-all motion-reduce:transition-none',
+ value == null && 'w-1/3 animate-pulse motion-reduce:animate-none',
+ indicatorClassName
+ )}
+ />
</ProgressPrimitive.Track>
</ProgressPrimitive.Root>
)
diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
index edcecb27..96d0a309 100644
--- a/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.test.tsx
@@ -1,9 +1,11 @@
+import { makeMediaProgress } from '@test-utils/media-progress'
import '@testing-library/jest-dom/vitest'
import { i18n } from '@renderer/lib/i18n'
import { DownloadErrorCode } from '@shared/errors'
import {
type BtExtension,
type DownloadTask,
+ TaskKind,
TaskStatus,
TaskType,
} from '@shared/types/task'
@@ -210,6 +212,32 @@ describe('TasksTile', () => {
vi.useRealTimers()
})
+ it('projects media stages and indeterminate mux duration without a stale ETA', () => {
+ setSource([
+ task('video', TaskStatus.Downloading, {
+ kind: TaskKind.Hls,
+ progress: 1,
+ mediaProgress: makeMediaProgress({
+ phase: 'muxing',
+ download: {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ }),
+ }),
+ ])
+ renderTile()
+ expect(
+ screen.getByRole('button', { name: 'video.iso, Merging' })
+ ).toBeInTheDocument()
+ expect(
+ screen.getByRole('progressbar', { name: 'video.iso progress: Merging' })
+ ).not.toHaveAttribute('aria-valuenow')
+ expect(screen.queryByText(/ETA/)).not.toBeInTheDocument()
+ })
+
it('exposes a three-option radio control with Active selected', () => {
renderTile()
diff --git a/src/renderer/routes/dashboard/tiles/tasks-tile.tsx b/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
index 9046091d..defd34db 100644
--- a/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
+++ b/src/renderer/routes/dashboard/tiles/tasks-tile.tsx
@@ -5,7 +5,6 @@ import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { useMinuteClock } from '@renderer/hooks/use-minute-clock'
import { useTaskList } from '@renderer/hooks/use-task-list'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
-
import { openAddTaskDialog } from '@renderer/lib/open-add-task-dialog'
import { formatRelativeTime } from '@renderer/lib/relative-time'
import { TASK_TYPE_META } from '@renderer/lib/task-type-meta'
@@ -13,6 +12,15 @@ import { projectTaskWindow, type TaskView } from '@renderer/lib/task-views'
import { cn } from '@renderer/lib/utils'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
+import {
+ getDownloadProgress,
+ getMediaPhaseLabel,
+ getOutputSize,
+ getStageProgress,
+ getTransferMetrics,
+ isMediaTask,
+ mediaProgressPercent,
+} from '@shared/utils/media-progress'
import { useCallback, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate, useSearchParams } from 'react-router'
@@ -59,6 +67,7 @@ interface RowPresentation {
primary: string
secondary: string
progress: number | null
+ indeterminate?: boolean
}
function spanKey(viewport: DashboardTileViewport): string {
@@ -168,7 +177,8 @@ function TaskRow({
const { t, i18n } = useTranslation()
const descriptionId = useId()
const buttonRef = useRef<HTMLButtonElement | null>(null)
- const statusLabel = taskStatusLabel(task.status, t)
+ const phase = getMediaPhaseLabel(task)
+ const statusLabel = phase ? t(phase) : taskStatusLabel(task.status, t)
let technicalDetail: string | null = null
let presentation: RowPresentation
@@ -195,15 +205,55 @@ function TaskRow({
progress: null,
}
} else if (view === 'recent') {
- const finalSize =
- task.sizeWhenDone > 0 ? task.sizeWhenDone : task.totalBytes
+ const finalSize = isMediaTask(task)
+ ? getOutputSize(task)
+ : task.sizeWhenDone > 0
+ ? task.sizeWhenDone
+ : task.totalBytes
presentation = {
- primary: formatBytes(finalSize),
+ primary: finalSize === null ? '—' : formatBytes(finalSize),
secondary: t('panel.dashboard.tasks.secondary.completed', {
time: formatRelativeTime(terminalDisplayTime(task), now, i18n.language),
}),
progress: null,
}
+ } else if (
+ isMediaTask(task) &&
+ (task.status === TaskStatus.Downloading ||
+ task.status === TaskStatus.Finalizing ||
+ task.status === TaskStatus.Queued)
+ ) {
+ const progress = getStageProgress(task)
+ const transfer = getTransferMetrics(task)
+ const downloading = task.mediaProgress?.phase === 'downloading'
+ presentation = {
+ primary:
+ downloading && engineOnline
+ ? formatSpeed(transfer.speedBps)
+ : statusLabel,
+ secondary: !engineOnline
+ ? t('panel.dashboard.tasks.secondary.offline')
+ : [
+ progress === null
+ ? statusLabel
+ : `${statusLabel} ${mediaProgressPercent(progress)}%`,
+ task.mediaProgress
+ ? t('panel.downloads.media.partsFormat', {
+ completed: task.mediaProgress.download.completedParts,
+ total: task.mediaProgress.download.totalParts,
+ })
+ : null,
+ downloading && transfer.etaSec !== null
+ ? t('panel.dashboard.tasks.secondary.eta', {
+ time: formatEta(transfer.etaSec, i18n.language),
+ })
+ : null,
+ ]
+ .filter(Boolean)
+ .join(' · '),
+ progress: progress === null ? null : mediaProgressPercent(progress),
+ indeterminate: progress === null,
+ }
} else {
switch (task.status) {
case TaskStatus.Downloading:
@@ -271,7 +321,12 @@ function TaskRow({
primary: t('panel.dashboard.tasks.metric.paused'),
secondary: engineOnline
? t('panel.dashboard.tasks.secondary.saved', {
- percent: Math.round(clampProgress(task.progress)),
+ percent:
+ getDownloadProgress(task) === null
+ ? '—'
+ : isMediaTask(task)
+ ? mediaProgressPercent(getDownloadProgress(task) ?? 0)
+ : Math.round(clampProgress(task.progress)),
})
: t('panel.dashboard.tasks.secondary.offline'),
progress: null,
@@ -348,7 +403,8 @@ function TaskRow({
className={cn(
'pointer-events-none relative z-10 grid h-full min-w-0 grid-cols-[14px_minmax(0,1fr)_auto] grid-rows-2 items-center gap-x-2 px-1',
verticalPaddingClass,
- presentation.progress !== null && 'pb-1.5'
+ (presentation.progress !== null || presentation.indeterminate) &&
+ 'pb-1.5'
)}
>
<Icon className="row-span-2 size-3.5 text-muted-foreground" />
@@ -368,12 +424,14 @@ function TaskRow({
{accessibleDescription}
</span>
- {!summary && presentation.progress !== null ? (
+ {!summary &&
+ (presentation.progress !== null || presentation.indeterminate) ? (
<Progress
- value={presentation.progress}
- aria-label={t('panel.dashboard.tasks.progressLabel', {
- name: task.name,
- })}
+ value={presentation.progress ?? undefined}
+ aria-label={
+ t('panel.dashboard.tasks.progressLabel', { name: task.name }) +
+ (phase ? `: ${statusLabel}` : '')
+ }
className="pointer-events-none absolute right-1 bottom-0.5 left-[26px] z-10 h-0.5 w-auto rounded-full"
/>
) : null}
diff --git a/src/renderer/routes/downloads/inspector/files-tab.tsx b/src/renderer/routes/downloads/inspector/files-tab.tsx
index a612b954..c051e12f 100644
--- a/src/renderer/routes/downloads/inspector/files-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/files-tab.tsx
@@ -7,6 +7,7 @@ import { transport } from '@renderer/lib/transport'
import { Commands } from '@shared/protocol/commands'
import type { DownloadTask, TaskFile } from '@shared/types/task'
import { TaskKind, TaskStatus, TaskType } from '@shared/types/task'
+import { mediaProgressPercent } from '@shared/utils/media-progress'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
@@ -77,7 +78,7 @@ export function FilesTab({ task }: { task: DownloadTask }) {
renderRowTrailing={(f) =>
isActive || isMedia ? (
<span className="shrink-0 text-xs tabular-nums text-muted-foreground">
- {formatProgressPercent(
+ {(isMedia ? mediaProgressPercent : formatProgressPercent)(
f.progress ??
(files.length === 1 && !isMedia
? task.progress
diff --git a/src/renderer/routes/downloads/inspector/multi-selection-summary.test.tsx b/src/renderer/routes/downloads/inspector/multi-selection-summary.test.tsx
index 94322c93..db827a6f 100644
--- a/src/renderer/routes/downloads/inspector/multi-selection-summary.test.tsx
+++ b/src/renderer/routes/downloads/inspector/multi-selection-summary.test.tsx
@@ -1,7 +1,8 @@
+import { makeMediaProgress } from '@test-utils/media-progress'
import '@testing-library/jest-dom/vitest'
import '@renderer/lib/i18n'
import type { DownloadTask } from '@shared/types/task'
-import { TaskStatus } from '@shared/types/task'
+import { TaskKind, TaskStatus } from '@shared/types/task'
import { makeDownloadTask } from '@test-utils/task'
import { render, screen } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
@@ -66,3 +67,65 @@ describe('MultiSelectionSummary', () => {
expect(screen.getByText(/8\.00 GB/)).toBeInTheDocument()
})
})
+
+it('averages download fractions while counting post-processing separately', () => {
+ const { rerender } = render(
+ <MultiSelectionSummary
+ tasks={[
+ fake({
+ kind: TaskKind.Hls,
+ progress: 1,
+ mediaProgress: makeMediaProgress({
+ phase: 'muxing',
+ download: {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ muxProgress: 0.1,
+ }),
+ }),
+ fake({ progress: 0.5 }),
+ ]}
+ />
+ )
+ expect(screen.getByText('75%')).toBeInTheDocument()
+ expect(screen.getByText('Processing').parentElement).toHaveTextContent('1')
+ expect(screen.getByText('Total size').parentElement).toHaveTextContent('—')
+ rerender(
+ <MultiSelectionSummary
+ tasks={[
+ fake({ kind: TaskKind.Hls, progress: 1 }),
+ fake({ progress: 0.5 }),
+ ]}
+ />
+ )
+ expect(
+ screen.getByText('Average download progress').parentElement
+ ).toHaveTextContent('—')
+})
+
+it('does not let completed selections erase a known remaining download ETA', () => {
+ render(
+ <MultiSelectionSummary
+ tasks={[
+ fake({ status: TaskStatus.Completed }),
+ fake({
+ kind: TaskKind.Hls,
+ mediaProgress: makeMediaProgress({
+ download: {
+ progress: 0.5,
+ completedParts: 1,
+ totalParts: 2,
+ totalBytes: 1000,
+ },
+ }),
+ }),
+ ]}
+ />
+ )
+ expect(screen.getByText('Longest ETA').parentElement).toHaveTextContent(
+ '00:10'
+ )
+})
diff --git a/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx b/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
index 3be3eaa1..5c9d8d67 100644
--- a/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
+++ b/src/renderer/routes/downloads/inspector/multi-selection-summary.tsx
@@ -1,8 +1,16 @@
import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { formatDurationHMS, formatProgressPercent } from '@renderer/lib/format'
-import type { DownloadTask, TaskStatus } from '@shared/types/task'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import {
+ getDownloadProgress,
+ getOutputSize,
+ isMediaProcessing,
+ isMediaTask,
+ mediaProgressPercent,
+} from '@shared/utils/media-progress'
import { useMemo } from 'react'
import { useTranslation } from 'react-i18next'
+import { getTaskEta, getTaskSpeed } from '../task-column-values'
function Card({
title,
@@ -41,17 +49,43 @@ export function MultiSelectionSummary({
const { t } = useTranslation()
const agg = useMemo(() => {
- const totalSize = tasks.reduce((s, x) => s + x.sizeWhenDone, 0)
+ const sizes = tasks.map(getOutputSize)
+ const totalSize = sizes.includes(null)
+ ? null
+ : sizes.reduce<number>((s, x) => s + (x ?? 0), 0)
+ const hasMedia = tasks.some(isMediaTask)
+ const processing = tasks.filter(isMediaProcessing).length
+ const progress = tasks.map(getDownloadProgress)
const downloaded = tasks.reduce((s, x) => s + x.downloadedBytes, 0)
- const avgProgress =
- tasks.reduce((s, x) => s + x.progress, 0) / Math.max(1, tasks.length)
- const combinedDown = tasks.reduce((s, x) => s + x.downloadSpeed, 0)
- const combinedUp = tasks.reduce((s, x) => s + x.uploadSpeed, 0)
- const longestEta = tasks.reduce((m, x) => Math.max(m, x.etaSeconds), 0)
+ const avgProgress = progress.includes(null)
+ ? null
+ : progress.reduce<number>((s, x) => s + (x ?? 0), 0) /
+ Math.max(1, tasks.length)
+ const combinedDown = tasks.reduce(
+ (s, x) => s + (getTaskSpeed(x, 'downloadSpeed') ?? 0),
+ 0
+ )
+ const combinedUp = tasks.reduce(
+ (s, x) => s + (getTaskSpeed(x, 'uploadSpeed') ?? 0),
+ 0
+ )
+ const etas = tasks
+ .filter(
+ (task) =>
+ task.status !== TaskStatus.Completed &&
+ task.status !== TaskStatus.Seeding
+ )
+ .map(getTaskEta)
+ const longestEta =
+ hasMedia && etas.includes(null)
+ ? null
+ : etas.reduce<number>((longest, eta) => Math.max(longest, eta ?? 0), 0)
const counts: Record<string, number> = {}
for (const x of tasks) counts[x.status] = (counts[x.status] ?? 0) + 1
return {
totalSize,
+ hasMedia,
+ processing,
downloaded,
avgProgress,
combinedDown,
@@ -66,15 +100,23 @@ export function MultiSelectionSummary({
<Card title={t('panel.downloads.inspector.multi.totals')}>
<Row
label={t('panel.downloads.inspector.multi.totalSize')}
- value={formatBytes(agg.totalSize)}
+ value={agg.totalSize === null ? '—' : formatBytes(agg.totalSize)}
/>
<Row
label={t('panel.downloads.inspector.multi.downloaded')}
value={formatBytes(agg.downloaded)}
/>
<Row
- label={t('panel.downloads.inspector.multi.avgProgress')}
- value={`${formatProgressPercent(agg.avgProgress)}%`}
+ label={t(
+ agg.hasMedia
+ ? 'panel.downloads.media.avgDownloadProgress'
+ : 'panel.downloads.inspector.multi.avgProgress'
+ )}
+ value={
+ agg.avgProgress === null
+ ? '—'
+ : `${agg.hasMedia ? mediaProgressPercent(agg.avgProgress) : formatProgressPercent(agg.avgProgress)}%`
+ }
/>
</Card>
<Card title={t('panel.downloads.inspector.multi.liveSpeed')}>
@@ -88,10 +130,18 @@ export function MultiSelectionSummary({
/>
<Row
label={t('panel.downloads.inspector.multi.longestEta')}
- value={formatDurationHMS(agg.longestEta)}
+ value={
+ agg.longestEta === null ? '—' : formatDurationHMS(agg.longestEta)
+ }
/>
</Card>
<Card title={t('panel.downloads.inspector.multi.statusDist')}>
+ {agg.hasMedia && (
+ <Row
+ label={t('panel.downloads.media.processingTasks')}
+ value={String(agg.processing)}
+ />
+ )}
{(Object.entries(agg.counts) as [TaskStatus, number][])
.sort((a, b) => b[1] - a[1])
.map(([status, n]) => (
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
index b841e805..86a068b1 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.test.tsx
@@ -1,3 +1,4 @@
+import { makeMediaProgress } from '@test-utils/media-progress'
import '@testing-library/jest-dom/vitest'
import { vi } from 'vitest'
@@ -266,3 +267,28 @@ describe('OverviewTab', () => {
})
})
})
+
+it('separates completed segment downloads from active mux progress and unknown output size', () => {
+ renderOverviewTab({
+ ...task,
+ kind: TaskKind.Hls,
+ type: TaskType.Http,
+ progress: 1,
+ mediaProgress: makeMediaProgress({
+ phase: 'muxing',
+ download: {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ muxProgress: 0.42,
+ }),
+ })
+ expect(screen.getByText('100%')).toBeInTheDocument()
+ expect(screen.getByText('42%')).toBeInTheDocument()
+ expect(screen.getByText('1000 / 1000 segments')).toBeInTheDocument()
+ expect(screen.getByText('Merging')).toBeInTheDocument()
+ expect(screen.getByText('Output size').parentElement).toHaveTextContent('—')
+ expect(screen.getByText('Download ETA').parentElement).toHaveTextContent('—')
+})
diff --git a/src/renderer/routes/downloads/inspector/overview-tab.tsx b/src/renderer/routes/downloads/inspector/overview-tab.tsx
index f86caf07..788b31fc 100644
--- a/src/renderer/routes/downloads/inspector/overview-tab.tsx
+++ b/src/renderer/routes/downloads/inspector/overview-tab.tsx
@@ -18,8 +18,17 @@ import { formatDurationHMS, formatProgressPercent } from '@renderer/lib/format'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus, TaskType } from '@shared/types/task'
import { canAttemptRetry } from '@shared/types/task-actions'
+import {
+ getDownloadProgress,
+ getOutputSize,
+ getTransferMetrics,
+ isMediaTask,
+ mediaProgressPercent,
+} from '@shared/utils/media-progress'
import { AlertCircleIcon, RotateCcw } from 'lucide-react'
import { useTranslation } from 'react-i18next'
+import { StatusPill } from '../status-pill'
+import { getTaskEta, getTaskSpeed } from '../task-column-values'
import { TaskTimestamp } from '../task-timestamp'
import { SeedingDuration } from './seeding-duration'
import { useTaskActions } from './use-task-actions'
@@ -119,6 +128,13 @@ export function OverviewTab({
const { formatSpeed, formatBytes } = useByteFormat()
const { t, i18n } = useTranslation()
+ const media = isMediaTask(task)
+ const progress = getDownloadProgress(task)
+ const outputSize = getOutputSize(task)
+ const transfer = getTransferMetrics(task)
+ const eta = getTaskEta(task)
+ const muxProgress = task.mediaProgress?.muxProgress ?? null
+ const downSpeed = getTaskSpeed(task, 'downloadSpeed')
const isBt = task.type === TaskType.Bt || task.type === TaskType.Magnet
return (
<div className="flex flex-col gap-3">
@@ -127,11 +143,15 @@ export function OverviewTab({
<Card title={t('panel.downloads.inspector.overview.transfer')}>
<Row
label={t('panel.downloads.inspector.overview.upSpeed')}
- value={formatSpeed(task.uploadSpeed)}
+ value={media ? '—' : formatSpeed(task.uploadSpeed)}
/>
<Row
label={t('panel.downloads.inspector.overview.downSpeed')}
- value={formatSpeed(task.downloadSpeed)}
+ value={
+ media && downSpeed === null
+ ? '—'
+ : formatSpeed(task.downloadSpeed)
+ }
/>
{isBt && (
<Row
@@ -145,17 +165,70 @@ export function OverviewTab({
/>
</Card>
<Card title={t('panel.downloads.inspector.overview.progress')}>
+ {media && (
+ <>
+ <Row
+ label={t('panel.downloads.media.stage')}
+ value={<StatusPill status={task.status} task={task} />}
+ />
+ {task.mediaProgress?.phase === 'muxing' && (
+ <Row
+ label={t('panel.downloads.media.muxProgress')}
+ value={
+ muxProgress === null
+ ? '—'
+ : `${mediaProgressPercent(muxProgress)}%`
+ }
+ />
+ )}
+ <Row
+ label={t('panel.downloads.media.parts')}
+ value={
+ task.mediaProgress
+ ? t('panel.downloads.media.partsFormat', {
+ completed: task.mediaProgress.download.completedParts,
+ total: task.mediaProgress.download.totalParts,
+ })
+ : '—'
+ }
+ />
+ <Row
+ label={t('panel.downloads.media.downloadSize')}
+ value={
+ transfer.bytesTotal === null
+ ? '—'
+ : formatBytes(transfer.bytesTotal)
+ }
+ />
+ </>
+ )}
<Row
- label={t('panel.downloads.inspector.overview.totalSize')}
- value={formatBytes(task.sizeWhenDone)}
+ label={t(
+ media
+ ? 'panel.downloads.media.outputSize'
+ : 'panel.downloads.inspector.overview.totalSize'
+ )}
+ value={outputSize === null ? '—' : formatBytes(outputSize)}
/>
<Row
- label={t('panel.downloads.inspector.overview.percent')}
- value={`${formatProgressPercent(task.progress)}%`}
+ label={t(
+ media
+ ? 'panel.downloads.media.downloadProgress'
+ : 'panel.downloads.inspector.overview.percent'
+ )}
+ value={
+ progress === null
+ ? '—'
+ : `${media ? mediaProgressPercent(progress) : formatProgressPercent(progress)}%`
+ }
/>
<Row
- label={t('panel.downloads.inspector.overview.eta')}
- value={formatDurationHMS(task.etaSeconds)}
+ label={t(
+ media
+ ? 'panel.downloads.media.downloadEta'
+ : 'panel.downloads.inspector.overview.eta'
+ )}
+ value={eta === null ? '—' : formatDurationHMS(eta)}
/>
{isBt && (
<Row
diff --git a/src/renderer/routes/downloads/sort.ts b/src/renderer/routes/downloads/sort.ts
index 1c5547b6..808f2e54 100644
--- a/src/renderer/routes/downloads/sort.ts
+++ b/src/renderer/routes/downloads/sort.ts
@@ -1,4 +1,8 @@
import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import {
+ getOutputSize,
+ getProgressSortValue,
+} from '@shared/utils/media-progress'
import { z } from 'zod'
import {
getTaskConnections,
@@ -77,9 +81,9 @@ function numericValue(
): number | null {
switch (column) {
case 'size':
- return task.sizeWhenDone
+ return getOutputSize(task)
case 'progress':
- return Math.max(0, Math.min(1, task.progress))
+ return getProgressSortValue(task)
case 'status':
return STATUS_ORDER[task.status]
case 'down':
diff --git a/src/renderer/routes/downloads/status-pill.tsx b/src/renderer/routes/downloads/status-pill.tsx
index 1bc4037f..5ec555a9 100644
--- a/src/renderer/routes/downloads/status-pill.tsx
+++ b/src/renderer/routes/downloads/status-pill.tsx
@@ -1,6 +1,10 @@
import { getStatusTone } from '@renderer/lib/task-status-ui'
import { cn } from '@renderer/lib/utils'
-import { TaskStatus } from '@shared/types/task'
+import { type DownloadTask, TaskStatus } from '@shared/types/task'
+import {
+ getMediaPhaseLabel,
+ isMediaProcessing,
+} from '@shared/utils/media-progress'
import { useTranslation } from 'react-i18next'
const LABEL_KEY: Record<TaskStatus, string> = {
@@ -19,12 +23,17 @@ const LABEL_KEY: Record<TaskStatus, string> = {
export function StatusPill({
status,
compact = false,
+ task,
}: {
status: TaskStatus
+ task?: DownloadTask
compact?: boolean
}) {
const { t } = useTranslation()
- const tone = getStatusTone(status)
+ const tone = getStatusTone(
+ task && isMediaProcessing(task) ? TaskStatus.Finalizing : status
+ )
+ const label = (task && getMediaPhaseLabel(task)) || LABEL_KEY[status]
return (
<span
data-testid="task-status-pill"
@@ -36,7 +45,7 @@ export function StatusPill({
tone.text
)}
>
- <span className="truncate">{t(LABEL_KEY[status])}</span>
+ <span className="truncate">{t(label)}</span>
</span>
)
}
diff --git a/src/renderer/routes/downloads/task-column-values.ts b/src/renderer/routes/downloads/task-column-values.ts
index ff95b34a..216a4cc7 100644
--- a/src/renderer/routes/downloads/task-column-values.ts
+++ b/src/renderer/routes/downloads/task-column-values.ts
@@ -1,10 +1,15 @@
import { type DownloadTask, TaskStatus, TaskType } from '@shared/types/task'
+import { getTransferMetrics, isMediaTask } from '@shared/utils/media-progress'
export function getTaskSpeed(
task: DownloadTask,
field: 'downloadSpeed' | 'uploadSpeed'
): number | null {
- const speed = task[field]
+ const speed = isMediaTask(task)
+ ? field === 'downloadSpeed'
+ ? getTransferMetrics(task).speedBps
+ : 0
+ : task[field]
return task.status === TaskStatus.Completed ||
task.status === TaskStatus.Finalizing ||
!Number.isFinite(speed) ||
@@ -14,6 +19,7 @@ export function getTaskSpeed(
}
export function getTaskEta(task: DownloadTask): number | null {
+ if (isMediaTask(task)) return getTransferMetrics(task).etaSec
return task.status === TaskStatus.Paused ||
task.status === TaskStatus.Completed ||
task.status === TaskStatus.Finalizing ||
diff --git a/src/renderer/routes/downloads/task-inspector-drawer.tsx b/src/renderer/routes/downloads/task-inspector-drawer.tsx
index 9a4e3b4d..86cc655a 100644
--- a/src/renderer/routes/downloads/task-inspector-drawer.tsx
+++ b/src/renderer/routes/downloads/task-inspector-drawer.tsx
@@ -178,7 +178,7 @@ export function TaskInspectorDrawer({
</div>
)}
</div>
- <StatusPill status={single.status} />
+ <StatusPill status={single.status} task={single} />
</div>
<Tabs
value={activeSubtab}
diff --git a/src/renderer/routes/downloads/task-progress.tsx b/src/renderer/routes/downloads/task-progress.tsx
new file mode 100644
index 00000000..de8abb7d
--- /dev/null
+++ b/src/renderer/routes/downloads/task-progress.tsx
@@ -0,0 +1,41 @@
+import { Progress } from '@renderer/components/ui/progress'
+import { formatProgressPercent } from '@renderer/lib/format'
+import { getProgressBarTone } from '@renderer/lib/task-status-ui'
+import { cn } from '@renderer/lib/utils'
+import type { DownloadTask } from '@shared/types/task'
+import {
+ getMediaPhaseLabel,
+ getStageProgress,
+ isMediaTask,
+ mediaProgressPercent,
+} from '@shared/utils/media-progress'
+import { useTranslation } from 'react-i18next'
+
+export function TaskProgress({ task }: { task: DownloadTask }) {
+ const { t } = useTranslation()
+ const progress = getStageProgress(task)
+ const pct =
+ progress === null
+ ? null
+ : isMediaTask(task)
+ ? mediaProgressPercent(progress)
+ : formatProgressPercent(progress)
+ const phase = getMediaPhaseLabel(task)
+ const label = [phase ? t(phase) : null, pct === null ? '—' : `${pct}%`]
+ .filter(Boolean)
+ .join(' ')
+ return (
+ <div className="flex items-center gap-2" title={label}>
+ <Progress
+ value={pct ?? undefined}
+ indicatorClassName={cn(
+ getProgressBarTone(task.status),
+ pct === null && !phase && 'w-0 animate-none'
+ )}
+ aria-label={`${task.name}: ${label}`}
+ className="h-1 min-w-4 flex-1"
+ />
+ <span className="min-w-0 shrink truncate text-right">{label}</span>
+ </div>
+ )
+}
diff --git a/src/renderer/routes/downloads/task-row.test.tsx b/src/renderer/routes/downloads/task-row.test.tsx
index b5a79b0e..8af3d8ca 100644
--- a/src/renderer/routes/downloads/task-row.test.tsx
+++ b/src/renderer/routes/downloads/task-row.test.tsx
@@ -1,3 +1,4 @@
+import { makeMediaProgress } from '@test-utils/media-progress'
import '@testing-library/jest-dom/vitest'
import { vi } from 'vitest'
@@ -61,6 +62,59 @@ function getEtaCell(container: HTMLElement): Element {
}
describe('TaskRow', () => {
+ it('shows media stages even with the status column hidden and exposes indeterminate progress', () => {
+ const task = fake({
+ kind: TaskKind.Hls,
+ progress: 1,
+ mediaProgress: makeMediaProgress(),
+ })
+ const { rerender } = render(
+ <TaskRow
+ task={task}
+ rowProps={rowProps}
+ columns={[
+ { id: 'name', width: 240, visible: true },
+ { id: 'progress', width: 160, visible: true },
+ ]}
+ />
+ )
+ expect(screen.getByText('Downloading 0.1%')).toBeInTheDocument()
+ expect(screen.getByRole('progressbar')).toHaveAttribute(
+ 'aria-valuenow',
+ '0.1'
+ )
+ rerender(
+ <TaskRow
+ task={{
+ ...task,
+ mediaProgress: makeMediaProgress({ phase: 'assembling' }),
+ }}
+ rowProps={rowProps}
+ columns={[{ id: 'progress', width: 160, visible: true }]}
+ />
+ )
+ expect(screen.getByText('Assembling —')).toBeInTheDocument()
+ expect(screen.getByRole('progressbar')).not.toHaveAttribute('aria-valuenow')
+ rerender(
+ <TaskRow
+ task={{
+ ...task,
+ mediaProgress: makeMediaProgress({
+ phase: 'muxing',
+ muxProgress: 0.42,
+ }),
+ }}
+ rowProps={rowProps}
+ columns={[{ id: 'progress', width: 160, visible: true }]}
+ />
+ )
+ expect(screen.getByText('Merging 42%')).toBeInTheDocument()
+ expect(screen.getByRole('progressbar')).toHaveAttribute(
+ 'aria-valuenow',
+ '42'
+ )
+ })
+
it('keeps a slow unfinished tail below 100% until bytes finish', () => {
const task = fake({ progress: 0.995, downloadSpeed: 102400 })
const { rerender } = render(<TaskRow task={task} rowProps={rowProps} />)
diff --git a/src/renderer/routes/downloads/task-row.tsx b/src/renderer/routes/downloads/task-row.tsx
index 74d12cec..d66efc8c 100644
--- a/src/renderer/routes/downloads/task-row.tsx
+++ b/src/renderer/routes/downloads/task-row.tsx
@@ -1,10 +1,10 @@
import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { resolveFailureReason } from '@renderer/lib/failure-reason'
-import { formatDurationHMS, formatProgressPercent } from '@renderer/lib/format'
-import { getProgressBarTone } from '@renderer/lib/task-status-ui'
+import { formatDurationHMS } from '@renderer/lib/format'
import { cn } from '@renderer/lib/utils'
import type { DownloadTask } from '@shared/types/task'
import { TaskStatus } from '@shared/types/task'
+import { getOutputSize } from '@shared/utils/media-progress'
import { memo, type ReactNode } from 'react'
import { useTranslation } from 'react-i18next'
import {
@@ -21,6 +21,7 @@ import {
getTaskSpeed,
getTaskTimestamp,
} from './task-column-values'
+import { TaskProgress } from './task-progress'
import { TaskTimestamp } from './task-timestamp'
export interface TaskRowProps {
@@ -45,7 +46,7 @@ function TaskRowBase({
}: TaskRowProps) {
const { formatBytes, formatSpeed } = useByteFormat()
const { t, i18n } = useTranslation()
- const pct = formatProgressPercent(task.progress)
+ const outputSize = getOutputSize(task)
const downloadSpeed = getTaskSpeed(task, 'downloadSpeed')
const uploadSpeed = getTaskSpeed(task, 'uploadSpeed')
const eta = getTaskEta(task)
@@ -82,19 +83,9 @@ function TaskRowBase({
{extension && <span className="shrink-0">{extension}</span>}
</span>
),
- size: formatBytes(task.sizeWhenDone),
- progress: (
- <span className="flex items-center gap-2">
- <span className="h-1 min-w-0 flex-1 overflow-hidden rounded-full bg-muted">
- <span
- className={cn('block h-full', getProgressBarTone(task.status))}
- style={{ width: `${pct}%` }}
- />
- </span>
- <span className="w-10 shrink-0 text-right">{pct}%</span>
- </span>
- ),
- status: <StatusPill status={task.status} compact />,
+ size: outputSize === null ? '—' : formatBytes(outputSize),
+ progress: <TaskProgress task={task} />,
+ status: <StatusPill status={task.status} task={task} compact />,
down: downloadSpeed === null ? '—' : formatSpeed(downloadSpeed),
up: uploadSpeed === null ? '—' : formatSpeed(uploadSpeed),
eta: eta === null ? '—' : formatDurationHMS(eta),
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index 8a20f961..39618f97 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -846,6 +846,23 @@
"uploadLimit": "Upload limit: {{speed}}",
"downloadLimit": "Download limit: {{speed}}",
"saveFailed": "Couldn’t change the speed mode. Try again."
+ },
+ "media": {
+ "preparing": "Preparing",
+ "decrypting": "Decrypting",
+ "assembling": "Assembling",
+ "muxing": "Merging",
+ "renaming": "Saving",
+ "stage": "Stage",
+ "downloadProgress": "Download progress",
+ "muxProgress": "Merge progress",
+ "parts": "Segments",
+ "partsFormat": "{{completed}} / {{total}} segments",
+ "downloadSize": "Download size",
+ "outputSize": "Output size",
+ "downloadEta": "Download ETA",
+ "avgDownloadProgress": "Average download progress",
+ "processingTasks": "Processing"
}
}
},
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 2c79993a..733beaa7 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -835,6 +835,23 @@
"uploadLimit": "上传上限:{{speed}}",
"downloadLimit": "下载上限:{{speed}}",
"saveFailed": "无法切换速度模式,请重试。"
+ },
+ "media": {
+ "preparing": "准备中",
+ "decrypting": "解密中",
+ "assembling": "拼接中",
+ "muxing": "合并中",
+ "renaming": "保存中",
+ "stage": "当前阶段",
+ "downloadProgress": "下载进度",
+ "muxProgress": "合并进度",
+ "parts": "分片",
+ "partsFormat": "{{completed}} / {{total}} 个分片",
+ "downloadSize": "下载总量",
+ "outputSize": "成品大小",
+ "downloadEta": "下载剩余时间",
+ "avgDownloadProgress": "平均下载进度",
+ "processingTasks": "处理中任务"
}
}
},
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 35f196f2..59f916f3 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -835,6 +835,23 @@
"uploadLimit": "上傳上限:{{speed}}",
"downloadLimit": "下載上限:{{speed}}",
"saveFailed": "無法切換速度模式,請重試。"
+ },
+ "media": {
+ "preparing": "準備中",
+ "decrypting": "解密中",
+ "assembling": "拼接中",
+ "muxing": "合併中",
+ "renaming": "儲存中",
+ "stage": "目前階段",
+ "downloadProgress": "下載進度",
+ "muxProgress": "合併進度",
+ "parts": "分片",
+ "partsFormat": "{{completed}} / {{total}} 個分片",
+ "downloadSize": "下載總量",
+ "outputSize": "成品大小",
+ "downloadEta": "下載剩餘時間",
+ "avgDownloadProgress": "平均下載進度",
+ "processingTasks": "處理中任務"
}
}
},
diff --git a/src/shared/schemas/media-progress.ts b/src/shared/schemas/media-progress.ts
new file mode 100644
index 00000000..8d949a55
--- /dev/null
+++ b/src/shared/schemas/media-progress.ts
@@ -0,0 +1,35 @@
+import { z } from 'zod'
+
+const bytes = z.number().finite().nonnegative()
+const fraction = z.number().finite().min(0).max(1)
+
+export const MediaProgressSchema = z.object({
+ version: z.literal(1),
+ phase: z.enum([
+ 'preparing',
+ 'downloading',
+ 'decrypting',
+ 'assembling',
+ 'muxing',
+ 'renaming',
+ ]),
+ download: z
+ .object({
+ progress: fraction,
+ completedParts: z.number().int().nonnegative(),
+ totalParts: z.number().int().positive(),
+ totalBytes: bytes.nullable(),
+ })
+ .refine(
+ (d) =>
+ d.completedParts <= d.totalParts &&
+ (d.progress === 1) === (d.completedParts === d.totalParts) &&
+ d.progress >= d.completedParts / d.totalParts - 1e-10,
+ 'Inconsistent media download progress'
+ ),
+ muxProgress: fraction.nullable(),
+ outputBytes: bytes.nullable(),
+})
+
+export type MediaProgressSnapshot = z.infer<typeof MediaProgressSchema>
+export type MediaPhase = MediaProgressSnapshot['phase']
diff --git a/src/shared/types/task-actions.ts b/src/shared/types/task-actions.ts
index e65abf6b..9948957b 100644
--- a/src/shared/types/task-actions.ts
+++ b/src/shared/types/task-actions.ts
@@ -55,6 +55,7 @@ export function canPause(t: DownloadTask): boolean {
// mux instance instead of status alone (status alone would leave the Pause
// button enabled during mux, where every click would fail with no gids).
if (isMediaKind(t.kind)) {
+ if (t.mediaProgress && t.mediaProgress.phase !== 'downloading') return false
const muxStarted = t.instances.some(
(i) =>
i.phase === TaskInstancePhase.FfmpegMux &&
diff --git a/src/shared/types/task.ts b/src/shared/types/task.ts
index 94889f32..936f8873 100644
--- a/src/shared/types/task.ts
+++ b/src/shared/types/task.ts
@@ -1,4 +1,5 @@
import type { DownloadErrorCode } from '../errors'
+import type { MediaProgressSnapshot } from '../schemas/media-progress'
export enum TaskStatus {
Queued = 'queued',
@@ -78,6 +79,8 @@ export interface DownloadTask {
type: TaskType
status: TaskStatus
progress: number
+ /** Fixed-size media phase snapshot; detailed files live outside SQLite. */
+ mediaProgress?: MediaProgressSnapshot
totalBytes: number
downloadedBytes: number
downloadSpeed: number
diff --git a/src/shared/utils/media-progress.test.ts b/src/shared/utils/media-progress.test.ts
new file mode 100644
index 00000000..4da1254f
--- /dev/null
+++ b/src/shared/utils/media-progress.test.ts
@@ -0,0 +1,126 @@
+import { MediaProgressSchema } from '@shared/schemas/media-progress'
+import { TaskKind, TaskStatus } from '@shared/types/task'
+import { canPause } from '@shared/types/task-actions'
+import { makeMediaProgress } from '@test-utils/media-progress'
+import { makeDownloadTask } from '@test-utils/task'
+import { describe, expect, it } from 'vitest'
+import {
+ getDownloadProgress,
+ getMediaPhaseLabel,
+ getOutputSize,
+ getProgressSortValue,
+ getStageProgress,
+ getTransferMetrics,
+ mediaProgressPercent,
+ segmentFraction,
+} from './media-progress'
+
+describe('media progress projections', () => {
+ it('never rounds incomplete work to 100%', () => {
+ expect(segmentFraction(100, 100, false)).toBeLessThan(1)
+ expect(mediaProgressPercent(0.99999999)).toBe(99.9)
+ expect(mediaProgressPercent(0.001)).toBe(0.1)
+ expect(segmentFraction(0, 0, true)).toBe(1)
+ expect(mediaProgressPercent(1)).toBe(100)
+ })
+ it.each([0, -1, Number.NaN, Number.POSITIVE_INFINITY])(
+ 'handles unknown/invalid total %s',
+ (total) => {
+ expect(segmentFraction(500, total, false)).toBe(0)
+ }
+ )
+ it('treats legacy progress and output size as unknown', () => {
+ const task = makeDownloadTask({
+ kind: TaskKind.Hls,
+ progress: 1,
+ totalBytes: 100,
+ downloadedBytes: 100,
+ sizeWhenDone: 100,
+ })
+ expect(getDownloadProgress(task)).toBeNull()
+ expect(getStageProgress(task)).toBeNull()
+ expect(getOutputSize(task)).toBeNull()
+ expect(getOutputSize({ ...task, status: TaskStatus.Completed })).toBeNull()
+ expect(getTransferMetrics(task)).toEqual({
+ bytesTotal: null,
+ speedBps: 0,
+ etaSec: null,
+ })
+ expect(getDownloadProgress({ ...task, status: TaskStatus.Completed })).toBe(
+ 1
+ )
+ })
+ it('keeps mux and download progress separate, and terminal status wins over phase', () => {
+ const mediaProgress = makeMediaProgress({
+ phase: 'muxing',
+ download: {
+ progress: 1,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: 2000,
+ },
+ muxProgress: 0.4,
+ })
+ const task = makeDownloadTask({
+ kind: TaskKind.Mux,
+ mediaProgress,
+ downloadSpeed: 500,
+ etaSeconds: 3,
+ })
+ expect(getDownloadProgress(task)).toBe(1)
+ expect(getStageProgress(task)).toBe(0.4)
+ expect(getTransferMetrics(task)).toEqual({
+ bytesTotal: 2000,
+ speedBps: 0,
+ etaSec: null,
+ })
+ expect(canPause(task)).toBe(false)
+ expect(getMediaPhaseLabel({ ...task, status: TaskStatus.Error })).toBeNull()
+ expect(
+ getMediaPhaseLabel({ ...task, status: TaskStatus.Paused })
+ ).toBeNull()
+ })
+ it('sorts by stage before local percentages and keeps legacy unknown', () => {
+ const downloading = makeDownloadTask({
+ kind: TaskKind.Hls,
+ mediaProgress: makeMediaProgress(),
+ })
+ const muxing = {
+ ...downloading,
+ mediaProgress: makeMediaProgress({ phase: 'muxing', muxProgress: 0 }),
+ }
+ expect(getProgressSortValue(muxing)).toBeGreaterThan(
+ getProgressSortValue(downloading)!
+ )
+ expect(
+ getProgressSortValue({ ...downloading, mediaProgress: undefined })
+ ).toBeNull()
+ expect(getProgressSortValue({ ...muxing, status: TaskStatus.Error })).toBe(
+ getProgressSortValue(muxing)
+ )
+ })
+ it('validates the persisted constant-size summary including exact completed count', () => {
+ expect(MediaProgressSchema.safeParse(makeMediaProgress()).success).toBe(
+ true
+ )
+ for (const download of [
+ { progress: 1, completedParts: 1, totalParts: 1000, totalBytes: null },
+ {
+ progress: 0.5,
+ completedParts: 1000,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ { progress: 0.5, completedParts: 1, totalParts: 0, totalBytes: null },
+ {
+ progress: Number.NaN,
+ completedParts: 0,
+ totalParts: 1,
+ totalBytes: null,
+ },
+ ])
+ expect(
+ MediaProgressSchema.safeParse(makeMediaProgress({ download })).success
+ ).toBe(false)
+ })
+})
diff --git a/src/shared/utils/media-progress.ts b/src/shared/utils/media-progress.ts
new file mode 100644
index 00000000..28bf2e6a
--- /dev/null
+++ b/src/shared/utils/media-progress.ts
@@ -0,0 +1,147 @@
+import type { MediaPhase } from '../schemas/media-progress'
+import { type DownloadTask, TaskKind, TaskStatus } from '../types/task'
+
+export const MEDIA_PHASE_LABELS: Record<MediaPhase, string> = {
+ preparing: 'panel.downloads.media.preparing',
+ downloading: 'panel.downloads.status.downloading',
+ decrypting: 'panel.downloads.media.decrypting',
+ assembling: 'panel.downloads.media.assembling',
+ muxing: 'panel.downloads.media.muxing',
+ renaming: 'panel.downloads.media.renaming',
+}
+
+export function isMediaTask(task: Pick<DownloadTask, 'kind'>): boolean {
+ return task.kind === TaskKind.Hls || task.kind === TaskKind.Mux
+}
+
+export function finiteProgress(value: number): number {
+ return Number.isFinite(value) ? Math.max(0, Math.min(1, value)) : 0
+}
+
+/** A byte-complete transfer still needs a successful completion event. */
+export function segmentFraction(
+ downloaded: number,
+ total: number,
+ completed: boolean
+): number {
+ if (completed) return 1
+ return Number.isFinite(total) && total > 0
+ ? Math.min(0.9999, finiteProgress(downloaded / total))
+ : 0
+}
+
+export function mediaProgressPercent(progress: number): number {
+ const value = finiteProgress(progress)
+ return value >= 1 ? 100 : Math.min(99.9, Math.round(value * 1000) / 10)
+}
+
+/** Transfer progress, never a mixture of transfer and mux percentages. */
+export function getDownloadProgress(task: DownloadTask): number | null {
+ if (
+ task.status === TaskStatus.Completed ||
+ task.status === TaskStatus.Seeding
+ )
+ return 1
+ return isMediaTask(task)
+ ? (task.mediaProgress?.download.progress ?? null)
+ : finiteProgress(task.progress)
+}
+
+export function getStageProgress(task: DownloadTask): number | null {
+ if (!isMediaTask(task) || !getMediaPhaseLabel(task))
+ return getDownloadProgress(task)
+ const media = task.mediaProgress
+ if (media?.phase === 'downloading') return media.download.progress
+ if (media?.phase === 'muxing') return media.muxProgress
+ return null
+}
+
+export function isMediaProcessing(task: DownloadTask): boolean {
+ return (
+ isMediaTask(task) &&
+ (task.status === TaskStatus.Downloading ||
+ task.status === TaskStatus.Finalizing) &&
+ task.mediaProgress !== undefined &&
+ !['preparing', 'downloading'].includes(task.mediaProgress.phase)
+ )
+}
+
+export function getMediaPhaseLabel(task: DownloadTask): string | null {
+ return isMediaTask(task) &&
+ task.mediaProgress &&
+ (task.status === TaskStatus.Downloading ||
+ task.status === TaskStatus.Finalizing ||
+ task.status === TaskStatus.Queued)
+ ? MEDIA_PHASE_LABELS[task.mediaProgress.phase]
+ : null
+}
+
+export function getOutputSize(task: DownloadTask): number | null {
+ if (!isMediaTask(task)) return task.sizeWhenDone
+ // Legacy sizeWhenDone held summed input bytes, not the published file size.
+ return task.mediaProgress?.outputBytes ?? null
+}
+
+const PHASE_ORDER: Record<MediaPhase, number> = {
+ preparing: 0,
+ downloading: 1,
+ decrypting: 2,
+ assembling: 3,
+ muxing: 4,
+ renaming: 5,
+}
+
+export function getProgressSortValue(task: DownloadTask): number | null {
+ if (
+ task.status === TaskStatus.Completed ||
+ task.status === TaskStatus.Seeding
+ )
+ return 12
+ if (task.status === TaskStatus.Finalizing) return 10
+ if (isMediaTask(task)) {
+ const media = task.mediaProgress
+ if (!media) return null
+ const progress =
+ media.phase === 'muxing'
+ ? media.muxProgress
+ : media.phase === 'downloading'
+ ? media.download.progress
+ : null
+ return PHASE_ORDER[media.phase] * 2 + (progress ?? 0)
+ }
+ const queued =
+ task.status === TaskStatus.Queued ||
+ task.status === TaskStatus.FetchingMetadata ||
+ task.status === TaskStatus.MetadataReady
+ return (queued ? 0 : 2) + finiteProgress(task.progress)
+}
+
+/** Wire and renderer transfer estimates share the same unknown semantics. */
+export function getTransferMetrics(task: DownloadTask): {
+ bytesTotal: number | null
+ speedBps: number
+ etaSec: number | null
+} {
+ const media = isMediaTask(task)
+ const bytesTotal = media
+ ? (task.mediaProgress?.download.totalBytes ?? null)
+ : task.totalBytes > 0
+ ? task.totalBytes
+ : null
+ const transferring =
+ !media ||
+ (task.status === TaskStatus.Downloading &&
+ task.mediaProgress?.phase === 'downloading')
+ const speedBps =
+ transferring && Number.isFinite(task.downloadSpeed)
+ ? Math.max(0, task.downloadSpeed)
+ : 0
+ const etaSec =
+ transferring &&
+ (!media || (bytesTotal !== null && speedBps > 0)) &&
+ Number.isFinite(task.etaSeconds) &&
+ task.etaSeconds > 0
+ ? task.etaSeconds
+ : null
+ return { bytesTotal, speedBps, etaSec }
+}
diff --git a/src/test-utils/media-progress.ts b/src/test-utils/media-progress.ts
new file mode 100644
index 00000000..5d206c51
--- /dev/null
+++ b/src/test-utils/media-progress.ts
@@ -0,0 +1,19 @@
+import type { MediaProgressSnapshot } from '@shared/schemas/media-progress'
+
+export function makeMediaProgress(
+ overrides: Partial<MediaProgressSnapshot> = {}
+): MediaProgressSnapshot {
+ return {
+ version: 1,
+ phase: 'downloading',
+ download: {
+ progress: 0.001,
+ completedParts: 1,
+ totalParts: 1000,
+ totalBytes: null,
+ },
+ muxProgress: null,
+ outputBytes: null,
+ ...overrides,
+ }
+}