HardSIDBuilder.java

package builder.hardsid;

import com.sun.jna.DefaultTypeMapper;
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.platform.EnumConverter;
import libsidplay.common.*;
import libsidplay.config.IAudioSection;
import libsidplay.config.IConfig;
import libsidplay.config.IEmulationSection;
import libsidplay.sidtune.SidTune;

import java.util.*;
import java.util.stream.Collectors;

import static builder.jhardsid.JHardSIDMapping.getModelDependantChipNum;
import static libsidplay.common.Engine.HARDSID;
import static libsidplay.config.ISidPlay2SystemProperties.MAX_SIDS;

/**
 *
 * Support of HARDSID USB devices like HardSID Uno, HardSID UPlay, and HardSID4U.
 *
 * @author Ken Händel
 *
 */
public class HardSIDBuilder implements HardwareSIDBuilder, Mixer {

    private static final short REGULAR_DELAY = 512;

    /**
     * System event context.
     */
    private final EventScheduler context;

    /**
     * Configuration
     */
    private final IConfig config;

    /**
     * CPU clock.
     */
    private final CPUClock cpuClock;

    private static HardSID hardSID;

    /**
     * Number of HardSID devices.
     */
    private static int deviceCount;

    /**
     * Device names of HardSID devices.
     */
    private static String[] deviceNames;

    /**
     * Number of SIDs of the first HardSID device.
     */
    private static int chipCount;

    /**
     * Device number. If more devices are connected, we use just the first one.
     */
    private byte deviceID;

    /**
     * Already used HardSIDs.
     */
    private final List<HardSIDEmu> sids = new ArrayList<>();

    private long lastSIDWriteTime;

    private int fastForwardFactor;

    private final int[] delayInCycles = new int[MAX_SIDS];

    @SuppressWarnings("deprecation")
    public HardSIDBuilder(EventScheduler context, IConfig config, CPUClock cpuClock) {
        this.context = context;
        this.config = config;
        this.cpuClock = cpuClock;
        if (hardSID == null) {
            try {
                hardSID = Native.load("hardsid", HardSID.class, createOptions());
//				hardSID = Native.load("/home/ken/Downloads/git/hardsid-usb-driver-interface-library-c/build/libhardsid.so", HardSID.class, createOptions());
//				hardSID = Native.load("C:\\Users\\kschw\\Downloads\\hardsid-usb-driver-interface-library-c\\build\\Debug\\hardsid.dll", HardSID.class, createOptions());
//				hardSID = Native.load("/Users/developer/Downloads/hardsid-usb-driver-interface-library-c/build/libhardsid.dylib", HardSID.class, createOptions());
            } catch (UnsatisfiedLinkError e) {
                System.err.println("Error: Windows, Linux or OSX is required to use " + HARDSID + " soundcard!");
                printInstallationHint();
                throw e;
            }
        }
        hardSID.InitHardSID_Mapper();
        deviceCount = hardSID.HardSID_Devices();
        chipCount = hardSID.HardSID_SIDCount(deviceID);
        deviceNames = new String[chipCount];
        for (int i = 1; i <= chipCount; i++) {
            deviceNames[i - 1] = "HardSID #" + i;
        }
    }

    @Override
    public void destroy() {
        if (hardSID != null) {
            hardSID.HardSID_Reset(deviceID);
            hardSID.HardSID_Uninitialize();
        }
    }

    private Map<String, Object> createOptions() {
        Map<String, Object> options = new HashMap<>();
        options.put(Library.OPTION_TYPE_MAPPER, new DefaultTypeMapper() {
            {
                addTypeConverter(WState.class, new EnumConverter<>(WState.class));
            }
        });
        return options;
    }

    @Override
    public SIDEmu lock(SIDEmu oldHardSID, int sidNum, SidTune tune) {
        IAudioSection audioSection = config.getAudioSection();
        IEmulationSection emulationSection = config.getEmulationSection();
        ChipModel chipModel = ChipModel.getChipModel(emulationSection, tune, sidNum);
        ChipModel defaultSidModel = emulationSection.getDefaultSidModel();

        Set<Integer> alreadyInUse = sids.stream().map(HardSIDEmu::getChipNum).map(Byte::intValue)
                .collect(Collectors.toSet());
        Integer chipNum = getModelDependantChipNum(config.getEmulationSection(), chipCount, alreadyInUse, chipModel);

        if (oldHardSID != null) {
            // always re-use hardware SID chips, if configuration changes,
            // the purpose is to ignore chip model changes!
            return oldHardSID;
        }
        if (deviceID < deviceCount && chipNum != null && chipNum < chipCount) {
            HardSIDEmu sid = createSID(deviceID, chipNum, sidNum, tune, chipModel, defaultSidModel);

            sid.lock();
            sid.setFilterEnable(emulationSection, sidNum);
            sid.setDigiBoost(emulationSection.isDigiBoosted8580());
            for (int voice = 0; voice < 4; voice++) {
                sid.setVoiceMute(voice, emulationSection.isMuteVoice(sidNum, voice));
            }
            sids.add(sid);
            setDeviceName(sidNum, deviceNames[chipNum]);
            setDelay(sidNum, audioSection.getDelay(sidNum));
            return sid;
        }
        System.err.printf("HARDSID ERROR: System doesn't have enough SID chips. Requested: (sidNum=%d)\n", sidNum);

        if (deviceCount == 0) {
            printInstallationHint();
        }
        return SIDEmu.NONE;
    }

