1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
|
/*
This file is part of Subsonic.
Subsonic is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Subsonic is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Subsonic. If not, see <http://www.gnu.org/licenses/>.
Copyright 2014 (C) Scott Jackson
*/
package github.daneren2005.dsub.provider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.media.AudioManager;
import android.media.MediaRouter;
import android.os.IBinder;
import androidx.mediarouter.media.MediaControlIntent;
import androidx.mediarouter.media.MediaRouteDescriptor;
import androidx.mediarouter.media.MediaRouteDiscoveryRequest;
import androidx.mediarouter.media.MediaRouteProvider;
import androidx.mediarouter.media.MediaRouteProviderDescriptor;
import android.util.Log;
import org.eclipse.jetty.util.log.Logger;
import org.fourthline.cling.android.AndroidUpnpService;
import org.fourthline.cling.android.AndroidUpnpServiceImpl;
import org.fourthline.cling.model.action.ActionInvocation;
import org.fourthline.cling.model.message.UpnpResponse;
import org.fourthline.cling.model.meta.Device;
import org.fourthline.cling.model.meta.LocalDevice;
import org.fourthline.cling.model.meta.RemoteDevice;
import org.fourthline.cling.model.meta.StateVariable;
import org.fourthline.cling.model.meta.StateVariableAllowedValueRange;
import org.fourthline.cling.model.types.ServiceType;
import org.fourthline.cling.registry.Registry;
import org.fourthline.cling.registry.RegistryListener;
import org.fourthline.cling.support.renderingcontrol.callback.GetVolume;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import github.daneren2005.dsub.domain.DLNADevice;
import github.daneren2005.dsub.domain.RemoteControlState;
import github.daneren2005.dsub.service.DLNAController;
import github.daneren2005.dsub.service.DownloadService;
import github.daneren2005.dsub.service.RemoteController;
public class DLNARouteProvider extends MediaRouteProvider {
private static final String TAG = DLNARouteProvider.class.getSimpleName();
public static final String CATEGORY_DLNA = "github.daneren2005.dsub.DLNA";
private DownloadService downloadService;
private RemoteController controller;
private HashMap<String, DLNADevice> devices = new HashMap<String, DLNADevice>();
private List<String> adding = new ArrayList<String>();
private List<String> removing = new ArrayList<String>();
private AndroidUpnpService dlnaService;
private ServiceConnection dlnaServiceConnection;
private RegistryListener registryListener;
private boolean searchOnConnect = false;
public DLNARouteProvider(Context context) {
super(context);
// Use custom logger
org.eclipse.jetty.util.log.Log.setLog(new JettyAndroidLog());
this.downloadService = (DownloadService) context;
dlnaServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
dlnaService = (AndroidUpnpService) service;
dlnaService.getRegistry().addListener(registryListener = new RegistryListener() {
@Override
public void remoteDeviceDiscoveryStarted(Registry registry, RemoteDevice remoteDevice) {
}
@Override
public void remoteDeviceDiscoveryFailed(Registry registry, RemoteDevice remoteDevice, Exception e) {
// Error is displayed in log anyways under W/trieveRemoteDescriptors
}
@Override
public void remoteDeviceAdded(Registry registry, RemoteDevice remoteDevice) {
deviceAdded(remoteDevice);
}
@Override
public void remoteDeviceUpdated(Registry registry, RemoteDevice remoteDevice) {
deviceAdded(remoteDevice);
}
@Override
public void remoteDeviceRemoved(Registry registry, RemoteDevice remoteDevice) {
deviceRemoved(remoteDevice);
}
@Override
public void localDeviceAdded(Registry registry, LocalDevice localDevice) {
deviceAdded(localDevice);
}
@Override
public void localDeviceRemoved(Registry registry, LocalDevice localDevice) {
deviceRemoved(localDevice);
}
@Override
public void beforeShutdown(Registry registry) {
}
@Override
public void afterShutdown() {
}
});
for (Device<?, ?, ?> device : dlnaService.getControlPoint().getRegistry().getDevices()) {
deviceAdded(device);
}
if(searchOnConnect) {
dlnaService.getControlPoint().search();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
dlnaService = null;
registryListener = null;
}
};
if(!context.getApplicationContext().bindService(new Intent(context, AndroidUpnpServiceImpl.class), dlnaServiceConnection, Context.BIND_AUTO_CREATE)) {
Log.e(TAG, "Failed to bind to DLNA service");
}
}
private void broadcastDescriptors() {
// Create intents
IntentFilter routeIntentFilter = new IntentFilter();
routeIntentFilter.addCategory(CATEGORY_DLNA);
routeIntentFilter.addAction(MediaControlIntent.ACTION_START_SESSION);
routeIntentFilter.addAction(MediaControlIntent.ACTION_GET_SESSION_STATUS);
routeIntentFilter.addAction(MediaControlIntent.ACTION_END_SESSION);
// Create descriptor
MediaRouteProviderDescriptor.Builder providerBuilder = new MediaRouteProviderDescriptor.Builder();
// Create route descriptor
for(Map.Entry<String, DLNADevice> deviceEntry: devices.entrySet()) {
DLNADevice device = deviceEntry.getValue();
int volume;
if(device.volumeMax <= 0) {
volume = 5;
} else {
int increments = (int) Math.ceil(device.volumeMax / 10.0);
volume = controller == null ? device.volume : (int) controller.getVolume();
volume = volume / increments;
}
MediaRouteDescriptor.Builder routeBuilder = new MediaRouteDescriptor.Builder(device.id, device.name);
routeBuilder.addControlFilter(routeIntentFilter)
.setPlaybackStream(AudioManager.STREAM_MUSIC)
.setPlaybackType(MediaRouter.RouteInfo.PLAYBACK_TYPE_REMOTE)
.setDescription(device.description)
.setVolume(volume)
.setVolumeMax(10)
.setVolumeHandling(MediaRouter.RouteInfo.PLAYBACK_VOLUME_VARIABLE);
providerBuilder.addRoute(routeBuilder.build());
}
setDescriptor(providerBuilder.build());
}
@Override
public void onDiscoveryRequestChanged(MediaRouteDiscoveryRequest request) {
if (request != null && request.isActiveScan()) {
if(dlnaService != null) {
dlnaService.getControlPoint().search();
} else {
searchOnConnect = true;
}
}
}
@Override
public RouteController onCreateRouteController(String routeId) {
DLNADevice device = devices.get(routeId);
if(device == null) {
Log.w(TAG, "No device exists for " + routeId);
return null;
}
return new DLNARouteController(device);
}
private void deviceAdded(final Device device) {
final org.fourthline.cling.model.meta.Service renderingControl = device.findService(new ServiceType("schemas-upnp-org", "RenderingControl"));
if(renderingControl == null) {
return;
}
final String id = device.getIdentity().getUdn().toString();
// In the process of looking up it's details already
if(adding.contains(id)) {
return;
}
// Just a temp disconnect, already have it's info
if(removing.contains(id)) {
removing.remove(id);
return;
}
synchronized (adding) {
adding.add(id);
}
if(device.getType().getType().equals("MediaRenderer") && device instanceof RemoteDevice) {
try {
dlnaService.getControlPoint().execute(new GetVolume(renderingControl) {
@Override
public void received(ActionInvocation actionInvocation, int currentVolume) {
int maxVolume = 100;
StateVariable volume = renderingControl.getStateVariable("Volume");
if (volume != null) {
StateVariableAllowedValueRange volumeRange = volume.getTypeDetails().getAllowedValueRange();
maxVolume = (int) volumeRange.getMaximum();
}
// Create a new DLNADevice to represent this item
String id = device.getIdentity().getUdn().toString();
String name = device.getDetails().getFriendlyName();
String displayName = device.getDisplayString();
DLNADevice newDevice = new DLNADevice(device, id, name, displayName, currentVolume, maxVolume);
devices.put(id, newDevice);
downloadService.post(new Runnable() {
@Override
public void run() {
broadcastDescriptors();
}
});
synchronized (adding) {
if (adding.contains(id)) {
adding.remove(id);
}
}
}
@Override
public void failure(ActionInvocation actionInvocation, UpnpResponse upnpResponse, String s) {
Log.w(TAG, "Failed to get default volume for DLNA route");
Log.w(TAG, "Reason: " + s);
synchronized (adding) {
if (adding.contains(id)) {
adding.remove(id);
}
}
}
});
} catch(Exception e) {
Log.e(TAG, "Failed to add device", e);
}
} else {
synchronized (adding) {
if(adding.contains(id)) {
adding.remove(id);
}
}
}
}
private void deviceRemoved(Device device) {
if(device.getType().getType().equals("MediaRenderer") && device instanceof RemoteDevice) {
final String id = device.getIdentity().getUdn().toString();
removing.add(id);
// Delay removal for a few seconds to make sure that it isn't just a temp disconnect
dlnaService.getControlPoint().search();
downloadService.postDelayed(new Runnable() {
@Override
public void run() {
if(removing.contains(id)) {
devices.remove(id);
removing.remove(id);
broadcastDescriptors();
}
}
}, 5000L);
}
}
public void destroy() {
if(dlnaService != null) {
dlnaService.getRegistry().removeListener(registryListener);
registryListener = null;
}
if(dlnaServiceConnection != null) {
getContext().getApplicationContext().unbindService(dlnaServiceConnection);
}
}
private class DLNARouteController extends RouteController {
private DLNADevice device;
public DLNARouteController(DLNADevice device) {
this.device = device;
}
@Override
public boolean onControlRequest(Intent intent, androidx.mediarouter.media.MediaRouter.ControlRequestCallback callback) {
if (intent.hasCategory(CATEGORY_DLNA)) {
return true;
} else {
return false;
}
}
@Override
public void onRelease() {
downloadService.setRemoteEnabled(RemoteControlState.LOCAL);
controller = null;
}
@Override
public void onSelect() {
controller = new DLNAController(downloadService, dlnaService.getControlPoint(), device);
downloadService.setRemoteEnabled(RemoteControlState.DLNA, controller);
}
@Override
public void onUnselect() {
downloadService.setRemoteEnabled(RemoteControlState.LOCAL);
controller = null;
}
@Override
public void onUpdateVolume(int delta) {
if(controller != null) {
controller.updateVolume(delta > 0);
}
broadcastDescriptors();
}
@Override
public void onSetVolume(int volume) {
if(controller != null) {
controller.setVolume(volume);
}
broadcastDescriptors();
}
}
public static class JettyAndroidLog implements Logger {
final private static java.util.logging.Logger log = java.util.logging.Logger.getLogger("Jetty");
public static boolean __isIgnoredEnabled = false;
public String _name;
public JettyAndroidLog() {
this (JettyAndroidLog.class.getName());
}
public JettyAndroidLog(String name) {
_name = name;
}
public String getName () {
return _name;
}
public void debug(Throwable th) {
// Log.d(TAG, "", th);
}
public void debug(String msg, Throwable th) {
// Log.d(TAG, msg, th);
}
public void debug(String msg, Object... args) {
// Log.d(TAG, msg);
}
public Logger getLogger(String name) {
return new JettyAndroidLog(name);
}
public void info(String msg, Object... args) {
// Log.i(TAG, msg);
}
public void info(Throwable th) {
// Log.i(TAG, "", th);
}
public void info(String msg, Throwable th) {
// Log.i(TAG, msg, th);
}
public boolean isDebugEnabled() {
return false;
}
public void warn(Throwable th) {
// Log.w(TAG, "", th);
}
public void warn(String msg, Object... args) {
// Log.w(TAG, msg);
}
public void warn(String msg, Throwable th) {
// Log.w(TAG, msg, th);
}
public boolean isIgnoredEnabled () {
return __isIgnoredEnabled;
}
public void ignore(Throwable ignored) {
if (__isIgnoredEnabled) {
warn("IGNORED", ignored);
}
}
public void setIgnoredEnabled(boolean enabled) {
__isIgnoredEnabled = enabled;
}
public void setDebugEnabled(boolean enabled) {
}
}
}
|