@kymoscope/sdk 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -67,7 +67,9 @@ export { encodeVideo, decodeVideo, fragmentVideo, VIDEO_MAX_FRAGMENT, type Video
67
67
  export type { VideoSource, EncodedUnit, VideoTrackInfo } from './lib/live/videoTrack';
68
68
  export { RecordedVideoSource, type RecordedVideoSourceOptions } from './lib/recordings/videoSource';
69
69
  export { LivePublisher, fetchUsage, liveBytesPerSec, RegistryError, type CameraQuality, type LiveProfile, type LiveUsage, type PublisherDeps, type PublisherOptions, type PublisherState, type PublisherStatus } from './lib/live/publisher';
70
- export { CameraSender, CAMERA_QUALITIES, LOW_PRESET, type CameraPreset, type CameraStats, type CameraLayerStats, type CameraSenderDeps } from './lib/live/cameraSender';
70
+ export { CameraSender, CAMERA_QUALITIES, LOW_PRESET, type CameraPreset, type CameraStats, type CameraLayerStats, type CameraSenderDeps, type CameraRecorder } from './lib/live/cameraSender';
71
+ export { BrowserRecorder, bufferLabel, type BrowserRecorderOptions, type Destination, type OwnStorage, type RecorderStatus } from './lib/recordings/writer';
72
+ export { SPLIT_STEPS, defaultSplit, formatSplit, parseSplit } from './lib/recordings/split';
71
73
  export type { RecordingKey } from './lib/recordings/keys';
72
74
  export { recordingKeyAad, recordingKeySealAad } from './lib/recordings/keys';
73
75
  export { parseKrc, parseKrcHeader, KRC_HEADER_BYTES } from './lib/recordings/krc';
@@ -36,7 +36,14 @@ export interface CameraSenderDeps {
36
36
  /** The low layer's downscale (test seam); defaults to drawing onto an OffscreenCanvas. The caller closes the result. */
37
37
  scale?: (frame: VideoFrame, width: number, height: number) => VideoFrame;
38
38
  }
39
- type Publisher = Pick<LivePublisher, 'send' | 'viewers' | 'onViewers' | 'bitrateKbps' | 'profile'>;
39
+ type Publisher = Pick<LivePublisher, 'send' | 'viewers' | 'onViewers' | 'bitrateKbps' | 'profile'> & Partial<Pick<LivePublisher, 'seal' | 'sendSealed'>>;
40
+ /** What a recording camera feeds (BrowserRecorder). */
41
+ export interface CameraRecorder {
42
+ /** Frames are wanted (its data stream records): encode even with no viewers. */
43
+ wants(): boolean;
44
+ /** One sealed message at the frame's capture time (ms epoch); `keyframe`: it starts a keyframe. */
45
+ add(sealed: Uint8Array, tMs: number, keyframe: boolean): void;
46
+ }
40
47
  export declare class CameraSender {
41
48
  private readonly high;
42
49
  private readonly lowOpt;
@@ -57,6 +64,7 @@ export declare class CameraSender {
57
64
  publisher: Publisher;
58
65
  preset?: CameraPreset;
59
66
  };
67
+ recorder?: CameraRecorder;
60
68
  }, deps?: CameraSenderDeps);
61
69
  /** Encode frames from `track` (a getUserMedia video track). Resolves once the encoder is configured;
62
70
  * frames then flow until stop(). Throws KymoscopeError('camera_codec_unsupported'). A low layer this
@@ -50,6 +50,8 @@ export type CameraQuality = '360p' | '480p' | '720p' | '1080p';
50
50
  * declares its high camera's profile. */
