2 * Copyright (c) 2010-2022 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.pulseaudio.internal;
15 import java.io.IOException;
16 import java.io.InputStream;
17 import java.io.InterruptedIOException;
18 import java.io.PipedInputStream;
19 import java.io.PipedOutputStream;
20 import java.net.Socket;
21 import java.util.HashSet;
23 import java.util.concurrent.ConcurrentLinkedQueue;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.function.Consumer;
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.pulseaudio.internal.handler.PulseaudioHandler;
31 import org.openhab.core.audio.AudioException;
32 import org.openhab.core.audio.AudioFormat;
33 import org.openhab.core.audio.AudioSource;
34 import org.openhab.core.audio.AudioStream;
35 import org.openhab.core.common.ThreadPoolManager;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
40 * The audio source for openhab, implemented by a connection to a pulseaudio source using Simple TCP protocol
42 * @author Miguel Álvarez - Initial contribution
46 public class PulseAudioAudioSource extends PulseaudioSimpleProtocolStream implements AudioSource {
48 private final Logger logger = LoggerFactory.getLogger(PulseAudioAudioSource.class);
49 private final ConcurrentLinkedQueue<PipedOutputStream> pipeOutputs = new ConcurrentLinkedQueue<>();
50 private final ScheduledExecutorService executor;
52 private @Nullable Future<?> pipeWriteTask;
54 public PulseAudioAudioSource(PulseaudioHandler pulseaudioHandler, ScheduledExecutorService scheduler) {
55 super(pulseaudioHandler, scheduler);
56 executor = ThreadPoolManager
57 .getScheduledPool("OH-binding-" + pulseaudioHandler.getThing().getUID() + "-source");
61 public Set<AudioFormat> getSupportedFormats() {
62 var supportedFormats = new HashSet<AudioFormat>();
63 var audioFormat = pulseaudioHandler.getSourceAudioFormat();
64 if (audioFormat != null) {
65 supportedFormats.add(audioFormat);
67 return supportedFormats;
71 public AudioStream getInputStream(AudioFormat audioFormat) throws AudioException {
73 for (int countAttempt = 1; countAttempt <= 2; countAttempt++) { // two attempts allowed
76 final Socket clientSocketLocal = clientSocket;
77 if (clientSocketLocal == null) {
80 var sourceFormat = pulseaudioHandler.getSourceAudioFormat();
81 if (sourceFormat == null) {
82 throw new AudioException("Unable to get source audio format");
84 if (!audioFormat.isCompatible(sourceFormat)) {
85 throw new AudioException("Incompatible audio format requested");
88 var pipeOutput = new PipedOutputStream();
89 var pipeInput = new PipedInputStream(pipeOutput, 1024 * 10) {
91 public void close() throws IOException {
92 unregisterPipe(pipeOutput);
96 registerPipe(pipeOutput);
97 // get raw audio from the pulse audio socket
98 return new PulseAudioStream(sourceFormat, pipeInput, (idle) -> {
101 scheduleDisconnect();
103 // ensure pipe is writing
107 } catch (IOException e) {
108 disconnect(); // disconnect to force clear connection in case of socket not cleanly shutdown
109 if (countAttempt == 2) { // we won't retry : log and quit
110 final Socket clientSocketLocal = clientSocket;
111 String port = clientSocketLocal != null ? Integer.toString(clientSocketLocal.getPort())
114 "Error while trying to get audio from pulseaudio audio source. Cannot connect to {}:{}, error: {}",
115 pulseaudioHandler.getHost(), port, e.getMessage());
119 } catch (InterruptedException ie) {
120 logger.info("Interrupted during source audio connection: {}", ie.getMessage());
122 throw new AudioException(ie);
126 } catch (IOException e) {
127 throw new AudioException(e);
129 scheduleDisconnect();
132 throw new AudioException("Unable to create input stream");
135 private synchronized void registerPipe(PipedOutputStream pipeOutput) {
136 this.pipeOutputs.add(pipeOutput);
140 private synchronized void startPipeWrite() {
141 if (this.pipeWriteTask == null) {
142 this.pipeWriteTask = executor.submit(() -> {
144 byte[] buffer = new byte[1024];
146 while (!pipeOutputs.isEmpty()) {
147 var stream = getSourceInputStream();
148 if (stream != null) {
150 lengthRead = stream.read(buffer);
152 for (var output : pipeOutputs) {
154 output.write(buffer, 0, lengthRead);
155 if (pipeOutputs.contains(output)) {
158 } catch (InterruptedIOException e) {
159 if (pipeOutputs.isEmpty()) {
160 // task has been ended while writing
163 logger.warn("InterruptedIOException while writing to from pulse source pipe: {}",
164 getExceptionMessage(e));
165 } catch (IOException e) {
166 logger.warn("IOException while writing to from pulse source pipe: {}",
167 getExceptionMessage(e));
168 } catch (RuntimeException e) {
169 logger.warn("RuntimeException while writing to pulse source pipe: {}",
170 getExceptionMessage(e));
173 } catch (IOException e) {
174 logger.warn("IOException while reading from pulse source: {}", getExceptionMessage(e));
175 if (readRetries == 0) {
176 // force reconnection on persistent IOException
181 } catch (RuntimeException e) {
182 logger.warn("RuntimeException while reading from pulse source: {}", getExceptionMessage(e));
185 logger.warn("Unable to get source input stream");
188 this.pipeWriteTask = null;
193 private synchronized void unregisterPipe(PipedOutputStream pipeOutput) {
194 this.pipeOutputs.remove(pipeOutput);
197 } catch (InterruptedException ignored) {
202 } catch (IOException ignored) {
206 private synchronized void stopPipeWriteTask() {
207 var pipeWriteTask = this.pipeWriteTask;
208 if (pipeOutputs.isEmpty() && pipeWriteTask != null) {
209 pipeWriteTask.cancel(true);
210 this.pipeWriteTask = null;
214 private @Nullable String getExceptionMessage(Exception e) {
215 String message = e.getMessage();
216 var cause = e.getCause();
217 if (message == null && cause != null) {
218 message = cause.getMessage();
223 private @Nullable InputStream getSourceInputStream() {
226 } catch (IOException | InterruptedException ignored) {
229 var clientSocketFinal = clientSocket;
230 return (clientSocketFinal != null) ? clientSocketFinal.getInputStream() : null;
231 } catch (IOException ignored) {
237 public void disconnect() {
242 static class PulseAudioStream extends AudioStream {
243 private final Logger logger = LoggerFactory.getLogger(PulseAudioAudioSource.class);
244 private final AudioFormat format;
245 private final InputStream input;
246 private final Consumer<Boolean> setIdle;
247 private boolean closed = false;
249 public PulseAudioStream(AudioFormat format, InputStream input, Consumer<Boolean> setIdle) {
251 this.format = format;
252 this.setIdle = setIdle;
256 public AudioFormat getFormat() {
261 public int read() throws IOException {
262 byte[] b = new byte[1];
263 int bytesRead = read(b);
264 if (-1 == bytesRead) {
267 Byte bb = Byte.valueOf(b[0]);
268 return bb.intValue();
272 public int read(byte @Nullable [] b) throws IOException {
273 return read(b, 0, b == null ? 0 : b.length);
277 public int read(byte @Nullable [] b, int off, int len) throws IOException {
279 throw new IOException("Buffer is null");
281 logger.trace("reading from pulseaudio stream");
283 throw new IOException("Stream is closed");
285 setIdle.accept(false);
286 return input.read(b, off, len);
290 public void close() throws IOException {
292 setIdle.accept(true);