]> git.basschouten.com Git - openhab-addons.git/blob
fe2cdaa78e575971dbda2fcea25a27e01a613362
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.upnpcontrol.internal.handler;
14
15 import static org.openhab.binding.upnpcontrol.internal.UpnpControlBindingConstants.*;
16
17 import java.net.URLDecoder;
18 import java.nio.charset.StandardCharsets;
19 import java.time.Instant;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collections;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.concurrent.CompletableFuture;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ExecutionException;
31 import java.util.concurrent.ScheduledFuture;
32 import java.util.concurrent.TimeUnit;
33 import java.util.concurrent.TimeoutException;
34 import java.util.regex.Matcher;
35 import java.util.regex.Pattern;
36 import java.util.stream.Collectors;
37
38 import org.eclipse.jdt.annotation.NonNullByDefault;
39 import org.eclipse.jdt.annotation.Nullable;
40 import org.jupnp.model.meta.RemoteDevice;
41 import org.openhab.binding.upnpcontrol.internal.UpnpChannelName;
42 import org.openhab.binding.upnpcontrol.internal.UpnpDynamicCommandDescriptionProvider;
43 import org.openhab.binding.upnpcontrol.internal.UpnpDynamicStateDescriptionProvider;
44 import org.openhab.binding.upnpcontrol.internal.audiosink.UpnpAudioSink;
45 import org.openhab.binding.upnpcontrol.internal.audiosink.UpnpAudioSinkReg;
46 import org.openhab.binding.upnpcontrol.internal.config.UpnpControlBindingConfiguration;
47 import org.openhab.binding.upnpcontrol.internal.config.UpnpControlRendererConfiguration;
48 import org.openhab.binding.upnpcontrol.internal.queue.UpnpEntry;
49 import org.openhab.binding.upnpcontrol.internal.queue.UpnpEntryQueue;
50 import org.openhab.binding.upnpcontrol.internal.queue.UpnpFavorite;
51 import org.openhab.binding.upnpcontrol.internal.services.UpnpRenderingControlConfiguration;
52 import org.openhab.binding.upnpcontrol.internal.util.UpnpControlUtil;
53 import org.openhab.binding.upnpcontrol.internal.util.UpnpXMLParser;
54 import org.openhab.core.audio.AudioFormat;
55 import org.openhab.core.io.net.http.HttpUtil;
56 import org.openhab.core.io.transport.upnp.UpnpIOService;
57 import org.openhab.core.library.types.DecimalType;
58 import org.openhab.core.library.types.NextPreviousType;
59 import org.openhab.core.library.types.OnOffType;
60 import org.openhab.core.library.types.PercentType;
61 import org.openhab.core.library.types.PlayPauseType;
62 import org.openhab.core.library.types.QuantityType;
63 import org.openhab.core.library.types.RewindFastforwardType;
64 import org.openhab.core.library.types.StringType;
65 import org.openhab.core.library.unit.Units;
66 import org.openhab.core.thing.Channel;
67 import org.openhab.core.thing.ChannelUID;
68 import org.openhab.core.thing.Thing;
69 import org.openhab.core.thing.ThingStatus;
70 import org.openhab.core.thing.ThingStatusDetail;
71 import org.openhab.core.types.Command;
72 import org.openhab.core.types.CommandOption;
73 import org.openhab.core.types.RefreshType;
74 import org.openhab.core.types.State;
75 import org.openhab.core.types.UnDefType;
76 import org.slf4j.Logger;
77 import org.slf4j.LoggerFactory;
78
79 /**
80  * The {@link UpnpRendererHandler} is responsible for handling commands sent to the UPnP Renderer. It extends
81  * {@link UpnpHandler} with UPnP renderer specific logic. It implements UPnP AVTransport and RenderingControl service
82  * actions.
83  *
84  * @author Mark Herwege - Initial contribution
85  * @author Karel Goderis - Based on UPnP logic in Sonos binding
86  */
87 @NonNullByDefault
88 public class UpnpRendererHandler extends UpnpHandler {
89
90     private final Logger logger = LoggerFactory.getLogger(UpnpRendererHandler.class);
91
92     // UPnP constants
93     static final String RENDERING_CONTROL = "RenderingControl";
94     static final String AV_TRANSPORT = "AVTransport";
95     static final String INSTANCE_ID = "InstanceID";
96
97     private volatile boolean audioSupport;
98     protected volatile Set<AudioFormat> supportedAudioFormats = new HashSet<>();
99     private volatile boolean audioSinkRegistered;
100
101     private volatile UpnpAudioSinkReg audioSinkReg;
102
103     private volatile Set<UpnpServerHandler> serverHandlers = ConcurrentHashMap.newKeySet();
104
105     protected @NonNullByDefault({}) UpnpControlRendererConfiguration config;
106     private UpnpRenderingControlConfiguration renderingControlConfiguration = new UpnpRenderingControlConfiguration();
107
108     private volatile List<CommandOption> favoriteCommandOptionList = List.of();
109     private volatile List<CommandOption> playlistCommandOptionList = List.of();
110
111     private @NonNullByDefault({}) ChannelUID favoriteSelectChannelUID;
112     private @NonNullByDefault({}) ChannelUID playlistSelectChannelUID;
113
114     private volatile PercentType soundVolume = new PercentType();
115     private @Nullable volatile PercentType notificationVolume;
116     private volatile List<String> sink = new ArrayList<>();
117
118     private volatile String favoriteName = ""; // Currently selected favorite
119
120     private volatile boolean repeat;
121     private volatile boolean shuffle;
122     private volatile boolean onlyplayone; // Set to true if we only want to play one at a time
123
124     // Queue as received from server and current and next media entries for playback
125     private volatile UpnpEntryQueue currentQueue = new UpnpEntryQueue();
126     volatile @Nullable UpnpEntry currentEntry = null;
127     volatile @Nullable UpnpEntry nextEntry = null;
128
129     // Group of fields representing current state of player
130     private volatile String nowPlayingUri = ""; // Used to block waiting for setting URI when it is the same as current
131                                                 // as some players will not send URI update when it is the same as
132                                                 // previous
133     private volatile String transportState = ""; // Current transportState to be able to refresh the control
134     volatile boolean playerStopped; // Set if the player is stopped from OH command or code, allows to identify
135                                     // if STOP came from other source when receiving STOP state from GENA event
136     volatile boolean playing; // Set to false when a STOP is received, so we can filter two consecutive STOPs
137                               // and not play next entry second time
138     private volatile @Nullable ScheduledFuture<?> paused; // Set when a pause command is given, to compensate for
139                                                           // renderers that cannot pause playback
140     private volatile @Nullable CompletableFuture<Boolean> isSettingURI; // Set to wait for setting URI before starting
141                                                                         // to play or seeking
142     private volatile @Nullable CompletableFuture<Boolean> isStopping; // Set when stopping to be able to wait for stop
143                                                                       // confirmation for subsequent actions that need
144                                                                       // the player to be stopped
145     volatile boolean registeredQueue; // Set when registering a new queue. This allows to decide if we just
146                                       // need to play URI, or serve the first entry in a queue when a play
147                                       // command is given.
148     volatile boolean playingQueue; // Identifies if we are playing a queue received from a server. If so, a new
149                                    // queue received will be played after the currently playing entry
150     private volatile boolean oneplayed; // Set to true when the one entry is being played, allows to check if stop is
151                                         // needed when only playing one
152     volatile boolean playingNotification; // Set when playing a notification
153     private volatile @Nullable ScheduledFuture<?> playingNotificationFuture; // Set when playing a notification, allows
154                                                                              // timing out notification
155     private volatile String notificationUri = ""; // Used to check if the received URI is from the notification
156     private final Object notificationLock = new Object();
157
158     // Track position and duration fields
159     private volatile int trackDuration = 0;
160     private volatile int trackPosition = 0;
161     private volatile long expectedTrackend = 0;
162     private volatile @Nullable ScheduledFuture<?> trackPositionRefresh;
163     private volatile int posAtNotificationStart = 0;
164
165     public UpnpRendererHandler(Thing thing, UpnpIOService upnpIOService, UpnpAudioSinkReg audioSinkReg,
166             UpnpDynamicStateDescriptionProvider upnpStateDescriptionProvider,
167             UpnpDynamicCommandDescriptionProvider upnpCommandDescriptionProvider,
168             UpnpControlBindingConfiguration configuration) {
169         super(thing, upnpIOService, configuration, upnpStateDescriptionProvider, upnpCommandDescriptionProvider);
170
171         serviceSubscriptions.add(AV_TRANSPORT);
172         serviceSubscriptions.add(RENDERING_CONTROL);
173
174         this.audioSinkReg = audioSinkReg;
175     }
176
177     @Override
178     public void initialize() {
179         super.initialize();
180         config = getConfigAs(UpnpControlRendererConfiguration.class);
181         if (config.seekStep < 1) {
182             config.seekStep = 1;
183         }
184         logger.debug("Initializing handler for media renderer device {}", thing.getLabel());
185
186         Channel favoriteSelectChannel = thing.getChannel(FAVORITE_SELECT);
187         if (favoriteSelectChannel != null) {
188             favoriteSelectChannelUID = favoriteSelectChannel.getUID();
189         } else {
190             String msg = String.format("@text/offline.channel-undefined [ \"%s\" ]", FAVORITE_SELECT);
191             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
192             return;
193         }
194         Channel playlistSelectChannel = thing.getChannel(PLAYLIST_SELECT);
195         if (playlistSelectChannel != null) {
196             playlistSelectChannelUID = playlistSelectChannel.getUID();
197         } else {
198             String msg = String.format("@text/offline.channel-undefined [ \"%s\" ]", PLAYLIST_SELECT);
199             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
200             return;
201         }
202
203         initDevice();
204     }
205
206     @Override
207     public void dispose() {
208         logger.debug("Disposing handler for media renderer device {}", thing.getLabel());
209
210         cancelTrackPositionRefresh();
211         resetPaused();
212         CompletableFuture<Boolean> settingURI = isSettingURI;
213         if (settingURI != null) {
214             settingURI.complete(false);
215         }
216
217         super.dispose();
218     }
219
220     @Override
221     protected void initJob() {
222         synchronized (jobLock) {
223             if (!upnpIOService.isRegistered(this)) {
224                 String msg = String.format("@text/offline.device-not-registered [ \"%s\" ]", getUDN());
225                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg);
226                 return;
227             }
228
229             if (!ThingStatus.ONLINE.equals(thing.getStatus())) {
230                 getProtocolInfo();
231
232                 getCurrentConnectionInfo();
233                 if (!checkForConnectionIds()) {
234                     String msg = String.format("@text/offline.no-connection-ids [ \"%s\" ]", getUDN());
235                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, msg);
236                     return;
237                 }
238
239                 getTransportState();
240
241                 updateFavoritesList();
242                 playlistsListChanged();
243
244                 RemoteDevice device = getDevice();
245                 if (device != null) { // The handler factory will update the device config later when it has not been
246                                       // set yet
247                     updateDeviceConfig(device);
248                 }
249
250                 updateStatus(ThingStatus.ONLINE);
251             }
252
253             if (!upnpSubscribed) {
254                 addSubscriptions();
255             }
256         }
257     }
258
259     @Override
260     public void updateDeviceConfig(RemoteDevice device) {
261         super.updateDeviceConfig(device);
262
263         UpnpRenderingControlConfiguration config = new UpnpRenderingControlConfiguration(device);
264         renderingControlConfiguration = config;
265         for (String audioChannel : config.audioChannels) {
266             createAudioChannels(audioChannel);
267         }
268
269         updateChannels();
270     }
271
272     private void createAudioChannels(String audioChannel) {
273         UpnpRenderingControlConfiguration config = renderingControlConfiguration;
274         if (config.volume && !UPNP_MASTER.equals(audioChannel)) {
275             String name = audioChannel + "volume";
276             if (UpnpChannelName.channelIdToUpnpChannelName(name) != null) {
277                 createChannel(UpnpChannelName.channelIdToUpnpChannelName(name));
278             } else {
279                 String label = String.format("@text/channel.upnpcontrol.vendorvolume.label [ \"%s\" ]", audioChannel);
280                 createChannel(name, label, "@text/channel.upnpcontrol.vendorvolume.description", ITEM_TYPE_VOLUME,
281                         CHANNEL_TYPE_VOLUME);
282             }
283         }
284         if (config.mute && !UPNP_MASTER.equals(audioChannel)) {
285             String name = audioChannel + "mute";
286             if (UpnpChannelName.channelIdToUpnpChannelName(name) != null) {
287                 createChannel(UpnpChannelName.channelIdToUpnpChannelName(name));
288             } else {
289                 String label = String.format("@text/channel.upnpcontrol.vendormute.label [ \"%s\" ]", audioChannel);
290                 createChannel(name, label, "@text/channel.upnpcontrol.vendormute.description", ITEM_TYPE_MUTE,
291                         CHANNEL_TYPE_MUTE);
292             }
293         }
294         if (config.loudness) {
295             String name = (UPNP_MASTER.equals(audioChannel) ? "" : audioChannel) + "loudness";
296             if (UpnpChannelName.channelIdToUpnpChannelName(name) != null) {
297                 createChannel(UpnpChannelName.channelIdToUpnpChannelName(name));
298             } else {
299                 String label = String.format("@text/channel.upnpcontrol.vendorloudness.label [ \"%s\" ]", audioChannel);
300                 createChannel(name, label, "@text/channel.upnpcontrol.vendorloudness.description", ITEM_TYPE_LOUDNESS,
301                         CHANNEL_TYPE_LOUDNESS);
302             }
303         }
304     }
305
306     /**
307      * Invoke Stop on UPnP AV Transport.
308      */
309     public void stop() {
310         playerStopped = true;
311
312         if (playing) {
313             CompletableFuture<Boolean> stopping = isStopping;
314             if (stopping != null) {
315                 stopping.complete(false);
316             }
317             isStopping = new CompletableFuture<Boolean>(); // set this so we can check if stop confirmation has been
318                                                            // received
319         }
320
321         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
322
323         invokeAction(AV_TRANSPORT, "Stop", inputs);
324     }
325
326     /**
327      * Invoke Play on UPnP AV Transport.
328      */
329     public void play() {
330         CompletableFuture<Boolean> settingURI = isSettingURI;
331         boolean uriSet = true;
332         try {
333             if (settingURI != null) {
334                 // wait for maximum 2.5s until the media URI is set before playing
335                 uriSet = settingURI.get(config.responseTimeout, TimeUnit.MILLISECONDS);
336             }
337         } catch (InterruptedException | ExecutionException | TimeoutException e) {
338             logger.debug("Timeout exception, media URI not yet set in renderer {}, trying to play anyway",
339                     thing.getLabel());
340         }
341
342         if (uriSet) {
343             Map<String, String> inputs = new HashMap<>();
344             inputs.put(INSTANCE_ID, Integer.toString(avTransportId));
345             inputs.put("Speed", "1");
346
347             invokeAction(AV_TRANSPORT, "Play", inputs);
348         } else {
349             logger.debug("Cannot play, cancelled setting URI in the renderer {}", thing.getLabel());
350         }
351     }
352
353     /**
354      * Invoke Pause on UPnP AV Transport.
355      */
356     protected void pause() {
357         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
358
359         invokeAction(AV_TRANSPORT, "Pause", inputs);
360     }
361
362     /**
363      * Invoke Next on UPnP AV Transport.
364      */
365     protected void next() {
366         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
367
368         invokeAction(AV_TRANSPORT, "Next", inputs);
369     }
370
371     /**
372      * Invoke Previous on UPnP AV Transport.
373      */
374     protected void previous() {
375         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
376
377         invokeAction(AV_TRANSPORT, "Previous", inputs);
378     }
379
380     /**
381      * Invoke Seek on UPnP AV Transport.
382      *
383      * @param seekTarget relative position in current track, format HH:mm:ss
384      */
385     protected void seek(String seekTarget) {
386         CompletableFuture<Boolean> settingURI = isSettingURI;
387         boolean uriSet = true;
388         try {
389             if (settingURI != null) {
390                 // wait for maximum 2.5s until the media URI is set before seeking
391                 uriSet = settingURI.get(config.responseTimeout, TimeUnit.MILLISECONDS);
392             }
393         } catch (InterruptedException | ExecutionException | TimeoutException e) {
394             logger.debug("Timeout exception, media URI not yet set in renderer {}, skipping seek", thing.getLabel());
395             return;
396         }
397
398         if (uriSet) {
399             Map<String, String> inputs = new HashMap<>();
400             inputs.put(INSTANCE_ID, Integer.toString(avTransportId));
401             inputs.put("Unit", "REL_TIME");
402             inputs.put("Target", seekTarget);
403
404             invokeAction(AV_TRANSPORT, "Seek", inputs);
405         } else {
406             logger.debug("Cannot seek, cancelled setting URI in the renderer {}", thing.getLabel());
407         }
408     }
409
410     /**
411      * Invoke SetAVTransportURI on UPnP AV Transport.
412      *
413      * @param URI
414      * @param URIMetaData
415      */
416     public void setCurrentURI(String URI, String URIMetaData) {
417         String uri = "";
418         uri = URLDecoder.decode(URI.trim(), StandardCharsets.UTF_8);
419         // Some renderers don't send a URI Last Changed event when the same URI is requested, so don't wait for it
420         // before starting to play
421         if (!uri.equals(nowPlayingUri) && !playingNotification) {
422             CompletableFuture<Boolean> settingURI = isSettingURI;
423             if (settingURI != null) {
424                 settingURI.complete(false);
425             }
426             isSettingURI = new CompletableFuture<Boolean>(); // set this so we don't start playing when not finished
427                                                              // setting URI
428         } else {
429             logger.debug("New URI {} is same as previous on renderer {}", nowPlayingUri, thing.getLabel());
430         }
431
432         Map<String, String> inputs = new HashMap<>();
433         inputs.put(INSTANCE_ID, Integer.toString(avTransportId));
434         inputs.put("CurrentURI", uri);
435         inputs.put("CurrentURIMetaData", URIMetaData);
436
437         invokeAction(AV_TRANSPORT, "SetAVTransportURI", inputs);
438     }
439
440     /**
441      * Invoke SetNextAVTransportURI on UPnP AV Transport.
442      *
443      * @param nextURI
444      * @param nextURIMetaData
445      */
446     protected void setNextURI(String nextURI, String nextURIMetaData) {
447         Map<String, String> inputs = new HashMap<>();
448         inputs.put(INSTANCE_ID, Integer.toString(avTransportId));
449         inputs.put("NextURI", nextURI);
450         inputs.put("NextURIMetaData", nextURIMetaData);
451
452         invokeAction(AV_TRANSPORT, "SetNextAVTransportURI", inputs);
453     }
454
455     /**
456      * Invoke GetTransportState on UPnP AV Transport.
457      * Result is received in {@link onValueReceived}.
458      */
459     protected void getTransportState() {
460         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
461
462         invokeAction(AV_TRANSPORT, "GetTransportInfo", inputs);
463     }
464
465     /**
466      * Invoke getPositionInfo on UPnP AV Transport.
467      * Result is received in {@link onValueReceived}.
468      */
469     protected void getPositionInfo() {
470         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
471
472         invokeAction(AV_TRANSPORT, "GetPositionInfo", inputs);
473     }
474
475     /**
476      * Invoke GetMediaInfo on UPnP AV Transport.
477      * Result is received in {@link onValueReceived}.
478      */
479     protected void getMediaInfo() {
480         Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
481
482         invokeAction(AV_TRANSPORT, "smarthome:audio stream http://icecast.vrtcdn.be/stubru_tijdloze-high.mp3", inputs);
483     }
484
485     /**
486      * Retrieves the current volume known to the control point, gets updated by GENA events or after UPnP Rendering
487      * Control GetVolume call. This method is used to retrieve volume by {@link UpnpAudioSink.getVolume}.
488      *
489      * @return current volume
490      */
491     public PercentType getCurrentVolume() {
492         return soundVolume;
493     }
494
495     /**
496      * Invoke GetVolume on UPnP Rendering Control.
497      * Result is received in {@link onValueReceived}.
498      *
499      * @param channel
500      */
501     protected void getVolume(String channel) {
502         Map<String, String> inputs = new HashMap<>();
503         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
504         inputs.put("Channel", channel);
505
506         invokeAction(RENDERING_CONTROL, "GetVolume", inputs);
507     }
508
509     /**
510      * Invoke SetVolume on UPnP Rendering Control.
511      *
512      * @param channel
513      * @param volume
514      */
515     protected void setVolume(String channel, PercentType volume) {
516         UpnpRenderingControlConfiguration config = renderingControlConfiguration;
517
518         long newVolume = volume.intValue() * config.maxvolume / 100;
519         Map<String, String> inputs = new HashMap<>();
520         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
521         inputs.put("Channel", channel);
522         inputs.put("DesiredVolume", String.valueOf(newVolume));
523
524         invokeAction(RENDERING_CONTROL, "SetVolume", inputs);
525     }
526
527     /**
528      * Invoke SetVolume for Master channel on UPnP Rendering Control.
529      *
530      * @param volume
531      */
532     public void setVolume(PercentType volume) {
533         setVolume(UPNP_MASTER, volume);
534     }
535
536     /**
537      * Invoke getMute on UPnP Rendering Control.
538      * Result is received in {@link onValueReceived}.
539      *
540      * @param channel
541      */
542     protected void getMute(String channel) {
543         Map<String, String> inputs = new HashMap<>();
544         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
545         inputs.put("Channel", channel);
546
547         invokeAction(RENDERING_CONTROL, "GetMute", inputs);
548     }
549
550     /**
551      * Invoke SetMute on UPnP Rendering Control.
552      *
553      * @param channel
554      * @param mute
555      */
556     protected void setMute(String channel, OnOffType mute) {
557         Map<String, String> inputs = new HashMap<>();
558         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
559         inputs.put("Channel", channel);
560         inputs.put("DesiredMute", mute == OnOffType.ON ? "1" : "0");
561
562         invokeAction(RENDERING_CONTROL, "SetMute", inputs);
563     }
564
565     /**
566      * Invoke getMute on UPnP Rendering Control.
567      * Result is received in {@link onValueReceived}.
568      *
569      * @param channel
570      */
571     protected void getLoudness(String channel) {
572         Map<String, String> inputs = new HashMap<>();
573         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
574         inputs.put("Channel", channel);
575
576         invokeAction(RENDERING_CONTROL, "GetLoudness", inputs);
577     }
578
579     /**
580      * Invoke SetMute on UPnP Rendering Control.
581      *
582      * @param channel
583      * @param mute
584      */
585     protected void setLoudness(String channel, OnOffType mute) {
586         Map<String, String> inputs = new HashMap<>();
587         inputs.put(INSTANCE_ID, Integer.toString(rcsId));
588         inputs.put("Channel", channel);
589         inputs.put("DesiredLoudness", mute == OnOffType.ON ? "1" : "0");
590
591         invokeAction(RENDERING_CONTROL, "SetLoudness", inputs);
592     }
593
594     /**
595      * Called from server handler for renderer to be able to send back status to server handler
596      *
597      * @param handler
598      */
599     protected void setServerHandler(UpnpServerHandler handler) {
600         logger.debug("Set server handler {} on renderer {}", handler.getThing().getLabel(), thing.getLabel());
601         serverHandlers.add(handler);
602     }
603
604     /**
605      * Should be called from server handler when server stops serving this renderer
606      */
607     protected void unsetServerHandler() {
608         logger.debug("Unset server handler on renderer {}", thing.getLabel());
609         for (UpnpServerHandler handler : serverHandlers) {
610             Thing serverThing = handler.getThing();
611             Channel serverChannel;
612             for (String channel : SERVER_CONTROL_CHANNELS) {
613                 if ((serverChannel = serverThing.getChannel(channel)) != null) {
614                     handler.updateServerState(serverChannel.getUID(), UnDefType.UNDEF);
615                 }
616             }
617
618             serverHandlers.remove(handler);
619         }
620     }
621
622     @Override
623     protected void updateState(ChannelUID channelUID, State state) {
624         // override to be able to propagate channel state updates to corresponding channels on the server
625         if (SERVER_CONTROL_CHANNELS.contains(channelUID.getId())) {
626             for (UpnpServerHandler handler : serverHandlers) {
627                 Thing serverThing = handler.getThing();
628                 Channel serverChannel = serverThing.getChannel(channelUID.getId());
629                 if (serverChannel != null) {
630                     logger.debug("Update server {} channel {} with state {} from renderer {}", serverThing.getLabel(),
631                             state, channelUID, thing.getLabel());
632                     handler.updateServerState(serverChannel.getUID(), state);
633                 }
634             }
635         }
636         super.updateState(channelUID, state);
637     }
638
639     @Override
640     public void handleCommand(ChannelUID channelUID, Command command) {
641         logger.debug("Handle command {} for channel {} on renderer {}", command, channelUID, thing.getLabel());
642
643         String id = channelUID.getId();
644
645         if (id.endsWith("volume")) {
646             handleCommandVolume(command, id);
647         } else if (id.endsWith("mute")) {
648             handleCommandMute(command, id);
649         } else if (id.endsWith("loudness")) {
650             handleCommandLoudness(command, id);
651         } else {
652             switch (id) {
653                 case STOP:
654                     handleCommandStop(command);
655                     break;
656                 case CONTROL:
657                     handleCommandControl(channelUID, command);
658                     break;
659                 case REPEAT:
660                     handleCommandRepeat(channelUID, command);
661                     break;
662                 case SHUFFLE:
663                     handleCommandShuffle(channelUID, command);
664                 case ONLY_PLAY_ONE:
665                     handleCommandOnlyPlayOne(channelUID, command);
666                     break;
667                 case URI:
668                     handleCommandUri(channelUID, command);
669                     break;
670                 case FAVORITE_SELECT:
671                     handleCommandFavoriteSelect(command);
672                     break;
673                 case FAVORITE:
674                     handleCommandFavorite(channelUID, command);
675                     break;
676                 case FAVORITE_ACTION:
677                     handleCommandFavoriteAction(command);
678                     break;
679                 case PLAYLIST_SELECT:
680                     handleCommandPlaylistSelect(command);
681                     break;
682                 case TRACK_POSITION:
683                     handleCommandTrackPosition(channelUID, command);
684                     break;
685                 case REL_TRACK_POSITION:
686                     handleCommandRelTrackPosition(channelUID, command);
687                     break;
688                 default:
689                     break;
690             }
691         }
692     }
693
694     private void handleCommandVolume(Command command, String id) {
695         if (command instanceof RefreshType) {
696             getVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""));
697         } else if (command instanceof PercentType) {
698             setVolume("volume".equals(id) ? UPNP_MASTER : id.replace("volume", ""), (PercentType) command);
699         }
700     }
701
702     private void handleCommandMute(Command command, String id) {
703         if (command instanceof RefreshType) {
704             getMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""));
705         } else if (command instanceof OnOffType) {
706             setMute("mute".equals(id) ? UPNP_MASTER : id.replace("mute", ""), (OnOffType) command);
707         }
708     }
709
710     private void handleCommandLoudness(Command command, String id) {
711         if (command instanceof RefreshType) {
712             getLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""));
713         } else if (command instanceof OnOffType) {
714             setLoudness("loudness".equals(id) ? UPNP_MASTER : id.replace("loudness", ""), (OnOffType) command);
715         }
716     }
717
718     private void handleCommandStop(Command command) {
719         if (OnOffType.ON.equals(command)) {
720             updateState(CONTROL, PlayPauseType.PAUSE);
721             stop();
722             updateState(TRACK_POSITION, new QuantityType<>(0, Units.SECOND));
723         }
724     }
725
726     private void handleCommandControl(ChannelUID channelUID, Command command) {
727         String state;
728         if (command instanceof RefreshType) {
729             state = transportState;
730             State newState = UnDefType.UNDEF;
731             if ("PLAYING".equals(state)) {
732                 newState = PlayPauseType.PLAY;
733             } else if ("STOPPED".equals(state)) {
734                 newState = PlayPauseType.PAUSE;
735             } else if ("PAUSED_PLAYBACK".equals(state)) {
736                 newState = PlayPauseType.PAUSE;
737             }
738             updateState(channelUID, newState);
739         } else if (command instanceof PlayPauseType) {
740             if (PlayPauseType.PLAY.equals(command)) {
741                 if (registeredQueue) {
742                     registeredQueue = false;
743                     playingQueue = true;
744                     oneplayed = false;
745                     serve();
746                 } else {
747                     play();
748                 }
749             } else if (PlayPauseType.PAUSE.equals(command)) {
750                 checkPaused();
751                 pause();
752             }
753         } else if (command instanceof NextPreviousType) {
754             if (NextPreviousType.NEXT.equals(command)) {
755                 serveNext();
756             } else if (NextPreviousType.PREVIOUS.equals(command)) {
757                 servePrevious();
758             }
759         } else if (command instanceof RewindFastforwardType) {
760             int pos = 0;
761             if (RewindFastforwardType.FASTFORWARD.equals(command)) {
762                 pos = Integer.min(trackDuration, trackPosition + config.seekStep);
763             } else if (command == RewindFastforwardType.REWIND) {
764                 pos = Integer.max(0, trackPosition - config.seekStep);
765             }
766             seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
767         }
768     }
769
770     private void handleCommandRepeat(ChannelUID channelUID, Command command) {
771         if (command instanceof RefreshType) {
772             updateState(channelUID, OnOffType.from(repeat));
773         } else {
774             repeat = (OnOffType.ON.equals(command));
775             currentQueue.setRepeat(repeat);
776             updateState(channelUID, OnOffType.from(repeat));
777             logger.debug("Repeat set to {} for {}", repeat, thing.getLabel());
778         }
779     }
780
781     private void handleCommandShuffle(ChannelUID channelUID, Command command) {
782         if (command instanceof RefreshType) {
783             updateState(channelUID, OnOffType.from(shuffle));
784         } else {
785             shuffle = (OnOffType.ON.equals(command));
786             currentQueue.setShuffle(shuffle);
787             if (!playing) {
788                 resetToStartQueue();
789             }
790             updateState(channelUID, OnOffType.from(shuffle));
791             logger.debug("Shuffle set to {} for {}", shuffle, thing.getLabel());
792         }
793     }
794
795     private void handleCommandOnlyPlayOne(ChannelUID channelUID, Command command) {
796         if (command instanceof RefreshType) {
797             updateState(channelUID, OnOffType.from(onlyplayone));
798         } else {
799             onlyplayone = (OnOffType.ON.equals(command));
800             oneplayed = (onlyplayone && playing) ? true : false;
801             if (oneplayed) {
802                 setNextURI("", "");
803             } else {
804                 UpnpEntry next = nextEntry;
805                 if (next != null) {
806                     setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
807                 }
808             }
809             updateState(channelUID, OnOffType.from(onlyplayone));
810             logger.debug("OnlyPlayOne set to {} for {}", onlyplayone, thing.getLabel());
811         }
812     }
813
814     private void handleCommandUri(ChannelUID channelUID, Command command) {
815         if (command instanceof RefreshType) {
816             updateState(channelUID, StringType.valueOf(nowPlayingUri));
817         } else if (command instanceof StringType) {
818             setCurrentURI(command.toString(), "");
819             play();
820         }
821     }
822
823     private void handleCommandFavoriteSelect(Command command) {
824         if (command instanceof StringType) {
825             favoriteName = command.toString();
826             updateState(FAVORITE, StringType.valueOf(favoriteName));
827             playFavorite();
828         }
829     }
830
831     private void handleCommandFavorite(ChannelUID channelUID, Command command) {
832         if (command instanceof StringType) {
833             favoriteName = command.toString();
834             if (favoriteCommandOptionList.contains(new CommandOption(favoriteName, favoriteName))) {
835                 playFavorite();
836             }
837         }
838         updateState(channelUID, StringType.valueOf(favoriteName));
839     }
840
841     private void handleCommandFavoriteAction(Command command) {
842         if (command instanceof StringType) {
843             switch (command.toString()) {
844                 case SAVE:
845                     handleCommandFavoriteSave();
846                     break;
847                 case DELETE:
848                     handleCommandFavoriteDelete();
849                     break;
850             }
851         }
852     }
853
854     private void handleCommandFavoriteSave() {
855         if (!favoriteName.isEmpty()) {
856             UpnpFavorite favorite = new UpnpFavorite(favoriteName, nowPlayingUri, currentEntry);
857             favorite.saveFavorite(favoriteName, bindingConfig.path);
858             updateFavoritesList();
859         }
860     }
861
862     private void handleCommandFavoriteDelete() {
863         if (!favoriteName.isEmpty()) {
864             UpnpControlUtil.deleteFavorite(favoriteName, bindingConfig.path);
865             updateFavoritesList();
866             updateState(FAVORITE, UnDefType.UNDEF);
867         }
868     }
869
870     private void handleCommandPlaylistSelect(Command command) {
871         if (command instanceof StringType) {
872             String playlistName = command.toString();
873             UpnpEntryQueue queue = new UpnpEntryQueue();
874             queue.restoreQueue(playlistName, null, bindingConfig.path);
875             registerQueue(queue);
876             resetToStartQueue();
877             playingQueue = true;
878             serve();
879         }
880     }
881
882     private void handleCommandTrackPosition(ChannelUID channelUID, Command command) {
883         if (command instanceof RefreshType) {
884             updateState(channelUID, new QuantityType<>(trackPosition, Units.SECOND));
885         } else if (command instanceof QuantityType<?>) {
886             QuantityType<?> position = ((QuantityType<?>) command).toUnit(Units.SECOND);
887             if (position != null) {
888                 int pos = Integer.min(trackDuration, position.intValue());
889                 seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
890             }
891         }
892     }
893
894     private void handleCommandRelTrackPosition(ChannelUID channelUID, Command command) {
895         if (command instanceof RefreshType) {
896             int relPosition = (trackDuration != 0) ? (trackPosition * 100) / trackDuration : 0;
897             updateState(channelUID, new PercentType(relPosition));
898         } else if (command instanceof PercentType) {
899             int pos = ((PercentType) command).intValue() * trackDuration / 100;
900             seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
901         }
902     }
903
904     /**
905      * Set the volume for notifications.
906      *
907      * @param volume
908      */
909     public void setNotificationVolume(PercentType volume) {
910         notificationVolume = volume;
911     }
912
913     /**
914      * Play a notification. Previous state of the renderer will resume at the end of the notification, or after the
915      * maximum notification duration as defined in the renderer parameters.
916      *
917      * @param URI for notification sound
918      */
919     public void playNotification(String URI) {
920         synchronized (notificationLock) {
921             if (URI.isEmpty()) {
922                 logger.debug("UPnP device {} received empty notification URI", thing.getLabel());
923                 return;
924             }
925
926             notificationUri = URI;
927
928             logger.debug("UPnP device {} playing notification {}", thing.getLabel(), URI);
929
930             cancelTrackPositionRefresh();
931             getPositionInfo();
932
933             cancelPlayingNotificationFuture();
934
935             if (config.maxNotificationDuration > 0) {
936                 playingNotificationFuture = upnpScheduler.schedule(this::stop, config.maxNotificationDuration,
937                         TimeUnit.SECONDS);
938             }
939             playingNotification = true;
940
941             setCurrentURI(URI, "");
942             setNextURI("", "");
943             PercentType volume = notificationVolume;
944             setVolume(volume == null
945                     ? new PercentType(Math.min(100,
946                             Math.max(0, (100 + config.notificationVolumeAdjustment) * soundVolume.intValue() / 100)))
947                     : volume);
948
949             CompletableFuture<Boolean> stopping = isStopping;
950             try {
951                 if (stopping != null) {
952                     // wait for maximum 2.5s until the renderer stopped before playing
953                     stopping.get(config.responseTimeout, TimeUnit.MILLISECONDS);
954                 }
955             } catch (InterruptedException | ExecutionException | TimeoutException e) {
956                 logger.debug("Timeout exception, renderer {} didn't stop yet, trying to play anyway", thing.getLabel());
957             }
958             play();
959         }
960     }
961
962     private void cancelPlayingNotificationFuture() {
963         ScheduledFuture<?> future = playingNotificationFuture;
964         if (future != null) {
965             future.cancel(true);
966             playingNotificationFuture = null;
967         }
968     }
969
970     private void resumeAfterNotification() {
971         synchronized (notificationLock) {
972             logger.debug("UPnP device {} resume after playing notification", thing.getLabel());
973
974             setCurrentURI(nowPlayingUri, "");
975             setVolume(soundVolume);
976
977             cancelPlayingNotificationFuture();
978
979             playingNotification = false;
980             notificationVolume = null;
981             notificationUri = "";
982
983             if (playing) {
984                 int pos = posAtNotificationStart;
985                 seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
986                 play();
987             }
988             posAtNotificationStart = 0;
989         }
990     }
991
992     private void playFavorite() {
993         UpnpFavorite favorite = new UpnpFavorite(favoriteName, bindingConfig.path);
994         String uri = favorite.getUri();
995         UpnpEntry entry = favorite.getUpnpEntry();
996         if (!uri.isEmpty()) {
997             String metadata = "";
998             if (entry != null) {
999                 metadata = UpnpXMLParser.compileMetadataString(entry);
1000             }
1001             setCurrentURI(uri, metadata);
1002             play();
1003         }
1004     }
1005
1006     void updateFavoritesList() {
1007         favoriteCommandOptionList = UpnpControlUtil.favorites(bindingConfig.path).stream()
1008                 .map(p -> (new CommandOption(p, p))).collect(Collectors.toList());
1009         updateCommandDescription(favoriteSelectChannelUID, favoriteCommandOptionList);
1010     }
1011
1012     @Override
1013     public void playlistsListChanged() {
1014         playlistCommandOptionList = UpnpControlUtil.playlists().stream().map(p -> (new CommandOption(p, p)))
1015                 .collect(Collectors.toList());
1016         updateCommandDescription(playlistSelectChannelUID, playlistCommandOptionList);
1017     }
1018
1019     @Override
1020     public void onStatusChanged(boolean status) {
1021         if (!status) {
1022             removeSubscriptions();
1023
1024             updateState(CONTROL, PlayPauseType.PAUSE);
1025             cancelTrackPositionRefresh();
1026         }
1027         super.onStatusChanged(status);
1028     }
1029
1030     @Override
1031     protected @Nullable String preProcessValueReceived(Map<String, String> inputs, @Nullable String variable,
1032             @Nullable String value, @Nullable String service, @Nullable String action) {
1033         if (variable == null) {
1034             return null;
1035         } else {
1036             switch (variable) {
1037                 case "CurrentVolume":
1038                     return (inputs.containsKey("Channel") ? inputs.get("Channel") : UPNP_MASTER) + "Volume";
1039                 case "CurrentMute":
1040                     return (inputs.containsKey("Channel") ? inputs.get("Channel") : UPNP_MASTER) + "Mute";
1041                 case "CurrentLoudness":
1042                     return (inputs.containsKey("Channel") ? inputs.get("Channel") : UPNP_MASTER) + "Loudness";
1043                 default:
1044                     return variable;
1045             }
1046         }
1047     }
1048
1049     @Override
1050     public void onValueReceived(@Nullable String variable, @Nullable String value, @Nullable String service) {
1051         if (logger.isTraceEnabled()) {
1052             logger.trace("UPnP device {} received variable {} with value {} from service {}", thing.getLabel(),
1053                     variable, value, service);
1054         } else {
1055             if (logger.isDebugEnabled() && !("AbsTime".equals(variable) || "RelCount".equals(variable)
1056                     || "RelTime".equals(variable) || "AbsCount".equals(variable) || "Track".equals(variable)
1057                     || "TrackDuration".equals(variable))) {
1058                 // don't log all variables received when updating the track position every second
1059                 logger.debug("UPnP device {} received variable {} with value {} from service {}", thing.getLabel(),
1060                         variable, value, service);
1061             }
1062         }
1063         if (variable == null) {
1064             return;
1065         }
1066
1067         if (variable.endsWith("Volume")) {
1068             onValueReceivedVolume(variable, value);
1069         } else if (variable.endsWith("Mute")) {
1070             onValueReceivedMute(variable, value);
1071         } else if (variable.endsWith("Loudness")) {
1072             onValueReceivedLoudness(variable, value);
1073         } else {
1074             switch (variable) {
1075                 case "LastChange":
1076                     onValueReceivedLastChange(value, service);
1077                     break;
1078                 case "CurrentTransportState":
1079                 case "TransportState":
1080                     onValueReceivedTransportState(value);
1081                     break;
1082                 case "CurrentTrackURI":
1083                 case "CurrentURI":
1084                     onValueReceivedCurrentURI(value);
1085                     break;
1086                 case "CurrentTrackMetaData":
1087                 case "CurrentURIMetaData":
1088                     onValueReceivedCurrentMetaData(value);
1089                     break;
1090                 case "NextAVTransportURIMetaData":
1091                 case "NextURIMetaData":
1092                     onValueReceivedNextMetaData(value);
1093                     break;
1094                 case "CurrentTrackDuration":
1095                 case "TrackDuration":
1096                     onValueReceivedDuration(value);
1097                     break;
1098                 case "RelTime":
1099                     onValueReceivedRelTime(value);
1100                     break;
1101                 default:
1102                     super.onValueReceived(variable, value, service);
1103                     break;
1104             }
1105         }
1106     }
1107
1108     private void onValueReceivedVolume(String variable, @Nullable String value) {
1109         if (value != null && !value.isEmpty()) {
1110             UpnpRenderingControlConfiguration config = renderingControlConfiguration;
1111
1112             long volume = Long.valueOf(value);
1113             volume = volume * 100 / config.maxvolume;
1114
1115             String upnpChannel = variable.replace("Volume", "volume").replace("Master", "");
1116             updateState(upnpChannel, new PercentType((int) volume));
1117
1118             if (!playingNotification && "volume".equals(upnpChannel)) {
1119                 soundVolume = new PercentType((int) volume);
1120             }
1121         }
1122     }
1123
1124     private void onValueReceivedMute(String variable, @Nullable String value) {
1125         if (value != null && !value.isEmpty()) {
1126             String upnpChannel = variable.replace("Mute", "mute").replace("Master", "");
1127             updateState(upnpChannel,
1128                     ("1".equals(value) || "true".equals(value.toLowerCase())) ? OnOffType.ON : OnOffType.OFF);
1129         }
1130     }
1131
1132     private void onValueReceivedLoudness(String variable, @Nullable String value) {
1133         if (value != null && !value.isEmpty()) {
1134             String upnpChannel = variable.replace("Loudness", "loudness").replace("Master", "");
1135             updateState(upnpChannel,
1136                     ("1".equals(value) || "true".equals(value.toLowerCase())) ? OnOffType.ON : OnOffType.OFF);
1137         }
1138     }
1139
1140     private void onValueReceivedLastChange(@Nullable String value, @Nullable String service) {
1141         // This is returned from a GENA subscription. The jupnp library does not allow receiving new GENA subscription
1142         // messages as long as this thread has not finished. As we may trigger long running processes based on this
1143         // result, we run it in a separate thread.
1144         upnpScheduler.submit(() -> {
1145             // pre-process some variables, eg XML processing
1146             if (value != null && !value.isEmpty()) {
1147                 if (AV_TRANSPORT.equals(service)) {
1148                     Map<String, String> parsedValues = UpnpXMLParser.getAVTransportFromXML(value);
1149                     for (Map.Entry<String, String> entrySet : parsedValues.entrySet()) {
1150                         switch (entrySet.getKey()) {
1151                             case "TransportState":
1152                                 // Update the transport state after the update of the media information
1153                                 // to not break the notification mechanism
1154                                 break;
1155                             case "AVTransportURI":
1156                                 onValueReceived("CurrentTrackURI", entrySet.getValue(), service);
1157                                 break;
1158                             case "AVTransportURIMetaData":
1159                                 onValueReceived("CurrentTrackMetaData", entrySet.getValue(), service);
1160                                 break;
1161                             default:
1162                                 onValueReceived(entrySet.getKey(), entrySet.getValue(), service);
1163                         }
1164                     }
1165                     if (parsedValues.containsKey("TransportState")) {
1166                         onValueReceived("TransportState", parsedValues.get("TransportState"), service);
1167                     }
1168                 } else if (RENDERING_CONTROL.equals(service)) {
1169                     Map<String, @Nullable String> parsedValues = UpnpXMLParser.getRenderingControlFromXML(value);
1170                     for (String parsedValue : parsedValues.keySet()) {
1171                         onValueReceived(parsedValue, parsedValues.get(parsedValue), RENDERING_CONTROL);
1172                     }
1173                 }
1174             }
1175         });
1176     }
1177
1178     private void onValueReceivedTransportState(@Nullable String value) {
1179         transportState = (value == null) ? "" : value;
1180
1181         if ("STOPPED".equals(value)) {
1182             CompletableFuture<Boolean> stopping = isStopping;
1183             if (stopping != null) {
1184                 stopping.complete(true); // We have received stop confirmation
1185                 isStopping = null;
1186             }
1187
1188             if (playingNotification) {
1189                 resumeAfterNotification();
1190                 return;
1191             }
1192
1193             cancelCheckPaused();
1194             updateState(CONTROL, PlayPauseType.PAUSE);
1195             cancelTrackPositionRefresh();
1196             // Only go to next for first STOP command, then wait until we received PLAYING before moving
1197             // to next (avoids issues with renderers sending multiple stop states)
1198             if (playing) {
1199                 playing = false;
1200
1201                 // playerStopped is true if stop came from openHAB. This allows us to identify if we played to the
1202                 // end of an entry, because STOP would come from the player and not from openHAB. We should then
1203                 // move to the next entry if the queue is not at the end already.
1204                 if (!playerStopped) {
1205                     if (Instant.now().toEpochMilli() >= expectedTrackend) {
1206                         // If we are receiving track duration info, we know when the track is expected to end. If we
1207                         // received STOP before track end, and it is not coming from openHAB, it must have been stopped
1208                         // from the renderer directly, and we do not want to play the next entry.
1209                         if (playingQueue) {
1210                             serveNext();
1211                         }
1212                     }
1213                 } else if (playingQueue) {
1214                     playingQueue = false;
1215                 }
1216             }
1217         } else if ("PLAYING".equals(value)) {
1218             if (playingNotification) {
1219                 return;
1220             }
1221
1222             playerStopped = false;
1223             playing = true;
1224             registeredQueue = false; // reset queue registration flag as we are playing something
1225             updateState(CONTROL, PlayPauseType.PLAY);
1226             scheduleTrackPositionRefresh();
1227         } else if ("PAUSED_PLAYBACK".equals(value)) {
1228             cancelCheckPaused();
1229             updateState(CONTROL, PlayPauseType.PAUSE);
1230         } else if ("NO_MEDIA_PRESENT".equals(value)) {
1231             updateState(CONTROL, UnDefType.UNDEF);
1232         }
1233     }
1234
1235     private void onValueReceivedCurrentURI(@Nullable String value) {
1236         CompletableFuture<Boolean> settingURI = isSettingURI;
1237         if (settingURI != null) {
1238             settingURI.complete(true); // We have received current URI, so can allow play to start
1239         }
1240
1241         UpnpEntry current = currentEntry;
1242         UpnpEntry next = nextEntry;
1243
1244         String uri = "";
1245         String currentUri = "";
1246         String nextUri = "";
1247         if (value != null) {
1248             uri = URLDecoder.decode(value.trim(), StandardCharsets.UTF_8);
1249         }
1250         if (current != null) {
1251             currentUri = URLDecoder.decode(current.getRes().trim(), StandardCharsets.UTF_8);
1252         }
1253         if (next != null) {
1254             nextUri = URLDecoder.decode(next.getRes(), StandardCharsets.UTF_8);
1255         }
1256
1257         if (playingNotification && uri.equals(notificationUri)) {
1258             // No need to update anything more if this is for playing a notification
1259             return;
1260         }
1261
1262         nowPlayingUri = uri;
1263         updateState(URI, StringType.valueOf(uri));
1264
1265         logger.trace("Renderer {} received URI: {}", thing.getLabel(), uri);
1266         logger.trace("Renderer {} current URI: {}, equal to received URI {}", thing.getLabel(), currentUri,
1267                 uri.equals(currentUri));
1268         logger.trace("Renderer {} next URI: {}", thing.getLabel(), nextUri);
1269
1270         if (!uri.equals(currentUri)) {
1271             if ((next != null) && uri.equals(nextUri)) {
1272                 // Renderer advanced to next entry independent of openHAB UPnP control point.
1273                 // Advance in the queue to keep proper position status.
1274                 // Make the next entry available to renderers that support it.
1275                 logger.trace("Renderer {} moved from '{}' to next entry '{}' in queue", thing.getLabel(), current,
1276                         next);
1277                 currentEntry = currentQueue.next();
1278                 nextEntry = currentQueue.get(currentQueue.nextIndex());
1279                 logger.trace("Renderer {} auto move forward, current queue index: {}", thing.getLabel(),
1280                         currentQueue.index());
1281
1282                 updateMetaDataState(next);
1283
1284                 // look one further to get next entry for next URI
1285                 next = nextEntry;
1286                 if ((next != null) && !onlyplayone) {
1287                     setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
1288                 }
1289             } else {
1290                 // A new entry is being served that does not match the next entry in the queue. This can be because a
1291                 // sound or stream is being played through an action, or another control point started a new entry.
1292                 // We should clear the metadata in this case and wait for new metadata to arrive.
1293                 clearMetaDataState();
1294             }
1295         }
1296     }
1297
1298     private void onValueReceivedCurrentMetaData(@Nullable String value) {
1299         if (playingNotification) {
1300             // Don't update metadata when playing notification
1301             return;
1302         }
1303
1304         if (value != null && !value.isEmpty()) {
1305             List<UpnpEntry> list = UpnpXMLParser.getEntriesFromXML(value);
1306             if (!list.isEmpty()) {
1307                 updateMetaDataState(list.get(0));
1308                 return;
1309             }
1310         }
1311         clearMetaDataState();
1312     }
1313
1314     private void onValueReceivedNextMetaData(@Nullable String value) {
1315         if (value != null && !value.isEmpty() && !"NOT_IMPLEMENTED".equals(value)) {
1316             List<UpnpEntry> list = UpnpXMLParser.getEntriesFromXML(value);
1317             if (!list.isEmpty()) {
1318                 nextEntry = list.get(0);
1319             }
1320         }
1321     }
1322
1323     private void onValueReceivedDuration(@Nullable String value) {
1324         // track duration and track position have format H+:MM:SS[.F+] or H+:MM:SS[.F0/F1]. We are not
1325         // interested in the fractional seconds, so drop everything after . and calculate in seconds.
1326         if (value == null || "NOT_IMPLEMENTED".equals(value)) {
1327             trackDuration = 0;
1328             updateState(TRACK_DURATION, UnDefType.UNDEF);
1329             updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
1330         } else {
1331             try {
1332                 trackDuration = Arrays.stream(value.split("\\.")[0].split(":")).mapToInt(n -> Integer.parseInt(n))
1333                         .reduce(0, (n, m) -> n * 60 + m);
1334                 updateState(TRACK_DURATION, new QuantityType<>(trackDuration, Units.SECOND));
1335             } catch (NumberFormatException e) {
1336                 logger.debug("Illegal format for track duration {}", value);
1337                 return;
1338             }
1339         }
1340         setExpectedTrackend();
1341     }
1342
1343     private void onValueReceivedRelTime(@Nullable String value) {
1344         if (value == null || "NOT_IMPLEMENTED".equals(value)) {
1345             trackPosition = 0;
1346             updateState(TRACK_POSITION, UnDefType.UNDEF);
1347             updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
1348         } else {
1349             try {
1350                 trackPosition = Arrays.stream(value.split("\\.")[0].split(":")).mapToInt(n -> Integer.parseInt(n))
1351                         .reduce(0, (n, m) -> n * 60 + m);
1352                 updateState(TRACK_POSITION, new QuantityType<>(trackPosition, Units.SECOND));
1353                 int relPosition = (trackDuration != 0) ? trackPosition * 100 / trackDuration : 0;
1354                 updateState(REL_TRACK_POSITION, new PercentType(relPosition));
1355             } catch (NumberFormatException e) {
1356                 logger.trace("Illegal format for track position {}", value);
1357                 return;
1358             }
1359         }
1360
1361         if (playingNotification) {
1362             posAtNotificationStart = trackPosition;
1363         }
1364
1365         setExpectedTrackend();
1366     }
1367
1368     @Override
1369     protected void updateProtocolInfo(String value) {
1370         sink.clear();
1371         supportedAudioFormats.clear();
1372         audioSupport = false;
1373
1374         sink.addAll(Arrays.asList(value.split(",")));
1375
1376         for (String protocol : sink) {
1377             Matcher matcher = PROTOCOL_PATTERN.matcher(protocol);
1378             if (matcher.find()) {
1379                 String format = matcher.group(1);
1380                 switch (format) {
1381                     case "audio/mpeg3":
1382                     case "audio/mp3":
1383                     case "audio/mpeg":
1384                         supportedAudioFormats.add(AudioFormat.MP3);
1385                         break;
1386                     case "audio/wav":
1387                     case "audio/wave":
1388                         supportedAudioFormats.add(AudioFormat.WAV);
1389                         break;
1390                 }
1391                 audioSupport = audioSupport || Pattern.matches("audio.*", format);
1392             }
1393         }
1394
1395         if (audioSupport) {
1396             logger.debug("Renderer {} supports audio", thing.getLabel());
1397             registerAudioSink();
1398         }
1399     }
1400
1401     private void clearCurrentEntry() {
1402         clearMetaDataState();
1403
1404         trackDuration = 0;
1405         updateState(TRACK_DURATION, UnDefType.UNDEF);
1406         trackPosition = 0;
1407         updateState(TRACK_POSITION, UnDefType.UNDEF);
1408         updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
1409
1410         currentEntry = null;
1411     }
1412
1413     /**
1414      * Register a new queue with media entries to the renderer. Set the next position at the first entry in the list.
1415      * If the renderer is currently playing, set the first entry in the list as the next media. If not playing, set it
1416      * as current media.
1417      *
1418      * @param queue
1419      */
1420     protected void registerQueue(UpnpEntryQueue queue) {
1421         if (currentQueue.equals(queue)) {
1422             // We get the same queue, so do nothing
1423             return;
1424         }
1425
1426         logger.debug("Registering queue on renderer {}", thing.getLabel());
1427
1428         registeredQueue = true;
1429         currentQueue = queue;
1430         currentQueue.setRepeat(repeat);
1431         currentQueue.setShuffle(shuffle);
1432         if (playingQueue) {
1433             nextEntry = currentQueue.get(currentQueue.nextIndex());
1434             UpnpEntry next = nextEntry;
1435             if ((next != null) && !onlyplayone) {
1436                 // make the next entry available to renderers that support it
1437                 logger.trace("Renderer {} still playing, set new queue as next entry", thing.getLabel());
1438                 setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
1439             }
1440         } else {
1441             resetToStartQueue();
1442         }
1443     }
1444
1445     /**
1446      * Move to next position in queue and start playing.
1447      */
1448     private void serveNext() {
1449         if (currentQueue.hasNext()) {
1450             currentEntry = currentQueue.next();
1451             nextEntry = currentQueue.get(currentQueue.nextIndex());
1452             logger.debug("Serve next media '{}' from queue on renderer {}", currentEntry, thing.getLabel());
1453             logger.trace("Serve next, current queue index: {}", currentQueue.index());
1454
1455             serve();
1456         } else {
1457             logger.debug("Cannot serve next, end of queue on renderer {}", thing.getLabel());
1458             resetToStartQueue();
1459         }
1460     }
1461
1462     /**
1463      * Move to previous position in queue and start playing.
1464      */
1465     private void servePrevious() {
1466         if (currentQueue.hasPrevious()) {
1467             currentEntry = currentQueue.previous();
1468             nextEntry = currentQueue.get(currentQueue.nextIndex());
1469             logger.debug("Serve previous media '{}' from queue on renderer {}", currentEntry, thing.getLabel());
1470             logger.trace("Serve previous, current queue index: {}", currentQueue.index());
1471
1472             serve();
1473         } else {
1474             logger.debug("Cannot serve previous, already at start of queue on renderer {}", thing.getLabel());
1475             resetToStartQueue();
1476         }
1477     }
1478
1479     private void resetToStartQueue() {
1480         logger.trace("Reset to start queue on renderer {}", thing.getLabel());
1481
1482         playingQueue = false;
1483         registeredQueue = true;
1484
1485         stop();
1486
1487         currentQueue.resetIndex(); // reset to beginning of queue
1488         currentEntry = currentQueue.next();
1489         nextEntry = currentQueue.get(currentQueue.nextIndex());
1490         logger.trace("Reset queue, current queue index: {}", currentQueue.index());
1491         UpnpEntry current = currentEntry;
1492         if (current != null) {
1493             clearMetaDataState();
1494             updateMetaDataState(current);
1495             setCurrentURI(current.getRes(), UpnpXMLParser.compileMetadataString(current));
1496         } else {
1497             clearCurrentEntry();
1498         }
1499
1500         UpnpEntry next = nextEntry;
1501         if (onlyplayone) {
1502             setNextURI("", "");
1503         } else if (next != null) {
1504             setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
1505         }
1506     }
1507
1508     /**
1509      * Serve media from a queue and play immediately when already playing.
1510      *
1511      * @param media
1512      */
1513     private void serve() {
1514         logger.trace("Serve media on renderer {}", thing.getLabel());
1515
1516         UpnpEntry entry = currentEntry;
1517         if (entry != null) {
1518             clearMetaDataState();
1519             String res = entry.getRes();
1520             if (res.isEmpty()) {
1521                 logger.debug("Renderer {} cannot serve media '{}', no URI", thing.getLabel(), currentEntry);
1522                 playingQueue = false;
1523                 return;
1524             }
1525             updateMetaDataState(entry);
1526             setCurrentURI(res, UpnpXMLParser.compileMetadataString(entry));
1527
1528             if ((playingQueue || playing) && !(onlyplayone && oneplayed)) {
1529                 logger.trace("Ready to play '{}' from queue", currentEntry);
1530
1531                 trackDuration = 0;
1532                 trackPosition = 0;
1533                 expectedTrackend = 0;
1534                 play();
1535
1536                 oneplayed = true;
1537                 playingQueue = true;
1538             }
1539
1540             // make the next entry available to renderers that support it
1541             if (!onlyplayone) {
1542                 UpnpEntry next = nextEntry;
1543                 if (next != null) {
1544                     setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
1545                 }
1546             }
1547         }
1548     }
1549
1550     /**
1551      * Called before handling a pause CONTROL command. If we do not received PAUSED_PLAYBACK or STOPPED back within
1552      * timeout, we will revert to playing state. This takes care of renderers that cannot pause playback.
1553      */
1554     private void checkPaused() {
1555         paused = upnpScheduler.schedule(this::resetPaused, config.responseTimeout, TimeUnit.MILLISECONDS);
1556     }
1557
1558     private void resetPaused() {
1559         updateState(CONTROL, PlayPauseType.PLAY);
1560     }
1561
1562     private void cancelCheckPaused() {
1563         ScheduledFuture<?> future = paused;
1564         if (future != null) {
1565             future.cancel(true);
1566             paused = null;
1567         }
1568     }
1569
1570     private void setExpectedTrackend() {
1571         expectedTrackend = Instant.now().toEpochMilli() + (trackDuration - trackPosition) * 1000
1572                 - config.responseTimeout;
1573     }
1574
1575     /**
1576      * Update the current track position every second if the channel is linked.
1577      */
1578     private void scheduleTrackPositionRefresh() {
1579         if (playingNotification) {
1580             return;
1581         }
1582
1583         cancelTrackPositionRefresh();
1584         if (!(isLinked(TRACK_POSITION) || isLinked(REL_TRACK_POSITION))) {
1585             // only get it once, so we can use the track end to correctly identify STOP pressed directly on renderer
1586             getPositionInfo();
1587         } else {
1588             if (trackPositionRefresh == null) {
1589                 trackPositionRefresh = upnpScheduler.scheduleWithFixedDelay(this::getPositionInfo, 1, 1,
1590                         TimeUnit.SECONDS);
1591             }
1592         }
1593     }
1594
1595     private void cancelTrackPositionRefresh() {
1596         ScheduledFuture<?> refresh = trackPositionRefresh;
1597
1598         if (refresh != null) {
1599             refresh.cancel(true);
1600         }
1601         trackPositionRefresh = null;
1602
1603         trackPosition = 0;
1604         updateState(TRACK_POSITION, new QuantityType<>(trackPosition, Units.SECOND));
1605         int relPosition = (trackDuration != 0) ? trackPosition / trackDuration : 0;
1606         updateState(REL_TRACK_POSITION, new PercentType(relPosition));
1607     }
1608
1609     /**
1610      * Update metadata channels for media with data received from the Media Server or AV Transport.
1611      *
1612      * @param media
1613      */
1614     private void updateMetaDataState(UpnpEntry media) {
1615         // We don't want to update metadata if the metadata from the AVTransport is less complete than in the current
1616         // entry.
1617         boolean isCurrent = false;
1618         UpnpEntry entry = null;
1619         if (playingQueue) {
1620             entry = currentEntry;
1621         }
1622
1623         logger.trace("Renderer {}, received media ID: {}", thing.getLabel(), media.getId());
1624
1625         if ((entry != null) && entry.getId().equals(media.getId())) {
1626             logger.trace("Current ID: {}", entry.getId());
1627
1628             isCurrent = true;
1629         } else {
1630             // Sometimes we receive the media URL without the ID, then compare on URL
1631             String mediaRes = media.getRes().trim();
1632             String entryRes = (entry != null) ? entry.getRes().trim() : "";
1633
1634             String mediaUrl = URLDecoder.decode(mediaRes, StandardCharsets.UTF_8);
1635             String entryUrl = URLDecoder.decode(entryRes, StandardCharsets.UTF_8);
1636             isCurrent = mediaUrl.equals(entryUrl);
1637
1638             logger.trace("Current queue res: {}", entryRes);
1639             logger.trace("Updated media res: {}", mediaRes);
1640         }
1641
1642         logger.trace("Received meta data is for current entry: {}", isCurrent);
1643
1644         if (!(isCurrent && media.getTitle().isEmpty())) {
1645             updateState(TITLE, StringType.valueOf(media.getTitle()));
1646         }
1647         if (!(isCurrent && (media.getAlbum().isEmpty() || media.getAlbum().matches("Unknown.*")))) {
1648             updateState(ALBUM, StringType.valueOf(media.getAlbum()));
1649         }
1650         if (!(isCurrent
1651                 && (media.getAlbumArtUri().isEmpty() || media.getAlbumArtUri().contains("DefaultAlbumCover")))) {
1652             if (media.getAlbumArtUri().isEmpty() || media.getAlbumArtUri().contains("DefaultAlbumCover")) {
1653                 updateState(ALBUM_ART, UnDefType.UNDEF);
1654             } else {
1655                 State albumArt = HttpUtil.downloadImage(media.getAlbumArtUri());
1656                 if (albumArt == null) {
1657                     logger.debug("Failed to download the content of album art from URL {}", media.getAlbumArtUri());
1658                     if (!isCurrent) {
1659                         updateState(ALBUM_ART, UnDefType.UNDEF);
1660                     }
1661                 } else {
1662                     updateState(ALBUM_ART, albumArt);
1663                 }
1664             }
1665         }
1666         if (!(isCurrent && (media.getCreator().isEmpty() || media.getCreator().matches("Unknown.*")))) {
1667             updateState(CREATOR, StringType.valueOf(media.getCreator()));
1668         }
1669         if (!(isCurrent && (media.getArtist().isEmpty() || media.getArtist().matches("Unknown.*")))) {
1670             updateState(ARTIST, StringType.valueOf(media.getArtist()));
1671         }
1672         if (!(isCurrent && (media.getPublisher().isEmpty() || media.getPublisher().matches("Unknown.*")))) {
1673             updateState(PUBLISHER, StringType.valueOf(media.getPublisher()));
1674         }
1675         if (!(isCurrent && (media.getGenre().isEmpty() || media.getGenre().matches("Unknown.*")))) {
1676             updateState(GENRE, StringType.valueOf(media.getGenre()));
1677         }
1678         if (!(isCurrent && (media.getOriginalTrackNumber() == null))) {
1679             Integer trackNumber = media.getOriginalTrackNumber();
1680             State trackNumberState = (trackNumber != null) ? new DecimalType(trackNumber) : UnDefType.UNDEF;
1681             updateState(TRACK_NUMBER, trackNumberState);
1682         }
1683     }
1684
1685     private void clearMetaDataState() {
1686         updateState(TITLE, UnDefType.UNDEF);
1687         updateState(ALBUM, UnDefType.UNDEF);
1688         updateState(ALBUM_ART, UnDefType.UNDEF);
1689         updateState(CREATOR, UnDefType.UNDEF);
1690         updateState(ARTIST, UnDefType.UNDEF);
1691         updateState(PUBLISHER, UnDefType.UNDEF);
1692         updateState(GENRE, UnDefType.UNDEF);
1693         updateState(TRACK_NUMBER, UnDefType.UNDEF);
1694     }
1695
1696     /**
1697      * @return Audio formats supported by the renderer.
1698      */
1699     public Set<AudioFormat> getSupportedAudioFormats() {
1700         return supportedAudioFormats;
1701     }
1702
1703     private void registerAudioSink() {
1704         if (audioSinkRegistered) {
1705             logger.debug("Audio Sink already registered for renderer {}", thing.getLabel());
1706             return;
1707         } else if (!upnpIOService.isRegistered(this)) {
1708             logger.debug("Audio Sink registration for renderer {} failed, no service", thing.getLabel());
1709             return;
1710         }
1711         logger.debug("Registering Audio Sink for renderer {}", thing.getLabel());
1712         audioSinkReg.registerAudioSink(this);
1713         audioSinkRegistered = true;
1714     }
1715
1716     /**
1717      * @return UPnP sink definitions supported by the renderer.
1718      */
1719     protected List<String> getSink() {
1720         return sink;
1721     }
1722 }