idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,600
private TrackType findTrackType ( ) { TrackType result = TRACK_TYPE_MAP . get ( packetBytes [ 42 ] ) ; if ( result == null ) { return TrackType . UNKNOWN ; } return result ; }
Determine the enum value corresponding to the track type found in the packet .
48
16
150,601
private PlayState1 findPlayState1 ( ) { PlayState1 result = PLAY_STATE_1_MAP . get ( packetBytes [ 123 ] ) ; if ( result == null ) { return PlayState1 . UNKNOWN ; } return result ; }
Determine the enum value corresponding to the first play state found in the packet .
53
17
150,602
private PlayState3 findPlayState3 ( ) { PlayState3 result = PLAY_STATE_3_MAP . get ( packetBytes [ 157 ] ) ; if ( result == null ) { return PlayState3 . UNKNOWN ; } return result ; }
Determine the enum value corresponding to the third play state found in the packet .
53
17
150,603
@ SuppressWarnings ( "WeakerAccess" ) public boolean isPlaying ( ) { if ( packetBytes . length >= 212 ) { return ( packetBytes [ STATUS_FLAGS ] & PLAYING_FLAG ) > 0 ; } else { final PlayState1 state = getPlayState1 ( ) ; return state == PlayState1 . PLAYING || state == PlayState1 . LOOPING || ( state == PlayState1 . SEARCHING && getPlayState2 ( ) == PlayState2 . MOVING ) ; } }
Was the CDJ playing a track when this update was sent?
114
13
150,604
@ SuppressWarnings ( "WeakerAccess" ) public String formatCueCountdown ( ) { int count = getCueCountdown ( ) ; if ( count == 511 ) { return "--.-" ; } if ( ( count >= 1 ) && ( count <= 256 ) ) { int bars = ( count - 1 ) / 4 ; int beats = ( ( count - 1 ) % 4 ) + 1 ; return String . format ( "%02d.%d" , bars , beats ) ; } if ( count == 0 ) { return "00.0" ; } return "??.?" ; }
Format a cue countdown indicator in the same way as the CDJ would at this point in the track .
131
21
150,605
private void clearDeck ( TrackMetadataUpdate update ) { if ( hotCache . remove ( DeckReference . getDeckReference ( update . player , 0 ) ) != null ) { deliverBeatGridUpdate ( update . player , null ) ; } }
We have received an update that invalidates the beat grid for a player so clear it and alert any listeners if this represents a change . This does not affect the hot cues ; they will stick around until the player loads a new track that overwrites one or more of them .
53
55
150,606
private void clearBeatGrids ( DeviceAnnouncement announcement ) { final int player = announcement . getNumber ( ) ; // Iterate over a copy to avoid concurrent modification issues for ( DeckReference deck : new HashSet < DeckReference > ( hotCache . keySet ( ) ) ) { if ( deck . player == player ) { hotCache . remove ( deck ) ; if ( deck . hotCue == 0 ) { deliverBeatGridUpdate ( player , null ) ; // Inform listeners the beat grid is gone. } } } }
We have received notification that a device is no longer on the network so clear out all its beat grids .
111
21
150,607
private void updateBeatGrid ( TrackMetadataUpdate update , BeatGrid beatGrid ) { hotCache . put ( DeckReference . getDeckReference ( update . player , 0 ) , beatGrid ) ; // Main deck if ( update . metadata . getCueList ( ) != null ) { // Update the cache with any hot cues in this track as well for ( CueList . Entry entry : update . metadata . getCueList ( ) . entries ) { if ( entry . hotCueNumber != 0 ) { hotCache . put ( DeckReference . getDeckReference ( update . player , entry . hotCueNumber ) , beatGrid ) ; } } } deliverBeatGridUpdate ( update . player , beatGrid ) ; }
We have obtained a beat grid for a device so store it and alert any listeners .
154
17
150,608
@ SuppressWarnings ( "WeakerAccess" ) public Map < DeckReference , BeatGrid > getLoadedBeatGrids ( ) { ensureRunning ( ) ; // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < DeckReference , BeatGrid > ( hotCache ) ) ; }
Get the beat grids available for all tracks currently loaded in any player either on the play deck or in a hot cue .
77
24
150,609
public BeatGrid requestBeatGridFrom ( final DataReference track ) { for ( BeatGrid cached : hotCache . values ( ) ) { if ( cached . dataReference . equals ( track ) ) { // Found a hot cue hit, use it. return cached ; } } return requestBeatGridInternal ( track , false ) ; }
Ask the specified player for the beat grid of the track in the specified slot with the specified rekordbox ID first checking if we have a cache we can use instead .
68
35
150,610
BeatGrid getBeatGrid ( int rekordboxId , SlotReference slot , Client client ) throws IOException { Message response = client . simpleRequest ( Message . KnownType . BEAT_GRID_REQ , null , client . buildRMST ( Message . MenuIdentifier . DATA , slot . slot ) , new NumberField ( rekordboxId ) ) ; if ( response . knownType == Message . KnownType . BEAT_GRID ) { return new BeatGrid ( new DataReference ( slot , rekordboxId ) , response ) ; } logger . error ( "Unexpected response type when requesting beat grid: {}" , response ) ; return null ; }
Requests the beat grid for a specific track ID given a connection to a player that has already been set up .
144
23
150,611
private void deliverBeatGridUpdate ( int player , BeatGrid beatGrid ) { if ( ! getBeatGridListeners ( ) . isEmpty ( ) ) { final BeatGridUpdate update = new BeatGridUpdate ( player , beatGrid ) ; for ( final BeatGridListener listener : getBeatGridListeners ( ) ) { try { listener . beatGridChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering beat grid update to listener" , t ) ; } } } }
Send a beat grid update announcement to all registered listeners .
107
11
150,612
@ SuppressWarnings ( "WeakerAccess" ) public synchronized void stop ( ) { if ( isRunning ( ) ) { MetadataFinder . getInstance ( ) . removeTrackMetadataListener ( metadataListener ) ; running . set ( false ) ; pendingUpdates . clear ( ) ; queueHandler . interrupt ( ) ; queueHandler = null ; // Report the loss of our previews, on the proper thread, and outside our lock. final Set < DeckReference > dyingCache = new HashSet < DeckReference > ( hotCache . keySet ( ) ) ; SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( DeckReference deck : dyingCache ) { if ( deck . hotCue == 0 ) { deliverBeatGridUpdate ( deck . player , null ) ; } } } } ) ; hotCache . clear ( ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop finding beat grids for all active players .
203
9
150,613
private long interpolateTimeSinceUpdate ( TrackPositionUpdate update , long currentTimestamp ) { if ( ! update . playing ) { return update . milliseconds ; } long elapsedMillis = ( currentTimestamp - update . timestamp ) / 1000000 ; long moved = Math . round ( update . pitch * elapsedMillis ) ; if ( update . reverse ) { return update . milliseconds - moved ; } return update . milliseconds + moved ; }
Figure out based on how much time has elapsed since we received an update and the playback position speed and direction at the time of that update where the player will be now .
90
34
150,614
private long interpolateTimeFromUpdate ( TrackPositionUpdate lastTrackUpdate , CdjStatus newDeviceUpdate , BeatGrid beatGrid ) { final int beatNumber = newDeviceUpdate . getBeatNumber ( ) ; final boolean noLongerPlaying = ! newDeviceUpdate . isPlaying ( ) ; // If we have just stopped, see if we are near a cue (assuming that information is available), and if so, // the best assumption is that the DJ jumped to that cue. if ( lastTrackUpdate . playing && noLongerPlaying ) { final CueList . Entry jumpedTo = findAdjacentCue ( newDeviceUpdate , beatGrid ) ; if ( jumpedTo != null ) return jumpedTo . cueTime ; } // Handle the special case where we were not playing either in the previous or current update, but the DJ // might have jumped to a different place in the track. if ( ! lastTrackUpdate . playing ) { if ( lastTrackUpdate . beatNumber == beatNumber && noLongerPlaying ) { // Haven't moved return lastTrackUpdate . milliseconds ; } else { if ( noLongerPlaying ) { // Have jumped without playing. if ( beatNumber < 0 ) { return - 1 ; // We don't know the position any more; weird to get into this state and still have a grid? } // As a heuristic, assume we are right before the beat? return timeOfBeat ( beatGrid , beatNumber , newDeviceUpdate ) ; } } } // One way or another, we are now playing. long elapsedMillis = ( newDeviceUpdate . getTimestamp ( ) - lastTrackUpdate . timestamp ) / 1000000 ; long moved = Math . round ( lastTrackUpdate . pitch * elapsedMillis ) ; long interpolated = ( lastTrackUpdate . reverse ) ? ( lastTrackUpdate . milliseconds - moved ) : lastTrackUpdate . milliseconds + moved ; if ( Math . abs ( beatGrid . findBeatAtTime ( interpolated ) - beatNumber ) < 2 ) { return interpolated ; // Our calculations still look plausible } // The player has jumped or drifted somewhere unexpected, correct. if ( newDeviceUpdate . isPlayingForwards ( ) ) { return timeOfBeat ( beatGrid , beatNumber , newDeviceUpdate ) ; } else { return beatGrid . getTimeWithinTrack ( Math . min ( beatNumber + 1 , beatGrid . beatCount ) ) ; } }
Sanity - check a new non - beat update make sure we are still interpolating a sensible position and correct as needed .
501
25
150,615
public long getTimeFor ( int player ) { TrackPositionUpdate update = positions . get ( player ) ; if ( update != null ) { return interpolateTimeSinceUpdate ( update , System . nanoTime ( ) ) ; } return - 1 ; // We don't know. }
Get the best guess we have for the current track position on the specified player .
58
16
150,616
private boolean interpolationsDisagree ( TrackPositionUpdate lastUpdate , TrackPositionUpdate currentUpdate ) { long now = System . nanoTime ( ) ; return Math . abs ( interpolateTimeSinceUpdate ( lastUpdate , now ) - interpolateTimeSinceUpdate ( currentUpdate , now ) ) > slack . get ( ) ; }
Check whether we have diverged from what we would predict from the last update that was sent to a particular track position listener .
67
25
150,617
@ SuppressWarnings ( "WeakerAccess" ) public synchronized void stop ( ) { if ( isRunning ( ) ) { BeatFinder . getInstance ( ) . removeBeatListener ( beatListener ) ; VirtualCdj . getInstance ( ) . removeUpdateListener ( updateListener ) ; running . set ( false ) ; positions . clear ( ) ; updates . clear ( ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop interpolating playback position for all active players .
96
10
150,618
public static synchronized DeckReference getDeckReference ( int player , int hotCue ) { Map < Integer , DeckReference > playerMap = instances . get ( player ) ; if ( playerMap == null ) { playerMap = new HashMap < Integer , DeckReference > ( ) ; instances . put ( player , playerMap ) ; } DeckReference result = playerMap . get ( hotCue ) ; if ( result == null ) { result = new DeckReference ( player , hotCue ) ; playerMap . put ( hotCue , result ) ; } return result ; }
Get a unique reference to a place where a track is currently loaded in a player .
121
17
150,619
public synchronized void setDeviceName ( String name ) { if ( name . getBytes ( ) . length > DEVICE_NAME_LENGTH ) { throw new IllegalArgumentException ( "name cannot be more than " + DEVICE_NAME_LENGTH + " bytes long" ) ; } Arrays . fill ( announcementBytes , DEVICE_NAME_OFFSET , DEVICE_NAME_LENGTH , ( byte ) 0 ) ; System . arraycopy ( name . getBytes ( ) , 0 , announcementBytes , DEVICE_NAME_OFFSET , name . getBytes ( ) . length ) ; }
Set the name to be used in announcing our presence on the network . The name can be no longer than twenty bytes and should be normal ASCII no Unicode .
127
31
150,620
private void setTempoMaster ( DeviceUpdate newMaster ) { DeviceUpdate oldMaster = tempoMaster . getAndSet ( newMaster ) ; if ( ( newMaster == null && oldMaster != null ) || ( newMaster != null && ( ( oldMaster == null ) || ! newMaster . getAddress ( ) . equals ( oldMaster . getAddress ( ) ) ) ) ) { // This is a change in master, so report it to any registered listeners deliverMasterChangedAnnouncement ( newMaster ) ; } }
Establish a new tempo master and if it is a change from the existing one report it to the listeners .
108
22
150,621
private void setMasterTempo ( double newTempo ) { double oldTempo = Double . longBitsToDouble ( masterTempo . getAndSet ( Double . doubleToLongBits ( newTempo ) ) ) ; if ( ( getTempoMaster ( ) != null ) && ( Math . abs ( newTempo - oldTempo ) > getTempoEpsilon ( ) ) ) { // This is a change in tempo, so report it to any registered listeners, and update our metronome if we are synced. if ( isSynced ( ) ) { metronome . setTempo ( newTempo ) ; notifyBeatSenderOfChange ( ) ; } deliverTempoChangedAnnouncement ( newTempo ) ; } }
Establish a new master tempo and if it is a change from the existing one report it to the listeners .
162
22
150,622
private void processUpdate ( DeviceUpdate update ) { updates . put ( update . getAddress ( ) , update ) ; // Keep track of the largest sync number we see. if ( update instanceof CdjStatus ) { int syncNumber = ( ( CdjStatus ) update ) . getSyncNumber ( ) ; if ( syncNumber > this . largestSyncCounter . get ( ) ) { this . largestSyncCounter . set ( syncNumber ) ; } } // Deal with the tempo master complexities, including handoff to/from us. if ( update . isTempoMaster ( ) ) { final Integer packetYieldingTo = update . getDeviceMasterIsBeingYieldedTo ( ) ; if ( packetYieldingTo == null ) { // This is a normal, non-yielding master packet. Update our notion of the current master, and, // if we were yielding, finish that process, updating our sync number appropriately. if ( master . get ( ) ) { if ( nextMaster . get ( ) == update . deviceNumber ) { syncCounter . set ( largestSyncCounter . get ( ) + 1 ) ; } else { if ( nextMaster . get ( ) == 0xff ) { logger . warn ( "Saw master asserted by player " + update . deviceNumber + " when we were not yielding it." ) ; } else { logger . warn ( "Expected to yield master role to player " + nextMaster . get ( ) + " but saw master asserted by player " + update . deviceNumber ) ; } } } master . set ( false ) ; nextMaster . set ( 0xff ) ; setTempoMaster ( update ) ; setMasterTempo ( update . getEffectiveTempo ( ) ) ; } else { // This is a yielding master packet. If it is us that is being yielded to, take over master. // Log a message if it was unsolicited, and a warning if it's coming from a different player than // we asked. if ( packetYieldingTo == getDeviceNumber ( ) ) { if ( update . deviceNumber != masterYieldedFrom . get ( ) ) { if ( masterYieldedFrom . get ( ) == 0 ) { logger . info ( "Accepting unsolicited Master yield; we must be the only synced device playing." ) ; } else { logger . warn ( "Expected player " + masterYieldedFrom . get ( ) + " to yield master to us, but player " + update . deviceNumber + " did." ) ; } } master . set ( true ) ; masterYieldedFrom . set ( 0 ) ; setTempoMaster ( null ) ; setMasterTempo ( getTempo ( ) ) ; } } } else { // This update was not acting as a tempo master; if we thought it should be, update our records. DeviceUpdate oldMaster = getTempoMaster ( ) ; if ( oldMaster != null && oldMaster . getAddress ( ) . equals ( update . getAddress ( ) ) ) { // This device has resigned master status, and nobody else has claimed it so far setTempoMaster ( null ) ; } } deliverDeviceUpdate ( update ) ; }
Process a device update once it has been received . Track it as the most recent update from its address and notify any registered listeners including master listeners if it results in changes to tracked state such as the current master player and tempo . Also handles the Baroque dance of handing off the tempo master role from or to another device .
663
65
150,623
void processBeat ( Beat beat ) { if ( isRunning ( ) && beat . isTempoMaster ( ) ) { setMasterTempo ( beat . getEffectiveTempo ( ) ) ; deliverBeatAnnouncement ( beat ) ; } }
Process a beat packet potentially updating the master tempo and sending our listeners a master beat notification . Does nothing if we are not active .
51
26
150,624
private InterfaceAddress findMatchingAddress ( DeviceAnnouncement aDevice , NetworkInterface networkInterface ) { for ( InterfaceAddress address : networkInterface . getInterfaceAddresses ( ) ) { if ( ( address . getBroadcast ( ) != null ) && Util . sameNetwork ( address . getNetworkPrefixLength ( ) , aDevice . getAddress ( ) , address . getAddress ( ) ) ) { return address ; } } return null ; }
Scan a network interface to find if it has an address space which matches the device we are trying to reach . If so return the address specification .
94
29
150,625
public Set < DeviceAnnouncement > findUnreachablePlayers ( ) { ensureRunning ( ) ; Set < DeviceAnnouncement > result = new HashSet < DeviceAnnouncement > ( ) ; for ( DeviceAnnouncement candidate : DeviceFinder . getInstance ( ) . getCurrentDevices ( ) ) { if ( ! Util . sameNetwork ( matchedAddress . getNetworkPrefixLength ( ) , matchedAddress . getAddress ( ) , candidate . getAddress ( ) ) ) { result . add ( candidate ) ; } } return Collections . unmodifiableSet ( result ) ; }
Checks if we can see any players that are on a different network than the one we chose for the Virtual CDJ . If so we are not going to be able to communicate with them and they should all be moved onto a single network .
125
49
150,626
public synchronized void stop ( ) { if ( isRunning ( ) ) { try { setSendingStatus ( false ) ; } catch ( Throwable t ) { logger . error ( "Problem stopping sending status during shutdown" , t ) ; } DeviceFinder . getInstance ( ) . removeIgnoredAddress ( socket . get ( ) . getLocalAddress ( ) ) ; socket . get ( ) . close ( ) ; socket . set ( null ) ; broadcastAddress . set ( null ) ; updates . clear ( ) ; setTempoMaster ( null ) ; setDeviceNumber ( ( byte ) 0 ) ; // Set up for self-assignment if restarted. deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop announcing ourselves and listening for status updates .
153
9
150,627
private void sendAnnouncement ( InetAddress broadcastAddress ) { try { DatagramPacket announcement = new DatagramPacket ( announcementBytes , announcementBytes . length , broadcastAddress , DeviceFinder . ANNOUNCEMENT_PORT ) ; socket . get ( ) . send ( announcement ) ; Thread . sleep ( getAnnounceInterval ( ) ) ; } catch ( Throwable t ) { logger . warn ( "Unable to send announcement packet, shutting down" , t ) ; stop ( ) ; } }
Send an announcement packet so the other devices see us as being part of the DJ Link network and send us updates .
108
23
150,628
private void deliverMasterChangedAnnouncement ( final DeviceUpdate update ) { for ( final MasterListener listener : getMasterListeners ( ) ) { try { listener . masterChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering master changed announcement to listener" , t ) ; } } }
Send a master changed announcement to all registered master listeners .
68
11
150,629
private void deliverTempoChangedAnnouncement ( final double tempo ) { for ( final MasterListener listener : getMasterListeners ( ) ) { try { listener . tempoChanged ( tempo ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering tempo changed announcement to listener" , t ) ; } } }
Send a tempo changed announcement to all registered master listeners .
68
11
150,630
private void deliverBeatAnnouncement ( final Beat beat ) { for ( final MasterListener listener : getMasterListeners ( ) ) { try { listener . newBeat ( beat ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering master beat announcement to listener" , t ) ; } } }
Send a beat announcement to all registered master listeners .
66
10
150,631
private void deliverDeviceUpdate ( final DeviceUpdate update ) { for ( DeviceUpdateListener listener : getUpdateListeners ( ) ) { try { listener . received ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering device update to listener" , t ) ; } } }
Send a device update to all registered update listeners .
63
10
150,632
private void deliverMediaDetailsUpdate ( final MediaDetails details ) { for ( MediaDetailsListener listener : getMediaDetailsListeners ( ) ) { try { listener . detailsAvailable ( details ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering media details response to listener" , t ) ; } } }
Send a media details response to all registered listeners .
67
10
150,633
@ SuppressWarnings ( "SameParameterValue" ) private void assembleAndSendPacket ( Util . PacketType kind , byte [ ] payload , InetAddress destination , int port ) throws IOException { DatagramPacket packet = Util . buildPacket ( kind , ByteBuffer . wrap ( announcementBytes , DEVICE_NAME_OFFSET , DEVICE_NAME_LENGTH ) . asReadOnlyBuffer ( ) , ByteBuffer . wrap ( payload ) ) ; packet . setAddress ( destination ) ; packet . setPort ( port ) ; socket . get ( ) . send ( packet ) ; }
Finish the work of building and sending a protocol packet .
130
11
150,634
private void sendSyncControlCommand ( DeviceUpdate target , byte command ) throws IOException { ensureRunning ( ) ; byte [ ] payload = new byte [ SYNC_CONTROL_PAYLOAD . length ] ; System . arraycopy ( SYNC_CONTROL_PAYLOAD , 0 , payload , 0 , SYNC_CONTROL_PAYLOAD . length ) ; payload [ 2 ] = getDeviceNumber ( ) ; payload [ 8 ] = getDeviceNumber ( ) ; payload [ 12 ] = command ; assembleAndSendPacket ( Util . PacketType . SYNC_CONTROL , payload , target . getAddress ( ) , BeatFinder . BEAT_PORT ) ; }
Assemble and send a packet that performs sync control turning a device s sync mode on or off or telling it to become the tempo master .
150
28
150,635
public void sendSyncModeCommand ( int deviceNumber , boolean synced ) throws IOException { final DeviceUpdate update = getLatestStatusFor ( deviceNumber ) ; if ( update == null ) { throw new IllegalArgumentException ( "Device " + deviceNumber + " not found on network." ) ; } sendSyncModeCommand ( update , synced ) ; }
Tell a device to turn sync on or off .
75
10
150,636
public void appointTempoMaster ( int deviceNumber ) throws IOException { final DeviceUpdate update = getLatestStatusFor ( deviceNumber ) ; if ( update == null ) { throw new IllegalArgumentException ( "Device " + deviceNumber + " not found on network." ) ; } appointTempoMaster ( update ) ; }
Tell a device to become tempo master .
68
8
150,637
public void sendFaderStartCommand ( Set < Integer > deviceNumbersToStart , Set < Integer > deviceNumbersToStop ) throws IOException { ensureRunning ( ) ; byte [ ] payload = new byte [ FADER_START_PAYLOAD . length ] ; System . arraycopy ( FADER_START_PAYLOAD , 0 , payload , 0 , FADER_START_PAYLOAD . length ) ; payload [ 2 ] = getDeviceNumber ( ) ; for ( int i = 1 ; i <= 4 ; i ++ ) { if ( deviceNumbersToStart . contains ( i ) ) { payload [ i + 4 ] = 0 ; } if ( deviceNumbersToStop . contains ( i ) ) { payload [ i + 4 ] = 1 ; } } assembleAndSendPacket ( Util . PacketType . FADER_START_COMMAND , payload , getBroadcastAddress ( ) , BeatFinder . BEAT_PORT ) ; }
Broadcast a packet that tells some players to start playing and others to stop . If a player number is in both sets it will be told to stop . Numbers outside the range 1 to 4 are ignored .
210
41
150,638
public void sendLoadTrackCommand ( int targetPlayer , int rekordboxId , int sourcePlayer , CdjStatus . TrackSourceSlot sourceSlot , CdjStatus . TrackType sourceType ) throws IOException { final DeviceUpdate update = getLatestStatusFor ( targetPlayer ) ; if ( update == null ) { throw new IllegalArgumentException ( "Device " + targetPlayer + " not found on network." ) ; } sendLoadTrackCommand ( update , rekordboxId , sourcePlayer , sourceSlot , sourceType ) ; }
Send a packet to the target player telling it to load the specified track from the specified source player .
113
20
150,639
public void sendLoadTrackCommand ( DeviceUpdate target , int rekordboxId , int sourcePlayer , CdjStatus . TrackSourceSlot sourceSlot , CdjStatus . TrackType sourceType ) throws IOException { ensureRunning ( ) ; byte [ ] payload = new byte [ LOAD_TRACK_PAYLOAD . length ] ; System . arraycopy ( LOAD_TRACK_PAYLOAD , 0 , payload , 0 , LOAD_TRACK_PAYLOAD . length ) ; payload [ 0x02 ] = getDeviceNumber ( ) ; payload [ 0x05 ] = getDeviceNumber ( ) ; payload [ 0x09 ] = ( byte ) sourcePlayer ; payload [ 0x0a ] = sourceSlot . protocolValue ; payload [ 0x0b ] = sourceType . protocolValue ; Util . numberToBytes ( rekordboxId , payload , 0x0d , 4 ) ; assembleAndSendPacket ( Util . PacketType . LOAD_TRACK_COMMAND , payload , target . getAddress ( ) , UPDATE_PORT ) ; }
Send a packet to the target device telling it to load the specified track from the specified source player .
233
20
150,640
public synchronized void setSendingStatus ( boolean send ) throws IOException { if ( isSendingStatus ( ) == send ) { return ; } if ( send ) { // Start sending status packets. ensureRunning ( ) ; if ( ( getDeviceNumber ( ) < 1 ) || ( getDeviceNumber ( ) > 4 ) ) { throw new IllegalStateException ( "Can only send status when using a standard player number, 1 through 4." ) ; } BeatFinder . getInstance ( ) . start ( ) ; BeatFinder . getInstance ( ) . addLifecycleListener ( beatFinderLifecycleListener ) ; final AtomicBoolean stillRunning = new AtomicBoolean ( true ) ; sendingStatus = stillRunning ; // Allow other threads to stop us when necessary. Thread sender = new Thread ( null , new Runnable ( ) { @ Override public void run ( ) { while ( stillRunning . get ( ) ) { sendStatus ( ) ; try { Thread . sleep ( getStatusInterval ( ) ) ; } catch ( InterruptedException e ) { logger . warn ( "beat-link VirtualCDJ status sender thread was interrupted; continuing" ) ; } } } } , "beat-link VirtualCdj status sender" ) ; sender . setDaemon ( true ) ; sender . start ( ) ; if ( isSynced ( ) ) { // If we are supposed to be synced, we need to respond to master beats and tempo changes. addMasterListener ( ourSyncMasterListener ) ; } if ( isPlaying ( ) ) { // Start the beat sender too, if we are supposed to be playing. beatSender . set ( new BeatSender ( metronome ) ) ; } } else { // Stop sending status packets, and responding to master beats and tempo changes if we were synced. BeatFinder . getInstance ( ) . removeLifecycleListener ( beatFinderLifecycleListener ) ; removeMasterListener ( ourSyncMasterListener ) ; sendingStatus . set ( false ) ; // Stop the status sending thread. sendingStatus = null ; // Indicate that we are no longer sending status. final BeatSender activeSender = beatSender . get ( ) ; // And stop the beat sender if we have one. if ( activeSender != null ) { activeSender . shutDown ( ) ; beatSender . set ( null ) ; } } }
Control whether the Virtual CDJ sends status packets to the other players . Most uses of Beat Link will not require this level of activity . However if you want to be able to take over the tempo master role and control the tempo and beat alignment of other players you will need to turn on this feature which also requires that you are using one of the standard player numbers 1 - 4 .
504
76
150,641
public void setPlaying ( boolean playing ) { if ( this . playing . get ( ) == playing ) { return ; } this . playing . set ( playing ) ; if ( playing ) { metronome . jumpToBeat ( whereStopped . get ( ) . getBeat ( ) ) ; if ( isSendingStatus ( ) ) { // Need to also start the beat sender. beatSender . set ( new BeatSender ( metronome ) ) ; } } else { final BeatSender activeSender = beatSender . get ( ) ; if ( activeSender != null ) { // We have a beat sender we need to stop. activeSender . shutDown ( ) ; beatSender . set ( null ) ; } whereStopped . set ( metronome . getSnapshot ( ) ) ; } }
Controls whether we report that we are playing . This will only have an impact when we are sending status and beat packets .
175
25
150,642
public synchronized void becomeTempoMaster ( ) throws IOException { logger . debug ( "Trying to become master." ) ; if ( ! isSendingStatus ( ) ) { throw new IllegalStateException ( "Must be sending status updates to become the tempo master." ) ; } // Is there someone we need to ask to yield to us? final DeviceUpdate currentMaster = getTempoMaster ( ) ; if ( currentMaster != null ) { // Send the yield request; we will become master when we get a successful response. byte [ ] payload = new byte [ MASTER_HANDOFF_REQUEST_PAYLOAD . length ] ; System . arraycopy ( MASTER_HANDOFF_REQUEST_PAYLOAD , 0 , payload , 0 , MASTER_HANDOFF_REQUEST_PAYLOAD . length ) ; payload [ 2 ] = getDeviceNumber ( ) ; payload [ 8 ] = getDeviceNumber ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Sending master yield request to player " + currentMaster ) ; } requestingMasterRoleFromPlayer . set ( currentMaster . deviceNumber ) ; assembleAndSendPacket ( Util . PacketType . MASTER_HANDOFF_REQUEST , payload , currentMaster . address , BeatFinder . BEAT_PORT ) ; } else if ( ! master . get ( ) ) { // There is no other master, we can just become it immediately. requestingMasterRoleFromPlayer . set ( 0 ) ; setMasterTempo ( getTempo ( ) ) ; master . set ( true ) ; } }
Arrange to become the tempo master . Starts a sequence of interactions with the other players that should end up with us in charge of the group tempo and beat alignment .
341
33
150,643
public synchronized void setSynced ( boolean sync ) { if ( synced . get ( ) != sync ) { // We are changing sync state, so add or remove our master listener as appropriate. if ( sync && isSendingStatus ( ) ) { addMasterListener ( ourSyncMasterListener ) ; } else { removeMasterListener ( ourSyncMasterListener ) ; } // Also, if there is a tempo master, and we just got synced, adopt its tempo. if ( ! isTempoMaster ( ) && getTempoMaster ( ) != null ) { setTempo ( getMasterTempo ( ) ) ; } } synced . set ( sync ) ; }
Controls whether we are currently staying in sync with the tempo master . Will only be meaningful if we are sending status packets .
140
25
150,644
public synchronized void jumpToBeat ( int beat ) { if ( beat < 1 ) { beat = 1 ; } else { beat = wrapBeat ( beat ) ; } if ( playing . get ( ) ) { metronome . jumpToBeat ( beat ) ; } else { whereStopped . set ( metronome . getSnapshot ( metronome . getTimeOfBeat ( beat ) ) ) ; } }
Moves our current playback position to the specified beat ; this will be reflected in any status and beat packets that we are sending . An incoming value less than one will jump us to the first beat .
87
40
150,645
public Set < PlaybackState > getPlaybackState ( ) { Set < PlaybackState > result = new HashSet < PlaybackState > ( playbackStateMap . values ( ) ) ; return Collections . unmodifiableSet ( result ) ; }
Look up all recorded playback state information .
52
8
150,646
private void setPlaybackPosition ( long milliseconds ) { PlaybackState oldState = currentSimpleState ( ) ; if ( oldState != null && oldState . position != milliseconds ) { setPlaybackState ( oldState . player , milliseconds , oldState . playing ) ; } }
Set the current playback position . This method can only be used in situations where the component is tied to a single player and therefore always has a single playback position .
58
32
150,647
private void setPlaying ( boolean playing ) { PlaybackState oldState = currentSimpleState ( ) ; if ( oldState != null && oldState . playing != playing ) { setPlaybackState ( oldState . player , oldState . position , playing ) ; } }
Set whether the player holding the waveform is playing which changes the indicator color to white from red . This method can only be used in situations where the component is tied to a single player and therefore has a single playback position .
56
45
150,648
public synchronized void setMonitoredPlayer ( final int player ) { if ( player < 0 ) { throw new IllegalArgumentException ( "player cannot be negative" ) ; } clearPlaybackState ( ) ; monitoredPlayer . set ( player ) ; if ( player > 0 ) { // Start monitoring the specified player setPlaybackState ( player , 0 , false ) ; // Start with default values for required simple state. VirtualCdj . getInstance ( ) . addUpdateListener ( updateListener ) ; MetadataFinder . getInstance ( ) . addTrackMetadataListener ( metadataListener ) ; cueList . set ( null ) ; // Assume the worst, but see if we have one available next. if ( MetadataFinder . getInstance ( ) . isRunning ( ) ) { TrackMetadata metadata = MetadataFinder . getInstance ( ) . getLatestMetadataFor ( player ) ; if ( metadata != null ) { cueList . set ( metadata . getCueList ( ) ) ; } } WaveformFinder . getInstance ( ) . addWaveformListener ( waveformListener ) ; if ( WaveformFinder . getInstance ( ) . isRunning ( ) && WaveformFinder . getInstance ( ) . isFindingDetails ( ) ) { waveform . set ( WaveformFinder . getInstance ( ) . getLatestDetailFor ( player ) ) ; } else { waveform . set ( null ) ; } BeatGridFinder . getInstance ( ) . addBeatGridListener ( beatGridListener ) ; if ( BeatGridFinder . getInstance ( ) . isRunning ( ) ) { beatGrid . set ( BeatGridFinder . getInstance ( ) . getLatestBeatGridFor ( player ) ) ; } else { beatGrid . set ( null ) ; } try { TimeFinder . getInstance ( ) . start ( ) ; if ( ! animating . getAndSet ( true ) ) { // Create the thread to update our position smoothly as the track plays new Thread ( new Runnable ( ) { @ Override public void run ( ) { while ( animating . get ( ) ) { try { Thread . sleep ( 33 ) ; // Animate at 30 fps } catch ( InterruptedException e ) { logger . warn ( "Waveform animation thread interrupted; ending" ) ; animating . set ( false ) ; } setPlaybackPosition ( TimeFinder . getInstance ( ) . getTimeFor ( getMonitoredPlayer ( ) ) ) ; } } } ) . start ( ) ; } } catch ( Exception e ) { logger . error ( "Unable to start the TimeFinder to animate the waveform detail view" ) ; animating . set ( false ) ; } } else { // Stop monitoring any player animating . set ( false ) ; VirtualCdj . getInstance ( ) . removeUpdateListener ( updateListener ) ; MetadataFinder . getInstance ( ) . removeTrackMetadataListener ( metadataListener ) ; WaveformFinder . getInstance ( ) . removeWaveformListener ( waveformListener ) ; cueList . set ( null ) ; waveform . set ( null ) ; beatGrid . set ( null ) ; } if ( ! autoScroll . get ( ) ) { invalidate ( ) ; } repaint ( ) ; }
Configures the player whose current track waveforms and status will automatically be reflected . Whenever a new track is loaded on that player the waveform and metadata will be updated and the current playback position and state of the player will be reflected by the component .
694
50
150,649
public PlaybackState getFurthestPlaybackState ( ) { PlaybackState result = null ; for ( PlaybackState state : playbackStateMap . values ( ) ) { if ( result == null || ( ! result . playing && state . playing ) || ( result . position < state . position ) && ( state . playing || ! result . playing ) ) { result = state ; } } return result ; }
Look up the playback state that has reached furthest in the track but give playing players priority over stopped players . This is used to choose the scroll center when auto - scrolling is active .
87
37
150,650
private int getSegmentForX ( int x ) { if ( autoScroll . get ( ) ) { int playHead = ( x - ( getWidth ( ) / 2 ) ) ; int offset = Util . timeToHalfFrame ( getFurthestPlaybackPosition ( ) ) / scale . get ( ) ; return ( playHead + offset ) * scale . get ( ) ; } return x * scale . get ( ) ; }
Figure out the starting waveform segment that corresponds to the specified coordinate in the window .
93
17
150,651
public int getXForBeat ( int beat ) { BeatGrid grid = beatGrid . get ( ) ; if ( grid != null ) { return millisecondsToX ( grid . getTimeWithinTrack ( beat ) ) ; } return 0 ; }
Determine the X coordinate within the component at which the specified beat begins .
50
16
150,652
public int millisecondsToX ( long milliseconds ) { if ( autoScroll . get ( ) ) { int playHead = ( getWidth ( ) / 2 ) + 2 ; long offset = milliseconds - getFurthestPlaybackPosition ( ) ; return playHead + ( Util . timeToHalfFrame ( offset ) / scale . get ( ) ) ; } return Util . timeToHalfFrame ( milliseconds ) / scale . get ( ) ; }
Converts a time in milliseconds to the appropriate x coordinate for drawing something at that time .
94
18
150,653
public static Color cueColor ( CueList . Entry entry ) { if ( entry . hotCueNumber > 0 ) { return Color . GREEN ; } if ( entry . isLoop ) { return Color . ORANGE ; } return Color . RED ; }
Determine the color to use to draw a cue list entry . Hot cues are green ordinary memory points are red and loops are orange .
52
28
150,654
public byte [ ] getPacketBytes ( ) { byte [ ] result = new byte [ packetBytes . length ] ; System . arraycopy ( packetBytes , 0 , result , 0 , packetBytes . length ) ; return result ; }
Get the raw data bytes of the device update packet .
49
11
150,655
public static DatagramPacket buildPacket ( PacketType type , ByteBuffer deviceName , ByteBuffer payload ) { ByteBuffer content = ByteBuffer . allocate ( 0x1f + payload . remaining ( ) ) ; content . put ( getMagicHeader ( ) ) ; content . put ( type . protocolValue ) ; content . put ( deviceName ) ; content . put ( payload ) ; return new DatagramPacket ( content . array ( ) , content . capacity ( ) ) ; }
Build a standard - format UDP packet for sending to port 50001 or 50002 in the protocol .
103
20
150,656
public static PacketType validateHeader ( DatagramPacket packet , int port ) { byte [ ] data = packet . getData ( ) ; if ( data . length < PACKET_TYPE_OFFSET ) { logger . warn ( "Packet is too short to be a Pro DJ Link packet; must be at least " + PACKET_TYPE_OFFSET + " bytes long, was only " + data . length + "." ) ; return null ; } if ( ! getMagicHeader ( ) . equals ( ByteBuffer . wrap ( data , 0 , MAGIC_HEADER . length ) ) ) { logger . warn ( "Packet did not have correct nine-byte header for the Pro DJ Link protocol." ) ; return null ; } final Map < Byte , PacketType > portMap = PACKET_TYPE_MAP . get ( port ) ; if ( portMap == null ) { logger . warn ( "Do not know any Pro DJ Link packets that are received on port " + port + "." ) ; return null ; } final PacketType result = portMap . get ( data [ PACKET_TYPE_OFFSET ] ) ; if ( result == null ) { logger . warn ( "Do not know any Pro DJ Link packets received on port " + port + " with type " + String . format ( "0x%02x" , data [ PACKET_TYPE_OFFSET ] ) + "." ) ; } return result ; }
Check to see whether a packet starts with the standard header bytes followed by a known byte identifying it . If so return the kind of packet that has been recognized .
306
32
150,657
public static long bytesToNumber ( byte [ ] buffer , int start , int length ) { long result = 0 ; for ( int index = start ; index < start + length ; index ++ ) { result = ( result << 8 ) + unsign ( buffer [ index ] ) ; } return result ; }
Reconstructs a number that is represented by more than one byte in a network packet in big - endian order .
63
25
150,658
@ SuppressWarnings ( "SameParameterValue" ) public static long bytesToNumberLittleEndian ( byte [ ] buffer , int start , int length ) { long result = 0 ; for ( int index = start + length - 1 ; index >= start ; index -- ) { result = ( result << 8 ) + unsign ( buffer [ index ] ) ; } return result ; }
Reconstructs a number that is represented by more than one byte in a network packet in little - endian order for the very few protocol values that are sent in this quirky way .
81
38
150,659
public static void numberToBytes ( int number , byte [ ] buffer , int start , int length ) { for ( int index = start + length - 1 ; index >= start ; index -- ) { buffer [ index ] = ( byte ) ( number & 0xff ) ; number = number >> 8 ; } }
Writes a number to the specified byte array field breaking it into its component bytes in big - endian order . If the number is too large to fit in the specified number of bytes only the low - order bytes are written .
64
46
150,660
public static long addressToLong ( InetAddress address ) { long result = 0 ; for ( byte element : address . getAddress ( ) ) { result = ( result << 8 ) + unsign ( element ) ; } return result ; }
Converts the bytes that make up an internet address into the corresponding integer value to make it easier to perform bit - masking operations on them .
50
29
150,661
public static boolean sameNetwork ( int prefixLength , InetAddress address1 , InetAddress address2 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Comparing address " + address1 . getHostAddress ( ) + " with " + address2 . getHostAddress ( ) + ", prefixLength=" + prefixLength ) ; } long prefixMask = 0xffffffff L & ( - 1 << ( 32 - prefixLength ) ) ; return ( addressToLong ( address1 ) & prefixMask ) == ( addressToLong ( address2 ) & prefixMask ) ; }
Checks whether two internet addresses are on the same subnet .
126
13
150,662
public static void writeFully ( ByteBuffer buffer , WritableByteChannel channel ) throws IOException { while ( buffer . hasRemaining ( ) ) { channel . write ( buffer ) ; } }
Writes the entire remaining contents of the buffer to the channel . May complete in one operation but the documentation is vague so this keeps going until we are sure .
41
32
150,663
public Map < Integer , String > getSignatures ( ) { ensureRunning ( ) ; // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < Integer , String > ( signatures ) ) ; }
Get the signatures that have been computed for all tracks currently loaded in any player for which we have been able to obtain all necessary metadata .
56
27
150,664
private void checkExistingTracks ( ) { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( Map . Entry < DeckReference , TrackMetadata > entry : MetadataFinder . getInstance ( ) . getLoadedTracks ( ) . entrySet ( ) ) { if ( entry . getKey ( ) . hotCue == 0 ) { // The track is currently loaded in a main player deck checkIfSignatureReady ( entry . getKey ( ) . player ) ; } } } } ) ; }
Send ourselves updates about any tracks that were loaded before we started since we missed them .
122
17
150,665
private void digestInteger ( MessageDigest digest , int value ) { byte [ ] valueBytes = new byte [ 4 ] ; Util . numberToBytes ( value , valueBytes , 0 , 4 ) ; digest . update ( valueBytes ) ; }
Helper method to add a Java integer value to a message digest .
52
13
150,666
public String computeTrackSignature ( final String title , final SearchableItem artist , final int duration , final WaveformDetail waveformDetail , final BeatGrid beatGrid ) { final String safeTitle = ( title == null ) ? "" : title ; final String artistName = ( artist == null ) ? "[no artist]" : artist . label ; try { // Compute the SHA-1 hash of our fields MessageDigest digest = MessageDigest . getInstance ( "SHA1" ) ; digest . update ( safeTitle . getBytes ( "UTF-8" ) ) ; digest . update ( ( byte ) 0 ) ; digest . update ( artistName . getBytes ( "UTF-8" ) ) ; digest . update ( ( byte ) 0 ) ; digestInteger ( digest , duration ) ; digest . update ( waveformDetail . getData ( ) ) ; for ( int i = 1 ; i <= beatGrid . beatCount ; i ++ ) { digestInteger ( digest , beatGrid . getBeatWithinBar ( i ) ) ; digestInteger ( digest , ( int ) beatGrid . getTimeWithinTrack ( i ) ) ; } byte [ ] result = digest . digest ( ) ; // Create a hex string representation of the hash StringBuilder hex = new StringBuilder ( result . length * 2 ) ; for ( byte aResult : result ) { hex . append ( Integer . toString ( ( aResult & 0xff ) + 0x100 , 16 ) . substring ( 1 ) ) ; } return hex . toString ( ) ; } catch ( NullPointerException e ) { logger . info ( "Returning null track signature because an input element was null." , e ) ; } catch ( NoSuchAlgorithmException e ) { logger . error ( "Unable to obtain SHA-1 MessageDigest instance for computing track signatures." , e ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( "Unable to work with UTF-8 string encoding for computing track signatures." , e ) ; } return null ; // We were unable to compute a signature }
Calculate the signature by which we can reliably recognize a loaded track .
439
15
150,667
private void handleUpdate ( final int player ) { final TrackMetadata metadata = MetadataFinder . getInstance ( ) . getLatestMetadataFor ( player ) ; final WaveformDetail waveformDetail = WaveformFinder . getInstance ( ) . getLatestDetailFor ( player ) ; final BeatGrid beatGrid = BeatGridFinder . getInstance ( ) . getLatestBeatGridFor ( player ) ; if ( metadata != null && waveformDetail != null && beatGrid != null ) { final String signature = computeTrackSignature ( metadata . getTitle ( ) , metadata . getArtist ( ) , metadata . getDuration ( ) , waveformDetail , beatGrid ) ; if ( signature != null ) { signatures . put ( player , signature ) ; deliverSignatureUpdate ( player , signature ) ; } } }
We have reason to believe we might have enough information to calculate a signature for the track loaded on a player . Verify that and if so perform the computation and record and report the new signature .
176
38
150,668
public synchronized void stop ( ) { if ( isRunning ( ) ) { MetadataFinder . getInstance ( ) . removeTrackMetadataListener ( metadataListener ) ; WaveformFinder . getInstance ( ) . removeWaveformListener ( waveformListener ) ; BeatGridFinder . getInstance ( ) . removeBeatGridListener ( beatGridListener ) ; running . set ( false ) ; pendingUpdates . clear ( ) ; queueHandler . interrupt ( ) ; queueHandler = null ; // Report the loss of our signatures, on the proper thread, outside our lock final Set < Integer > dyingSignatures = new HashSet < Integer > ( signatures . keySet ( ) ) ; signatures . clear ( ) ; SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( Integer player : dyingSignatures ) { deliverSignatureUpdate ( player , null ) ; } } } ) ; } deliverLifecycleAnnouncement ( logger , false ) ; }
Stop finding signatures for all active players .
211
8
150,669
private void expireDevices ( ) { long now = System . currentTimeMillis ( ) ; // Make a copy so we don't have to worry about concurrent modification. Map < InetAddress , DeviceAnnouncement > copy = new HashMap < InetAddress , DeviceAnnouncement > ( devices ) ; for ( Map . Entry < InetAddress , DeviceAnnouncement > entry : copy . entrySet ( ) ) { if ( now - entry . getValue ( ) . getTimestamp ( ) > MAXIMUM_AGE ) { devices . remove ( entry . getKey ( ) ) ; deliverLostAnnouncement ( entry . getValue ( ) ) ; } } if ( devices . isEmpty ( ) ) { firstDeviceTime . set ( 0 ) ; // We have lost contact with the Pro DJ Link network, so start over with next device. } }
Remove any device announcements that are so old that the device seems to have gone away .
182
17
150,670
private void updateDevices ( DeviceAnnouncement announcement ) { firstDeviceTime . compareAndSet ( 0 , System . currentTimeMillis ( ) ) ; devices . put ( announcement . getAddress ( ) , announcement ) ; }
Record a device announcement in the devices map so we know whe saw it .
48
15
150,671
public synchronized void start ( ) throws SocketException { if ( ! isRunning ( ) ) { socket . set ( new DatagramSocket ( ANNOUNCEMENT_PORT ) ) ; startTime . set ( System . currentTimeMillis ( ) ) ; deliverLifecycleAnnouncement ( logger , true ) ; final byte [ ] buffer = new byte [ 512 ] ; final DatagramPacket packet = new DatagramPacket ( buffer , buffer . length ) ; Thread receiver = new Thread ( null , new Runnable ( ) { @ Override public void run ( ) { boolean received ; while ( isRunning ( ) ) { try { if ( getCurrentDevices ( ) . isEmpty ( ) ) { socket . get ( ) . setSoTimeout ( 60000 ) ; // We have no devices to check for timeout; block for a whole minute to check for shutdown } else { socket . get ( ) . setSoTimeout ( 1000 ) ; // Check every second to see if a device has vanished } socket . get ( ) . receive ( packet ) ; received = ! ignoredAddresses . contains ( packet . getAddress ( ) ) ; } catch ( SocketTimeoutException ste ) { received = false ; } catch ( IOException e ) { // Don't log a warning if the exception was due to the socket closing at shutdown. if ( isRunning ( ) ) { // We did not expect to have a problem; log a warning and shut down. logger . warn ( "Problem reading from DeviceAnnouncement socket, stopping" , e ) ; stop ( ) ; } received = false ; } try { if ( received && ( packet . getLength ( ) == 54 ) ) { final Util . PacketType kind = Util . validateHeader ( packet , ANNOUNCEMENT_PORT ) ; if ( kind == Util . PacketType . DEVICE_KEEP_ALIVE ) { // Looks like the kind of packet we need if ( packet . getLength ( ) < 54 ) { logger . warn ( "Ignoring too-short " + kind . name + " packet; expected 54 bytes, but only got " + packet . getLength ( ) + "." ) ; } else { if ( packet . getLength ( ) > 54 ) { logger . warn ( "Processing too-long " + kind . name + " packet; expected 54 bytes, but got " + packet . getLength ( ) + "." ) ; } DeviceAnnouncement announcement = new DeviceAnnouncement ( packet ) ; final boolean foundNewDevice = isDeviceNew ( announcement ) ; updateDevices ( announcement ) ; if ( foundNewDevice ) { deliverFoundAnnouncement ( announcement ) ; } } } } expireDevices ( ) ; } catch ( Throwable t ) { logger . warn ( "Problem processing DeviceAnnouncement packet" , t ) ; } } } } , "beat-link DeviceFinder receiver" ) ; receiver . setDaemon ( true ) ; receiver . start ( ) ; } }
Start listening for device announcements and keeping track of the DJ Link devices visible on the network . If already listening has no effect .
629
25
150,672
@ SuppressWarnings ( "WeakerAccess" ) public synchronized void stop ( ) { if ( isRunning ( ) ) { final Set < DeviceAnnouncement > lastDevices = getCurrentDevices ( ) ; socket . get ( ) . close ( ) ; socket . set ( null ) ; devices . clear ( ) ; firstDeviceTime . set ( 0 ) ; // Report the loss of all our devices, on the proper thread, outside our lock SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( DeviceAnnouncement announcement : lastDevices ) { deliverLostAnnouncement ( announcement ) ; } } } ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop listening for device announcements . Also discard any announcements which had been received and notify any registered listeners that those devices have been lost .
161
26
150,673
private void deliverFoundAnnouncement ( final DeviceAnnouncement announcement ) { for ( final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners ( ) ) { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try { listener . deviceFound ( announcement ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering device found announcement to listener" , t ) ; } } } ) ; } }
Send a device found announcement to all registered listeners .
102
10
150,674
private void deliverLostAnnouncement ( final DeviceAnnouncement announcement ) { for ( final DeviceAnnouncementListener listener : getDeviceAnnouncementListeners ( ) ) { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { try { listener . deviceLost ( announcement ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering device lost announcement to listener" , t ) ; } } } ) ; } }
Send a device lost announcement to all registered listeners .
102
10
150,675
private void performSetupExchange ( ) throws IOException { Message setupRequest = new Message ( 0xfffffffe L , Message . KnownType . SETUP_REQ , new NumberField ( posingAsPlayer , 4 ) ) ; sendMessage ( setupRequest ) ; Message response = Message . read ( is ) ; if ( response . knownType != Message . KnownType . MENU_AVAILABLE ) { throw new IOException ( "Did not receive message type 0x4000 in response to setup message, got: " + response ) ; } if ( response . arguments . size ( ) != 2 ) { throw new IOException ( "Did not receive two arguments in response to setup message, got: " + response ) ; } final Field player = response . arguments . get ( 1 ) ; if ( ! ( player instanceof NumberField ) ) { throw new IOException ( "Second argument in response to setup message was not a number: " + response ) ; } if ( ( ( NumberField ) player ) . getValue ( ) != targetPlayer ) { throw new IOException ( "Expected to connect to player " + targetPlayer + ", but welcome response identified itself as player " + ( ( NumberField ) player ) . getValue ( ) ) ; } }
Exchanges the initial fully - formed messages which establishes the transaction context for queries to the dbserver .
264
21
150,676
private void performTeardownExchange ( ) throws IOException { Message teardownRequest = new Message ( 0xfffffffe L , Message . KnownType . TEARDOWN_REQ ) ; sendMessage ( teardownRequest ) ; // At this point, the server closes the connection from its end, so we can’t read any more. }
Exchanges the final messages which politely report our intention to disconnect from the dbserver .
77
18
150,677
void close ( ) { try { performTeardownExchange ( ) ; } catch ( IOException e ) { logger . warn ( "Problem reporting our intention to close the dbserver connection" , e ) ; } try { channel . close ( ) ; } catch ( IOException e ) { logger . warn ( "Problem closing dbserver client output channel" , e ) ; } try { os . close ( ) ; } catch ( IOException e ) { logger . warn ( "Problem closing dbserver client output stream" , e ) ; } try { is . close ( ) ; } catch ( IOException e ) { logger . warn ( "Problem closing dbserver client input stream" , e ) ; } try { socket . close ( ) ; } catch ( IOException e ) { logger . warn ( "Problem closing dbserver client socket" , e ) ; } }
Closes the connection to the dbserver . This instance can no longer be used after this action .
186
21
150,678
@ SuppressWarnings ( "SameParameterValue" ) private void sendField ( Field field ) throws IOException { if ( isConnected ( ) ) { try { field . write ( channel ) ; } catch ( IOException e ) { logger . warn ( "Problem trying to write field to dbserver, closing connection" , e ) ; close ( ) ; throw e ; } return ; } throw new IOException ( "sendField() called after dbserver connection was closed" ) ; }
Attempt to send the specified field to the dbserver . This low - level function is available only to the package itself for use in setting up the connection . It was previously also used for sending parts of larger - scale messages but because that sometimes led to them being fragmented into multiple network packets and Windows rekordbox cannot handle that full message sending no longer uses this method .
105
76
150,679
private void sendMessage ( Message message ) throws IOException { logger . debug ( "Sending> {}" , message ) ; int totalSize = 0 ; for ( Field field : message . fields ) { totalSize += field . getBytes ( ) . remaining ( ) ; } ByteBuffer combined = ByteBuffer . allocate ( totalSize ) ; for ( Field field : message . fields ) { logger . debug ( "..sending> {}" , field ) ; combined . put ( field . getBytes ( ) ) ; } combined . flip ( ) ; Util . writeFully ( combined , channel ) ; }
Sends a message to the dbserver first assembling it into a single byte buffer so that it can be sent as a single packet .
127
28
150,680
public synchronized Message simpleRequest ( Message . KnownType requestType , Message . KnownType responseType , Field ... arguments ) throws IOException { final NumberField transaction = assignTransactionNumber ( ) ; final Message request = new Message ( transaction , new NumberField ( requestType . protocolValue , 2 ) , arguments ) ; sendMessage ( request ) ; final Message response = Message . read ( is ) ; if ( response . transaction . getValue ( ) != transaction . getValue ( ) ) { throw new IOException ( "Received response with wrong transaction ID. Expected: " + transaction . getValue ( ) + ", got: " + response ) ; } if ( responseType != null && response . knownType != responseType ) { throw new IOException ( "Received response with wrong type. Expected: " + responseType + ", got: " + response ) ; } return response ; }
Send a request that expects a single message as its response then read and return that response .
185
18
150,681
public synchronized Message menuRequestTyped ( Message . KnownType requestType , Message . MenuIdentifier targetMenu , CdjStatus . TrackSourceSlot slot , CdjStatus . TrackType trackType , Field ... arguments ) throws IOException { if ( ! menuLock . isHeldByCurrentThread ( ) ) { throw new IllegalStateException ( "renderMenuItems() cannot be called without first successfully calling tryLockingForMenuOperation()" ) ; } Field [ ] combinedArguments = new Field [ arguments . length + 1 ] ; combinedArguments [ 0 ] = buildRMST ( targetMenu , slot , trackType ) ; System . arraycopy ( arguments , 0 , combinedArguments , 1 , arguments . length ) ; final Message response = simpleRequest ( requestType , Message . KnownType . MENU_AVAILABLE , combinedArguments ) ; final NumberField reportedRequestType = ( NumberField ) response . arguments . get ( 0 ) ; if ( reportedRequestType . getValue ( ) != requestType . protocolValue ) { throw new IOException ( "Menu request did not return result for same type as request; sent type: " + requestType . protocolValue + ", received type: " + reportedRequestType . getValue ( ) + ", response: " + response ) ; } return response ; }
Send a request for a menu that we will retrieve items from in subsequent requests when the request must reflect the actual type of track being asked about .
274
29
150,682
@ SuppressWarnings ( "WeakerAccess" ) public static synchronized SlotReference getSlotReference ( int player , CdjStatus . TrackSourceSlot slot ) { Map < CdjStatus . TrackSourceSlot , SlotReference > playerMap = instances . get ( player ) ; if ( playerMap == null ) { playerMap = new HashMap < CdjStatus . TrackSourceSlot , SlotReference > ( ) ; instances . put ( player , playerMap ) ; } SlotReference result = playerMap . get ( slot ) ; if ( result == null ) { result = new SlotReference ( player , slot ) ; playerMap . put ( slot , result ) ; } return result ; }
Get a unique reference to a media slot on the network from which tracks can be loaded .
143
18
150,683
@ SuppressWarnings ( "WeakerAccess" ) public static SlotReference getSlotReference ( DataReference dataReference ) { return getSlotReference ( dataReference . player , dataReference . slot ) ; }
Get a unique reference to the media slot on the network from which the specified data was loaded .
44
19
150,684
@ Override public boolean isTempoMaster ( ) { DeviceUpdate master = VirtualCdj . getInstance ( ) . getTempoMaster ( ) ; return ( master != null ) && master . getAddress ( ) . equals ( address ) ; }
Was this beat sent by the current tempo master?
52
10
150,685
protected void deliverLifecycleAnnouncement ( final Logger logger , final boolean starting ) { new Thread ( new Runnable ( ) { @ Override public void run ( ) { for ( final LifecycleListener listener : getLifecycleListeners ( ) ) { try { if ( starting ) { listener . started ( LifecycleParticipant . this ) ; } else { listener . stopped ( LifecycleParticipant . this ) ; } } catch ( Throwable t ) { logger . warn ( "Problem delivering lifecycle announcement to listener" , t ) ; } } } } , "Lifecycle announcement delivery" ) . start ( ) ; }
Send a lifecycle announcement to all registered listeners .
136
10
150,686
private String mountPath ( CdjStatus . TrackSourceSlot slot ) { switch ( slot ) { case SD_SLOT : return "/B/" ; case USB_SLOT : return "/C/" ; } throw new IllegalArgumentException ( "Don't know how to NFS mount filesystem for slot " + slot ) ; }
Return the filesystem path needed to mount the NFS filesystem associated with a particular media slot .
68
18
150,687
private void deliverDatabaseUpdate ( SlotReference slot , Database database , boolean available ) { for ( final DatabaseListener listener : getDatabaseListeners ( ) ) { try { if ( available ) { listener . databaseMounted ( slot , database ) ; } else { listener . databaseUnmounted ( slot , database ) ; } } catch ( Throwable t ) { logger . warn ( "Problem delivering rekordbox database availability update to listener" , t ) ; } } }
Send a database announcement to all registered listeners .
97
9
150,688
@ SuppressWarnings ( "SameParameterValue" ) private void delegatingRepaint ( int x , int y , int width , int height ) { final RepaintDelegate delegate = repaintDelegate . get ( ) ; if ( delegate != null ) { //logger.info("Delegating repaint: " + x + ", " + y + ", " + width + ", " + height); delegate . repaint ( x , y , width , height ) ; } else { //logger.info("Normal repaint: " + x + ", " + y + ", " + width + ", " + height); repaint ( x , y , width , height ) ; } }
Determine whether we should use the normal repaint process or delegate that to another component that is hosting us in a soft - loaded manner to save memory .
147
32
150,689
private void updateWaveform ( WaveformPreview preview ) { this . preview . set ( preview ) ; if ( preview == null ) { waveformImage . set ( null ) ; } else { BufferedImage image = new BufferedImage ( preview . segmentCount , preview . maxHeight , BufferedImage . TYPE_INT_RGB ) ; Graphics g = image . getGraphics ( ) ; g . setColor ( Color . BLACK ) ; g . fillRect ( 0 , 0 , preview . segmentCount , preview . maxHeight ) ; for ( int segment = 0 ; segment < preview . segmentCount ; segment ++ ) { g . setColor ( preview . segmentColor ( segment , false ) ) ; g . drawLine ( segment , preview . maxHeight , segment , preview . maxHeight - preview . segmentHeight ( segment , false ) ) ; if ( preview . isColor ) { // We have a front color segment to draw on top. g . setColor ( preview . segmentColor ( segment , true ) ) ; g . drawLine ( segment , preview . maxHeight , segment , preview . maxHeight - preview . segmentHeight ( segment , true ) ) ; } } waveformImage . set ( image ) ; } }
Create an image of the proper size to hold a new waveform preview image and draw it .
254
19
150,690
private int getMaxHeight ( ) { int result = 0 ; for ( int i = 0 ; i < segmentCount ; i ++ ) { result = Math . max ( result , segmentHeight ( i , false ) ) ; } return result ; }
Scan the segments to find the largest height value present .
51
11
150,691
@ SuppressWarnings ( "WeakerAccess" ) public int segmentHeight ( final int segment , final boolean front ) { final ByteBuffer bytes = getData ( ) ; if ( isColor ) { final int base = segment * 6 ; final int frontHeight = Util . unsign ( bytes . get ( base + 5 ) ) ; if ( front ) { return frontHeight ; } else { return Math . max ( frontHeight , Math . max ( Util . unsign ( bytes . get ( base + 3 ) ) , Util . unsign ( bytes . get ( base + 4 ) ) ) ) ; } } else { return getData ( ) . get ( segment * 2 ) & 0x1f ; } }
Determine the height of the preview given an index into it .
154
14
150,692
@ SuppressWarnings ( "WeakerAccess" ) public Color segmentColor ( final int segment , final boolean front ) { final ByteBuffer bytes = getData ( ) ; if ( isColor ) { final int base = segment * 6 ; final int backHeight = segmentHeight ( segment , false ) ; if ( backHeight == 0 ) { return Color . BLACK ; } final int maxLevel = front ? 255 : 191 ; final int red = Util . unsign ( bytes . get ( base + 3 ) ) * maxLevel / backHeight ; final int green = Util . unsign ( bytes . get ( base + 4 ) ) * maxLevel / backHeight ; final int blue = Util . unsign ( bytes . get ( base + 5 ) ) * maxLevel / backHeight ; return new Color ( red , green , blue ) ; } else { final int intensity = getData ( ) . get ( segment * 2 + 1 ) & 0x07 ; return ( intensity >= 5 ) ? INTENSE_COLOR : NORMAL_COLOR ; } }
Determine the color of the waveform given an index into it .
222
15
150,693
public boolean hasChanged ( MediaDetails originalMedia ) { if ( ! hashKey ( ) . equals ( originalMedia . hashKey ( ) ) ) { throw new IllegalArgumentException ( "Can't compare media details with different hashKey values" ) ; } return playlistCount != originalMedia . playlistCount || trackCount != originalMedia . trackCount ; }
Check whether the media seems to have changed since a saved version of it was used . We ignore changes in free space because those probably just reflect history entries being added .
73
33
150,694
public byte [ ] getValueAsArray ( ) { ByteBuffer buffer = getValue ( ) ; byte [ ] result = new byte [ buffer . remaining ( ) ] ; buffer . get ( result ) ; return result ; }
Get the bytes which represent the payload of this field without the leading type tag and length header as a newly - allocated byte array .
46
26
150,695
public int getHotCueCount ( ) { if ( rawMessage != null ) { return ( int ) ( ( NumberField ) rawMessage . arguments . get ( 5 ) ) . getValue ( ) ; } int total = 0 ; for ( Entry entry : entries ) { if ( entry . hotCueNumber > 0 ) { ++ total ; } } return total ; }
Return the number of entries in the cue list that represent hot cues .
78
14
150,696
private List < Entry > sortEntries ( List < Entry > loadedEntries ) { Collections . sort ( loadedEntries , new Comparator < Entry > ( ) { @ Override public int compare ( Entry entry1 , Entry entry2 ) { int result = ( int ) ( entry1 . cuePosition - entry2 . cuePosition ) ; if ( result == 0 ) { int h1 = ( entry1 . hotCueNumber != 0 ) ? 1 : 0 ; int h2 = ( entry2 . hotCueNumber != 0 ) ? 1 : 0 ; result = h1 - h2 ; } return result ; } } ) ; return Collections . unmodifiableList ( loadedEntries ) ; }
Sorts the entries into the order we want to present them in which is by position with hot cues coming after ordinary memory points if both exist at the same position which often happens .
148
36
150,697
private void addEntriesFromTag ( List < Entry > entries , RekordboxAnlz . CueTag tag ) { for ( RekordboxAnlz . CueEntry cueEntry : tag . cues ( ) ) { // TODO: Need to figure out how to identify deleted entries to ignore. if ( cueEntry . type ( ) == RekordboxAnlz . CueEntryType . LOOP ) { entries . add ( new Entry ( ( int ) cueEntry . hotCue ( ) , Util . timeToHalfFrame ( cueEntry . time ( ) ) , Util . timeToHalfFrame ( cueEntry . loopTime ( ) ) ) ) ; } else { entries . add ( new Entry ( ( int ) cueEntry . hotCue ( ) , Util . timeToHalfFrame ( cueEntry . time ( ) ) ) ) ; } } }
Helper method to add cue list entries from a parsed ANLZ cue tag
187
15
150,698
public final static String process ( final String input , final Configuration configuration ) { try { return process ( new StringReader ( input ) , configuration ) ; } catch ( final IOException e ) { // This _can never_ happen return null ; } }
Transforms an input String into HTML using the given Configuration .
51
12
150,699
public final static String process ( final File file , final Configuration configuration ) throws IOException { final FileInputStream input = new FileInputStream ( file ) ; final String ret = process ( input , configuration ) ; input . close ( ) ; return ret ; }
Transforms an input file into HTML using the given Configuration .
53
12