1 /* 2 * Copyright (C) 2008 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package android.media; 18 19 20 import android.compat.annotation.UnsupportedAppUsage; 21 import android.content.res.AssetFileDescriptor; 22 import android.os.Handler; 23 import android.os.Looper; 24 import android.os.Message; 25 import android.util.AndroidRuntimeException; 26 import android.util.Log; 27 28 import java.io.FileDescriptor; 29 import java.lang.ref.WeakReference; 30 31 /** 32 * JetPlayer provides access to JET content playback and control. 33 * 34 * <p>Please refer to the JET Creator User Manual for a presentation of the JET interactive 35 * music concept and how to use the JetCreator tool to create content to be player by JetPlayer. 36 * 37 * <p>Use of the JetPlayer class is based around the playback of a number of JET segments 38 * sequentially added to a playback FIFO queue. The rendering of the MIDI content stored in each 39 * segment can be dynamically affected by two mechanisms: 40 * <ul> 41 * <li>tracks in a segment can be muted or unmuted at any moment, individually or through 42 * a mask (to change the mute state of multiple tracks at once)</li> 43 * <li>parts of tracks in a segment can be played at predefined points in the segment, in order 44 * to maintain synchronization with the other tracks in the segment. This is achieved through 45 * the notion of "clips", which can be triggered at any time, but that will play only at the 46 * right time, as authored in the corresponding JET file.</li> 47 * </ul> 48 * As a result of the rendering and playback of the JET segments, the user of the JetPlayer instance 49 * can receive notifications from the JET engine relative to: 50 * <ul> 51 * <li>the playback state,</li> 52 * <li>the number of segments left to play in the queue,</li> 53 * <li>application controller events (CC80-83) to mark points in the MIDI segments.</li> 54 * </ul> 55 * Use {@link #getJetPlayer()} to construct a JetPlayer instance. JetPlayer is a singleton class. 56 * </p> 57 * 58 * <div class="special reference"> 59 * <h3>Developer Guides</h3> 60 * <p>For more information about how to use JetPlayer, read the 61 * <a href="{@docRoot}guide/topics/media/jetplayer.html">JetPlayer</a> developer guide.</p></div> 62 */ 63 public class JetPlayer 64 { 65 //-------------------------------------------- 66 // Constants 67 //------------------------ 68 /** 69 * The maximum number of simultaneous tracks. Use {@link #getMaxTracks()} to 70 * access this value. 71 */ 72 private static int MAXTRACKS = 32; 73 74 // to keep in sync with the JetPlayer class constants 75 // defined in frameworks/base/include/media/JetPlayer.h 76 private static final int JET_EVENT = 1; 77 private static final int JET_USERID_UPDATE = 2; 78 private static final int JET_NUMQUEUEDSEGMENT_UPDATE = 3; 79 private static final int JET_PAUSE_UPDATE = 4; 80 81 // to keep in sync with external/sonivox/arm-wt-22k/lib_src/jet_data.h 82 // Encoding of event information on 32 bits 83 private static final int JET_EVENT_VAL_MASK = 0x0000007f; // mask for value 84 private static final int JET_EVENT_CTRL_MASK = 0x00003f80; // mask for controller 85 private static final int JET_EVENT_CHAN_MASK = 0x0003c000; // mask for channel 86 private static final int JET_EVENT_TRACK_MASK = 0x00fc0000; // mask for track number 87 private static final int JET_EVENT_SEG_MASK = 0xff000000; // mask for segment ID 88 private static final int JET_EVENT_CTRL_SHIFT = 7; // shift to get controller number to bit 0 89 private static final int JET_EVENT_CHAN_SHIFT = 14; // shift to get MIDI channel to bit 0 90 private static final int JET_EVENT_TRACK_SHIFT = 18; // shift to get track ID to bit 0 91 private static final int JET_EVENT_SEG_SHIFT = 24; // shift to get segment ID to bit 0 92 93 // to keep in sync with values used in external/sonivox/arm-wt-22k/Android.mk 94 // Jet rendering audio parameters 95 private static final int JET_OUTPUT_RATE = 22050; // _SAMPLE_RATE_22050 in Android.mk 96 private static final int JET_OUTPUT_CHANNEL_CONFIG = 97 AudioFormat.CHANNEL_OUT_STEREO; // NUM_OUTPUT_CHANNELS=2 in Android.mk 98 99 100 //-------------------------------------------- 101 // Member variables 102 //------------------------ 103 /** 104 * Handler for jet events and status updates coming from the native code 105 */ 106 private NativeEventHandler mEventHandler = null; 107 108 /** 109 * Looper associated with the thread that creates the AudioTrack instance 110 */ 111 private Looper mInitializationLooper = null; 112 113 /** 114 * Lock to protect the event listener updates against event notifications 115 */ 116 private final Object mEventListenerLock = new Object(); 117 118 private OnJetEventListener mJetEventListener = null; 119 120 private static JetPlayer singletonRef; 121 122 static { 123 System.loadLibrary("media_jni"); 124 } 125 126 //-------------------------------- 127 // Used exclusively by native code 128 //-------------------- 129 /** 130 * Accessed by native methods: provides access to C++ JetPlayer object 131 */ 132 @SuppressWarnings("unused") 133 @UnsupportedAppUsage 134 private long mNativePlayerInJavaObj; 135 136 137 //-------------------------------------------- 138 // Constructor, finalize 139 //------------------------ 140 /** 141 * Factory method for the JetPlayer class. 142 * @return the singleton JetPlayer instance 143 */ getJetPlayer()144 public static JetPlayer getJetPlayer() { 145 if (singletonRef == null) { 146 singletonRef = new JetPlayer(); 147 } 148 return singletonRef; 149 } 150 151 /** 152 * Cloning a JetPlayer instance is not supported. Calling clone() will generate an exception. 153 */ clone()154 public Object clone() throws CloneNotSupportedException { 155 // JetPlayer is a singleton class, 156 // so you can't clone a JetPlayer instance 157 throw new CloneNotSupportedException(); 158 } 159 160 JetPlayer()161 private JetPlayer() { 162 163 // remember which looper is associated with the JetPlayer instanciation 164 if ((mInitializationLooper = Looper.myLooper()) == null) { 165 mInitializationLooper = Looper.getMainLooper(); 166 } 167 168 int buffSizeInBytes = AudioTrack.getMinBufferSize(JET_OUTPUT_RATE, 169 JET_OUTPUT_CHANNEL_CONFIG, AudioFormat.ENCODING_PCM_16BIT); 170 171 if ((buffSizeInBytes != AudioTrack.ERROR) 172 && (buffSizeInBytes != AudioTrack.ERROR_BAD_VALUE)) { 173 174 native_setup(new WeakReference<JetPlayer>(this), 175 JetPlayer.getMaxTracks(), 176 // bytes to frame conversion: 177 // 1200 == minimum buffer size in frames on generation 1 hardware 178 Math.max(1200, buffSizeInBytes / 179 (AudioFormat.getBytesPerSample(AudioFormat.ENCODING_PCM_16BIT) * 180 2 /*channels*/))); 181 } 182 } 183 184 finalize()185 protected void finalize() { 186 native_finalize(); 187 } 188 189 190 /** 191 * Stops the current JET playback, and releases all associated native resources. 192 * The object can no longer be used and the reference should be set to null 193 * after a call to release(). 194 */ release()195 public void release() { 196 native_release(); 197 singletonRef = null; 198 } 199 200 201 //-------------------------------------------- 202 // Getters 203 //------------------------ 204 /** 205 * Returns the maximum number of simultaneous MIDI tracks supported by JetPlayer 206 */ getMaxTracks()207 public static int getMaxTracks() { 208 return JetPlayer.MAXTRACKS; 209 } 210 211 212 //-------------------------------------------- 213 // Jet functionality 214 //------------------------ 215 /** 216 * Loads a .jet file from a given path. 217 * @param path the path to the .jet file, for instance "/sdcard/mygame/music.jet". 218 * @return true if loading the .jet file was successful, false if loading failed. 219 */ loadJetFile(String path)220 public boolean loadJetFile(String path) { 221 return native_loadJetFromFile(path); 222 } 223 224 225 /** 226 * Loads a .jet file from an asset file descriptor. 227 * @param afd the asset file descriptor. 228 * @return true if loading the .jet file was successful, false if loading failed. 229 */ loadJetFile(AssetFileDescriptor afd)230 public boolean loadJetFile(AssetFileDescriptor afd) { 231 long len = afd.getLength(); 232 if (len < 0) { 233 throw new AndroidRuntimeException("no length for fd"); 234 } 235 return native_loadJetFromFileD( 236 afd.getFileDescriptor(), afd.getStartOffset(), len); 237 } 238 239 /** 240 * Closes the resource containing the JET content. 241 * @return true if successfully closed, false otherwise. 242 */ closeJetFile()243 public boolean closeJetFile() { 244 return native_closeJetFile(); 245 } 246 247 248 /** 249 * Starts playing the JET segment queue. 250 * @return true if rendering and playback is successfully started, false otherwise. 251 */ play()252 public boolean play() { 253 return native_playJet(); 254 } 255 256 257 /** 258 * Pauses the playback of the JET segment queue. 259 * @return true if rendering and playback is successfully paused, false otherwise. 260 */ pause()261 public boolean pause() { 262 return native_pauseJet(); 263 } 264 265 266 /** 267 * Queues the specified segment in the JET queue. 268 * @param segmentNum the identifier of the segment. 269 * @param libNum the index of the sound bank associated with the segment. Use -1 to indicate 270 * that no sound bank (DLS file) is associated with this segment, in which case JET will use 271 * the General MIDI library. 272 * @param repeatCount the number of times the segment will be repeated. 0 means the segment will 273 * only play once. -1 means the segment will repeat indefinitely. 274 * @param transpose the amount of pitch transposition. Set to 0 for normal playback. 275 * Range is -12 to +12. 276 * @param muteFlags a bitmask to specify which MIDI tracks will be muted during playback. Bit 0 277 * affects track 0, bit 1 affects track 1 etc. 278 * @param userID a value specified by the application that uniquely identifies the segment. 279 * this value is received in the 280 * {@link OnJetEventListener#onJetUserIdUpdate(JetPlayer, int, int)} event listener method. 281 * Normally, the application will keep a byte value that is incremented each time a new 282 * segment is queued up. This can be used to look up any special characteristics of that 283 * track including trigger clips and mute flags. 284 * @return true if the segment was successfully queued, false if the queue is full or if the 285 * parameters are invalid. 286 */ queueJetSegment(int segmentNum, int libNum, int repeatCount, int transpose, int muteFlags, byte userID)287 public boolean queueJetSegment(int segmentNum, int libNum, int repeatCount, 288 int transpose, int muteFlags, byte userID) { 289 return native_queueJetSegment(segmentNum, libNum, repeatCount, 290 transpose, muteFlags, userID); 291 } 292 293 294 /** 295 * Queues the specified segment in the JET queue. 296 * @param segmentNum the identifier of the segment. 297 * @param libNum the index of the soundbank associated with the segment. Use -1 to indicate that 298 * no sound bank (DLS file) is associated with this segment, in which case JET will use 299 * the General MIDI library. 300 * @param repeatCount the number of times the segment will be repeated. 0 means the segment will 301 * only play once. -1 means the segment will repeat indefinitely. 302 * @param transpose the amount of pitch transposition. Set to 0 for normal playback. 303 * Range is -12 to +12. 304 * @param muteArray an array of booleans to specify which MIDI tracks will be muted during 305 * playback. The value at index 0 affects track 0, value at index 1 affects track 1 etc. 306 * The length of the array must be {@link #getMaxTracks()} for the call to succeed. 307 * @param userID a value specified by the application that uniquely identifies the segment. 308 * this value is received in the 309 * {@link OnJetEventListener#onJetUserIdUpdate(JetPlayer, int, int)} event listener method. 310 * Normally, the application will keep a byte value that is incremented each time a new 311 * segment is queued up. This can be used to look up any special characteristics of that 312 * track including trigger clips and mute flags. 313 * @return true if the segment was successfully queued, false if the queue is full or if the 314 * parameters are invalid. 315 */ queueJetSegmentMuteArray(int segmentNum, int libNum, int repeatCount, int transpose, boolean[] muteArray, byte userID)316 public boolean queueJetSegmentMuteArray(int segmentNum, int libNum, int repeatCount, 317 int transpose, boolean[] muteArray, byte userID) { 318 if (muteArray.length != JetPlayer.getMaxTracks()) { 319 return false; 320 } 321 return native_queueJetSegmentMuteArray(segmentNum, libNum, repeatCount, 322 transpose, muteArray, userID); 323 } 324 325 326 /** 327 * Modifies the mute flags. 328 * @param muteFlags a bitmask to specify which MIDI tracks are muted. Bit 0 affects track 0, 329 * bit 1 affects track 1 etc. 330 * @param sync if false, the new mute flags will be applied as soon as possible by the JET 331 * render and playback engine. If true, the mute flags will be updated at the start of the 332 * next segment. If the segment is repeated, the flags will take effect the next time 333 * segment is repeated. 334 * @return true if the mute flags were successfully updated, false otherwise. 335 */ setMuteFlags(int muteFlags, boolean sync)336 public boolean setMuteFlags(int muteFlags, boolean sync) { 337 return native_setMuteFlags(muteFlags, sync); 338 } 339 340 341 /** 342 * Modifies the mute flags for the current active segment. 343 * @param muteArray an array of booleans to specify which MIDI tracks are muted. The value at 344 * index 0 affects track 0, value at index 1 affects track 1 etc. 345 * The length of the array must be {@link #getMaxTracks()} for the call to succeed. 346 * @param sync if false, the new mute flags will be applied as soon as possible by the JET 347 * render and playback engine. If true, the mute flags will be updated at the start of the 348 * next segment. If the segment is repeated, the flags will take effect the next time 349 * segment is repeated. 350 * @return true if the mute flags were successfully updated, false otherwise. 351 */ setMuteArray(boolean[] muteArray, boolean sync)352 public boolean setMuteArray(boolean[] muteArray, boolean sync) { 353 if(muteArray.length != JetPlayer.getMaxTracks()) 354 return false; 355 return native_setMuteArray(muteArray, sync); 356 } 357 358 359 /** 360 * Mutes or unmutes a single track. 361 * @param trackId the index of the track to mute. 362 * @param muteFlag set to true to mute, false to unmute. 363 * @param sync if false, the new mute flags will be applied as soon as possible by the JET 364 * render and playback engine. If true, the mute flag will be updated at the start of the 365 * next segment. If the segment is repeated, the flag will take effect the next time 366 * segment is repeated. 367 * @return true if the mute flag was successfully updated, false otherwise. 368 */ setMuteFlag(int trackId, boolean muteFlag, boolean sync)369 public boolean setMuteFlag(int trackId, boolean muteFlag, boolean sync) { 370 return native_setMuteFlag(trackId, muteFlag, sync); 371 } 372 373 374 /** 375 * Schedules the playback of a clip. 376 * This will automatically update the mute flags in sync with the JET Clip Marker (controller 377 * 103). The parameter clipID must be in the range of 0-63. After the call to triggerClip, when 378 * JET next encounters a controller event 103 with bits 0-5 of the value equal to clipID and 379 * bit 6 set to 1, it will automatically unmute the track containing the controller event. 380 * When JET encounters the complementary controller event 103 with bits 0-5 of the value equal 381 * to clipID and bit 6 set to 0, it will mute the track again. 382 * @param clipId the identifier of the clip to trigger. 383 * @return true if the clip was successfully triggered, false otherwise. 384 */ triggerClip(int clipId)385 public boolean triggerClip(int clipId) { 386 return native_triggerClip(clipId); 387 } 388 389 390 /** 391 * Empties the segment queue, and clears all clips that are scheduled for playback. 392 * @return true if the queue was successfully cleared, false otherwise. 393 */ clearQueue()394 public boolean clearQueue() { 395 return native_clearQueue(); 396 } 397 398 399 //--------------------------------------------------------- 400 // Internal class to handle events posted from native code 401 //------------------------ 402 private class NativeEventHandler extends Handler 403 { 404 private JetPlayer mJet; 405 NativeEventHandler(JetPlayer jet, Looper looper)406 public NativeEventHandler(JetPlayer jet, Looper looper) { 407 super(looper); 408 mJet = jet; 409 } 410 411 @Override handleMessage(Message msg)412 public void handleMessage(Message msg) { 413 OnJetEventListener listener = null; 414 synchronized (mEventListenerLock) { 415 listener = mJet.mJetEventListener; 416 } 417 switch(msg.what) { 418 case JET_EVENT: 419 if (listener != null) { 420 // call the appropriate listener after decoding the event parameters 421 // encoded in msg.arg1 422 mJetEventListener.onJetEvent( 423 mJet, 424 (short)((msg.arg1 & JET_EVENT_SEG_MASK) >> JET_EVENT_SEG_SHIFT), 425 (byte) ((msg.arg1 & JET_EVENT_TRACK_MASK) >> JET_EVENT_TRACK_SHIFT), 426 // JETCreator channel numbers start at 1, but the index starts at 0 427 // in the .jet files 428 (byte)(((msg.arg1 & JET_EVENT_CHAN_MASK) >> JET_EVENT_CHAN_SHIFT) + 1), 429 (byte) ((msg.arg1 & JET_EVENT_CTRL_MASK) >> JET_EVENT_CTRL_SHIFT), 430 (byte) (msg.arg1 & JET_EVENT_VAL_MASK) ); 431 } 432 return; 433 case JET_USERID_UPDATE: 434 if (listener != null) { 435 listener.onJetUserIdUpdate(mJet, msg.arg1, msg.arg2); 436 } 437 return; 438 case JET_NUMQUEUEDSEGMENT_UPDATE: 439 if (listener != null) { 440 listener.onJetNumQueuedSegmentUpdate(mJet, msg.arg1); 441 } 442 return; 443 case JET_PAUSE_UPDATE: 444 if (listener != null) 445 listener.onJetPauseUpdate(mJet, msg.arg1); 446 return; 447 448 default: 449 loge("Unknown message type " + msg.what); 450 return; 451 } 452 } 453 } 454 455 456 //-------------------------------------------- 457 // Jet event listener 458 //------------------------ 459 /** 460 * Sets the listener JetPlayer notifies when a JET event is generated by the rendering and 461 * playback engine. 462 * Notifications will be received in the same thread as the one in which the JetPlayer 463 * instance was created. 464 * @param listener 465 */ setEventListener(OnJetEventListener listener)466 public void setEventListener(OnJetEventListener listener) { 467 setEventListener(listener, null); 468 } 469 470 /** 471 * Sets the listener JetPlayer notifies when a JET event is generated by the rendering and 472 * playback engine. 473 * Use this method to receive JET events in the Handler associated with another 474 * thread than the one in which you created the JetPlayer instance. 475 * @param listener 476 * @param handler the Handler that will receive the event notification messages. 477 */ setEventListener(OnJetEventListener listener, Handler handler)478 public void setEventListener(OnJetEventListener listener, Handler handler) { 479 synchronized(mEventListenerLock) { 480 481 mJetEventListener = listener; 482 483 if (listener != null) { 484 if (handler != null) { 485 mEventHandler = new NativeEventHandler(this, handler.getLooper()); 486 } else { 487 // no given handler, use the looper the AudioTrack was created in 488 mEventHandler = new NativeEventHandler(this, mInitializationLooper); 489 } 490 } else { 491 mEventHandler = null; 492 } 493 494 } 495 } 496 497 498 /** 499 * Handles the notification when the JET engine generates an event. 500 */ 501 public interface OnJetEventListener { 502 /** 503 * Callback for when the JET engine generates a new event. 504 * 505 * @param player the JET player the event is coming from 506 * @param segment 8 bit unsigned value 507 * @param track 6 bit unsigned value 508 * @param channel 4 bit unsigned value 509 * @param controller 7 bit unsigned value 510 * @param value 7 bit unsigned value 511 */ onJetEvent(JetPlayer player, short segment, byte track, byte channel, byte controller, byte value)512 void onJetEvent(JetPlayer player, 513 short segment, byte track, byte channel, byte controller, byte value); 514 /** 515 * Callback for when JET's currently playing segment's userID is updated. 516 * 517 * @param player the JET player the status update is coming from 518 * @param userId the ID of the currently playing segment 519 * @param repeatCount the repetition count for the segment (0 means it plays once) 520 */ onJetUserIdUpdate(JetPlayer player, int userId, int repeatCount)521 void onJetUserIdUpdate(JetPlayer player, int userId, int repeatCount); 522 523 /** 524 * Callback for when JET's number of queued segments is updated. 525 * 526 * @param player the JET player the status update is coming from 527 * @param nbSegments the number of segments in the JET queue 528 */ onJetNumQueuedSegmentUpdate(JetPlayer player, int nbSegments)529 void onJetNumQueuedSegmentUpdate(JetPlayer player, int nbSegments); 530 531 /** 532 * Callback for when JET pause state is updated. 533 * 534 * @param player the JET player the status update is coming from 535 * @param paused indicates whether JET is paused (1) or not (0) 536 */ onJetPauseUpdate(JetPlayer player, int paused)537 void onJetPauseUpdate(JetPlayer player, int paused); 538 } 539 540 541 //-------------------------------------------- 542 // Native methods 543 //------------------------ native_setup(Object Jet_this, int maxTracks, int trackBufferSize)544 private native final boolean native_setup(Object Jet_this, 545 int maxTracks, int trackBufferSize); native_finalize()546 private native final void native_finalize(); native_release()547 private native final void native_release(); native_loadJetFromFile(String pathToJetFile)548 private native final boolean native_loadJetFromFile(String pathToJetFile); native_loadJetFromFileD(FileDescriptor fd, long offset, long len)549 private native final boolean native_loadJetFromFileD(FileDescriptor fd, long offset, long len); native_closeJetFile()550 private native final boolean native_closeJetFile(); native_playJet()551 private native final boolean native_playJet(); native_pauseJet()552 private native final boolean native_pauseJet(); native_queueJetSegment(int segmentNum, int libNum, int repeatCount, int transpose, int muteFlags, byte userID)553 private native final boolean native_queueJetSegment(int segmentNum, int libNum, 554 int repeatCount, int transpose, int muteFlags, byte userID); native_queueJetSegmentMuteArray(int segmentNum, int libNum, int repeatCount, int transpose, boolean[] muteArray, byte userID)555 private native final boolean native_queueJetSegmentMuteArray(int segmentNum, int libNum, 556 int repeatCount, int transpose, boolean[] muteArray, byte userID); native_setMuteFlags(int muteFlags, boolean sync)557 private native final boolean native_setMuteFlags(int muteFlags, boolean sync); native_setMuteArray(boolean[]muteArray, boolean sync)558 private native final boolean native_setMuteArray(boolean[]muteArray, boolean sync); native_setMuteFlag(int trackId, boolean muteFlag, boolean sync)559 private native final boolean native_setMuteFlag(int trackId, boolean muteFlag, boolean sync); native_triggerClip(int clipId)560 private native final boolean native_triggerClip(int clipId); native_clearQueue()561 private native final boolean native_clearQueue(); 562 563 //--------------------------------------------------------- 564 // Called exclusively by native code 565 //-------------------- 566 @SuppressWarnings("unused") 567 @UnsupportedAppUsage postEventFromNative(Object jetplayer_ref, int what, int arg1, int arg2)568 private static void postEventFromNative(Object jetplayer_ref, 569 int what, int arg1, int arg2) { 570 //logd("Event posted from the native side: event="+ what + " args="+ arg1+" "+arg2); 571 JetPlayer jet = (JetPlayer)((WeakReference)jetplayer_ref).get(); 572 573 if ((jet != null) && (jet.mEventHandler != null)) { 574 Message m = 575 jet.mEventHandler.obtainMessage(what, arg1, arg2, null); 576 jet.mEventHandler.sendMessage(m); 577 } 578 579 } 580 581 582 //--------------------------------------------------------- 583 // Utils 584 //-------------------- 585 private final static String TAG = "JetPlayer-J"; 586 logd(String msg)587 private static void logd(String msg) { 588 Log.d(TAG, "[ android.media.JetPlayer ] " + msg); 589 } 590 loge(String msg)591 private static void loge(String msg) { 592 Log.e(TAG, "[ android.media.JetPlayer ] " + msg); 593 } 594 595 } 596