| 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, 'WEBVTT\n\n'); |
| 338 | child.emit('close', 0); |
| 339 | }); |
| 340 | return child; |
| 341 | } |
| 342 | |
| 343 | const playlistPath = String(args[args.length - 1] || ''); |
| 344 | const outputDir = path.dirname(playlistPath); |
| 345 | process.nextTick(() => |
| 346 | { |
| 347 | fs.mkdirSync(outputDir, { recursive: true }); |
| 348 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 349 | }); |
| 350 | |
| 351 | return child; |
| 352 | }); |
| 353 | |
| 354 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 355 | await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ |
| 356 | sessionId: expect.any(String), |
| 357 | durationSeconds: null, |
| 358 | videoWidth: 854, |
| 359 | videoHeight: 480, |
| 360 | subtitleTracks: [ |
| 361 | expect.objectContaining({ |
| 362 | fileName: 'subtitle-0.vtt', |
| 363 | language: 'und', |
| 364 | isDefault: true, |
| 365 | }), |
| 366 | ], |
| 367 | imageSubtitleTracks: [], |
| 368 | subtitleSummary: { |
| 369 | total: 1, |
| 370 | converted: 1, |
| 371 | imageBased: 0, |
| 372 | skipped: 0, |
| 373 | }, |
| 374 | }); |
| 375 | }); |
| 376 | |
| 377 | test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () => |
| 378 | { |
| 379 | mockSpawn.mockImplementation((command, args) => |
| 380 | { |
| 381 | const child = makeChildProcess(); |
| 382 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 383 | |
| 384 | if (exeName.includes('ffprobe')) |
| 385 | { |
| 386 | process.nextTick(() => |
| 387 | { |
| 388 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 389 | streams: [ |
| 390 | { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} }, |
| 391 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 392 | { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} }, |
| 393 | ], |
| 394 | }))); |
| 395 | child.emit('close', 0); |
| 396 | }); |
| 397 | return child; |
| 398 | } |
| 399 | |
| 400 | const mapIndex = args.indexOf('-map'); |
| 401 | const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; |
| 402 | |
| 403 | // Fail subtitle extraction but keep HLS transcoding path successful. |
| 404 | if (mappedValue.startsWith('0:s:')) |
| 405 | { |
| 406 | process.nextTick(() => |
| 407 | { |
| 408 | child.stderr.emit('data', Buffer.from('Subtitle codec not supported')); |
| 409 | child.emit('close', 1); |
| 410 | }); |
| 411 | return child; |
| 412 | } |
| 413 | |
| 414 | const playlistPath = String(args[args.length - 1] || ''); |
| 415 | const outputDir = path.dirname(playlistPath); |
| 416 | process.nextTick(() => |
| 417 | { |
| 418 | fs.mkdirSync(outputDir, { recursive: true }); |
| 419 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 420 | }); |
| 421 | |
| 422 | return child; |
| 423 | }); |
| 424 | |
| 425 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 426 | await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ |
| 427 | sessionId: expect.any(String), |
| 428 | durationSeconds: null, |
| 429 | videoWidth: 1920, |
| 430 | videoHeight: 1080, |
| 431 | subtitleTracks: [], |
| 432 | imageSubtitleTracks: [ |
| 433 | expect.objectContaining({ |
| 434 | label: 'Subtitle 1 (eng)', |
| 435 | language: 'eng', |
| 436 | streamIndex: 0, |
| 437 | }), |
| 438 | ], |
| 439 | subtitleSummary: { |
| 440 | total: 1, |
| 441 | converted: 0, |
| 442 | imageBased: 1, |
| 443 | skipped: 0, |
| 444 | }, |
| 445 | }); |
| 446 | }); |
| 447 | |
| 448 | test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () => |
| 449 | { |
| 450 | mockSpawn.mockImplementation((command, args) => |
| 451 | { |
| 452 | const child = makeChildProcess(); |
| 453 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 454 | |
| 455 | if (exeName.includes('ffprobe')) |
| 456 | { |
| 457 | process.nextTick(() => |
| 458 | { |
| 459 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 460 | streams: [ |
| 461 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 462 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 463 | ], |
| 464 | }))); |
| 465 | child.emit('close', 0); |
| 466 | }); |
| 467 | return child; |
| 468 | } |
| 469 | |
| 470 | const playlistPath = String(args[args.length - 1] || ''); |
| 471 | const outputDir = path.dirname(playlistPath); |
| 472 | process.nextTick(() => |
| 473 | { |
| 474 | fs.mkdirSync(outputDir, { recursive: true }); |
| 475 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 476 | }); |
| 477 | return child; |
| 478 | }); |
| 479 | |
| 480 | const streamModule = require('../server/video-stream'); |
| 481 | const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); |
| 482 | const beforeDirs = new Set( |
| 483 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 484 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 485 | : [] |
| 486 | ); |
| 487 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 488 | const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 489 | const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 490 | expect(newDirName).toEqual(expect.any(String)); |
| 491 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 492 | expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true); |
| 493 | const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 494 | |
| 495 | // ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries. |
| 496 | // With one video + one audio stream the names are 'video' and 'Audio-1'. |
| 497 | for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1) |
| 498 | { |
| 499 | const pad = String(segmentIndex).padStart(6, '0'); |
| 500 | fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 501 | fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 502 | } |
| 503 | |
| 504 | const { req, res } = makeReqRes(); |
| 505 | await streamModule.sendVideoStreamAsset( |
| 506 | session.sessionId, |
| 507 | `stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`, |
| 508 | req, |
| 509 | res |
| 510 | ); |
| 511 | |
| 512 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 513 | |
| 514 | expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false); |
| 515 | expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true); |
| 516 | expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false); |
| 517 | expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true); |
| 518 | expect(pruneOldImageSubtitleCaches).toHaveBeenCalled(); |
| 519 | |
| 520 | const debugSnapshot = streamModule.getVideoStreamDebugSnapshot(); |
| 521 | const activeStream = debugSnapshot.activeStreams.find((stream) => stream.sourcePath === sourceFile); |
| 522 | expect(debugSnapshot.streamPruneDeleteBatchSize).toBe(16); |
| 523 | expect(activeStream).toEqual(expect.objectContaining({ |
| 524 | lastSegmentPrune: expect.objectContaining({ |
| 525 | cutoff: 40, |
| 526 | deletedSegments: expect.any(Number), |
| 527 | durationMs: expect.any(Number), |
| 528 | completedAt: expect.any(Number), |
| 529 | }), |
| 530 | })); |
| 531 | expect(activeStream.lastSegmentPrune.deletedSegments).toBeGreaterThan(0); |
| 532 | |
| 533 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 534 | }); |
| 535 | |
| 536 | test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () => |
| 537 | { |
| 538 | mockSpawn.mockImplementation((command, args) => |
| 539 | { |
| 540 | const child = makeChildProcess(); |
| 541 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 542 | if (exeName.includes('ffprobe')) |
| 543 | { |
| 544 | process.nextTick(() => |
| 545 | { |
| 546 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 547 | streams: [ |
| 548 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 549 | ], |
| 550 | }))); |
| 551 | child.emit('close', 0); |
| 552 | }); |
| 553 | return child; |
| 554 | } |
| 555 | const outputDir = path.dirname(String(args[args.length - 1] || '')); |
| 556 | process.nextTick(() => |
| 557 | { |
| 558 | fs.mkdirSync(outputDir, { recursive: true }); |
| 559 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 560 | }); |
| 561 | return child; |
| 562 | }); |
| 563 | |
| 564 | const streamModule = require('../server/video-stream'); |
| 565 | const beforeDirs = new Set( |
| 566 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 567 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 568 | : [] |
| 569 | ); |
| 570 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 571 | const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d)); |
| 572 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 573 | |
| 574 | // Write a small number of named-variant segments (below the retention window). |
| 575 | const segmentCount = 10; |
| 576 | for (let i = 0; i < segmentCount; i += 1) |
| 577 | { |
| 578 | fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`); |
| 579 | } |
| 580 | |
| 581 | const { req, res } = makeReqRes(); |
| 582 | await streamModule.sendVideoStreamAsset( |
| 583 | session.sessionId, |
| 584 | `stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`, |
| 585 | req, |
| 586 | res |
| 587 | ); |
| 588 | |
| 589 | // Segment count is below retention threshold — nothing should be deleted. |
| 590 | expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount); |
| 591 | |
| 592 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 593 | }); |
| 594 | |
| 595 | test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () => |
| 596 | { |
| 597 | mockSpawn.mockImplementation((command, args) => |
| 598 | { |
| 599 | const child = makeChildProcess(); |
| 600 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 601 | |
| 602 | if (exeName.includes('ffprobe')) |
| 603 | { |
| 604 | process.nextTick(() => |
| 605 | { |
| 606 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 607 | streams: [ |
| 608 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 609 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 610 | ], |
| 611 | }))); |
| 612 | child.emit('close', 0); |
| 613 | }); |
| 614 | return child; |
| 615 | } |
| 616 | |
| 617 | const playlistPath = String(args[args.length - 1] || ''); |
| 618 | const outputDir = path.dirname(playlistPath); |
| 619 | process.nextTick(() => |
| 620 | { |
| 621 | fs.mkdirSync(outputDir, { recursive: true }); |
| 622 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 623 | }); |
| 624 | return child; |
| 625 | }); |
| 626 | |
| 627 | const streamModule = require('../server/video-stream'); |
| 628 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 629 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 630 | |
| 631 | expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId); |
| 632 | |
| 633 | const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) => |
| 634 | path.basename(String(command || '')).toLowerCase().includes('ffmpeg') |
| 635 | ); |
| 636 | expect(ffmpegSpawns).toHaveLength(1); |
| 637 | |
| 638 | const firstReqRes = makeReqRes(); |
| 639 | await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res); |
| 640 | |
| 641 | const secondReqRes = makeReqRes(); |
| 642 | await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res); |
| 643 | |
| 644 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 645 | |
| 646 | const stillActiveReqRes = makeReqRes(); |
| 647 | await expect( |
| 648 | streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res) |
| 649 | ).resolves.toBeUndefined(); |
| 650 | |
| 651 | const releasedReqRes = makeReqRes(); |
| 652 | await expect( |
| 653 | streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res) |
| 654 | ).rejects.toMatchObject({ status: 404 }); |
| 655 | |
| 656 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 657 | }); |
| 658 | |
| 659 | test('prunes subtitle caches using the slowest viewer across same-file sessions', async () => |
| 660 | { |
| 661 | mockSpawn.mockImplementation((command, args) => |
| 662 | { |
| 663 | const child = makeChildProcess(); |
| 664 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 665 | |
| 666 | if (exeName.includes('ffprobe')) |
| 667 | { |
| 668 | process.nextTick(() => |
| 669 | { |
| 670 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 671 | streams: [ |
| 672 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 673 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 674 | ], |
| 675 | }))); |
| 676 | child.emit('close', 0); |
| 677 | }); |
| 678 | return child; |
| 679 | } |
| 680 | |
| 681 | const playlistPath = String(args[args.length - 1] || ''); |
| 682 | const outputDir = path.dirname(playlistPath); |
| 683 | process.nextTick(() => |
| 684 | { |
| 685 | fs.mkdirSync(outputDir, { recursive: true }); |
| 686 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 687 | }); |
| 688 | return child; |
| 689 | }); |
| 690 | |
| 691 | const streamModule = require('../server/video-stream'); |
| 692 | const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); |
| 693 | const beforeDirs = new Set( |
| 694 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 695 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 696 | : [] |
| 697 | ); |
| 698 | |
| 699 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 700 | const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 701 | const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 702 | const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); |
| 703 | const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 704 | |
| 705 | for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1) |
| 706 | { |
| 707 | const pad = String(segmentIndex).padStart(6, '0'); |
| 708 | fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 709 | fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 710 | } |
| 711 | |
| 712 | let reqRes = makeReqRes(); |
| 713 | await streamModule.sendVideoStreamAsset( |
| 714 | firstViewer.sessionId, |
| 715 | `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, |
| 716 | reqRes.req, |
| 717 | reqRes.res |
| 718 | ); |
| 719 | |
| 720 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 721 | |
| 722 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 723 | const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 724 | const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName)); |
| 725 | const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || '')); |
| 726 | |
| 727 | fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1'); |
| 728 | |
| 729 | reqRes = makeReqRes(); |
| 730 | await streamModule.sendVideoStreamAsset( |
| 731 | secondViewer.sessionId, |
| 732 | 'stream_video_segment_000001.ts', |
| 733 | reqRes.req, |
| 734 | reqRes.res |
| 735 | ); |
| 736 | |
| 737 | pruneOldImageSubtitleCaches.mockClear(); |
| 738 | |
| 739 | reqRes = makeReqRes(); |
| 740 | await streamModule.sendVideoStreamAsset( |
| 741 | firstViewer.sessionId, |
| 742 | `stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`, |
| 743 | reqRes.req, |
| 744 | reqRes.res |
| 745 | ); |
| 746 | |
| 747 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 748 | |
| 749 | expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6); |
| 750 | |
| 751 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 752 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 753 | }); |
| 754 | |
| 755 | test('purges subtitle disk cache when the module is first loaded', () => |
| 756 | { |
| 757 | const { purgeSubtitleCacheDir } = require('../server/image-subtitles'); |
| 758 | require('../server/video-stream'); |
| 759 | expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1); |
| 760 | }); |
| 761 | |
| 762 | test('purges stream output directory when the module is first loaded', () => |
| 763 | { |
| 764 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 765 | const orphanDir = path.join(streamRoot, 'orphan-after-restart'); |
| 766 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 767 | fs.writeFileSync(path.join(orphanDir, 'stream_0_segment_000001.ts'), 'segment'); |
| 768 | |
| 769 | require('../server/video-stream'); |
| 770 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 771 | }); |
| 772 | |
| 773 | test('cleanupIdleStreamArtifacts removes stream output directory when no streams are active', () => |
| 774 | { |
| 775 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 776 | const orphanDir = path.join(streamRoot, 'orphan-idle-cleanup'); |
| 777 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 778 | fs.writeFileSync(path.join(orphanDir, 'stream_0.m3u8'), '#EXTM3U\n'); |
| 779 | |
| 780 | const streamModule = require('../server/video-stream'); |
| 781 | streamModule.cleanupIdleStreamArtifacts(); |
| 782 | |
| 783 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 784 | }); |
| 785 | |
| 786 | test('clears subtitle caches for a video when its last stream is released', async () => |
| 787 | { |
| 788 | mockSpawn.mockImplementation((command, args) => |
| 789 | { |
| 790 | const child = makeChildProcess(); |
| 791 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 792 | |
| 793 | if (exeName.includes('ffprobe')) |
| 794 | { |
| 795 | process.nextTick(() => |
| 796 | { |
| 797 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 798 | streams: [ |
| 799 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 800 | ], |
| 801 | }))); |
| 802 | child.emit('close', 0); |
| 803 | }); |
| 804 | return child; |
| 805 | } |
| 806 | |
| 807 | const playlistPath = String(args[args.length - 1] || ''); |
| 808 | const outputDir = path.dirname(playlistPath); |
| 809 | process.nextTick(() => |
| 810 | { |
| 811 | fs.mkdirSync(outputDir, { recursive: true }); |
| 812 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 813 | }); |
| 814 | return child; |
| 815 | }); |
| 816 | |
| 817 | const streamModule = require('../server/video-stream'); |
| 818 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 819 | |
| 820 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 821 | clearCachesForFile.mockClear(); |
| 822 | |
| 823 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 824 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 825 | }); |
| 826 | |
| 827 | test('keeps subtitle caches while another same-file session is still active', async () => |
| 828 | { |
| 829 | mockSpawn.mockImplementation((command, args) => |
| 830 | { |
| 831 | const child = makeChildProcess(); |
| 832 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 833 | |
| 834 | if (exeName.includes('ffprobe')) |
| 835 | { |
| 836 | process.nextTick(() => |
| 837 | { |
| 838 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 839 | streams: [ |
| 840 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 841 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 842 | ], |
| 843 | }))); |
| 844 | child.emit('close', 0); |
| 845 | }); |
| 846 | return child; |
| 847 | } |
| 848 | |
| 849 | const playlistPath = String(args[args.length - 1] || ''); |
| 850 | const outputDir = path.dirname(playlistPath); |
| 851 | process.nextTick(() => |
| 852 | { |
| 853 | fs.mkdirSync(outputDir, { recursive: true }); |
| 854 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 855 | }); |
| 856 | return child; |
| 857 | }); |
| 858 | |
| 859 | const streamModule = require('../server/video-stream'); |
| 860 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 861 | const beforeDirs = new Set( |
| 862 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 863 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 864 | : [] |
| 865 | ); |
| 866 | |
| 867 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 868 | const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 869 | const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 870 | const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); |
| 871 | const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 872 | |
| 873 | for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1) |
| 874 | { |
| 875 | const pad = String(segmentIndex).padStart(6, '0'); |
| 876 | fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); |
| 877 | fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); |
| 878 | } |
| 879 | |
| 880 | let reqRes = makeReqRes(); |
| 881 | await streamModule.sendVideoStreamAsset( |
| 882 | firstViewer.sessionId, |
| 883 | `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, |
| 884 | reqRes.req, |
| 885 | reqRes.res |
| 886 | ); |
| 887 | |
| 888 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 889 | |
| 890 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 891 | clearCachesForFile.mockClear(); |
| 892 | |
| 893 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 894 | expect(clearCachesForFile).not.toHaveBeenCalled(); |
| 895 | |
| 896 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 897 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 898 | }); |
| 899 | |
| 900 | test('destroys zero-viewer sessions immediately even with an in-flight asset response', async () => |
| 901 | { |
| 902 | mockSpawn.mockImplementation((command, args) => |
| 903 | { |
| 904 | const child = makeChildProcess(); |
| 905 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 906 | |
| 907 | if (exeName.includes('ffprobe')) |
| 908 | { |
| 909 | process.nextTick(() => |
| 910 | { |
| 911 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 912 | streams: [ |
| 913 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 914 | ], |
| 915 | }))); |
| 916 | child.emit('close', 0); |
| 917 | }); |
| 918 | return child; |
| 919 | } |
| 920 | |
| 921 | const playlistPath = String(args[args.length - 1] || ''); |
| 922 | const outputDir = path.dirname(playlistPath); |
| 923 | process.nextTick(() => |
| 924 | { |
| 925 | fs.mkdirSync(outputDir, { recursive: true }); |
| 926 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 927 | }); |
| 928 | return child; |
| 929 | }); |
| 930 | |
| 931 | const streamModule = require('../server/video-stream'); |
| 932 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 933 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 934 | clearCachesForFile.mockClear(); |
| 935 | |
| 936 | const req = new EventEmitter(); |
| 937 | const res = new EventEmitter(); |
| 938 | let finishSendFile; |
| 939 | |
| 940 | res.set = () => res; |
| 941 | res.type = () => res; |
| 942 | res.sendFile = (targetPath, cb) => |
| 943 | { |
| 944 | finishSendFile = () => |
| 945 | { |
| 946 | res.emit('finish'); |
| 947 | cb(); |
| 948 | }; |
| 949 | expect(fs.existsSync(targetPath)).toBe(true); |
| 950 | }; |
| 951 | |
| 952 | const assetPromise = streamModule.sendVideoStreamAsset(session.sessionId, 'master.m3u8', req, res); |
| 953 | await new Promise((resolve) => setImmediate(resolve)); |
| 954 | |
| 955 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 956 | |
| 957 | const debugAfterRelease = streamModule.getVideoStreamDebugSnapshot(); |
| 958 | expect(debugAfterRelease.activeSessionCount).toBe(0); |
| 959 | expect(debugAfterRelease.activeLeaseCount).toBe(0); |
| 960 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 961 | |
| 962 | finishSendFile(); |
| 963 | await expect(assetPromise).resolves.toBeUndefined(); |
| 964 | }); |
| 965 | }); |