@dominevo/addon-media-library 0.1.10 → 0.1.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,4 @@
1
- import { mkdir, open, readFile, readdir, realpath, rename, stat, unlink, writeFile } from "node:fs/promises";
1
+ import { mkdir, open, readFile, readdir, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises";
2
2
  import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";
3
3
  import { createHash } from "node:crypto";
4
4
  import { createReadStream, existsSync, readFileSync } from "node:fs";
@@ -2890,7 +2890,7 @@ function initializeContext(params) {
2890
2890
  external: params?.external ?? void 0
2891
2891
  };
2892
2892
  }
2893
- function process(schema, ctx, _params = {
2893
+ function process$1(schema, ctx, _params = {
2894
2894
  path: [],
2895
2895
  schemaPath: []
2896
2896
  }) {
@@ -2927,7 +2927,7 @@ function process(schema, ctx, _params = {
2927
2927
  const parent = schema._zod.parent;
2928
2928
  if (parent) {
2929
2929
  if (!result.ref) result.ref = parent;
2930
- process(parent, ctx, params);
2930
+ process$1(parent, ctx, params);
2931
2931
  ctx.seen.get(parent).isParent = true;
2932
2932
  }
2933
2933
  }
@@ -3147,7 +3147,7 @@ var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
3147
3147
  ...params,
3148
3148
  processors
3149
3149
  });
3150
- process(schema, ctx);
3150
+ process$1(schema, ctx);
3151
3151
  extractDefs(ctx, schema);
3152
3152
  return finalize(ctx, schema);
3153
3153
  };
@@ -3159,7 +3159,7 @@ var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) =
3159
3159
  io,
3160
3160
  processors
3161
3161
  });
3162
- process(schema, ctx);
3162
+ process$1(schema, ctx);
3163
3163
  extractDefs(ctx, schema);
3164
3164
  return finalize(ctx, schema);
3165
3165
  };
