SIDBuilderFactory.java

package builder;

import builder.resid.ReSIDBuilder;
import libsidplay.common.CPUClock;
import libsidplay.common.Engine;
import libsidplay.common.EventScheduler;
import libsidplay.common.SIDBuilder;
import libsidplay.components.cart.Cartridge;
import libsidplay.config.IConfig;

/** Creates software SIDs without requiring the optional network and hardware implementations. */
public final class SIDBuilderFactory {

    public interface Backend {
        SIDBuilder create(Engine engine, EventScheduler context, IConfig config, CPUClock cpuClock,
                          Cartridge cartridge, int cyclesPerFrame);

        String credits();
    }

    private static Backend hardwareBackend;

    private SIDBuilderFactory() {
    }

    public static SIDBuilder create(Engine engine, EventScheduler context, IConfig config, CPUClock cpuClock,
                                    Cartridge cartridge, int cyclesPerFrame) {
        if (engine == Engine.EMULATION) {
            return new ReSIDBuilder(context, config, cpuClock, cartridge);
        }
        Backend backend = getHardwareBackend();
        if (backend == null) {
            throw new UnsupportedOperationException(
                    "SID engine " + engine + " is not included in this emulator library; use EMULATION.");
        }
        return backend.create(engine, context, config, cpuClock, cartridge, cyclesPerFrame);
    }

    public static String credits() {
        Backend backend = getHardwareBackend();
        return backend != null ? backend.credits() : "";
    }

    private static synchronized Backend getHardwareBackend() {
        if (hardwareBackend == null) {
            try {
                hardwareBackend = Class.forName("builder.HardwareSIDBuilderFactory").asSubclass(Backend.class)
                        .getConstructor().newInstance();
            } catch (ClassNotFoundException e) {
                return null;
            } catch (ReflectiveOperationException e) {
                throw new IllegalStateException("Cannot initialize hardware SID support", e);
            }
        }
        return hardwareBackend;
    }
}