| 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 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 521 | }); |
| 522 | |
| 523 | test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () => |
| 524 | { |
| 525 | mockSpawn.mockImplementation((command, args) => |
| 526 | { |
| 527 | const child = makeChildProcess(); |
| 528 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 529 | if (exeName.includes('ffprobe')) |
| 530 | { |
| 531 | process.nextTick(() => |
| 532 | { |
| 533 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 534 | streams: [ |
| 535 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 536 | ], |
| 537 | }))); |
| 538 | child.emit('close', 0); |
| 539 | }); |
| 540 | return child; |
| 541 | } |
| 542 | const outputDir = path.dirname(String(args[args.length - 1] || '')); |
| 543 | process.nextTick(() => |
| 544 | { |
| 545 | fs.mkdirSync(outputDir, { recursive: true }); |
| 546 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 547 | }); |
| 548 | return child; |
| 549 | }); |
| 550 | |
| 551 | const streamModule = require('../server/video-stream'); |
| 552 | const beforeDirs = new Set( |
| 553 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 554 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 555 | : [] |
| 556 | ); |
| 557 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 558 | const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d)); |
| 559 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 560 | |
| 561 | // Write a small number of named-variant segments (below the retention window). |
| 562 | const segmentCount = 10; |
| 563 | for (let i = 0; i < segmentCount; i += 1) |
| 564 | { |
| 565 | fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`); |
| 566 | } |
| 567 | |
| 568 | const { req, res } = makeReqRes(); |
| 569 | await streamModule.sendVideoStreamAsset( |
| 570 | session.sessionId, |
| 571 | `stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`, |
| 572 | req, |
| 573 | res |
| 574 | ); |
| 575 | |
| 576 | // Segment count is below retention threshold — nothing should be deleted. |
| 577 | expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount); |
| 578 | |
| 579 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 580 | }); |
| 581 | |
| 582 | test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () => |
| 583 | { |
| 584 | mockSpawn.mockImplementation((command, args) => |
| 585 | { |
| 586 | const child = makeChildProcess(); |
| 587 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 588 | |
| 589 | if (exeName.includes('ffprobe')) |
| 590 | { |
| 591 | process.nextTick(() => |
| 592 | { |
| 593 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 594 | streams: [ |
| 595 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 596 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 597 | ], |
| 598 | }))); |
| 599 | child.emit('close', 0); |
| 600 | }); |
| 601 | return child; |
| 602 | } |
| 603 | |
| 604 | const playlistPath = String(args[args.length - 1] || ''); |
| 605 | const outputDir = path.dirname(playlistPath); |
| 606 | process.nextTick(() => |
| 607 | { |
| 608 | fs.mkdirSync(outputDir, { recursive: true }); |
| 609 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 610 | }); |
| 611 | return child; |
| 612 | }); |
| 613 | |
| 614 | const streamModule = require('../server/video-stream'); |
| 615 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 616 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 617 | |
| 618 | expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId); |
| 619 | |
| 620 | const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) => |
| 621 | path.basename(String(command || '')).toLowerCase().includes('ffmpeg') |
| 622 | ); |
| 623 | expect(ffmpegSpawns).toHaveLength(1); |
| 624 | |
| 625 | const firstReqRes = makeReqRes(); |
| 626 | await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res); |
| 627 | |
| 628 | const secondReqRes = makeReqRes(); |
| 629 | await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res); |
| 630 | |
| 631 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 632 | |
| 633 | const stillActiveReqRes = makeReqRes(); |
| 634 | await expect( |
| 635 | streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res) |
| 636 | ).resolves.toBeUndefined(); |
| 637 | |
| 638 | const releasedReqRes = makeReqRes(); |
| 639 | await expect( |
| 640 | streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res) |
| 641 | ).rejects.toMatchObject({ status: 404 }); |
| 642 | |
| 643 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 644 | }); |
| 645 | |
| 646 | test('purges subtitle disk cache when the module is first loaded', () => |
| 647 | { |
| 648 | const { purgeSubtitleCacheDir } = require('../server/image-subtitles'); |
| 649 | require('../server/video-stream'); |
| 650 | expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1); |
| 651 | }); |
| 652 | |
| 653 | test('purges stream output directory when the module is first loaded', () => |
| 654 | { |
| 655 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 656 | const orphanDir = path.join(streamRoot, 'orphan-after-restart'); |
| 657 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 658 | fs.writeFileSync(path.join(orphanDir, 'stream_0_segment_000001.ts'), 'segment'); |
| 659 | |
| 660 | require('../server/video-stream'); |
| 661 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 662 | }); |
| 663 | |
| 664 | test('cleanupIdleStreamArtifacts removes stream output directory when no streams are active', () => |
| 665 | { |
| 666 | const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); |
| 667 | const orphanDir = path.join(streamRoot, 'orphan-idle-cleanup'); |
| 668 | fs.mkdirSync(orphanDir, { recursive: true }); |
| 669 | fs.writeFileSync(path.join(orphanDir, 'stream_0.m3u8'), '#EXTM3U\n'); |
| 670 | |
| 671 | const streamModule = require('../server/video-stream'); |
| 672 | streamModule.cleanupIdleStreamArtifacts(); |
| 673 | |
| 674 | expect(fs.existsSync(orphanDir)).toBe(false); |
| 675 | }); |
| 676 | |
| 677 | test('clears subtitle caches for a video when its last stream is released', async () => |
| 678 | { |
| 679 | mockSpawn.mockImplementation((command, args) => |
| 680 | { |
| 681 | const child = makeChildProcess(); |
| 682 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 683 | |
| 684 | if (exeName.includes('ffprobe')) |
| 685 | { |
| 686 | process.nextTick(() => |
| 687 | { |
| 688 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 689 | streams: [ |
| 690 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 691 | ], |
| 692 | }))); |
| 693 | child.emit('close', 0); |
| 694 | }); |
| 695 | return child; |
| 696 | } |
| 697 | |
| 698 | const playlistPath = String(args[args.length - 1] || ''); |
| 699 | const outputDir = path.dirname(playlistPath); |
| 700 | process.nextTick(() => |
| 701 | { |
| 702 | fs.mkdirSync(outputDir, { recursive: true }); |
| 703 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 704 | }); |
| 705 | return child; |
| 706 | }); |
| 707 | |
| 708 | const streamModule = require('../server/video-stream'); |
| 709 | const { clearCachesForFile } = require('../server/image-subtitles'); |
| 710 | |
| 711 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 712 | clearCachesForFile.mockClear(); |
| 713 | |
| 714 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 715 | expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); |
| 716 | }); |
| 717 | }); |