    public static void printInstallationHint() {
        if (OS.get() == OS.WINDOWS) {
            printWindowsInstallationHint();
        } else if (OS.get() == OS.LINUX) {
            printLinuxInstallationHint();
        } else if (OS.get() == OS.MAC) {
            printMacInstallationHint();
        }
    }

    private static void printLinuxInstallationHint() {
        System.err.println("\"To give proper permissions, please type the following commands:\"");
        System.err.println("sudo vi /etc/udev/rules.d/92-hardsid4u.rules");
        System.err.println("\"Now, add the following single line:\"");
        System.err.println(
                "SUBSYSTEM==\"usb\",ATTR{idVendor}==\"6581\",ATTR{idProduct}==\"8580\",MODE=\"0660\",GROUP=\"plugdev\"");
        System.err.println("\"And finally type this command to refresh device configuration:\"");
        System.err.println("sudo udevadm trigger");
        System.err.println("sudo chmod -R 777 /dev/bus/usb/");
        System.err.println("You are ready to start :-)");
    }

    private static void printMacInstallationHint() {
        System.err.println("Unknown things to do... N.Y.T");
        System.err.println("This should work out-of-the box!? Is a different device driver loaded?");
    }

    private static void printWindowsInstallationHint() {
        System.err.println(
                "Go to \"Control Panel / Hardware / Device Manager\" and uninstall previous HardSID driver, and then reboot!");
        System.err.println("Now install Zadigs USB driver installation from that web-site: https://zadig.akeo.ie/");
        System.err.println(
                "Click install for device (658x 8580) and WinUSB, where x=1-3. These settings were already proposed by the installer for me.");
        System.err.println("You are ready to start :-)");
    }

    @Override
    public void unlock(final SIDEmu sidEmu) {
        HardSIDEmu hardSid = (HardSIDEmu) sidEmu;
        hardSid.unlock();
        sids.remove(sidEmu);
    }

    @Override
    public int getDeviceCount() {
        return chipCount;
    }

    public static String[] getDeviceNames() {
        return deviceNames;
    }

    @Override
    public Integer getDeviceId(int sidNum) {
        return sidNum < sids.size() ? (int) sids.get(sidNum).getChipNum() : null;
    }

    @Override
    public String getDeviceName(int sidNum) {
        return sidNum < sids.size() ? sids.get(sidNum).getDeviceName() : null;
    }

    public void setDeviceName(int sidNum, String serialNo) {
        if (sidNum < sids.size()) {
            sids.get(sidNum).setDeviceName(serialNo);
        }
    }

    @Override
    public ChipModel getDeviceChipModel(int sidNum) {
        return sidNum < sids.size() ? sids.get(sidNum).getChipModel() : null;
    }

    @Override
    public void start() {
    }

    @Override
    public void fadeIn(double fadeIn) {
        System.err.println("Fade-in unsupported by HardSID");
        // XXX unsupported by HardSID
    }

    @Override
    public void fadeOut(double fadeOut) {
        System.err.println("Fade-out unsupported by HardSID");
        // XXX unsupported by HardSID
    }

    @Override
    public void setVolume(int sidNum, float volume) {
        System.err.println("Volume unsupported by HardSID");
        // XXX unsupported by HardSID
    }

    @Override
    public void setBalance(int sidNum, float balance) {
        System.err.println("Balance unsupported by HardSID");
        // XXX unsupported by HardSID
    }

    public int getDelay(int sidNum) {
        return delayInCycles[sidNum];
    }

    @Override
    public void setDelay(int sidNum, int delay) {
        delayInCycles[sidNum] = (int) (cpuClock.getCpuFrequency() / 1000. * delay);
    }

    @Override
    public void fastForward() {
        fastForwardFactor++;
    }

    @Override
    public void normalSpeed() {
        fastForwardFactor = 0;
    }

    @Override
    public boolean isFastForward() {
        return fastForwardFactor != 0;
    }

    @Override
    public int getFastForwardFactor() {
        return fastForwardFactor;
    }

    @Override
    public int getFastForwardBitMask() {
        return (1 << fastForwardFactor) - 1;
    }

    @Override
    public void pause() {
        hardSID.HardSID_Flush(deviceID);
    }

    private HardSIDEmu createSID(byte deviceId, int chipNum, int sidNum, SidTune tune, ChipModel chipModel,
                                 ChipModel defaultChipModel) {
        final IEmulationSection emulationSection = config.getEmulationSection();

        if (SidTune.isFakeStereoSid(emulationSection, tune, sidNum)) {
            return new HardSIDEmu.FakeStereo(this, context, cpuClock, hardSID, deviceId, chipNum, sidNum, chipModel,
                    defaultChipModel, sids, emulationSection);
        } else {
            return new HardSIDEmu(this, context, cpuClock, hardSID, deviceId, chipNum, sidNum, chipModel,
                    defaultChipModel);
        }
    }

    int clocksSinceLastAccess() {
        final long now = context.getTime(Event.Phase.PHI2);
        int diff = (int) (now - lastSIDWriteTime);
        lastSIDWriteTime = now;
        return diff >> fastForwardFactor;
    }

    long eventuallyDelay() {
        final long now = context.getTime(Event.Phase.PHI2);
        int diff = (int) (now - lastSIDWriteTime);
        if (diff > REGULAR_DELAY) {
            lastSIDWriteTime += REGULAR_DELAY;
            hardSID.HardSID_Delay(deviceID, (short) (REGULAR_DELAY >> fastForwardFactor));
        }
        return REGULAR_DELAY;
    }
}