| 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 | })); |
| 16 | |
| 17 | function makeChildProcess () |
| 18 | { |
| 19 | const child = new EventEmitter(); |
| 20 | child.stdout = new EventEmitter(); |
| 21 | child.stderr = new EventEmitter(); |
| 22 | child.kill = jest.fn(); |
| 23 | return child; |
| 24 | } |
| 25 | |
| 26 | function makeReqRes () |
| 27 | { |
| 28 | const req = new EventEmitter(); |
| 29 | const res = new EventEmitter(); |
| 30 | const headers = {}; |
| 31 | |
| 32 | res.set = (name, value) => |
| 33 | { |
| 34 | headers[name] = value; |
| 35 | return res; |
| 36 | }; |
| 37 | res.type = () => res; |
| 38 | res.sendFile = (targetPath, cb) => |
| 39 | { |
| 40 | process.nextTick(() => |
| 41 | { |
| 42 | if (!fs.existsSync(targetPath)) |
| 43 | { |
| 44 | const err = new Error('File not found'); |
| 45 | err.code = 'ENOENT'; |
| 46 | cb(err); |
| 47 | return; |
| 48 | } |
| 49 | |
| 50 | res.emit('finish'); |
| 51 | cb(); |
| 52 | }); |
| 53 | }; |
| 54 | |
| 55 | return { req, res, headers }; |
| 56 | } |
| 57 | |
| 58 | describe('video stream bootstrap', () => |
| 59 | { |
| 60 | let mockSpawn; |
| 61 | let sourceFile; |
| 62 | |
| 63 | beforeEach(() => |
| 64 | { |
| 65 | jest.resetModules(); |
| 66 | mockSpawn = require('child_process').spawn; |
| 67 | mockSpawn.mockReset(); |
| 68 | |
| 69 | const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-')); |
| 70 | sourceFile = path.join(tmpDir, 'clip.mkv'); |
| 71 | fs.writeFileSync(sourceFile, 'video'); |
| 72 | }); |
| 73 | |
| 74 | test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () => |
| 75 | { |
| 76 | mockSpawn.mockImplementation((command, args) => |
| 77 | { |
| 78 | const child = makeChildProcess(); |
| 79 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 80 | |
| 81 | if (exeName.includes('ffprobe')) |
| 82 | { |
| 83 | process.nextTick(() => |
| 84 | { |
| 85 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 86 | format: { duration: '12.5' }, |
| 87 | streams: [ |
| 88 | { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} }, |
| 89 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 90 | ], |
| 91 | }))); |
| 92 | child.emit('close', 0); |
| 93 | }); |
| 94 | return child; |
| 95 | } |
| 96 | |
| 97 | expect(exeName.includes('ffmpeg')).toBe(true); |
| 98 | |
| 99 | const outputPattern = String(args[args.length - 1] || ''); |
| 100 | const outputDir = path.dirname(outputPattern); |
| 101 | |
| 102 | process.nextTick(() => |
| 103 | { |
| 104 | fs.mkdirSync(outputDir, { recursive: true }); |
| 105 | setTimeout(() => |
| 106 | { |
| 107 | fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n'); |
| 108 | }, 40); |
| 109 | }); |
| 110 | |
| 111 | return child; |
| 112 | }); |
| 113 | |
| 114 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 115 | const session = await createVideoStreamSession(sourceFile); |
| 116 | |
| 117 | expect(session).toEqual({ |
| 118 | sessionId: expect.any(String), |
| 119 | durationSeconds: 12.5, |
| 120 | videoWidth: 1920, |
| 121 | videoHeight: 1080, |
| 122 | subtitleTracks: [], |
| 123 | imageSubtitleTracks: [], |
| 124 | subtitleSummary: { |
| 125 | total: 0, |
| 126 | converted: 0, |
| 127 | imageBased: 0, |
| 128 | skipped: 0, |
| 129 | }, |
| 130 | }); |
| 131 | }); |
| 132 | |
| 133 | test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () => |
| 134 | { |
| 135 | mockSpawn.mockImplementation((command, args) => |
| 136 | { |
| 137 | const child = makeChildProcess(); |
| 138 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 139 | |
| 140 | if (exeName.includes('ffprobe')) |
| 141 | { |
| 142 | process.nextTick(() => |
| 143 | { |
| 144 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 145 | streams: [ |
| 146 | { codec_type: 'video', codec_name: 'h264', width: 1280, height: 720, tags: {}, disposition: {} }, |
| 147 | { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } }, |
| 148 | ], |
| 149 | }))); |
| 150 | child.emit('close', 0); |
| 151 | }); |
| 152 | return child; |
| 153 | } |
| 154 | |
| 155 | const segmentArgIndex = args.indexOf('-hls_segment_filename'); |
| 156 | expect(segmentArgIndex).toBeGreaterThan(-1); |
| 157 | expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts'); |
| 158 | expect(args).not.toContain('-hls_playlist_type'); |
| 159 | |
| 160 | const playlistPath = String(args[args.length - 1] || ''); |
| 161 | const outputDir = path.dirname(playlistPath); |
| 162 | process.nextTick(() => |
| 163 | { |
| 164 | fs.mkdirSync(outputDir, { recursive: true }); |
| 165 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 166 | }); |
| 167 | |
| 168 | return child; |
| 169 | }); |
| 170 | |
| 171 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 172 | await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ |
| 173 | sessionId: expect.any(String), |
| 174 | durationSeconds: null, |
| 175 | videoWidth: 1280, |
| 176 | videoHeight: 720, |
| 177 | subtitleTracks: [], |
| 178 | imageSubtitleTracks: [], |
| 179 | subtitleSummary: { |
| 180 | total: 0, |
| 181 | converted: 0, |
| 182 | imageBased: 0, |
| 183 | skipped: 0, |
| 184 | }, |
| 185 | }); |
| 186 | }); |
| 187 | |
| 188 | test('createVideoStreamSession reads duration from ffprobe duration tags', async () => |
| 189 | { |
| 190 | mockSpawn.mockImplementation((command, args) => |
| 191 | { |
| 192 | const child = makeChildProcess(); |
| 193 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 194 | |
| 195 | if (exeName.includes('ffprobe')) |
| 196 | { |
| 197 | process.nextTick(() => |
| 198 | { |
| 199 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 200 | streams: [ |
| 201 | { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, tags: { DURATION: '00:22:17.500000000' }, disposition: {} }, |
| 202 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 203 | ], |
| 204 | }))); |
| 205 | child.emit('close', 0); |
| 206 | }); |
| 207 | return child; |
| 208 | } |
| 209 | |
| 210 | const playlistPath = String(args[args.length - 1] || ''); |
| 211 | const outputDir = path.dirname(playlistPath); |
| 212 | process.nextTick(() => |
| 213 | { |
| 214 | fs.mkdirSync(outputDir, { recursive: true }); |
| 215 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 216 | }); |
| 217 | |
| 218 | return child; |
| 219 | }); |
| 220 | |
| 221 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 222 | await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({ |
| 223 | durationSeconds: 1337.5, |
| 224 | }); |
| 225 | }); |
| 226 | |
| 227 | test('createVideoStreamSession does not become ready from subtitle files alone', async () => |
| 228 | { |
| 229 | mockSpawn.mockImplementation((command, args) => |
| 230 | { |
| 231 | const child = makeChildProcess(); |
| 232 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 233 | |
| 234 | if (exeName.includes('ffprobe')) |
| 235 | { |
| 236 | process.nextTick(() => |
| 237 | { |
| 238 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 239 | streams: [ |
| 240 | { codec_type: 'video', codec_name: 'h264', width: 1024, height: 576, tags: {}, disposition: {} }, |
| 241 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 242 | { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} }, |
| 243 | ], |
| 244 | }))); |
| 245 | child.emit('close', 0); |
| 246 | }); |
| 247 | return child; |
| 248 | } |
| 249 | |
| 250 | const mapIndex = args.indexOf('-map'); |
| 251 | const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; |
| 252 | |
| 253 | if (mappedValue.startsWith('0:s:')) |
| 254 | { |
| 255 | const subtitleTarget = String(args[args.length - 1] || ''); |
| 256 | process.nextTick(() => |
| 257 | { |
| 258 | fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true }); |
| 259 | fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n'); |
| 260 | child.emit('close', 0); |
| 261 | }); |
| 262 | return child; |
| 263 | } |
| 264 | |
| 265 | const playlistPath = String(args[args.length - 1] || ''); |
| 266 | const outputDir = path.dirname(playlistPath); |
| 267 | process.nextTick(() => |
| 268 | { |
| 269 | fs.mkdirSync(outputDir, { recursive: true }); |
| 270 | setTimeout(() => |
| 271 | { |
| 272 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 273 | }, 80); |
| 274 | }); |
| 275 | |
| 276 | return child; |
| 277 | }); |
| 278 | |
| 279 | const { createVideoStreamSession } = require('../server/video-stream'); |
| 280 | const startedAt = Date.now(); |
| 281 | const session = await createVideoStreamSession(sourceFile); |
| 282 | const elapsedMs = Date.now() - startedAt; |
| 283 | |
| 284 | expect(elapsedMs).toBeGreaterThanOrEqual(60); |
| 285 | expect(session).toEqual({ |
| 286 | sessionId: expect.any(String), |
| 287 | durationSeconds: null, |
| 288 | videoWidth: 1024, |
| 289 | videoHeight: 576, |
| 290 | subtitleTracks: [ |
| 291 | expect.objectContaining({ |
| 292 | fileName: 'subtitle-0.vtt', |
| 293 | language: 'eng', |
| 294 | }), |
| 295 | ], |
| 296 | imageSubtitleTracks: [], |
| 297 | subtitleSummary: { |
| 298 | total: 1, |
| 299 | converted: 1, |
| 300 | imageBased: 0, |
| 301 | skipped: 0, |
| 302 | }, |
| 303 | }); |
| 304 | }); |
| 305 | |
| 306 | test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () => |
| 307 | { |
| 308 | mockSpawn.mockImplementation((command, args) => |
| 309 | { |
| 310 | const child = makeChildProcess(); |
| 311 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 312 | |
| 313 | if (exeName.includes('ffprobe')) |
| 314 | { |
| 315 | process.nextTick(() => |
| 316 | { |
| 317 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 318 | streams: [ |
| 319 | { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} }, |
| 320 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 321 | { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} }, |
| 322 | ], |
| 323 | }))); |
| 324 | child.emit('close', 0); |
| 325 | }); |
| 326 | return child; |
| 327 | } |
| 328 | |
| 329 | const mapIndex = args.indexOf('-map'); |
| 330 | const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; |
| 331 | |
| 332 | // Fail subtitle extraction but keep HLS transcoding path successful. |
| 333 | if (mappedValue.startsWith('0:s:')) |
| 334 | { |
| 335 | process.nextTick(() => |
| 336 | { |
| 337 | child.stderr.emit('data', Buffer.from('Subtitle codec not supported')); |
| 338 | child.emit('close', 1); |
| 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: 1920, |
| 359 | videoHeight: 1080, |
| 360 | subtitleTracks: [], |
| 361 | imageSubtitleTracks: [ |
| 362 | expect.objectContaining({ |
| 363 | label: 'Subtitle 1 (eng)', |
| 364 | language: 'eng', |
| 365 | streamIndex: 0, |
| 366 | }), |
| 367 | ], |
| 368 | subtitleSummary: { |
| 369 | total: 1, |
| 370 | converted: 0, |
| 371 | imageBased: 1, |
| 372 | skipped: 0, |
| 373 | }, |
| 374 | }); |
| 375 | }); |
| 376 | |
| 377 | test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', 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', tags: {}, disposition: {} }, |
| 391 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 392 | ], |
| 393 | }))); |
| 394 | child.emit('close', 0); |
| 395 | }); |
| 396 | return child; |
| 397 | } |
| 398 | |
| 399 | const playlistPath = String(args[args.length - 1] || ''); |
| 400 | const outputDir = path.dirname(playlistPath); |
| 401 | process.nextTick(() => |
| 402 | { |
| 403 | fs.mkdirSync(outputDir, { recursive: true }); |
| 404 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 405 | }); |
| 406 | return child; |
| 407 | }); |
| 408 | |
| 409 | const streamModule = require('../server/video-stream'); |
| 410 | const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); |
| 411 | const beforeDirs = new Set( |
| 412 | fs.existsSync(streamModule.STREAM_ROOT_DIR) |
| 413 | ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) |
| 414 | : [] |
| 415 | ); |
| 416 | const session = await streamModule.createVideoStreamSession(sourceFile); |
| 417 | const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); |
| 418 | const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName)); |
| 419 | expect(newDirName).toEqual(expect.any(String)); |
| 420 | const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); |
| 421 | expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true); |
| 422 | const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; |
| 423 | |
| 424 | for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1) |
| 425 | { |
| 426 | const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`; |
| 427 | fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`); |
| 428 | } |
| 429 | |
| 430 | const { req, res } = makeReqRes(); |
| 431 | await streamModule.sendVideoStreamAsset( |
| 432 | session.sessionId, |
| 433 | `stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`, |
| 434 | req, |
| 435 | res |
| 436 | ); |
| 437 | |
| 438 | await new Promise((resolve) => setTimeout(resolve, 80)); |
| 439 | |
| 440 | expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false); |
| 441 | expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true); |
| 442 | expect(pruneOldImageSubtitleCaches).toHaveBeenCalled(); |
| 443 | |
| 444 | streamModule.releaseVideoStreamSession(session.sessionId); |
| 445 | }); |
| 446 | |
| 447 | test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () => |
| 448 | { |
| 449 | mockSpawn.mockImplementation((command, args) => |
| 450 | { |
| 451 | const child = makeChildProcess(); |
| 452 | const exeName = path.basename(String(command || '')).toLowerCase(); |
| 453 | |
| 454 | if (exeName.includes('ffprobe')) |
| 455 | { |
| 456 | process.nextTick(() => |
| 457 | { |
| 458 | child.stdout.emit('data', Buffer.from(JSON.stringify({ |
| 459 | streams: [ |
| 460 | { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, |
| 461 | { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, |
| 462 | ], |
| 463 | }))); |
| 464 | child.emit('close', 0); |
| 465 | }); |
| 466 | return child; |
| 467 | } |
| 468 | |
| 469 | const playlistPath = String(args[args.length - 1] || ''); |
| 470 | const outputDir = path.dirname(playlistPath); |
| 471 | process.nextTick(() => |
| 472 | { |
| 473 | fs.mkdirSync(outputDir, { recursive: true }); |
| 474 | fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); |
| 475 | }); |
| 476 | return child; |
| 477 | }); |
| 478 | |
| 479 | const streamModule = require('../server/video-stream'); |
| 480 | const firstViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 481 | const secondViewer = await streamModule.createVideoStreamSession(sourceFile); |
| 482 | |
| 483 | expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId); |
| 484 | |
| 485 | const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) => |
| 486 | path.basename(String(command || '')).toLowerCase().includes('ffmpeg') |
| 487 | ); |
| 488 | expect(ffmpegSpawns).toHaveLength(1); |
| 489 | |
| 490 | const firstReqRes = makeReqRes(); |
| 491 | await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res); |
| 492 | |
| 493 | const secondReqRes = makeReqRes(); |
| 494 | await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res); |
| 495 | |
| 496 | streamModule.releaseVideoStreamSession(firstViewer.sessionId); |
| 497 | |
| 498 | const stillActiveReqRes = makeReqRes(); |
| 499 | await expect( |
| 500 | streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res) |
| 501 | ).resolves.toBeUndefined(); |
| 502 | |
| 503 | const releasedReqRes = makeReqRes(); |
| 504 | await expect( |
| 505 | streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res) |
| 506 | ).rejects.toMatchObject({ status: 404 }); |
| 507 | |
| 508 | streamModule.releaseVideoStreamSession(secondViewer.sessionId); |
| 509 | }); |
| 510 | }); |