1 /* 2 * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package com.sun.media.sound; 27 28 import java.io.DataOutputStream; 29 import java.io.PipedInputStream; 30 import java.io.PipedOutputStream; 31 import java.io.ByteArrayOutputStream; 32 import java.io.ByteArrayInputStream; 33 import java.io.SequenceInputStream; 34 import java.io.File; 35 import java.io.FileOutputStream; 36 import java.io.InputStream; 37 import java.io.IOException; 38 import java.io.OutputStream; 39 40 import javax.sound.midi.InvalidMidiDataException; 41 import javax.sound.midi.MidiEvent; 42 import javax.sound.midi.MetaMessage; 43 import javax.sound.midi.Sequence; 44 import javax.sound.midi.ShortMessage; 45 import javax.sound.midi.SysexMessage; 46 import javax.sound.midi.Track; 47 import javax.sound.midi.spi.MidiFileWriter; 48 49 50 /** 51 * MIDI file writer. 52 * 53 * @author Kara Kytle 54 * @author Jan Borgersen 55 */ 56 public final class StandardMidiFileWriter extends MidiFileWriter { 57 58 private static final int MThd_MAGIC = 0x4d546864; // 'MThd' 59 private static final int MTrk_MAGIC = 0x4d54726b; // 'MTrk' 60 61 private static final int ONE_BYTE = 1; 62 private static final int TWO_BYTE = 2; 63 private static final int SYSEX = 3; 64 private static final int META = 4; 65 private static final int ERROR = 5; 66 private static final int IGNORE = 6; 67 68 private static final int MIDI_TYPE_0 = 0; 69 private static final int MIDI_TYPE_1 = 1; 70 71 private static final int bufferSize = 16384; // buffersize for write 72 private DataOutputStream tddos; // data output stream for track writing 73 74 75 76 /** 77 * MIDI parser types 78 */ 79 private static final int types[] = { 80 MIDI_TYPE_0, 81 MIDI_TYPE_1 82 }; 83 84 85 /** 86 * new 87 */ 88 public int[] getMidiFileTypes() { 89 int[] localArray = new int[types.length]; 90 System.arraycopy(types, 0, localArray, 0, types.length); 91 return localArray; 92 } 93 94 /** 95 * Obtains the file types that this provider can write from the 96 * sequence specified. 97 * @param sequence the sequence for which midi file type support 98 * is queried 99 * @return array of file types. If no file types are supported, 100 * returns an array of length 0. 101 */ 102 public int[] getMidiFileTypes(Sequence sequence){ 103 int typesArray[]; 104 Track tracks[] = sequence.getTracks(); 105 106 if( tracks.length==1 ) { 107 typesArray = new int[2]; 108 typesArray[0] = MIDI_TYPE_0; 109 typesArray[1] = MIDI_TYPE_1; 110 } else { 111 typesArray = new int[1]; 112 typesArray[0] = MIDI_TYPE_1; 113 } 114 115 return typesArray; 116 } 117 118 public boolean isFileTypeSupported(int type) { 119 for(int i=0; i<types.length; i++) { 120 if( type == types[i] ) { 121 return true; 122 } 123 } 124 return false; 125 } 126 127 public int write(Sequence in, int type, OutputStream out) throws IOException { 128 byte [] buffer = null; 129 130 int bytesRead = 0; 131 long bytesWritten = 0; 132 133 if( !isFileTypeSupported(type,in) ) { 134 throw new IllegalArgumentException("Could not write MIDI file"); 135 } 136 // First get the fileStream from this sequence 137 InputStream fileStream = getFileStream(type,in); 138 if (fileStream == null) { 139 throw new IllegalArgumentException("Could not write MIDI file"); 140 } 141 buffer = new byte[bufferSize]; 142 143 while( (bytesRead = fileStream.read( buffer )) >= 0 ) { 144 out.write( buffer, 0, bytesRead ); 145 bytesWritten += bytesRead; 146 } 147 // Done....return bytesWritten 148 return (int) bytesWritten; 149 } 150 151 public int write(Sequence in, int type, File out) throws IOException { 152 FileOutputStream fos = new FileOutputStream(out); // throws IOException 153 int bytesWritten = write( in, type, fos ); 154 fos.close(); 155 return bytesWritten; 156 } 157 158 //================================================================================= 159 160 161 private InputStream getFileStream(int type, Sequence sequence) throws IOException { 162 Track tracks[] = sequence.getTracks(); 163 int bytesBuilt = 0; 164 int headerLength = 14; 165 int length = 0; 166 int timeFormat; 167 float divtype; 168 169 PipedOutputStream hpos = null; 170 DataOutputStream hdos = null; 171 PipedInputStream headerStream = null; 172 173 InputStream trackStreams [] = null; 174 InputStream trackStream = null; 175 InputStream fStream = null; 176 177 // Determine the filetype to write 178 if( type==MIDI_TYPE_0 ) { 179 if (tracks.length != 1) { 180 return null; 181 } 182 } else if( type==MIDI_TYPE_1 ) { 183 if (tracks.length < 1) { // $$jb: 05.31.99: we _can_ write TYPE_1 if tracks.length==1 184 return null; 185 } 186 } else { 187 if(tracks.length==1) { 188 type = MIDI_TYPE_0; 189 } else if(tracks.length>1) { 190 type = MIDI_TYPE_1; 191 } else { 192 return null; 193 } 194 } 195 196 // Now build the file one track at a time 197 // Note that above we made sure that MIDI_TYPE_0 only happens 198 // if tracks.length==1 199 200 trackStreams = new InputStream[tracks.length]; 201 int trackCount = 0; 202 for(int i=0; i<tracks.length; i++) { 203 try { 204 trackStreams[trackCount] = writeTrack( tracks[i], type ); 205 trackCount++; 206 } catch (InvalidMidiDataException e) { 207 if(Printer.err) Printer.err("Exception in write: " + e.getMessage()); 208 } 209 //bytesBuilt += trackStreams[i].getLength(); 210 } 211 212 // Now seqence the track streams 213 if( trackCount == 1 ) { 214 trackStream = trackStreams[0]; 215 } else if( trackCount > 1 ){ 216 trackStream = trackStreams[0]; 217 for(int i=1; i<tracks.length; i++) { 218 // fix for 5048381: NullPointerException when saving a MIDI sequence 219 // don't include failed track streams 220 if (trackStreams[i] != null) { 221 trackStream = new SequenceInputStream( trackStream, trackStreams[i]); 222 } 223 } 224 } else { 225 throw new IllegalArgumentException("invalid MIDI data in sequence"); 226 } 227 228 // Now build the header... 229 hpos = new PipedOutputStream(); 230 hdos = new DataOutputStream(hpos); 231 headerStream = new PipedInputStream(hpos); 232 233 // Write the magic number 234 hdos.writeInt( MThd_MAGIC ); 235 236 // Write the header length 237 hdos.writeInt( headerLength - 8 ); 238 239 // Write the filetype 240 if(type==MIDI_TYPE_0) { 241 hdos.writeShort( 0 ); 242 } else { 243 // MIDI_TYPE_1 244 hdos.writeShort( 1 ); 245 } 246 247 // Write the number of tracks 248 hdos.writeShort( (short) trackCount ); 249 250 // Determine and write the timing format 251 divtype = sequence.getDivisionType(); 252 if( divtype == Sequence.PPQ ) { 253 timeFormat = sequence.getResolution(); 254 } else if( divtype == Sequence.SMPTE_24) { 255 timeFormat = (24<<8) * -1; 256 timeFormat += (sequence.getResolution() & 0xFF); 257 } else if( divtype == Sequence.SMPTE_25) { 258 timeFormat = (25<<8) * -1; 259 timeFormat += (sequence.getResolution() & 0xFF); 260 } else if( divtype == Sequence.SMPTE_30DROP) { 261 timeFormat = (29<<8) * -1; 262 timeFormat += (sequence.getResolution() & 0xFF); 263 } else if( divtype == Sequence.SMPTE_30) { 264 timeFormat = (30<<8) * -1; 265 timeFormat += (sequence.getResolution() & 0xFF); 266 } else { 267 // $$jb: 04.08.99: What to really do here? 268 return null; 269 } 270 hdos.writeShort( timeFormat ); 271 272 // now construct an InputStream to become the FileStream 273 fStream = new SequenceInputStream(headerStream, trackStream); 274 hdos.close(); 275 276 length = bytesBuilt + headerLength; 277 return fStream; 278 } 279 280 /** 281 * Returns ONE_BYTE, TWO_BYTE, SYSEX, META, 282 * ERROR, or IGNORE (i.e. invalid for a MIDI file) 283 */ 284 private int getType(int byteValue) { 285 if ((byteValue & 0xF0) == 0xF0) { 286 switch(byteValue) { 287 case 0xF0: 288 case 0xF7: 289 return SYSEX; 290 case 0xFF: 291 return META; 292 } 293 return IGNORE; 294 } 295 296 switch(byteValue & 0xF0) { 297 case 0x80: 298 case 0x90: 299 case 0xA0: 300 case 0xB0: 301 case 0xE0: 302 return TWO_BYTE; 303 case 0xC0: 304 case 0xD0: 305 return ONE_BYTE; 306 } 307 return ERROR; 308 } 309 310 private static final long mask = 0x7F; 311 312 private int writeVarInt(long value) throws IOException { 313 int len = 1; 314 int shift=63; // number of bitwise left-shifts of mask 315 // first screen out leading zeros 316 while ((shift > 0) && ((value & (mask << shift)) == 0)) shift-=7; 317 // then write actual values 318 while (shift > 0) { 319 tddos.writeByte((int) (((value & (mask << shift)) >> shift) | 0x80)); 320 shift-=7; 321 len++; 322 } 323 tddos.writeByte((int) (value & mask)); 324 return len; 325 } 326 327 private InputStream writeTrack( Track track, int type ) throws IOException, InvalidMidiDataException { 328 int bytesWritten = 0; 329 int lastBytesWritten = 0; 330 int size = track.size(); 331 PipedOutputStream thpos = new PipedOutputStream(); 332 DataOutputStream thdos = new DataOutputStream(thpos); 333 PipedInputStream thpis = new PipedInputStream(thpos); 334 335 ByteArrayOutputStream tdbos = new ByteArrayOutputStream(); 336 tddos = new DataOutputStream(tdbos); 337 ByteArrayInputStream tdbis = null; 338 339 SequenceInputStream fStream = null; 340 341 long currentTick = 0; 342 long deltaTick = 0; 343 long eventTick = 0; 344 int runningStatus = -1; 345 346 // ----------------------------- 347 // Write each event in the track 348 // ----------------------------- 349 for(int i=0; i<size; i++) { 350 MidiEvent event = track.get(i); 351 352 int status; 353 int eventtype; 354 int metatype; 355 int data1, data2; 356 int length; 357 byte data[] = null; 358 ShortMessage shortMessage = null; 359 MetaMessage metaMessage = null; 360 SysexMessage sysexMessage = null; 361 362 // get the tick 363 // $$jb: this gets easier if we change all system-wide time to delta ticks 364 eventTick = event.getTick(); 365 deltaTick = event.getTick() - currentTick; 366 currentTick = event.getTick(); 367 368 // get the status byte 369 status = event.getMessage().getStatus(); 370 eventtype = getType( status ); 371 372 switch( eventtype ) { 373 case ONE_BYTE: 374 shortMessage = (ShortMessage) event.getMessage(); 375 data1 = shortMessage.getData1(); 376 bytesWritten += writeVarInt( deltaTick ); 377 378 if(status!=runningStatus) { 379 runningStatus=status; 380 tddos.writeByte(status); bytesWritten += 1; 381 } 382 tddos.writeByte(data1); bytesWritten += 1; 383 break; 384 385 case TWO_BYTE: 386 shortMessage = (ShortMessage) event.getMessage(); 387 data1 = shortMessage.getData1(); 388 data2 = shortMessage.getData2(); 389 390 bytesWritten += writeVarInt( deltaTick ); 391 if(status!=runningStatus) { 392 runningStatus=status; 393 tddos.writeByte(status); bytesWritten += 1; 394 } 395 tddos.writeByte(data1); bytesWritten += 1; 396 tddos.writeByte(data2); bytesWritten += 1; 397 break; 398 399 case SYSEX: 400 sysexMessage = (SysexMessage) event.getMessage(); 401 length = sysexMessage.getLength(); 402 data = sysexMessage.getMessage(); 403 bytesWritten += writeVarInt( deltaTick ); 404 405 // $$jb: 04.08.99: always write status for sysex 406 runningStatus=status; 407 tddos.writeByte( data[0] ); bytesWritten += 1; 408 409 // $$jb: 10.18.99: we don't maintain length in 410 // the message data for SysEx (it is not transmitted 411 // over the line), so write the calculated length 412 // minus the status byte 413 bytesWritten += writeVarInt( (data.length-1) ); 414 415 // $$jb: 10.18.99: now write the rest of the 416 // message 417 tddos.write(data, 1, (data.length-1)); 418 bytesWritten += (data.length-1); 419 break; 420 421 case META: 422 metaMessage = (MetaMessage) event.getMessage(); 423 length = metaMessage.getLength(); 424 data = metaMessage.getMessage(); 425 bytesWritten += writeVarInt( deltaTick ); 426 427 // $$jb: 10.18.99: getMessage() returns the 428 // entire valid midi message for a file, 429 // including the status byte and the var-length-int 430 // length value, so we can just write the data 431 // here. note that we must _always_ write the 432 // status byte, regardless of runningStatus. 433 runningStatus=status; 434 tddos.write( data, 0, data.length ); 435 bytesWritten += data.length; 436 break; 437 438 case IGNORE: 439 // ignore this event 440 break; 441 442 case ERROR: 443 // ignore this event 444 break; 445 446 default: 447 throw new InvalidMidiDataException("internal file writer error"); 448 } 449 } 450 // --------------------------------- 451 // End write each event in the track 452 // --------------------------------- 453 454 // Build Track header now that we know length 455 thdos.writeInt(MTrk_MAGIC); 456 thdos.writeInt(bytesWritten); 457 bytesWritten += 8; 458 459 // Now sequence them 460 tdbis = new ByteArrayInputStream( tdbos.toByteArray() ); 461 fStream = new SequenceInputStream(thpis,tdbis); 462 thdos.close(); 463 tddos.close(); 464 465 return fStream; 466 } 467 }