idx
int64
0
165k
question
stringlengths
73
4.15k
target
stringlengths
5
918
len_question
int64
21
890
len_target
int64
3
255
150,500
public void hideKeyboard ( ) { InputMethodManager inputMethodManager = ( InputMethodManager ) getContext ( ) . getApplicationContext ( ) . getSystemService ( Context . INPUT_METHOD_SERVICE ) ; inputMethodManager . hideSoftInputFromWindow ( mPhoneEdit . getWindowToken ( ) , 0 ) ; }
Hide keyboard from phoneEdit field
70
6
150,501
public void setDefault ( ) { try { TelephonyManager telephonyManager = ( TelephonyManager ) getContext ( ) . getSystemService ( Context . TELEPHONY_SERVICE ) ; String phone = telephonyManager . getLine1Number ( ) ; if ( phone != null && ! phone . isEmpty ( ) ) { this . setNumber ( phone ) ; } else { String iso = telephonyManager . getNetworkCountryIso ( ) ; setEmptyDefault ( iso ) ; } } catch ( SecurityException e ) { setEmptyDefault ( ) ; } }
Set default value Will try to retrieve phone number from device
120
11
150,502
public void setEmptyDefault ( String iso ) { if ( iso == null || iso . isEmpty ( ) ) { iso = DEFAULT_COUNTRY ; } int defaultIdx = mCountries . indexOfIso ( iso ) ; mSelectedCountry = mCountries . get ( defaultIdx ) ; mCountrySpinner . setSelection ( defaultIdx ) ; }
Set default value with
82
4
150,503
private void setHint ( ) { if ( mPhoneEdit != null && mSelectedCountry != null && mSelectedCountry . getIso ( ) != null ) { Phonenumber . PhoneNumber phoneNumber = mPhoneUtil . getExampleNumberForType ( mSelectedCountry . getIso ( ) , PhoneNumberUtil . PhoneNumberType . MOBILE ) ; if ( phoneNumber != null ) { mPhoneEdit . setHint ( mPhoneUtil . format ( phoneNumber , PhoneNumberUtil . PhoneNumberFormat . NATIONAL ) ) ; } } }
Set hint number for country
125
5
150,504
@ SuppressWarnings ( "unused" ) public Phonenumber . PhoneNumber getPhoneNumber ( ) { try { String iso = null ; if ( mSelectedCountry != null ) { iso = mSelectedCountry . getIso ( ) ; } return mPhoneUtil . parse ( mPhoneEdit . getText ( ) . toString ( ) , iso ) ; } catch ( NumberParseException ignored ) { return null ; } }
Get PhoneNumber object
96
4
150,505
@ SuppressWarnings ( "unused" ) public boolean isValid ( ) { Phonenumber . PhoneNumber phoneNumber = getPhoneNumber ( ) ; return phoneNumber != null && mPhoneUtil . isValidNumber ( phoneNumber ) ; }
Check if number is valid
54
5
150,506
@ SuppressWarnings ( "unused" ) public void setError ( CharSequence error , Drawable icon ) { mPhoneEdit . setError ( error , icon ) ; }
Sets an error message that will be displayed in a popup when the EditText has focus along with an icon displayed at the right - hand side .
40
30
150,507
public void setOnKeyboardDone ( final IntlPhoneInputListener listener ) { mPhoneEdit . setOnEditorActionListener ( new TextView . OnEditorActionListener ( ) { @ Override public boolean onEditorAction ( TextView v , int actionId , KeyEvent event ) { if ( actionId == EditorInfo . IME_ACTION_DONE ) { listener . done ( IntlPhoneInput . this , isValid ( ) ) ; } return false ; } } ) ; }
Set keyboard done listener to detect when the user click DONE on his keyboard
103
15
150,508
private synchronized Client allocateClient ( int targetPlayer , String description ) throws IOException { Client result = openClients . get ( targetPlayer ) ; if ( result == null ) { // We need to open a new connection. final DeviceAnnouncement deviceAnnouncement = DeviceFinder . getInstance ( ) . getLatestAnnouncementFrom ( targetPlayer ) ; if ( deviceAnnouncement == null ) { throw new IllegalStateException ( "Player " + targetPlayer + " could not be found " + description ) ; } final int dbServerPort = getPlayerDBServerPort ( targetPlayer ) ; if ( dbServerPort < 0 ) { throw new IllegalStateException ( "Player " + targetPlayer + " does not have a db server " + description ) ; } final byte posingAsPlayerNumber = ( byte ) chooseAskingPlayerNumber ( targetPlayer ) ; Socket socket = null ; try { InetSocketAddress address = new InetSocketAddress ( deviceAnnouncement . getAddress ( ) , dbServerPort ) ; socket = new Socket ( ) ; socket . connect ( address , socketTimeout . get ( ) ) ; socket . setSoTimeout ( socketTimeout . get ( ) ) ; result = new Client ( socket , targetPlayer , posingAsPlayerNumber ) ; } catch ( IOException e ) { try { socket . close ( ) ; } catch ( IOException e2 ) { logger . error ( "Problem closing socket for failed client creation attempt " + description ) ; } throw e ; } openClients . put ( targetPlayer , result ) ; useCounts . put ( result , 0 ) ; } useCounts . put ( result , useCounts . get ( result ) + 1 ) ; return result ; }
Finds or opens a client to talk to the dbserver on the specified player incrementing its use count .
363
23
150,509
private void closeClient ( Client client ) { logger . debug ( "Closing client {}" , client ) ; client . close ( ) ; openClients . remove ( client . targetPlayer ) ; useCounts . remove ( client ) ; timestamps . remove ( client ) ; }
When it is time to actually close a client do so and clean up the related data structures .
60
19
150,510
private synchronized void freeClient ( Client client ) { int current = useCounts . get ( client ) ; if ( current > 0 ) { timestamps . put ( client , System . currentTimeMillis ( ) ) ; // Mark that it was used until now. useCounts . put ( client , current - 1 ) ; if ( ( current == 1 ) && ( idleLimit . get ( ) == 0 ) ) { closeClient ( client ) ; // This was the last use, and we are supposed to immediately close idle clients. } } else { logger . error ( "Ignoring attempt to free a client that is not allocated: {}" , client ) ; } }
Decrements the client s use count and makes it eligible for closing if it is no longer in use .
141
21
150,511
public < T > T invokeWithClientSession ( int targetPlayer , ClientTask < T > task , String description ) throws Exception { if ( ! isRunning ( ) ) { throw new IllegalStateException ( "ConnectionManager is not running, aborting " + description ) ; } final Client client = allocateClient ( targetPlayer , description ) ; try { return task . useClient ( client ) ; } finally { freeClient ( client ) ; } }
Obtain a dbserver client session that can be used to perform some task call that task with the client then release the client .
92
27
150,512
@ SuppressWarnings ( "WeakerAccess" ) public int getPlayerDBServerPort ( int player ) { ensureRunning ( ) ; Integer result = dbServerPorts . get ( player ) ; if ( result == null ) { return - 1 ; } return result ; }
Look up the database server port reported by a given player . You should not use this port directly ; instead ask this class for a session to use while you communicate with the database .
60
36
150,513
private void requestPlayerDBServerPort ( DeviceAnnouncement announcement ) { Socket socket = null ; try { InetSocketAddress address = new InetSocketAddress ( announcement . getAddress ( ) , DB_SERVER_QUERY_PORT ) ; socket = new Socket ( ) ; socket . connect ( address , socketTimeout . get ( ) ) ; InputStream is = socket . getInputStream ( ) ; OutputStream os = socket . getOutputStream ( ) ; socket . setSoTimeout ( socketTimeout . get ( ) ) ; os . write ( DB_SERVER_QUERY_PACKET ) ; byte [ ] response = readResponseWithExpectedSize ( is , 2 , "database server port query packet" ) ; if ( response . length == 2 ) { setPlayerDBServerPort ( announcement . getNumber ( ) , ( int ) Util . bytesToNumber ( response , 0 , 2 ) ) ; } } catch ( java . net . ConnectException ce ) { logger . info ( "Player " + announcement . getNumber ( ) + " doesn't answer rekordbox port queries, connection refused. Won't attempt to request metadata." ) ; } catch ( Exception e ) { logger . warn ( "Problem requesting database server port number" , e ) ; } finally { if ( socket != null ) { try { socket . close ( ) ; } catch ( IOException e ) { logger . warn ( "Problem closing database server port request socket" , e ) ; } } } }
Query a player to determine the port on which its database server is running .
316
15
150,514
private byte [ ] receiveBytes ( InputStream is ) throws IOException { byte [ ] buffer = new byte [ 8192 ] ; int len = ( is . read ( buffer ) ) ; if ( len < 1 ) { throw new IOException ( "receiveBytes read " + len + " bytes." ) ; } return Arrays . copyOf ( buffer , len ) ; }
Receive some bytes from the player we are requesting metadata from .
79
13
150,515
@ SuppressWarnings ( "SameParameterValue" ) private byte [ ] readResponseWithExpectedSize ( InputStream is , int size , String description ) throws IOException { byte [ ] result = receiveBytes ( is ) ; if ( result . length != size ) { logger . warn ( "Expected " + size + " bytes while reading " + description + " response, received " + result . length ) ; } return result ; }
Receive an expected number of bytes from the player logging a warning if we get a different number of them .
93
22
150,516
private synchronized void closeIdleClients ( ) { List < Client > candidates = new LinkedList < Client > ( openClients . values ( ) ) ; logger . debug ( "Scanning for idle clients; " + candidates . size ( ) + " candidates." ) ; for ( Client client : candidates ) { if ( ( useCounts . get ( client ) < 1 ) && ( ( timestamps . get ( client ) + idleLimit . get ( ) * 1000 ) <= System . currentTimeMillis ( ) ) ) { logger . debug ( "Idle time reached for unused client {}" , client ) ; closeClient ( client ) ; } } }
Finds any clients which are not currently in use and which have been idle for longer than the idle timeout and closes them .
140
25
150,517
public synchronized void start ( ) throws SocketException { if ( ! isRunning ( ) ) { DeviceFinder . getInstance ( ) . addLifecycleListener ( lifecycleListener ) ; DeviceFinder . getInstance ( ) . addDeviceAnnouncementListener ( announcementListener ) ; DeviceFinder . getInstance ( ) . start ( ) ; for ( DeviceAnnouncement device : DeviceFinder . getInstance ( ) . getCurrentDevices ( ) ) { requestPlayerDBServerPort ( device ) ; } new Thread ( null , new Runnable ( ) { @ Override public void run ( ) { while ( isRunning ( ) ) { try { Thread . sleep ( 500 ) ; } catch ( InterruptedException e ) { logger . warn ( "Interrupted sleeping to close idle dbserver clients" ) ; } closeIdleClients ( ) ; } logger . info ( "Idle dbserver client closer shutting down." ) ; } } , "Idle dbserver client closer" ) . start ( ) ; running . set ( true ) ; deliverLifecycleAnnouncement ( logger , true ) ; } }
Start offering shared dbserver sessions .
240
8
150,518
public synchronized void stop ( ) { if ( isRunning ( ) ) { running . set ( false ) ; DeviceFinder . getInstance ( ) . removeDeviceAnnouncementListener ( announcementListener ) ; dbServerPorts . clear ( ) ; for ( Client client : openClients . values ( ) ) { try { client . close ( ) ; } catch ( Exception e ) { logger . warn ( "Problem closing " + client + " when stopping" , e ) ; } } openClients . clear ( ) ; useCounts . clear ( ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop offering shared dbserver sessions .
132
8
150,519
private SearchableItem buildSearchableItem ( Message menuItem ) { return new SearchableItem ( ( int ) ( ( NumberField ) menuItem . arguments . get ( 1 ) ) . getValue ( ) , ( ( StringField ) menuItem . arguments . get ( 3 ) ) . getValue ( ) ) ; }
Creates a searchable item that represents a metadata field found for a track .
67
16
150,520
private ColorItem buildColorItem ( Message menuItem ) { final int colorId = ( int ) ( ( NumberField ) menuItem . arguments . get ( 1 ) ) . getValue ( ) ; final String label = ( ( StringField ) menuItem . arguments . get ( 3 ) ) . getValue ( ) ; return buildColorItem ( colorId , label ) ; }
Creates a color item that represents a color field found for a track based on a dbserver message .
78
22
150,521
private ColorItem buildColorItem ( int colorId , String label ) { Color color ; String colorName ; switch ( colorId ) { case 0 : color = new Color ( 0 , 0 , 0 , 0 ) ; colorName = "No Color" ; break ; case 1 : color = Color . PINK ; colorName = "Pink" ; break ; case 2 : color = Color . RED ; colorName = "Red" ; break ; case 3 : color = Color . ORANGE ; colorName = "Orange" ; break ; case 4 : color = Color . YELLOW ; colorName = "Yellow" ; break ; case 5 : color = Color . GREEN ; colorName = "Green" ; break ; case 6 : color = Color . CYAN ; colorName = "Aqua" ; break ; case 7 : color = Color . BLUE ; colorName = "Blue" ; break ; case 8 : color = new Color ( 128 , 0 , 128 ) ; colorName = "Purple" ; break ; default : color = new Color ( 0 , 0 , 0 , 0 ) ; colorName = "Unknown Color" ; } return new ColorItem ( colorId , label , color , colorName ) ; }
Creates a color item that represents a color field fond for a track .
255
15
150,522
private void parseMetadataItem ( Message item ) { switch ( item . getMenuItemType ( ) ) { case TRACK_TITLE : title = ( ( StringField ) item . arguments . get ( 3 ) ) . getValue ( ) ; artworkId = ( int ) ( ( NumberField ) item . arguments . get ( 8 ) ) . getValue ( ) ; break ; case ARTIST : artist = buildSearchableItem ( item ) ; break ; case ORIGINAL_ARTIST : originalArtist = buildSearchableItem ( item ) ; break ; case REMIXER : remixer = buildSearchableItem ( item ) ; case ALBUM_TITLE : album = buildSearchableItem ( item ) ; break ; case LABEL : label = buildSearchableItem ( item ) ; break ; case DURATION : duration = ( int ) ( ( NumberField ) item . arguments . get ( 1 ) ) . getValue ( ) ; break ; case TEMPO : tempo = ( int ) ( ( NumberField ) item . arguments . get ( 1 ) ) . getValue ( ) ; break ; case COMMENT : comment = ( ( StringField ) item . arguments . get ( 3 ) ) . getValue ( ) ; break ; case KEY : key = buildSearchableItem ( item ) ; break ; case RATING : rating = ( int ) ( ( NumberField ) item . arguments . get ( 1 ) ) . getValue ( ) ; break ; case COLOR_NONE : case COLOR_AQUA : case COLOR_BLUE : case COLOR_GREEN : case COLOR_ORANGE : case COLOR_PINK : case COLOR_PURPLE : case COLOR_RED : case COLOR_YELLOW : color = buildColorItem ( item ) ; break ; case GENRE : genre = buildSearchableItem ( item ) ; break ; case DATE_ADDED : dateAdded = ( ( StringField ) item . arguments . get ( 3 ) ) . getValue ( ) ; break ; case YEAR : year = ( int ) ( ( NumberField ) item . arguments . get ( 1 ) ) . getValue ( ) ; break ; case BIT_RATE : bitRate = ( int ) ( ( NumberField ) item . arguments . get ( 1 ) ) . getValue ( ) ; break ; default : logger . warn ( "Ignoring track metadata item with unknown type: {}" , item ) ; } }
Processes one of the menu responses that jointly constitute the track metadata updating our fields accordingly .
518
18
150,523
@ SuppressWarnings ( "WeakerAccess" ) public ByteBuffer getRawData ( ) { if ( rawData != null ) { rawData . rewind ( ) ; return rawData . slice ( ) ; } return null ; }
Get the raw bytes of the beat grid as it was read over the network . This can be used to analyze fields that have not yet been reliably understood and is also used for storing the beat grid in a cache file . This is not available when the beat grid was loaded by Crate Digger .
51
59
150,524
private RekordboxAnlz . BeatGridTag findTag ( RekordboxAnlz anlzFile ) { for ( RekordboxAnlz . TaggedSection section : anlzFile . sections ( ) ) { if ( section . body ( ) instanceof RekordboxAnlz . BeatGridTag ) { return ( RekordboxAnlz . BeatGridTag ) section . body ( ) ; } } throw new IllegalArgumentException ( "No beat grid found inside analysis file " + anlzFile ) ; }
Helper function to find the beat grid section in a rekordbox track analysis file .
121
18
150,525
private int beatOffset ( int beatNumber ) { if ( beatCount == 0 ) { throw new IllegalStateException ( "There are no beats in this beat grid." ) ; } if ( beatNumber < 1 || beatNumber > beatCount ) { throw new IndexOutOfBoundsException ( "beatNumber (" + beatNumber + ") must be between 1 and " + beatCount ) ; } return beatNumber - 1 ; }
Calculate where within the beat grid array the information for the specified beat can be found . Yes this is a super simple calculation ; the main point of the method is to provide a nice exception when the beat is out of bounds .
89
47
150,526
@ SuppressWarnings ( "WeakerAccess" ) public int findBeatAtTime ( long milliseconds ) { int found = Arrays . binarySearch ( timeWithinTrackValues , milliseconds ) ; if ( found >= 0 ) { // An exact match, just change 0-based array index to 1-based beat number return found + 1 ; } else if ( found == - 1 ) { // We are before the first beat return found ; } else { // We are after some beat, report its beat number return - ( found + 1 ) ; } }
Finds the beat in which the specified track position falls .
115
12
150,527
public List < Message > requestTrackMenuFrom ( final SlotReference slotReference , final int sortOrder ) throws Exception { ConnectionManager . ClientTask < List < Message >> task = new ConnectionManager . ClientTask < List < Message > > ( ) { @ Override public List < Message > useClient ( Client client ) throws Exception { return MetadataFinder . getInstance ( ) . getFullTrackList ( slotReference . slot , client , sortOrder ) ; } } ; return ConnectionManager . getInstance ( ) . invokeWithClientSession ( slotReference . player , task , "requesting track menu" ) ; }
Ask the specified player for a Track menu .
128
9
150,528
public List < Message > requestArtistMenuFrom ( final SlotReference slotReference , final int sortOrder ) throws Exception { ConnectionManager . ClientTask < List < Message >> task = new ConnectionManager . ClientTask < List < Message > > ( ) { @ Override public List < Message > useClient ( Client client ) throws Exception { if ( client . tryLockingForMenuOperations ( MetadataFinder . MENU_TIMEOUT , TimeUnit . SECONDS ) ) { try { logger . debug ( "Requesting Artist menu." ) ; Message response = client . menuRequest ( Message . KnownType . ARTIST_MENU_REQ , Message . MenuIdentifier . MAIN_MENU , slotReference . slot , new NumberField ( sortOrder ) ) ; return client . renderMenuItems ( Message . MenuIdentifier . MAIN_MENU , slotReference . slot , CdjStatus . TrackType . REKORDBOX , response ) ; } finally { client . unlockForMenuOperations ( ) ; } } else { throw new TimeoutException ( "Unable to lock player for menu operations." ) ; } } } ; return ConnectionManager . getInstance ( ) . invokeWithClientSession ( slotReference . player , task , "requesting artist menu" ) ; }
Ask the specified player for an Artist menu .
270
9
150,529
public List < Message > requestFolderMenuFrom ( final SlotReference slotReference , final int sortOrder , final int folderId ) throws Exception { ConnectionManager . ClientTask < List < Message >> task = new ConnectionManager . ClientTask < List < Message > > ( ) { @ Override public List < Message > useClient ( Client client ) throws Exception { if ( client . tryLockingForMenuOperations ( MetadataFinder . MENU_TIMEOUT , TimeUnit . SECONDS ) ) { try { logger . debug ( "Requesting Key menu." ) ; Message response = client . menuRequestTyped ( Message . KnownType . FOLDER_MENU_REQ , Message . MenuIdentifier . MAIN_MENU , slotReference . slot , CdjStatus . TrackType . UNANALYZED , new NumberField ( sortOrder ) , new NumberField ( folderId ) , new NumberField ( 0xffffff ) ) ; return client . renderMenuItems ( Message . MenuIdentifier . MAIN_MENU , slotReference . slot , CdjStatus . TrackType . UNANALYZED , response ) ; } finally { client . unlockForMenuOperations ( ) ; } } else { throw new TimeoutException ( "Unable to lock player for menu operations." ) ; } } } ; return ConnectionManager . getInstance ( ) . invokeWithClientSession ( slotReference . player , task , "requesting folder menu" ) ; }
Ask the specified player for a Folder menu for exploring its raw filesystem . This is a request for unanalyzed items so we do a typed menu request .
312
31
150,530
public static Field read ( DataInputStream is ) throws IOException { final byte tag = is . readByte ( ) ; final Field result ; switch ( tag ) { case 0x0f : case 0x10 : case 0x11 : result = new NumberField ( tag , is ) ; break ; case 0x14 : result = new BinaryField ( is ) ; break ; case 0x26 : result = new StringField ( is ) ; break ; default : throw new IOException ( "Unable to read a field with type tag " + tag ) ; } logger . debug ( "..received> {}" , result ) ; return result ; }
Read a field from the supplied stream starting with the tag that identifies the type and reading enough to collect the corresponding value .
136
24
150,531
public void write ( WritableByteChannel channel ) throws IOException { logger . debug ( "..writing> {}" , this ) ; Util . writeFully ( getBytes ( ) , channel ) ; }
Write the field to the specified channel .
44
8
150,532
@ SuppressWarnings ( "WeakerAccess" ) public TrackMetadata requestMetadataFrom ( final CdjStatus status ) { if ( status . getTrackSourceSlot ( ) == CdjStatus . TrackSourceSlot . NO_TRACK || status . getRekordboxId ( ) == 0 ) { return null ; } final DataReference track = new DataReference ( status . getTrackSourcePlayer ( ) , status . getTrackSourceSlot ( ) , status . getRekordboxId ( ) ) ; return requestMetadataFrom ( track , status . getTrackType ( ) ) ; }
Given a status update from a CDJ find the metadata for the track that it has loaded if any . If there is an appropriate metadata cache will use that otherwise makes a query to the players dbserver .
128
42
150,533
@ SuppressWarnings ( "WeakerAccess" ) public TrackMetadata requestMetadataFrom ( final DataReference track , final CdjStatus . TrackType trackType ) { return requestMetadataInternal ( track , trackType , false ) ; }
Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID unless we have a metadata cache available for the specified media slot in which case that will be used instead .
53
42
150,534
private TrackMetadata requestMetadataInternal ( final DataReference track , final CdjStatus . TrackType trackType , final boolean failIfPassive ) { // First check if we are using cached data for this request. MetadataCache cache = getMetadataCache ( SlotReference . getSlotReference ( track ) ) ; if ( cache != null && trackType == CdjStatus . TrackType . REKORDBOX ) { return cache . getTrackMetadata ( null , track ) ; } // Then see if any registered metadata providers can offer it for us. final MediaDetails sourceDetails = getMediaDetailsFor ( track . getSlotReference ( ) ) ; if ( sourceDetails != null ) { final TrackMetadata provided = allMetadataProviders . getTrackMetadata ( sourceDetails , track ) ; if ( provided != null ) { return provided ; } } // At this point, unless we are allowed to actively request the data, we are done. We can always actively // request tracks from rekordbox. if ( passive . get ( ) && failIfPassive && track . slot != CdjStatus . TrackSourceSlot . COLLECTION ) { return null ; } // Use the dbserver protocol implementation to request the metadata. ConnectionManager . ClientTask < TrackMetadata > task = new ConnectionManager . ClientTask < TrackMetadata > ( ) { @ Override public TrackMetadata useClient ( Client client ) throws Exception { return queryMetadata ( track , trackType , client ) ; } } ; try { return ConnectionManager . getInstance ( ) . invokeWithClientSession ( track . player , task , "requesting metadata" ) ; } catch ( Exception e ) { logger . error ( "Problem requesting metadata, returning null" , e ) ; } return null ; }
Ask the specified player for metadata about the track in the specified slot with the specified rekordbox ID using cached media instead if it is available and possibly giving up if we are in passive mode .
373
40
150,535
TrackMetadata queryMetadata ( final DataReference track , final CdjStatus . TrackType trackType , final Client client ) throws IOException , InterruptedException , TimeoutException { // Send the metadata menu request if ( client . tryLockingForMenuOperations ( 20 , TimeUnit . SECONDS ) ) { try { final Message . KnownType requestType = ( trackType == CdjStatus . TrackType . REKORDBOX ) ? Message . KnownType . REKORDBOX_METADATA_REQ : Message . KnownType . UNANALYZED_METADATA_REQ ; final Message response = client . menuRequestTyped ( requestType , Message . MenuIdentifier . MAIN_MENU , track . slot , trackType , new NumberField ( track . rekordboxId ) ) ; final long count = response . getMenuResultsCount ( ) ; if ( count == Message . NO_MENU_RESULTS_AVAILABLE ) { return null ; } // Gather the cue list and all the metadata menu items final List < Message > items = client . renderMenuItems ( Message . MenuIdentifier . MAIN_MENU , track . slot , trackType , response ) ; final CueList cueList = getCueList ( track . rekordboxId , track . slot , client ) ; return new TrackMetadata ( track , trackType , items , cueList ) ; } finally { client . unlockForMenuOperations ( ) ; } } else { throw new TimeoutException ( "Unable to lock the player for menu operations" ) ; } }
Request metadata for a specific track ID given a dbserver connection to a player that has already been set up . Separated into its own method so it could be used multiple times with the same connection when gathering all track metadata .
341
47
150,536
CueList getCueList ( int rekordboxId , CdjStatus . TrackSourceSlot slot , Client client ) throws IOException { Message response = client . simpleRequest ( Message . KnownType . CUE_LIST_REQ , null , client . buildRMST ( Message . MenuIdentifier . DATA , slot ) , new NumberField ( rekordboxId ) ) ; if ( response . knownType == Message . KnownType . CUE_LIST ) { return new CueList ( response ) ; } logger . error ( "Unexpected response type when requesting cue list: {}" , response ) ; return null ; }
Requests the cue list for a specific track ID given a dbserver connection to a player that has already been set up .
134
26
150,537
List < Message > getFullTrackList ( final CdjStatus . TrackSourceSlot slot , final Client client , final int sortOrder ) throws IOException , InterruptedException , TimeoutException { // Send the metadata menu request if ( client . tryLockingForMenuOperations ( MENU_TIMEOUT , TimeUnit . SECONDS ) ) { try { Message response = client . menuRequest ( Message . KnownType . TRACK_MENU_REQ , Message . MenuIdentifier . MAIN_MENU , slot , new NumberField ( sortOrder ) ) ; final long count = response . getMenuResultsCount ( ) ; if ( count == Message . NO_MENU_RESULTS_AVAILABLE || count == 0 ) { return Collections . emptyList ( ) ; } // Gather all the metadata menu items return client . renderMenuItems ( Message . MenuIdentifier . MAIN_MENU , slot , CdjStatus . TrackType . REKORDBOX , response ) ; } finally { client . unlockForMenuOperations ( ) ; } } else { throw new TimeoutException ( "Unable to lock the player for menu operations" ) ; } }
Request the list of all tracks in the specified slot given a dbserver connection to a player that has already been set up .
247
26
150,538
private void clearDeck ( CdjStatus update ) { if ( hotCache . remove ( DeckReference . getDeckReference ( update . getDeviceNumber ( ) , 0 ) ) != null ) { deliverTrackMetadataUpdate ( update . getDeviceNumber ( ) , null ) ; } }
We have received an update that invalidates any previous metadata for that player so clear it out 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 .
61
56
150,539
private void clearMetadata ( 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 ) { deliverTrackMetadataUpdate ( player , null ) ; // Inform listeners the metadata is gone. } } } }
We have received notification that a device is no longer on the network so clear out its metadata .
110
19
150,540
private void updateMetadata ( CdjStatus update , TrackMetadata data ) { hotCache . put ( DeckReference . getDeckReference ( update . getDeviceNumber ( ) , 0 ) , data ) ; // Main deck if ( data . getCueList ( ) != null ) { // Update the cache with any hot cues in this track as well for ( CueList . Entry entry : data . getCueList ( ) . entries ) { if ( entry . hotCueNumber != 0 ) { hotCache . put ( DeckReference . getDeckReference ( update . getDeviceNumber ( ) , entry . hotCueNumber ) , data ) ; } } } deliverTrackMetadataUpdate ( update . getDeviceNumber ( ) , data ) ; }
We have obtained metadata for a device so store it and alert any listeners .
159
15
150,541
public Map < DeckReference , TrackMetadata > getLoadedTracks ( ) { ensureRunning ( ) ; // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < DeckReference , TrackMetadata > ( hotCache ) ) ; }
Get the metadata of all tracks currently loaded in any player either on the play deck or in a hot cue .
65
22
150,542
public void attachMetadataCache ( SlotReference slot , File file ) throws IOException { ensureRunning ( ) ; if ( slot . player < 1 || slot . player > 4 || DeviceFinder . getInstance ( ) . getLatestAnnouncementFrom ( slot . player ) == null ) { throw new IllegalArgumentException ( "unable to attach metadata cache for player " + slot . player ) ; } if ( ( slot . slot != CdjStatus . TrackSourceSlot . USB_SLOT ) && ( slot . slot != CdjStatus . TrackSourceSlot . SD_SLOT ) ) { throw new IllegalArgumentException ( "unable to attach metadata cache for slot " + slot . slot ) ; } MetadataCache cache = new MetadataCache ( file ) ; final MediaDetails slotDetails = getMediaDetailsFor ( slot ) ; if ( cache . sourceMedia != null && slotDetails != null ) { if ( ! slotDetails . hashKey ( ) . equals ( cache . sourceMedia . hashKey ( ) ) ) { throw new IllegalArgumentException ( "Cache was created for different media (" + cache . sourceMedia . hashKey ( ) + ") than is in the slot (" + slotDetails . hashKey ( ) + ")." ) ; } if ( slotDetails . hasChanged ( cache . sourceMedia ) ) { logger . warn ( "Media has changed (" + slotDetails + ") since cache was created (" + cache . sourceMedia + "). Attaching anyway as instructed." ) ; } } attachMetadataCacheInternal ( slot , cache ) ; }
Attach a metadata cache file to a particular player media slot so the cache will be used instead of querying the player for metadata . This supports operation with metadata during shows where DJs are using all four player numbers and heavily cross - linking between them .
330
49
150,543
void attachMetadataCacheInternal ( SlotReference slot , MetadataCache cache ) { MetadataCache oldCache = metadataCacheFiles . put ( slot , cache ) ; if ( oldCache != null ) { try { oldCache . close ( ) ; } catch ( IOException e ) { logger . error ( "Problem closing previous metadata cache" , e ) ; } } deliverCacheUpdate ( slot , cache ) ; }
Finishes the process of attaching a metadata cache file once it has been opened and validated .
86
18
150,544
public void detachMetadataCache ( SlotReference slot ) { MetadataCache oldCache = metadataCacheFiles . remove ( slot ) ; if ( oldCache != null ) { try { oldCache . close ( ) ; } catch ( IOException e ) { logger . error ( "Problem closing metadata cache" , e ) ; } deliverCacheUpdate ( slot , null ) ; } }
Removes any metadata cache file that might have been assigned to a particular player media slot so metadata will be looked up from the player itself .
78
28
150,545
public List < File > getAutoAttachCacheFiles ( ) { ArrayList < File > currentFiles = new ArrayList < File > ( autoAttachCacheFiles ) ; Collections . sort ( currentFiles , new Comparator < File > ( ) { @ Override public int compare ( File o1 , File o2 ) { return o1 . getName ( ) . compareTo ( o2 . getName ( ) ) ; } } ) ; return Collections . unmodifiableList ( currentFiles ) ; }
Get the metadata cache files that are currently configured to be automatically attached when matching media is mounted in a player on the network .
104
25
150,546
private void flushHotCacheSlot ( SlotReference slot ) { // Iterate over a copy to avoid concurrent modification issues for ( Map . Entry < DeckReference , TrackMetadata > entry : new HashMap < DeckReference , TrackMetadata > ( hotCache ) . entrySet ( ) ) { if ( slot == SlotReference . getSlotReference ( entry . getValue ( ) . trackReference ) ) { logger . debug ( "Evicting cached metadata in response to unmount report {}" , entry . getValue ( ) ) ; hotCache . remove ( entry . getKey ( ) ) ; } } }
Discards any tracks from the hot cache that were loaded from a now - unmounted media slot because they are no longer valid .
126
26
150,547
private void recordMount ( SlotReference slot ) { if ( mediaMounts . add ( slot ) ) { deliverMountUpdate ( slot , true ) ; } if ( ! mediaDetails . containsKey ( slot ) ) { try { VirtualCdj . getInstance ( ) . sendMediaQuery ( slot ) ; } catch ( Exception e ) { logger . warn ( "Problem trying to request media details for " + slot , e ) ; } } }
Records that there is media mounted in a particular media player slot updating listeners if this is a change . Also send a query to the player requesting details about the media mounted in that slot if we don t already have that information .
92
46
150,548
private void removeMount ( SlotReference slot ) { mediaDetails . remove ( slot ) ; if ( mediaMounts . remove ( slot ) ) { deliverMountUpdate ( slot , false ) ; } }
Records that there is no media mounted in a particular media player slot updating listeners if this is a change and clearing any affected items from our in - memory caches .
41
33
150,549
private void deliverMountUpdate ( SlotReference slot , boolean mounted ) { if ( mounted ) { logger . info ( "Reporting media mounted in " + slot ) ; } else { logger . info ( "Reporting media removed from " + slot ) ; } for ( final MountListener listener : getMountListeners ( ) ) { try { if ( mounted ) { listener . mediaMounted ( slot ) ; } else { listener . mediaUnmounted ( slot ) ; } } catch ( Throwable t ) { logger . warn ( "Problem delivering mount update to listener" , t ) ; } } if ( mounted ) { MetadataCache . tryAutoAttaching ( slot ) ; } }
Send a mount update announcement to all registered listeners and see if we can auto - attach a media cache file .
140
22
150,550
private void deliverCacheUpdate ( SlotReference slot , MetadataCache cache ) { for ( final MetadataCacheListener listener : getCacheListeners ( ) ) { try { if ( cache == null ) { listener . cacheDetached ( slot ) ; } else { listener . cacheAttached ( slot , cache ) ; } } catch ( Throwable t ) { logger . warn ( "Problem delivering metadata cache update to listener" , t ) ; } } }
Send a metadata cache update announcement to all registered listeners .
94
11
150,551
private void deliverTrackMetadataUpdate ( int player , TrackMetadata metadata ) { if ( ! getTrackMetadataListeners ( ) . isEmpty ( ) ) { final TrackMetadataUpdate update = new TrackMetadataUpdate ( player , metadata ) ; for ( final TrackMetadataListener listener : getTrackMetadataListeners ( ) ) { try { listener . metadataChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering track metadata update to listener" , t ) ; } } } }
Send a track metadata update announcement to all registered listeners .
111
11
150,552
private void addMetadataProviderForMedia ( String key , MetadataProvider provider ) { if ( ! metadataProviders . containsKey ( key ) ) { metadataProviders . put ( key , Collections . newSetFromMap ( new ConcurrentHashMap < MetadataProvider , Boolean > ( ) ) ) ; } Set < MetadataProvider > providers = metadataProviders . get ( key ) ; providers . add ( provider ) ; }
Internal method that adds a metadata provider to the set associated with a particular hash key creating the set if needed .
90
22
150,553
public void removeMetadataProvider ( MetadataProvider provider ) { for ( Set < MetadataProvider > providers : metadataProviders . values ( ) ) { providers . remove ( provider ) ; } }
Removes a metadata provider so it will no longer be consulted to provide metadata for tracks loaded from any media .
41
22
150,554
public Set < MetadataProvider > getMetadataProviders ( MediaDetails sourceMedia ) { String key = ( sourceMedia == null ) ? "" : sourceMedia . hashKey ( ) ; Set < MetadataProvider > result = metadataProviders . get ( key ) ; if ( result == null ) { return Collections . emptySet ( ) ; } return Collections . unmodifiableSet ( new HashSet < MetadataProvider > ( result ) ) ; }
Get the set of metadata providers that can offer metadata for tracks loaded from the specified media .
94
18
150,555
private int getColorWaveformBits ( final ByteBuffer waveBytes , final int segment ) { final int base = ( segment * 2 ) ; final int big = Util . unsign ( waveBytes . get ( base ) ) ; final int small = Util . unsign ( waveBytes . get ( base + 1 ) ) ; return big * 256 + small ; }
Color waveforms are represented by a series of sixteen bit integers into which color and height information are packed . This function returns the integer corresponding to a particular half - frame in the waveform .
78
38
150,556
private static void addCacheFormatEntry ( List < Message > trackListEntries , int playlistId , ZipOutputStream zos ) throws IOException { // Add a marker so we can recognize this as a metadata archive. I would use the ZipFile comment, but // that is not available until Java 7, and Beat Link is supposed to be backwards compatible with Java 6. // Since we are doing this anyway, we can also provide information about the nature of the cache, and // how many metadata entries it contains, which is useful for auto-attachment. zos . putNextEntry ( new ZipEntry ( CACHE_FORMAT_ENTRY ) ) ; String formatEntry = CACHE_FORMAT_IDENTIFIER + ":" + playlistId + ":" + trackListEntries . size ( ) ; zos . write ( formatEntry . getBytes ( "UTF-8" ) ) ; }
Add a marker so we can recognize this as a metadata archive . I would use the ZipFile comment but that is not available until Java 7 and Beat Link is supposed to be backwards compatible with Java 6 . Since we are doing this anyway we can also provide information about the nature of the cache and how many metadata entries it contains which is useful for auto - attachment .
190
73
150,557
private static void addCacheDetailsEntry ( SlotReference slot , ZipOutputStream zos , WritableByteChannel channel ) throws IOException { // Record the details of the media being cached, to make it easier to recognize now that we can. MediaDetails details = MetadataFinder . getInstance ( ) . getMediaDetailsFor ( slot ) ; if ( details != null ) { zos . putNextEntry ( new ZipEntry ( CACHE_DETAILS_ENTRY ) ) ; Util . writeFully ( details . getRawBytes ( ) , channel ) ; } }
Record the details of the media being cached to make it easier to recognize now that we have access to that information .
122
23
150,558
private String getCacheFormatEntry ( ) throws IOException { ZipEntry zipEntry = zipFile . getEntry ( CACHE_FORMAT_ENTRY ) ; InputStream is = zipFile . getInputStream ( zipEntry ) ; try { Scanner s = new Scanner ( is , "UTF-8" ) . useDelimiter ( "\\A" ) ; String tag = null ; if ( s . hasNext ( ) ) tag = s . next ( ) ; return tag ; } finally { is . close ( ) ; } }
Find and read the cache format entry in a metadata cache file .
115
13
150,559
public List < Integer > getTrackIds ( ) { ArrayList < Integer > results = new ArrayList < Integer > ( trackCount ) ; Enumeration < ? extends ZipEntry > entries = zipFile . entries ( ) ; while ( entries . hasMoreElements ( ) ) { ZipEntry entry = entries . nextElement ( ) ; if ( entry . getName ( ) . startsWith ( CACHE_METADATA_ENTRY_PREFIX ) ) { String idPart = entry . getName ( ) . substring ( CACHE_METADATA_ENTRY_PREFIX . length ( ) ) ; if ( idPart . length ( ) > 0 ) { results . add ( Integer . valueOf ( idPart ) ) ; } } } return Collections . unmodifiableList ( results ) ; }
Returns a list of the rekordbox IDs of the tracks contained in the cache .
175
18
150,560
public static void createMetadataCache ( SlotReference slot , int playlistId , File cache ) throws Exception { createMetadataCache ( slot , playlistId , cache , null ) ; }
Creates a metadata cache archive file of all tracks in the specified slot on the specified player . Any previous contents of the specified file will be replaced .
38
30
150,561
static void tryAutoAttaching ( final SlotReference slot ) { if ( ! MetadataFinder . getInstance ( ) . getMountedMediaSlots ( ) . contains ( slot ) ) { logger . error ( "Unable to auto-attach cache to empty slot {}" , slot ) ; return ; } if ( MetadataFinder . getInstance ( ) . getMetadataCache ( slot ) != null ) { logger . info ( "Not auto-attaching to slot {}; already has a cache attached." , slot ) ; return ; } if ( MetadataFinder . getInstance ( ) . getAutoAttachCacheFiles ( ) . isEmpty ( ) ) { logger . debug ( "No auto-attach files configured." ) ; return ; } new Thread ( new Runnable ( ) { @ Override public void run ( ) { try { Thread . sleep ( 5 ) ; // Give us a chance to find out what type of media is in the new mount. final MediaDetails details = MetadataFinder . getInstance ( ) . getMediaDetailsFor ( slot ) ; if ( details != null && details . mediaType == CdjStatus . TrackType . REKORDBOX ) { // First stage attempt: See if we can match based on stored media details, which is both more reliable and // less disruptive than trying to sample the player database to compare entries. boolean attached = false ; for ( File file : MetadataFinder . getInstance ( ) . getAutoAttachCacheFiles ( ) ) { final MetadataCache cache = new MetadataCache ( file ) ; try { if ( cache . sourceMedia != null && cache . sourceMedia . hashKey ( ) . equals ( details . hashKey ( ) ) ) { // We found a solid match, no need to probe tracks. final boolean changed = cache . sourceMedia . hasChanged ( details ) ; logger . info ( "Auto-attaching metadata cache " + cache . getName ( ) + " to slot " + slot + " based on media details " + ( changed ? "(changed since created)!" : "(unchanged)." ) ) ; MetadataFinder . getInstance ( ) . attachMetadataCacheInternal ( slot , cache ) ; attached = true ; return ; } } finally { if ( ! attached ) { cache . close ( ) ; } } } // Could not match based on media details; fall back to older method based on probing track metadata. ConnectionManager . ClientTask < Object > task = new ConnectionManager . ClientTask < Object > ( ) { @ Override public Object useClient ( Client client ) throws Exception { tryAutoAttachingWithConnection ( slot , client ) ; return null ; } } ; ConnectionManager . getInstance ( ) . invokeWithClientSession ( slot . player , task , "trying to auto-attach metadata cache" ) ; } } catch ( Exception e ) { logger . error ( "Problem trying to auto-attach metadata cache for slot " + slot , e ) ; } } } , "Metadata cache file auto-attachment attempt" ) . start ( ) ; }
See if there is an auto - attach cache file that seems to match the media in the specified slot and if so attach it .
644
26
150,562
private static Map < Integer , LinkedList < MetadataCache > > gatherCandidateAttachmentGroups ( ) { Map < Integer , LinkedList < MetadataCache > > candidateGroups = new TreeMap < Integer , LinkedList < MetadataCache > > ( ) ; final Iterator < File > iterator = MetadataFinder . getInstance ( ) . getAutoAttachCacheFiles ( ) . iterator ( ) ; while ( iterator . hasNext ( ) ) { final File file = iterator . next ( ) ; try { final MetadataCache candidate = new MetadataCache ( file ) ; if ( candidateGroups . get ( candidate . sourcePlaylist ) == null ) { candidateGroups . put ( candidate . sourcePlaylist , new LinkedList < MetadataCache > ( ) ) ; } candidateGroups . get ( candidate . sourcePlaylist ) . add ( candidate ) ; } catch ( Exception e ) { logger . error ( "Unable to open metadata cache file " + file + ", discarding" , e ) ; iterator . remove ( ) ; } } return candidateGroups ; }
Groups all of the metadata cache files that are candidates for auto - attachment to player slots into lists that are keyed by the playlist ID used to create the cache file . Files that cache all tracks have a playlist ID of 0 .
233
47
150,563
private static int findTrackIdAtOffset ( SlotReference slot , Client client , int offset ) throws IOException { Message entry = client . renderMenuItems ( Message . MenuIdentifier . MAIN_MENU , slot . slot , CdjStatus . TrackType . REKORDBOX , offset , 1 ) . get ( 0 ) ; if ( entry . getMenuItemType ( ) == Message . MenuItemType . UNKNOWN ) { logger . warn ( "Encountered unrecognized track list entry item type: {}" , entry ) ; } return ( int ) ( ( NumberField ) entry . arguments . get ( 1 ) ) . getValue ( ) ; }
As part of checking whether a metadata cache can be auto - mounted for a particular media slot this method looks up the track at the specified offset within the player s track list and returns its rekordbox ID .
139
43
150,564
private boolean isPacketLongEnough ( DatagramPacket packet , int expectedLength , String name ) { final int length = packet . getLength ( ) ; if ( length < expectedLength ) { logger . warn ( "Ignoring too-short " + name + " packet; expecting " + expectedLength + " bytes and got " + length + "." ) ; return false ; } if ( length > expectedLength ) { logger . warn ( "Processing too-long " + name + " packet; expecting " + expectedLength + " bytes and got " + length + "." ) ; } return true ; }
Helper method to check that we got the right size packet .
128
12
150,565
public synchronized void stop ( ) { if ( isRunning ( ) ) { socket . get ( ) . close ( ) ; socket . set ( null ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop listening for beats .
47
5
150,566
private void deliverSyncCommand ( byte command ) { for ( final SyncListener listener : getSyncListeners ( ) ) { try { switch ( command ) { case 0x01 : listener . becomeMaster ( ) ; case 0x10 : listener . setSyncMode ( true ) ; break ; case 0x20 : listener . setSyncMode ( false ) ; break ; } } catch ( Throwable t ) { logger . warn ( "Problem delivering sync command to listener" , t ) ; } } }
Send a sync command to all registered listeners .
104
9
150,567
private void deliverMasterYieldCommand ( int toPlayer ) { for ( final MasterHandoffListener listener : getMasterHandoffListeners ( ) ) { try { listener . yieldMasterTo ( toPlayer ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering master yield command to listener" , t ) ; } } }
Send a master handoff yield command to all registered listeners .
72
12
150,568
private void deliverMasterYieldResponse ( int fromPlayer , boolean yielded ) { for ( final MasterHandoffListener listener : getMasterHandoffListeners ( ) ) { try { listener . yieldResponse ( fromPlayer , yielded ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering master yield response to listener" , t ) ; } } }
Send a master handoff yield response to all registered listeners .
76
12
150,569
private void deliverOnAirUpdate ( Set < Integer > audibleChannels ) { for ( final OnAirListener listener : getOnAirListeners ( ) ) { try { listener . channelsOnAir ( audibleChannels ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering channels on-air update to listener" , t ) ; } } }
Send a channels on - air update to all registered listeners .
76
12
150,570
private void deliverFaderStartCommand ( Set < Integer > playersToStart , Set < Integer > playersToStop ) { for ( final FaderStartListener listener : getFaderStartListeners ( ) ) { try { listener . fadersChanged ( playersToStart , playersToStop ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering fader start command to listener" , t ) ; } } }
Send a fader start command to all registered listeners .
90
11
150,571
public void write ( WritableByteChannel channel ) throws IOException { logger . debug ( "Writing> {}" , this ) ; for ( Field field : fields ) { field . write ( channel ) ; } }
Writes the message to the specified channel for example when creating metadata cache files .
44
16
150,572
public final void setFindDetails ( boolean findDetails ) { this . findDetails . set ( findDetails ) ; if ( findDetails ) { primeCache ( ) ; // Get details for any tracks that were already loaded on players. } else { // Inform our listeners, on the proper thread, that the detailed waveforms are no longer available final Set < DeckReference > dyingCache = new HashSet < DeckReference > ( detailHotCache . keySet ( ) ) ; detailHotCache . clear ( ) ; SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( DeckReference deck : dyingCache ) { deliverWaveformDetailUpdate ( deck . player , null ) ; } } } ) ; } }
Set whether we should retrieve the waveform details in addition to the waveform previews .
158
17
150,573
public final void setColorPreferred ( boolean preferColor ) { if ( this . preferColor . compareAndSet ( ! preferColor , preferColor ) && isRunning ( ) ) { stop ( ) ; try { start ( ) ; } catch ( Exception e ) { logger . error ( "Unexplained exception restarting; we had been running already!" , e ) ; } } }
Set whether we should obtain color versions of waveforms and previews when they are available . This will only affect waveforms loaded after the setting has been changed . If this changes the setting and we were running stop and restart in order to flush and reload the correct waveform versions .
81
55
150,574
private void clearDeckPreview ( TrackMetadataUpdate update ) { if ( previewHotCache . remove ( DeckReference . getDeckReference ( update . player , 0 ) ) != null ) { deliverWaveformPreviewUpdate ( update . player , null ) ; } }
We have received an update that invalidates the waveform preview 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 .
56
56
150,575
private void clearDeckDetail ( TrackMetadataUpdate update ) { if ( detailHotCache . remove ( DeckReference . getDeckReference ( update . player , 0 ) ) != null ) { deliverWaveformDetailUpdate ( update . player , null ) ; } }
We have received an update that invalidates the waveform detail 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 .
58
56
150,576
private void clearWaveforms ( DeviceAnnouncement announcement ) { final int player = announcement . getNumber ( ) ; // Iterate over a copy to avoid concurrent modification issues for ( DeckReference deck : new HashSet < DeckReference > ( previewHotCache . keySet ( ) ) ) { if ( deck . player == player ) { previewHotCache . remove ( deck ) ; if ( deck . hotCue == 0 ) { deliverWaveformPreviewUpdate ( player , null ) ; // Inform listeners that preview is gone. } } } // Again iterate over a copy to avoid concurrent modification issues for ( DeckReference deck : new HashSet < DeckReference > ( detailHotCache . keySet ( ) ) ) { if ( deck . player == player ) { detailHotCache . remove ( deck ) ; if ( deck . hotCue == 0 ) { deliverWaveformDetailUpdate ( player , null ) ; // Inform listeners that detail is gone. } } } }
We have received notification that a device is no longer on the network so clear out all its waveforms .
201
21
150,577
private void updatePreview ( TrackMetadataUpdate update , WaveformPreview preview ) { previewHotCache . put ( DeckReference . getDeckReference ( update . player , 0 ) , preview ) ; // 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 ) { previewHotCache . put ( DeckReference . getDeckReference ( update . player , entry . hotCueNumber ) , preview ) ; } } } deliverWaveformPreviewUpdate ( update . player , preview ) ; }
We have obtained a waveform preview for a device so store it and alert any listeners .
153
18
150,578
private void updateDetail ( TrackMetadataUpdate update , WaveformDetail detail ) { detailHotCache . put ( DeckReference . getDeckReference ( update . player , 0 ) , detail ) ; // 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 ) { detailHotCache . put ( DeckReference . getDeckReference ( update . player , entry . hotCueNumber ) , detail ) ; } } } deliverWaveformDetailUpdate ( update . player , detail ) ; }
We have obtained waveform detail for a device so store it and alert any listeners .
156
17
150,579
@ SuppressWarnings ( "WeakerAccess" ) public Map < DeckReference , WaveformPreview > getLoadedPreviews ( ) { ensureRunning ( ) ; // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < DeckReference , WaveformPreview > ( previewHotCache ) ) ; }
Get the waveform previews available for all tracks currently loaded in any player either on the play deck or in a hot cue .
79
25
150,580
@ SuppressWarnings ( "WeakerAccess" ) public Map < DeckReference , WaveformDetail > getLoadedDetails ( ) { ensureRunning ( ) ; if ( ! isFindingDetails ( ) ) { throw new IllegalStateException ( "WaveformFinder is not configured to find waveform details." ) ; } // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < DeckReference , WaveformDetail > ( detailHotCache ) ) ; }
Get the waveform details available for all tracks currently loaded in any player either on the play deck or in a hot cue .
113
25
150,581
private WaveformPreview requestPreviewInternal ( final DataReference trackReference , final boolean failIfPassive ) { // First check if we are using cached data for this slot MetadataCache cache = MetadataFinder . getInstance ( ) . getMetadataCache ( SlotReference . getSlotReference ( trackReference ) ) ; if ( cache != null ) { return cache . getWaveformPreview ( null , trackReference ) ; } // Then see if any registered metadata providers can offer it for us. final MediaDetails sourceDetails = MetadataFinder . getInstance ( ) . getMediaDetailsFor ( trackReference . getSlotReference ( ) ) ; if ( sourceDetails != null ) { final WaveformPreview provided = MetadataFinder . getInstance ( ) . allMetadataProviders . getWaveformPreview ( sourceDetails , trackReference ) ; if ( provided != null ) { return provided ; } } // At this point, unless we are allowed to actively request the data, we are done. We can always actively // request tracks from rekordbox. if ( MetadataFinder . getInstance ( ) . isPassive ( ) && failIfPassive && trackReference . slot != CdjStatus . TrackSourceSlot . COLLECTION ) { return null ; } // We have to actually request the preview using the dbserver protocol. ConnectionManager . ClientTask < WaveformPreview > task = new ConnectionManager . ClientTask < WaveformPreview > ( ) { @ Override public WaveformPreview useClient ( Client client ) throws Exception { return getWaveformPreview ( trackReference . rekordboxId , SlotReference . getSlotReference ( trackReference ) , client ) ; } } ; try { return ConnectionManager . getInstance ( ) . invokeWithClientSession ( trackReference . player , task , "requesting waveform preview" ) ; } catch ( Exception e ) { logger . error ( "Problem requesting waveform preview, returning null" , e ) ; } return null ; }
Ask the specified player for the waveform preview in the specified slot with the specified rekordbox ID using cached media instead if it is available and possibly giving up if we are in passive mode .
415
40
150,582
public WaveformPreview requestWaveformPreviewFrom ( final DataReference dataReference ) { ensureRunning ( ) ; for ( WaveformPreview cached : previewHotCache . values ( ) ) { if ( cached . dataReference . equals ( dataReference ) ) { // Found a hot cue hit, use it. return cached ; } } return requestPreviewInternal ( dataReference , false ) ; }
Ask the specified player for the specified waveform preview from the specified media slot first checking if we have a cached copy .
79
24
150,583
WaveformPreview getWaveformPreview ( int rekordboxId , SlotReference slot , Client client ) throws IOException { final NumberField idField = new NumberField ( rekordboxId ) ; // First try to get the NXS2-style color waveform if we are supposed to. if ( preferColor . get ( ) ) { try { Message response = client . simpleRequest ( Message . KnownType . ANLZ_TAG_REQ , Message . KnownType . ANLZ_TAG , client . buildRMST ( Message . MenuIdentifier . MAIN_MENU , slot . slot ) , idField , new NumberField ( Message . ANLZ_FILE_TAG_COLOR_WAVEFORM_PREVIEW ) , new NumberField ( Message . ALNZ_FILE_TYPE_EXT ) ) ; return new WaveformPreview ( new DataReference ( slot , rekordboxId ) , response ) ; } catch ( Exception e ) { logger . info ( "No color waveform preview available for slot " + slot + ", id " + rekordboxId + "; requesting blue version." , e ) ; } } Message response = client . simpleRequest ( Message . KnownType . WAVE_PREVIEW_REQ , Message . KnownType . WAVE_PREVIEW , client . buildRMST ( Message . MenuIdentifier . DATA , slot . slot ) , NumberField . WORD_1 , idField , NumberField . WORD_0 ) ; return new WaveformPreview ( new DataReference ( slot , rekordboxId ) , response ) ; }
Requests the waveform preview for a specific track ID given a connection to a player that has already been set up .
338
24
150,584
public WaveformDetail requestWaveformDetailFrom ( final DataReference dataReference ) { ensureRunning ( ) ; for ( WaveformDetail cached : detailHotCache . values ( ) ) { if ( cached . dataReference . equals ( dataReference ) ) { // Found a hot cue hit, use it. return cached ; } } return requestDetailInternal ( dataReference , false ) ; }
Ask the specified player for the specified waveform detail from the specified media slot first checking if we have a cached copy .
83
24
150,585
WaveformDetail getWaveformDetail ( int rekordboxId , SlotReference slot , Client client ) throws IOException { final NumberField idField = new NumberField ( rekordboxId ) ; // First try to get the NXS2-style color waveform if we are supposed to. if ( preferColor . get ( ) ) { try { Message response = client . simpleRequest ( Message . KnownType . ANLZ_TAG_REQ , Message . KnownType . ANLZ_TAG , client . buildRMST ( Message . MenuIdentifier . MAIN_MENU , slot . slot ) , idField , new NumberField ( Message . ANLZ_FILE_TAG_COLOR_WAVEFORM_DETAIL ) , new NumberField ( Message . ALNZ_FILE_TYPE_EXT ) ) ; return new WaveformDetail ( new DataReference ( slot , rekordboxId ) , response ) ; } catch ( Exception e ) { logger . info ( "No color waveform available for slot " + slot + ", id " + rekordboxId + "; requesting blue version." , e ) ; } } Message response = client . simpleRequest ( Message . KnownType . WAVE_DETAIL_REQ , Message . KnownType . WAVE_DETAIL , client . buildRMST ( Message . MenuIdentifier . MAIN_MENU , slot . slot ) , idField , NumberField . WORD_0 ) ; return new WaveformDetail ( new DataReference ( slot , rekordboxId ) , response ) ; }
Requests the waveform detail for a specific track ID given a connection to a player that has already been set up .
340
24
150,586
private void deliverWaveformPreviewUpdate ( final int player , final WaveformPreview preview ) { final Set < WaveformListener > listeners = getWaveformListeners ( ) ; if ( ! listeners . isEmpty ( ) ) { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { final WaveformPreviewUpdate update = new WaveformPreviewUpdate ( player , preview ) ; for ( final WaveformListener listener : listeners ) { try { listener . previewChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering waveform preview update to listener" , t ) ; } } } } ) ; } }
Send a waveform preview update announcement to all registered listeners .
143
12
150,587
private void deliverWaveformDetailUpdate ( final int player , final WaveformDetail detail ) { if ( ! getWaveformListeners ( ) . isEmpty ( ) ) { SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { final WaveformDetailUpdate update = new WaveformDetailUpdate ( player , detail ) ; for ( final WaveformListener listener : getWaveformListeners ( ) ) { try { listener . detailChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering waveform detail update to listener" , t ) ; } } } } ) ; } }
Send a waveform detail update announcement to all registered listeners .
142
12
150,588
private void primeCache ( ) { 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 handleUpdate ( new TrackMetadataUpdate ( entry . getKey ( ) . player , entry . getValue ( ) ) ) ; } } } } ) ; }
Send ourselves updates about any tracks that were loaded before we started or before we were requesting details since we missed them .
130
23
150,589
@ 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 waveforms, on the proper thread, outside our lock final Set < DeckReference > dyingPreviewCache = new HashSet < DeckReference > ( previewHotCache . keySet ( ) ) ; previewHotCache . clear ( ) ; final Set < DeckReference > dyingDetailCache = new HashSet < DeckReference > ( detailHotCache . keySet ( ) ) ; detailHotCache . clear ( ) ; SwingUtilities . invokeLater ( new Runnable ( ) { @ Override public void run ( ) { for ( DeckReference deck : dyingPreviewCache ) { // Report the loss of our previews. if ( deck . hotCue == 0 ) { deliverWaveformPreviewUpdate ( deck . player , null ) ; } } for ( DeckReference deck : dyingDetailCache ) { // Report the loss of our details. if ( deck . hotCue == 0 ) { deliverWaveformDetailUpdate ( deck . player , null ) ; } } } } ) ; deliverLifecycleAnnouncement ( logger , false ) ; } }
Stop finding waveforms for all active players .
299
9
150,590
private void clearArt ( 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 ) { deliverAlbumArtUpdate ( player , null ) ; // Inform listeners that the artwork is gone. } } } // Again iterate over a copy to avoid concurrent modification issues for ( DataReference art : new HashSet < DataReference > ( artCache . keySet ( ) ) ) { if ( art . player == player ) { artCache . remove ( art ) ; } } }
We have received notification that a device is no longer on the network so clear out its artwork .
165
19
150,591
private void updateArt ( TrackMetadataUpdate update , AlbumArt art ) { hotCache . put ( DeckReference . getDeckReference ( update . player , 0 ) , art ) ; // 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 ) , art ) ; } } } deliverAlbumArtUpdate ( update . player , art ) ; }
We have obtained album art for a device so store it and alert any listeners .
150
16
150,592
public Map < DeckReference , AlbumArt > getLoadedArt ( ) { ensureRunning ( ) ; // Make a copy so callers get an immutable snapshot of the current state. return Collections . unmodifiableMap ( new HashMap < DeckReference , AlbumArt > ( hotCache ) ) ; }
Get the art available for all tracks currently loaded in any player either on the play deck or in a hot cue .
62
23
150,593
private AlbumArt requestArtworkInternal ( final DataReference artReference , final CdjStatus . TrackType trackType , final boolean failIfPassive ) { // First check if we are using cached data for this slot. MetadataCache cache = MetadataFinder . getInstance ( ) . getMetadataCache ( SlotReference . getSlotReference ( artReference ) ) ; if ( cache != null ) { final AlbumArt result = cache . getAlbumArt ( null , artReference ) ; if ( result != null ) { artCache . put ( artReference , result ) ; } return result ; } // Then see if any registered metadata providers can offer it for us. final MediaDetails sourceDetails = MetadataFinder . getInstance ( ) . getMediaDetailsFor ( artReference . getSlotReference ( ) ) ; if ( sourceDetails != null ) { final AlbumArt provided = MetadataFinder . getInstance ( ) . allMetadataProviders . getAlbumArt ( sourceDetails , artReference ) ; if ( provided != null ) { return provided ; } } // At this point, unless we are allowed to actively request the data, we are done. We can always actively // request tracks from rekordbox. if ( MetadataFinder . getInstance ( ) . isPassive ( ) && failIfPassive && artReference . slot != CdjStatus . TrackSourceSlot . COLLECTION ) { return null ; } // We have to actually request the art using the dbserver protocol. ConnectionManager . ClientTask < AlbumArt > task = new ConnectionManager . ClientTask < AlbumArt > ( ) { @ Override public AlbumArt useClient ( Client client ) throws Exception { return getArtwork ( artReference . rekordboxId , SlotReference . getSlotReference ( artReference ) , trackType , client ) ; } } ; try { AlbumArt artwork = ConnectionManager . getInstance ( ) . invokeWithClientSession ( artReference . player , task , "requesting artwork" ) ; if ( artwork != null ) { // Our cache file load or network request succeeded, so add to the level 2 cache. artCache . put ( artReference , artwork ) ; } return artwork ; } catch ( Exception e ) { logger . error ( "Problem requesting album art, returning null" , e ) ; } return null ; }
Ask the specified player for the album art in the specified slot with the specified rekordbox ID using cached media instead if it is available and possibly giving up if we are in passive mode .
490
39
150,594
public AlbumArt requestArtworkFrom ( final DataReference artReference , final CdjStatus . TrackType trackType ) { ensureRunning ( ) ; AlbumArt artwork = findArtInMemoryCaches ( artReference ) ; // First check the in-memory artwork caches. if ( artwork == null ) { artwork = requestArtworkInternal ( artReference , trackType , false ) ; } return artwork ; }
Ask the specified player for the specified artwork from the specified media slot first checking if we have a cached copy .
83
22
150,595
AlbumArt getArtwork ( int artworkId , SlotReference slot , CdjStatus . TrackType trackType , Client client ) throws IOException { // Send the artwork request Message response = client . simpleRequest ( Message . KnownType . ALBUM_ART_REQ , Message . KnownType . ALBUM_ART , client . buildRMST ( Message . MenuIdentifier . DATA , slot . slot , trackType ) , new NumberField ( ( long ) artworkId ) ) ; // Create an image from the response bytes return new AlbumArt ( new DataReference ( slot , artworkId ) , ( ( BinaryField ) response . arguments . get ( 3 ) ) . getValue ( ) ) ; }
Request the artwork with a particular artwork ID given a connection to a player that has already been set up .
148
21
150,596
private AlbumArt findArtInMemoryCaches ( DataReference artReference ) { // First see if we can find the new track in the hot cache as a hot cue for ( AlbumArt cached : hotCache . values ( ) ) { if ( cached . artReference . equals ( artReference ) ) { // Found a hot cue hit, use it. return cached ; } } // Not in the hot cache, see if it is in our LRU cache return artCache . get ( artReference ) ; }
Look for the specified album art in both the hot cache of loaded tracks and the longer - lived LRU cache .
104
23
150,597
private void deliverAlbumArtUpdate ( int player , AlbumArt art ) { if ( ! getAlbumArtListeners ( ) . isEmpty ( ) ) { final AlbumArtUpdate update = new AlbumArtUpdate ( player , art ) ; for ( final AlbumArtListener listener : getAlbumArtListeners ( ) ) { try { listener . albumArtChanged ( update ) ; } catch ( Throwable t ) { logger . warn ( "Problem delivering album art update to listener" , t ) ; } } } }
Send an album art update announcement to all registered listeners .
108
11
150,598
public BufferedImage getImage ( ) { ByteBuffer artwork = getRawBytes ( ) ; artwork . rewind ( ) ; byte [ ] imageBytes = new byte [ artwork . remaining ( ) ] ; artwork . get ( imageBytes ) ; try { return ImageIO . read ( new ByteArrayInputStream ( imageBytes ) ) ; } catch ( IOException e ) { logger . error ( "Weird! Caught exception creating image from artwork bytes" , e ) ; return null ; } }
Given the byte buffer containing album art build an actual image from it for easy rendering .
103
17
150,599
private TrackSourceSlot findTrackSourceSlot ( ) { TrackSourceSlot result = TRACK_SOURCE_SLOT_MAP . get ( packetBytes [ 41 ] ) ; if ( result == null ) { return TrackSourceSlot . UNKNOWN ; } return result ; }
Determine the enum value corresponding to the track source slot found in the packet .
55
17