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