@@ -3263,7 +3263,7 @@ var arrayProcessor = (schema, ctx, _json, params) => {
3263
3263
  if (typeof minimum === "number") json.minItems = minimum;
3264
3264
  if (typeof maximum === "number") json.maxItems = maximum;
3265
3265
  json.type = "array";
3266
- json.items = process(def.element, ctx, {
3266
+ json.items = process$1(def.element, ctx, {
3267
3267
  ...params,
3268
3268
  path: [...params.path, "items"]
3269
3269
  });
@@ -3274,7 +3274,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3274
3274
  json.type = "object";
3275
3275
  json.properties = {};
3276
3276
  const shape = def.shape;
3277
- for (const key in shape) json.properties[key] = process(shape[key], ctx, {
3277
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
3278
3278
  ...params,
3279
3279
  path: [
3280
3280
  ...params.path,
@@ -3292,7 +3292,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3292
3292
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
3293
3293
  else if (!def.catchall) {
3294
3294
  if (ctx.io === "output") json.additionalProperties = false;
3295
- } else if (def.catchall) json.additionalProperties = process(def.catchall, ctx, {
3295
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
3296
3296
  ...params,
3297
3297
  path: [...params.path, "additionalProperties"]
3298
3298
  });
@@ -3300,7 +3300,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3300
3300
  var unionProcessor = (schema, ctx, json, params) => {
3301
3301
  const def = schema._zod.def;
3302
3302
  const isExclusive = def.inclusive === false;
3303
- const options = def.options.map((x, i) => process(x, ctx, {
3303
+ const options = def.options.map((x, i) => process$1(x, ctx, {
3304
3304
  ...params,
3305
3305
  path: [
3306
3306
  ...params.path,
@@ -3313,7 +3313,7 @@ var unionProcessor = (schema, ctx, json, params) => {
3313
3313
  };
3314
3314
  var intersectionProcessor = (schema, ctx, json, params) => {
3315
3315
  const def = schema._zod.def;
3316
- const a = process(def.left, ctx, {
3316
+ const a = process$1(def.left, ctx, {
3317
3317
  ...params,
3318
3318
  path: [
3319
3319
  ...params.path,
@@ -3321,7 +3321,7 @@ var intersectionProcessor = (schema, ctx, json, params) => {
3321
3321
  0
3322
3322
  ]
3323
3323
  });
3324
- const b = process(def.right, ctx, {
3324
+ const b = process$1(def.right, ctx, {
3325
3325
  ...params,
3326
3326
  path: [
3327
3327
  ...params.path,
@@ -3339,7 +3339,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3339
3339
  const keyType = def.keyType;
3340
3340
  const patterns = keyType._zod.bag?.patterns;
3341
3341
  if (def.mode === "loose" && patterns && patterns.size > 0) {
3342
- const valueSchema = process(def.valueType, ctx, {
3342
+ const valueSchema = process$1(def.valueType, ctx, {
3343
3343
  ...params,
3344
3344
  path: [
3345
3345
  ...params.path,
@@ -3350,11 +3350,11 @@ var recordProcessor = (schema, ctx, _json, params) => {
3350
3350
  json.patternProperties = {};
3351
3351
  for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
3352
3352
  } else {
3353
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process(def.keyType, ctx, {
3353
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, {
3354
3354
  ...params,
3355
3355
  path: [...params.path, "propertyNames"]
3356
3356
  });
3357
- json.additionalProperties = process(def.valueType, ctx, {
3357
+ json.additionalProperties = process$1(def.valueType, ctx, {
3358
3358
  ...params,
3359
3359
  path: [...params.path, "additionalProperties"]
3360
3360
  });
@@ -3367,7 +3367,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3367
3367
  };
3368
3368
  var nullableProcessor = (schema, ctx, json, params) => {
3369
3369
  const def = schema._zod.def;
3370
- const inner = process(def.innerType, ctx, params);
3370
+ const inner = process$1(def.innerType, ctx, params);
3371
3371
  const seen = ctx.seen.get(schema);
3372
3372
  if (ctx.target === "openapi-3.0") {
3373
3373
  seen.ref = def.innerType;
@@ -3376,27 +3376,27 @@ var nullableProcessor = (schema, ctx, json, params) => {
3376
3376
  };
3377
3377
  var nonoptionalProcessor = (schema, ctx, _json, params) => {
3378
3378
  const def = schema._zod.def;
3379
- process(def.innerType, ctx, params);
3379
+ process$1(def.innerType, ctx, params);
3380
3380
  const seen = ctx.seen.get(schema);
3381
3381
  seen.ref = def.innerType;
3382
3382
  };
3383
3383
  var defaultProcessor = (schema, ctx, json, params) => {
3384
3384
  const def = schema._zod.def;
3385
- process(def.innerType, ctx, params);
3385
+ process$1(def.innerType, ctx, params);
3386
3386
  const seen = ctx.seen.get(schema);
3387
3387
  seen.ref = def.innerType;
3388
3388
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
3389
3389
  };
3390
3390
  var prefaultProcessor = (schema, ctx, json, params) => {
3391
3391
  const def = schema._zod.def;
3392
- process(def.innerType, ctx, params);
3392
+ process$1(def.innerType, ctx, params);
3393
3393
  const seen = ctx.seen.get(schema);
3394
3394
  seen.ref = def.innerType;
3395
3395
  if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3396
3396
  };
3397
3397
  var catchProcessor = (schema, ctx, json, params) => {
3398
3398
  const def = schema._zod.def;
3399
- process(def.innerType, ctx, params);
3399
+ process$1(def.innerType, ctx, params);
3400
3400
  const seen = ctx.seen.get(schema);
3401
3401
  seen.ref = def.innerType;
3402
3402
  let catchValue;
@@ -3411,20 +3411,20 @@ var pipeProcessor = (schema, ctx, _json, params) => {
3411
3411
  const def = schema._zod.def;
3412
3412
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
3413
3413
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
3414
- process(innerType, ctx, params);
3414
+ process$1(innerType, ctx, params);
3415
3415
  const seen = ctx.seen.get(schema);
3416
3416
  seen.ref = innerType;
3417
3417
  };
3418
3418
  var readonlyProcessor = (schema, ctx, json, params) => {
3419
3419
  const def = schema._zod.def;
3420
- process(def.innerType, ctx, params);
3420
+ process$1(def.innerType, ctx, params);
3421
3421
  const seen = ctx.seen.get(schema);
3422
3422
  seen.ref = def.innerType;
3423
3423
  json.readOnly = true;
3424
3424
  };
3425
3425
  var optionalProcessor = (schema, ctx, _json, params) => {
3426
3426
  const def = schema._zod.def;
3427
- process(def.innerType, ctx, params);
3427
+ process$1(def.innerType, ctx, params);
3428
3428
  const seen = ctx.seen.get(schema);
3429
3429
  seen.ref = def.innerType;
3430
3430
  };
@@ -8865,6 +8865,22 @@ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8865
8865
  label: /* @__PURE__ */ string(),
8866
8866
  path: /* @__PURE__ */ string()
8867
8867
  });
8868
+ /**
8869
+ * Scrub thumbnails of the file. `path` is the relative hub path of the WebVTT index (cues point at
8870
+ * `sprite-N.jpg#xywh=x,y,w,h` beside it), set only when `status` is `ready`. `pending`: being generated in the
8871
+ * background, ask again later; `failed`: ffmpeg could not; `skipped`: the file has no duration or is too short;
8872
+ * `disabled`: the installation turned generation off.
8873
+ */
8874
+ var MediaTrickplaySchema = /* @__PURE__ */ object({
8875
+ status: /* @__PURE__ */ _enum([
8876
+ "ready",
8877
+ "pending",
8878
+ "failed",
8879
+ "skipped",
8880
+ "disabled"
8881
+ ]),
8882
+ path: /* @__PURE__ */ string().nullable()
8883
+ });
8868
8884
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8869
8885
  overview: /* @__PURE__ */ string().nullable(),
8870
8886
  ids: /* @__PURE__ */ object({
@@ -8879,7 +8895,9 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8879
8895
  /** The file's chapters in order; empty when it has none or it is not probed yet. */
8880
8896
  chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8881
8897
  /** Sidecar subtitle files found next to the video; empty when none. */
8882
- externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8898
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly(),
8899
+ /** Scrub thumbnails of the file; `null` when the item has no file. */
8900
+ trickplay: /* @__PURE__ */ MediaTrickplaySchema.nullable()
8883
8901
  });
8884
8902
  /**
8885
8903
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9444,6 +9462,8 @@ var MediaLibrarySettingsSchema = object({
9444
9462
  /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9445
9463
  folderRoots: string().default(""),
9446
9464
  rescanMinutes: number().int().min(0).default(60),
9465
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
9466
+ trickplay: boolean().default(true),
9447
9467
  /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9448
9468
  metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9449
9469
  /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
@@ -9562,22 +9582,33 @@ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9562
9582
  id: "folders",
9563
9583
  title: "Folders",
9564
9584
  titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9565
- fields: [{
9566
- type: "textarea",
9567
- key: "folderRoots",
9568
- label: "Folders to walk",
9569
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9570
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
9571
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9572
- }, {
9573
- type: "number",
9574
- key: "rescanMinutes",
9575
- label: "Rescan every (minutes)",
9576
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9577
- description: "0 scans only when asked.",
9578
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9579
- min: 0
9580
- }]
9585
+ fields: [
9586
+ {
9587
+ type: "textarea",
9588
+ key: "folderRoots",
9589
+ label: "Folders to walk",
9590
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9591
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
9592
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9593
+ },
9594
+ {
9595
+ type: "number",
9596
+ key: "rescanMinutes",
9597
+ label: "Rescan every (minutes)",
9598
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9599
+ description: "0 scans only when asked.",
9600
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9601
+ min: 0
9602
+ },
9603
+ {
9604
+ type: "boolean",
9605
+ key: "trickplay",
9606
+ label: "Scrub thumbnails",
9607
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
9608
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
9609
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
9610
+ }
9611
+ ]
9581
9612
  },
9582
9613
  {
9583
9614
  id: "metadata",
@@ -9821,6 +9852,34 @@ function fillMissingKeys(rows, stored) {
9821
9852
  });
9822
9853
  }
9823
9854
  //#endregion
9855
+ //#region src/servable.ts
9856
+ /**
9857
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9858
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9859
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9860
+ */
9861
+ async function resolveServable(path, roots) {
9862
+ if (!isAbsolute(path) || path.includes("\0")) return null;
9863
+ let real;
9864
+ try {
9865
+ real = await realpath(path);
9866
+ } catch {
9867
+ return null;
9868
+ }
9869
+ for (const root of roots) {
9870
+ if (root === "") continue;
9871
+ let realRoot;
9872
+ try {
9873
+ realRoot = await realpath(root);
9874
+ } catch {
9875
+ continue;
9876
+ }
9877
+ const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9878
+ if (real.startsWith(prefix)) return real;
9879
+ }
9880
+ return null;
9881
+ }
9882
+ //#endregion
9824
9883
  //#region src/naming.ts
9825
9884
  /** Case- and accent-insensitive form of a title, for search and ordering. */
9826
9885
  function foldTitle(title) {
@@ -9878,34 +9937,6 @@ function guessFromFilename(fileName, parentDir) {
9878
9937
  };
9879
9938
  }
9880
9939
  //#endregion
9881
- //#region src/servable.ts
9882
- /**
9883
- * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9884
- * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9885
- * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9886
- */
9887
- async function resolveServable(path, roots) {
9888
- if (!isAbsolute(path) || path.includes("\0")) return null;
9889
- let real;
9890
- try {
9891
- real = await realpath(path);
9892
- } catch {
9893
- return null;
9894
- }
9895
- for (const root of roots) {
9896
- if (root === "") continue;
9897
- let realRoot;
9898
- try {
9899
- realRoot = await realpath(root);
9900
- } catch {
9901
- continue;
9902
- }
9903
- const prefix = realRoot.endsWith(sep) ? realRoot : `${realRoot}${sep}`;
9904
- if (real.startsWith(prefix)) return real;
9905
- }
9906
- return null;
9907
- }
9908
- //#endregion
9909
9940
  //#region src/file-plane.ts
9910
9941
  /**
9911
9942
  * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
@@ -9991,7 +10022,7 @@ function pump(path, start, end, res, stallMs) {
9991
10022
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9992
10023
  });
9993
10024
  }
9994
- function reject$1(res, status, extra) {
10025
+ function reject$2(res, status, extra) {
9995
10026
  res.writeHead(status, {
9996
10027
  "Content-Length": 0,
9997
10028
  ...extra
@@ -10003,18 +10034,18 @@ function createFilePlaneHandler(deps) {
10003
10034
  const stallMs = deps.stallMs ?? 3e4;
10004
10035
  return async (req, res) => {
10005
10036
  const method = req.method ?? "GET";
10006
- if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10037
+ if (method !== "GET" && method !== "HEAD") return reject$2(res, 405, { Allow: "GET, HEAD" });
10007
10038
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
10008
10039
  let itemId;
10009
10040
  try {
10010
10041
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
10011
10042
  } catch {
10012
10043
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
10013
- return reject$1(res, 404);
10044
+ return reject$2(res, 404);
10014
10045
  }
10015
10046
  if (!isItemId(itemId)) {
10016
10047
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
10017
- return reject$1(res, 404);
10048
+ return reject$2(res, 404);
10018
10049
  }
10019
10050
  const tags = { itemId };
10020
10051
  const catalogued = await deps.lookup(itemId);
@@ -10023,7 +10054,7 @@ function createFilePlaneHandler(deps) {
10023
10054
  tags,
10024
10055
  meta: { reason: "not-catalogued" }
10025
10056
  });
10026
- return reject$1(res, 404);
10057
+ return reject$2(res, 404);
10027
10058
  }
10028
10059
  const path = await resolveServable(catalogued, await deps.roots());
10029
10060
  if (path === null) {
@@ -10031,7 +10062,7 @@ function createFilePlaneHandler(deps) {
10031
10062
  tags,
10032
10063
  meta: { reason: "outside-roots" }
10033
10064
  });
10034
- return reject$1(res, 404);
10065
+ return reject$2(res, 404);
10035
10066
  }
10036
10067
  let size;
10037
10068
  try {
@@ -10041,7 +10072,7 @@ function createFilePlaneHandler(deps) {
10041
10072
  tags,
10042
10073
  meta: { reason: "gone" }
10043
10074
  });
10044
- return reject$1(res, 404);
10075
+ return reject$2(res, 404);
10045
10076
  }
10046
10077
  const range = parseRange(headerOf(req.headers.range), size);
10047
10078
  if (range.kind === "unsatisfiable") {
@@ -10052,7 +10083,7 @@ function createFilePlaneHandler(deps) {
10052
10083
  size
10053
10084
  }
10054
10085
  });
10055
- return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
10086
+ return reject$2(res, 416, { "Content-Range": `bytes */${size}` });
10056
10087
  }
10057
10088
  const start = range.kind === "range" ? range.start : 0;
10058
10089
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10185,7 +10216,7 @@ function toWebVtt(source, format, offsetMs = 0) {
10185
10216
  }
10186
10217
  return out.join("\n");
10187
10218
  }
10188
- function reject(res, status, extra) {
10219
+ function reject$1(res, status, extra) {
10189
10220
  res.writeHead(status, {
10190
10221
  "Content-Length": 0,
10191
10222
  ...extra
@@ -10204,21 +10235,21 @@ function parseOffsetMs(query) {
10204
10235
  function createSubtitlePlaneHandler(deps) {
10205
10236
  return async (req, res) => {
10206
10237
  const method = req.method ?? "GET";
10207
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10238
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10208
10239
  const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10209
10240
  const segments = rawPath.replace(/^\//, "").split("/");
10210
10241
  let itemId;
10211
10242
  let sidecar;
10212
10243
  try {
10213
- if (segments.length !== 2) return reject(res, 404);
10244
+ if (segments.length !== 2) return reject$1(res, 404);
10214
10245
  itemId = decodeURIComponent(segments[0] ?? "");
10215
10246
  sidecar = decodeURIComponent(segments[1] ?? "");
10216
10247
  } catch {
10217
- return reject(res, 404);
10248
+ return reject$1(res, 404);
10218
10249
  }
10219
10250
  if (!isItemId(itemId)) {
10220
10251
  deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10221
- return reject(res, 404);
10252
+ return reject$1(res, 404);
10222
10253
  }
10223
10254
  const tags = { itemId };
10224
10255
  const offsetMs = parseOffsetMs(query);
@@ -10227,7 +10258,7 @@ function createSubtitlePlaneHandler(deps) {
10227
10258
  tags,
10228
10259
  meta: { reason: "bad-offset" }
10229
10260
  });
10230
- return reject(res, 400);
10261
+ return reject$1(res, 400);
10231
10262
  }
10232
10263
  const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10233
10264
  if (known === void 0) {
@@ -10235,7 +10266,7 @@ function createSubtitlePlaneHandler(deps) {
10235
10266
  tags,
10236
10267
  meta: { reason: "not-a-sidecar" }
10237
10268
  });
10238
- return reject(res, 404);
10269
+ return reject$1(res, 404);
10239
10270
  }
10240
10271
  const path = await resolveServable(known.filePath, await deps.roots());
10241
10272
  if (path === null) {
@@ -10243,7 +10274,7 @@ function createSubtitlePlaneHandler(deps) {
10243
10274
  tags,
10244
10275
  meta: { reason: "outside-roots" }
10245
10276
  });
10246
- return reject(res, 404);
10277
+ return reject$1(res, 404);
10247
10278
  }
10248
10279
  try {
10249
10280
  if ((await stat(path)).size > 5242880) {
@@ -10251,7 +10282,7 @@ function createSubtitlePlaneHandler(deps) {
10251
10282
  tags,
10252
10283
  meta: { reason: "too-large" }
10253
10284
  });
10254
- return reject(res, 404);
10285
+ return reject$1(res, 404);
10255
10286
  }
10256
10287
  const body = Buffer.from(toWebVtt(await readFile(path, "utf8"), known.format, offsetMs), "utf8");
10257
10288
  res.writeHead(200, {
@@ -10274,6 +10305,408 @@ function createSubtitlePlaneHandler(deps) {
10274
10305
  tags,
10275
10306
  meta: { reason: "gone" }
10276
10307
  });
10308
+ reject$1(res, 404);
10309
+ }
10310
+ };
10311
+ }
10312
+ var TILES_PER_SHEET = 100;
10313
+ var GENERATE_TIMEOUT_MS = 3600 * 1e3;
10314
+ var INDEX_NAME = "index.vtt";
10315
+ /** The names a client may ask for inside one item's trickplay folder. */
10316
+ var TRICKPLAY_FILE_NAME = /^(?:index\.vtt|sprite-\d{1,4}\.jpg)$/;
10317
+ var FailureSchema = object({
10318
+ at: number(),
10319
+ attempts: number().int(),
10320
+ reason: string()
10321
+ });
10322
+ /** The height of one tile for a picture of this shape; even, as the encoder wants. */
10323
+ function tileHeightOf(width, height) {
10324
+ return Math.max(2, Math.round(320 * height / width / 2) * 2);
10325
+ }
10326
+ /** The ffmpeg arguments: one frame per interval, scaled, tiled into sheets of the grid, one JPEG per sheet. */
10327
+ function trickplayArgs(job) {
10328
+ return [
10329
+ "-hide_banner",
10330
+ "-nostdin",
10331
+ "-loglevel",
10332
+ "error",
10333
+ "-threads",
10334
+ "1",
10335
+ "-i",
10336
+ `file:${job.inputPath}`,
10337
+ "-an",
10338
+ "-sn",
10339
+ "-vf",
10340
+ `fps=1/10,scale=320:${job.tileHeight},tile=10x10`,
10341
+ "-q:v",
10342
+ "6",
10343
+ "-start_number",
10344
+ "0",
10345
+ join(job.outDir, "sprite-%d.jpg")
10346
+ ];
10347
+ }
10348
+ /** ffmpeg at the lowest priority (`nice`, where there is one), so a scrub image never takes a stream's CPU. */
10349
+ function createFfmpegTrickplayGenerator(binaryPath) {
10350
+ return (job) => new Promise((done, reject) => {
10351
+ const args = trickplayArgs(job);
10352
+ const [command, argv] = process.platform === "win32" ? [binaryPath, args] : ["nice", [
10353
+ "-n",
10354
+ "19",
10355
+ binaryPath,
10356
+ ...args
10357
+ ]];
10358
+ execFile(command, argv, {
10359
+ timeout: GENERATE_TIMEOUT_MS,
10360
+ maxBuffer: 1024 * 1024,
10361
+ encoding: "utf8"
10362
+ }, (error, _stdout, stderr) => {
10363
+ if (error === null) done();
10364
+ else reject(new Error(error.killed === true ? "ffmpeg timed out" : stderr.slice(0, 300) || error.message));
10365
+ });
10366
+ });
10367
+ }
10368
+ function timestamp(seconds) {
10369
+ const totalMs = Math.round(seconds * 1e3);
10370
+ const pad = (value, width) => String(value).padStart(width, "0");
10371
+ return `${pad(Math.floor(totalMs / 36e5), 2)}:${pad(Math.floor(totalMs / 6e4) % 60, 2)}:${pad(Math.floor(totalMs / 1e3) % 60, 2)}.${pad(totalMs % 1e3, 3)}`;
10372
+ }
10373
+ /** The WebVTT index: one cue per interval, each pointing at its tile as `sprite-N.jpg#xywh=x,y,w,h`. */
10374
+ function buildTrickplayVtt(durationSec, tileHeight) {
10375
+ const frames = Math.ceil(durationSec / 10);
10376
+ const lines = ["WEBVTT", ""];
10377
+ for (let index = 0; index < frames; index += 1) {
10378
+ const slot = index % TILES_PER_SHEET;
10379
+ const x = slot % 10 * 320;
10380
+ const y = Math.floor(slot / 10) * tileHeight;
10381
+ const start = index * 10;
10382
+ const end = Math.min((index + 1) * 10, durationSec);
10383
+ lines.push(`${timestamp(start)} --> ${timestamp(end)}`, `sprite-${Math.floor(index / TILES_PER_SHEET)}.jpg#xywh=${x},${y},320,${tileHeight}`, "");
10384
+ }
10385
+ return lines.join("\n");
10386
+ }
10387
+ function fingerprintOf(source) {
10388
+ return `${source.sizeBytes}-${source.mtimeMs}`;
10389
+ }
10390
+ /** An item id is `source:kind:key`; the colons become underscores so the folder name is portable. */
10391
+ function folderOf(itemId) {
10392
+ return itemId.replaceAll(":", "_");
10393
+ }
10394
+ /**
10395
+ * The trickplay cache: sprite sheets and a WebVTT index per item, under the addon's data dir, keyed by the
10396
+ * file's size and mtime (a changed file generates anew). One ffmpeg at a time, in the background.
10397
+ */
10398
+ var TrickplayService = class {
10399
+ deps;
10400
+ queue = [];
10401
+ queued = /* @__PURE__ */ new Set();
10402
+ running = false;
10403
+ /** Files found outside the library roots: remembered (until restart) so they are not queued again. */
10404
+ outsideRoots = /* @__PURE__ */ new Set();
10405
+ idle = Promise.resolve();
10406
+ constructor(deps) {
10407
+ this.deps = deps;
10408
+ }
10409
+ keyOf(source) {
10410
+ return `${source.itemId}\u0000${fingerprintOf(source)}`;
10411
+ }
10412
+ itemDir(source) {
10413
+ return join(this.deps.cacheDir, folderOf(source.itemId));
10414
+ }
10415
+ readyDir(source) {
10416
+ return join(this.itemDir(source), fingerprintOf(source));
10417
+ }
10418
+ failurePath(source) {
10419
+ return join(this.itemDir(source), `${fingerprintOf(source)}.failed.json`);
10420
+ }
10421
+ /** The reason this file cannot have trickplay, or `null` when it can. */
10422
+ skipReason(source) {
10423
+ if (source.durationMs === null || source.durationMs <= 0) return "no-duration";
10424
+ if (source.durationMs / 1e3 < 30) return "too-short";
10425
+ if (source.width === null || source.height === null || source.width <= 0 || source.height <= 0) return "no-video-size";
10426
+ return null;
10427
+ }
10428
+ async readFailure(source) {
10429
+ try {
10430
+ return FailureSchema.parse(JSON.parse(await readFile(this.failurePath(source), "utf8")));
10431
+ } catch {
10432
+ return null;
10433
+ }
10434
+ }
10435
+ async isReady(source) {
10436
+ try {
10437
+ return (await stat(join(this.readyDir(source), INDEX_NAME))).isFile();
10438
+ } catch {
10439
+ return false;
10440
+ }
10441
+ }
10442
+ /**
10443
+ * What a client may be told about `source`, and (when nothing is ready) a request for the work: a run
10444
+ * is queued unless one is queued already, it failed for good, or it failed too recently to try again.
10445
+ */
10446
+ async request(source, basePath) {
10447
+ const tags = { itemId: source.itemId };
10448
+ if (!this.deps.enabled()) return {
10449
+ status: "disabled",
10450
+ path: null
10451
+ };
10452
+ if (await this.isReady(source)) return {
10453
+ status: "ready",
10454
+ path: `${basePath}/${INDEX_NAME}`
10455
+ };
10456
+ if (this.outsideRoots.has(this.keyOf(source))) return {
10457
+ status: "skipped",
10458
+ path: null
10459
+ };
10460
+ const skip = this.skipReason(source);
10461
+ if (skip !== null) {
10462
+ this.deps.logger.debug("trickplay not generated", {
10463
+ tags,
10464
+ meta: { reason: skip }
10465
+ });
10466
+ return {
10467
+ status: "skipped",
10468
+ path: null
10469
+ };
10470
+ }
10471
+ const failure = await this.readFailure(source);
10472
+ if (failure !== null) {
10473
+ if (failure.attempts >= 3) return {
10474
+ status: "failed",
10475
+ path: null
10476
+ };
10477
+ if (this.deps.now() - failure.at < 216e5) return {
10478
+ status: "failed",
10479
+ path: null
10480
+ };
10481
+ }
10482
+ this.enqueue(source);
10483
+ return {
10484
+ status: "pending",
10485
+ path: null
10486
+ };
10487
+ }
10488
+ /** Queue one file; a second request for the same file while it waits or runs changes nothing. */
10489
+ enqueue(source) {
10490
+ const key = `${source.itemId}\u0000${fingerprintOf(source)}`;
10491
+ if (this.queued.has(key)) return;
10492
+ this.queued.add(key);
10493
+ this.queue.push(source);
10494
+ this.deps.logger.debug("trickplay queued", {
10495
+ tags: { itemId: source.itemId },
10496
+ meta: { waiting: this.queue.length }
10497
+ });
10498
+ if (!this.running) {
10499
+ this.running = true;
10500
+ this.idle = this.drain();
10501
+ }
10502
+ }
10503
+ /** Resolves when the queue is empty and nothing runs. */
10504
+ settled() {
10505
+ return this.idle;
10506
+ }
10507
+ async drain() {
10508
+ try {
10509
+ for (let next = this.queue.shift(); next !== void 0; next = this.queue.shift()) try {
10510
+ await this.generateOne(next);
10511
+ } catch (error) {
10512
+ this.deps.logger.warn("trickplay run aborted", {
10513
+ tags: { itemId: next.itemId },
10514
+ meta: { reason: error instanceof Error ? error.message : String(error) }
10515
+ });
10516
+ } finally {
10517
+ this.queued.delete(`${next.itemId}\u0000${fingerprintOf(next)}`);
10518
+ }
10519
+ } finally {
10520
+ this.running = false;
10521
+ }
10522
+ }
10523
+ async generateOne(source) {
10524
+ const tags = { itemId: source.itemId };
10525
+ const { logger } = this.deps;
10526
+ if (!this.deps.enabled()) {
10527
+ logger.info("trickplay skipped", {
10528
+ tags,
10529
+ meta: { reason: "disabled" }
10530
+ });
10531
+ return;
10532
+ }
10533
+ if (await this.isReady(source)) return;
10534
+ const skip = this.skipReason(source);
10535
+ if (skip !== null || source.width === null || source.height === null || source.durationMs === null) {
10536
+ logger.info("trickplay skipped", {
10537
+ tags,
10538
+ meta: { reason: skip ?? "no-video-size" }
10539
+ });
10540
+ return;
10541
+ }
10542
+ const attempts = ((await this.readFailure(source))?.attempts ?? 0) + 1;
10543
+ if (!await this.deps.inRoots(source.path)) {
10544
+ this.outsideRoots.add(this.keyOf(source));
10545
+ logger.warn("trickplay skipped", {
10546
+ tags,
10547
+ meta: { reason: "outside-roots" }
10548
+ });
10549
+ return;
10550
+ }
10551
+ const finalDir = this.readyDir(source);
10552
+ const workDir = `${finalDir}.work`;
10553
+ const tileHeight = tileHeightOf(source.width, source.height);
10554
+ const startedAt = this.deps.now();
10555
+ try {
10556
+ await rm(workDir, {
10557
+ recursive: true,
10558
+ force: true
10559
+ });
10560
+ await mkdir(workDir, { recursive: true });
10561
+ await this.deps.generate({
10562
+ inputPath: source.path,
10563
+ outDir: workDir,
10564
+ tileHeight
10565
+ });
10566
+ const sheets = (await readdir(workDir)).filter((name) => /^sprite-\d+\.jpg$/.test(name));
10567
+ if (sheets.length === 0) throw new Error("ffmpeg wrote no sprite sheet");
10568
+ await writeFile(join(workDir, INDEX_NAME), buildTrickplayVtt(source.durationMs / 1e3, tileHeight), "utf8");
10569
+ await rm(finalDir, {
10570
+ recursive: true,
10571
+ force: true
10572
+ });
10573
+ await rename(workDir, finalDir);
10574
+ await rm(this.failurePath(source), { force: true });
10575
+ await this.pruneOthers(source);
10576
+ logger.info("trickplay generated", {
10577
+ tags,
10578
+ meta: {
10579
+ sheets: sheets.length,
10580
+ tileHeight,
10581
+ tookMs: this.deps.now() - startedAt
10582
+ }
10583
+ });
10584
+ } catch (error) {
10585
+ const reason = error instanceof Error ? error.message : String(error);
10586
+ try {
10587
+ await rm(workDir, {
10588
+ recursive: true,
10589
+ force: true
10590
+ });
10591
+ await mkdir(this.itemDir(source), { recursive: true });
10592
+ await writeFile(this.failurePath(source), JSON.stringify({
10593
+ at: this.deps.now(),
10594
+ attempts,
10595
+ reason
10596
+ }), "utf8");
10597
+ } catch (writeError) {
10598
+ logger.warn("trickplay failure could not be recorded", {
10599
+ tags,
10600
+ meta: { error: writeError instanceof Error ? writeError.message : String(writeError) }
10601
+ });
10602
+ }
10603
+ logger.warn("trickplay failed", {
10604
+ tags,
10605
+ meta: {
10606
+ reason,
10607
+ attempts,
10608
+ retry: attempts < 3
10609
+ }
10610
+ });
10611
+ }
10612
+ }
10613
+ /** A changed file leaves its old fingerprint behind: drop every other fingerprint of the item. */
10614
+ async pruneOthers(source) {
10615
+ const keep = fingerprintOf(source);
10616
+ for (const name of await readdir(this.itemDir(source))) if (name !== keep && name !== `${keep}.failed.json`) await rm(join(this.itemDir(source), name), {
10617
+ recursive: true,
10618
+ force: true
10619
+ });
10620
+ }
10621
+ /** The absolute path of a ready file of `source`'s current fingerprint, or `null` when it is not there. */
10622
+ async fileFor(source, name) {
10623
+ if (!TRICKPLAY_FILE_NAME.test(name)) return null;
10624
+ const path = join(this.readyDir(source), name);
10625
+ try {
10626
+ return (await stat(path)).isFile() ? path : null;
10627
+ } catch {
10628
+ return null;
10629
+ }
10630
+ }
10631
+ };
10632
+ //#endregion
10633
+ //#region src/trickplay-plane.ts
10634
+ function reject(res, status, extra) {
10635
+ res.writeHead(status, {
10636
+ "Content-Length": 0,
10637
+ ...extra
10638
+ });
10639
+ res.end();
10640
+ }
10641
+ /** The `trickplay` plane: `GET|HEAD /<itemId>/index.vtt` and `/<itemId>/sprite-<n>.jpg`. */
10642
+ function createTrickplayPlaneHandler(deps) {
10643
+ return async (req, res) => {
10644
+ const method = req.method ?? "GET";
10645
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10646
+ const segments = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
10647
+ let itemId;
10648
+ let name;
10649
+ try {
10650
+ if (segments.length !== 2) return reject(res, 404);
10651
+ itemId = decodeURIComponent(segments[0] ?? "");
10652
+ name = decodeURIComponent(segments[1] ?? "");
10653
+ } catch {
10654
+ return reject(res, 404);
10655
+ }
10656
+ if (!isItemId(itemId)) {
10657
+ deps.logger.warn("trickplay request refused: not an item id", { meta: { reason: "bad-id" } });
10658
+ return reject(res, 404);
10659
+ }
10660
+ const tags = { itemId };
10661
+ if (!TRICKPLAY_FILE_NAME.test(name)) {
10662
+ deps.logger.info("trickplay request refused: not a trickplay file", {
10663
+ tags,
10664
+ meta: { reason: "bad-name" }
10665
+ });
10666
+ return reject(res, 404);
10667
+ }
10668
+ const source = await deps.source(itemId);
10669
+ if (source === null) {
10670
+ deps.logger.info("trickplay request refused: the item has no file", {
10671
+ tags,
10672
+ meta: { reason: "no-file" }
10673
+ });
10674
+ return reject(res, 404);
10675
+ }
10676
+ if (await resolveServable(source.path, await deps.roots()) === null) {
10677
+ deps.logger.warn("trickplay request refused: outside the library roots", {
10678
+ tags,
10679
+ meta: { reason: "outside-roots" }
10680
+ });
10681
+ return reject(res, 404);
10682
+ }
10683
+ const path = await deps.cache.fileFor(source, name);
10684
+ if (path === null) {
10685
+ deps.logger.info("trickplay request refused: not generated yet", {
10686
+ tags,
10687
+ meta: { reason: "not-ready" }
10688
+ });
10689
+ return reject(res, 404);
10690
+ }
10691
+ try {
10692
+ const body = await readFile(path);
10693
+ const isIndex = name === "index.vtt";
10694
+ res.writeHead(200, {
10695
+ "Content-Type": isIndex ? "text/vtt; charset=utf-8" : "image/jpeg",
10696
+ "Content-Length": body.length,
10697
+ "Cache-Control": isIndex ? "private, no-store" : "private, max-age=3600"
10698
+ });
10699
+ if (method === "HEAD") res.end();
10700
+ else res.end(body);
10701
+ deps.logger.debug("trickplay served", {
10702
+ tags,
10703
+ meta: { name }
10704
+ });
10705
+ } catch {
10706
+ deps.logger.warn("trickplay request refused: file vanished", {
10707
+ tags,
10708
+ meta: { reason: "gone" }
10709
+ });
10277
10710
  reject(res, 404);
10278
10711
  }
10279
10712
  };
@@ -11288,6 +11721,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
11288
11721
  }
11289
11722
  var FILE_PLANE_PREFIX = "file";
11290
11723
  var SUBTITLE_PLANE_PREFIX = "subtitle";
11724
+ var TRICKPLAY_PLANE_PREFIX = "trickplay";
11291
11725
  var HUB_PLANE_BASE = "/addon/media-library";
11292
11726
  var SEARCH_DEFAULT_LIMIT = 50;
11293
11727
  var RECENT_DEFAULT_LIMIT = 20;
@@ -11302,6 +11736,10 @@ function playPathOf(itemId) {
11302
11736
  function subtitlePathOf(itemId, sidecarId) {
11303
11737
  return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11304
11738
  }
11739
+ /** The base of one item's trickplay files: `<base>/index.vtt`, `<base>/sprite-<n>.jpg`. */
11740
+ function trickplayBaseOf(itemId) {
11741
+ return `${HUB_PLANE_BASE}/${TRICKPLAY_PLANE_PREFIX}/${itemId}`;
11742
+ }
11305
11743
  function imagePathOf(itemId, which) {
11306
11744
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
11307
11745
  }
@@ -11323,13 +11761,15 @@ var LibraryStore = class {
11323
11761
  serverLanguage;
11324
11762
  now;
11325
11763
  listDir;
11764
+ trickplay;
11326
11765
  locks = /* @__PURE__ */ new Map();
11327
- constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
11766
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir, trickplay = null) {
11328
11767
  this.db = db;
11329
11768
  this.logger = logger;
11330
11769
  this.serverLanguage = serverLanguage;
11331
11770
  this.now = now;
11332
11771
  this.listDir = listDir;
11772
+ this.trickplay = trickplay;
11333
11773
  }
11334
11774
  async init() {
11335
11775
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11503,9 +11943,26 @@ var LibraryStore = class {
11503
11943
  format: sidecar.format,
11504
11944
  label: sidecar.label,
11505
11945
  path: subtitlePathOf(row.id, sidecar.id)
11506
- }))
11946
+ })),
11947
+ trickplay: file === void 0 || this.trickplay === null ? null : await this.trickplay.request(trickplaySourceOf(row.id, file), trickplayBaseOf(row.id))
11507
11948
  };
11508
11949
  }
11950
+ /** The catalogued file of `itemId` as the trickplay cache sees it; `null` when it has none. */
11951
+ async trickplaySource(itemId) {
11952
+ const catalogued = await this.playableFile(itemId);
11953
+ return catalogued === null ? null : trickplaySourceOf(itemId, catalogued.row);
11954
+ }
11955
+ /** Every catalogued file, for the sweep after a scan. */
11956
+ async trickplaySources() {
11957
+ const items = await this.queryAllItems();
11958
+ const files = new Map(parseRows(FileRowSchema, await queryAll(this.db, FILES, "path", {}), this.invalid(FILES)).map((file) => [file.path, file]));
11959
+ const sources = [];
11960
+ for (const item of items) {
11961
+ const file = item.filePath === null ? void 0 : files.get(item.filePath);
11962
+ if (file !== void 0) sources.push(trickplaySourceOf(item.id, file));
11963
+ }
11964
+ return sources;
11965
+ }
11509
11966
  /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11510
11967
  async subtitleSidecars(itemId) {
11511
11968
  const catalogued = await this.playableFile(itemId);
@@ -11807,6 +12264,18 @@ var LibraryStore = class {
11807
12264
  return entries;
11808
12265
  }
11809
12266
  };
12267
+ function trickplaySourceOf(itemId, file) {
12268
+ const video = file.streams.find((stream) => stream.kind === "video");
12269
+ return {
12270
+ itemId,
12271
+ path: file.path,
12272
+ sizeBytes: file.sizeBytes,
12273
+ mtimeMs: file.mtimeMs,
12274
+ durationMs: file.probeOk ? file.durationMs : null,
12275
+ width: video?.width ?? null,
12276
+ height: video?.height ?? null
12277
+ };
12278
+ }
11810
12279
  async function defaultListDir(dir) {
11811
12280
  try {
11812
12281
  return new Map((await readdir(dir)).map((name) => [name.toLowerCase(), name]));
@@ -15115,6 +15584,7 @@ var ScanController = class {
15115
15584
  deps;
15116
15585
  sources;
15117
15586
  logger;
15587
+ afterScan;
15118
15588
  running = false;
15119
15589
  last = {
15120
15590
  running: false,
@@ -15127,10 +15597,11 @@ var ScanController = class {
15127
15597
  skipped: 0
15128
15598
  };
15129
15599
  timer = null;
15130
- constructor(deps, sources, logger) {
15600
+ constructor(deps, sources, logger, afterScan = async () => {}) {
15131
15601
  this.deps = deps;
15132
15602
  this.sources = sources;
15133
15603
  this.logger = logger;
15604
+ this.afterScan = afterScan;
15134
15605
  }
15135
15606
  status() {
15136
15607
  return {
@@ -15160,6 +15631,11 @@ var ScanController = class {
15160
15631
  } finally {
15161
15632
  this.running = false;
15162
15633
  }
15634
+ try {
15635
+ await this.afterScan();
15636
+ } catch (error) {
15637
+ this.logger.warn("after-scan work failed", { meta: { error: String(error) } });
15638
+ }
15163
15639
  }
15164
15640
  /** (Re)arm the rescan timer; `0` minutes turns it off. */
15165
15641
  schedule(minutes) {
@@ -15181,8 +15657,11 @@ var ScanController = class {
15181
15657
  * place in every item is kept here. Bytes leave through two data-plane routes served by item id.
15182
15658
  */
15183
15659
  var IMG_CACHE_DIR = "img-cache";
15660
+ var TRICKPLAY_CACHE_DIR = "trickplay";
15184
15661
  var MediaLibraryAddon = class extends BaseAddon {
15185
15662
  scans = null;
15663
+ /** The trickplay switch, held in memory: the generator reads it off the settings path. */
15664
+ trickplayOn = true;
15186
15665
  constructor() {
15187
15666
  super({});
15188
15667
  }
@@ -15197,6 +15676,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15197
15676
  }
15198
15677
  async onScopedSettingsChanged() {
15199
15678
  const settings = await this.readSettings();
15679
+ this.trickplayOn = settings.trickplay;
15200
15680
  this.scans?.schedule(settings.rescanMinutes);
15201
15681
  this.scans?.start("settings");
15202
15682
  }
@@ -15252,9 +15732,26 @@ var MediaLibraryAddon = class extends BaseAddon {
15252
15732
  const db = settingsStoreDb(ctx.api.settingsStore);
15253
15733
  const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
15254
15734
  await serverLanguage.refresh();
15255
- const store = new LibraryStore(db, logger, () => serverLanguage.current());
15256
- await store.init();
15257
15735
  const ffmpeg = await ctx.deps.ensureFfmpeg();
15736
+ const roots = async () => {
15737
+ const settings = await this.readSettings();
15738
+ return [
15739
+ ...resolveSources(settings).folderRoots,
15740
+ settings.seriesPathTo || settings.seriesPathFrom,
15741
+ settings.moviesPathTo || settings.moviesPathFrom
15742
+ ].filter((root) => root !== "");
15743
+ };
15744
+ this.trickplayOn = (await this.readSettings()).trickplay;
15745
+ const trickplay = new TrickplayService({
15746
+ cacheDir: join(ctx.dataDir, TRICKPLAY_CACHE_DIR),
15747
+ generate: createFfmpegTrickplayGenerator(ffmpeg),
15748
+ enabled: () => this.trickplayOn,
15749
+ inRoots: async (path) => await resolveServable(path, await roots()) !== null,
15750
+ logger,
15751
+ now: () => Date.now()
15752
+ });
15753
+ const store = new LibraryStore(db, logger, () => serverLanguage.current(), void 0, void 0, trickplay);
15754
+ await store.init();
15258
15755
  const scans = new ScanController({
15259
15756
  db,
15260
15757
  logger,
@@ -15296,7 +15793,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15296
15793
  }),
15297
15794
  createAnilist: () => createAnilistProvider({ fetch: httpRemoteFetch }),
15298
15795
  now: () => Date.now()
15299
- }, async () => resolveSources(await this.readSettings()), logger);
15796
+ }, async () => resolveSources(await this.readSettings()), logger, async () => {
15797
+ if (!this.trickplayOn) return;
15798
+ for (const source of await store.trickplaySources()) await trickplay.request(source, trickplayBaseOf(source.itemId));
15799
+ });
15300
15800
  this.scans = scans;
15301
15801
  const plexImports = new PlexImportController(logger, () => Date.now());
15302
15802
  const startPlex = async (mode) => {
@@ -15324,14 +15824,6 @@ var MediaLibraryAddon = class extends BaseAddon {
15324
15824
  message: started ? `Plex ${mode === "run" ? "import" : "preview"} started: read the report with plexImportStatus` : "A Plex import is already running"
15325
15825
  };
15326
15826
  };
15327
- const roots = async () => {
15328
- const settings = await this.readSettings();
15329
- return [
15330
- ...resolveSources(settings).folderRoots,
15331
- settings.seriesPathTo || settings.seriesPathFrom,
15332
- settings.moviesPathTo || settings.moviesPathFrom
15333
- ].filter((root) => root !== "");
15334
- };
15335
15827
  await ctx.dataPlane?.serve({
15336
15828
  prefix: FILE_PLANE_PREFIX,
15337
15829
  access: "viewer",
@@ -15350,6 +15842,16 @@ var MediaLibraryAddon = class extends BaseAddon {
15350
15842
  logger
15351
15843
  })
15352
15844
  });
15845
+ await ctx.dataPlane?.serve({
15846
+ prefix: TRICKPLAY_PLANE_PREFIX,
15847
+ access: "viewer",
15848
+ handler: createTrickplayPlaneHandler({
15849
+ source: (itemId) => store.trickplaySource(itemId),
15850
+ cache: trickplay,
15851
+ roots,
15852
+ logger
15853
+ })
15854
+ });
15353
15855
  await ctx.dataPlane?.serve({
15354
15856
  prefix: "img",
15355
15857
  access: "viewer",