| 1 | 'use strict'; |
| 2 | |
| 3 | const { EventEmitter } = require('events'); |
| 4 | const fs = require('fs'); |
| 5 | const os = require('os'); |
| 6 | const path = require('path'); |
| 7 | |
| 8 | jest.mock('child_process', () => ({ |
| 9 | spawn: jest.fn(), |
| 10 | })); |
| 11 | |
| 12 | jest.mock('../server/image-subtitles', () => ({ |
| 13 | clearCachesForFile: jest.fn(), |
| 14 | pruneOldImageSubtitleCaches: jest.fn(), |
| 15 | purgeSubtitleCacheDir: jest.fn(), |
| 16 | })); |
| 17 | |
| 18 | function makeChildProcess () |
| 19 | { |
| 20 | const child = new EventEmitter(); |
| 21 | child.stdout = new EventEmitter(); |
| 22 | child.stderr = new EventEmitter(); |
| 23 | child.kill = jest.fn(); |
| 24 | return child; |
| 25 | } |
| 26 | |
| 27 | function makeReqRes () |
| 28 | { |
| 29 | const req = new EventEmitter(); |
| 30 | const res = new EventEmitter(); |
| 31 | const headers = {}; |
| 32 | |
| 33 | res.set = (name, value) => |
| 34 | { |
| 35 | headers[name] = value; |
| 36 | return res; |
| 37 | }; |
| 38 | res.type = () => res; |
| 39 | res.sendFile = (targetPath, cb) => |
| 40 | { |
| 41 | process.nextTick(() => |
| 42 | { |
| 43 | if (!fs.existsSync(targetPath)) |
| 44 | { |
| 45 | const err = new Error('File not found'); |
| 46 | err.code = 'ENOENT'; |
| 47 | cb(err); |
| 48 | return; |
| 49 | } |
| 50 | |
| 51 | res.emit('finish'); |
| 52 | cb(); |
| 53 | }); |
| 54 | }; |
| 55 | |
| 56 | return { req, res, headers }; |
| 57 | } |
| 58 | |
| 59 | describe('video stream bootstrap', () => |
| 60 | { |
| 61 | let mockSpawn; |
| 62 | let sourceFile; |
| 63 | |
| 64 | beforeEach(() => |
| 65 | { |
| 66 | jest.resetModules(); |
| 67 | mockSpawn = require('child_process').spawn; |
| 68 | mockSpawn.mockReset(); |
| 69 | |
| 70 | const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-')); |
| 71 | sourceFile = path.join(tmpDir, 'clip.mkv'); |
| 72 | fs.writeFileSync(sourceFile, 'video'); |
| 73 | }); |
| 74 | |
| 75 | test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () => |
| 76 | { |
| 77 | mockSpawn.mockImplementation((command, args) => |
| 78 | { |
| 79 | const child = makeChildProcess(); |
| 80 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 81 | |
| 82 | if (exeName.includes('ffprobe')) |
| 83 | { |
| 84 | process.nextTick(() => |
| 85 | { |
| 86 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 87 | format: { duration: '12.5' }, |
| 88 | streams: [ |
| 89 | { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} }, |
| 90 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 91 | ], |
| 92 | }))); |
| 93 | child.emit('close', 0); |
| 94 | }); |
| 95 | return child; |
| 96 | } |
| 97 | |
| 98 | expect(exeName.includes('ffmpeg')).toBe(true); |
| 99 | |
| 100 | const outputPattern = String(args[args.length - 1] || ''); |
| 101 | const outputDir = path.dirname(outputPattern); |
| 102 | |
| 103 | process.nextTick(() => |
| 104 | { |
| 105 | fs.mkdirSync(outputDir, { recursive: true }); |
| 106 | setTimeout(() => |
| 107 | { |
| 108 | fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n'); |
| 109 | }, 40); |
| 110 | }); |
| 111 | |
| 112 | return child; |
| 113 | }); |
| 114 | |
| 115 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 116 | const session = await createVideoStreamSession(sourceFile); |
| 117 | |
| 118 | expect(session).toEqual({ |
| 119 | sessionId: expect.any(String), |
| 120 | durationSeconds: 12.5, |
| 121 | videoWidth: 1920, |
| 122 | videoHeight: 1080, |
| 123 | subtitleTracks: [], |
| 124 | imageSubtitleTracks: [], |
| 125 | subtitleSummary: { |
| 126 | total: 0, |
| 127 | converted: 0, |
| 128 | imageBased: 0, |
| 129 | skipped: 0, |
| 130 | }, |
| 131 | }); |
| 132 | }); |
| 133 | |
| 134 | test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () => |
| 135 | { |
| 136 | mockSpawn.mockImplementation((command, args) => |
| 137 | { |
| 138 | const child = makeChildProcess(); |
| 139 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 140 | |
| 141 | if (exeName.includes('ffprobe')) |
| 142 | { |
| 143 | process.nextTick(() => |
| 144 | { |
| 145 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 146 | streams: [ |
| 147 | { codec_type: 'video', codec_name: 'h264', width: 1280, height: 720, tags: {}, disposition: {} }, |
| 148 | { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } }, |
| 149 | ], |
| 150 | }))); |
| 151 | child.emit('close', 0); |
| 152 | }); |
| 153 | return child; |
| 154 | } |
| 155 | |
| 156 | const segmentArgIndex = args.indexOf('-hls_segment_filename'); |
| 157 | expect(segmentArgIndex).toBeGreaterThan(-1); |
| 158 | expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts'); |
| 159 | expect(args).not.toContain('-hls_playlist_type'); |
| 160 | |
| 161 | const playlistPath = String(args[args.length - 1] || ''); |
| 162 | const outputDir = path.dirname(playlistPath); |
| 163 | process.nextTick(() => |
| 164 | { |
| 165 | fs.mkdirSync(outputDir, { recursive: true }); |
| 166 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 167 | }); |
| 168 | |
| 169 | return child; |
| 170 | }); |
| 171 | |
| 172 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 173 | await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ |
| 174 | sessionId: expect.any(String), |
| 175 | durationSeconds: null, |
| 176 | videoWidth: 1280, |
| 177 | videoHeight: 720, |
| 178 | subtitleTracks: [], |
| 179 | imageSubtitleTracks: [], |
| 180 | subtitleSummary: { |
| 181 | total: 0, |
| 182 | converted: 0, |
| 183 | imageBased: 0, |
| 184 | skipped: 0, |
| 185 | }, |
| 186 | }); |
| 187 | }); |
| 188 | |
| 189 | test('createVideoStreamSession reads duration from ffprobe duration tags', async () => |
| 190 | { |
| 191 | mockSpawn.mockImplementation((command, args) => |
| 192 | { |
| 193 | const child = makeChildProcess(); |
| 194 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 195 | |
| 196 | if (exeName.includes('ffprobe')) |
| 197 | { |
| 198 | process.nextTick(() => |
| 199 | { |
| 200 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 201 | streams: [ |
| 202 | { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, tags: { DURATION: '00:22:17.500000000' }, disposition: {} }, |
| 203 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 204 | ], |
| 205 | }))); |
| 206 | child.emit('close', 0); |
| 207 | }); |
| 208 | return child; |
| 209 | } |
| 210 | |
| 211 | const playlistPath = String(args[args.length - 1] || ''); |
| 212 | const outputDir = path.dirname(playlistPath); |
| 213 | process.nextTick(() => |
| 214 | { |
| 215 | fs.mkdirSync(outputDir, { recursive: true }); |
| 216 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 217 | }); |
| 218 | |
| 219 | return child; |
| 220 | }); |
| 221 | |
| 222 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 223 | await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({ |
| 224 | durationSeconds: 1337.5, |
| 225 | }); |
| 226 | }); |
| 227 | |
| 228 | test('createVideoStreamSession does not become ready from subtitle files alone', async () => |
| 229 | { |
| 230 | mockSpawn.mockImplementation((command, args) => |
| 231 | { |
| 232 | const child = makeChildProcess(); |
| 233 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 234 | |
| 235 | if (exeName.includes('ffprobe')) |
| 236 | { |
| 237 | process.nextTick(() => |
| 238 | { |
| 239 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 240 | streams: [ |
| 241 | { codec_type: 'video', codec_name: 'h264', width: 1024, height: 576, tags: {}, disposition: {} }, |
| 242 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 243 | { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} }, |
| 244 | ], |
| 245 | }))); |
| 246 | child.emit('close', 0); |
| 247 | }); |
| 248 | return child; |
| 249 | } |
| 250 | |
| 251 | const mapIndex = args.indexOf('-map'); |
| 252 | const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; |
| 253 | |
| 254 | if (mappedValue.startsWith('0:s:')) |
| 255 | { |
| 256 | const subtitleTarget = String(args[args.length - 1] || ''); |
| 257 | process.nextTick(() => |
| 258 | { |
| 259 | fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true }); |
| 260 | fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n'); |
| 261 | child.emit('close', 0); |
| 262 | }); |
| 263 | return child; |
| 264 | } |
| 265 | |
| 266 | const playlistPath = String(args[args.length - 1] || ''); |
| 267 | const outputDir = path.dirname(playlistPath); |
| 268 | process.nextTick(() => |
| 269 | { |
| 270 | fs.mkdirSync(outputDir, { recursive: true }); |
| 271 | setTimeout(() => |
| 272 | { |
| 273 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 274 | }, 80); |
| 275 | }); |
| 276 | |
| 277 | return child; |
| 278 | }); |
| 279 | |
| 280 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 281 | const startedAt = Date.now(); |
| 282 | const session = await createVideoStreamSession(sourceFile); |
| 283 | const elapsedMs = Date.now() - startedAt; |
| 284 | |
| 285 | expect(elapsedMs).toBeGreaterThanOrEqual(60); |
| 286 | expect(session).toEqual({ |
| 287 | sessionId: expect.any(String), |
| 288 | durationSeconds: null, |
| 289 | videoWidth: 1024, |
| 290 | videoHeight: 576, |
| 291 | subtitleTracks: [ |
| 292 | expect.objectContaining({ |
| 293 | fileName: 'subtitle-0.vtt', |
| 294 | language: 'eng', |
| 295 | }), |
| 296 | ], |
| 297 | imageSubtitleTracks: [], |
| 298 | subtitleSummary: { |
| 299 | total: 1, |
| 300 | converted: 1, |
| 301 | imageBased: 0, |
| 302 | skipped: 0, |
| 303 | }, |
| 304 | }); |
| 305 | }); |
| 306 | |
| 307 | test('createVideoStreamSession includes matching sidecar srt subtitles', async () => |
| 308 | { |
| 309 | fs.writeFileSync(path.join(path.dirname(sourceFile), 'clip.srt'), '1\n00:00:00,000 --> 00:00:01,000\nHello\n'); |
| 310 | |
| 311 | mockSpawn.mockImplementation((command, args) => |
| 312 | { |
| 313 | const child = makeChildProcess(); |
| 314 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 315 | |
| 316 | if (exeName.includes('ffprobe')) |
| 317 | { |
| 318 | process.nextTick(() => |
| 319 | { |
| 320 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 321 | streams: [ |
| 322 | { codec_type: 'video', codec_name: 'h264', width: 854, height: 480, tags: {}, disposition: {} }, |
| 323 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 324 | ], |
| 325 | }))); |
| 326 | child.emit('close', 0); |
| 327 | }); |
| 328 | return child; |
| 329 | } |
| 330 | |
| 331 | const subtitleTarget = String(args[args.length - 1] || ''); |
| 332 | if (args.includes('-c:s') && args.includes('webvtt') && subtitleTarget.endsWith('.vtt')) |
| 333 | { |
| 334 | process.nextTick(() => |
| 335 | { |
| 336 | fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true }); |
| 337 | fs.writeFileSync(subtitleTarget, [ |
| 338 | 'WEBVTT', |
| 339 | '', |
| 340 | '00:00:01.000 --> 00:00:02.000', |
| 341 | 'Hello {editor note} world', |
| 342 | '', |
| 343 | ].join('\n')); |
| 344 | child.emit('close', 0); |
| 345 | }); |
| 346 | return child; |
| 347 | } |
| 348 | |
| 349 | const playlistPath = String(args[args.length - 1] || ''); |
| 350 | const outputDir = path.dirname(playlistPath); |
| 351 | process.nextTick(() => |
| 352 | { |
| 353 | fs.mkdirSync(outputDir, { recursive: true }); |
| 354 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 355 | }); |
| 356 | |
| 357 | return child; |
| 358 | }); |
| 359 | |
| 360 | const { createVideoStreamSession, STREAM_ROOT_DIR } = require('../server/video-stream'); |
| 361 | const session = await createVideoStreamSession(sourceFile); |
| 362 | expect(session).toEqual({ |
| 363 | sessionId: expect.any(String), |
| 364 | durationSeconds: null, |
| 365 | videoWidth: 854, |
| 366 | videoHeight: 480, |
| 367 | subtitleTracks: [ |
| 368 | expect.objectContaining({ |
| 369 | fileName: 'subtitle-0.vtt', |
| 370 | language: 'und', |
| 371 | isDefault: true, |
| 372 | }), |
| 373 | ], |
| 374 | imageSubtitleTracks: [], |
| 375 | subtitleSummary: { |
| 376 | total: 1, |
| 377 | converted: 1, |
| 378 | imageBased: 0, |
| 379 | skipped: 0, |
| 380 | }, |
| 381 | }); |
| 382 | |
| 383 | const vttPath = path.join( |
| 384 | STREAM_ROOT_DIR, |
| 385 | fs.readdirSync(STREAM_ROOT_DIR)[0], |
| 386 | 'subtitle-0.vtt', |
| 387 | ); |
| 388 | const vttText = fs.readFileSync(vttPath, 'utf8'); |
| 389 | expect(vttText).toContain('Hello world'); |
| 390 | expect(vttText).not.toContain('{editor note}'); |
| 391 | }); |
| 392 | |
| 393 | test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () => |
| 394 | { |
| 395 | mockSpawn.mockImplementation((command, args) => |
| 396 | { |
| 397 | const child = makeChildProcess(); |
| 398 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 399 | |
| 400 | if (exeName.includes('ffprobe')) |
| 401 | { |
| 402 | process.nextTick(() => |
| 403 | { |
| 404 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 405 | streams: [ |
| 406 | { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} }, |
| 407 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 408 | { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} }, |
| 409 | ], |
| 410 | }))); |
| 411 | child.emit('close', 0); |
| 412 | }); |
| 413 | return child; |
| 414 | } |
| 415 | |
| 416 | const mapIndex = args.indexOf('-map'); |
| 417 | const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; |
| 418 | |
| 419 | // Fail subtitle extraction but keep HLS transcoding path successful. |
| 420 | if (mappedValue.startsWith('0:s:')) |
| 421 | { |
| 422 | process.nextTick(() => |
| 423 | { |
| 424 | child.stderr.emit('data', Buffer.from('Subtitle codec not supported')); |
| 425 | child.emit('close', 1); |
| 426 | }); |
| 427 | return child; |
| 428 | } |
| 429 | |
| 430 | const playlistPath = String(args[args.length - 1] || ''); |
| 431 | const outputDir = path.dirname(playlistPath); |
| 432 | process.nextTick(() => |
| 433 | { |
| 434 | fs.mkdirSync(outputDir, { recursive: true }); |
| 435 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 436 | }); |
| 437 | |
| 438 | return child; |
| 439 | }); |
| 440 | |
| 441 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 442 | await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ |
| 443 | sessionId: expect.any(String), |
| 444 | durationSeconds: null, |
| 445 | videoWidth: 1920, |
| 446 | videoHeight: 1080, |
| 447 | subtitleTracks: [], |
| 448 | imageSubtitleTracks: [ |
| 449 | expect.objectContaining({ |
| 450 | label: 'Subtitle 1 (eng)', |
| 451 | language: 'eng', |
| 452 | streamIndex: 0, |
| 453 | }), |
| 454 | ], |
| 455 | subtitleSummary: { |
| 456 | total: 1, |
| 457 | converted: 0, |
| 458 | imageBased: 1, |
| 459 | skipped: 0, |
| 460 | }, |
| 461 | }); |
| 462 | }); |
| 463 | |
| 464 | test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () => |
| 465 | { |
| 466 | mockSpawn.mockImplementation((command, args) => |
| 467 | { |
| 468 | const child = makeChildProcess(); |
| 469 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 470 | |
| 471 | if (exeName.includes('ffprobe')) |
| 472 | { |
| 473 | process.nextTick(() => |
| 474 | { |
| 475 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 476 | streams: [ |
| 477 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 478 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 479 | ], |
| 480 | }))); |
| 481 | child.emit('close', 0); |
| 482 | }); |
| 483 | return child; |
| 484 | } |
| 485 | |
| 486 | const playlistPath = String(args[args.length - 1] || ''); |
| 487 | const outputDir = path.dirname(playlistPath); |
| 488 | process.nextTick(() => |
| 489 | { |
| 490 | fs.mkdirSync(outputDir, { recursive: true }); |
| 491 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 492 | }); |
| 493 | return child; |
| 494 | }); |
| 495 | |
| 496 | const streamModule = require('../server/video-stream'); |
| 497 | const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); |
| 498 | const beforeDirs = new Set( |
| 499 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 500 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 501 | : [] |
| 502 | ); |
| 503 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 504 | const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 505 | const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 506 | expect(newDirName).toEqual(expect.any(String)); |
| 507 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 508 | expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true); |
| 509 | const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 510 | |
| 511 | // ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries. |
| 512 | // With one video + one audio stream the names are 'video' and 'Audio-1'. |
| 513 | for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1) |
| 514 | { |
| 515 | const pad = String(segmentIndex).padStart(6, '0'); |
| 516 | fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 517 | fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 518 | } |
| 519 | |
| 520 | const { req, res } = makeReqRes(); |
| 521 | await streamModule.sendVideoStreamAsset( |
| 522 | session.sessionId, |
| 523 | `stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`, |
| 524 | req, |
| 525 | res |
| 526 | ); |
| 527 | |
| 528 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 529 | |
| 530 | expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false); |
| 531 | expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true); |
| 532 | expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false); |
| 533 | expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true); |
| 534 | expect(pruneOldImageSubtitleCaches).toHaveBeenCalled(); |
| 535 | |
| 536 | const debugSnapshot = streamModule.getVideoStreamDebugSnapshot(); |
| 537 | const activeStream = debugSnapshot.activeStreams.find((stream) => stream.sourcePath === sourceFile); |
| 538 | expect(debugSnapshot.streamPruneDeleteBatchSize).toBe(16); |
| 539 | expect(activeStream).toEqual(expect.objectContaining({ |
| 540 | lastSegmentPrune: expect.objectContaining({ |
| 541 | cutoff: 40, |
| 542 | deletedSegments: expect.any(Number), |
| 543 | durationMs: expect.any(Number), |
| 544 | completedAt: expect.any(Number), |
| 545 | }), |
| 546 | })); |
| 547 | expect(activeStream.lastSegmentPrune.deletedSegments).toBeGreaterThan(0); |
| 548 | |
| 549 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 550 | }); |
| 551 | |
| 552 | test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () => |
| 553 | { |
| 554 | mockSpawn.mockImplementation((command, args) => |
| 555 | { |
| 556 | const child = makeChildProcess(); |
| 557 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 558 | if (exeName.includes('ffprobe')) |
| 559 | { |
| 560 | process.nextTick(() => |
| 561 | { |
| 562 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 563 | streams: [ |
| 564 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 565 | ], |
| 566 | }))); |
| 567 | child.emit('close', 0); |
| 568 | }); |
| 569 | return child; |
| 570 | } |
| 571 | const outputDir = path.dirname(String(args[args.length - 1] || '')); |
| 572 | process.nextTick(() => |
| 573 | { |
| 574 | fs.mkdirSync(outputDir, { recursive: true }); |
| 575 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 576 | }); |
| 577 | return child; |
| 578 | }); |
| 579 | |
| 580 | const streamModule = require('../server/video-stream'); |
| 581 | const beforeDirs = new Set( |
| 582 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 583 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 584 | : [] |
| 585 | ); |
| 586 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 587 | const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d)); |
| 588 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 589 | |
| 590 | // Write a small number of named-variant segments (below the retention window). |
| 591 | const segmentCount = 10; |
| 592 | for (let i = 0; i < segmentCount; i += 1) |
| 593 | { |
| 594 | fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`); |
| 595 | } |
| 596 | |
| 597 | const { req, res } = makeReqRes(); |
| 598 | await streamModule.sendVideoStreamAsset( |
| 599 | session.sessionId, |
| 600 | `stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`, |
| 601 | req, |
| 602 | res |
| 603 | ); |
| 604 | |
| 605 | // Segment count is below retention threshold — nothing should be deleted. |
| 606 | expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount); |
| 607 | |
| 608 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 609 | }); |
| 610 | |
| 611 | test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () => |
| 612 | { |
| 613 | mockSpawn.mockImplementation((command, args) => |
| 614 | { |
| 615 | const child = makeChildProcess(); |
| 616 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 617 | |
| 618 | if (exeName.includes('ffprobe')) |
| 619 | { |
| 620 | process.nextTick(() => |
| 621 | { |
| 622 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 623 | streams: [ |
| 624 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 625 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 626 | ], |
| 627 | }))); |
| 628 | child.emit('close', 0); |
| 629 | }); |
| 630 | return child; |
| 631 | } |
| 632 | |
| 633 | const playlistPath = String(args[args.length - 1] || ''); |
| 634 | const outputDir = path.dirname(playlistPath); |
| 635 | process.nextTick(() => |
| 636 | { |
| 637 | fs.mkdirSync(outputDir, { recursive: true }); |
| 638 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 639 | }); |
| 640 | return child; |
| 641 | }); |
| 642 | |
| 643 | const streamModule = require('../server/video-stream'); |
| 644 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 645 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 646 | |
| 647 | expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId); |
| 648 | |
| 649 | const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) => |
| 650 | path.basename(String(command || '')).toLowerCase().includes('ffmpeg') |
| 651 | ); |
| 652 | expect(ffmpegSpawns).toHaveLength(1); |
| 653 | |
| 654 | const firstReqRes = makeReqRes(); |
| 655 | await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res); |
| 656 | |
| 657 | const secondReqRes = makeReqRes(); |
| 658 | await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res); |
| 659 | |
| 660 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 661 | |
| 662 | const stillActiveReqRes = makeReqRes(); |
| 663 | await expect( |
| 664 | streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res) |
| 665 | ).resolves.toBeUndefined(); |
| 666 | |
| 667 | const releasedReqRes = makeReqRes(); |
| 668 | await expect( |
| 669 | streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res) |
| 670 | ).rejects.toMatchObject({ status: 404 }); |
| 671 | |
| 672 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 673 | }); |
| 674 | |
| 675 | test('prunes subtitle caches using the slowest viewer across same-file sessions', async () => |
| 676 | { |
| 677 | mockSpawn.mockImplementation((command, args) => |
| 678 | { |
| 679 | const child = makeChildProcess(); |
| 680 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 681 | |
| 682 | if (exeName.includes('ffprobe')) |
| 683 | { |
| 684 | process.nextTick(() => |
| 685 | { |
| 686 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 687 | streams: [ |
| 688 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 689 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 690 | ], |
| 691 | }))); |
| 692 | child.emit('close', 0); |
| 693 | }); |
| 694 | return child; |
| 695 | } |
| 696 | |
| 697 | const playlistPath = String(args[args.length - 1] || ''); |
| 698 | const outputDir = path.dirname(playlistPath); |
| 699 | process.nextTick(() => |
| 700 | { |
| 701 | fs.mkdirSync(outputDir, { recursive: true }); |
| 702 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 703 | }); |
| 704 | return child; |
| 705 | }); |
| 706 | |
| 707 | const streamModule = require('../server/video-stream'); |
| 708 | const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); |
| 709 | const beforeDirs = new Set( |
| 710 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 711 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 712 | : [] |
| 713 | ); |
| 714 | |
| 715 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 716 | const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 717 | const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 718 | const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); |
| 719 | const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 720 | |
| 721 | for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1) |
| 722 | { |
| 723 | const pad = String(segmentIndex).padStart(6, '0'); |
| 724 | fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 725 | fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 726 | } |
| 727 | |
| 728 | let reqRes = makeReqRes(); |
| 729 | await streamModule.sendVideoStreamAsset( |
| 730 | firstViewer.sessionId, |
| 731 | `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, |
| 732 | reqRes.req, |
| 733 | reqRes.res |
| 734 | ); |
| 735 | |
| 736 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 737 | |
| 738 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 739 | const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 740 | const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName)); |
| 741 | const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || '')); |
| 742 | |
| 743 | fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1'); |
| 744 | |
| 745 | reqRes = makeReqRes(); |
| 746 | await streamModule.sendVideoStreamAsset( |
| 747 | secondViewer.sessionId, |
| 748 | 'stream_video_segment_000001.ts', |
| 749 | reqRes.req, |
| 750 | reqRes.res |
| 751 | ); |
| 752 | |
| 753 | pruneOldImageSubtitleCaches.mockClear(); |
| 754 | |
| 755 | reqRes = makeReqRes(); |
| 756 | await streamModule.sendVideoStreamAsset( |
| 757 | firstViewer.sessionId, |
| 758 | `stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`, |
| 759 | reqRes.req, |
| 760 | reqRes.res |
| 761 | ); |
| 762 | |
| 763 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 764 | |
| 765 | expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6); |
| 766 | |
| 767 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 768 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 769 | }); |
| 770 | |
| 771 | test('purges subtitle disk cache when the module is first loaded', () => |
| 772 | { |
| 773 | const { purgeSubtitleCacheDir } = require('../server/image-subtitles'); |
| 774 | require('../server/video-stream'); |
| 775 | expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1); |
| 776 | }); |
| 777 | |
| 778 | test('purges stream output directory when the module is first loaded', () => |
| 779 | { |
| 780 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 781 | const orphanDir = path.join(streamRoot, 'orphan-after-restart'); |
| 782 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 783 | fs.writeFileSync(path.join(orphanDir, 'stream_0_segment_000001.ts'), 'segment'); |
| 784 | |
| 785 | require('../server/video-stream'); |
| 786 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 787 | }); |
| 788 | |
| 789 | test('cleanupIdleStreamArtifacts removes stream output directory when no streams are active', () => |
| 790 | { |
| 791 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 792 | const orphanDir = path.join(streamRoot, 'orphan-idle-cleanup'); |
| 793 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 794 | fs.writeFileSync(path.join(orphanDir, 'stream_0.m3u8'), '#EXTM3U\n'); |
| 795 | |
| 796 | const streamModule = require('../server/video-stream'); |
| 797 | streamModule.cleanupIdleStreamArtifacts(); |
| 798 | |
| 799 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 800 | }); |
| 801 | |
| 802 | test('clears subtitle caches for a video when its last stream is released', async () => |
| 803 | { |
| 804 | mockSpawn.mockImplementation((command, args) => |
| 805 | { |
| 806 | const child = makeChildProcess(); |
| 807 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 808 | |
| 809 | if (exeName.includes('ffprobe')) |
| 810 | { |
| 811 | process.nextTick(() => |
| 812 | { |
| 813 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 814 | streams: [ |
| 815 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 816 | ], |
| 817 | }))); |
| 818 | child.emit('close', 0); |
| 819 | }); |
| 820 | return child; |
| 821 | } |
| 822 | |
| 823 | const playlistPath = String(args[args.length - 1] || ''); |
| 824 | const outputDir = path.dirname(playlistPath); |
| 825 | process.nextTick(() => |
| 826 | { |
| 827 | fs.mkdirSync(outputDir, { recursive: true }); |
| 828 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 829 | }); |
| 830 | return child; |
| 831 | }); |
| 832 | |
| 833 | const streamModule = require('../server/video-stream'); |
| 834 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 835 | |
| 836 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 837 | clearCachesForFile.mockClear(); |
| 838 | |
| 839 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 840 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 841 | }); |
| 842 | |
| 843 | test('keeps subtitle caches while another same-file session is still active', async () => |
| 844 | { |
| 845 | mockSpawn.mockImplementation((command, args) => |
| 846 | { |
| 847 | const child = makeChildProcess(); |
| 848 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 849 | |
| 850 | if (exeName.includes('ffprobe')) |
| 851 | { |
| 852 | process.nextTick(() => |
| 853 | { |
| 854 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 855 | streams: [ |
| 856 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 857 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 858 | ], |
| 859 | }))); |
| 860 | child.emit('close', 0); |
| 861 | }); |
| 862 | return child; |
| 863 | } |
| 864 | |
| 865 | const playlistPath = String(args[args.length - 1] || ''); |
| 866 | const outputDir = path.dirname(playlistPath); |
| 867 | process.nextTick(() => |
| 868 | { |
| 869 | fs.mkdirSync(outputDir, { recursive: true }); |
| 870 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 871 | }); |
| 872 | return child; |
| 873 | }); |
| 874 | |
| 875 | const streamModule = require('../server/video-stream'); |
| 876 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 877 | const beforeDirs = new Set( |
| 878 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 879 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 880 | : [] |
| 881 | ); |
| 882 | |
| 883 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 884 | const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 885 | const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 886 | const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); |
| 887 | const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 888 | |
| 889 | for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1) |
| 890 | { |
| 891 | const pad = String(segmentIndex).padStart(6, '0'); |
| 892 | fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 893 | fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 894 | } |
| 895 | |
| 896 | let reqRes = makeReqRes(); |
| 897 | await streamModule.sendVideoStreamAsset( |
| 898 | firstViewer.sessionId, |
| 899 | `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, |
| 900 | reqRes.req, |
| 901 | reqRes.res |
| 902 | ); |
| 903 | |
| 904 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 905 | |
| 906 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 907 | clearCachesForFile.mockClear(); |
| 908 | |
| 909 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 910 | expect(clearCachesForFile).not.toHaveBeenCalled(); |
| 911 | |
| 912 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 913 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 914 | }); |
| 915 | |
| 916 | test('destroys zero-viewer sessions immediately even with an in-flight asset response', async () => |
| 917 | { |
| 918 | mockSpawn.mockImplementation((command, args) => |
| 919 | { |
| 920 | const child = makeChildProcess(); |
| 921 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 922 | |
| 923 | if (exeName.includes('ffprobe')) |
| 924 | { |
| 925 | process.nextTick(() => |
| 926 | { |
| 927 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 928 | streams: [ |
| 929 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 930 | ], |
| 931 | }))); |
| 932 | child.emit('close', 0); |
| 933 | }); |
| 934 | return child; |
| 935 | } |
| 936 | |
| 937 | const playlistPath = String(args[args.length - 1] || ''); |
| 938 | const outputDir = path.dirname(playlistPath); |
| 939 | process.nextTick(() => |
| 940 | { |
| 941 | fs.mkdirSync(outputDir, { recursive: true }); |
| 942 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 943 | }); |
| 944 | return child; |
| 945 | }); |
| 946 | |
| 947 | const streamModule = require('../server/video-stream'); |
| 948 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 949 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 950 | clearCachesForFile.mockClear(); |
| 951 | |
| 952 | const req = new EventEmitter(); |
| 953 | const res = new EventEmitter(); |
| 954 | let finishSendFile; |
| 955 | |
| 956 | res.set = () => res; |
| 957 | res.type = () => res; |
| 958 | res.sendFile = (targetPath, cb) => |
| 959 | { |
| 960 | finishSendFile = () => |
| 961 | { |
| 962 | res.emit('finish'); |
| 963 | cb(); |
| 964 | }; |
| 965 | expect(fs.existsSync(targetPath)).toBe(true); |
| 966 | }; |
| 967 | |
| 968 | const assetPromise = streamModule.sendVideoStreamAsset(session.sessionId, 'master.m3u8', req, res); |
| 969 | await new Promise((resolve) => setImmediate(resolve)); |
| 970 | |
| 971 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 972 | |
| 973 | const debugAfterRelease = streamModule.getVideoStreamDebugSnapshot(); |
| 974 | expect(debugAfterRelease.activeSessionCount).toBe(0); |
| 975 | expect(debugAfterRelease.activeLeaseCount).toBe(0); |
| 976 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 977 | |
| 978 | finishSendFile(); |
| 979 | await expect(assetPromise).resolves.toBeUndefined(); |
| 980 | }); |
| 981 | }); |
| 982 | |
| 983 | describe('text subtitle editor-note sanitization', () => |
| 984 | { |
| 985 | const { stripSubtitleEditorNotes, sanitizeWebVttContent } = require('../server/video-stream'); |
| 986 | |
| 987 | test('stripSubtitleEditorNotes removes brace-wrapped notes from cue text', () => |
| 988 | { |
| 989 | const input = "He grabs the handle{Maybe rephrase, don't make it this short} and jumps"; |
| 990 | expect(stripSubtitleEditorNotes(input)).toBe('He grabs the handle and jumps'); |
| 991 | }); |
| 992 | |
| 993 | test('stripSubtitleEditorNotes removes multiple notes in one line', () => |
| 994 | { |
| 995 | expect(stripSubtitleEditorNotes('Hello {note one} there {note two} friend')) |
| 996 | .toBe('Hello there friend'); |
| 997 | }); |
| 998 | |
| 999 | test('sanitizeWebVttContent preserves timestamps and strips cue text notes', () => |
| 1000 | { |
| 1001 | const vtt = [ |
| 1002 | 'WEBVTT', |
| 1003 | '', |
| 1004 | '00:00:01.000 --> 00:00:04.000', |
| 1005 | "He grabs the handle{Maybe rephrase, don't make it this short} and jumps", |
| 1006 | '', |
| 1007 | ].join('\n'); |
| 1008 | |
| 1009 | const sanitized = sanitizeWebVttContent(vtt); |
| 1010 | expect(sanitized).toContain('00:00:01.000 --> 00:00:04.000'); |
| 1011 | expect(sanitized).toContain('He grabs the handle and jumps'); |
| 1012 | expect(sanitized).not.toContain('{Maybe rephrase'); |
| 1013 | }); |
| 1014 | }); |