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.voice.mimic.internal;
16 import java.io.IOException;
17 import java.io.InputStream;
18 import java.util.ArrayList;
19 import java.util.List;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.openhab.core.audio.AudioException;
23 import org.openhab.core.audio.AudioFormat;
24 import org.openhab.core.audio.FileAudioStream;
27 * A FileAudioStream that autodelete after it and its clone are closed
28 * Useful to not congest temporary directory
30 * @author Gwendal Roulleau - Initial contribution
33 public class AutoDeleteFileAudioStream extends FileAudioStream {
35 private final File file;
36 private final AudioFormat audioFormat;
37 private final List<ClonedFileInputStream> clonedAudioStreams = new ArrayList<>(1);
38 private boolean isOpen = true;
40 public AutoDeleteFileAudioStream(File file, AudioFormat format) throws AudioException {
43 this.audioFormat = format;
47 public void close() throws IOException {
53 protected void deleteIfPossible() {
54 boolean aClonedStreamIsOpen = clonedAudioStreams.stream().anyMatch(as -> as.isOpen);
55 if (!isOpen && !aClonedStreamIsOpen) {
61 public InputStream getClonedStream() throws AudioException {
62 ClonedFileInputStream clonedInputStream = new ClonedFileInputStream(this, file, audioFormat);
63 clonedAudioStreams.add(clonedInputStream);
64 return clonedInputStream;
67 private static class ClonedFileInputStream extends FileAudioStream {
68 protected boolean isOpen = true;
69 private final AutoDeleteFileAudioStream parent;
71 public ClonedFileInputStream(AutoDeleteFileAudioStream parent, File file, AudioFormat audioFormat)
72 throws AudioException {
73 super(file, audioFormat);
78 public void close() throws IOException {
81 parent.deleteIfPossible();