]> git.basschouten.com Git - openhab-addons.git/blob
bc5c960179e6daf6a2a1bb304c583e122034ce06
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.ipcamera.internal;
14
15 import static org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.*;
16
17 import java.io.BufferedReader;
18 import java.io.IOException;
19 import java.io.InputStream;
20 import java.io.InputStreamReader;
21 import java.util.ArrayList;
22 import java.util.Collections;
23 import java.util.List;
24 import java.util.concurrent.Executors;
25 import java.util.concurrent.ScheduledExecutorService;
26 import java.util.concurrent.TimeUnit;
27
28 import org.eclipse.jdt.annotation.NonNullByDefault;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.openhab.binding.ipcamera.internal.IpCameraBindingConstants.FFmpegFormat;
31 import org.openhab.binding.ipcamera.internal.handler.IpCameraHandler;
32 import org.openhab.core.library.types.DecimalType;
33 import org.openhab.core.library.types.OnOffType;
34 import org.slf4j.Logger;
35 import org.slf4j.LoggerFactory;
36
37 /**
38  * The {@link Ffmpeg} class is responsible for handling multiple ffmpeg conversions which are used for many tasks
39  *
40  *
41  * @author Matthew Skinner - Initial contribution
42  */
43
44 @NonNullByDefault
45 public class Ffmpeg {
46     private final Logger logger = LoggerFactory.getLogger(getClass());
47     private IpCameraHandler ipCameraHandler;
48     private @Nullable Process process = null;
49     private String ffmpegCommand = "";
50     private FFmpegFormat format;
51     private List<String> commandArrayList = new ArrayList<String>();
52     private IpCameraFfmpegThread ipCameraFfmpegThread = new IpCameraFfmpegThread();
53     private int keepAlive = 8;
54     private String password;
55
56     public Ffmpeg(IpCameraHandler handle, FFmpegFormat format, String ffmpegLocation, String inputArguments,
57             String input, String outArguments, String output, String username, String password) {
58         this.format = format;
59         this.password = password;
60         ipCameraHandler = handle;
61         String altInput = input;
62         // Input can be snapshots not just rtsp or http
63         if (!password.isEmpty() && !input.contains("@") && input.contains("rtsp")) {
64             String credentials = username + ":" + password + "@";
65             // will not work for https: but currently binding does not use https
66             altInput = input.substring(0, 7) + credentials + input.substring(7);
67         }
68         if (inputArguments.isEmpty()) {
69             ffmpegCommand = "-i " + altInput + " " + outArguments + " " + output;
70         } else {
71             ffmpegCommand = inputArguments + " -i " + altInput + " " + outArguments + " " + output;
72         }
73         Collections.addAll(commandArrayList, ffmpegCommand.trim().split("\\s+"));
74         // ffmpegLocation may have a space in its folder
75         commandArrayList.add(0, ffmpegLocation);
76     }
77
78     public void setKeepAlive(int numberOfEightSeconds) {
79         // We poll every 8 seconds due to mjpeg stream requirement.
80         if (keepAlive == -1 && numberOfEightSeconds > 1) {
81             return;// When set to -1 this will not auto turn off stream.
82         }
83         keepAlive = numberOfEightSeconds;
84     }
85
86     public void checkKeepAlive() {
87         if (keepAlive == 1) {
88             stopConverting();
89         } else if (keepAlive <= -1 && !getIsAlive()) {
90             logger.warn("HLS stream was not running, restarting it now.");
91             startConverting();
92         }
93         if (keepAlive > 0) {
94             keepAlive--;
95         }
96     }
97
98     private class IpCameraFfmpegThread extends Thread {
99         private ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(2);
100         public int countOfMotions;
101
102         IpCameraFfmpegThread() {
103             setDaemon(true);
104         }
105
106         private void gifCreated() {
107             // Without a small delay, Pushover sends no file 10% of time.
108             ipCameraHandler.setChannelState(CHANNEL_RECORDING_GIF, DecimalType.ZERO);
109             ipCameraHandler.setChannelState(CHANNEL_GIF_HISTORY_LENGTH,
110                     new DecimalType(++ipCameraHandler.gifHistoryLength));
111         }
112
113         private void mp4Created() {
114             ipCameraHandler.setChannelState(CHANNEL_RECORDING_MP4, DecimalType.ZERO);
115             ipCameraHandler.setChannelState(CHANNEL_MP4_HISTORY_LENGTH,
116                     new DecimalType(++ipCameraHandler.mp4HistoryLength));
117         }
118
119         @Override
120         public void run() {
121             try {
122                 process = Runtime.getRuntime().exec(commandArrayList.toArray(new String[commandArrayList.size()]));
123                 Process localProcess = process;
124                 if (localProcess != null) {
125                     InputStream errorStream = localProcess.getErrorStream();
126                     InputStreamReader errorStreamReader = new InputStreamReader(errorStream);
127                     BufferedReader bufferedReader = new BufferedReader(errorStreamReader);
128                     String line = null;
129                     while ((line = bufferedReader.readLine()) != null) {
130                         if (format.equals(FFmpegFormat.RTSP_ALARMS)) {
131                             logger.debug("{}", line);
132                             if (line.contains("lavfi.")) {
133                                 if (countOfMotions == 4) {
134                                     ipCameraHandler.motionDetected(CHANNEL_FFMPEG_MOTION_ALARM);
135                                 } else {
136                                     countOfMotions++;
137                                 }
138                             } else if (line.contains("speed=")) {
139                                 if (countOfMotions > 0) {
140                                     countOfMotions--;
141                                     countOfMotions--;
142                                     if (countOfMotions <= 0) {
143                                         ipCameraHandler.noMotionDetected(CHANNEL_FFMPEG_MOTION_ALARM);
144                                     }
145                                 }
146                             } else if (line.contains("silence_start")) {
147                                 ipCameraHandler.noAudioDetected();
148                             } else if (line.contains("silence_end")) {
149                                 ipCameraHandler.audioDetected();
150                             }
151                         } else {
152                             logger.debug("{}", line);
153                         }
154                     }
155                 }
156             } catch (IOException e) {
157                 logger.warn("An error occured trying to process the messages from FFmpeg.");
158             } finally {
159                 switch (format) {
160                     case GIF:
161                         threadPool.schedule(this::gifCreated, 800, TimeUnit.MILLISECONDS);
162                         break;
163                     case RECORD:
164                         threadPool.schedule(this::mp4Created, 800, TimeUnit.MILLISECONDS);
165                         break;
166                     default:
167                         break;
168                 }
169             }
170         }
171     }
172
173     public void startConverting() {
174         if (!ipCameraFfmpegThread.isAlive()) {
175             ipCameraFfmpegThread = new IpCameraFfmpegThread();
176             logger.debug("Starting ffmpeg with this command now:{}", ffmpegCommand.replaceAll(password, "********"));
177             ipCameraFfmpegThread.start();
178             if (format.equals(FFmpegFormat.HLS)) {
179                 ipCameraHandler.setChannelState(CHANNEL_START_STREAM, OnOffType.ON);
180             }
181         }
182         if (keepAlive != -1) {
183             keepAlive = 8;
184         }
185     }
186
187     public boolean getIsAlive() {
188         Process localProcess = process;
189         if (localProcess != null) {
190             return localProcess.isAlive();
191         }
192         return false;
193     }
194
195     public void stopConverting() {
196         if (ipCameraFfmpegThread.isAlive()) {
197             logger.debug("Stopping ffmpeg {} now when keepalive is:{}", format, keepAlive);
198             Process localProcess = process;
199             if (localProcess != null) {
200                 localProcess.destroyForcibly();
201             }
202             if (format.equals(FFmpegFormat.HLS)) {
203                 ipCameraHandler.setChannelState(CHANNEL_START_STREAM, OnOffType.OFF);
204             }
205         }
206     }
207 }