namespace Spice86.Core.Emulator.Devices.CdRom;
using Spice86.Shared.Emulator.Storage.CdRom;
using Spice86.Core.Emulator.Devices.Sound;
using Spice86.Shared.Interfaces;
using Spice86.Audio.Common;
using Spice86.Audio.Filters;
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
/// Manages real-time CD audio streaming through the software mixer.
public sealed class CdAudioPlayer {
private const int CdAudioSampleRateHz = 44100;
private const int AudioSectorSizeBytes = 2352;
private const int SamplesPerSector = 588;
private readonly SoundChannel _soundChannel;
private readonly IDriveActivityNotifier _activityNotifier;
private readonly ICdRomDrive _drive;
private readonly char _driveLetter = '\0';
private byte[] _rawAudioBuffer = [];
private float[] _floatSampleBuffer = [];
/// Initialises a new with an activity notifier.
/// The CD-ROM drive
/// The sound channel creator used to register the CD audio channel.
/// Notifier that surfaces per-drive read activity for streamed audio sectors.
/// The DOS drive letter that owns the audio stream.
public CdAudioPlayer(ICdRomDrive cdRomDrive, ISoundChannelCreator channelCreator, IDriveActivityNotifier activityNotifier, char driveLetter) {
_soundChannel = channelCreator.AddChannel(AudioCallback, CdAudioSampleRateHz, "CD Audio",
new HashSet { ChannelFeature.DigitalAudio, ChannelFeature.Stereo, ChannelFeature.ReverbSend });
_soundChannel.Enable(false);
_drive = cdRomDrive;
_activityNotifier = activityNotifier;
_driveLetter = char.ToUpperInvariant(driveLetter);
}
/// Enables the sound channel to begin streaming audio.
public void StartPlayback() {
_soundChannel.Enable(true);
}
/// Disables the sound channel and halts audio streaming.
public void StopPlayback() {
_soundChannel.Enable(false);
}
/// Disables the sound channel without resetting the playback position.
public void PausePlayback() {
_soundChannel.Enable(false);
}
/// Re-enables the sound channel to continue streaming audio.
public void ResumePlayback() {
_soundChannel.Enable(true);
}
/// Applies MSCDEX channel-control routing and gain to the live CD audio mixer channel.
/// Mapped destination for the left CD channel.
/// Gain for the left CD channel in the 0-255 MSCDEX range.
/// Mapped destination for the right CD channel.
/// Gain for the right CD channel in the 0-255 MSCDEX range.
public void ApplyChannelControl(byte leftOutput, byte leftVolume, byte rightOutput, byte rightVolume) {
_soundChannel.AppVolume = new AudioFrame(leftVolume / 255.0f, rightVolume / 255.0f);
_soundChannel.SetChannelMap(new StereoLine {
Left = leftOutput == 1 ? LineIndex.Right : LineIndex.Left,
Right = rightOutput == 0 ? LineIndex.Left : LineIndex.Right,
});
}
private void AudioCallback(int framesRequested) {
if (_drive == null) {
return;
}
CdAudioPlayback status = _drive.GetAudioStatus();
if (status.Status != CdAudioStatus.Playing) {
_soundChannel.Enable(false);
return;
}
int remainingSectors = status.EndLba - status.CurrentLba;
if (remainingSectors <= 0) {
status.Status = CdAudioStatus.Stopped;
_soundChannel.Enable(false);
return;
}
int sectorsNeeded = (framesRequested + SamplesPerSector - 1) / SamplesPerSector;
int sectorsToRead = Math.Min(sectorsNeeded, remainingSectors);
int rawBytesNeeded = sectorsToRead * AudioSectorSizeBytes;
if (_rawAudioBuffer.Length < rawBytesNeeded) {
_rawAudioBuffer = new byte[rawBytesNeeded];
}
Span rawAudio = _rawAudioBuffer.AsSpan(0, rawBytesNeeded);
int bytesRead = _drive.Read(status.CurrentLba, sectorsToRead, rawAudio, CdSectorMode.AudioRaw2352);
int completeSectorsRead = bytesRead / AudioSectorSizeBytes;
if (completeSectorsRead <= 0) {
status.Status = CdAudioStatus.Stopped;
_soundChannel.Enable(false);
return;
}
int completeBytesRead = completeSectorsRead * AudioSectorSizeBytes;
if (_driveLetter != '\0') {
_activityNotifier.NotifyRead(_driveLetter);
}
int sampleCount = completeBytesRead / 2;
if (_floatSampleBuffer.Length < sampleCount) {
_floatSampleBuffer = new float[sampleCount];
}
// CD-DA on a BIN image is signed 16-bit little-endian PCM (Red Book)
ReadOnlySpan rawAudioRead = _rawAudioBuffer.AsSpan(0, completeBytesRead);
for (int i = 0; i < sampleCount; i++) {
short sample = BinaryPrimitives.ReadInt16LittleEndian(rawAudioRead.Slice(i * 2, 2));
_floatSampleBuffer[i] = sample;
}
int numFrames = sampleCount / 2;
_soundChannel.AddSamplesFloat(numFrames, _floatSampleBuffer.AsSpan(0, sampleCount));
status.CurrentLba += completeSectorsRead;
if (status.CurrentLba >= status.EndLba || completeSectorsRead < sectorsToRead) {
status.Status = CdAudioStatus.Stopped;
_soundChannel.Enable(false);
}
}
}