]> ruin.nu Git - moosique.git/blobdiff - Moosique.java
Fixed accessors, encoders and decoders for tempo and time signature.
[moosique.git] / Moosique.java
index c99d93cef21971aa71ae7bcf4ede6db984c0521a..e2b7f3e490821832347b01fae8c9289f9eff228a 100644 (file)
@@ -20,17 +20,17 @@ public class Moosique {
        private static Receiver receiver;
        private static MidiChannel[] channels;
        private static MidiChannel activeChannel;
-       private static MidiEvent[] timeSignatures, tempoChanges;
 
-       private static ArrayList copyBuffer, emptyTracks;
+       private static ArrayList copyBuffer, emptyTracks, timeSignatures, tempoChanges;
        private static Map trackMute = new HashMap();
        private static Map trackSolo = new HashMap();
        private static Thread player;
 
-       private static String filename;
+       private static File file = null;
        private static long editPosition;
        private static boolean makeGUI = true, initSound = true, edited = false, drawEmptyTracks = false;
        public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
+       public static final int WHOLE_NOTE = 0, HALF_NOTE = 1, QUARTER_NOTE = 2, EIGHTH_NOTE = 3, SIXTEENTH_NOTE = 4;
 
        /** 
         * Starts the application.
@@ -39,43 +39,51 @@ public class Moosique {
         * loads a sequence and creates the GUI.
         */
        public static void main (String[] args) {
-               System.out.println("\nMoosique version 1.0\n");
+               out("\nMoosique version 1.0\n");
 
                // Parses command-line arguments.
                String fileArg = null;
                for (int i = 0; i < args.length; i++) {
                        if (args[i].equals("-n")) makeGUI = false;
-                       else if (args[i].equals("-m")) initSound = false;
                        else if (fileArg == null) fileArg = args[i];
                }
 
                // Acquires MIDI devices and connects them.
                System.out.print("Initializing MIDI devices.");
                try {
+                       // Configures sequencer
                        sequencer = MidiSystem.getSequencer();
                        System.out.print(".");
                        sequencer.open();
+                       sequencer.addMetaEventListener(new SongEndListener());
+
+                       // Configures synthesizer
                        synthesizer = MidiSystem.getSynthesizer();
                        System.out.print(".");
                        synthesizer.open();
+
+                       // Configures receiver, transmitter and channels.
                        receiver = synthesizer.getReceiver();
                        sequencer.getTransmitter().setReceiver(receiver);
                        channels = synthesizer.getChannels();
                        setActiveChannel(0);
                } catch (MidiUnavailableException e) {
-                       System.out.println("Failed, quitting.");
+                       out("Failed, quitting.");
                        System.exit(1);
                }
-               System.out.println("Done");
+               out("Done");
+
+               // Loads user preferences (work directory, last opened files etc).
+               loadPreferences();
 
                //If a filename is given as the command-line argument, attempts to load a sequence from the file.
                if (fileArg != null) {
                        System.out.print("Loading MIDI sequence from " + fileArg + "...");
-                       if (!load(fileArg)) {
-                               System.out.println("Failed, creating new sequence");
+                       if (!load(new File(fileArg))) {
+                               out("Failed, creating new sequence");
                                clearSequence();
                        } else {
-                               System.out.println("Done");
+                               out("Done");
                        }
                } else {
                        // Otherwise creates a new empty one.
@@ -88,13 +96,13 @@ public class Moosique {
                        try {
                                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                        } catch (Exception e) {}
-                       gui = new MooGUI(seq);
-                       System.out.println("Done");
+                       gui = new MooGUI(seq, file);
+                       out("Done");
                } else {
                        System.out.print("Playing...");
                        play();
                        while (sequencer.isRunning()) {}
-                       System.out.println("Done");
+                       out("Done");
                        quit();
                }
        }
@@ -133,14 +141,6 @@ public class Moosique {
                return channels[i];
        }
 
-       /** 
-        * Returns the MidiChannels of the selected synthesizer.
-        * @return the available MidiChannels
-        */
-       public static MidiChannel[] getChannels() {
-               return channels;
-       }
-
        /** 
         * Returns the current copy buffer.
         * @return the current copy buffer
@@ -169,7 +169,7 @@ public class Moosique {
         * Calculates the position (measures, beats, ticks) in the current sequence for the given tick position.
         * @return an array of integers where index 0 is measures, 1 is beats and 2 is ticks.
         */
-       public static int[] getPositionForTick(long ticks) {
+       public static int[] getPositionForTicks(long ticks) {
                /*
                int measures, beats, ticks;
                for (int i = 0; i < timeSignatures.length; i++) {
@@ -206,12 +206,21 @@ public class Moosique {
        }
 
        /** 
-        * Returns the tempo of the current sequence.
-        * @return the tick position
+        * Returns the tempo in the given tick position.
+        * @param tick the tick position for which to return the tempo
+        * @return the tempo at the specified tick position
         */
-       public static int getTempo() {
-               return 120;
-               // if (tempoMsg == null) return 0;
+       public static int getTempo(long tick) {
+               if (tempoChanges.size() == 0) return 120;
+               MidiEvent tempoEvent = (MidiEvent)tempoChanges.get(0);
+               if (tempoChanges.size() > 1) {
+                       for (int i = 1; i < tempoChanges.size(); i++) {
+                               MidiEvent nextTempoEvent = (MidiEvent)tempoChanges.get(i);
+                               if (nextTempoEvent.getTick() < tick && nextTempoEvent.getTick() > tempoEvent.getTick())
+                                       tempoEvent = nextTempoEvent;
+                       }
+               }
+               return decodeTempo(((MetaMessage)tempoEvent.getMessage()).getData());
        }
 
        /** 
@@ -230,13 +239,22 @@ public class Moosique {
        }
 
        /** 
-        * Returns the tempo of the current sequence.
-        * @return the tick position
+        * Returns the time signature in the given tick position.
+        * @param tick the tick position for which to return the time signature
+        * @return an array of two integers where [0] is the numerator and [1] the denominator
         */
-       public static int[] getTimeSig() {
+       public static int[] getTimeSig(long tick) {
                int[] ts = {4, 4};
-               return ts;
-               // if (timeSigMsg == null) return 0;
+               if (timeSignatures.size() == 0) return ts;
+               MidiEvent timeSigEvent = (MidiEvent)timeSignatures.get(0);
+               if (timeSignatures.size() > 1) {
+                       for (int i = 1; i < timeSignatures.size(); i++) {
+                               MidiEvent nextTimeSigEvent = (MidiEvent)timeSignatures.get(i);
+                               if (nextTimeSigEvent.getTick() < tick && nextTimeSigEvent.getTick() > timeSigEvent.getTick())
+                                       timeSigEvent = nextTimeSigEvent;
+                       }
+               }
+               return decodeTimeSig(((MetaMessage)timeSigEvent.getMessage()).getData());
        }
 
        /** 
@@ -345,14 +363,101 @@ public class Moosique {
                // timeSigMsg
        }
        
+       /** 
+        * Sets the solo setting of the given track.
+        * @param on    true for solo, false for not
+        */
        public static void setTrackSolo(Track track, boolean on){
                trackSolo.put(track, new Boolean(on));  
        }
 
+       /** 
+        * Sets the mute setting of the given track.
+        * @param on    true for mute, false for not
+        */
        public static void setTrackMute(Track track, boolean on){
                trackMute.put(track, new Boolean(on));  
        }
 
+       /** 
+        * Sets the current playback volume.
+        * @param volume        the volume, between 0 and 1
+        */
+       public void setVolume(long volume) {
+               for (int i = 0; i < channels.length; i++) {
+                       channels[i].controlChange(7, (int)(volume * 127.0));
+               }
+       }
+
+
+
+
+
+
+
+
+       /*                              ***
+        **  ENCODING / DECODING METHODS **
+        ***                              */
+
+
+
+
+
+
+
+
+       /** 
+        * Returns the byte array for the given tempo.
+        * @param tempo the tempo in beats per minute
+        * @return an array of bytes representing the given tempo
+        */
+       public static byte[] encodeTempo(int tempo) {
+               int microSecsPerQuarter = 60000000 / tempo;
+               byte[] b = new byte[3];
+               b[0] = (byte)(microSecsPerQuarter / 65536);
+               b[1] = (byte)((microSecsPerQuarter - (b[0] * 65536)) / 256);
+               b[2] = (byte)(microSecsPerQuarter - (b[0] * 65536) - (b[1] * 256));
+               return b;
+       }
+
+       /** 
+        * Returns the tempo for the given byte array.
+        * @param an array of three bytes representing the tempo
+        * @return the tempo in beats per minute
+        */
+       public static int decodeTempo(byte[] bytes) {
+               return 60000000 / (bytes[0] * 65536 + bytes[1] * 256 + bytes[2]); // bytes[0] & 0xFF ???
+       }
+
+       /** 
+        * Returns the byte array for the given time signature.
+        * @param numerator     the numerator of the time signature
+        * @param denominator   the denominator of the time signature
+        * @return an array of bytes representing the given time signature
+        */
+       public static byte[] encodeTimeSig(int numerator, int denominator) {
+               byte[] b = {
+                       (byte)numerator,
+                       (byte)(Math.log(denominator) / Math.log(2)),
+                       (byte)96,
+                       (byte)8
+               };
+               return b;
+       }
+       /** 
+        * Returns the time signature for the given byte array.
+        * @param an array of four bytes representing the time signature
+        * @return an array of two integers where [0] is the numerator and [1] the denominator
+        */
+       public static int[] decodeTimeSig(byte[] bytes) {
+               int[] t = {
+                       (int)bytes[0],
+                       (int)(1 << bytes[1])
+               };
+               return t;
+       }
+
 
 
 
@@ -404,29 +509,11 @@ public class Moosique {
                        }
                }
 
-
                // Disables input to volatile components
                // gui.disable();
 
                // Creates the visualisation thread and starts it.
-               player = new Thread () {
-                       public void run() {
-                               while(sequencer.isRunning()) {
-                                       // Updates the GUI with the current tick position.
-                                       gui.update(sequencer.getTickPosition());
-
-                                       // Puts the thread to sleep for as long as it takes
-                                       // the sequencer to reach the next sixteenth.
-                                       try {
-                                               //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
-                                               sleep (10);
-                                       } catch (InterruptedException e) {
-                                               Moosique.stop();
-                                       }
-                               }
-                               Moosique.stop();
-                       }
-               };
+               player = new PlayThread();
                player.start();
        }
 
@@ -474,27 +561,70 @@ public class Moosique {
         * Replaces the current sequence with a new one, holding three empty tracks.
         */
        public static void clearSequence() {
-               // Creates a new sequence and sends it to the sequencer.
                try {
+                       // Creates a new sequence.
                        seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
-                       sequencer.setSequence(seq);
-                       filename = null;
+                       Track[] tracks = seq.getTracks();
+
+                       // Creates messages for default tempo (120) and time signature (4/4).
+                       MetaMessage timeSigMsg = new MetaMessage();
+                       MetaMessage tempoMsg = new MetaMessage();
+                       try {
+                               timeSigMsg.setMessage(88, encodeTimeSig(4, 4), 4);
+                               tempoMsg.setMessage(81, encodeTempo(120), 3);
+                       } catch (InvalidMidiDataException e) {}
+
+                       // Adds them to track 0.
+                       tracks[0].add(new MidiEvent(timeSigMsg, (long)0));
+                       tracks[0].add(new MidiEvent(tempoMsg, (long)0));
+
+                       // Sets program and title for the tracks.
+                       initializeTrack(tracks[1], 0, 24, "Guitar");
+                       initializeTrack(tracks[2], 1, 33, "Bass");
+                       initializeTrack(tracks[3], 9, 0, "Drums");
+
+                       file = null;
                        emptyTracks = new ArrayList();
+                       timeSignatures = new ArrayList();
+                       tempoChanges = new ArrayList();
                        trackSolo = new HashMap();
                        trackMute = new HashMap();
                        copyBuffer = new ArrayList();
                } catch (InvalidMidiDataException e) {}
-               // Sends sequence to GUI.
+               // Sends the sequence to the GUI.
                if (gui != null) gui.setSequence(seq);
        }
+
+       /** 
+        * Creates event in the given track for program change and title.
+        */
+       private static void initializeTrack(Track track, int channel, int program, String title) {
+                       // Creates program change and title message.
+                       ShortMessage programMsg = new ShortMessage();
+                       MetaMessage titleMsg = new MetaMessage();
+
+                       // Sets the data of the messages.
+                       try {
+                               programMsg.setMessage(ShortMessage.PROGRAM_CHANGE, channel, program, 0);
+                               titleMsg.setMessage(3, title.getBytes(), title.length());
+                       } catch (InvalidMidiDataException e) {}
+
+                       // Adds them to the track.
+                       track.add(new MidiEvent(programMsg, (long)0));
+                       track.add(new MidiEvent(titleMsg, (long)0));
+       }
        
        /** 
         * Wraps each NoteOn event in the track with its NoteOff event in a MooNote.
+        * @param track         the track to convert
+        * @param quantize      whether to round locations and durations in the track to nearest 16th
+        * @return a list of the created MooNotes
         */
-       public static void convertTrack(Track track) {
+       public static List convertTrack(Track track, boolean quantize) {
                // Searches the track for NoteOn and NoteOff events
                ArrayList noteOns = new ArrayList(track.size() / 2);
                ArrayList noteOffs = new ArrayList(track.size() / 2);
+               ArrayList newMooNotes = new ArrayList();
                MidiEvent event;
                for (int j = 0; j < track.size(); j++) {
                        event = track.get(j);
@@ -518,48 +648,52 @@ public class Moosique {
                ShortMessage onMsg, nextOffMsg;
                while(iOn.hasNext()) {
                        on = (MidiEvent)iOn.next();
-                       onMsg = (ShortMessage)on.getMessage();
-                       iOff = noteOffs.iterator();
-                       while(iOff.hasNext()) {
-                               nextOff = (MidiEvent)iOff.next();
-                               nextOffMsg = (ShortMessage)nextOff.getMessage();
-                               if(onMsg.getChannel() == nextOffMsg.getChannel() &&
-                                  onMsg.getData1() == nextOffMsg.getData1() &&
-                                  c.compare(nextOff, on) > 0) {
-                                       off = nextOff;
-                                       iOff.remove();
-                                       break;
+                       if (!(on instanceof MooNote)) {
+                               onMsg = (ShortMessage)on.getMessage();
+                               iOff = noteOffs.iterator();
+                               while(iOff.hasNext()) {
+                                       nextOff = (MidiEvent)iOff.next();
+                                       nextOffMsg = (ShortMessage)nextOff.getMessage();
+                                       if(onMsg.getChannel() == nextOffMsg.getChannel() &&
+                                          onMsg.getData1() == nextOffMsg.getData1() &&
+                                          c.compare(nextOff, on) > 0) {
+                                               off = nextOff;
+                                               iOff.remove();
+                                               break;
+                                       }
+                                               
                                }
-                                       
-                       }
-                       track.remove(on);
-                       if (off != null) {
-                               track.add(new MooNote(on, off));
-                       } else {
-                               track.add(new MooNote(on, new MidiEvent((ShortMessage)on.getMessage().clone(), on.getTick() + 48)));
+                               track.remove(on);
+                               MooNote mn;
+                               if (off != null) {
+                                       mn = new MooNote(on, off);
+                               } else {
+                                       mn = new MooNote(on, new MidiEvent((ShortMessage)on.getMessage().clone(), on.getTick() + 48));
+                               }
+                               track.add(mn);
+                               newMooNotes.add(mn);
+                               iOn.remove();
                        }
-                       iOn.remove();
                }
+               if (quantize) quantize(newMooNotes, SIXTEENTH_NOTE, true, true);
+               return newMooNotes;
        }
 
        /** 
         * Loads a MIDI sequence from the given file.
         * @param filename      the filename to use
         */
-       public static boolean load(String file) {
+       public static boolean load(File loadFile) {
                // Loads sequence from file
-               filename = file;
-               try {
-                       seq = MidiSystem.getSequence(new File(filename));
-               } catch (InvalidMidiDataException e) {
-                       return false;
-               } catch (IOException e) {
-                       return false;
-               }
+               try {seq = MidiSystem.getSequence(loadFile);}
+               catch (Exception e) {return false;}
+               file = loadFile;
                edited = false;
 
                Track[] tracks = seq.getTracks();
                emptyTracks = new ArrayList();
+               timeSignatures = new ArrayList();
+               tempoChanges = new ArrayList();
                trackMute = new HashMap();
                trackSolo = new HashMap();
                copyBuffer = new ArrayList();
@@ -573,17 +707,15 @@ public class Moosique {
                        if (event.getMessage().getStatus() == MetaMessage.META) {
                                metaMsg = (MetaMessage)event.getMessage();
                                switch(metaMsg.getType()) {
-                                       case 81: tc.add(event); break;
-                                       case 88: ts.add(event);
+                                       case 81: tempoChanges.add(event); break;
+                                       case 88: timeSignatures.add(event);
                                }
                        }
                }
-               // timeSignatures = ts.toArray(timeSignatures);
-               // tempoChanges = tc.toArray(tempoChanges);
 
                // Converts tracks.
                for (int i = 0; i < tracks.length; i++) {
-                       convertTrack(tracks[i]);
+                       convertTrack(tracks[i], false);
                }
 
                // Sends sequence to GUI and sequencer, then returns
@@ -594,6 +726,31 @@ public class Moosique {
                return true;
        }
 
+       /** 
+        * Quantizes the given list of MIDI events
+        * @param notes         a list of the notes to quantize
+        * @param resolution    the note size to round each note to
+        * @param location      whether the quantize should affect the location of the note
+        * @param duration      whether the quantize should affect the duration of the note
+        */
+       public static void quantize(List notes, int resolution, boolean location, boolean duration) {
+               // Math.round(mn.getTick() / ticksPerSixteenth);
+       }
+
+       /** 
+        * Loads the user preferences.
+        */
+       public static void loadPreferences() {
+               
+       }
+
+       /** 
+        * Saves the user preferences.
+        */
+       public static void savePreferences() {
+               
+       }
+
        /** 
         * Prompts the user .
         */
@@ -612,9 +769,9 @@ public class Moosique {
         * Saves the current sequence to the previously given filename.
         */
        public static boolean save() {
-               if (filename == null) return false;
+               if (file == null) return false;
                else {
-                       saveAs(filename);
+                       saveAs(file);
                        return true;
                }
        }
@@ -623,19 +780,26 @@ public class Moosique {
         * Saves the current sequence to the given filename
         * @param file  the filename to use
         */
-       public static boolean saveAs(String file) {
+       public static boolean saveAs(File saveFile) {
                try {
-                       MidiSystem.write(seq, 1, new File(file));
-                       filename = file;
+                       MidiSystem.write(seq, 1, saveFile);
+                       file = saveFile;
                        edited = false;
-                       gui.setStatus("Saved " + file);
+                       gui.setStatus("Saved " + file.getAbsolutePath());
                        return true;
                } catch (IOException e) {
-                       gui.setStatus("Failed in saving " + file);
+                       gui.setStatus("Failed in saving " + file.getAbsolutePath());
                        return false;
                }
        }
 
+       /** 
+        * Prints the given string to the System output.
+        */
+       private static void out(String text) {
+               System.out.println(text);
+       }
+
        /** 
         * Releases all reserved devices and exits the program.
         */
@@ -643,17 +807,50 @@ public class Moosique {
                if (gui != null) {
                        if (promptOnUnsavedChanges()) return;
                }
+               savePreferences();
                if (sequencer.isOpen()) sequencer.close();
                if (synthesizer.isOpen()) synthesizer.close();
                System.exit(0);
        }
        
        /** 
-        * A Comparator for sorting lists of MidiEvents.
+        * A Ccmparator for sorting lists of MidiEvents.
         */
        public static class MidiEventComparator implements Comparator {
                public int compare(Object o1, Object o2) {
-                       return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
+                       int diff = (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
+                       if (diff != 0 || !(((MidiEvent)o1).getMessage() instanceof ShortMessage) || !(((MidiEvent)o2).getMessage() instanceof ShortMessage)) return diff;
+                       return (((ShortMessage)((MidiEvent)o1).getMessage()).getData1() - ((ShortMessage)((MidiEvent)o2).getMessage()).getData1());
+               }
+       }
+
+       /** 
+        * The thread that updates the GUI during playback.
+        */
+       public static class PlayThread extends Thread {
+               public void run() {
+                       // Updates the GUI with the current tick position.
+                       gui.update(sequencer.getTickPosition());
+
+                       // Puts the thread to sleep for as long as it takes
+                       // the sequencer to reach the next sixteenth.
+                       try {
+                               //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
+                               sleep (10);
+                       } catch (InterruptedException e) {
+                               Moosique.stop();
+                       }
+               }
+       }
+
+       /** 
+        * A listener for detecting the end of the sequence.
+        */
+       public static class SongEndListener implements MetaEventListener {
+               public void meta(MetaMessage event) {
+                       if (event.getType() == 47)
+                               // End of sequence
+                               stop();
                }
        }
 }