2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.upnpcontrol.internal.handler;
15 import static org.openhab.binding.upnpcontrol.internal.UpnpControlBindingConstants.*;
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;
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;
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;
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
84 * @author Mark Herwege - Initial contribution
85 * @author Karel Goderis - Based on UPnP logic in Sonos binding
88 public class UpnpRendererHandler extends UpnpHandler {
90 private final Logger logger = LoggerFactory.getLogger(UpnpRendererHandler.class);
93 static final String RENDERING_CONTROL = "RenderingControl";
94 static final String AV_TRANSPORT = "AVTransport";
95 static final String INSTANCE_ID = "InstanceID";
97 private volatile boolean audioSupport;
98 protected volatile Set<AudioFormat> supportedAudioFormats = new HashSet<>();
99 private volatile boolean audioSinkRegistered;
101 private volatile UpnpAudioSinkReg audioSinkReg;
103 private volatile Set<UpnpServerHandler> serverHandlers = ConcurrentHashMap.newKeySet();
105 protected @NonNullByDefault({}) UpnpControlRendererConfiguration config;
106 private UpnpRenderingControlConfiguration renderingControlConfiguration = new UpnpRenderingControlConfiguration();
108 private volatile List<CommandOption> favoriteCommandOptionList = List.of();
109 private volatile List<CommandOption> playlistCommandOptionList = List.of();
111 private @NonNullByDefault({}) ChannelUID favoriteSelectChannelUID;
112 private @NonNullByDefault({}) ChannelUID playlistSelectChannelUID;
114 private volatile PercentType soundVolume = new PercentType();
115 private @Nullable volatile PercentType notificationVolume;
116 private volatile List<String> sink = new ArrayList<>();
118 private volatile String favoriteName = ""; // Currently selected favorite
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
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;
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
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
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();
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;
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);
171 serviceSubscriptions.add(AV_TRANSPORT);
172 serviceSubscriptions.add(RENDERING_CONTROL);
174 this.audioSinkReg = audioSinkReg;
178 public void initialize() {
180 config = getConfigAs(UpnpControlRendererConfiguration.class);
181 if (config.seekStep < 1) {
184 logger.debug("Initializing handler for media renderer device {}", thing.getLabel());
186 Channel favoriteSelectChannel = thing.getChannel(FAVORITE_SELECT);
187 if (favoriteSelectChannel != null) {
188 favoriteSelectChannelUID = favoriteSelectChannel.getUID();
190 String msg = String.format("@text/offline.channel-undefined [ \"%s\" ]", FAVORITE_SELECT);
191 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
194 Channel playlistSelectChannel = thing.getChannel(PLAYLIST_SELECT);
195 if (playlistSelectChannel != null) {
196 playlistSelectChannelUID = playlistSelectChannel.getUID();
198 String msg = String.format("@text/offline.channel-undefined [ \"%s\" ]", PLAYLIST_SELECT);
199 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, msg);
207 public void dispose() {
208 logger.debug("Disposing handler for media renderer device {}", thing.getLabel());
210 cancelTrackPositionRefresh();
212 CompletableFuture<Boolean> settingURI = isSettingURI;
213 if (settingURI != null) {
214 settingURI.complete(false);
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);
229 if (!ThingStatus.ONLINE.equals(thing.getStatus())) {
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);
241 updateFavoritesList();
242 playlistsListChanged();
244 RemoteDevice device = getDevice();
245 if (device != null) { // The handler factory will update the device config later when it has not been
247 updateDeviceConfig(device);
250 updateStatus(ThingStatus.ONLINE);
253 if (!upnpSubscribed) {
260 public void updateDeviceConfig(RemoteDevice device) {
261 super.updateDeviceConfig(device);
263 UpnpRenderingControlConfiguration config = new UpnpRenderingControlConfiguration(device);
264 renderingControlConfiguration = config;
265 for (String audioChannel : config.audioChannels) {
266 createAudioChannels(audioChannel);
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));
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);
284 if (config.mute && !UPNP_MASTER.equals(audioChannel)) {
285 String name = audioChannel + "mute";
286 if (UpnpChannelName.channelIdToUpnpChannelName(name) != null) {
287 createChannel(UpnpChannelName.channelIdToUpnpChannelName(name));
289 String label = String.format("@text/channel.upnpcontrol.vendormute.label [ \"%s\" ]", audioChannel);
290 createChannel(name, label, "@text/channel.upnpcontrol.vendormute.description", ITEM_TYPE_MUTE,
294 if (config.loudness) {
295 String name = (UPNP_MASTER.equals(audioChannel) ? "" : audioChannel) + "loudness";
296 if (UpnpChannelName.channelIdToUpnpChannelName(name) != null) {
297 createChannel(UpnpChannelName.channelIdToUpnpChannelName(name));
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);
307 * Invoke Stop on UPnP AV Transport.
310 playerStopped = true;
313 CompletableFuture<Boolean> stopping = isStopping;
314 if (stopping != null) {
315 stopping.complete(false);
317 isStopping = new CompletableFuture<Boolean>(); // set this so we can check if stop confirmation has been
321 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
323 invokeAction(AV_TRANSPORT, "Stop", inputs);
327 * Invoke Play on UPnP AV Transport.
330 CompletableFuture<Boolean> settingURI = isSettingURI;
331 boolean uriSet = true;
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);
337 } catch (InterruptedException | ExecutionException | TimeoutException e) {
338 logger.debug("Timeout exception, media URI not yet set in renderer {}, trying to play anyway",
343 Map<String, String> inputs = new HashMap<>();
344 inputs.put(INSTANCE_ID, Integer.toString(avTransportId));
345 inputs.put("Speed", "1");
347 invokeAction(AV_TRANSPORT, "Play", inputs);
349 logger.debug("Cannot play, cancelled setting URI in the renderer {}", thing.getLabel());
354 * Invoke Pause on UPnP AV Transport.
356 protected void pause() {
357 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
359 invokeAction(AV_TRANSPORT, "Pause", inputs);
363 * Invoke Next on UPnP AV Transport.
365 protected void next() {
366 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
368 invokeAction(AV_TRANSPORT, "Next", inputs);
372 * Invoke Previous on UPnP AV Transport.
374 protected void previous() {
375 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
377 invokeAction(AV_TRANSPORT, "Previous", inputs);
381 * Invoke Seek on UPnP AV Transport.
383 * @param seekTarget relative position in current track, format HH:mm:ss
385 protected void seek(String seekTarget) {
386 CompletableFuture<Boolean> settingURI = isSettingURI;
387 boolean uriSet = true;
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);
393 } catch (InterruptedException | ExecutionException | TimeoutException e) {
394 logger.debug("Timeout exception, media URI not yet set in renderer {}, skipping seek", thing.getLabel());
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);
404 invokeAction(AV_TRANSPORT, "Seek", inputs);
406 logger.debug("Cannot seek, cancelled setting URI in the renderer {}", thing.getLabel());
411 * Invoke SetAVTransportURI on UPnP AV Transport.
416 public void setCurrentURI(String URI, String URIMetaData) {
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);
426 isSettingURI = new CompletableFuture<Boolean>(); // set this so we don't start playing when not finished
429 logger.debug("New URI {} is same as previous on renderer {}", nowPlayingUri, thing.getLabel());
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);
437 invokeAction(AV_TRANSPORT, "SetAVTransportURI", inputs);
441 * Invoke SetNextAVTransportURI on UPnP AV Transport.
444 * @param nextURIMetaData
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);
452 invokeAction(AV_TRANSPORT, "SetNextAVTransportURI", inputs);
456 * Invoke GetTransportState on UPnP AV Transport.
457 * Result is received in {@link onValueReceived}.
459 protected void getTransportState() {
460 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
462 invokeAction(AV_TRANSPORT, "GetTransportInfo", inputs);
466 * Invoke getPositionInfo on UPnP AV Transport.
467 * Result is received in {@link onValueReceived}.
469 protected void getPositionInfo() {
470 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
472 invokeAction(AV_TRANSPORT, "GetPositionInfo", inputs);
476 * Invoke GetMediaInfo on UPnP AV Transport.
477 * Result is received in {@link onValueReceived}.
479 protected void getMediaInfo() {
480 Map<String, String> inputs = Collections.singletonMap(INSTANCE_ID, Integer.toString(avTransportId));
482 invokeAction(AV_TRANSPORT, "smarthome:audio stream http://icecast.vrtcdn.be/stubru_tijdloze-high.mp3", inputs);
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}.
489 * @return current volume
491 public PercentType getCurrentVolume() {
496 * Invoke GetVolume on UPnP Rendering Control.
497 * Result is received in {@link onValueReceived}.
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);
506 invokeAction(RENDERING_CONTROL, "GetVolume", inputs);
510 * Invoke SetVolume on UPnP Rendering Control.
515 protected void setVolume(String channel, PercentType volume) {
516 UpnpRenderingControlConfiguration config = renderingControlConfiguration;
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));
524 invokeAction(RENDERING_CONTROL, "SetVolume", inputs);
528 * Invoke SetVolume for Master channel on UPnP Rendering Control.
532 public void setVolume(PercentType volume) {
533 setVolume(UPNP_MASTER, volume);
537 * Invoke getMute on UPnP Rendering Control.
538 * Result is received in {@link onValueReceived}.
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);
547 invokeAction(RENDERING_CONTROL, "GetMute", inputs);
551 * Invoke SetMute on UPnP Rendering Control.
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");
562 invokeAction(RENDERING_CONTROL, "SetMute", inputs);
566 * Invoke getMute on UPnP Rendering Control.
567 * Result is received in {@link onValueReceived}.
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);
576 invokeAction(RENDERING_CONTROL, "GetLoudness", inputs);
580 * Invoke SetMute on UPnP Rendering Control.
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");
591 invokeAction(RENDERING_CONTROL, "SetLoudness", inputs);
595 * Called from server handler for renderer to be able to send back status to server handler
599 protected void setServerHandler(UpnpServerHandler handler) {
600 logger.debug("Set server handler {} on renderer {}", handler.getThing().getLabel(), thing.getLabel());
601 serverHandlers.add(handler);
605 * Should be called from server handler when server stops serving this renderer
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);
618 serverHandlers.remove(handler);
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);
636 super.updateState(channelUID, state);
640 public void handleCommand(ChannelUID channelUID, Command command) {
641 logger.debug("Handle command {} for channel {} on renderer {}", command, channelUID, thing.getLabel());
643 String id = channelUID.getId();
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);
654 handleCommandStop(command);
657 handleCommandControl(channelUID, command);
660 handleCommandRepeat(channelUID, command);
663 handleCommandShuffle(channelUID, command);
665 handleCommandOnlyPlayOne(channelUID, command);
668 handleCommandUri(channelUID, command);
670 case FAVORITE_SELECT:
671 handleCommandFavoriteSelect(command);
674 handleCommandFavorite(channelUID, command);
676 case FAVORITE_ACTION:
677 handleCommandFavoriteAction(command);
679 case PLAYLIST_SELECT:
680 handleCommandPlaylistSelect(command);
683 handleCommandTrackPosition(channelUID, command);
685 case REL_TRACK_POSITION:
686 handleCommandRelTrackPosition(channelUID, command);
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);
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);
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);
718 private void handleCommandStop(Command command) {
719 if (OnOffType.ON.equals(command)) {
720 updateState(CONTROL, PlayPauseType.PAUSE);
722 updateState(TRACK_POSITION, new QuantityType<>(0, Units.SECOND));
726 private void handleCommandControl(ChannelUID channelUID, Command command) {
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;
738 updateState(channelUID, newState);
739 } else if (command instanceof PlayPauseType) {
740 if (PlayPauseType.PLAY.equals(command)) {
741 if (registeredQueue) {
742 registeredQueue = false;
749 } else if (PlayPauseType.PAUSE.equals(command)) {
753 } else if (command instanceof NextPreviousType) {
754 if (NextPreviousType.NEXT.equals(command)) {
756 } else if (NextPreviousType.PREVIOUS.equals(command)) {
759 } else if (command instanceof RewindFastforwardType) {
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);
766 seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
770 private void handleCommandRepeat(ChannelUID channelUID, Command command) {
771 if (command instanceof RefreshType) {
772 updateState(channelUID, OnOffType.from(repeat));
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());
781 private void handleCommandShuffle(ChannelUID channelUID, Command command) {
782 if (command instanceof RefreshType) {
783 updateState(channelUID, OnOffType.from(shuffle));
785 shuffle = (OnOffType.ON.equals(command));
786 currentQueue.setShuffle(shuffle);
790 updateState(channelUID, OnOffType.from(shuffle));
791 logger.debug("Shuffle set to {} for {}", shuffle, thing.getLabel());
795 private void handleCommandOnlyPlayOne(ChannelUID channelUID, Command command) {
796 if (command instanceof RefreshType) {
797 updateState(channelUID, OnOffType.from(onlyplayone));
799 onlyplayone = (OnOffType.ON.equals(command));
800 oneplayed = (onlyplayone && playing) ? true : false;
804 UpnpEntry next = nextEntry;
806 setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
809 updateState(channelUID, OnOffType.from(onlyplayone));
810 logger.debug("OnlyPlayOne set to {} for {}", onlyplayone, thing.getLabel());
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(), "");
823 private void handleCommandFavoriteSelect(Command command) {
824 if (command instanceof StringType) {
825 favoriteName = command.toString();
826 updateState(FAVORITE, StringType.valueOf(favoriteName));
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))) {
838 updateState(channelUID, StringType.valueOf(favoriteName));
841 private void handleCommandFavoriteAction(Command command) {
842 if (command instanceof StringType) {
843 switch (command.toString()) {
845 handleCommandFavoriteSave();
848 handleCommandFavoriteDelete();
854 private void handleCommandFavoriteSave() {
855 if (!favoriteName.isEmpty()) {
856 UpnpFavorite favorite = new UpnpFavorite(favoriteName, nowPlayingUri, currentEntry);
857 favorite.saveFavorite(favoriteName, bindingConfig.path);
858 updateFavoritesList();
862 private void handleCommandFavoriteDelete() {
863 if (!favoriteName.isEmpty()) {
864 UpnpControlUtil.deleteFavorite(favoriteName, bindingConfig.path);
865 updateFavoritesList();
866 updateState(FAVORITE, UnDefType.UNDEF);
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);
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));
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));
905 * Set the volume for notifications.
909 public void setNotificationVolume(PercentType volume) {
910 notificationVolume = volume;
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.
917 * @param URI for notification sound
919 public void playNotification(String URI) {
920 synchronized (notificationLock) {
922 logger.debug("UPnP device {} received empty notification URI", thing.getLabel());
926 notificationUri = URI;
928 logger.debug("UPnP device {} playing notification {}", thing.getLabel(), URI);
930 cancelTrackPositionRefresh();
933 cancelPlayingNotificationFuture();
935 if (config.maxNotificationDuration > 0) {
936 playingNotificationFuture = upnpScheduler.schedule(this::stop, config.maxNotificationDuration,
939 playingNotification = true;
941 setCurrentURI(URI, "");
943 PercentType volume = notificationVolume;
944 setVolume(volume == null
945 ? new PercentType(Math.min(100,
946 Math.max(0, (100 + config.notificationVolumeAdjustment) * soundVolume.intValue() / 100)))
949 CompletableFuture<Boolean> stopping = isStopping;
951 if (stopping != null) {
952 // wait for maximum 2.5s until the renderer stopped before playing
953 stopping.get(config.responseTimeout, TimeUnit.MILLISECONDS);
955 } catch (InterruptedException | ExecutionException | TimeoutException e) {
956 logger.debug("Timeout exception, renderer {} didn't stop yet, trying to play anyway", thing.getLabel());
962 private void cancelPlayingNotificationFuture() {
963 ScheduledFuture<?> future = playingNotificationFuture;
964 if (future != null) {
966 playingNotificationFuture = null;
970 private void resumeAfterNotification() {
971 synchronized (notificationLock) {
972 logger.debug("UPnP device {} resume after playing notification", thing.getLabel());
974 setCurrentURI(nowPlayingUri, "");
975 setVolume(soundVolume);
977 cancelPlayingNotificationFuture();
979 playingNotification = false;
980 notificationVolume = null;
981 notificationUri = "";
984 int pos = posAtNotificationStart;
985 seek(String.format("%02d:%02d:%02d", pos / 3600, (pos % 3600) / 60, pos % 60));
988 posAtNotificationStart = 0;
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 = "";
999 metadata = UpnpXMLParser.compileMetadataString(entry);
1001 setCurrentURI(uri, metadata);
1006 void updateFavoritesList() {
1007 favoriteCommandOptionList = UpnpControlUtil.favorites(bindingConfig.path).stream()
1008 .map(p -> (new CommandOption(p, p))).collect(Collectors.toList());
1009 updateCommandDescription(favoriteSelectChannelUID, favoriteCommandOptionList);
1013 public void playlistsListChanged() {
1014 playlistCommandOptionList = UpnpControlUtil.playlists().stream().map(p -> (new CommandOption(p, p)))
1015 .collect(Collectors.toList());
1016 updateCommandDescription(playlistSelectChannelUID, playlistCommandOptionList);
1020 public void onStatusChanged(boolean status) {
1022 removeSubscriptions();
1024 updateState(CONTROL, PlayPauseType.PAUSE);
1025 cancelTrackPositionRefresh();
1027 super.onStatusChanged(status);
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) {
1037 case "CurrentVolume":
1038 return (inputs.containsKey("Channel") ? inputs.get("Channel") : UPNP_MASTER) + "Volume";
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";
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);
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);
1063 if (variable == null) {
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);
1076 onValueReceivedLastChange(value, service);
1078 case "CurrentTransportState":
1079 case "TransportState":
1080 onValueReceivedTransportState(value);
1082 case "CurrentTrackURI":
1084 onValueReceivedCurrentURI(value);
1086 case "CurrentTrackMetaData":
1087 case "CurrentURIMetaData":
1088 onValueReceivedCurrentMetaData(value);
1090 case "NextAVTransportURIMetaData":
1091 case "NextURIMetaData":
1092 onValueReceivedNextMetaData(value);
1094 case "CurrentTrackDuration":
1095 case "TrackDuration":
1096 onValueReceivedDuration(value);
1099 onValueReceivedRelTime(value);
1102 super.onValueReceived(variable, value, service);
1108 private void onValueReceivedVolume(String variable, @Nullable String value) {
1109 if (value != null && !value.isEmpty()) {
1110 UpnpRenderingControlConfiguration config = renderingControlConfiguration;
1112 long volume = Long.valueOf(value);
1113 volume = volume * 100 / config.maxvolume;
1115 String upnpChannel = variable.replace("Volume", "volume").replace("Master", "");
1116 updateState(upnpChannel, new PercentType((int) volume));
1118 if (!playingNotification && "volume".equals(upnpChannel)) {
1119 soundVolume = new PercentType((int) volume);
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);
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);
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
1155 case "AVTransportURI":
1156 onValueReceived("CurrentTrackURI", entrySet.getValue(), service);
1158 case "AVTransportURIMetaData":
1159 onValueReceived("CurrentTrackMetaData", entrySet.getValue(), service);
1162 onValueReceived(entrySet.getKey(), entrySet.getValue(), service);
1165 if (parsedValues.containsKey("TransportState")) {
1166 onValueReceived("TransportState", parsedValues.get("TransportState"), service);
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);
1178 private void onValueReceivedTransportState(@Nullable String value) {
1179 transportState = (value == null) ? "" : value;
1181 if ("STOPPED".equals(value)) {
1182 CompletableFuture<Boolean> stopping = isStopping;
1183 if (stopping != null) {
1184 stopping.complete(true); // We have received stop confirmation
1188 if (playingNotification) {
1189 resumeAfterNotification();
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)
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.
1213 } else if (playingQueue) {
1214 playingQueue = false;
1217 } else if ("PLAYING".equals(value)) {
1218 if (playingNotification) {
1222 playerStopped = false;
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);
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
1241 UpnpEntry current = currentEntry;
1242 UpnpEntry next = nextEntry;
1245 String currentUri = "";
1246 String nextUri = "";
1247 if (value != null) {
1248 uri = URLDecoder.decode(value.trim(), StandardCharsets.UTF_8);
1250 if (current != null) {
1251 currentUri = URLDecoder.decode(current.getRes().trim(), StandardCharsets.UTF_8);
1254 nextUri = URLDecoder.decode(next.getRes(), StandardCharsets.UTF_8);
1257 if (playingNotification && uri.equals(notificationUri)) {
1258 // No need to update anything more if this is for playing a notification
1262 nowPlayingUri = uri;
1263 updateState(URI, StringType.valueOf(uri));
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);
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,
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());
1282 updateMetaDataState(next);
1284 // look one further to get next entry for next URI
1286 if ((next != null) && !onlyplayone) {
1287 setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
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();
1298 private void onValueReceivedCurrentMetaData(@Nullable String value) {
1299 if (playingNotification) {
1300 // Don't update metadata when playing notification
1304 if (value != null && !value.isEmpty()) {
1305 List<UpnpEntry> list = UpnpXMLParser.getEntriesFromXML(value);
1306 if (!list.isEmpty()) {
1307 updateMetaDataState(list.get(0));
1311 clearMetaDataState();
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);
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)) {
1328 updateState(TRACK_DURATION, UnDefType.UNDEF);
1329 updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
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);
1340 setExpectedTrackend();
1343 private void onValueReceivedRelTime(@Nullable String value) {
1344 if (value == null || "NOT_IMPLEMENTED".equals(value)) {
1346 updateState(TRACK_POSITION, UnDefType.UNDEF);
1347 updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
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);
1361 if (playingNotification) {
1362 posAtNotificationStart = trackPosition;
1365 setExpectedTrackend();
1369 protected void updateProtocolInfo(String value) {
1371 supportedAudioFormats.clear();
1372 audioSupport = false;
1374 sink.addAll(Arrays.asList(value.split(",")));
1376 for (String protocol : sink) {
1377 Matcher matcher = PROTOCOL_PATTERN.matcher(protocol);
1378 if (matcher.find()) {
1379 String format = matcher.group(1);
1384 supportedAudioFormats.add(AudioFormat.MP3);
1388 supportedAudioFormats.add(AudioFormat.WAV);
1391 audioSupport = audioSupport || Pattern.matches("audio.*", format);
1396 logger.debug("Renderer {} supports audio", thing.getLabel());
1397 registerAudioSink();
1401 private void clearCurrentEntry() {
1402 clearMetaDataState();
1405 updateState(TRACK_DURATION, UnDefType.UNDEF);
1407 updateState(TRACK_POSITION, UnDefType.UNDEF);
1408 updateState(REL_TRACK_POSITION, UnDefType.UNDEF);
1410 currentEntry = null;
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
1420 protected void registerQueue(UpnpEntryQueue queue) {
1421 if (currentQueue.equals(queue)) {
1422 // We get the same queue, so do nothing
1426 logger.debug("Registering queue on renderer {}", thing.getLabel());
1428 registeredQueue = true;
1429 currentQueue = queue;
1430 currentQueue.setRepeat(repeat);
1431 currentQueue.setShuffle(shuffle);
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));
1441 resetToStartQueue();
1446 * Move to next position in queue and start playing.
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());
1457 logger.debug("Cannot serve next, end of queue on renderer {}", thing.getLabel());
1458 resetToStartQueue();
1463 * Move to previous position in queue and start playing.
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());
1474 logger.debug("Cannot serve previous, already at start of queue on renderer {}", thing.getLabel());
1475 resetToStartQueue();
1479 private void resetToStartQueue() {
1480 logger.trace("Reset to start queue on renderer {}", thing.getLabel());
1482 playingQueue = false;
1483 registeredQueue = true;
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));
1497 clearCurrentEntry();
1500 UpnpEntry next = nextEntry;
1503 } else if (next != null) {
1504 setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
1509 * Serve media from a queue and play immediately when already playing.
1513 private void serve() {
1514 logger.trace("Serve media on renderer {}", thing.getLabel());
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;
1525 updateMetaDataState(entry);
1526 setCurrentURI(res, UpnpXMLParser.compileMetadataString(entry));
1528 if ((playingQueue || playing) && !(onlyplayone && oneplayed)) {
1529 logger.trace("Ready to play '{}' from queue", currentEntry);
1533 expectedTrackend = 0;
1537 playingQueue = true;
1540 // make the next entry available to renderers that support it
1542 UpnpEntry next = nextEntry;
1544 setNextURI(next.getRes(), UpnpXMLParser.compileMetadataString(next));
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.
1554 private void checkPaused() {
1555 paused = upnpScheduler.schedule(this::resetPaused, config.responseTimeout, TimeUnit.MILLISECONDS);
1558 private void resetPaused() {
1559 updateState(CONTROL, PlayPauseType.PLAY);
1562 private void cancelCheckPaused() {
1563 ScheduledFuture<?> future = paused;
1564 if (future != null) {
1565 future.cancel(true);
1570 private void setExpectedTrackend() {
1571 expectedTrackend = Instant.now().toEpochMilli() + (trackDuration - trackPosition) * 1000
1572 - config.responseTimeout;
1576 * Update the current track position every second if the channel is linked.
1578 private void scheduleTrackPositionRefresh() {
1579 if (playingNotification) {
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
1588 if (trackPositionRefresh == null) {
1589 trackPositionRefresh = upnpScheduler.scheduleWithFixedDelay(this::getPositionInfo, 1, 1,
1595 private void cancelTrackPositionRefresh() {
1596 ScheduledFuture<?> refresh = trackPositionRefresh;
1598 if (refresh != null) {
1599 refresh.cancel(true);
1601 trackPositionRefresh = null;
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));
1610 * Update metadata channels for media with data received from the Media Server or AV Transport.
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
1617 boolean isCurrent = false;
1618 UpnpEntry entry = null;
1620 entry = currentEntry;
1623 logger.trace("Renderer {}, received media ID: {}", thing.getLabel(), media.getId());
1625 if ((entry != null) && entry.getId().equals(media.getId())) {
1626 logger.trace("Current ID: {}", entry.getId());
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() : "";
1634 String mediaUrl = URLDecoder.decode(mediaRes, StandardCharsets.UTF_8);
1635 String entryUrl = URLDecoder.decode(entryRes, StandardCharsets.UTF_8);
1636 isCurrent = mediaUrl.equals(entryUrl);
1638 logger.trace("Current queue res: {}", entryRes);
1639 logger.trace("Updated media res: {}", mediaRes);
1642 logger.trace("Received meta data is for current entry: {}", isCurrent);
1644 if (!(isCurrent && media.getTitle().isEmpty())) {
1645 updateState(TITLE, StringType.valueOf(media.getTitle()));
1647 if (!(isCurrent && (media.getAlbum().isEmpty() || media.getAlbum().matches("Unknown.*")))) {
1648 updateState(ALBUM, StringType.valueOf(media.getAlbum()));
1651 && (media.getAlbumArtUri().isEmpty() || media.getAlbumArtUri().contains("DefaultAlbumCover")))) {
1652 if (media.getAlbumArtUri().isEmpty() || media.getAlbumArtUri().contains("DefaultAlbumCover")) {
1653 updateState(ALBUM_ART, UnDefType.UNDEF);
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());
1659 updateState(ALBUM_ART, UnDefType.UNDEF);
1662 updateState(ALBUM_ART, albumArt);
1666 if (!(isCurrent && (media.getCreator().isEmpty() || media.getCreator().matches("Unknown.*")))) {
1667 updateState(CREATOR, StringType.valueOf(media.getCreator()));
1669 if (!(isCurrent && (media.getArtist().isEmpty() || media.getArtist().matches("Unknown.*")))) {
1670 updateState(ARTIST, StringType.valueOf(media.getArtist()));
1672 if (!(isCurrent && (media.getPublisher().isEmpty() || media.getPublisher().matches("Unknown.*")))) {
1673 updateState(PUBLISHER, StringType.valueOf(media.getPublisher()));
1675 if (!(isCurrent && (media.getGenre().isEmpty() || media.getGenre().matches("Unknown.*")))) {
1676 updateState(GENRE, StringType.valueOf(media.getGenre()));
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);
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);
1697 * @return Audio formats supported by the renderer.
1699 public Set<AudioFormat> getSupportedAudioFormats() {
1700 return supportedAudioFormats;
1703 private void registerAudioSink() {
1704 if (audioSinkRegistered) {
1705 logger.debug("Audio Sink already registered for renderer {}", thing.getLabel());
1707 } else if (!upnpIOService.isRegistered(this)) {
1708 logger.debug("Audio Sink registration for renderer {} failed, no service", thing.getLabel());
1711 logger.debug("Registering Audio Sink for renderer {}", thing.getLabel());
1712 audioSinkReg.registerAudioSink(this);
1713 audioSinkRegistered = true;
1717 * @return UPnP sink definitions supported by the renderer.
1719 protected List<String> getSink() {