fix(native): complete cross-platform media and packet integration
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
Release Tag / validate-version (push) Canceled after 0s
Release Tag / trigger-release (push) Canceled after 0s
macOS native compatibility / native (arm64, macos-15) (push) Canceled after 0s
macOS native compatibility / native (x64, macos-15-intel) (push) Canceled after 0s
This commit is contained in:
1 parent
4e2c48624a
commit
abda6a96de
18 files changed
+474
-230
No files matched your search
@@ -0,0 +1,38 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { encodeSilk } from '@/napcat-core/helper/audio';
|
||||
import { FFmpegService } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
|
||||
vi.mock('@/napcat-core/helper/ffmpeg/ffmpeg', () => ({
|
||||
FFmpegService: { isSilk: vi.fn(), convertToNTSilkTct: vi.fn(), getDuration: vi.fn() },
|
||||
}));
|
||||
|
||||
const logger = { log: vi.fn() } as unknown as LogWrapper;
|
||||
|
||||
beforeEach(() => vi.resetAllMocks());
|
||||
|
||||
describe('SILK encoding', () => {
|
||||
it('reads duration from the encoded output including the final packet', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
|
||||
vi.mocked(FFmpegService.getDuration).mockResolvedValue(0.02);
|
||||
const result = await encodeSilk('/short.wav', '/temp', logger);
|
||||
expect(result.converted).toBe(true);
|
||||
expect(FFmpegService.convertToNTSilkTct).toHaveBeenCalledWith('/short.wav', result.path);
|
||||
expect(FFmpegService.getDuration).toHaveBeenCalledWith(result.path);
|
||||
expect(result.duration).toBe(0.02);
|
||||
});
|
||||
|
||||
it('propagates a corrupt SILK error without estimating its duration', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(true);
|
||||
vi.mocked(FFmpegService.getDuration).mockRejectedValue(new Error('corrupt SILK packet'));
|
||||
await expect(encodeSilk('/corrupt.silk', '/temp', logger)).rejects.toThrow('corrupt SILK packet');
|
||||
expect(FFmpegService.convertToNTSilkTct).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('propagates conversion errors to the caller', async () => {
|
||||
vi.mocked(FFmpegService.isSilk).mockResolvedValue(false);
|
||||
vi.mocked(FFmpegService.convertToNTSilkTct).mockRejectedValue(new Error('encoder unavailable'));
|
||||
await expect(encodeSilk('/audio.wav', '/temp', logger)).rejects.toThrow('encoder unavailable');
|
||||
expect(FFmpegService.getDuration).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import path from 'node:path';
|
||||
import { FFmpegAdapterFactory } from '@/napcat-core/helper/ffmpeg/ffmpeg-adapter-factory';
|
||||
import { FFmpegAddonAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-addon-adapter';
|
||||
import { FFmpegExecAdapter } from '@/napcat-core/helper/ffmpeg/ffmpeg-exec-adapter';
|
||||
import { FFmpegService, getFFmpegPath } from '@/napcat-core/helper/ffmpeg/ffmpeg';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
execute: vi.fn(),
|
||||
dlopen: vi.fn(),
|
||||
exists: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('fs', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('fs')>();
|
||||
return { ...original, existsSync: mocks.exists };
|
||||
});
|
||||
|
||||
vi.mock('child_process', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('child_process')>();
|
||||
return {
|
||||
...original,
|
||||
execFile: Object.assign(vi.fn(), {
|
||||
[Symbol.for('nodejs.util.promisify.custom')]: mocks.execute,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock('node:process', async (importOriginal) => {
|
||||
const original = await importOriginal<typeof import('node:process')>();
|
||||
return { ...original, dlopen: mocks.dlopen };
|
||||
});
|
||||
|
||||
const logger = { log: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
|
||||
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
||||
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
|
||||
beforeEach(() => {
|
||||
FFmpegAdapterFactory.reset();
|
||||
vi.stubEnv('FFMPEG_PATH', '');
|
||||
vi.stubEnv('FFPROBE_PATH', '');
|
||||
mocks.execute.mockReset().mockResolvedValue({ stdout: '', stderr: '' });
|
||||
mocks.dlopen.mockReset();
|
||||
mocks.exists.mockReset().mockReturnValue(false);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllEnvs();
|
||||
Object.defineProperty(process, 'platform', platformDescriptor);
|
||||
Object.defineProperty(process, 'arch', archDescriptor);
|
||||
});
|
||||
|
||||
describe('FFmpeg platform paths', () => {
|
||||
it.each(['arm64', 'x64'])('finds Homebrew for macOS %s outside GUI PATH', (arch) => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
vi.stubEnv('PATH', '/usr/bin:/bin');
|
||||
const prefix = arch === 'arm64' ? '/opt/homebrew/bin' : '/usr/local/bin';
|
||||
mocks.exists.mockImplementation(candidate => String(candidate).startsWith(path.join(prefix)));
|
||||
expect(getFFmpegPath('ffmpeg')).toBe(path.join(prefix, 'ffmpeg'));
|
||||
expect(getFFmpegPath('ffprobe')).toBe(path.join(prefix, 'ffprobe'));
|
||||
});
|
||||
|
||||
it('preserves explicit paths containing spaces without searching alternatives', () => {
|
||||
vi.stubEnv('FFMPEG_PATH', '/private/My Tools/ffmpeg');
|
||||
vi.stubEnv('FFPROBE_PATH', '/private/My Tools/ffprobe');
|
||||
const exists = mocks.exists.mockReturnValue(true);
|
||||
expect(getFFmpegPath('ffmpeg', '/app')).toBe('/private/My Tools/ffmpeg');
|
||||
expect(getFFmpegPath('ffprobe', '/app')).toBe('/private/My Tools/ffprobe');
|
||||
expect(exists).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses packaged Windows executables before PATH', () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'win32' });
|
||||
mocks.exists.mockReturnValue(true);
|
||||
expect(getFFmpegPath('ffmpeg', '/app')).toBe(path.join('/app', 'ffmpeg', 'ffmpeg.exe'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('FFmpeg adapter selection', () => {
|
||||
it.each(['arm64', 'x64'])('loads the packaged macOS %s addon', async (arch) => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
mocks.exists.mockReturnValue(true);
|
||||
mocks.dlopen.mockImplementation(module => { module.exports = {}; });
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app');
|
||||
expect(adapter.name).toBe('FFmpegAddon');
|
||||
expect(mocks.dlopen).toHaveBeenCalledWith(expect.anything(), path.join('/app', 'native/ffmpeg', 'ffmpegAddon.darwin.' + arch + '.node'));
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not hide a broken packaged addon behind another adapter', async () => {
|
||||
vi.spyOn(console, 'log').mockImplementation(() => {});
|
||||
mocks.exists.mockReturnValue(true);
|
||||
mocks.dlopen.mockImplementation(() => { throw new Error('wrong architecture'); });
|
||||
await expect(FFmpegAdapterFactory.getAdapter(logger, 'ffmpeg', 'ffprobe', '/app')).rejects.toThrow('Native Addon');
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
|
||||
});
|
||||
|
||||
it('honors an explicit command line configuration', async () => {
|
||||
vi.stubEnv('FFMPEG_PATH', '/tools/ffmpeg');
|
||||
mocks.exists.mockReturnValue(true);
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger, '/tools/ffmpeg', '/tools/ffprobe', '/app');
|
||||
expect(adapter.name).toBe('FFmpegExec');
|
||||
expect(mocks.dlopen).not.toHaveBeenCalled();
|
||||
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffmpeg', ['-version'], expect.objectContaining({ timeout: 10000 }));
|
||||
expect(mocks.execute).toHaveBeenCalledWith('/tools/ffprobe', ['-version'], expect.objectContaining({ timeout: 10000 }));
|
||||
});
|
||||
|
||||
it('rejects a missing ffprobe and allows a corrected configuration', async () => {
|
||||
mocks.exists.mockReturnValue(false);
|
||||
mocks.execute.mockImplementation(async command => {
|
||||
if (command === 'ffprobe') throw new Error('ENOENT');
|
||||
return { stdout: '', stderr: '' };
|
||||
});
|
||||
await expect(FFmpegAdapterFactory.getAdapter(logger)).rejects.toThrow('ffprobe');
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBeNull();
|
||||
mocks.execute.mockResolvedValue({ stdout: '', stderr: '' });
|
||||
expect((await FFmpegAdapterFactory.getAdapter(logger)).name).toBe('FFmpegExec');
|
||||
});
|
||||
|
||||
it('validates replacement paths before changing the active adapter', async () => {
|
||||
const adapter = await FFmpegAdapterFactory.getAdapter(logger);
|
||||
mocks.execute.mockRejectedValue(new Error('EACCES'));
|
||||
await expect(FFmpegAdapterFactory.updateFFmpegPath(logger, '/bad/ffmpeg', '/bad/ffprobe')).rejects.toThrow('/bad/ffprobe');
|
||||
expect(FFmpegAdapterFactory.getCurrentAdapter()).toBe(adapter);
|
||||
});
|
||||
});
|
||||
|
||||
describe('FFmpeg media operations', () => {
|
||||
it('transcodes encoded audio without treating its bytes as raw PCM', async () => {
|
||||
mocks.exists.mockReturnValue(true);
|
||||
await new FFmpegExecAdapter().convertFile('/record.wav', '/record.mp3', 'mp3');
|
||||
expect(mocks.execute).toHaveBeenCalledWith('ffmpeg', [
|
||||
'-i', '/record.wav', '-vn', '-ac', '1', '-y', '/record.mp3',
|
||||
], expect.objectContaining({ timeout: 120000, windowsHide: true }));
|
||||
});
|
||||
|
||||
it('reports a corrupt video instead of inventing dimensions and duration', async () => {
|
||||
mocks.execute.mockRejectedValue(new Error('invalid video'));
|
||||
await expect(new FFmpegExecAdapter().getVideoInfo('/video.mp4')).rejects.toThrow('invalid video');
|
||||
});
|
||||
|
||||
it('reads actual video metadata and JPEG bytes without a shared temporary file', async () => {
|
||||
const thumbnail = Buffer.from([255, 216, 255, 217]);
|
||||
mocks.execute.mockImplementation(async command => command === 'ffprobe'
|
||||
? { stdout: JSON.stringify({ streams: [{ width: 360, height: 480 }], format: { duration: '0.5', format_name: 'mov,mp4' } }) }
|
||||
: { stdout: thumbnail });
|
||||
await expect(new FFmpegExecAdapter().getVideoInfo('/clip with spaces.mp4')).resolves.toEqual({
|
||||
width: 360, height: 480, duration: 0.5, format: 'mov,mp4', thumbnail,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the native PNG encoder for legacy videos on macOS', async () => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
const adapter = new FFmpegAddonAdapter('/app');
|
||||
const extract = vi.spyOn(adapter, 'extractThumbnail').mockResolvedValue();
|
||||
vi.spyOn(FFmpegAdapterFactory, 'getAdapter').mockResolvedValue(adapter);
|
||||
await FFmpegService.init('/app', logger);
|
||||
await FFmpegService.extractLegacyVideoThumbnail('/video.mp4', '/thumbnail.png');
|
||||
expect(extract).toHaveBeenCalledWith('/video.mp4', '/thumbnail.png', 'png');
|
||||
expect(mocks.execute).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps startup available and reports unavailable media until paths are corrected', async () => {
|
||||
vi.resetModules();
|
||||
const { FFmpegService: service } = await import('@/napcat-core/helper/ffmpeg/ffmpeg');
|
||||
mocks.exists.mockReturnValue(false);
|
||||
mocks.execute.mockRejectedValue(new Error('ENOENT'));
|
||||
await expect(service.init('/app', logger)).resolves.toBeUndefined();
|
||||
await expect(service.getDuration('/audio.wav')).rejects.toThrow('ffprobe');
|
||||
expect(logger.logError).toHaveBeenCalled();
|
||||
mocks.execute.mockResolvedValue({ stdout: '1.5', stderr: '' });
|
||||
await service.setFfmpegPath('/installed tools', logger);
|
||||
await expect(service.getDuration('/audio.wav')).resolves.toBe(1.5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import fs from 'node:fs';
|
||||
import { NativePacketHandler } from '@/napcat-core/packet/handler/client';
|
||||
import { Napi2NativeLoader } from '@/napcat-core/packet/handler/napi2nativeLoader';
|
||||
import { NativePacketClient } from '@/napcat-core/packet/client/nativeClient';
|
||||
import type { LogWrapper } from '@/napcat-core/helper/log';
|
||||
import type { NapCoreContext } from '@/napcat-core/packet/context/napCoreContext';
|
||||
import type { PacketLogger } from '@/napcat-core/packet/context/loggerContext';
|
||||
import type { LogStack } from '@/napcat-core/packet/context/clientContext';
|
||||
import type { PacketBuf } from '@/napcat-core/packet/transformer/base';
|
||||
|
||||
const logger = { log: vi.fn(), logWarn: vi.fn(), logError: vi.fn() } as unknown as LogWrapper;
|
||||
const platformDescriptor = Object.getOwnPropertyDescriptor(process, 'platform')!;
|
||||
const archDescriptor = Object.getOwnPropertyDescriptor(process, 'arch')!;
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
vi.spyOn(fs, 'existsSync').mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
Object.defineProperty(process, 'platform', platformDescriptor);
|
||||
Object.defineProperty(process, 'arch', archDescriptor);
|
||||
});
|
||||
|
||||
describe('macOS native loaders', () => {
|
||||
it.each(['arm64', 'x64'])('loads both packet modules for %s', async (arch) => {
|
||||
Object.defineProperty(process, 'arch', { value: arch });
|
||||
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation((module) => {
|
||||
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue('success') } });
|
||||
});
|
||||
const handler = new NativePacketHandler({ logger });
|
||||
expect(await handler.init('7.0.2-53644')).toBe(true);
|
||||
expect(dlopen.mock.calls[0]![1]).toContain('MoeHoo.darwin.' + arch + '.node');
|
||||
const loader = new Napi2NativeLoader({ logger });
|
||||
expect(loader.loaded).toBe(true);
|
||||
expect(dlopen.mock.calls[1]![1]).toContain('napi2native.darwin.' + arch + '.node');
|
||||
});
|
||||
|
||||
it.each(['error hook', 'error search', undefined])('does not report native failure %s as success', async (result) => {
|
||||
Object.defineProperty(process, 'arch', { value: 'arm64' });
|
||||
vi.spyOn(process, 'dlopen').mockImplementation(module => {
|
||||
Object.assign(module, { exports: { initHook: vi.fn().mockReturnValue(result) } });
|
||||
});
|
||||
expect(await new NativePacketHandler({ logger }).init('7.0.2-53644')).toBe(false);
|
||||
});
|
||||
|
||||
it('does not attempt dlopen when a native binary is absent', async () => {
|
||||
vi.mocked(fs.existsSync).mockReturnValue(false);
|
||||
const dlopen = vi.spyOn(process, 'dlopen').mockImplementation(() => {});
|
||||
const handler = new NativePacketHandler({ logger });
|
||||
expect(await handler.init('7.0.2-53644')).toBe(false);
|
||||
expect(new Napi2NativeLoader({ logger }).loaded).toBe(false);
|
||||
expect(dlopen).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('NativePacketClient', () => {
|
||||
function fixture () {
|
||||
const send = vi.fn();
|
||||
const minimum = vi.fn().mockImplementation(version => Number(version) <= 40768);
|
||||
const native = { initHook: vi.fn().mockReturnValue(true) };
|
||||
const core = { basicInfo: { requireMinNTQQBuild: minimum }, sendSsoCmdReqByContend: send };
|
||||
const logs = { pushLogWarn: vi.fn(), pushLogInfo: vi.fn(), pushLogError: vi.fn() };
|
||||
const client = new NativePacketClient(
|
||||
core as unknown as NapCoreContext,
|
||||
{ error: vi.fn() } as unknown as PacketLogger,
|
||||
logs as unknown as LogStack,
|
||||
native as unknown as Napi2NativeLoader
|
||||
);
|
||||
return { client, send, minimum, native };
|
||||
}
|
||||
|
||||
it('initializes the oldest supported build and clears availability after failure', async () => {
|
||||
const { client, minimum, native } = fixture();
|
||||
await client.init(0, '10', '20');
|
||||
expect(minimum).toHaveBeenCalledWith('40768');
|
||||
expect(client.available).toBe(true);
|
||||
native.initHook.mockReturnValue(false);
|
||||
await client.init(0, '10', '20');
|
||||
expect(client.available).toBe(false);
|
||||
});
|
||||
|
||||
it.each(['success', 'failure', 'timeout'])('clears request timers after %s', async (outcome) => {
|
||||
vi.useFakeTimers();
|
||||
const { client, send } = fixture();
|
||||
const payload = Buffer.from([0, 255, 128]) as PacketBuf;
|
||||
if (outcome === 'success') send.mockResolvedValue({ rspbuffer: payload });
|
||||
if (outcome === 'failure') send.mockRejectedValue(new Error('network unavailable'));
|
||||
if (outcome === 'timeout') send.mockReturnValue(new Promise(() => {}));
|
||||
const pending = client.sendPacket('Test.Command', payload, true, 50);
|
||||
if (outcome === 'success') {
|
||||
await expect(pending).resolves.toEqual({ seq: 0, cmd: 'Test.Command', data: payload });
|
||||
} else {
|
||||
const assertion = expect(pending).rejects.toThrow(outcome === 'timeout' ? '超时' : 'network unavailable');
|
||||
if (outcome === 'timeout') await vi.advanceTimersByTimeAsync(50);
|
||||
await assertion;
|
||||
}
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
expect(send).toHaveBeenCalledWith('Test.Command', payload);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user