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