]> ruin.nu Git - moosique.git/blob - Moosique.java
FIXED THE LAST MAJOR BUG!!!
[moosique.git] / Moosique.java
1 import javax.sound.midi.*;
2 import java.io.*;
3 import javax.swing.*;
4 import java.util.*;
5
6 /**
7  * Moosique - The MIDI Tracker
8  * 
9  * Main class that handles initiation, IO and sound.
10  * 
11  * @author  Einar Pehrson
12  */
13  
14 public class Moosique {
15
16         private static MooGUI gui;
17         private static Sequence seq;
18         private static Sequencer sequencer;
19         private static Synthesizer synthesizer;
20         private static MidiChannel[] channels;
21         private static MidiChannel activeChannel;
22         private static MidiEvent[] timeSignatures, tempoChanges;
23         private static ArrayList emptyTracks;
24
25         private static String filename, fileArg;
26         private static long editPosition;
27         private static boolean makeGUI = true, isEdited = false, drawEmptyTracks = false;
28         private static Thread player;
29         public static final int DEFAULT_RESOLUTION = 96, DEFAULT_TRACKS = 4;
30
31         /** 
32          * Starts the application.
33          */
34         public static void main (String[] args) {
35                 System.out.println("\nMoosique version 1.0\n");
36
37                 // Parses command-line arguments.
38                 for (int i = 0; i < args.length; i++) {
39                         if (args[i].equals("-n")) {makeGUI = false;}
40                         else if (fileArg == null) {fileArg = args[i];}
41                 }
42
43                 // Acquires MIDI devices and connects them.
44                 System.out.print("Initializing MIDI devices.");
45                 try {
46                         sequencer = MidiSystem.getSequencer();
47                         System.out.print(".");
48                         sequencer.open();
49                         synthesizer = MidiSystem.getSynthesizer();
50                         System.out.print(".");
51                         synthesizer.open();
52                         sequencer.getTransmitter().setReceiver(synthesizer.getReceiver());
53                         channels = synthesizer.getChannels();
54                         setActiveChannel(0);
55                 } catch (MidiUnavailableException e) {
56                         System.out.println("Failed, quitting.");
57 //                      System.exit(1);
58                 }
59                 System.out.println("Done");
60
61                 //If a filename is given as the command-line argument, attempts to load a sequence from the file.
62                 if (fileArg != null) {
63                         System.out.print("Loading MIDI sequence from " + fileArg + "...");
64                         if (!load(fileArg)) {
65                                 System.out.println("Failed");
66                                 clearSequence();
67                         } else {
68                                 System.out.println("Done");
69                         }
70                 } else {
71                         // Otherwise creates a new empty one.
72                         clearSequence();
73                 }
74
75                 // Builds GUI, unless n-flag is set.
76                 if (makeGUI) {
77                         System.out.print("Building GUI.");
78                         try {
79                                 UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
80                         } catch (Exception e) {}
81                         gui = new MooGUI(seq);
82                         System.out.println("Done");
83                 } else {
84                         System.out.print("Playing...");
85                         play();
86                         while (sequencer.isRunning()) {}
87                         System.out.println("Done");
88                         quit();
89                 }
90         }
91
92         /** 
93          * Returns the GUI.
94          * @return the GUI
95          */
96         public static MooGUI getGUI() {
97                 return gui;
98         }
99
100         /** 
101          * Returns the current sequence.
102          * @return the current sequence
103          */
104         public static Sequence getSequence() {
105                 return seq;
106         }
107
108         /** 
109          * Returns the current sequencer.
110          * @return the current sequencer
111          */
112         public static Sequencer getSequencer() {
113                 return sequencer;
114         }
115
116         /** 
117          * Returns the MidiChannels of the selected synthesizer.
118          * @return the available MidiChannels
119          */
120         public static MidiChannel[] getChannels() {
121                 return channels;
122         }
123
124         /** 
125          * Returns the MidiChannels of the selected synthesizer.
126          * @return the available MidiChannels
127          */
128         public static MidiChannel getChannel(int i) {
129                 return channels[i];
130         }
131
132         /** 
133          * Returns the currently active MidiChannel.
134          * @return the active MidiChannel
135          */
136         public static MidiChannel getActiveChannel() {
137                 return activeChannel;
138         }
139
140         /** 
141          * Sets the currently active MidiChannel.
142          * @param channel       the number of the MidiChannel to activate
143          */
144         public static void setActiveChannel(int channel) {
145                 activeChannel = channels[channel];
146         }
147
148         /** 
149          * Replaces the current sequence with a new one, holding three empty tracks.
150          */
151         public static void clearSequence() {
152                 // Creates a new sequence and sends it to the sequencer.
153                 try {
154                         seq = new Sequence(Sequence.PPQ, DEFAULT_RESOLUTION, DEFAULT_TRACKS);
155                         sequencer.setSequence(seq);
156                         emptyTracks = new ArrayList();
157                 } catch (InvalidMidiDataException e) {}
158                 // Sends sequence to GUI.
159                 if (gui != null) gui.setSequence(seq);
160         }
161
162         /** 
163          * Starts playback of the current sequence.
164          */
165         public static void play() {
166                 sequencer.setTickPosition(editPosition);
167                 resume();
168         }
169
170         /** 
171          * Pauses playback of the current sequence.
172          */
173         public static void pause() {
174                 if (sequencer.isRunning()) {
175                         sequencer.stop();
176                 }
177                 if (player != null) player.interrupt();
178         }
179
180         /** 
181          * Resumes playback of the current sequence.
182          */
183         public static void resume() {
184                 gui.update(0);
185                 try {
186                         sequencer.setSequence(seq);
187                 } catch (InvalidMidiDataException e) {}
188                 sequencer.start();
189
190                 // Disables input to volatile components
191                 // gui.disable();
192
193                 // Creates the visualisation thread and starts it.
194                 player = new Thread () {
195                         public void run() {
196                                 long ticksPerSixteenth = seq.getResolution()/4;
197                                 System.out.println("Ticks/16: " + ticksPerSixteenth);
198                                 long position = sequencer.getTickPosition();
199                                 while(sequencer.isRunning()) {
200                                         long pos = sequencer.getTickPosition();
201                                         long tickDiff = pos - position;
202                                         System.out.print(" ... " + tickDiff);
203                                         position = pos;
204
205                                         // Updates the GUI with the current tick position.
206                                         gui.update(sequencer.getTickPosition());
207
208                                         // Puts the thread to sleep for as long as it takes
209                                         // the sequencer to reach the next sixteenth.
210                                         try {
211                                                 //sleep((long)((15000 / getTempo()) * (tickDiff / ticksPerSixteenth)));
212                                                 sleep (10);
213                                         } catch (InterruptedException e) {
214                                                 Moosique.stop();
215                                         }
216                                 }
217                                 Moosique.stop();
218                         }
219                 };
220                 player.start();
221         }
222
223         /** 
224          * Stops playback of the current sequence.
225          */
226         public static void stop() {
227                 if (sequencer.isRunning()) {
228                         sequencer.stop();
229                 }
230                 sequencer.setTickPosition(editPosition);
231                 if (player != null) player.interrupt();
232                 gui.update((long)0);
233         }
234
235         /** 
236          * Returns the current editing position of the sequencer.
237          * @return the tick position
238          */
239         public static long getEditPosition() {
240                 return editPosition;
241         }
242
243         /** 
244          * Sets the current editing position of the sequencer.
245          * @param ticks         the tick position
246          */
247         public static void setEditPosition(long ticks) {
248                 editPosition = ticks;
249         }
250
251         /** 
252          * Returns the tempo of the current sequence.
253          * @return the tick position
254          */
255         public static int getTempo() {
256                 return 120;
257                 // if (tempoMsg == null) return 0;
258         }
259
260         /** 
261          * Sets the current editing position of the sequencer.
262          * @param ticks         the tick position
263          */
264         public static void setTempo(int bpm) {
265                 // tempoMsg
266         }
267
268         /** 
269          * Returns the tempo of the current sequence.
270          * @return the tick position
271          */
272         public static int[] getTimeSig() {
273                 int[] ts = {4, 4};
274                 return ts;
275                 // if (timeSigMsg == null) return 0;
276         }
277
278         /** 
279          * Sets the current editing position of the sequencer.
280          * @param ticks         the tick position
281          */
282         public static void setTimeSig(int bpm) {
283                 // timeSigMsg
284         }
285
286         /** 
287          * Returns true if the current sequence has been edited.
288          * @return the tick position
289          */
290         public static boolean isEdited() {
291                 return isEdited;
292         }
293
294         /** 
295          * Sets the current sequence as edited, which implies prompts when loading a new sequence.
296          */
297         public static void setEdited() {
298                 isEdited = true;
299         }
300
301         /** 
302          * Rewinds the current sequence the given number of measures.
303          * @param measures      the number of measures to rewind
304          */
305         public static void rewind(long ticks) {
306                 editPosition -= ticks;
307         }
308
309         /** 
310          * Fast forwards the current sequence the given number of measures.
311          * @param measures      the number of measures to fast forward
312          */
313         public static void forward(long ticks) {
314                 editPosition += ticks;
315         }
316
317         /** 
318          * Returns whether the given track should be drawn
319          * @return true if the given track should be drawn
320          */
321         public static boolean shouldBeDrawn(Track track) {
322                 if (drawEmptyTracks) return true;
323                 else return (!emptyTracks.contains(track));
324         }
325
326
327         /** 
328          * Sets whether empty tracks should be drawn
329          * @param state         true if empty tracks should be drawn
330          */
331         public static void setDrawEmptyTracks(boolean state) {
332                 drawEmptyTracks = state;
333         }
334
335         /** 
336          * Loads the MooSequence in the given file.
337          * @param filename      the filename to use
338          */
339         public static boolean load(String file) {
340                 // Loads sequence from file
341                 filename = file;
342                 try {
343                         seq = MidiSystem.getSequence(new File(filename));
344                 } catch (InvalidMidiDataException e) {
345                         return false;
346                 } catch (IOException e) {
347                         return false;
348                 }
349                 isEdited = false;
350
351                 Track[] tracks = seq.getTracks();
352                 emptyTracks = new ArrayList();
353
354                 // Searches track 0 for changes in tempo and time signature.
355                 MidiEvent event;
356                 MetaMessage metaMsg;
357                 ArrayList ts = new ArrayList(), tc = new ArrayList();
358                 for (int i = 0; i < tracks[0].size(); i++) {
359                         event = tracks[0].get(i);
360                         if (event.getMessage().getStatus() == MetaMessage.META) {
361                                 metaMsg = (MetaMessage)event.getMessage();
362                                 switch(metaMsg.getType()) {
363                                         case 81: tc.add(event); break;
364                                         case 88: ts.add(event);
365                                 }
366                         }
367                 }
368 //              timeSignatures = ts.toArray(timeSignatures);
369 //              tempoChanges = tc.toArray(tempoChanges);
370
371                 // Wraps each NoteOn event with its NoteOff event in a MooNote
372                 ArrayList noteOns, noteOffs;
373                 for (int i = 0; i < tracks.length; i++) {
374                         // Searches the sequence for NoteOn and NoteOff events
375                         noteOns = new ArrayList(tracks[i].size() / 2);
376                         noteOffs = new ArrayList(tracks[i].size() / 2);
377                         for (int j = 0; j < tracks[i].size(); j++) {
378                                 event = tracks[i].get(j);
379                                 if (event.getMessage().getStatus() >= 144 &&
380                                     event.getMessage().getStatus() < 160) noteOns.add(event);
381                                 if (event.getMessage().getStatus() >= 128 &&
382                                     event.getMessage().getStatus() < 144) noteOffs.add(event);
383                         }
384                         noteOns.trimToSize();
385                         noteOffs.trimToSize();
386                         if (noteOns.size() == 0) emptyTracks.add(tracks[i]);
387                         
388                         // Sorts the note lists by tick position.
389                         Comparator c = new Comparator() {
390                                 public int compare(Object o1, Object o2) {
391                                         return (int)(((MidiEvent)o1).getTick() - ((MidiEvent)o2).getTick());
392                                 }
393                         };
394                         Collections.sort(noteOns, c);
395                         Collections.sort(noteOffs, c);
396
397                         // Replaces each NoteOn event it with a MooNote containing a reference to the NoteOff event.
398                         Iterator iOn = noteOns.iterator(), iOff;
399                         MidiEvent on, off = null, nextOff;
400                         ShortMessage onMsg, nextOffMsg;
401                         while(iOn.hasNext()) {
402                                 on = (MidiEvent)iOn.next();
403                                 onMsg = (ShortMessage)on.getMessage();
404                                 iOff = noteOffs.iterator();
405                                 while(iOff.hasNext()) {
406                                         nextOff = (MidiEvent)iOff.next();
407                                         nextOffMsg = (ShortMessage)nextOff.getMessage();
408                                         if(onMsg.getChannel() == nextOffMsg.getChannel() &&
409                                            onMsg.getData1() == nextOffMsg.getData1() &&
410                                            c.compare(nextOff, on) > 0) {
411                                                 off = nextOff;
412                                                 iOff.remove();
413                                                 break;
414                                         }
415                                                 
416                                 }
417                                 tracks[i].remove(on);
418                                 if (off != null) {
419                                         tracks[i].add(new MooNote(on, off));
420                                 } else {
421                                         tracks[i].add(new MooNote(on));
422                                 }
423                                 iOn.remove();
424                         }
425                 }
426                 // Sends sequence to GUI and sequencer, then returns
427                 if (gui != null) gui.setSequence(seq);
428                 try {
429                         sequencer.setSequence(seq);
430                 } catch (InvalidMidiDataException e) {}
431                 return true;
432         }
433
434         /** 
435          * Saves the current sequence to the given filename
436          * @param file  the filename to use
437          */
438         public static void saveAs(String file) {
439                 try {
440                         MidiSystem.write(seq, 1, new File(filename));
441                 } catch (IOException e) {}
442                 filename = file;
443                 gui.setStatus("Saved " + file);
444         }
445
446         /** 
447          * Saves the current sequence to the previously given filename.
448          */
449         public static void save() {
450                 saveAs(filename);
451         }
452
453         /** 
454          * Releases all reserved devices and exits the program.
455          */
456         public static void quit() {
457                 if (sequencer.isOpen()) sequencer.close();
458                 if (synthesizer.isOpen()) synthesizer.close();
459                 System.exit(0);
460         }
461 }