@dominevo/addon-media-library 0.1.10 → 0.1.12

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.
@@ -2894,7 +2894,7 @@ function initializeContext(params) {
2894
2894
  external: params?.external ?? void 0
2895
2895
  };
2896
2896
  }
2897
- function process(schema, ctx, _params = {
2897
+ function process$1(schema, ctx, _params = {
2898
2898
  path: [],
2899
2899
  schemaPath: []
2900
2900
  }) {
@@ -2931,7 +2931,7 @@ function process(schema, ctx, _params = {
2931
2931
  const parent = schema._zod.parent;
2932
2932
  if (parent) {
2933
2933
  if (!result.ref) result.ref = parent;
2934
- process(parent, ctx, params);
2934
+ process$1(parent, ctx, params);
2935
2935
  ctx.seen.get(parent).isParent = true;
2936
2936
  }
2937
2937
  }
@@ -3151,7 +3151,7 @@ var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
3151
3151
  ...params,
3152
3152
  processors
3153
3153
  });
3154
- process(schema, ctx);
3154
+ process$1(schema, ctx);
3155
3155
  extractDefs(ctx, schema);
3156
3156
  return finalize(ctx, schema);
3157
3157
  };
@@ -3163,7 +3163,7 @@ var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) =
3163
3163
  io,
3164
3164
  processors
3165
3165
  });
3166
- process(schema, ctx);
3166
+ process$1(schema, ctx);
3167
3167
  extractDefs(ctx, schema);
3168
3168
  return finalize(ctx, schema);
3169
3169
  };
