001package org.intellimate.izou.system.sound.replaced;
002
003import org.apache.logging.log4j.LogManager;
004import org.apache.logging.log4j.Logger;
005import org.aspectj.lang.ProceedingJoinPoint;
006import org.aspectj.lang.annotation.Around;
007import org.aspectj.lang.annotation.Aspect;
008import org.intellimate.izou.addon.AddOnModel;
009import org.intellimate.izou.main.Main;
010import org.intellimate.izou.system.sound.*;
011
012import javax.sound.sampled.Clip;
013import javax.sound.sampled.DataLine;
014import javax.sound.sampled.Line;
015import javax.sound.sampled.SourceDataLine;
016import java.util.Optional;
017
018/**
019 * @author LeanderK
020 * @version 1.0
021 */
022@Aspect
023public class MixerAspect {
024    static Main main;
025    private static final Logger logger= LogManager.getLogger(MixerAspect.class);
026
027    public static synchronized void init(Main main) {
028        if (MixerAspect.main == null)
029            MixerAspect.main = main;
030    }
031
032    /**
033     * creates the appropriate IzouSoundLine if the request originates from an AddOn.
034     * @param line the line
035     * @return an IzouSoundLine if an addon requested the line
036     */
037    static Line getAndRegisterLine(Line line) {
038        AddOnModel addOnModel;
039        Optional<AddOnModel> addOnModelForClassLoader = main.getSecurityManager().getAddOnModelForClassLoader();
040        if (!addOnModelForClassLoader.isPresent()) {
041            logger.debug("the SoundManager will not manage this line, obtained by system");
042            return line;
043        } else {
044            addOnModel = addOnModelForClassLoader.get();
045        }
046
047        IzouSoundLineBaseClass izouSoundLine;
048        if (line instanceof SourceDataLine) {
049            if (line instanceof Clip) {
050                izouSoundLine = new IzouSoundLineClipAndSDLine((Clip) line, (SourceDataLine) line, main, false, addOnModel);
051            } else {
052                izouSoundLine = new IzouSoundSourceDataLine((SourceDataLine) line, main, false, addOnModel);
053            }
054        } else if (line instanceof Clip) {
055            izouSoundLine = new IzouSoundLineClip((Clip) line, main, false, addOnModel);
056        } else if (line instanceof DataLine) {
057            izouSoundLine = new IzouSoundDataLine((DataLine) line, main, false, addOnModel);
058        } else {
059            izouSoundLine = new IzouSoundLineBaseClass(line, main, false, addOnModel);
060        }
061        main.getSoundManager().addIzouSoundLine(addOnModel, izouSoundLine);
062        return izouSoundLine;
063    }
064
065    @Around("execution(* javax.sound.sampled.AudioSystem.getLine(javax.sound.sampled.Line.Info))")
066    public Object getLineAdvice(ProceedingJoinPoint pjp) throws Throwable {
067        pjp.getArgs();
068        Line line = (Line) pjp.proceed();
069        return MixerAspect.getAndRegisterLine(line);
070    }
071}