51
51
  export interface LiveProfile {
52
52
  mode: 'live' | 'record';
53
+ /** On the wire only (set from splitEvery). */
54
+ split_every?: number;
53
55
  hz?: number;
54
56
  channels?: number;
55
57
  sources?: {
@@ -60,6 +62,9 @@ export interface LiveProfile {
60
62
  bytes_per_sec?: number;
61
63
  quality?: CameraQuality;
62
64
  fps?: number;
65
+ /** A data `record` stream's file period: '1m' … '24h' or its seconds (lib/recordings/split.ts); default from
66
+ * `bytes_per_sec` (files of about 150 MB). Sent as `split_every`. The SDK records only cameras (BrowserRecorder). */
67
+ splitEvery?: string | number;
63
68
  }
64
69
  /** A data stream's `bytes_per_sec`: `messagesPerSec` messages a second of `plaintextBytes` each (one representative
65
70
  * message's plaintext as handed to send(), with the samples one message carries), sealed and framed as the publisher
@@ -132,9 +137,6 @@ export declare class LivePublisher {
132
137
  private readonly password;
133
138
  private token;
134
139
  private ticket;
135
- /** The current ticket says rec (the reply's `recording`); `authRec`: the one the open socket authenticated with. */
136
- private ticketRec;
137
- private authRec;
138
140
  private relayUrl;
139
141
  private apiKeyId;
140
142
  private projectId;
@@ -197,6 +199,13 @@ export declare class LivePublisher {
197
199
  /** Seal with the current stream key (the key id of its epoch when e2ee) and send; false if not sent
198
200
  * (no key yet, socket down, stopped). */
199
201
  send(kind: number, plaintext: Uint8Array): Promise<boolean>;
202
+ /** The sealed message send() would publish (what a recorder keeps), or null without a stream key yet. */
203
+ seal(kind: number, plaintext: Uint8Array): Promise<Uint8Array<ArrayBuffer> | null>;
204
+ /** Publish an already sealed message; false when the socket is down. */
205
+ sendSealed(message: Uint8Array<ArrayBuffer>): boolean;
206
+ /** One recording-upload call with this stream's `pt.` token (supabase/functions/recording-upload/CONTRACT.md):
207
+ * what a BrowserRecorder needs. Rejects with a RegistryError. */
208
+ recordingUpload(body: Record<string, unknown>): Promise<any>;
200
209
  /** Close the socket and stop the timers. The stream stays registered (never deleted here), offline at once: what
201
210
  * it declared stops counting against the live limits now, not when the live window runs out. */
202
211
  stop(): void;
@@ -221,8 +230,7 @@ export declare class LivePublisher {
221
230
  private disconnect;
222
231
  /** Reconnect: at once after a stable connection, else after the backoff (1 s doubling to 10 s). */
223
232
  private dropped;
224
- /** Use `ticket` from now on; re-authenticate the open socket in-band when due, or at once when it
225
- * says rec and the socket's ticket didn't. */
233
+ /** Use `ticket` from now on; re-authenticate the open socket in-band when due. */
226
234
  private setTicket;
227
235
  private setViewers;
228
236
  private refuse;
@@ -0,0 +1,10 @@
1
+ export declare const SPLIT_STEPS: readonly [60, 300, 900, 1800, 3600, 7200, 14400, 28800, 43200, 86400];
2
+ /** Only a guide for the default period: files are never cut by size (time rules, the user decided 2026-11-09). */
3
+ export declare const FILE_TARGET_BYTES: number;
4
+ /** '1h' / '15m' / 3600 → seconds, or null when it isn't a step. */
5
+ export declare function parseSplit(v: unknown): number | null;
6
+ export declare const formatSplit: (s: number) => string;
7
+ /** The longest step whose file stays under the target at `bytesPerSec`; 1 min when none does. */
8
+ export declare function defaultSplit(bytesPerSec: number): number;
9
+ /** The next cut after `tMs` (strictly later), aligned to the sender's local clock (`utcOffsetS`, e.g. +3600). */
10
+ export declare function nextCut(tMs: number, periodS: number, utcOffsetS: number): number;
@@ -0,0 +1,187 @@
1
+ export declare const CHUNK_MS = 60000;
2
+ export declare const CHUNK_MAX_BYTES: number;
3
+ export declare const PARENT_POLL_MS = 10000;
4
+ export declare const FAST_POLL_MS = 2000;
5
+ export declare const PARENT_GONE_MS = 30000;
6
+ /** The wait after a failed upload pass: 2 s, doubling, at most 60 s. */
7
+ export declare const backoff: (ms: number) => number;
8
+ export declare const bufferLabel: (mb: number) => string;
9
+ /** The parts of the File System Access handles the recorder uses (OPFS, a picked folder, or a fake in tests). */
10
+ export interface RecFile {
11
+ kind: 'file';
12
+ getFile(): Promise<Blob>;
13
+ createWritable(): Promise<{
14
+ write(b: BufferSource | Blob | string): Promise<void>;
15
+ close(): Promise<void>;
16
+ }>;
17
+ }
18
+ export interface RecDir {
19
+ kind: 'directory';
20
+ getDirectoryHandle(name: string, o?: {
21
+ create?: boolean;
22
+ }): Promise<RecDir>;
23
+ getFileHandle(name: string, o?: {
24
+ create?: boolean;
25
+ }): Promise<RecFile>;
26
+ removeEntry(name: string, o?: {
27
+ recursive?: boolean;
28
+ }): Promise<void>;
29
+ entries(): AsyncIterable<[string, RecDir | RecFile]>;
30
+ }
31
+ /** The project's own storage, reached from this browser (the server only says which one: the keys stay here). */
32
+ export interface OwnStorage {
33
+ /** A folder the user picked (File System Access: Chrome and Edge). */
34
+ folder?: RecDir | FileSystemDirectoryHandle;
35
+ /** S3 or compatible (MinIO, R2…): the bucket must allow PUT from this page's origin (CORS). */
36
+ s3?: {
37
+ endpoint: string;
38
+ region?: string;
39
+ bucket: string;
40
+ prefix?: string;
41
+ accessKeyId: string;
42
+ secretAccessKey: string;
43
+ };
44
+ }
45
+ export interface Destination {
46
+ id: string;
47
+ name: string;
48
+ kind: 's3' | 'folder';
49
+ }
50
+ export type RecorderStatus = {
51
+ type: 'destination';
52
+ name: string;
53
+ splitEvery: number | null;
54
+ message: string;
55
+ } | {
56
+ type: 'storage_needed';
57
+ destination: Destination;
58
+ message: string;
59
+ } | {
60
+ type: 'refused' | 'buffer_full' | 'chunk_dropped' | 'storage_error' | 'disk_error';
61
+ message: string;
62
+ reason?: string;
63
+ };
64
+ export interface BrowserRecorderOptions {
65
+ /** The camera's stream id. */
66
+ streamId: string;
67
+ /** The data stream the camera belongs to: its files are cut with that stream's recordings. */
68
+ parentStreamId: string;
69
+ /** recording-upload (LivePublisher.recordingUpload); rejects with {status, code} (RegistryError). */
70
+ call: (body: Record<string, unknown>) => Promise<Record<string, unknown>>;
71
+ /** Local space for chunks not stored yet (default 2048). */
72
+ bufferMaxMB?: number;
73
+ storage?: OwnStorage | null;
74
+ /** Own storage only: how long it keeps the files. */
75
+ retentionDays?: number;
76
+ onStatus?: (s: RecorderStatus) => void;
77
+ /** Test seams. */
78
+ root?: () => Promise<RecDir>;
79
+ fetch?: typeof fetch;
80
+ now?: () => number;
81
+ /** Web Locks (navigator.locks); null: this page is the only uploader. */
82
+ locks?: LockManager | null;
83
+ /** Start the upload loop (default true; tests drive uploadPending/pollParent themselves). */
84
+ autostart?: boolean;
85
+ }
86
+ /** A message without any URL's query string (a presigned S3 URL's signature never reaches a log). */
87
+ export declare const redactUrls: (s: string) => string;
88
+ export declare class BrowserRecorder {
89
+ readonly streamId: string;
90
+ readonly parentStreamId: string;
91
+ readonly bufferMaxMB: number;
92
+ /** Chunks a full buffer dropped before they were stored. */
93
+ dropped: number;
94
+ /** Bytes in the buffer at the last count. */
95
+ usedBytes: number;
96
+ private storage;
97
+ private readonly opts;
98
+ private readonly now;
99
+ private readonly fetch;
100
+ private readonly locks;
101
+ private rootDir;
102
+ /** The data stream's open recording (null: none; undefined: not asked yet), and when it was last asked. */
103
+ private parent;
104
+ private polledAt;
105
+ private polling;
106
+ /** When the data stream's recording is expected to be cut (its period's next clock cut), and since when the server
107
+ * has said it has none open. */
108
+ private cutAt;
109
+ private noneSince;
110
+ private file;
111
+ private chunk;
112
+ private continues;
113
+ /** The last ended file, and the files refused, gone or whose last chunk a full buffer dropped (in memory). */
114
+ private prev;
115
+ private readonly lost;
116
+ /** Disk writes in order (opening a file, its chunks, its end). */
117
+ private io;
118
+ /** Files this recorder still writes: never closed on the server until their end is on disk. */
119
+ private readonly writing;
120
+ private readonly held;
121
+ private readonly opened;
122
+ private readonly blocked;
123
+ private readonly wait;
124
+ private readonly said;
125
+ private fullSaid;
126
+ private refusedUntil;
127
+ private closing;
128
+ private stopped;
129
+ private wake;
130
+ private loop;
131
+ constructor(opts: BrowserRecorderOptions);
132
+ /** Whether frames are wanted now: a file is open or the data stream records (the camera encodes for it). */
133
+ wants(): boolean;
134
+ /** The data stream's file period in seconds (from `current`), null until known. */
135
+ splitEvery: number | null;
136
+ /** The open file's recording id, or null. */
137
+ get currentId(): string | null;
138
+ /** The project's own storage became reachable (the page picked its folder): the files waiting for it go. */
139
+ setStorage(storage: OwnStorage | null): void;
140
+ /** One sealed message at `tMs` (the frame's capture time, ms since epoch). `keyframe`: it starts a keyframe; files
141
+ * open and end only there. */
142
+ add(sealed: Uint8Array, tMs: number, keyframe: boolean): void;
143
+ /** Close a chunk open for CHUNK_MS (the loop calls it every second). */
144
+ tick(): void;
145
+ /** End the current file now (the camera stops); the next file doesn't continue it. */
146
+ stop(): void;
147
+ /** Ask the server for the data stream's open recording (a failure keeps what was known). */
148
+ pollParent(): Promise<void>;
149
+ /** Ask again: every PARENT_POLL_MS; right after the expected cut and every FAST_POLL_MS for a minute past it; and
150
+ * every FAST_POLL_MS while a file is open but the server says none (a cut's gap, or a stop). */
151
+ private pollDue;
152
+ private root;
153
+ /** Run a disk write after the ones before it; a failure is said once and never stops live. */
154
+ private queue;
155
+ private openFile;
156
+ private endFile;
157
+ private flush;
158
+ /** Every file under rec/ counts (one budget for every stream); past it the oldest chunks go. */
159
+ private enforceMax;
160
+ private status;
161
+ private say;
162
+ /** Whether this recorder uploads folder `id`: its own, or a leftover no running recorder holds (a leftover without
163
+ * meta is removed). */
164
+ private claim;
165
+ private release;
166
+ /** [id, meta, dir] of the folders this recorder uploads, oldest first. */
167
+ private files;
168
+ /** Drop a file's chunks here (refused or gone on the server: lost, so the next file continues nothing; or stored
169
+ * and closed); the current one ends. */
170
+ private forget;
171
+ /** The file's destination once opened; null when it was refused (dropped) or can't go yet (kept). */
172
+ private open;
173
+ private put;
174
+ private writeOwn;
175
+ private dropChunk;
176
+ private uploadChunk;
177
+ /** The server lost a file it had opened (404): the chunks still here go under a new recording id, continuing
178
+ * nothing (the current file ends first). False when none are left (the file is forgotten as before). */
179
+ private reopen;
180
+ /** One pass over the files this recorder uploads, oldest first. True when nothing is left to upload (files waiting
181
+ * for their storage aside). Rejects on a failure worth retrying (the caller backs off). */
182
+ uploadPending(): Promise<boolean>;
183
+ private run;
184
+ /** End the current file and give the uploader up to `timeoutMs` to store what is left; the rest stays in the buffer
185
+ * and goes out the next time a camera records on this browser. */
186
+ close(timeoutMs?: number): Promise<void>;
187
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kymoscope/sdk",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "The Kymoscope data engine and charts for the browser: import large measurement files, plot them, stream live data end-to-end encrypted.",
5
5
  "license": "SEE LICENSE IN LICENSE.md",
6
6
  "homepage": "https://kymoscope.com/docs/introduction",
@@ -64,6 +64,9 @@
64
64
  "publishConfig": {
65
65
  "access": "public"
66
66
  },
67
+ "dependencies": {
68
+ "aws4fetch": "1.0.20"
69
+ },
67
70
  "main": "./dist/kymoscope-sdk.js",
68
71
  "module": "./dist/kymoscope-sdk.js",
69
72
  "types": "./dist/types/index.d.ts"
@@ -1,5 +0,0 @@
1
- /*! @kymoscope/sdk (c) 2026 Kymoscope. Proprietary software: use requires a license. See LICENSE.md. */
2
- import{At as e,Dt as t,Et as n,Ft as r,It as i,Lt as a,Mt as o,Nt as s,Ot as c,Pt as l,Rt as u,Tt as d,_ as f,_t as p,a as m,d as h,f as g,jt as _,kt as v,o as y,p as b,s as x,t as S,u as ee,v as C,vt as te,wt as ne,yt as re}from"./keys-Iv24Wam2.js";function w(e,t){return e.selection.find(e=>e.group===t)?.channels??[]}var ie=4096,ae={sin:Math.sin,cos:Math.cos,tan:Math.tan,asin:Math.asin,acos:Math.acos,atan:Math.atan,sinh:Math.sinh,cosh:Math.cosh,tanh:Math.tanh,exp:Math.exp,ln:Math.log,log:Math.log,log10:Math.log10,sqrt:Math.sqrt,abs:Math.abs,pow:Math.pow,min:Math.min,max:Math.max};function oe(e){if(e.length>ie)return null;let t=e.match(/\d+\.?\d*(?:[eE][+-]?\d+)?|\.\d+(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|\*\*|[-+*/^(),]|\S/g)??[],n=0,r=()=>t[n],i=()=>{throw Error(`formula`)},a=e=>{t[n++]!==e&&i()},o=()=>{let e=s();for(;r()===`+`||r()===`-`;){let r=t[n++],i=e,a=s();e=r===`+`?e=>i(e)+a(e):e=>i(e)-a(e)}return e},s=()=>{let e=c();for(;r()===`*`||r()===`/`;){let r=t[n++],i=e,a=c();e=r===`*`?e=>i(e)*a(e):e=>i(e)/a(e)}return e},c=()=>{if(r()===`-`){n++;let e=c();return t=>-e(t)}return r()===`+`?(n++,c()):l()},l=()=>{let e=u();if(r()===`^`||r()===`**`){n++;let t=c();return n=>e(n)**t(n)}return e},u=()=>{let e=t[n++];if(e===void 0&&i(),e===`(`){let e=o();return a(`)`),e}if(/^[\d.]/.test(e)){let t=Number(e);return Number.isFinite(t)||i(),()=>t}if(e===`X`||e===`x`||e===`X1`)return e=>e;if(Object.hasOwn(ae,e)){let t=ae[e];a(`(`);let i=[o()];for(;r()===`,`;)n++,i.push(o());return a(`)`),i.length===1?e=>t(i[0](e)):e=>t(...i.map(t=>t(e)))}return i()};try{let e=o();return n===t.length?e:null}catch{return null}}var T={k:`id`};function se(e,t){let{keys:n,vals:r}=e,i=n.length;if(i===0)return t;if(t<=n[0])return r[0];if(t>=n[i-1])return r[i-1];let a=0,o=i-1;for(;o-a>1;){let e=a+o>>1;n[e]<=t?a=e:o=e}return e.interp?r[a]+(r[o]-r[a])*(t-n[a])/(n[o]-n[a]):t-n[a]<=n[o]-t?r[a]:r[o]}function E(e,t){let n=t.length;switch(e.k){case`lin`:{let{a:r,b:i}=e;if(r===1&&i===0)return;for(let e=0;e<n;e++)t[e]=r*t[e]+i;return}case`rat`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e];t[e]=(r*n*n+i*n+a)/(o*n*n+s*n+c)}return}case`poly`:{let[r,i,a,o,s,c]=e.p;for(let e=0;e<n;e++){let n=t[e]-s-c;t[e]=(i-o*n)/(a*n-r)}return}case`alg`:{let r=e.f;for(let e=0;e<n;e++)t[e]=r(t[e]);return}case`tab`:for(let r=0;r<n;r++)t[r]=se(e,t[r]);return;case`rtv`:for(let r=0;r<n;r++){let n=t[r],i=e.def;for(let t=0;t<e.lo.length;t++)if(n>=e.lo[t]&&n<=e.hi[t]){i=e.vals[t];break}t[r]=i}return;default:return}}function ce(e,t){let n=Float64Array.of(t);return E(e,n),n[0]}var le=(e,t)=>e===null||typeof e==`string`?e:String(ce(e,t));function ue(e,t){let n=Array(t.length),r=e.ranges.every(e=>e.lo===e.hi)?new Map(e.ranges.map(e=>[e.lo,e.to])):null;for(let i=0;i<t.length;i++){let a=t[i];if(a!==a){n[i]=null;continue}let o=e.def;if(r){let e=r.get(a);e!==void 0&&(o=e)}else for(let t of e.ranges)if(a>=t.lo&&(e.int||t.lo===t.hi?a<=t.hi:a<t.hi)){o=t.to;break}n[i]=le(o,a)}return n}function de(e,t){let n=(e,t)=>({type:e,bigEndian:t,encoding:`latin1`});switch(e){case 0:return n(`uint`,!t);case 1:return n(`int`,!t);case 2:case 3:return n(`float`,!t);case 7:return n(`string`,!1);case 8:return n(`bytes`,!1);case 9:return n(`uint`,!0);case 10:return n(`int`,!0);case 11:case 12:return n(`float`,!0);case 13:return n(`uint`,!1);case 14:return n(`int`,!1);case 15:case 16:return n(`float`,!1);default:return null}}async function fe(e,t,n){let r=u(t).getUint16(24,!0)===0,i=async t=>{let n=u(await e.read(t,4)).getUint16(2,r),i=await e.read(t,n);return{id:o(i.subarray(0,2)),v:u(i),b:i,size:n}},a=(e,t)=>e.getUint32(t,r),c=(e,t)=>e.getUint16(t,r),l=(e,t)=>e.getFloat64(t,r),d=async e=>e?s((await i(e)).b.subarray(4),!0):``,f=[],p=new Set,m=e=>{if(p.has(e))throw Error(`This MDF file is damaged (its blocks link in a loop).`);p.add(e)},h=async(e,t)=>{if(!e)return{conv:T,unit:``};let{v:n,b:r}=await i(e),o=s(r.subarray(22,42),!0),u=c(n,42),f=c(n,44),p=e=>l(n,46+8*e);switch(u){case 0:return{conv:{k:`lin`,a:p(1),b:p(0)},unit:o};case 1:case 2:{let e=new Float64Array(f),t=new Float64Array(f);for(let n=0;n<f;n++)e[n]=p(2*n),t[n]=p(2*n+1);return{conv:{k:`tab`,keys:e,vals:t,interp:u===1},unit:o}}case 6:return{conv:{k:`poly`,p:[0,1,2,3,4,5].map(p)},unit:o};case 9:return{conv:{k:`rat`,p:[0,1,2,3,4,5].map(p)},unit:o};case 10:{let e=s(r.subarray(46,302),!0),t=oe(e);return{conv:t?{k:`alg`,f:t}:{k:`unsupported`,what:`the formula "${e}"`},unit:o}}case 11:return{conv:{k:`text`,ranges:Array.from({length:f},(e,t)=>{let i=46+40*t,a=l(n,i);return{lo:a,hi:a,to:s(r.subarray(i+8,i+40),!0)}}),def:null,int:t},unit:o};case 12:{let e=await Promise.all(Array.from({length:f},async(e,t)=>{let r=46+20*t;return{lo:l(n,r),hi:l(n,r+8),to:await d(a(n,r+16))}}));return{conv:{k:`text`,ranges:e.slice(1),def:e[0]?.to??null,int:t},unit:o}}case 65535:return{conv:T,unit:o};default:return{conv:{k:`unsupported`,what:`MDF3 conversion type ${u}`},unit:o}}},g=await i(64),_=null;if(g.size>=172&&(a(g.v,164)||a(g.v,168))){let e=a(g.v,168)*4294967296+a(g.v,164);_=new Date(e/1e6).toISOString()}else{let e=o(g.b.subarray(18,28)),t=o(g.b.subarray(28,36));/^\d\d:\d\d:\d{4}$/.test(e)&&(_=`${e.slice(6)}-${e.slice(3,5)}-${e.slice(0,2)}T${t}`)}let v=[],y=0;for(let e=a(g.v,4),t=0;e;t++){m(e);let n=await i(e),o=c(n.v,22),l=[];for(let e=a(n.v,8);e;){m(e);let n=await i(e),u=[],p=null;for(let e=a(n.v,8);e;){m(e);let t=await i(e),n=s(t.b.subarray(26,58),!0),o=(t.size>=222?await d(a(t.v,218)):``)||n,l=de(c(t.v,190),r),g=c(t.v,186)+(t.size>=228?8*c(t.v,226):0);if(!l)f.push(`${o}: MDF3 data type ${c(t.v,190)} is not supported; skipped.`);else{let{conv:e,unit:n}=await h(a(t.v,8),l.type!==`float`),r={name:o,unit:n,kind:c(t.v,24)===1?`master`:`value`,...l,conv:e,sd:null,sdRecordId:null,byteOffset:g>>3,bitOffset:g&7,bitCount:c(t.v,188),invalBit:null,allInvalid:!1};r.kind===`master`&&!p?p=r:r.kind===`value`&&u.push(r)}e=a(t.v,4)}y++,l.push({name:await d(a(n.v,12))||`Group ${y}`,dg:t,recordId:c(n.v,16),recordIdSize:+(o>0),idTrailer:+(o===2),dataBytes:c(n.v,20),invalBytes:0,cycles:a(n.v,22),vlsdCg:!1,sorted:!0,master:p,channels:u,stream:[],busType:0,busEvent:!1}),e=a(n.v,4)}let u=l.reduce((e,t)=>e+t.cycles*(t.recordIdSize+t.dataBytes+t.idTrailer),0),p=[{offset:a(n.v,16),length:u,zip:null}];for(let e of l)e.stream=p,e.sorted=l.length===1,v.push(e);e=a(n.v,4)}return{version:`MDF ${n}`,startTime:_,groups:v,notes:f,meta:{}}}var pe=`This MF4 is damaged (its blocks link in a loop).`;function D(e,t){if(e.seen.has(t))throw Error(pe);e.seen.add(t)}async function O(e,t){let n=await e.read(t,24);if(n.length<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let r=u(n),a=o(n.subarray(0,4)),s=i(r,8),c=i(r,16);if(!a.startsWith(`##`)||s<24+8*c||s>1<<26)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let l=await e.read(t,s);if(l.length<s)throw Error(`This MF4 is damaged (the block at byte ${t} runs past the end of the file).`);let d=u(l),f=[];for(let e=0;e<c;e++)f.push(i(d,24+8*e));let p=l.subarray(24+8*c);return{id:a,links:f,data:u(p),bytes:p}}var me={lt:`<`,gt:`>`,amp:`&`,quot:`"`,apos:`'`};function he(e){let t=e.indexOf(`<TX>`),n=t<0?-1:e.indexOf(`</TX>`,t+4);return(n>=0?e.slice(t+4,n):e.replace(/<[^<>]*>/g,``)).replace(/&(lt|gt|amp|quot|apos);/g,(e,t)=>me[t]).trim()}function k(e,t){if(!t)return Promise.resolve(``);let n=e.texts.get(t);return n||(n=O(e.io,t).then(e=>{let t=s(e.bytes);return e.id===`##MD`?he(t):t}),e.texts.set(t,n)),n}async function A(e,t,n=0){if(!t)return[];let r=e.io,a=await r.read(t,24),s=o(a.subarray(0,4)),c=a.length<24?0:i(u(a),8);switch(s){case`##DT`:case`##SD`:case`##RD`:return[{offset:t+24,length:c-24,zip:null}];case`##DZ`:{let e=u(await r.read(t+24,24));if(e.byteLength<24)throw Error(`This MF4 is damaged (bad block at byte ${t}).`);let n=e.getUint8(2);if(n===2||n===3)throw Error(`This MF4 uses zstd compression, which isn't supported yet.`);if(n===4||n===5)throw Error(`This MF4 uses LZ4 compression, which isn't supported yet.`);if(n>5)throw Error(`This MF4 is damaged (unknown compression type ${n}).`);let a=e.getUint32(4,!0),o=i(e,8),s=i(e,16);if(o>ne(s)||n===1&&a===0)throw Error(`This MF4 is damaged (bad compressed block at byte ${t}).`);if(n===1&&o>268435456)throw Error(`This MF4 has a compressed block over 256 MB, which Kymoscope cannot read.`);return[{offset:t+48,length:s,zip:{type:n,param:a,orgLength:o}}]}case`##DL`:{if(n>1)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);let i=[];for(let n=t;n;){D(e,n);let t=await O(r,n);for(let n of t.links.slice(1))i.push(...await A(e,n,2));n=t.links[0]}return i}case`##HL`:if(n>0)throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`);return D(e,t),A(e,(await O(r,t)).links[0],1);case`##DV`:case`##DI`:throw Error(`This MF4 uses column-oriented storage (MDF 4.2 DV/DI blocks), which Kymoscope cannot read yet.`);default:throw Error(`This MF4 is damaged (unexpected ${s} block in its data).`)}}async function ge(e,t,n){return t?o(await e.io.read(t,4))===`##CC`?_e(e,t,n+1):k(e,t):null}async function _e(e,t,n=0){if(!t||n>4||e.busy.has(t))return T;let r=e.convs.get(t);if(r)return r;e.busy.add(t);try{let r=await ve(e,t,n);return e.convs.set(t,r),r}finally{e.busy.delete(t)}}async function ve(e,t,n){let r=await O(e.io,t),i=r.data,a=i.getUint8(0),o=i.getUint16(4,!0),s=i.getUint16(6,!0),c=new Float64Array(s);for(let e=0;e<s;e++)c[e]=i.getFloat64(24+8*e,!0);let l=r.links.slice(4,4+o),u=()=>Promise.all(l.map(t=>ge(e,t,n)));switch(a){case 0:return T;case 1:return{k:`lin`,b:c[0],a:c[1]};case 2:return{k:`rat`,p:[...c]};case 3:{let t=await k(e,l[0]),n=oe(t);return n?{k:`alg`,f:n}:{k:`unsupported`,what:`the formula "${t}"`}}case 4:case 5:{let e=s>>1,t=new Float64Array(e),n=new Float64Array(e);for(let r=0;r<e;r++)t[r]=c[2*r],n[r]=c[2*r+1];return{k:`tab`,keys:t,vals:n,interp:a===4}}case 6:{let e=Math.max(0,Math.floor((s-1)/3)),t=new Float64Array(e),n=new Float64Array(e),r=new Float64Array(e);for(let i=0;i<e;i++)t[i]=c[3*i],n[i]=c[3*i+1],r[i]=c[3*i+2];return{k:`rtv`,lo:t,hi:n,vals:r,def:c[s-1]}}case 7:{let e=await u();return{k:`text`,ranges:[...c].map((t,n)=>({lo:t,hi:t,to:e[n]??null})),def:e[s]??null,int:!0}}case 8:{let e=await u(),t=s>>1;return{k:`text`,ranges:Array.from({length:t},(t,n)=>({lo:c[2*n],hi:c[2*n+1],to:e[n]??null})),def:e[t]??null,int:!0}}default:return{k:`unsupported`,what:`conversion type ${a}`}}}var ye={0:{type:`uint`,bigEndian:!1,encoding:`latin1`},1:{type:`uint`,bigEndian:!0,encoding:`latin1`},2:{type:`int`,bigEndian:!1,encoding:`latin1`},3:{type:`int`,bigEndian:!0,encoding:`latin1`},4:{type:`float`,bigEndian:!1,encoding:`latin1`},5:{type:`float`,bigEndian:!0,encoding:`latin1`},6:{type:`string`,bigEndian:!1,encoding:`latin1`},7:{type:`string`,bigEndian:!1,encoding:`utf-8`},8:{type:`string`,bigEndian:!1,encoding:`utf-16le`},9:{type:`string`,bigEndian:!0,encoding:`utf-16be`},10:{type:`bytes`,bigEndian:!1,encoding:`latin1`}};async function be(e,t){let{io:n,notes:r}=e,a=t.data,s=a.getUint8(0),c=a.getUint8(1),l=a.getUint8(2),u=await k(e,t.links[2]),d=ye[l];if(!d)return r.push(`${u}: data type ${l} is not supported; the channel was skipped.`),null;let f;if(s===2||s===3)if(c===1)f=s===2?`master`:`vmaster`;else{if(r.push(`The master channel ${u} is not time (sync type ${c}): samples are numbered instead.`),s===3)return null;f=`value`}else if(s===1)f=`vlsd`;else if(s===0||s===4)f=`value`;else return r.push(`${u}: channel type ${s} is not supported; skipped.`),null;let p=await _e(e,t.links[4]),m=p.k===`text`?{...p,int:d.type!==`float`}:p,h=await k(e,t.links[6]);!h&&t.links[4]&&(h=await k(e,(await O(n,t.links[4])).links[1]));let g=null,_=null;f===`vlsd`&&t.links[5]&&(o(await n.read(t.links[5],4))===`##CG`?_=i((await O(n,t.links[5])).data,0):g=await A(e,t.links[5]));let v=a.getUint32(12,!0);return{name:u,unit:h,kind:f,...d,conv:m,sd:g,sdRecordId:_,byteOffset:a.getUint32(4,!0),bitOffset:a.getUint8(3),bitCount:a.getUint32(8,!0),invalBit:v&2?a.getUint32(16,!0):null,allInvalid:(v&1)!=0}}async function xe(e,t,n,r=0){let{io:i,notes:a}=e;for(let s=t;s;){D(e,s);let t=await O(i,s),c=t.links[1];c&&r<4&&(o(await i.read(c,4))===`##CN`?await xe(e,c,n,r+1):a.push(`${await k(e,t.links[2])}: array channels (CA) are not supported yet; skipped.`));let l=await be(e,t);l&&n.push(l),s=t.links[0]}}async function Se(e,t,n,r){let a=t.data,o=a.getUint16(16,!0),s=0;t.links[3]&&(s=(await O(e.io,t.links[3])).data.getUint8(1));let c={name:await k(e,t.links[2]),dg:n,recordId:i(a,0),recordIdSize:r,idTrailer:0,dataBytes:a.getUint32(24,!0),invalBytes:a.getUint32(28,!0),cycles:i(a,8),vlsdCg:(o&1)!=0,sorted:!0,master:null,channels:[],stream:[],busType:s,busEvent:(o&2)!=0};if(c.vlsdCg)return c;let l=[];await xe(e,t.links[1],l);for(let e of l)e.kind===`master`||e.kind===`vmaster`?c.master||=e:c.channels.push(e);return c}async function Ce(e,t){let n=await O(e,64);if(n.id!==`##HD`)throw Error(`This MF4 is damaged (no header block).`);let r=i(n.data,0),a=(n.data.getUint8(12)&1)!=0,o=new Date(r/1e6).toISOString(),s=r>0?a?o.slice(0,-1):o:null,c={io:e,notes:[],seen:new Set,texts:new Map,convs:new Map,busy:new Set},l=[],u=0;for(let t=n.links[0],r=0;t;r++){D(c,t);let n=await O(e,t),i=n.data.getUint8(0),a=[];for(let t=n.links[1];t;){D(c,t);let n=await O(e,t),o=await Se(c,n,r,i);o.vlsdCg||(u++,o.name||=`Group ${u}`),a.push(o),t=n.links[0]}let o=await A(c,n.links[2]),s=a.length===1;for(let e of a)e.stream=o,e.sorted=s,l.push(e);t=n.links[0]}return{version:`MF4 ${t}`,startTime:s,groups:l,notes:c.notes,meta:{}}}function we(e){let t=e&32768?-1:1,n=e>>10&31,r=e&1023;return n===0?t*2**-14*(r/1024):n===31?r?NaN:t*(1/0):t*2**(n-15)*(1+r/1024)}function j(e,t,n,r,i,a,o=0){let s=u(t),c=!e.bigEndian,l=i+e.byteOffset,d=e.bitCount;if(e.bitOffset===0)if(e.type===`float`){if(d===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat64(l,c);return}if(d===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getFloat32(l,c);return}if(d===16){for(let e=0;e<n;e++,l+=r)a[o+e]=we(s.getUint16(l,c));return}}else if(e.type===`int`){if(d===8){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt8(l);return}if(d===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt16(l,c);return}if(d===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l,c);return}if(d===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getInt32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}else{if(d===8){for(let e=0;e<n;e++,l+=r)a[o+e]=t[l];return}if(d===16){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint16(l,c);return}if(d===32){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l,c);return}if(d===64){for(let e=0;e<n;e++,l+=r)a[o+e]=s.getUint32(l+(c?4:0),c)*4294967296+s.getUint32(l+(c?0:4),c);return}}let f=e.bitOffset+d+7>>3,p=2**e.bitOffset,m=2**d,h=m/2,g=e.type===`int`;for(let e=0;e<n;e++,l+=r){let n=0;if(c)for(let e=f-1;e>=0;e--)n=n*256+t[l+e];else for(let e=0;e<f;e++)n=n*256+t[l+e];n=Math.floor(n/p)%m,a[o+e]=g&&n>=h?n-m:n}}var Te=new Map,Ee=e=>{let t=Te.get(e);return t||Te.set(e,t=new TextDecoder(e)),t};function De(e){let t=e.indexOf(`\0`);return t<0?e:e.slice(0,t)}function Oe(e,t,n,r,i){let a=Ee(e.encoding),o=e.bitCount>>3,s=Array(n);for(let c=0,l=i+e.byteOffset;c<n;c++,l+=r)s[c]=De(a.decode(t.subarray(l,l+o)));return s}function ke(e,t,n,r,i,a){let o=a instanceof Float64Array?NaN:null;if(e.allInvalid){for(let e=0;e<n;e++)a[e]=o;return}if(e.invalBit===null)return;let s=1<<(e.invalBit&7);for(let c=0,l=i+(e.invalBit>>3);c<n;c++,l+=r)t[l]&s&&(a[c]=o)}var M=e=>e.recordIdSize+e.dataBytes+e.invalBytes+e.idTrailer,Ae=64<<20,je=(e,t)=>e.reduce((e,n)=>e+(n.zip?n.zip.orgLength:Math.max(0,Math.min(n.length,t-n.offset))),0),Me=e=>e.byteOffset+Math.ceil((e.bitOffset+e.bitCount)/8);function Ne(e,t){return e.kind===`vmaster`?!0:(e.kind===`vlsd`||e.type===`uint`||e.type===`int`||e.type===`float`?!(e.bitCount>=1&&e.bitCount<=64):!(e.bitCount>=8))?!1:Me(e)<=t.dataBytes}function Pe(e,t){let n=e.notes;for(let r of e.groups){if(![0,1,2,4,8].includes(r.recordIdSize))throw Error(`This MDF file is damaged (bad record id size).`);if(r.vlsdCg)continue;let e=M(r);if(e>Ae||e===0){r.cycles>0&&n.push(`${r.name||`A group`}: its records are ${e===0?`empty`:`too large`} (damaged); skipped.`),r.cycles=0;continue}r.cycles=Math.min(r.cycles,Math.floor(je(r.stream,t)/e));let i=r.channels.filter(e=>!Ne(e,r));for(let e of i)n.push(`${e.name}: its bits lie outside its record (damaged); skipped.`);i.length&&(r.channels=r.channels.filter(e=>!i.includes(e))),r.master&&!Ne(r.master,r)&&(n.push(`${r.master.name}: the time channel lies outside its record (damaged): samples are numbered instead.`),r.master=null);for(let e of r.master?[...r.channels,r.master]:r.channels)e.invalBit!==null&&e.invalBit>=8*r.invalBytes&&(e.invalBit=null)}}function Fe(e,t){let n=0;for(let r of e.master?[...t,e.master]:t){if(r.invalBit!==null)return 1/0;r.kind!==`vmaster`&&(n=Math.max(n,r.byteOffset+(r.bitOffset+r.bitCount+7>>3)))}return e.recordIdSize+n}var Ie=65536,Le=`This file's compressed data is damaged.`;async function*Re(e){for(let t=0;t<e.length;t+=Ie)yield e.subarray(t,t+Ie)}async function*ze(e){if(typeof DecompressionStream!=`function`){let t=[],n=new x(e=>{t.push(e)});for await(let r of e)for(n.push(r,!1);t.length;)yield t.shift();for(n.push(new Uint8Array,!0);t.length;)yield t.shift();return}let t=new DecompressionStream(`deflate`),n=t.writable.getWriter();(async()=>{for await(let t of e)await n.write(t);await n.close()})().catch(e=>n.abort(e).catch(()=>{}));let r=t.readable.getReader();try{for(;;){let{done:e,value:t}=await r.read().catch(e=>{throw e instanceof TypeError?Error(Le):e});if(e)return;yield t}}finally{r.cancel().catch(()=>{})}}async function N(e,t=-1,n=1/0){let r=[],i=Math.min(t,n),a=t>=0?new Uint8Array(i):null,o=0;for await(let s of ze(Re(e))){if(a){if(o+s.length>t&&n>t)throw Error(`Compressed data is longer than its header says.`);a.set(o+s.length>i?s.subarray(0,i-o):s,o)}else r.push(s);if(o+=s.length,o>=n)break}if(a)return o>=i?a:a.subarray(0,o);let s=r.length===1?r[0]:new Uint8Array(o);return r.length>1&&r.reduce((e,t)=>(s.set(t,e),e+t.length),0),o>n?s.subarray(0,n):s}var Be=new Uint8Array(Uint32Array.of(1).buffer)[0]===1;function Ve(e,t,n,r=t){let i=Math.floor(n/t),a=new Uint8Array(r<t?i*r:n),o=r%4==0&&Be?new Uint32Array(a.buffer,0,i*r>>2):null,s=r>>2;for(let t=0;t<i;t+=512){let n=Math.min(i,t+512);if(o)for(let a=0;a<r;a+=4){let r=a*i,c=r+i,l=c+i,u=l+i;for(let i=t,d=t*s+(a>>2);i<n;i++,d+=s)o[d]=e[r+i]|e[c+i]<<8|e[l+i]<<16|e[u+i]<<24}else for(let o=0;o<r;o++){let s=o*i;for(let i=t,c=t*r+o;i<n;i++,c+=r)a[c]=e[s+i]}}let c=i*t;return r===t&&a.set(e.subarray(c,n),c),a}function He(e,t,n){if(!(n<t)||e.length===0)return t;let r=Math.min(t,n+3&-4);return r===t?t:e.every(e=>e.zip?.type===1&&e.zip.param===t&&e.zip.orgLength%t===0)?r:t}async function Ue(e,t,n=1/0,r=1/0){let i=await e.slice(t.offset,t.length),{type:a,param:o,orgLength:s}=t.zip;if(a===0)return N(i,s,r);let c=Math.min(n,o);return Ve(await N(i,s,c<o?s/o*c:1/0),o,s,c)}async function*P(e,t,n,r=1/0){let i=e=>!!e?.zip&&!(e.zip.type===0&&(e.length>16777216||e.zip.orgLength>268435456)),a=null;for(let o=0;o<t.length;o++){let s=t[o];if(n?.throwIfAborted(),!s.zip)for await(let t of e.windows(s.offset,s.length))yield t.bytes;else if(i(s)){let n=a??Ue(e,s,r);a=i(t[o+1])?Ue(e,t[o+1],r):null,a?.catch(()=>{}),yield await n}else{let t=s.zip.orgLength;for await(let n of ze((async function*(){for await(let t of e.windows(s.offset,s.length))yield t.bytes})()))if(yield n.length>t?n.subarray(0,t):n,(t-=n.length)<=0)break}}}async function*We(e,t,n,r){if(r<=0||t<=0)return;let i=Math.min(n,r),a=null,o=0,s=0;for await(let n of e){let e=0;for(;e<n.length&&s<r;){if(o===0){let a=Math.min(i,r-s,Math.floor((n.length-e)/t));if(a>0){yield{buf:n.subarray(e,e+a*t),n:a},s+=a,e+=a*t;continue}}a??=new Uint8Array(t*i);let c=Math.min(a.length,(r-s)*t),l=Math.min(n.length-e,c-o);if(a.set(n.subarray(e,e+l),o),o+=l,e+=l,o===c){let e=o/t;yield{buf:a,n:e},s+=e,o=0}}if(s>=r)return}a&&o>=t&&(yield{buf:a,n:Math.floor(o/t)})}async function Ge(e,t,n,r){let i=n*r,a=0;for(let n of t){let t=n.zip?n.zip.orgLength:n.length;if(i<a)return null;if(i+r<=a+t)return n.zip?null:e.read(n.offset+i-a,r);a+=t}return null}var Ke=(e,t)=>(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0,qe=class{#e;#t;#n;#r;#i=new Uint8Array;#a=0;#o;#s=0;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n,this.#r=P(e,t,n),this.#o=t.reduce((e,t)=>e+(t.zip?t.zip.orgLength:t.length),0)}peek(e){let t=e-this.#a;if(t<0||t+4>this.#i.length)return null;let n=Ke(this.#i,t);return t+4+n>this.#i.length?null:this.#i.subarray(t+4,t+4+n)}async get(e){for(;;){let t=this.peek(e);if(t)return t;let n=e-this.#a;if(e+4>this.#o||n>=0&&n+4<=this.#i.length&&e+4+Ke(this.#i,n)>this.#o)throw Error(`This MF4 is damaged (string data ends early).`);e<this.#a&&(this.#r=P(this.#e,this.#t,this.#n),this.#i=new Uint8Array,this.#a=0);let r=await this.#r.next();if(r.done)throw Error(`This MF4 is damaged (string data ends early).`);if((this.#s+=r.value.length)>4*this.#o+16777216)throw Error(`This MF4 is damaged (its string offsets jump back and forth).`);let i=Math.max(0,Math.min(e-this.#a,this.#i.length)),a=this.#i.subarray(i),o=new Uint8Array(a.length+r.value.length);o.set(a),o.set(r.value,a.length),this.#a+=i,this.#i=o}}},Je=e=>Math.max(1,Math.min(65536,Math.floor((8<<20)/Math.max(1,e)))),Ye=64<<20,Xe=class{#e;#t;#n=new Map;#r=new Map;constructor(e,t){this.#e=e,this.#t=t}want(e){this.#r.has(e)||this.#r.set(e,new Map)}wanted(e){return this.#r.has(e)}put(e,t,n){this.#r.get(e).set(t,n)}async bytes(e,t){let n=Array(t.length);if(e.sdRecordId!==null){let r=this.#r.get(e.sdRecordId);for(let e=0;e<t.length;e++)n[e]=r?.get(t[e])??null,r?.delete(t[e]);return n}if(!e.sd)return n.fill(null);let r=this.#n.get(e);r||this.#n.set(e,r=new qe(this.#e,e.sd,this.#t));for(let e=0;e<t.length;e++)n[e]=r.peek(t[e])??await r.get(t[e]);return n}async strings(e,t){let n=Ee(e.encoding);return(await this.bytes(e,t)).map(e=>e?De(n.decode(e)):null)}};function Ze(e,t,n,r,i=M(e),a=new Float64Array(n)){let o=e.master;if(!o)return null;if(o.kind===`vmaster`)for(let e=0;e<n;e++)a[e]=r+e;else j(o,t,n,i,e.recordIdSize,a);return E(o.conv,a),a}function Qe(e,t,n){return n===1?e[t]:n===2?e[t]|e[t+1]<<8:n===4?(e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0:((e[t]|e[t+1]<<8|e[t+2]<<16|e[t+3]<<24)>>>0)+4294967296*((e[t+4]|e[t+5]<<8|e[t+6]<<16|e[t+7]<<24)>>>0)}function $e(e,t){let n=new Uint8Array(e.length+t.length);return n.set(e),n.set(t,e.length),n}async function*et(e,t,n,r,i,a=1/0){let o=t.groups[n[0]];if(o.sorted){let t=He(o.stream,M(o),a),r=0;for await(let{buf:a,n:s}of We(P(e,o.stream,i,t),t,Je(t),o.cycles))yield{g:n[0],buf:a,n:s,start:r,size:t},r+=s;return}let s=t.groups.map((e,t)=>({g:e,k:t})).filter(({g:e})=>e.dg===o.dg),c=o.recordIdSize,l=new Map;for(let e of n){let n=t.groups[e],r=M(n);l.set(n.recordId,{k:e,size:r,buf:new Uint8Array(r*Math.min(Je(r),Math.max(1,n.cycles))),fill:0,start:0})}let u=new Map(s.map(({g:e})=>[e.recordId,e.vlsdCg?-1:M(e)])),d=new Map,f=new Uint8Array;for await(let t of P(e,o.stream,i)){let e=f.length?$e(f,t):t,n=0;for(;!(n+c>e.length);){let t=Qe(e,n,c),i=u.get(t);if(i===void 0)throw Error(`This MF4 is damaged (unknown record id ${t}).`);if(i<0){if(n+c+4>e.length)break;let i=(e[n+c]|e[n+c+1]<<8|e[n+c+2]<<16|e[n+c+3]<<24)>>>0;if(i>Ye)throw Error(`This MF4 is damaged (a string record of ${i} bytes).`);let a=n+c+4+i;if(a>e.length)break;let o=d.get(t)??0;r.wanted(t)&&r.put(t,o,e.slice(n+c+4,a)),d.set(t,o+4+i),n=a;continue}if(n+i>e.length)break;let a=l.get(t);if(a&&(a.buf.set(e.subarray(n,n+i),a.fill),a.fill+=i,a.fill===a.buf.length)){let e=a.fill/a.size;yield{g:a.k,buf:a.buf,n:e,start:a.start,size:a.size},a.start+=e,a.fill=0}n+=i}f=e.slice(n)}for(let e of l.values())e.fill&&(yield{g:e.k,buf:e.buf,n:e.fill/e.size,start:e.start,size:e.size})}var F=(e,t)=>t?e+2147483648:e,tt=/^BO_\s+(\d+)\s+(\w+)\s*:\s*(\d+)/,nt=/^SG_\s+(\w+)\s*(?:(M|m\d+M?)\s*)?:\s*(\d+)\|(\d+)@([01])([+-])\s*\(([^,)]*),([^)]*)\)\s*\[[^\]]*\]\s*"([^"]*)"/,rt=/^VAL_\s+(\d+)\s+(\w+)\s+(.*);/,it=/^SIG_VALTYPE_\s+(\d+)\s+(\w+)\s*:\s*([12])\s*;/,at=/^-?\d+(?:\.\d+)?$/;function ot(e){let t=e.split(`"`),n=new Map;for(let e=0;e+1<t.length;e+=2){let r=t[e].trim();at.test(r)&&n.set(Number(r),t[e+1])}return n}var st=(e,t)=>e<=511&&t>=1&&t<=64;function ct(e){let t=new Map,n=new Map,r=new Map,i=(e,t)=>{let i=n.get(Number(e));return i?r.get(i)?.get(t):void 0},a=null;for(let o of e.split(/\r?\n/)){let e=o.trim(),s;if(s=tt.exec(e)){let e=Number(s[1]),r=e>=2147483648,i=r?e-2147483648:e;a={id:i,extended:r,name:s[2],size:Number(s[3]),signals:[]},t.set(F(i,r),a),n.set(e,a)}else if((s=nt.exec(e))&&a){let e=s[2],t=Number(s[3]),n=Number(s[4]);if(!st(t,n)||!s[7].trim()||!s[8].trim())continue;let i={name:s[1],start:t,length:n,littleEndian:s[5]===`1`,signed:s[6]===`-`,factor:Number(s[7]),offset:Number(s[8]),unit:s[9],mux:e?e===`M`?`switch`:parseInt(e.slice(1),10):null,float:0,values:null};a.signals.push(i);let o=r.get(a);o||r.set(a,o=new Map),o.has(i.name)||o.set(i.name,i)}else if(s=rt.exec(e)){let e=i(s[1],s[2]);e&&(e.values=ot(s[3]))}else if(s=it.exec(e)){let e=i(s[1],s[2]);e&&(e.float=s[3]===`1`?32:64)}else (e.startsWith(`BO_`)||e===``)&&e===``&&(a=null)}return t}function I(e){if(e.float){let t=e.float/8,n=e.start>>3,r=e.littleEndian,i=new DataView(new ArrayBuffer(8));return(e,a)=>{for(let r=0;r<t;r++)i.setUint8(r,e[a+n+r]??0);return t===4?i.getFloat32(0,r):i.getFloat64(0,r)}}let t=e.length,n=2**t,r=n/2,i=e.signed;if(e.littleEndian){let a=e.start>>3,o=e.start&7;if(o+t<=32){let e=t===32?-1:(1<<t)-1;return(t,s)=>{let c=s+a,l=((t[c]|t[c+1]<<8|t[c+2]<<16|t[c+3]<<24)>>>o&e)>>>0;return i&&l>=r?l-n:l}}let s=o+t+7>>3,c=2**(t-(32-o)),l=2**(32-o);return(e,t)=>{let u=t+a,d=(e[u]|e[u+1]<<8|e[u+2]<<16|e[u+3]<<24)>>>o,f=0;for(let t=s-1;t>=4;t--)f=f*256+(e[u+t]??0);let p=d+f%c*l;return i&&p>=r?p-n:p}}let a=e.start>>3,o=e.start&7;if(7-o+t<=32){let e=32-(7-o)-t,s=t===32?-1:(1<<t)-1;return(t,o)=>{let c=o+a,l=((t[c]<<24|t[c+1]<<16|t[c+2]<<8|t[c+3])>>>e&s)>>>0;return i&&l>=r?l-n:l}}let s=(1<<o+1)-1,c=t-(o+1)>>3,l=t-(o+1)&7,u=2**l;return(e,t)=>{let o=(e[t+a]??0)&s,d=t+a+1;for(let t=0;t<c;t++)o=o*256+(e[d++]??0);return l>0&&(o=o*u+((e[d]??0)>>8-l)),i&&o>=r?o-n:o}}function lt(e){let t=e.length,n=2**t,r=n/2,i=e.signed,a=t===32?-1:(1<<t)-1;if(!e.float&&e.littleEndian&&(e.start&7)+t<=32){let t=e.start>>3,o=e.start&7;return(e,s,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=s[c[p]]+t,m=((e[l]|e[l+1]<<8|e[l+2]<<16|e[l+3]<<24)>>>o&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}if(!e.float&&!e.littleEndian&&7-(e.start&7)+t<=32){let o=e.start>>3,s=32-(7-(e.start&7))-t;return(e,t,c,l,u,d,f)=>{for(let p=0;p<l;p++){let l=t[c[p]]+o,m=((e[l]<<24|e[l+1]<<16|e[l+2]<<8|e[l+3])>>>s&a)>>>0;u[p]=(i&&m>=r?m-n:m)*d+f}}}let o=I(e);return(e,t,n,r,i,a,s)=>{for(let c=0;c<r;c++)i[c]=o(e,t[n[c]])*a+s}}function ut(e){if(!e.busEvent||e.busType!==2)return null;let t=t=>e.channels.find(e=>e.name.endsWith(t))??null,n=t(`DataFrame.ID`),r=t(`DataFrame.DataBytes`);return!n||!r?null:{id:n,ide:t(`DataFrame.IDE`),data:r}}var dt=()=>({n:0,time:new Float64Array,key:new Float64Array,id:new Float64Array,ide:new Float64Array,bytes:null,buf:new Uint8Array,dataAt:new Int32Array});async function ft(e,t,n,r,i,a,o,s){s.key.length<r&&Object.assign(s,{time:new Float64Array(r),key:new Float64Array(r),id:new Float64Array(r),ide:new Float64Array(r),dataAt:new Int32Array(r)});let c=e.recordIdSize,{id:l,ide:u,key:d,dataAt:f}=s;j(t.id,n,r,a,c,l),t.ide&&j(t.ide,n,r,a,c,u);for(let e=0;e<r;e++){let n=l[e],r=n&536870911;d[e]=F(r,t.ide?u[e]!==0:n>=2147483648||r>2047)}if(s.bytes=null,t.data.kind===`vlsd`){let e=new Float64Array(r);j({...t.data,type:`uint`},n,r,a,c,e),s.bytes=await o.bytes(t.data,e)}else for(let e=0,n=c+t.data.byteOffset;e<r;e++,n+=a)f[e]=n;if(!Ze(e,n,r,i,a,s.time.subarray(0,r)))for(let e=0;e<r;e++)s.time[e]=i+e;return s.n=r,s.buf=n,s}var pt=new Uint8Array;function mt(e){return e.float?(e.start>>3)+e.float/8:e.littleEndian?(e.start>>3)+((e.start&7)+e.length+7>>3):(e.start>>3)+1+(Math.max(0,e.length-((e.start&7)+1))+7>>3)}function ht(e,t,n){let r=0;for(let e of n.values())for(let t of e.signals)r=Math.max(r,mt(t));let i=t.data.kind===`vlsd`?t.data:{...t.data,bitCount:Math.min(t.data.bitCount,r*8)};return Fe(e,t.ide?[t.id,t.ide,i]:[t.id,i])}function gt(e,t){let n=t.map(t=>e.signals[e.channels[t].s]);return{route:e,col:n.map(lt),read:n.map(I),factor:n.map(e=>e.factor),offset:n.map(e=>e.offset),table:t.map((t,r)=>e.channels[t].text?n[r].values:null),idx:new Int32Array,cnt:0,n:0,t0:NaN,t1:NaN}}function _t(e,t,n,r,i,a=1,o=0){let s=new Float64Array(i);if(n.bytes)for(let e=0;e<i;e++)s[e]=t(n.bytes[r[e]]??pt,0)*a+o;else e(n.buf,n.dataAt,r,i,s,a,o);return s}function vt(e,t){let{idx:n,cnt:r}=e,i=new Float64Array(r);for(let e=0;e<r;e++)i[e]=t.time[n[e]];return e.n===0&&(e.t0=i[0]),e.t1=i[r-1],e.n+=r,e.cnt=0,{time:i,cols:e.col.map((i,a)=>{let o=e.table[a];return o?Array.from(_t(i,e.read[a],t,n,r),e=>o.get(e)??null):_t(i,e.read[a],t,n,r,e.factor[a],e.offset[a])})}}var yt=e=>({key:e,skip:!0,frames:0,all:null,sw:null,byMux:new Map,idx:new Int32Array,cnt:0});function bt(e,t){let n=e.signals.find(e=>e.mux===`switch`);return{key:F(e.id,e.extended),skip:!1,frames:0,all:t,sw:n?{col:lt(n),read:I(n)}:null,byMux:new Map,idx:new Int32Array,cnt:0}}var xt=class{#e=Array(2048);#t=new Map;#n;constructor(e){this.#n=e}get(e){let t=e<2048?this.#e[e]:this.#t.get(e);return t||(t=this.#n(e),e<2048?this.#e[e]=t:this.#t.set(e,t)),t}};function St(e,t,n){let r=[];for(let n=0;n<e.n;n++){let i=t.get(e.key[n]);if(i.skip){i.frames++;continue}i.cnt===0&&(r.push(i),i.idx.length<e.n&&(i.idx=new Int32Array(e.n))),i.idx[i.cnt++]=n}let i=[];for(let t of r){if(t.all&&(t.all.idx=t.idx,t.all.cnt=t.cnt,i.push(t.all)),t.sw){let r=_t(t.sw.col,t.sw.read,e,t.idx,t.cnt);for(let e=0;e<t.cnt;e++){let a=t.byMux.get(r[e]);a===void 0&&((a=n(t,r[e]))||t.byMux.size<4096)&&t.byMux.set(r[e],a),a&&(a.cnt===0&&(i.push(a),a.idx.length<t.cnt&&(a.idx=new Int32Array(t.cnt))),a.idx[a.cnt++]=t.idx[e])}}t.cnt=0}return i}var Ct=48e6;async function wt(e,t,n,r){let i=new Map;if(t.groups.forEach((e,t)=>{let n=ut(e);n&&e.cycles>0&&i.set(t,n)}),i.size===0)return null;if(n.length===0)return{dbc:new Map,layouts:i,routes:[],notes:[],cache:new Map};let o=ct(a(new Uint8Array(await n[0].arrayBuffer()))),s=[],c=new Map,l=new Map,u=0,d=new Xe(e,r);for(let[n,a]of i){let i=t.groups[n],f=(e,t)=>{let n=e.signals.filter(e=>t===null?typeof e.mux!=`number`:e.mux===t),r=[];return n.forEach((e,t)=>{r.push({s:t,text:!1}),e.values&&r.push({s:t,text:!0})}),gt({key:F(e.id,e.extended),mux:t,signals:n,channels:r},r.map((e,t)=>t))},p=new xt(e=>{let t=o.get(e);if(!t){let t=yt(e);return c.set(e,t),t}let r=bt(t,f(t,null));return s.push({model:n,m:r}),r});a.data.sdRecordId!==null&&d.want(a.data.sdRecordId);let m=dt();for await(let s of et(e,t,[n],d,r,ht(i,a,o))){let e=await ft(i,a,s.buf,s.n,s.start,s.size,d,m),t=(e,t)=>{let n=o.get(e.key);return n.signals.some(e=>e.mux===t)?f(n,t):null};for(let n of St(e,p,t)){let t=vt(n,e);if(u<0)continue;if((u+=t.time.length*(1+t.cols.length))>Ct){u=-1,l.clear();continue}let r=l.get(n);r||l.set(n,r=[]),r.push(t)}}}let f=[],p=new Map;for(let{model:e,m:t}of s)for(let n of[t.all,...t.byMux.values()]){if(!n)continue;let{route:t,n:r,t0:i,t1:a}=n;if(t.signals.length===0)continue;let s=o.get(t.key);u>=0&&p.set(t,l.get(n)??[]),f.push({model:e,route:t,group:{name:t.mux===null?s.name:`${s.name} [m=${t.mux}]`,channels:t.channels.map(e=>({name:e.text?`${t.signals[e.s].name} (text)`:t.signals[e.s].name,unit:e.text?``:t.signals[e.s].unit,text:e.text})),samples:r,time:{kind:`timestamps`},rateHz:r>1&&a>i?Math.round((r-1)/(a-i)*1e6)/1e6:null}})}let m=[];if(c.size){let e=[...c.values()].reduce((e,t)=>e+t.frames,0),t=[...c.keys()].map(e=>`0x${(e%2147483648).toString(16).toUpperCase()}`).join(`, `);m.push(`${e} frame${e===1?``:`s`} with ${c.size} id${c.size===1?``:`s`} not in the DBC ${e===1?`was`:`were`} skipped (${t}).`)}return{dbc:o,layouts:i,routes:f,notes:m,cache:p}}async function*Tt(e,t,n,r,i,a){let o=[];for(let e of i){let t=r.cache.get(e.route);if(!t){o.push(e);continue}r.cache.delete(e.route);let n=0;for(let r of t)yield{group:e.group,start:n,length:r.time.length,time:r.time,columns:e.sel.map(e=>r.cols[e])},n+=r.time.length}if(!o.length)return;let s=r.layouts.get(n),c=t.groups[n],l=new Map,u=new Map;for(let e of o){let t=gt(e.route,e.sel);l.set(t,e.group);let n=u.get(e.route.key);n||u.set(e.route.key,n={all:null,byMux:new Map}),e.route.mux===null?n.all=t:n.byMux.set(e.route.mux,t)}let d=new xt(e=>{let t=u.get(e);if(!t)return yt(e);let n=bt(r.dbc.get(e),t.all);return t.byMux.size||(n.sw=null),n}),f=new Xe(e,a);s.data.sdRecordId!==null&&f.want(s.data.sdRecordId);let p=dt();for await(let i of et(e,t,[n],f,a,ht(c,s,r.dbc))){let e=await ft(c,s,i.buf,i.n,i.start,i.size,f,p);for(let t of St(e,d,(e,t)=>u.get(e.key).byMux.get(t)??null)){let n=t.n,r=vt(t,e);yield{group:l.get(t),start:n,length:r.time.length,time:r.time,columns:r.cols}}}}var Et=e=>Math.round(e*1e6)/1e6,Dt=e=>e.kind===`value`?e.type!==`bytes`:e.kind===`vlsd`&&e.type===`string`,Ot=e=>({name:e.name,unit:e.unit,text:e.type===`string`||e.kind===`vlsd`||e.conv.k===`text`});async function kt(e,t){let n=t.master;if(!n||t.cycles<2)return null;if(n.kind===`vmaster`)return n.conv.k===`lin`&&n.conv.a>0?Et(1/n.conv.a):null;if(!t.sorted)return null;let r=M(t),i=t.cycles,a,o;if(t.stream[0]?.zip){let n=He(t.stream.slice(0,1),r,Fe(t,[])),s=await Ue(e,t.stream[0],n,4096*r);if(i=Math.min(t.cycles,Math.floor(s.length/n)),i<2)return null;a=s.subarray(0,n),o=s.subarray((i-1)*n,i*n)}else a=await Ge(e,t.stream,0,r),o=await Ge(e,t.stream,t.cycles-1,r);if(!a||!o)return null;let s=new Float64Array(2);return j(n,a,1,r,t.recordIdSize,s,0),j(n,o,1,r,t.recordIdSize,s,1),E(n.conv,s),s[1]>s[0]?Et((i-1)/(s[1]-s[0])):null}async function At(e,t,n,r,i,a,o){let s;if(e.kind===`vlsd`){let a=new Float64Array(n);j({...e,type:`uint`},t,n,r,i,a),s=await o.strings(e,a)}else if(e.type===`string`)s=Oe(e,t,n,r,i);else{let a=new Float64Array(n);j(e,t,n,r,i,a),e.conv.k===`text`?s=ue(e.conv,a):(E(e.conv,a),s=a)}return ke(e,t,n,r,a,s),s}async function jt(e,t,n,r,i,a,o,s){let c=e.recordIdSize,l=[];for(let i of t)l.push(await At(e.channels[i],n,r,a,c,c+e.dataBytes,s));return{group:o,time:Ze(e,n,r,i,a),start:i,length:r,columns:l}}async function*Mt(e,t){let n=e.plan.state,r=t.filter(e=>n.groups[e].route),i=t.filter(e=>!n.groups[e].route);if(r.length){let t=r.map(t=>({group:t,route:n.groups[t].route,sel:w(e,t)}));yield*Tt(e.io,n.model,n.groups[r[0]].model,n.bus,t,e.signal)}if(!i.length)return;let a=new Xe(e.io,e.signal),o=new Map;for(let t of i){let r=n.groups[t],i=w(e,t).map(e=>r.channels[e]);for(let e of i){let t=n.model.groups[r.model].channels[e].sdRecordId;t!==null&&a.want(t)}o.set(r.model,{pg:t,cols:i})}let[s,{cols:c}]=o.entries().next().value,l=n.model.groups[s],u=o.size===1?Fe(l,c.map(e=>l.channels[e])):1/0;for await(let t of et(e.io,n.model,[...o.keys()],a,e.signal,u)){let{pg:e,cols:r}=o.get(t.g);yield await jt(n.model.groups[t.g],r,t.buf,t.n,t.start,t.size,e,a)}}function Nt(e){let t=e.plan.state,n=new Map;for(let r of e.selection){let e=t.model.groups[t.groups[r.group].model].dg;n.set(e,[...n.get(e)??[],r.group])}return[...n].sort((e,t)=>e[0]-t[0]).map(([,e])=>e)}var Pt={..._,async plan(e,t){let n=await t.read(0,64);if(r(n,`UnFinMF`))throw Error(`This MF4 was not finalized by its logger (it starts with UnFinMF). Finalize it with the logger software or asammdf, then open it again.`);let i=o(n.subarray(8,16)).replace(/\0/g,``).trim(),a=Number(i.replace(`.`,``).slice(0,3))>=400?await Ce(t,i):await fe(t,n,i);Pe(a,t.size);let s=await wt(t,a,e.companions.filter(e=>e.name.toLowerCase().endsWith(`.dbc`))),c=new Set(s?.layouts.keys()??[]),l=[],u=[],d=[...a.notes],f=0;for(let e=0;e<a.groups.length;e++){let n=a.groups[e];if(n.vlsdCg||n.cycles===0||c.has(e))continue;let r=[];if(n.channels.forEach((e,t)=>{Dt(e)?r.push(t):f++}),r.length!==0){for(let e of r){let t=n.channels[e].conv;t.k===`unsupported`&&d.push(`${n.channels[e].name}: ${t.what} is not supported; raw values are shown.`)}u.push({model:e,channels:r}),l.push({name:n.name,channels:r.map(e=>Ot(n.channels[e])),samples:n.cycles,time:n.master?{kind:`timestamps`}:{kind:`index`},rateHz:await kt(t,n)})}}if(f&&d.push(`${f} byte-array channel${f===1?` was`:`s were`} skipped.`),s){if(s.routes.length===0&&s.dbc.size===0){if(l.length===0)throw Error(`This MF4 has raw CAN frames. Drop its .dbc file together with it to decode signals.`);d.push(`This MF4 also has raw CAN frames. Drop its .dbc file together with it to decode signals.`)}for(let e of s.routes)u.push({model:e.model,route:e.route}),l.push(e.group);d.push(...s.notes)}if(l.length===0)throw Error(`This MDF file has no channels with samples.`);let p={model:a,groups:u,bus:s};return{format:a.version,startTime:a.startTime,groups:l,meta:a.meta,events:[],notes:d,interleaved:!!s?.routes.length||a.groups.some(e=>!e.sorted&&!e.vlsdCg),state:p}},async*stream(e){for(let t of Nt(e))yield*Mt(e,t)},streamGroup(e,t){return Mt(e,[t])}};function Ft(e){let t=[];for(let n of a(e).split(`\0`)){if(!n)continue;let e=n.split(``),r=parseFloat(e[0].split(``)[0]);Number.isFinite(r)&&t.push({onset:r,texts:e.slice(1).filter(e=>e.length>0)})}return t}function It(e,t){let n=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(e),r=/^(\d\d)\.(\d\d)\.(\d\d)$/.exec(t);if(!n||!r)return null;let i=Number(n[3]);return`${i>=85?1900+i:2e3+i}-${n[2]}-${n[1]}T${r[1]}:${r[2]}:${r[3]}`}var Lt=e=>`${+e.toFixed(6)} Hz`;function Rt(e,t,n,r,i,a,o,s){let{bit:c,off:l}=e;if(a===2)for(let e=0;e<i;e++)o[s+e]=c*(l+t.getInt16(r+2*e,!0));else for(let e=0,t=r;e<i;e++,t+=3)o[s+e]=c*(l+((n[t]|n[t+1]<<8|n[t+2]<<16)<<8>>8))}var zt={...e,async plan(e,t){let n=await t.read(0,256),r=(e,t)=>o(n.subarray(e,e+t)).trim(),i=n[0]===255,a=parseInt(r(252,4),10),s=parseInt(r(184,8),10),c=r(192,44),l=/^(EDF|BDF)\+/.test(c),u=/^(EDF|BDF)\+D/.test(c),d=parseFloat(r(244,8));if(!(a>0)||s!==256*(a+1)||!(d>0))throw Error(`This EDF/BDF header is damaged.`);let f=await t.read(256,a*256),p=(e,t,n)=>o(f.subarray(e*a+t*n,e*a+t*(n+1))).trim(),m=i?3:2,h=[],g=0;for(let e=0;e<a;e++){let t=parseFloat(p(104,8,e)),n=parseFloat(p(112,8,e)),r=parseFloat(p(120,8,e)),i=parseFloat(p(128,8,e)),a=Number(p(216,8,e));if(!(Number.isInteger(a)&&a>=0))throw Error(`This EDF/BDF header is damaged (samples per record).`);let o=(n-t)/(i-r);h.push({label:p(0,16,e),unit:p(96,8,e),spr:a,offset:g,bit:o,off:n/o-i}),g+=a*m}let _=g;if(!(_>0&&s+_<=t.size))throw Error(`This EDF/BDF file is damaged (its data records do not fit in it).`);let v=Math.floor((t.size-s)/_),y=parseInt(r(236,8),10),b=[];y>=0?y>v&&(b.push(`The file is shorter than its header says: ${v} of ${y} data records were read.`),y=v):y=v;let x=l?h.flatMap((e,t)=>/^(EDF|BDF) Annotations$/.test(e.label)?[t]:[]):[],S=new Map;h.forEach((e,t)=>{!x.includes(t)&&e.spr>0&&S.set(e.spr,[...S.get(e.spr)??[],t])});let ee=[...S.values()],C=ee.map(e=>{let t=h[e[0]].spr/d;return{name:Lt(t),channels:e.map(e=>({name:h[e].label,unit:h[e].unit})),samples:y*h[e[0]].spr,rateHz:t,time:u?{kind:`timestamps`}:{kind:`rate`,rate:t,start:0}}}),te={headerBytes:s,records:y,duration:d,recordBytes:_,bps:m,signals:h,groups:ee,annotations:x,discontinuous:u};return{format:`${i?`BDF`:`EDF`}${l?u?`+D`:`+`:``}`,startTime:It(r(168,8),r(176,8)),groups:C,meta:{patient:r(8,80),recording:r(88,80)},events:[],notes:u?[`Discontinuous recording: each gap shows as a break in the traces.`,...b]:b,state:te}},async*stream(e){let t=e.plan.state,n=Math.max(1,Math.floor(te/t.recordBytes)),r=e.selection.map(e=>({g:e.group,chans:e.channels.map(n=>t.signals[t.groups[e.group][n]]),spr:t.signals[t.groups[e.group][0]].spr})),i=r.map(()=>0),a=0,o=NaN;for await(let s of e.io.windows(t.headerBytes,t.records*t.recordBytes,n*t.recordBytes)){e.signal?.throwIfAborted();let n=Math.floor(s.bytes.length/t.recordBytes);if(n===0)break;let c=u(s.bytes),l=new Float64Array(n),d=[];for(let e=0;e<n;e++)l[e]=(a+e)*t.duration,t.annotations.forEach((n,r)=>{let i=t.signals[n],a=e*t.recordBytes+i.offset,o=Ft(s.bytes.subarray(a,a+i.spr*t.bps));r===0&&o.length&&(l[e]=o[0].onset);for(let e of o)for(let t of e.texts)d.push({time:e.onset,text:t})});let f=new Uint8Array(n),p=0;if(t.discontinuous)for(let e=0;e<n;e++){let n=e?l[e-1]+t.duration:o;n===n&&l[e]>n+1e-9&&(f[e]=1,p++)}for(let e=0;e<r.length;e++){let a=r[e],u=a.spr/t.duration,m=n*a.spr+p,h=t.discontinuous?new Float64Array(m):null,g=a.chans.map(()=>new Float64Array(m)),_=0;for(let e=0;e<n;e++){if(f[e]){h[_]=e?l[e-1]+t.duration:o;for(let e of g)e[_]=NaN;_++}if(h)for(let t=0;t<a.spr;t++)h[_+t]=l[e]+t/u;let n=e*t.recordBytes;a.chans.forEach((e,r)=>Rt(e,c,s.bytes,n+e.offset,a.spr,t.bps,g[r],_)),_+=a.spr}let v={group:a.g,time:h,start:i[e],length:m,columns:g};e===0&&d.length&&(v.events=d),i[e]+=m,yield v}o=l[n-1]+t.duration,a+=n}}},L={float32:4,double64:8,int8:1,int16:2,int32:4,int64:8};function R(e,t,n=0){let r=e.indexOf(`<${t}>`,n);if(r<0)return``;let i=e.indexOf(`</${t}>`,r);return i<0?``:e.slice(r+t.length+2,i).trim()}function Bt(e,t){let n=[];for(let r=e.indexOf(`<${t}>`);r>=0;){let i=e.indexOf(`</${t}>`,r);if(i<0)break;n.push(e.slice(r,i+t.length+3)),r=e.indexOf(`<${t}>`,i)}return n}var Vt=1e5,Ht=e=>e.fmt===`string`||L[e.fmt]!==void 0;function z(e,t,n){let r=e[n];if((r===1||r===4||r===8)&&n+1+r<=e.length)return r===1?[e[n+1],2]:r===4?[t.getUint32(n+1,!0),5]:[i(t,n+1),9];throw Error(`This XDF file is damaged (bad length field).`)}function Ut(e,t,n,r){if(n>=e.length)return-1;if(e[n++]===8&&(n+=8),r.fmt!==`string`)return n+L[r.fmt]*r.nch<=e.length?n+L[r.fmt]*r.nch:-1;for(let i=0;i<r.nch;i++){if(n>=e.length)return-1;let[r,i]=z(e,t,n);n+=i+r}return n<=e.length?n:-1}async function*Wt(e,t){let n=new Uint8Array;for await(let r of e.windows(4,e.size-4)){t?.throwIfAborted();let i=r.bytes,a=r.offset-n.length;if(n.length){let e=new Uint8Array(n.length+i.length);e.set(n),e.set(i,n.length),i=e}let o=u(i),s=0;for(;!(s+1>i.length);){let t=i[s];if(s+1+t>i.length)break;let[n,r]=z(i,o,s),c=s+r+n;if(a+c>e.size)return;if(c>i.length)break;yield{tag:i[s+r]|i[s+r+1]<<8,body:i.subarray(s+r+2,c)},s=c}n=i.slice(s)}}function Gt(e,t,n){let r=t-e.i0,i=n-e.t0;e.n++,e.si+=r,e.st+=i,e.sii+=r*r,e.sit+=r*i}function Kt(e){let t=e.n*e.sii-e.si*e.si;e.b=t>0?(e.n*e.sit-e.si*e.st)/t:0,e.a=(e.st-e.b*e.si)/Math.max(1,e.n)}function qt(e){if(e.length===0)return[0,0];if(e.length===1)return[e[0][1],0];let t={i0:e[0][0],t0:0,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0};for(let[n,r]of e)Gt(t,n,r);return Kt(t),[t.a-t.b*t.i0,t.b]}function Jt(e,t,n){let r=t.t0+t.a+t.b*(n-t.i0);return r+e.c0+e.c1*r}var Yt={...v,async plan(e,t){let n=new Map,r=``;for await(let e of Wt(t)){let t=u(e.body);if(e.tag===1)r=a(e.body);else if(e.tag===2){let r=t.getUint32(0,!0),i=a(e.body.subarray(4)),o=parseInt(R(i,`channel_count`),10)||1;if(!(o>=1&&o<=Vt))throw Error(`This XDF file is damaged (a stream with ${o} channels).`);let s=Bt(i,`channel`);n.set(r,{id:r,name:R(i,`name`)||`Stream ${r}`,nch:o,srate:parseFloat(R(i,`nominal_srate`))||0,fmt:R(i,`channel_format`)||`float32`,labels:Array.from({length:o},(e,t)=>R(s[t]??``,`label`)||`Ch${t+1}`),units:Array.from({length:o},(e,t)=>R(s[t]??``,`unit`)),count:0,segs:[],clock:[],c0:0,c1:0,lastTs:NaN})}else if(e.tag===3){let r=n.get(t.getUint32(0,!0));if(!r||!Ht(r))continue;let[i,a]=z(e.body,t,4),o=4+a,s=L[r.fmt],c=r.srate>0?Math.max(1,500/r.srate):1/0;for(let n=0;n<i&&!(Ut(e.body,t,o,r)<0);n++){let n;if(e.body[o++]===8?(n=t.getFloat64(o,!0),o+=8):n=r.lastTs+(r.srate>0?1/r.srate:0),r.fmt===`string`)for(let n=0;n<r.nch;n++){let[n,r]=z(e.body,t,o);o+=r+n}else o+=s*r.nch;if(r.srate>0){let e=r.segs[r.segs.length-1];(!e||n-r.lastTs>c)&&r.segs.push(e={i0:r.count,t0:n,n:0,si:0,st:0,sii:0,sit:0,a:0,b:0}),Gt(e,r.count,n)}else r.count===0&&r.segs.push({i0:0,t0:n,n:1,si:0,st:0,sii:0,sit:0,a:0,b:0});r.lastTs=n,r.count++}}else if(e.tag===4){let e=n.get(t.getUint32(0,!0));e&&e.clock.push([t.getFloat64(4,!0),t.getFloat64(12,!0)])}}let i=[],o=[...n.values()].sort((e,t)=>e.id-t.id).filter(e=>(Ht(e)||i.push(`${e.name}: channel format ${e.fmt} is not supported; skipped.`),Ht(e))),s=1/0;for(let e of o){[e.c0,e.c1]=qt(e.clock);for(let t of e.segs)Kt(t);if(e.count===0)continue;let t=e.srate>0?Jt(e,e.segs[0],0):e.segs[0].t0+e.c0+e.c1*e.segs[0].t0;s=Math.min(s,t)}let c=re(o.map(e=>e.name),[]),l=o.map((e,t)=>({name:c[t],channels:e.labels.map((t,n)=>({name:t,unit:e.units[n],...e.fmt===`string`?{text:!0,sparse:!0}:{}})),samples:e.count,time:{kind:`timestamps`},rateHz:e.srate>0?e.srate:null,irregular:e.srate===0})),d=R(r,`version`);return{format:`XDF ${d||`1.0`}`,startTime:null,groups:l,meta:{header:d},events:[],notes:i,state:{streams:o,origin:Number.isFinite(s)?s:0}}},async*stream(e){let t=e.plan.state,n=8192,r=new Map,i=e=>e.sel.map(()=>e.s.fmt===`string`?Array(n):new Float64Array(n));for(let a of e.selection){let o=t.streams[a.group],s={g:a.group,s:o,sel:w(e,a.group),time:new Float64Array(n),cols:[],n:0,start:0,seg:0,i:0,raw:NaN};s.cols=i(s),r.set(o.id,s)}let o=e=>{let t={group:e.g,time:e.time.slice(0,e.n),start:e.start,length:e.n,columns:e.cols.map(t=>t.slice(0,e.n))};return e.start+=e.n,e.n=0,e.time=new Float64Array(n),e.cols=i(e),t};for await(let i of Wt(e.io,e.signal)){if(i.tag!==3)continue;let e=u(i.body),s=r.get(e.getUint32(0,!0));if(!s)continue;let c=s.s,[l,d]=z(i.body,e,4),f=4+d,p=L[c.fmt],m=[];for(let r=0;r<l&&!(Ut(i.body,e,f,c)<0);r++){let r;i.body[f++]===8?(r=e.getFloat64(f,!0),f+=8):r=s.raw+(c.srate>0?1/c.srate:0),s.raw=r;let l;if(c.srate>0){for(;s.seg+1<c.segs.length&&c.segs[s.seg+1].i0<=s.i;)s.seg++;l=Jt(c,c.segs[s.seg],s.i)}else l=r+c.c0+c.c1*r;if(s.time[s.n]=l-t.origin,c.fmt===`string`){let n=[];for(let t=0;t<c.nch;t++){let[t,r]=z(i.body,e,f);n.push(a(i.body.subarray(f+r,f+r+t))),f+=r+t}s.sel.forEach((e,t)=>{s.cols[t][s.n]=n[e]}),m.push({time:l-t.origin,text:n.join(` `)})}else s.sel.forEach((t,n)=>{let r=f+t*p,i=s.cols[n];switch(c.fmt){case`float32`:i[s.n]=e.getFloat32(r,!0);break;case`double64`:i[s.n]=e.getFloat64(r,!0);break;case`int8`:i[s.n]=e.getInt8(r);break;case`int16`:i[s.n]=e.getInt16(r,!0);break;case`int32`:i[s.n]=e.getInt32(r,!0);break;default:i[s.n]=e.getInt32(r+4,!0)*4294967296+e.getUint32(r,!0)}}),f+=p*c.nch;s.i++,++s.n===n&&(yield o(s))}m.length&&(yield{group:s.g,time:new Float64Array,start:s.start,length:0,columns:s.sel.map(()=>new Float64Array),events:m})}for(let e of r.values())e.n&&(yield o(e))}},Xt=2,Zt=8,Qt=4,$t=32,en=64,tn=4713,nn=4714,B=32,V=68,H={1:1,2:2,3:4,4:8,5:1,6:2,7:4,8:8,9:4,10:8,25:4,26:8,33:1,68:16},rn={0:5,1:1,2:6,3:2,4:7,5:3,6:8,7:4,8:9,9:10,4294967295:V},an=65536,on=65536,sn=(e,t,n)=>n?l(e,t+8,n)+i(e,t,n)/2**64:l(e,t,n)+i(e,t+8,n)/2**64;function cn(e,t,n,r,o){switch(r){case B:{let r=e.getUint32(n,o);return[a(t.subarray(n+4,n+4+r)),4+r]}case 1:return[e.getInt8(n),1];case 2:return[e.getInt16(n,o),2];case 3:return[e.getInt32(n,o),4];case 4:return[l(e,n,o),8];case 5:return[e.getUint8(n),1];case 6:return[e.getUint16(n,o),2];case 7:return[e.getUint32(n,o),4];case 8:return[i(e,n,o),8];case 9:case 25:return[e.getFloat32(n,o),4];case 10:case 26:return[e.getFloat64(n,o),8];case 33:return[e.getUint8(n)!==0,1];case V:return[sn(e,n,o),16];default:throw Error(`This TDMS file has a property of type ${r}, which Kymoscope cannot read.`)}}function ln(e){let t=/^\/'((?:[^']|'')*)'(?:\/'((?:[^']|'')*)')?$/.exec(e);return t?[t[1].replace(/''/g,`'`),(t[2]??``).replace(/''/g,`'`)]:null}var un=4294967295;function dn(e){if(e.has(`NI_Number_Of_Scales`))return Number(e.get(`NI_Number_Of_Scales`));let t=0;for(let n of e.keys()){let e=/^NI_Scale\[(\d+)\]_Scale_Type$/.exec(n);e&&(t=Math.max(t,Number(e[1])+1))}return t}function fn(e,t,n){let r=e.find(e=>dn(e)>0);if(!r||r.get(`NI_Scaling_Status`)===`scaled`)return null;let i=(e,a)=>{if(e===un||e<0||a>8)return e=>e;let o=r.get(`NI_Scale[${e}]_Scale_Type`);if(o===void 0)return e=>e;if(o===`Linear`){let t=Number(r.get(`NI_Scale[${e}]_Linear_Slope`)),n=Number(r.get(`NI_Scale[${e}]_Linear_Y_Intercept`)??0),o=i(Number(r.get(`NI_Scale[${e}]_Linear_Input_Source`)??un),a+1);return o&&(e=>t*o(e)+n)}if(o===`Polynomial`){let o=Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients_Size`)??4);if(!(Number.isInteger(o)&&o>=0&&o<=64))return t.push(`${n}: an NI polynomial scale with ${o} coefficients is not supported; raw values are shown.`),null;let s=Array.from({length:o},(t,n)=>Number(r.get(`NI_Scale[${e}]_Polynomial_Coefficients[${n}]`))),c=i(Number(r.get(`NI_Scale[${e}]_Polynomial_Input_Source`)??un),a+1);return c&&(e=>{let t=c(e),n=0;for(let e=o-1;e>=0;e--)n=n*t+s[e];return n})}return t.push(`${n}: NI scale type ${String(o)} is not supported; raw values are shown.`),null};return i(dn(r)-1,0)}var pn={1:Int8Array,2:Int16Array,3:Int32Array,5:Uint8Array,6:Uint16Array,7:Uint32Array,9:Float32Array,10:Float64Array,25:Float32Array,26:Float64Array,33:Uint8Array};function mn(e,t,n,r,a,o,s,c){let u=pn[e];if(u&&o&&r===H[e]&&(t.byteOffset+n)%r===0){s.set(new u(t.buffer,t.byteOffset+n,a),c);return}switch(e){case 1:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getInt8(n);return;case 2:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getInt16(n,o);return;case 3:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getInt32(n,o);return;case 4:for(let e=0;e<a;e++,n+=r)s[c+e]=l(t,n,o);return;case 5:case 33:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getUint8(n);return;case 6:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getUint16(n,o);return;case 7:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getUint32(n,o);return;case 8:for(let e=0;e<a;e++,n+=r)s[c+e]=i(t,n,o);return;case 9:case 25:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getFloat32(n,o);return;case 10:case 26:for(let e=0;e<a;e++,n+=r)s[c+e]=t.getFloat64(n,o);return;case V:for(let e=0;e<a;e++,n+=r)s[c+e]=sn(t,n,o);return;default:s.fill(NaN,c,c+a)}}async function hn(e,t,n){let r=new Map,o=[],s=[],c=new Map,l=new Map,d=t??e,f=0,p=0;for(;f+28<=e.size&&p+28<=d.size;){let m=t?p:f,h=await d.read(m,28),g=u(h);if(!(h[0]===84&&h[1]===68&&h[2]===83&&(h[3]===109||h[3]===104)))throw Error(`This TDMS file is damaged (no segment lead-in where one should be).`);let _=g.getUint32(4,!0),v=!(_&en),y=i(g,12,v),b=i(g,20,v),x=y>=2**53?e.size:Math.min(e.size,f+28+y);if(b>x-f-28)throw Error(`This TDMS file is damaged (segment metadata longer than its segment).`);if(_&Xt){let e=await d.read(m+28,b),t=u(e);_&Qt&&(s=[],c=new Map);let o=0,f=t.getUint32(o,v);o+=4;for(let u=0;u<f;u++){let u=t.getUint32(o,v),d=a(e.subarray(o+4,o+4+u));o+=4+u;let f=ln(d),p=r.get(d);p||r.set(d,p={path:d,group:f?.[0]??``,name:f?.[1]??``,type:0,props:new Map,pieces:[],total:0});let m=t.getUint32(o,v);o+=4;let h=null;if(m===4294967295)h=null;else if(m===0)h=l.get(p)??null;else if(m===tn||m===nn){let e=i(t,o+8,v),r=t.getUint32(o+16,v),a=m===tn?20:17,s=o+20,c=rn[t.getUint32(s,v)]??0,l=t.getUint32(s+8,v);o=s+r*a;let u=t.getUint32(o,v);o+=4;let d=0;for(let e=0;e<u;e++)d+=t.getUint32(o+4*e,v);o+=4*u,m===nn?n.push(`${p.name}: DAQmx digital line data is not supported; skipped.`):(r>1&&n.push(`${p.name}: only the first of its ${r} DAQmx scalers is read.`),h={type:c,count:e,bytes:0,daqmx:{byteOffset:l,stride:d}})}else{let e=t.getUint32(o,v),n=i(t,o+8,v),r=e===B?i(t,o+16,v):n*(H[e]??0);o+=m-4,h={type:e,count:n,bytes:r,daqmx:null}}h&&(p.type=h.type,l.set(p,h));let g=t.getUint32(o,v);o+=4;for(let n=0;n<g;n++){let n=t.getUint32(o,v),r=a(e.subarray(o+4,o+4+n));o+=4+n;let i=t.getUint32(o,v);o+=4;let[s,c]=cn(t,e,o,i,v);p.props.set(r,s),o+=c}let _=c.get(p);_===void 0?c.set(p,s.push({obj:p,idx:h})-1):s[_].idx=h}}if(_&Zt){let e=f+28+b,t=s.filter(e=>e.idx&&e.idx.count>0),n=t.filter(e=>e.idx.daqmx),r=(_&$t)!==0,i=0,a=0;n.length?(a=n[0].idx.daqmx.stride,i=n[0].idx.count*a):r?(a=t.reduce((e,t)=>e+(H[t.idx.type]??0),0),i=(t[0]?.idx.count??0)*a):i=t.reduce((e,t)=>e+t.idx.bytes,0);let c=i>0?Math.floor((x-e)/i):0,l=o.push({rawStart:e,chunkSize:i,chunks:c,le:v})-1,u=0;for(let e of t){let t=e.idx,n=H[t.type]??0,o=t.daqmx?{seg:l,count:t.count,offset:t.daqmx.byteOffset,bytes:0,stride:a,type:t.type}:{seg:l,count:t.count,offset:u,bytes:t.bytes,stride:r?a:n,type:t.type};t.daqmx||(u+=r?n:t.bytes),o.type===B?o.count=Math.min(o.count,Math.floor(o.bytes/4)):n>0&&(o.count=Math.min(o.count,o.stride>0?Math.max(0,Math.floor((i-o.offset-n)/o.stride)+1):0)),e.obj.pieces.push(o),c&&(e.obj.total+=o.count*c)}}if(f=x,p+=28+b,x>=e.size)break}return{objs:[...r.values()],segments:o}}var gn={...c,async plan(e,t){let n=e.companions.find(e=>e.name.toLowerCase().endsWith(`.tdms_index`)),r=[],{objs:i,segments:a}=await hn(t,n?new p(n):null,r),o=i.find(e=>e.path===`/`)?.props,s=i.filter(e=>e.name&&e.total>0&&(e.type===B||H[e.type])),c=new Set(s);for(let e of i)e.name&&e.total>0&&!c.has(e)&&r.push(`${e.name}: TDMS data type ${e.type} is not supported; skipped.`);let l=s.map(e=>e.props.get(`wf_start_time`)).filter(e=>typeof e==`number`),d=l.reduce((e,t)=>Math.min(e,t),l.length?1/0:0),f=new Map;for(let e of s){let t=`${e.total}|${e.props.get(`wf_increment`)??``}`,n=f.get(e.group)??new Map,r=n.get(t);r?r.push(e):n.set(t,[e]),f.set(e.group,n)}let m=[],h=[];for(let[e,t]of f)for(let n of t.values()){let r=n[0].props.get(`wf_increment`),i=typeof r==`number`&&r>0?1/r:null,a=i?null:n.find(e=>e.type===V)??n.find(e=>e.type!==B&&/^(time|timestamp|t)$/i.test(e.name))??null,o=n.filter(e=>e!==a),s=n[0].props.get(`wf_start_time`),c=i?Number(n[0].props.get(`wf_start_offset`)??0)+(typeof s==`number`?s-d:0):0;m.push({name:t.size===1?e:`${e} (${i?+i.toFixed(6):n[0].total} ${i?`Hz`:`samples`})`,channels:o.map(e=>({name:e.name,unit:String(e.props.get(`unit_string`)??``),text:e.type===B})),samples:n[0].total,time:i?{kind:`rate`,rate:i,start:c}:a?{kind:`timestamps`}:{kind:`index`},rateHz:i}),h.push({channels:o,time:a,origin:0})}if(m.length===0)throw Error(`This TDMS file has no channels with data.`);let g=[];for(let e of h){if(!e.time)continue;let n=e.time.pieces[0],r=a[n.seg],i=await t.read(r.rawStart+n.offset,H[n.type]??8),o=new Float64Array(1);mn(n.type,u(i),0,0,1,r.le,o,0),g.push(o[0])}let _=g.reduce((e,t)=>Math.min(e,t),g.length?1/0:0);for(let e of h)e.origin=_;let v=new Date(Date.UTC(1904,0,1)+d*1e3),y=d&&Number.isFinite(v.getTime())?v.toISOString():null,b={objs:i,segments:a,groups:h},x={};for(let[e,t]of o??[])typeof t==`string`&&(x[e]=t);return{format:`TDMS`,startTime:y,groups:m,meta:x,events:[],notes:r,state:b}},async*stream(e){for(let t of e.selection)yield*vn(e,t.group)},streamGroup:(e,t)=>vn(e,t)};function _n(e,t,n,r,i,a){let o=0;for(;o<i&&r.pi<t.pieces.length;){let s=t.pieces[r.pi],c=e.segments[s.seg];if(r.chunk>=c.chunks){r.pi++,r.chunk=0,r.row=0;continue}let l=Math.min(i-o,s.count-r.row),u=c.rawStart+r.chunk*c.chunkSize+s.offset;if(s.type===B)a.push({ch:n,at:u,end:u+s.bytes,rows:l,first:r.row,out:o,piece:s,le:c.le,range:0});else{let e=u+r.row*s.stride;a.push({ch:n,at:e,end:e+(l-1)*s.stride+H[s.type],rows:l,first:r.row,out:o,piece:s,le:c.le,range:0})}o+=l,r.row+=l,r.row>=s.count&&(r.chunk++,r.row=0)}}async function*vn(e,t){let n=e.plan.state,r=n.groups[t],i=w(e,t).map(e=>r.channels[e]),o=r.time?[r.time,...i]:i;if(!o.length)return;let s=new Map(n.objs.map(e=>[e.path,e.props])),c=e=>s.get(e)??new Map,l=c(`/`),d=o.map(e=>fn([e.props,c(`/'${e.group.replace(/'/g,`''`)}'`),l],[],e.name)),f=o.map(()=>({pi:0,chunk:0,row:0})),p=o.reduce((e,t)=>Math.min(e,t.total),1/0);for(let i=0;i<p;){e.signal?.throwIfAborted();let s=Math.min(an,p-i),c=[];o.forEach((e,t)=>_n(n,e,t,f[t],s,c));let l=c.slice().sort((e,t)=>e.at-t.at),m=[];for(let e of l){let t=m[m.length-1];t&&e.at<=t.end+on&&Math.max(t.end,e.end)-t.at<=16777216?t.end=Math.max(t.end,e.end):m.push({at:e.at,end:e.end}),e.range=m.length-1}let h=[];for(let t of m)h.push(await e.io.slice(t.at,t.end-t.at));let g=h.map(u),_=o.map(e=>e.type===B?Array(s).fill(null):new Float64Array(s).fill(NaN));for(let e of c){let t=e.at-m[e.range].at,n=e.piece;if(n.type===B){let r=h[e.range],i=g[e.range],o=t+4*n.count,s=_[e.ch];for(let n=0;n<e.rows;n++){let c=e.first+n,l=c===0?0:i.getUint32(t+4*(c-1),e.le),u=i.getUint32(t+4*c,e.le);s[e.out+n]=a(r.subarray(o+l,o+u))}}else mn(n.type,g[e.range],t,n.stride,e.rows,e.le,_[e.ch],e.out)}for(let e=0;e<o.length;e++){let t=d[e],n=_[e];if(t&&n instanceof Float64Array)for(let e=0;e<s;e++)n[e]=t(n[e])}let v=null;if(r.time){v=_.shift();for(let e=0;e<s;e++)v[e]-=r.origin}yield{group:t,time:v,start:i,length:s,columns:_},i+=s}}var yn=e=>!!e&&typeof e.keys==`function`,bn=1e5;function xn(){let e=new Set,t=0,n=!1;return{enter(t){let r=null;try{r=t.create_reference?Array.prototype.join.call(t.create_reference().ref_data,`,`):null}catch{r=null}return r===null?!0:e.has(r)?(n=!0,!1):(e.add(r),!0)},count:()=>++t<=bn,note:()=>t>1e5?`This file has more than ${bn.toLocaleString(`en-US`)} objects (or links that repeat its groups); only the first were read.`:n?`Some groups of this file link back to a group already read; each was read once.`:null}}function Sn(e,t,n,r){return t.reduce((e,t)=>e*t,1)*Math.max(1,e.metadata.size||1)>(r?n*1032+1024:n)}var Cn=e=>!!e&&typeof e.slice==`function`,U=null,W=null,G=new WeakMap;function wn(){!U||W||(W=U(),W.catch(()=>{W=null}))}function Tn(e){if(!U)return Promise.reject(Error(`HDF5 and MAT 7.3 files are read in the import worker, and this environment has no workers.`));wn();let t=G.get(e);return t||(t=W.then(t=>t(e)).then(e=>({root:e.root,close:()=>{}})),G.set(e,t),t.catch(()=>G.delete(e))),t}var En=new WeakMap;function K(e,t,n){let r=En.get(e);r||En.set(e,r=new Map);let i=r.get(t);return i||r.set(t,i=n??e.get(t)),i}function q(e){return e instanceof Float64Array?e:e instanceof BigInt64Array||e instanceof BigUint64Array?Float64Array.from(e,e=>Number(e)):ArrayBuffer.isView(e)?new Float64Array(e):Float64Array.from(e)}var Dn={s:1,sec:1,second:1,seconds:1,ms:.001,msec:.001,us:1e-6,µs:1e-6,ns:1e-9};function J(e,...t){for(let n of t){let t=e[n]?.value;if(typeof t==`string`)return t;if(Array.isArray(t)&&typeof t[0]==`string`)return t[0]}return``}function On(e,...t){for(let n of t){let t=e[n]?.value,r=typeof t==`number`?t:ArrayBuffer.isView(t)?Number(t[0]):NaN;if(Number.isFinite(r))return r}return null}var kn=0,An=1,jn=3,Mn=6,Nn=new Set([1,2,3,4,5,6]),Pn=/^(time|t|timestamps?|.*[_ ]time|time[_ ].*)$/i,Fn=[`sampling_rate`,`sample_rate`,`samplerate`,`sampleRate`,`fs`,`Fs`,`rate`];function In(e,t,n,r,i,a,o=0){i.set(n,t.attrs);for(let s of t.keys()){if(!a.count())return;let c=n===`/`?`/${s}`:`${n}/${s}`,l=t.get(s);if(yn(l))o<16&&a.enter(l)&&In(e,l,c,r,i,a,o+1);else if(Cn(l)){let t=K(e,c,l);r.push({path:c,parent:n,name:s,ds:t,attrs:t.attrs})}}}var Y=e=>e===`/`?`root`:e.slice(1),Ln=e=>Math.max(4096,Math.min(1<<20,Math.floor((8<<20)/(8*Math.max(1,e)))));async function Rn(e,t){let n=K(e,t.path);if(t.col===null)return q(n.slice([[0,1]]))[0]*t.factor;let r=n.slice([[0,1]]);return Number(r[0][t.col])*t.factor}var zn={...n,async plan(e){let t=await Tn(e.main);try{let n=[],r=new Map,i=xn();i.enter(t.root),In(t.root,t.root,`/`,n,r,i);let a=[],o=i.note();o&&a.push(o);let s=new Map,c=[],l=0;for(let t of n){let n=t.ds.metadata.shape??[],r=t.ds.metadata.type,i=t.ds.metadata.chunks?t.ds.filters??[]:[],o=i.find(e=>!Nn.has(e.id)),u=!o;if(u&&i.length>0&&n.length>0&&n.every(e=>e>0))try{t.ds.slice(n.map(()=>[0,1]))}catch{u=!1}if(!u){a.push(`${t.path}: compressed with a filter Kymoscope cannot read${o?` (${o.name||o.id})`:``}; skipped.`);continue}if(Sn(t.ds,n,e.main.size,i.length>0)){a.push(`${t.path}: larger than the file can hold (never written, or damaged); skipped.`);continue}if(n.length===1&&n[0]>1&&(r===kn||r===An||r===jn)){let e=`${t.parent}|${n[0]}`,r=s.get(e)??{parent:t.parent,n:n[0],leaves:[]};r.leaves.push(t),s.set(e,r)}else if(n.length===2&&n[0]>1&&n[1]<=4096&&(r===kn||r===An)){let e=On(t.attrs,...Fn);c.push({name:Y(t.path),kind:`matrix`,rows:n[0],rate:e,time:null,origin:0,cols:Array.from({length:n[1]},(e,n)=>({path:t.path,col:n,text:!1,factor:1}))})}else if(n.length===1&&r===Mn){let e=(t.ds.metadata.compound_type?.members??[]).flatMap((e,n)=>e.type===kn||e.type===An?[{path:t.path,col:n,text:!1,factor:1,name:e.name}]:[]),r=e.find(e=>Pn.test(e.name));c.push({name:Y(t.path),kind:`compound`,rows:n[0],rate:null,origin:0,time:r??null,cols:e.filter(e=>e!==r)})}else l++}for(let e of s.values()){let t=[...s.values()].filter(t=>t.parent===e.parent).length>1,n=e.leaves.find(e=>J(e.attrs,`CLASS`)===`DIMENSION_SCALE`)??e.leaves.find(e=>Pn.test(e.name)&&e.ds.metadata.type!==jn),i=n?Dn[J(n.attrs,`units`,`unit`,`Units`)]??1:1,a=n?null:On(r.get(e.parent)??{},...Fn);c.push({name:t?`${Y(e.parent)} (${e.n} rows)`:Y(e.parent),kind:`vectors`,rows:e.n,rate:a,origin:0,time:n?{path:n.path,col:null,text:!1,factor:i}:null,cols:e.leaves.filter(e=>e!==n).map(e=>({path:e.path,col:null,text:e.ds.metadata.type===jn,factor:1}))})}l&&a.push(`${l} dataset${l===1?``:`s`} with other shapes or types (images, references, 3-D) skipped.`),c.sort((e,t)=>e.name.localeCompare(t.name));let u=c.map((e,t)=>e.time||e.rate?t:-1).filter(e=>e>=0),d=1/0;for(let e of c)e.time&&(d=Math.min(d,await Rn(t.root,e.time)));for(let e of c)e.origin=Number.isFinite(d)?d:0;let f=new Map(n.map(e=>[e.path,e]));for(let e of c)e.chunk=[...e.cols,...e.time?[e.time]:[]].reduce((e,t)=>Math.max(e,f.get(t.path).ds.metadata.chunks?.[0]??0),0);let p=e=>J(f.get(e.path).attrs,`units`,`unit`,`Units`,`UNITS`),m=(e,t)=>e.kind===`matrix`?`${e.name.split(`/`).pop()}[${t.col+1}]`:e.kind===`compound`?f.get(t.path).ds.metadata.compound_type.members[t.col].name:t.path.split(`/`).pop(),h=c.map(e=>({name:e.name,channels:e.cols.map(t=>({name:m(e,t),unit:e.kind===`vectors`?p(t):``,text:t.text})),samples:e.rows,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}));if(h.length===0)throw Error(`This HDF5 file has no datasets Kymoscope can plot.`);let g=h.length>20||h.length>1&&u.length<h.length,_=g?u.length?u:[c.reduce((e,t,n)=>t.rows*t.cols.length>c[e].rows*c[e].cols.length?n:e,0)]:void 0;return g&&a.push(`Only the groups with a time base are read unless you choose others in the channel picker.`),{format:`HDF5`,startTime:null,groups:h,meta:{},events:[],notes:a,pick:g,defaultGroups:_,state:{groups:c}}}finally{t.close()}},async*stream(e){for(let t of e.selection)yield*Bn(e,t.group)},streamGroup:(e,t)=>Bn(e,t)};async function*Bn(e,t){let n=e.plan.state.groups[t],r=w(e,t).map(e=>n.cols[e]),i=await Tn(e.files.main);try{let a=n.chunk??0,o=a>0?Math.max(1,Math.min(Math.floor((1<<20)/a),Math.ceil(Ln(r.length+1)/a)))*a:Ln(r.length+1);for(let a=0;a<n.rows;a+=o){e.signal?.throwIfAborted();let s=Math.min(n.rows,a+o),c=s-a,l=null,u=e=>{let t=K(i.root,e.path);if(n.kind===`vectors`){let n=t.slice([[a,s]]);if(e.text)return Array.from(n,e=>e==null?null:String(e));let r=q(n);if(e.factor!==1)for(let t=0;t<c;t++)r[t]*=e.factor;return r}let r=new Float64Array(c);if(n.kind===`matrix`){let n=(t.shape??[0,1])[1],i=l??=t.slice([[a,s],[0,n]]);for(let t=0;t<c;t++)r[t]=Number(i[t*n+e.col])}else{let n=l??=t.slice([[a,s]]);for(let t=0;t<c;t++)r[t]=Number(n[t][e.col])*e.factor}return r},d=null;if(n.time){d=u(n.time);for(let e=0;e<c;e++)d[e]-=n.origin}yield{group:t,time:d,start:a,length:c,columns:r.map(u)}}}finally{i.close()}}var Vn=/^(time|t|tout|timestamps?)$/i,Hn=/^(fs|sample_?rate|sampling_?rate|rate|samplerate)$/i,Un=e=>e.slice(e.lastIndexOf(`.`)+1),Wn=e=>e.includes(`.`)?e.slice(0,e.lastIndexOf(`.`)):``;function Gn(e,t){let n=/^(.*)\.values(\[\d+\])?$/.exec(e.name),r=n&&(t.get(`${n[1]}.label`)||t.get(`${n[1]}.blockName`));return r?{...e,name:`${r}${n[2]??``}`}:e}function Kn(e,t,n){let r=new Map;for(let t of e){if(!(t.length>1))continue;let e=r.get(t.length);e?e.push(t):r.set(t.length,[t])}let i=[...n].filter(([e])=>Hn.test(Un(e))),a=i.length===1?i[0][1]:null,o=[];for(let[e,n]of r){let r=n.find(e=>Vn.test(Un(e.name))||/(_time|\.Time)$/.test(e.name))??null;o.push({name:r?Wn(r.name)||r.name:`${e} samples`,channels:n.filter(e=>e!==r).map(e=>Gn(e,t)),time:r,rate:r?null:a,origin:0})}return o}function qn(e){return e.map(e=>({name:e.name,channels:e.channels.map(e=>({name:e.name,unit:``})),samples:e.channels[0]?.length??e.time?.length??0,time:e.time?{kind:`timestamps`}:e.rate?{kind:`rate`,rate:e.rate,start:0}:{kind:`index`},rateHz:e.rate}))}async function Jn(e){let t=1/0;for(let n of e)n.time&&(t=Math.min(t,(await n.time.read(0,1))[0]));for(let n of e)n.origin=Number.isFinite(t)?t:0}var Yn=class{#e;size;constructor(e){this.#e=e,this.size=e.size}read(e,t){return t>=65536?this.#e.slice(e,t):this.#e.read(e,t)}release(){}},Xn=class{#e;#t;#n;#r=null;keep=!0;size;constructor(e,t,n,r){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.size=r.length}async read(e,t){return this.#r??=await N(await this.#e.slice(this.#t,this.#n),this.size,this.size),this.#r.subarray(e,e+t)}release(){this.keep||(this.#r=null)}},X={1:1,2:1,3:2,4:2,5:4,6:4,7:4,9:8,12:8,13:8};function Z(e,t,n,r,i=1){let a=u(t),o=r.length,s=X[e]*i;if(e===9&&i===1&&n){r.set(t.byteOffset%8==0?new Float64Array(t.buffer,t.byteOffset,o):new Float64Array(t.slice(0,o*8).buffer));return}switch(e){case 1:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt8(t);return;case 2:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint8(t);return;case 3:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt16(t,n);return;case 4:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint16(t,n);return;case 5:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t,n);return;case 6:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t,n);return;case 7:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat32(t,n);return;case 9:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getFloat64(t,n);return;case 12:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getInt32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;case 13:for(let e=0,t=0;e<o;e++,t+=s)r[e]=a.getUint32(t+(n?4:0),n)*4294967296+a.getUint32(t+(n?0:4),n);return;default:r.fill(NaN)}}async function Q(e,t,n){let r=u(await e.read(t,8)),i=r.getUint32(0,n);if(i>>>16)return{type:i&65535,bytes:i>>>16,data:t+4,next:t+8};let a=r.getUint32(4,n);return{type:i,bytes:a,data:t+8,next:i===15?t+8+a:t+8+a+(8-a%8)%8}}function Zn(e,t,n,r,i){let[a,o]=t,s=X[r.type];if(!s)return[];let c=(e,t)=>async(a,o)=>{let c=new Float64Array(o-a);return t===1?Z(r.type,await n.read(r.data+(e+a)*s,(o-a)*s),i,c):Z(r.type,await n.read(r.data+(e+a*t)*s,((o-a-1)*t+1)*s),i,c,t),c};return a===1||o===1?[{name:e,length:a*o,read:c(0,1)}]:a>=o?Array.from({length:o},(t,n)=>({name:`${e}[${n+1}]`,length:a,read:c(n*a,1)})):Array.from({length:a},(t,n)=>({name:`${e}[${n+1}]`,length:o,read:c(n,a)}))}async function Qn(e,t,n,r,i,c,l){let d=t,f=await Q(e,d,n),p=u(await e.read(f.data,8)).getUint32(0,n),m=p&255;d=f.next;let h=await Q(e,d,n);if(h.bytes>128){c.notes.push(`A MAT variable with more than 32 dimensions was skipped (damaged).`);return}let g=u(await e.read(h.data,h.bytes)),_=Array.from({length:h.bytes/4},(e,t)=>g.getInt32(4*t,n));d=h.next;let v=await Q(e,d,n),y=o(await e.read(v.data,v.bytes));d=v.next;let b=i??y,x=r?`${r}.${b}`:b,S=_.reduce((e,t)=>e*t,1);if(m>=6&&m<=15){if(S===0)return;let t=await Q(e,d,n);if(p&2048&&c.notes.push(`${x}: the imaginary part was skipped.`),_.length>2){c.notes.push(`${x}: arrays with more than two dimensions are skipped.`);return}if(!X[t.type])return;if(!(S>0)||S*X[t.type]>t.bytes||t.data+t.bytes>e.size){c.notes.push(`${x}: its data is shorter than its dimensions (damaged); skipped.`);return}if(S===1){let r=new Float64Array(1);Z(t.type,await e.read(t.data,X[t.type]??8),n,r),c.scalars.set(x,r[0]);return}c.channels.push(...Zn(x,_,e,t,n));return}if(m===4){let t=await Q(e,d,n);if(t.bytes>$n)return;let r=await e.read(t.data,t.bytes),i=t.type===3||t.type===4||t.type===17?new TextDecoder(n?`utf-16le`:`utf-16be`).decode(r.subarray(0,r.length&-2)):a(r);_[0]<=1&&c.strings.set(x,i);return}if(m===2){let t=await Q(e,d,n),r=u(await e.read(t.data,4)).getInt32(0,n);d=t.next;let i=await Q(e,d,n);if(!(r>0))return;let a=await e.read(i.data,i.bytes),o=Array.from({length:Math.floor(a.length/r)},(e,t)=>s(a.subarray(t*r,(t+1)*r)));if(d=i.next,o.length===0||S*o.length*8>e.size-d){S>0&&o.length>0&&c.notes.push(`${x}: its fields are longer than the file (damaged); skipped.`);return}for(let t=0;t<S;t++){let r=S>1?`${x}(${t+1})`:x;for(let t of o){let i=await Q(e,d,n);i.type===14&&i.bytes>0&&l<16&&await Qn(e,i.data,n,r,t,c,l+1),d=i.next}}return}m===1?c.notes.push(`${x}: cell arrays are skipped.`):m===5?c.notes.push(`${x}: sparse arrays are skipped.`):c.notes.includes(er)||c.notes.push(er)}var $n=1<<17,er=`MATLAB objects (timeseries, SimulationOutput) were skipped: save them as 'Structure with time' or as structs.`,tr=512<<20;async function nr(e){let t=o((await e.read(0,128)).subarray(126,128))===`IM`,n={channels:[],strings:new Map,scalars:new Map,notes:[],sources:[]},r=new Yn(e),i=0;for(let a=128;a+8<=e.size;){let o=await Q(r,a,t);if(o.type===15){if(o.bytes>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let r=await e.slice(o.data,o.bytes),a=await N(r,-1,8),s=a.length<8?0:8+u(a).getUint32(4,t);if(s>ne(o.bytes))throw Error(`A compressed variable in this MAT file is damaged.`);if(s>1<<30)throw Error(`A compressed variable in this MAT file is over 1 GB; save it with -v7.3 to open it here.`);let c=await N(r,s,s),l=new Xn(e,o.data,o.bytes,c);n.sources.push(l),i+=c.length;let d=await Q(l,0,t);if(d.type===14&&await Qn(l,d.data,t,``,null,n,0),i>tr)for(let e of n.sources)e.keep=!1,e.release()}else o.type===14&&await Qn(r,o.data,t,``,null,n,0);a=o.next}return n}var rr=65536,ir=new Set([`double`,`single`,`int8`,`uint8`,`int16`,`uint16`,`int32`,`uint32`,`int64`,`uint64`,`logical`]);function ar(e,t){let n={channels:[],strings:new Map,scalars:new Map,notes:[]},r=xn();r.enter(e);let i=t=>K(e,t),a=(e,t,n)=>{let r=null;return(a,o)=>((r?.s!==a||r.e!==o)&&(r={s:a,e:o,v:q(t?i(e).slice([[0,n],[a,o]]):i(e).slice([[a,o],[0,n]]))}),r.v)},o=(e,s,c,l)=>{for(let u of e.keys()){if(!r.count())return;if(u.startsWith(`#`))continue;let d=e.get(u);if(!d)continue;let f=`${s}/${u}`,p=c?`${c}.${u}`:u,m=d.attrs,h=J(m,`MATLAB_class`);if(m.MATLAB_empty)continue;if(yn(d)){h===`struct`&&l<16&&r.enter(d)&&o(d,f,p,l+1);continue}if(!Cn(d))continue;let g=d.shape??[];if(h===`char`){if(g.reduce((e,t)=>e*t,1)>rr)continue;let e=q(d.slice(g.map(e=>[0,e])));n.strings.set(p,new TextDecoder(`utf-16le`).decode(Uint16Array.from(e)))}else if(ir.has(h)&&g.length===2&&Sn(d,g,t,!!d.metadata.chunks))n.notes.push(`${p}: larger than the file can hold (never written, or damaged); skipped.`);else if(ir.has(h)&&g.length===2){let[e,t]=g;if(e*t===1){n.scalars.set(p,q(i(f).slice([[0,1],[0,1]]))[0]);continue}if(e===1||t===1){let r=e*t;n.channels.push({name:p,length:r,read:async(t,n)=>q(e===1?i(f).slice([[0,1],[t,n]]):i(f).slice([[t,n],[0,1]]))})}else if(t>=e){let r=a(f,!0,e);for(let i=0;i<e;i++)n.channels.push({name:`${p}[${i+1}]`,length:t,read:async(e,t)=>r(e,t).slice(i*(t-e),(i+1)*(t-e))})}else{let r=a(f,!1,t);for(let i=0;i<t;i++)n.channels.push({name:`${p}[${i+1}]`,length:e,read:async(e,n)=>{let a=r(e,n),o=new Float64Array(n-e);for(let e=0;e<o.length;e++)o[e]=a[e*t+i];return o}})}}else h===`cell`?n.notes.push(`${p}: cell arrays are skipped.`):h&&n.notes.push(`${p}: MATLAB class ${h} is skipped.`)}};o(e,``,``,0);let s=r.note();return s&&n.notes.push(s),n}var or=e=>Math.max(4096,Math.min(1<<18,Math.floor((16<<20)/(8*Math.max(1,e))))),sr={...t,async plan(e,t){let n=r(await t.read(0,20),`MATLAB 7.3`),i,a=[];if(n)i=ar((await Tn(e.main)).root,e.main.size);else{let e=await nr(t);a=e.sources,i=e}let o=Kn(i.channels,i.strings,i.scalars).filter(e=>e.channels.length>0);await Jn(o);let s=qn(o);if(s.length===0)throw Error(`This MAT file has no numeric vectors or matrices to plot.`);let c=s.flatMap((e,t)=>e.time.kind===`index`?[]:[t]),l=s.length>1&&c.length<s.length,u=Object.fromEntries(i.strings);for(let[e,t]of i.scalars)u[e]=String(t);return{format:n?`MAT 7.3`:`MAT 5`,startTime:null,groups:s,meta:u,events:[],notes:i.notes,pick:l,defaultGroups:l&&c.length?c:void 0,state:{groups:o,sources:a}}},async*stream(e){for(let t of e.selection)yield*cr(e,t.group)},streamGroup:(e,t)=>cr(e,t)};async function*cr(e,t){let n=e.plan.state,r=n.groups[t],i=w(e,t).map(e=>r.channels[e]),a=r.channels[0].length,o=or(i.length+1);try{for(let n=0;n<a;n+=o){e.signal?.throwIfAborted();let s=Math.min(a,n+o),c=null;if(r.time){c=await r.time.read(n,s);for(let e=0;e<c.length;e++)c[e]-=r.origin}let l=[];for(let e of i)l.push(await e.read(n,s));yield{group:t,time:c,start:n,length:s-n,columns:l}}}finally{for(let e of n.sources)e.release()}}function lr(e,t){let n=/^\s*(\d{1,2})\/(\d{1,2})\/(\d{2,4})\s*,\s*(\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))?/.exec(e??``);if(!n)return[null,0,!1];let[r,i]=t===1991?[n[2],n[1]]:[n[1],n[2]],a=n[3].length===2?2e3+Number(n[3]):Number(n[3]),o=Number(`${n[6]}.${n[7]??`0`}`);return[`${a}-${i.padStart(2,`0`)}-${r.padStart(2,`0`)}T${n[4].padStart(2,`0`)}:${n[5]}:${o.toFixed(3).padStart(6,`0`)}`,Date.UTC(a,Number(i)-1,Number(r),Number(n[4]),Number(n[5]))/1e3+o,(n[7]??``).length>6]}function ur(e){let t=e.split(/\r?\n/).map(e=>e.trim()),[n,,r]=t[0].split(`,`),i=Number(r)||1991,a=/(\d+)A\s*,\s*(\d+)D/i.exec(t[1]??``);if(!a)throw Error(`This COMTRADE .cfg is damaged (second line).`);let o=Number(a[1]),s=Number(a[2]);if(o+s>t.length)throw Error(`This COMTRADE .cfg is damaged (more channels than lines).`);let c=2,l=[];for(let e=0;e<o;e++,c++){let e=(t[c]??``).split(`,`);l.push({name:(e[1]??``).trim(),unit:(e[4]??``).trim(),a:Number(e[5]),b:Number(e[6]??0)||0})}let u=[];for(let e=0;e<s;e++,c++)u.push(((t[c]??``).split(`,`)[1]??``).trim());c++;let d=Number(t[c++]);if(!(Number.isInteger(d)&&d>=0&&d<=t.length-c))throw Error(`This COMTRADE .cfg is damaged (sample rates).`);let f=[];for(let e=0;e<Math.max(1,d);e++,c++){let[e,n]=(t[c]??``).split(`,`).map(Number);f.push([d===0?0:e,n])}let[p,m,h]=lr(t[c++],i),[g,_,v]=lr(t[c++],i),y=(t[c++]||`ASCII`).toUpperCase(),b=Number(t[c++])||1;return{station:n.trim(),rev:i,analog:l,digital:u,rates:f,start:p,trigger:g,startSec:m,triggerSec:_,ft:y,timemult:b,timebase:h||v?1e-9:1e-6}}var dr={BINARY:2,BINARY32:4,FLOAT32:4},fr=16<<20;async function pr(e){let t=o(await e.read(0,Math.min(e.size,1<<20))),n=t.search(/---\s*file type:\s*CFG\s*---\r?\n/i),r=/---\s*file type:\s*DAT\s+(ASCII|BINARY32|BINARY|FLOAT32)(?:\s*:\s*(\d+))?\s*---\r?\n/i.exec(t);if(n<0||!r)throw Error(`This COMTRADE .cff is damaged (no CFG or DAT section in its first megabyte).`);let i=t.indexOf(`
3
- `,n)+1,a=t.slice(i).search(/---\s*file type:\s*(INF|HDR|DAT)/i),s=t.slice(i,a<0?void 0:i+a),c=r.index+r[0].length;return{cfg:s,offset:c,length:r[2]?Number(r[2]):e.size-c}}function mr(e,t,n,r){let i=0,a=0,o=t,s=0;for(let[t,c]of e){for(;o<c&&s<n;)r[s++]=a+(o-i)/t,o++;if(a+=(c-i)/t,i=c,s>=n)return}let c=e[e.length-1];for(;s<n;s++,o++)r[s]=a+(o-i)/c[0]}var hr=e=>e.companions.find(e=>e.name.toLowerCase().endsWith(`.dat`)),gr={...d,async plan(e,t){let n=e.main.name.toLowerCase().endsWith(`.cff`),r,i;if(n){let e=await pr(t);r=e.cfg,i={data:`self`,offset:e.offset,length:e.length}}else{let n=hr(e);if(!n)throw Error(`This COMTRADE .cfg needs its .dat file: drop both together.`);if(t.size>fr)throw Error(`This .cfg is too large to be a COMTRADE configuration file.`);r=o(await t.read(0,t.size)),i={data:`companion`,offset:0,length:n.size}}let a=ur(r);if(a.ft!==`ASCII`&&!dr[a.ft])throw Error(`This COMTRADE file has data file type ${a.ft}, which Kymoscope cannot read.`);let s=Math.ceil(a.digital.length/16),c=a.ft===`ASCII`?0:8+a.analog.length*dr[a.ft]+2*s,l=c?Math.floor(i.length/c):i.length,u=Math.min(a.rates[a.rates.length-1][1]||(c?l:-1),l),d=a.rates.length===1&&a.rates[0][0]>0?a.rates[0][0]:null,f=[`Analog values are shown as recorded (primary or secondary, per the CFG).`];return{format:`COMTRADE ${a.rev} (${a.ft})`,startTime:a.start,meta:{station:a.station,trigger:a.trigger??``},groups:[{name:a.station||`COMTRADE`,channels:[...a.analog.map(e=>({name:e.name,unit:e.unit})),...a.digital.map(e=>({name:e,unit:``}))],samples:u,time:{kind:`timestamps`},rateHz:d}],events:a.start&&a.trigger?[{time:Math.round((a.triggerSec-a.startSec)*1e6)/1e6,text:`Trigger`}]:[],notes:f,state:{...i,cfg:a,samples:u,recordSize:c}}},stream:e=>_r(e)};async function*_r(e){let t=e.plan.state,{cfg:n}=t,r=t.data===`self`?e.io:new p(hr(e.files)),i=w(e,0),a=n.analog.length,o=n.rates[0][0]>0,s=n.timemult*n.timebase,c=65536,l=0,d=(e,t,r)=>{let i=new Float64Array(e);if(o)mr(n.rates,l,e,i);else for(let n=0;n<e;n++)i[n]=t[n]*s;let a={group:0,time:i,start:l,length:e,columns:r};return l+=e,a};if(n.ft===`ASCII`){let o=n.rev>=1999?`99999`:``,s=i.map(e=>e<a?n.analog[e]:null),l=new Float64Array(c),u=i.map(()=>new Float64Array(c)),f=0,p=(e,t,n)=>{let r=e.slice(t,n).split(`,`);if(!(r.length<2)){l[f]=Number(r[1]);for(let e=0;e<i.length;e++){let t=(r[2+i[e]]??``).trim(),n=s[e];u[e][f]=t===``||n&&t===o?NaN:n?n.a*Number(t)+n.b:Number(t)}f++}},m=``,h=new TextDecoder(`latin1`);for await(let n of r.windows(t.offset,t.length)){e.signal?.throwIfAborted();let t=m+h.decode(n.bytes),r=0;for(let e=t.indexOf(`
4
- `,r);e>=0;e=t.indexOf(`
5
- `,r))p(t,r,e),r=e+1,f===c&&(yield d(f,l,u),l=new Float64Array(c),u=i.map(()=>new Float64Array(c)),f=0);m=t.slice(r)}m.trim()&&p(m,0,m.length),f&&(yield d(f,l.slice(0,f),u.map(e=>e.slice(0,f))));return}let f=t.recordSize,m=dr[n.ft],h=Math.max(1,Math.floor(Math.min(te,c*f)/f)),g=t.samples;for await(let s of r.windows(t.offset,Math.min(t.length,t.samples*f),h*f)){e.signal?.throwIfAborted();let t=Math.min(g,Math.floor(s.bytes.length/f));if(t<=0)break;let r=u(s.bytes),c=new Float64Array(t);if(!o)for(let e=0;e<t;e++)c[e]=r.getUint32(e*f+4,!0);yield d(t,c,i.map(e=>{let i=new Float64Array(t);if(e<a){let{a,b:o}=n.analog[e],s=8+e*m;if(n.ft===`BINARY`)for(let e=0,n=s;e<t;e++,n+=f){let t=r.getInt16(n,!0);i[e]=t===-32768?NaN:a*t+o}else if(n.ft===`BINARY32`)for(let e=0,n=s;e<t;e++,n+=f){let t=r.getInt32(n,!0);i[e]=t===-2147483648?NaN:a*t+o}else for(let e=0,n=s;e<t;e++,n+=f)i[e]=a*r.getFloat32(n,!0)+o}else{let n=e-a,o=8+a*m+2*(n>>4),s=1<<(n&15);for(let e=0,n=o;e<t;e++,n+=f)i[e]=r.getUint16(n,!0)&s?1:0}return i})),g-=t}}var $=8192;async function*vr(e){let t=0;for(;t+56<=e.size;){let n=y(await e.read(t,56));if(yield await e.slice(t,n.bytes),n.bytes<=56)return;t+=n.bytes}}function yr(e){let t=e.filter(e=>e&&typeof e.t==`number`&&Array.isArray(e.signals)),n={},r={};return t.forEach((e,i)=>{for(let a of e.signals){if(!a||typeof a.name!=`string`)continue;let e=n[a.name]??=new Float64Array(t.length).fill(NaN);e[i]=typeof a.value==`number`?a.value:NaN,a.unit&&!r[a.name]&&(r[a.name]=a.unit)}}),{t:t.map(e=>e.t),columns:n,units:r}}var br=4096;function xr(e){let t=2166136261^e.length;for(let n=0,r=Math.min(e.length,64);n<r;n++)t=Math.imul(t^e[n],16777619);return t>>>0}var Sr=(e,t)=>e.length===t.length&&e.every((e,n)=>e===t[n]),Cr=class{known=new Map;real=new Set;pending=new Set;held=new Set;note(e){for(let t of e){let e=this.known.get(t.name);(!e||t.t>=e.t)&&this.known.set(t.name,{t:t.t,v:t.v,unit:t.unit}),!this.real.has(t.name)&&!this.held.has(t.name)&&this.pending.add(t.name)}}sampled(e){for(let t of[this.pending,this.held])for(let n of t){let r=e[n];if(r){for(let e=0;e<r.length;e++)if(Number.isFinite(r[e])){this.real.add(n),t.delete(n);break}}}}start(e){if(this.pending.size===0||e.t.length===0)return e;let t={...e.columns},n={...e.units};for(let r of this.pending){let i=this.known.get(r),a=new Float64Array(e.t.length).fill(NaN);a[0]=i.v,t[r]=a,i.unit&&!n[r]&&(n[r]=i.unit),this.held.add(r)}return this.pending.clear(),{...e,columns:t,units:n}}end(e,t){if(e===null||this.held.size===0)return null;let n={},r={};for(let e of this.held){let t=this.known.get(e);n[e]=Float64Array.of(t.v),t.unit&&(r[e]=t.unit)}return{at:t,t:[e],columns:n,units:r}}};async function*wr(e,t,n,r){let i=S(e.keys??[]),a=new Map,o=new Map,s=r?null:new Cr,c=null,l=0,u=e=>s?(s.sampled(e.columns),e.t.length&&(c=+e.t[e.t.length-1],l=e.at),s.start(e)):e;for await(let e of vr(t)){let{header:t,messages:c}=m(e);n.t0??=t.t0;for(let e of c){let t=xr(e.bytes),c=o.get(t);if(c&&Sr(c,e.bytes))continue;o.set(t,e.bytes),o.size>br&&o.delete(o.keys().next().value);let l=await i(e.bytes);if(!l){n.lost++;continue}try{if(l.kind===5){let e=h(l.plaintext);a.set(e.id,e);continue}if(l.kind===4){let t=await ee(l.plaintext,a);if(!t){n.lost++;continue}let i={at:e.at,t:t.block.t,columns:t.block.columns,units:t.block.units??{},historical:t.historical};t.historical&&s?.sampled(i.columns),(r===void 0||r===!!t.historical)&&(yield t.historical?i:u(i));continue}if(r)continue;if(l.kind===7){let e=g(l.plaintext,a);e&&s?.note(e)}else if(l.kind===3){let t=b(l.plaintext);yield u({at:e.at,t:t.t,columns:t.columns,units:t.units??{}})}else if(l.kind===2){let t=f(l.plaintext);yield u({at:e.at,...yr(Array.isArray(t?.frames)?t.frames:[])})}}catch{n.lost++}}}let d=s?.end(c,l);d&&(yield d)}function Tr(e,t,n){let r=e===null?t:t===null?e:Math.min(e,t);return r===null?{}:r>1e9?{wallOrigin:String(r),wallQuality:`exact`}:Number.isFinite(n)?{wallOrigin:String(r+n),wallQuality:`approx`}:{}}var Er={mdf:Pt,edf:zt,xdf:Yt,tdms:gn,hdf5:zn,mat:sr,comtrade:gr,krc:{id:`krc`,label:`Kymoscope recording`,extensions:[],sniff:()=>!1,async plan(e,t){let n=[C],r=new Map([[C,`s`]]),i={lost:0,t0:null},a=0,o=!1,s=null,c=null,l=0,u=-1/0,d=0,f=1/0;for await(let p of wr(e,t,i)){a+=p.t.length,p.historical&&(o=!0);let e=p.t.length;e&&p.historical?c??=+p.t[0]:e&&(s??=+p.t[0],+p.t[0]+l<u&&(l=u+Math.max(0,(p.at-d)/1e3)-+p.t[0]),d=p.at,u=+p.t[e-1]+l,f=Math.min(f,p.at/1e3-u));for(let e of Object.keys(p.columns))e!==`ElapsedTime`&&(r.has(e)?!r.get(e)&&p.units[e]&&r.set(e,p.units[e]):(n.push(e),r.set(e,p.units[e]??``)))}let p=n.map(e=>({name:e,unit:r.get(e)??``})),m=i.lost?[`${i.lost} ${i.lost===1?`message`:`messages`} couldn't be opened with the keys this browser has.`]:[];return{format:`Kymoscope recording`,startTime:i.t0===null?null:new Date(i.t0).toISOString(),groups:[{name:`Recording`,channels:p,samples:a,time:{kind:`timestamps`},rateHz:null}],meta:Tr(s,c,f),events:[],notes:m,state:{names:n,backlog:o}}},async*stream(e){let{names:t,backlog:n=!1}=e.plan.state,r=e.selection.find(e=>e.group===0)?.channels??[],i=new Map(r.map((e,n)=>[t[e],n])),a=i.get(C),o=()=>r.map(()=>new Float64Array($).fill(NaN)),s=new Float64Array($),c=o(),l=0,u=0,d=0,f=-1/0,p=0,m=null,h=()=>{let e={group:0,time:s.slice(0,l),start:u,length:l,columns:c.map(e=>e.slice(0,l))};return u+=l,l=0,s=new Float64Array($),c=o(),e};function*g(e){let t=e.t.length;for(let n=0;n<t;){let r=Math.min(t-n,$-l);for(let t=0;t<r;t++){let r=+e.t[n+t]+d;m??=r,s[l+t]=r-m}if(a!==void 0)for(let t=0;t<r;t++)c[a][l+t]=+e.t[n+t];for(let[t,a]of Object.entries(e.columns)){let e=t===`ElapsedTime`?void 0:i.get(t);if(e===void 0)continue;let o=c[e];if(a instanceof Float64Array||a instanceof Float32Array)o.set(a.subarray(n,n+r),l);else for(let e=0;e<r;e++)o[l+e]=+a[n+e]}l+=r,n+=r,l===$&&(yield h())}}let _=n?wr(e.files,e.io,{lost:0,t0:null},!0):null,v=async()=>{for(let e=await _?.next();e&&!e.done;e=await _.next())if(e.value.t.length)return e.value;return null},y=await v();for await(let t of wr(e.files,e.io,{lost:0,t0:null},n?!1:void 0)){if(e.signal?.aborted)return;let n=t.t.length;if(n!==0){for(+t.t[0]+d<f&&(d=f+Math.max(0,(t.at-p)/1e3)-+t.t[0]),p=t.at;y&&+y.t[0]<+t.t[0];y=await v())yield*g(y);yield*g(t),f=+t.t[n-1]+d}}for(;y&&!e.signal?.aborted;y=await v())yield*g(y);l>0&&(yield h())}}};function Dr(e){let t=Er[e];if(!t)throw Error(`No importer for format ${e}.`);return t}export{Dr as importerFor};