@@ -3267,7 +3267,7 @@ var arrayProcessor = (schema, ctx, _json, params) => {
3267
3267
  if (typeof minimum === "number") json.minItems = minimum;
3268
3268
  if (typeof maximum === "number") json.maxItems = maximum;
3269
3269
  json.type = "array";
3270
- json.items = process(def.element, ctx, {
3270
+ json.items = process$1(def.element, ctx, {
3271
3271
  ...params,
3272
3272
  path: [...params.path, "items"]
3273
3273
  });
@@ -3278,7 +3278,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3278
3278
  json.type = "object";
3279
3279
  json.properties = {};
3280
3280
  const shape = def.shape;
3281
- for (const key in shape) json.properties[key] = process(shape[key], ctx, {
3281
+ for (const key in shape) json.properties[key] = process$1(shape[key], ctx, {
3282
3282
  ...params,
3283
3283
  path: [
3284
3284
  ...params.path,
@@ -3296,7 +3296,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3296
3296
  if (def.catchall?._zod.def.type === "never") json.additionalProperties = false;
3297
3297
  else if (!def.catchall) {
3298
3298
  if (ctx.io === "output") json.additionalProperties = false;
3299
- } else if (def.catchall) json.additionalProperties = process(def.catchall, ctx, {
3299
+ } else if (def.catchall) json.additionalProperties = process$1(def.catchall, ctx, {
3300
3300
  ...params,
3301
3301
  path: [...params.path, "additionalProperties"]
3302
3302
  });
@@ -3304,7 +3304,7 @@ var objectProcessor = (schema, ctx, _json, params) => {
3304
3304
  var unionProcessor = (schema, ctx, json, params) => {
3305
3305
  const def = schema._zod.def;
3306
3306
  const isExclusive = def.inclusive === false;
3307
- const options = def.options.map((x, i) => process(x, ctx, {
3307
+ const options = def.options.map((x, i) => process$1(x, ctx, {
3308
3308
  ...params,
3309
3309
  path: [
3310
3310
  ...params.path,
@@ -3317,7 +3317,7 @@ var unionProcessor = (schema, ctx, json, params) => {
3317
3317
  };
3318
3318
  var intersectionProcessor = (schema, ctx, json, params) => {
3319
3319
  const def = schema._zod.def;
3320
- const a = process(def.left, ctx, {
3320
+ const a = process$1(def.left, ctx, {
3321
3321
  ...params,
3322
3322
  path: [
3323
3323
  ...params.path,
@@ -3325,7 +3325,7 @@ var intersectionProcessor = (schema, ctx, json, params) => {
3325
3325
  0
3326
3326
  ]
3327
3327
  });
3328
- const b = process(def.right, ctx, {
3328
+ const b = process$1(def.right, ctx, {
3329
3329
  ...params,
3330
3330
  path: [
3331
3331
  ...params.path,
@@ -3343,7 +3343,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3343
3343
  const keyType = def.keyType;
3344
3344
  const patterns = keyType._zod.bag?.patterns;
3345
3345
  if (def.mode === "loose" && patterns && patterns.size > 0) {
3346
- const valueSchema = process(def.valueType, ctx, {
3346
+ const valueSchema = process$1(def.valueType, ctx, {
3347
3347
  ...params,
3348
3348
  path: [
3349
3349
  ...params.path,
@@ -3354,11 +3354,11 @@ var recordProcessor = (schema, ctx, _json, params) => {
3354
3354
  json.patternProperties = {};
3355
3355
  for (const pattern of patterns) json.patternProperties[pattern.source] = valueSchema;
3356
3356
  } else {
3357
- if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process(def.keyType, ctx, {
3357
+ if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") json.propertyNames = process$1(def.keyType, ctx, {
3358
3358
  ...params,
3359
3359
  path: [...params.path, "propertyNames"]
3360
3360
  });
3361
- json.additionalProperties = process(def.valueType, ctx, {
3361
+ json.additionalProperties = process$1(def.valueType, ctx, {
3362
3362
  ...params,
3363
3363
  path: [...params.path, "additionalProperties"]
3364
3364
  });
@@ -3371,7 +3371,7 @@ var recordProcessor = (schema, ctx, _json, params) => {
3371
3371
  };
3372
3372
  var nullableProcessor = (schema, ctx, json, params) => {
3373
3373
  const def = schema._zod.def;
3374
- const inner = process(def.innerType, ctx, params);
3374
+ const inner = process$1(def.innerType, ctx, params);
3375
3375
  const seen = ctx.seen.get(schema);
3376
3376
  if (ctx.target === "openapi-3.0") {
3377
3377
  seen.ref = def.innerType;
@@ -3380,27 +3380,27 @@ var nullableProcessor = (schema, ctx, json, params) => {
3380
3380
  };
3381
3381
  var nonoptionalProcessor = (schema, ctx, _json, params) => {
3382
3382
  const def = schema._zod.def;
3383
- process(def.innerType, ctx, params);
3383
+ process$1(def.innerType, ctx, params);
3384
3384
  const seen = ctx.seen.get(schema);
3385
3385
  seen.ref = def.innerType;
3386
3386
  };
3387
3387
  var defaultProcessor = (schema, ctx, json, params) => {
3388
3388
  const def = schema._zod.def;
3389
- process(def.innerType, ctx, params);
3389
+ process$1(def.innerType, ctx, params);
3390
3390
  const seen = ctx.seen.get(schema);
3391
3391
  seen.ref = def.innerType;
3392
3392
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
3393
3393
  };
3394
3394
  var prefaultProcessor = (schema, ctx, json, params) => {
3395
3395
  const def = schema._zod.def;
3396
- process(def.innerType, ctx, params);
3396
+ process$1(def.innerType, ctx, params);
3397
3397
  const seen = ctx.seen.get(schema);
3398
3398
  seen.ref = def.innerType;
3399
3399
  if (ctx.io === "input") json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
3400
3400
  };
3401
3401
  var catchProcessor = (schema, ctx, json, params) => {
3402
3402
  const def = schema._zod.def;
3403
- process(def.innerType, ctx, params);
3403
+ process$1(def.innerType, ctx, params);
3404
3404
  const seen = ctx.seen.get(schema);
3405
3405
  seen.ref = def.innerType;
3406
3406
  let catchValue;
@@ -3415,20 +3415,20 @@ var pipeProcessor = (schema, ctx, _json, params) => {
3415
3415
  const def = schema._zod.def;
3416
3416
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
3417
3417
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
3418
- process(innerType, ctx, params);
3418
+ process$1(innerType, ctx, params);
3419
3419
  const seen = ctx.seen.get(schema);
3420
3420
  seen.ref = innerType;
3421
3421
  };
3422
3422
  var readonlyProcessor = (schema, ctx, json, params) => {
3423
3423
  const def = schema._zod.def;
3424
- process(def.innerType, ctx, params);
3424
+ process$1(def.innerType, ctx, params);
3425
3425
  const seen = ctx.seen.get(schema);
3426
3426
  seen.ref = def.innerType;
3427
3427
  json.readOnly = true;
3428
3428
  };
3429
3429
  var optionalProcessor = (schema, ctx, _json, params) => {
3430
3430
  const def = schema._zod.def;
3431
- process(def.innerType, ctx, params);
3431
+ process$1(def.innerType, ctx, params);
3432
3432
  const seen = ctx.seen.get(schema);
3433
3433
  seen.ref = def.innerType;
3434
3434
  };
@@ -8869,6 +8869,22 @@ var ExternalSubtitleSchema = /* @__PURE__ */ object({
8869
8869
  label: /* @__PURE__ */ string(),
8870
8870
  path: /* @__PURE__ */ string()
8871
8871
  });
8872
+ /**
8873
+ * Scrub thumbnails of the file. `path` is the relative hub path of the WebVTT index (cues point at
8874
+ * `sprite-N.jpg#xywh=x,y,w,h` beside it), set only when `status` is `ready`. `pending`: being generated in the
8875
+ * background, ask again later; `failed`: ffmpeg could not; `skipped`: the file has no duration or is too short;
8876
+ * `disabled`: the installation turned generation off.
8877
+ */
8878
+ var MediaTrickplaySchema = /* @__PURE__ */ object({
8879
+ status: /* @__PURE__ */ _enum([
8880
+ "ready",
8881
+ "pending",
8882
+ "failed",
8883
+ "skipped",
8884
+ "disabled"
8885
+ ]),
8886
+ path: /* @__PURE__ */ string().nullable()
8887
+ });
8872
8888
  var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8873
8889
  overview: /* @__PURE__ */ string().nullable(),
8874
8890
  ids: /* @__PURE__ */ object({
@@ -8883,7 +8899,9 @@ var MediaItemDetailSchema = /* @__PURE__ */ MediaItemSummarySchema.extend({
8883
8899
  /** The file's chapters in order; empty when it has none or it is not probed yet. */
8884
8900
  chapters: /* @__PURE__ */ array(MediaChapterSchema).readonly(),
8885
8901
  /** Sidecar subtitle files found next to the video; empty when none. */
8886
- externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly()
8902
+ externalSubtitles: /* @__PURE__ */ array(ExternalSubtitleSchema).readonly(),
8903
+ /** Scrub thumbnails of the file; `null` when the item has no file. */
8904
+ trickplay: /* @__PURE__ */ MediaTrickplaySchema.nullable()
8887
8905
  });
8888
8906
  /**
8889
8907
  * A person of an item's credits. `photoPath` is an image-plane handle relative to the hub origin
@@ -9448,6 +9466,8 @@ var MediaLibrarySettingsSchema = object({
9448
9466
  /** Plain folders walked for files the arr apps do not know, one absolute path per line. */
9449
9467
  folderRoots: string().default(""),
9450
9468
  rescanMinutes: number().int().min(0).default(60),
9469
+ /** Scrub thumbnails, generated in the background with ffmpeg and cached under the addon's data dir. */
9470
+ trickplay: boolean().default(true),
9451
9471
  /** The metadata chain, one row per step in the order they answer; the first answer to a field wins (D1125). */
9452
9472
  metadataProviders: array(MetadataProviderRowSchema).default(defaultProviderRows),
9453
9473
  /** The Plex import (a one-shot, re-runnable action): the server, a token, and how paths and users line up. */
@@ -9566,22 +9586,33 @@ var MEDIA_LIBRARY_CLUSTER_SCHEMA = { sections: [
9566
9586
  id: "folders",
9567
9587
  title: "Folders",
9568
9588
  titleKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.title",
9569
- fields: [{
9570
- type: "textarea",
9571
- key: "folderRoots",
9572
- label: "Folders to walk",
9573
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9574
- description: "One absolute path per line. Files the arr apps do not know are added from here.",
9575
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9576
- }, {
9577
- type: "number",
9578
- key: "rescanMinutes",
9579
- label: "Rescan every (minutes)",
9580
- labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9581
- description: "0 scans only when asked.",
9582
- descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9583
- min: 0
9584
- }]
9589
+ fields: [
9590
+ {
9591
+ type: "textarea",
9592
+ key: "folderRoots",
9593
+ label: "Folders to walk",
9594
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.label",
9595
+ description: "One absolute path per line. Files the arr apps do not know are added from here.",
9596
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.folderRoots.description"
9597
+ },
9598
+ {
9599
+ type: "number",
9600
+ key: "rescanMinutes",
9601
+ label: "Rescan every (minutes)",
9602
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.label",
9603
+ description: "0 scans only when asked.",
9604
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.rescanMinutes.description",
9605
+ min: 0
9606
+ },
9607
+ {
9608
+ type: "boolean",
9609
+ key: "trickplay",
9610
+ label: "Scrub thumbnails",
9611
+ labelKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.label",
9612
+ description: "Generate preview pictures for the seek bar in the background, one ffmpeg at a time at low priority.",
9613
+ descriptionKey: "media-library:mediaLibraryAddon.clusterSettings.s_folders.trickplay.description"
9614
+ }
9615
+ ]
9585
9616
  },
9586
9617
  {
9587
9618
  id: "metadata",
@@ -9825,6 +9856,34 @@ function fillMissingKeys(rows, stored) {
9825
9856
  });
9826
9857
  }
9827
9858
  //#endregion
9859
+ //#region src/servable.ts
9860
+ /**
9861
+ * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9862
+ * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9863
+ * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9864
+ */
9865
+ async function resolveServable(path, roots) {
9866
+ if (!(0, node_path.isAbsolute)(path) || path.includes("\0")) return null;
9867
+ let real;
9868
+ try {
9869
+ real = await (0, node_fs_promises.realpath)(path);
9870
+ } catch {
9871
+ return null;
9872
+ }
9873
+ for (const root of roots) {
9874
+ if (root === "") continue;
9875
+ let realRoot;
9876
+ try {
9877
+ realRoot = await (0, node_fs_promises.realpath)(root);
9878
+ } catch {
9879
+ continue;
9880
+ }
9881
+ const prefix = realRoot.endsWith(node_path.sep) ? realRoot : `${realRoot}${node_path.sep}`;
9882
+ if (real.startsWith(prefix)) return real;
9883
+ }
9884
+ return null;
9885
+ }
9886
+ //#endregion
9828
9887
  //#region src/naming.ts
9829
9888
  /** Case- and accent-insensitive form of a title, for search and ordering. */
9830
9889
  function foldTitle(title) {
@@ -9882,34 +9941,6 @@ function guessFromFilename(fileName, parentDir) {
9882
9941
  };
9883
9942
  }
9884
9943
  //#endregion
9885
- //#region src/servable.ts
9886
- /**
9887
- * A file is servable only when its REAL path (symlinks resolved) is inside a configured root.
9888
- * The path itself comes from the catalogue by item id; this is the second lock on the same door,
9889
- * so a catalogue row that names `/etc/passwd`, or a symlink that points out of the library, serves nothing.
9890
- */
9891
- async function resolveServable(path, roots) {
9892
- if (!(0, node_path.isAbsolute)(path) || path.includes("\0")) return null;
9893
- let real;
9894
- try {
9895
- real = await (0, node_fs_promises.realpath)(path);
9896
- } catch {
9897
- return null;
9898
- }
9899
- for (const root of roots) {
9900
- if (root === "") continue;
9901
- let realRoot;
9902
- try {
9903
- realRoot = await (0, node_fs_promises.realpath)(root);
9904
- } catch {
9905
- continue;
9906
- }
9907
- const prefix = realRoot.endsWith(node_path.sep) ? realRoot : `${realRoot}${node_path.sep}`;
9908
- if (real.startsWith(prefix)) return real;
9909
- }
9910
- return null;
9911
- }
9912
- //#endregion
9913
9944
  //#region src/file-plane.ts
9914
9945
  /**
9915
9946
  * Parse one `Range: bytes=…` header against a file of `size` bytes. A header this server does not
@@ -9995,7 +10026,7 @@ function pump(path, start, end, res, stallMs) {
9995
10026
  res.on("close", () => settle(sent > 0 && res.writableFinished ? "finished" : "client-closed"));
9996
10027
  });
9997
10028
  }
9998
- function reject$1(res, status, extra) {
10029
+ function reject$2(res, status, extra) {
9999
10030
  res.writeHead(status, {
10000
10031
  "Content-Length": 0,
10001
10032
  ...extra
@@ -10007,18 +10038,18 @@ function createFilePlaneHandler(deps) {
10007
10038
  const stallMs = deps.stallMs ?? 3e4;
10008
10039
  return async (req, res) => {
10009
10040
  const method = req.method ?? "GET";
10010
- if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10041
+ if (method !== "GET" && method !== "HEAD") return reject$2(res, 405, { Allow: "GET, HEAD" });
10011
10042
  const raw = (req.url ?? "/").split("?")[0] ?? "/";
10012
10043
  let itemId;
10013
10044
  try {
10014
10045
  itemId = decodeURIComponent(raw.replace(/^\//, ""));
10015
10046
  } catch {
10016
10047
  deps.logger.warn("file request refused: bad escape", { meta: { reason: "bad-id" } });
10017
- return reject$1(res, 404);
10048
+ return reject$2(res, 404);
10018
10049
  }
10019
10050
  if (!isItemId(itemId)) {
10020
10051
  deps.logger.warn("file request refused: not an item id", { meta: { reason: "bad-id" } });
10021
- return reject$1(res, 404);
10052
+ return reject$2(res, 404);
10022
10053
  }
10023
10054
  const tags = { itemId };
10024
10055
  const catalogued = await deps.lookup(itemId);
@@ -10027,7 +10058,7 @@ function createFilePlaneHandler(deps) {
10027
10058
  tags,
10028
10059
  meta: { reason: "not-catalogued" }
10029
10060
  });
10030
- return reject$1(res, 404);
10061
+ return reject$2(res, 404);
10031
10062
  }
10032
10063
  const path = await resolveServable(catalogued, await deps.roots());
10033
10064
  if (path === null) {
@@ -10035,7 +10066,7 @@ function createFilePlaneHandler(deps) {
10035
10066
  tags,
10036
10067
  meta: { reason: "outside-roots" }
10037
10068
  });
10038
- return reject$1(res, 404);
10069
+ return reject$2(res, 404);
10039
10070
  }
10040
10071
  let size;
10041
10072
  try {
@@ -10045,7 +10076,7 @@ function createFilePlaneHandler(deps) {
10045
10076
  tags,
10046
10077
  meta: { reason: "gone" }
10047
10078
  });
10048
- return reject$1(res, 404);
10079
+ return reject$2(res, 404);
10049
10080
  }
10050
10081
  const range = parseRange(headerOf(req.headers.range), size);
10051
10082
  if (range.kind === "unsatisfiable") {
@@ -10056,7 +10087,7 @@ function createFilePlaneHandler(deps) {
10056
10087
  size
10057
10088
  }
10058
10089
  });
10059
- return reject$1(res, 416, { "Content-Range": `bytes */${size}` });
10090
+ return reject$2(res, 416, { "Content-Range": `bytes */${size}` });
10060
10091
  }
10061
10092
  const start = range.kind === "range" ? range.start : 0;
10062
10093
  const end = range.kind === "range" ? range.end : size - 1;
@@ -10189,7 +10220,7 @@ function toWebVtt(source, format, offsetMs = 0) {
10189
10220
  }
10190
10221
  return out.join("\n");
10191
10222
  }
10192
- function reject(res, status, extra) {
10223
+ function reject$1(res, status, extra) {
10193
10224
  res.writeHead(status, {
10194
10225
  "Content-Length": 0,
10195
10226
  ...extra
@@ -10208,21 +10239,21 @@ function parseOffsetMs(query) {
10208
10239
  function createSubtitlePlaneHandler(deps) {
10209
10240
  return async (req, res) => {
10210
10241
  const method = req.method ?? "GET";
10211
- if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10242
+ if (method !== "GET" && method !== "HEAD") return reject$1(res, 405, { Allow: "GET, HEAD" });
10212
10243
  const [rawPath = "/", query = ""] = (req.url ?? "/").split("?");
10213
10244
  const segments = rawPath.replace(/^\//, "").split("/");
10214
10245
  let itemId;
10215
10246
  let sidecar;
10216
10247
  try {
10217
- if (segments.length !== 2) return reject(res, 404);
10248
+ if (segments.length !== 2) return reject$1(res, 404);
10218
10249
  itemId = decodeURIComponent(segments[0] ?? "");
10219
10250
  sidecar = decodeURIComponent(segments[1] ?? "");
10220
10251
  } catch {
10221
- return reject(res, 404);
10252
+ return reject$1(res, 404);
10222
10253
  }
10223
10254
  if (!isItemId(itemId)) {
10224
10255
  deps.logger.warn("subtitle request refused: not an item id", { meta: { reason: "bad-id" } });
10225
- return reject(res, 404);
10256
+ return reject$1(res, 404);
10226
10257
  }
10227
10258
  const tags = { itemId };
10228
10259
  const offsetMs = parseOffsetMs(query);
@@ -10231,7 +10262,7 @@ function createSubtitlePlaneHandler(deps) {
10231
10262
  tags,
10232
10263
  meta: { reason: "bad-offset" }
10233
10264
  });
10234
- return reject(res, 400);
10265
+ return reject$1(res, 400);
10235
10266
  }
10236
10267
  const known = (await deps.sidecars(itemId))?.find((candidate) => candidate.id === sidecar);
10237
10268
  if (known === void 0) {
@@ -10239,7 +10270,7 @@ function createSubtitlePlaneHandler(deps) {
10239
10270
  tags,
10240
10271
  meta: { reason: "not-a-sidecar" }
10241
10272
  });
10242
- return reject(res, 404);
10273
+ return reject$1(res, 404);
10243
10274
  }
10244
10275
  const path = await resolveServable(known.filePath, await deps.roots());
10245
10276
  if (path === null) {
@@ -10247,7 +10278,7 @@ function createSubtitlePlaneHandler(deps) {
10247
10278
  tags,
10248
10279
  meta: { reason: "outside-roots" }
10249
10280
  });
10250
- return reject(res, 404);
10281
+ return reject$1(res, 404);
10251
10282
  }
10252
10283
  try {
10253
10284
  if ((await (0, node_fs_promises.stat)(path)).size > 5242880) {
@@ -10255,7 +10286,7 @@ function createSubtitlePlaneHandler(deps) {
10255
10286
  tags,
10256
10287
  meta: { reason: "too-large" }
10257
10288
  });
10258
- return reject(res, 404);
10289
+ return reject$1(res, 404);
10259
10290
  }
10260
10291
  const body = Buffer.from(toWebVtt(await (0, node_fs_promises.readFile)(path, "utf8"), known.format, offsetMs), "utf8");
10261
10292
  res.writeHead(200, {
@@ -10278,6 +10309,408 @@ function createSubtitlePlaneHandler(deps) {
10278
10309
  tags,
10279
10310
  meta: { reason: "gone" }
10280
10311
  });
10312
+ reject$1(res, 404);
10313
+ }
10314
+ };
10315
+ }
10316
+ var TILES_PER_SHEET = 100;
10317
+ var GENERATE_TIMEOUT_MS = 3600 * 1e3;
10318
+ var INDEX_NAME = "index.vtt";
10319
+ /** The names a client may ask for inside one item's trickplay folder. */
10320
+ var TRICKPLAY_FILE_NAME = /^(?:index\.vtt|sprite-\d{1,4}\.jpg)$/;
10321
+ var FailureSchema = object({
10322
+ at: number(),
10323
+ attempts: number().int(),
10324
+ reason: string()
10325
+ });
10326
+ /** The height of one tile for a picture of this shape; even, as the encoder wants. */
10327
+ function tileHeightOf(width, height) {
10328
+ return Math.max(2, Math.round(320 * height / width / 2) * 2);
10329
+ }
10330
+ /** The ffmpeg arguments: one frame per interval, scaled, tiled into sheets of the grid, one JPEG per sheet. */
10331
+ function trickplayArgs(job) {
10332
+ return [
10333
+ "-hide_banner",
10334
+ "-nostdin",
10335
+ "-loglevel",
10336
+ "error",
10337
+ "-threads",
10338
+ "1",
10339
+ "-i",
10340
+ `file:${job.inputPath}`,
10341
+ "-an",
10342
+ "-sn",
10343
+ "-vf",
10344
+ `fps=1/10,scale=320:${job.tileHeight},tile=10x10`,
10345
+ "-q:v",
10346
+ "6",
10347
+ "-start_number",
10348
+ "0",
10349
+ (0, node_path.join)(job.outDir, "sprite-%d.jpg")
10350
+ ];
10351
+ }
10352
+ /** ffmpeg at the lowest priority (`nice`, where there is one), so a scrub image never takes a stream's CPU. */
10353
+ function createFfmpegTrickplayGenerator(binaryPath) {
10354
+ return (job) => new Promise((done, reject) => {
10355
+ const args = trickplayArgs(job);
10356
+ const [command, argv] = process.platform === "win32" ? [binaryPath, args] : ["nice", [
10357
+ "-n",
10358
+ "19",
10359
+ binaryPath,
10360
+ ...args
10361
+ ]];
10362
+ (0, node_child_process.execFile)(command, argv, {
10363
+ timeout: GENERATE_TIMEOUT_MS,
10364
+ maxBuffer: 1024 * 1024,
10365
+ encoding: "utf8"
10366
+ }, (error, _stdout, stderr) => {
10367
+ if (error === null) done();
10368
+ else reject(new Error(error.killed === true ? "ffmpeg timed out" : stderr.slice(0, 300) || error.message));
10369
+ });
10370
+ });
10371
+ }
10372
+ function timestamp(seconds) {
10373
+ const totalMs = Math.round(seconds * 1e3);
10374
+ const pad = (value, width) => String(value).padStart(width, "0");
10375
+ 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)}`;
10376
+ }
10377
+ /** The WebVTT index: one cue per interval, each pointing at its tile as `sprite-N.jpg#xywh=x,y,w,h`. */
10378
+ function buildTrickplayVtt(durationSec, tileHeight) {
10379
+ const frames = Math.ceil(durationSec / 10);
10380
+ const lines = ["WEBVTT", ""];
10381
+ for (let index = 0; index < frames; index += 1) {
10382
+ const slot = index % TILES_PER_SHEET;
10383
+ const x = slot % 10 * 320;
10384
+ const y = Math.floor(slot / 10) * tileHeight;
10385
+ const start = index * 10;
10386
+ const end = Math.min((index + 1) * 10, durationSec);
10387
+ lines.push(`${timestamp(start)} --> ${timestamp(end)}`, `sprite-${Math.floor(index / TILES_PER_SHEET)}.jpg#xywh=${x},${y},320,${tileHeight}`, "");
10388
+ }
10389
+ return lines.join("\n");
10390
+ }
10391
+ function fingerprintOf(source) {
10392
+ return `${source.sizeBytes}-${source.mtimeMs}`;
10393
+ }
10394
+ /** An item id is `source:kind:key`; the colons become underscores so the folder name is portable. */
10395
+ function folderOf(itemId) {
10396
+ return itemId.replaceAll(":", "_");
10397
+ }
10398
+ /**
10399
+ * The trickplay cache: sprite sheets and a WebVTT index per item, under the addon's data dir, keyed by the
10400
+ * file's size and mtime (a changed file generates anew). One ffmpeg at a time, in the background.
10401
+ */
10402
+ var TrickplayService = class {
10403
+ deps;
10404
+ queue = [];
10405
+ queued = /* @__PURE__ */ new Set();
10406
+ running = false;
10407
+ /** Files found outside the library roots: remembered (until restart) so they are not queued again. */
10408
+ outsideRoots = /* @__PURE__ */ new Set();
10409
+ idle = Promise.resolve();
10410
+ constructor(deps) {
10411
+ this.deps = deps;
10412
+ }
10413
+ keyOf(source) {
10414
+ return `${source.itemId}\u0000${fingerprintOf(source)}`;
10415
+ }
10416
+ itemDir(source) {
10417
+ return (0, node_path.join)(this.deps.cacheDir, folderOf(source.itemId));
10418
+ }
10419
+ readyDir(source) {
10420
+ return (0, node_path.join)(this.itemDir(source), fingerprintOf(source));
10421
+ }
10422
+ failurePath(source) {
10423
+ return (0, node_path.join)(this.itemDir(source), `${fingerprintOf(source)}.failed.json`);
10424
+ }
10425
+ /** The reason this file cannot have trickplay, or `null` when it can. */
10426
+ skipReason(source) {
10427
+ if (source.durationMs === null || source.durationMs <= 0) return "no-duration";
10428
+ if (source.durationMs / 1e3 < 30) return "too-short";
10429
+ if (source.width === null || source.height === null || source.width <= 0 || source.height <= 0) return "no-video-size";
10430
+ return null;
10431
+ }
10432
+ async readFailure(source) {
10433
+ try {
10434
+ return FailureSchema.parse(JSON.parse(await (0, node_fs_promises.readFile)(this.failurePath(source), "utf8")));
10435
+ } catch {
10436
+ return null;
10437
+ }
10438
+ }
10439
+ async isReady(source) {
10440
+ try {
10441
+ return (await (0, node_fs_promises.stat)((0, node_path.join)(this.readyDir(source), INDEX_NAME))).isFile();
10442
+ } catch {
10443
+ return false;
10444
+ }
10445
+ }
10446
+ /**
10447
+ * What a client may be told about `source`, and (when nothing is ready) a request for the work: a run
10448
+ * is queued unless one is queued already, it failed for good, or it failed too recently to try again.
10449
+ */
10450
+ async request(source, basePath) {
10451
+ const tags = { itemId: source.itemId };
10452
+ if (!this.deps.enabled()) return {
10453
+ status: "disabled",
10454
+ path: null
10455
+ };
10456
+ if (await this.isReady(source)) return {
10457
+ status: "ready",
10458
+ path: `${basePath}/${INDEX_NAME}`
10459
+ };
10460
+ if (this.outsideRoots.has(this.keyOf(source))) return {
10461
+ status: "skipped",
10462
+ path: null
10463
+ };
10464
+ const skip = this.skipReason(source);
10465
+ if (skip !== null) {
10466
+ this.deps.logger.debug("trickplay not generated", {
10467
+ tags,
10468
+ meta: { reason: skip }
10469
+ });
10470
+ return {
10471
+ status: "skipped",
10472
+ path: null
10473
+ };
10474
+ }
10475
+ const failure = await this.readFailure(source);
10476
+ if (failure !== null) {
10477
+ if (failure.attempts >= 3) return {
10478
+ status: "failed",
10479
+ path: null
10480
+ };
10481
+ if (this.deps.now() - failure.at < 216e5) return {
10482
+ status: "failed",
10483
+ path: null
10484
+ };
10485
+ }
10486
+ this.enqueue(source);
10487
+ return {
10488
+ status: "pending",
10489
+ path: null
10490
+ };
10491
+ }
10492
+ /** Queue one file; a second request for the same file while it waits or runs changes nothing. */
10493
+ enqueue(source) {
10494
+ const key = `${source.itemId}\u0000${fingerprintOf(source)}`;
10495
+ if (this.queued.has(key)) return;
10496
+ this.queued.add(key);
10497
+ this.queue.push(source);
10498
+ this.deps.logger.debug("trickplay queued", {
10499
+ tags: { itemId: source.itemId },
10500
+ meta: { waiting: this.queue.length }
10501
+ });
10502
+ if (!this.running) {
10503
+ this.running = true;
10504
+ this.idle = this.drain();
10505
+ }
10506
+ }
10507
+ /** Resolves when the queue is empty and nothing runs. */
10508
+ settled() {
10509
+ return this.idle;
10510
+ }
10511
+ async drain() {
10512
+ try {
10513
+ for (let next = this.queue.shift(); next !== void 0; next = this.queue.shift()) try {
10514
+ await this.generateOne(next);
10515
+ } catch (error) {
10516
+ this.deps.logger.warn("trickplay run aborted", {
10517
+ tags: { itemId: next.itemId },
10518
+ meta: { reason: error instanceof Error ? error.message : String(error) }
10519
+ });
10520
+ } finally {
10521
+ this.queued.delete(`${next.itemId}\u0000${fingerprintOf(next)}`);
10522
+ }
10523
+ } finally {
10524
+ this.running = false;
10525
+ }
10526
+ }
10527
+ async generateOne(source) {
10528
+ const tags = { itemId: source.itemId };
10529
+ const { logger } = this.deps;
10530
+ if (!this.deps.enabled()) {
10531
+ logger.info("trickplay skipped", {
10532
+ tags,
10533
+ meta: { reason: "disabled" }
10534
+ });
10535
+ return;
10536
+ }
10537
+ if (await this.isReady(source)) return;
10538
+ const skip = this.skipReason(source);
10539
+ if (skip !== null || source.width === null || source.height === null || source.durationMs === null) {
10540
+ logger.info("trickplay skipped", {
10541
+ tags,
10542
+ meta: { reason: skip ?? "no-video-size" }
10543
+ });
10544
+ return;
10545
+ }
10546
+ const attempts = ((await this.readFailure(source))?.attempts ?? 0) + 1;
10547
+ if (!await this.deps.inRoots(source.path)) {
10548
+ this.outsideRoots.add(this.keyOf(source));
10549
+ logger.warn("trickplay skipped", {
10550
+ tags,
10551
+ meta: { reason: "outside-roots" }
10552
+ });
10553
+ return;
10554
+ }
10555
+ const finalDir = this.readyDir(source);
10556
+ const workDir = `${finalDir}.work`;
10557
+ const tileHeight = tileHeightOf(source.width, source.height);
10558
+ const startedAt = this.deps.now();
10559
+ try {
10560
+ await (0, node_fs_promises.rm)(workDir, {
10561
+ recursive: true,
10562
+ force: true
10563
+ });
10564
+ await (0, node_fs_promises.mkdir)(workDir, { recursive: true });
10565
+ await this.deps.generate({
10566
+ inputPath: source.path,
10567
+ outDir: workDir,
10568
+ tileHeight
10569
+ });
10570
+ const sheets = (await (0, node_fs_promises.readdir)(workDir)).filter((name) => /^sprite-\d+\.jpg$/.test(name));
10571
+ if (sheets.length === 0) throw new Error("ffmpeg wrote no sprite sheet");
10572
+ await (0, node_fs_promises.writeFile)((0, node_path.join)(workDir, INDEX_NAME), buildTrickplayVtt(source.durationMs / 1e3, tileHeight), "utf8");
10573
+ await (0, node_fs_promises.rm)(finalDir, {
10574
+ recursive: true,
10575
+ force: true
10576
+ });
10577
+ await (0, node_fs_promises.rename)(workDir, finalDir);
10578
+ await (0, node_fs_promises.rm)(this.failurePath(source), { force: true });
10579
+ await this.pruneOthers(source);
10580
+ logger.info("trickplay generated", {
10581
+ tags,
10582
+ meta: {
10583
+ sheets: sheets.length,
10584
+ tileHeight,
10585
+ tookMs: this.deps.now() - startedAt
10586
+ }
10587
+ });
10588
+ } catch (error) {
10589
+ const reason = error instanceof Error ? error.message : String(error);
10590
+ try {
10591
+ await (0, node_fs_promises.rm)(workDir, {
10592
+ recursive: true,
10593
+ force: true
10594
+ });
10595
+ await (0, node_fs_promises.mkdir)(this.itemDir(source), { recursive: true });
10596
+ await (0, node_fs_promises.writeFile)(this.failurePath(source), JSON.stringify({
10597
+ at: this.deps.now(),
10598
+ attempts,
10599
+ reason
10600
+ }), "utf8");
10601
+ } catch (writeError) {
10602
+ logger.warn("trickplay failure could not be recorded", {
10603
+ tags,
10604
+ meta: { error: writeError instanceof Error ? writeError.message : String(writeError) }
10605
+ });
10606
+ }
10607
+ logger.warn("trickplay failed", {
10608
+ tags,
10609
+ meta: {
10610
+ reason,
10611
+ attempts,
10612
+ retry: attempts < 3
10613
+ }
10614
+ });
10615
+ }
10616
+ }
10617
+ /** A changed file leaves its old fingerprint behind: drop every other fingerprint of the item. */
10618
+ async pruneOthers(source) {
10619
+ const keep = fingerprintOf(source);
10620
+ for (const name of await (0, node_fs_promises.readdir)(this.itemDir(source))) if (name !== keep && name !== `${keep}.failed.json`) await (0, node_fs_promises.rm)((0, node_path.join)(this.itemDir(source), name), {
10621
+ recursive: true,
10622
+ force: true
10623
+ });
10624
+ }
10625
+ /** The absolute path of a ready file of `source`'s current fingerprint, or `null` when it is not there. */
10626
+ async fileFor(source, name) {
10627
+ if (!TRICKPLAY_FILE_NAME.test(name)) return null;
10628
+ const path = (0, node_path.join)(this.readyDir(source), name);
10629
+ try {
10630
+ return (await (0, node_fs_promises.stat)(path)).isFile() ? path : null;
10631
+ } catch {
10632
+ return null;
10633
+ }
10634
+ }
10635
+ };
10636
+ //#endregion
10637
+ //#region src/trickplay-plane.ts
10638
+ function reject(res, status, extra) {
10639
+ res.writeHead(status, {
10640
+ "Content-Length": 0,
10641
+ ...extra
10642
+ });
10643
+ res.end();
10644
+ }
10645
+ /** The `trickplay` plane: `GET|HEAD /<itemId>/index.vtt` and `/<itemId>/sprite-<n>.jpg`. */
10646
+ function createTrickplayPlaneHandler(deps) {
10647
+ return async (req, res) => {
10648
+ const method = req.method ?? "GET";
10649
+ if (method !== "GET" && method !== "HEAD") return reject(res, 405, { Allow: "GET, HEAD" });
10650
+ const segments = ((req.url ?? "/").split("?")[0] ?? "/").replace(/^\//, "").split("/");
10651
+ let itemId;
10652
+ let name;
10653
+ try {
10654
+ if (segments.length !== 2) return reject(res, 404);
10655
+ itemId = decodeURIComponent(segments[0] ?? "");
10656
+ name = decodeURIComponent(segments[1] ?? "");
10657
+ } catch {
10658
+ return reject(res, 404);
10659
+ }
10660
+ if (!isItemId(itemId)) {
10661
+ deps.logger.warn("trickplay request refused: not an item id", { meta: { reason: "bad-id" } });
10662
+ return reject(res, 404);
10663
+ }
10664
+ const tags = { itemId };
10665
+ if (!TRICKPLAY_FILE_NAME.test(name)) {
10666
+ deps.logger.info("trickplay request refused: not a trickplay file", {
10667
+ tags,
10668
+ meta: { reason: "bad-name" }
10669
+ });
10670
+ return reject(res, 404);
10671
+ }
10672
+ const source = await deps.source(itemId);
10673
+ if (source === null) {
10674
+ deps.logger.info("trickplay request refused: the item has no file", {
10675
+ tags,
10676
+ meta: { reason: "no-file" }
10677
+ });
10678
+ return reject(res, 404);
10679
+ }
10680
+ if (await resolveServable(source.path, await deps.roots()) === null) {
10681
+ deps.logger.warn("trickplay request refused: outside the library roots", {
10682
+ tags,
10683
+ meta: { reason: "outside-roots" }
10684
+ });
10685
+ return reject(res, 404);
10686
+ }
10687
+ const path = await deps.cache.fileFor(source, name);
10688
+ if (path === null) {
10689
+ deps.logger.info("trickplay request refused: not generated yet", {
10690
+ tags,
10691
+ meta: { reason: "not-ready" }
10692
+ });
10693
+ return reject(res, 404);
10694
+ }
10695
+ try {
10696
+ const body = await (0, node_fs_promises.readFile)(path);
10697
+ const isIndex = name === "index.vtt";
10698
+ res.writeHead(200, {
10699
+ "Content-Type": isIndex ? "text/vtt; charset=utf-8" : "image/jpeg",
10700
+ "Content-Length": body.length,
10701
+ "Cache-Control": isIndex ? "private, no-store" : "private, max-age=3600"
10702
+ });
10703
+ if (method === "HEAD") res.end();
10704
+ else res.end(body);
10705
+ deps.logger.debug("trickplay served", {
10706
+ tags,
10707
+ meta: { name }
10708
+ });
10709
+ } catch {
10710
+ deps.logger.warn("trickplay request refused: file vanished", {
10711
+ tags,
10712
+ meta: { reason: "gone" }
10713
+ });
10281
10714
  reject(res, 404);
10282
10715
  }
10283
10716
  };
@@ -11292,6 +11725,7 @@ function sortByShownTitle(rows, requested, serverDefault) {
11292
11725
  }
11293
11726
  var FILE_PLANE_PREFIX = "file";
11294
11727
  var SUBTITLE_PLANE_PREFIX = "subtitle";
11728
+ var TRICKPLAY_PLANE_PREFIX = "trickplay";
11295
11729
  var HUB_PLANE_BASE = "/addon/media-library";
11296
11730
  var SEARCH_DEFAULT_LIMIT = 50;
11297
11731
  var RECENT_DEFAULT_LIMIT = 20;
@@ -11306,6 +11740,10 @@ function playPathOf(itemId) {
11306
11740
  function subtitlePathOf(itemId, sidecarId) {
11307
11741
  return `${HUB_PLANE_BASE}/${SUBTITLE_PLANE_PREFIX}/${itemId}/${sidecarId}`;
11308
11742
  }
11743
+ /** The base of one item's trickplay files: `<base>/index.vtt`, `<base>/sprite-<n>.jpg`. */
11744
+ function trickplayBaseOf(itemId) {
11745
+ return `${HUB_PLANE_BASE}/${TRICKPLAY_PLANE_PREFIX}/${itemId}`;
11746
+ }
11309
11747
  function imagePathOf(itemId, which) {
11310
11748
  return `${HUB_PLANE_BASE}/img/${itemId}/${which}`;
11311
11749
  }
@@ -11327,13 +11765,15 @@ var LibraryStore = class {
11327
11765
  serverLanguage;
11328
11766
  now;
11329
11767
  listDir;
11768
+ trickplay;
11330
11769
  locks = /* @__PURE__ */ new Map();
11331
- constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir) {
11770
+ constructor(db, logger, serverLanguage = () => "en", now = Date.now, listDir = defaultListDir, trickplay = null) {
11332
11771
  this.db = db;
11333
11772
  this.logger = logger;
11334
11773
  this.serverLanguage = serverLanguage;
11335
11774
  this.now = now;
11336
11775
  this.listDir = listDir;
11776
+ this.trickplay = trickplay;
11337
11777
  }
11338
11778
  async init() {
11339
11779
  for (const declaration of COLLECTIONS) await this.db.declare(declaration);
@@ -11507,9 +11947,26 @@ var LibraryStore = class {
11507
11947
  format: sidecar.format,
11508
11948
  label: sidecar.label,
11509
11949
  path: subtitlePathOf(row.id, sidecar.id)
11510
- }))
11950
+ })),
11951
+ trickplay: file === void 0 || this.trickplay === null ? null : await this.trickplay.request(trickplaySourceOf(row.id, file), trickplayBaseOf(row.id))
11511
11952
  };
11512
11953
  }
11954
+ /** The catalogued file of `itemId` as the trickplay cache sees it; `null` when it has none. */
11955
+ async trickplaySource(itemId) {
11956
+ const catalogued = await this.playableFile(itemId);
11957
+ return catalogued === null ? null : trickplaySourceOf(itemId, catalogued.row);
11958
+ }
11959
+ /** Every catalogued file, for the sweep after a scan. */
11960
+ async trickplaySources() {
11961
+ const items = await this.queryAllItems();
11962
+ const files = new Map(parseRows(FileRowSchema, await queryAll(this.db, FILES, "path", {}), this.invalid(FILES)).map((file) => [file.path, file]));
11963
+ const sources = [];
11964
+ for (const item of items) {
11965
+ const file = item.filePath === null ? void 0 : files.get(item.filePath);
11966
+ if (file !== void 0) sources.push(trickplaySourceOf(item.id, file));
11967
+ }
11968
+ return sources;
11969
+ }
11513
11970
  /** The subtitle files next to the video of `itemId`; empty when it has none or no file. */
11514
11971
  async subtitleSidecars(itemId) {
11515
11972
  const catalogued = await this.playableFile(itemId);
@@ -11811,6 +12268,18 @@ var LibraryStore = class {
11811
12268
  return entries;
11812
12269
  }
11813
12270
  };
12271
+ function trickplaySourceOf(itemId, file) {
12272
+ const video = file.streams.find((stream) => stream.kind === "video");
12273
+ return {
12274
+ itemId,
12275
+ path: file.path,
12276
+ sizeBytes: file.sizeBytes,
12277
+ mtimeMs: file.mtimeMs,
12278
+ durationMs: file.probeOk ? file.durationMs : null,
12279
+ width: video?.width ?? null,
12280
+ height: video?.height ?? null
12281
+ };
12282
+ }
11814
12283
  async function defaultListDir(dir) {
11815
12284
  try {
11816
12285
  return new Map((await (0, node_fs_promises.readdir)(dir)).map((name) => [name.toLowerCase(), name]));
@@ -15119,6 +15588,7 @@ var ScanController = class {
15119
15588
  deps;
15120
15589
  sources;
15121
15590
  logger;
15591
+ afterScan;
15122
15592
  running = false;
15123
15593
  last = {
15124
15594
  running: false,
@@ -15131,10 +15601,11 @@ var ScanController = class {
15131
15601
  skipped: 0
15132
15602
  };
15133
15603
  timer = null;
15134
- constructor(deps, sources, logger) {
15604
+ constructor(deps, sources, logger, afterScan = async () => {}) {
15135
15605
  this.deps = deps;
15136
15606
  this.sources = sources;
15137
15607
  this.logger = logger;
15608
+ this.afterScan = afterScan;
15138
15609
  }
15139
15610
  status() {
15140
15611
  return {
@@ -15164,6 +15635,11 @@ var ScanController = class {
15164
15635
  } finally {
15165
15636
  this.running = false;
15166
15637
  }
15638
+ try {
15639
+ await this.afterScan();
15640
+ } catch (error) {
15641
+ this.logger.warn("after-scan work failed", { meta: { error: String(error) } });
15642
+ }
15167
15643
  }
15168
15644
  /** (Re)arm the rescan timer; `0` minutes turns it off. */
15169
15645
  schedule(minutes) {
@@ -15185,8 +15661,11 @@ var ScanController = class {
15185
15661
  * place in every item is kept here. Bytes leave through two data-plane routes served by item id.
15186
15662
  */
15187
15663
  var IMG_CACHE_DIR = "img-cache";
15664
+ var TRICKPLAY_CACHE_DIR = "trickplay";
15188
15665
  var MediaLibraryAddon = class extends BaseAddon {
15189
15666
  scans = null;
15667
+ /** The trickplay switch, held in memory: the generator reads it off the settings path. */
15668
+ trickplayOn = true;
15190
15669
  constructor() {
15191
15670
  super({});
15192
15671
  }
@@ -15201,6 +15680,7 @@ var MediaLibraryAddon = class extends BaseAddon {
15201
15680
  }
15202
15681
  async onScopedSettingsChanged() {
15203
15682
  const settings = await this.readSettings();
15683
+ this.trickplayOn = settings.trickplay;
15204
15684
  this.scans?.schedule(settings.rescanMinutes);
15205
15685
  this.scans?.start("settings");
15206
15686
  }
@@ -15256,9 +15736,26 @@ var MediaLibraryAddon = class extends BaseAddon {
15256
15736
  const db = settingsStoreDb(ctx.api.settingsStore);
15257
15737
  const serverLanguage = new ServerLanguage(async () => (await ctx.api.system.info.query()).defaultLanguage, () => Date.now(), logger);
15258
15738
  await serverLanguage.refresh();
15259
- const store = new LibraryStore(db, logger, () => serverLanguage.current());
15260
- await store.init();
15261
15739
  const ffmpeg = await ctx.deps.ensureFfmpeg();
15740
+ const roots = async () => {
15741
+ const settings = await this.readSettings();
15742
+ return [
15743
+ ...resolveSources(settings).folderRoots,
15744
+ settings.seriesPathTo || settings.seriesPathFrom,
15745
+ settings.moviesPathTo || settings.moviesPathFrom
15746
+ ].filter((root) => root !== "");
15747
+ };
15748
+ this.trickplayOn = (await this.readSettings()).trickplay;
15749
+ const trickplay = new TrickplayService({
15750
+ cacheDir: (0, node_path.join)(ctx.dataDir, TRICKPLAY_CACHE_DIR),
15751
+ generate: createFfmpegTrickplayGenerator(ffmpeg),
15752
+ enabled: () => this.trickplayOn,
15753
+ inRoots: async (path) => await resolveServable(path, await roots()) !== null,
15754
+ logger,
15755
+ now: () => Date.now()
15756
+ });
15757
+ const store = new LibraryStore(db, logger, () => serverLanguage.current(), void 0, void 0, trickplay);
15758
+ await store.init();
15262
15759
  const scans = new ScanController({
15263
15760
  db,
15264
15761
  logger,
@@ -15300,7 +15797,10 @@ var MediaLibraryAddon = class extends BaseAddon {
15300
15797
  }),
15301
15798
  createAnilist: () => createAnilistProvider({ fetch: httpRemoteFetch }),
15302
15799
  now: () => Date.now()
15303
- }, async () => resolveSources(await this.readSettings()), logger);
15800
+ }, async () => resolveSources(await this.readSettings()), logger, async () => {
15801
+ if (!this.trickplayOn) return;
15802
+ for (const source of await store.trickplaySources()) await trickplay.request(source, trickplayBaseOf(source.itemId));
15803
+ });
15304
15804
  this.scans = scans;
15305
15805
  const plexImports = new PlexImportController(logger, () => Date.now());
15306
15806
  const startPlex = async (mode) => {
@@ -15328,14 +15828,6 @@ var MediaLibraryAddon = class extends BaseAddon {
15328
15828
  message: started ? `Plex ${mode === "run" ? "import" : "preview"} started: read the report with plexImportStatus` : "A Plex import is already running"
15329
15829
  };
15330
15830
  };
15331
- const roots = async () => {
15332
- const settings = await this.readSettings();
15333
- return [
15334
- ...resolveSources(settings).folderRoots,
15335
- settings.seriesPathTo || settings.seriesPathFrom,
15336
- settings.moviesPathTo || settings.moviesPathFrom
15337
- ].filter((root) => root !== "");
15338
- };
15339
15831
  await ctx.dataPlane?.serve({
15340
15832
  prefix: FILE_PLANE_PREFIX,
15341
15833
  access: "viewer",
@@ -15354,6 +15846,16 @@ var MediaLibraryAddon = class extends BaseAddon {
15354
15846
  logger
15355
15847
  })
15356
15848
  });
15849
+ await ctx.dataPlane?.serve({
15850
+ prefix: TRICKPLAY_PLANE_PREFIX,
15851
+ access: "viewer",
15852
+ handler: createTrickplayPlaneHandler({
15853
+ source: (itemId) => store.trickplaySource(itemId),
15854
+ cache: trickplay,
15855
+ roots,
15856
+ logger
15857
+ })
15858
+ });
15357
15859
  await ctx.dataPlane?.serve({
15358
15860
  prefix: "img",
15359
15861
  access: "viewer",