-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstream_control.py
More file actions
1162 lines (961 loc) · 38.6 KB
/
Copy pathstream_control.py
File metadata and controls
1162 lines (961 loc) · 38.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import time
import json
import re
import subprocess
import os
import logging
import glob
import psutil
from dotenv import load_dotenv
from flask import Flask, request, render_template, jsonify, send_file, abort
from flask_basicauth import BasicAuth
from threading import Thread, Event, Timer
from datetime import datetime
# Flask application
app = Flask(__name__)
# Determine the current working directory
current_directory = os.path.dirname(os.path.abspath(__file__))
log_file_path = os.path.join(current_directory, 'stream_control.log')
sys_info_file_path = os.path.join(current_directory, 'system_info.txt')
# Configure logging
logging.basicConfig(
filename=log_file_path,
level=logging.DEBUG,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# Disable werkzeug logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
# Truncate the stream_control.log file
with open('stream_control.log', 'w'):
pass
# Load environment variables from .env file
load_dotenv()
# Load environment variables from .auth file
load_dotenv('.auth')
# Configure BasicAuth using environment variables
app.config['BASIC_AUTH_USERNAME'] = os.getenv('BASIC_AUTH_USERNAME')
app.config['BASIC_AUTH_PASSWORD'] = os.getenv('BASIC_AUTH_PASSWORD')
# Disable automatic force to allow exclusion of PWA resources
app.config['BASIC_AUTH_FORCE'] = False
# Basic auth enabled
basic_auth = BasicAuth(app)
@app.before_request
def force_basic_auth():
"""Enforce basic auth globally except for PWA manifest, service worker, and icons."""
if os.getenv('BASIC_AUTH_FORCE') == 'True':
# List of paths that should be public
if request.path.endswith('manifest.json') or \
request.path.endswith('sw.js') or \
'/static/assets/icons/' in request.path:
return
if not basic_auth.authenticate():
return basic_auth.challenge()
stop_event = Event()
# RTMP stream settings
STREAM_KEY = os.getenv('STREAM_KEY')
RTMP_SERVER = os.getenv('RTMP_SERVER')
# ALSA audio source
ALSA_AUDIO_SOURCE = os.getenv('ALSA_AUDIO_SOURCE')
# Stream Settings
VIDEO_SIZE = os.getenv('VIDEO_SIZE')
FRAME_RATE = int(os.getenv('FRAME_RATE'))
BITRATE = int(os.getenv('BITRATE'))
KEYFRAME_INTERVAL = int(os.getenv('KEYFRAME_INTERVAL'))
AUDIO_OFFSET = os.getenv('AUDIO_OFFSET')
STREAM_M3U8_URL = os.getenv('STREAM_M3U8_URL')
STREAM_FILE = os.getenv('STREAM_FILE') # Add STREAM_FILE variable
FORMAT = os.getenv('FORMAT')
PRESET = os.getenv('PRESET')
REPORT = os.getenv('REPORT')
MAX_TIME = os.getenv('MAX_TIME')
# Calculate buffer size and keyframe interval
BUFFER_SIZE = BITRATE * 2 # in kbps
def get_device_value():
device_file = "audio_device.txt"
if os.path.isfile(device_file):
with open(device_file, "r") as file:
return file.read().strip()
else:
logging.debug("audio_device.txt file not found")
exit(1)
def get_audio_device(device_value):
arecord_output = subprocess.run(['arecord', '-l'], capture_output=True, text=True).stdout
for line in arecord_output.splitlines():
if device_value in line:
card_match = re.search(r'card\s+(\d+):', line)
device_match = re.search(r'device\s+(\d+):', line)
if card_match and device_match:
card = card_match.group(1)
device = device_match.group(1)
if device_value.startswith("hw:") or device_value.startswith("plughw:"):
return f"{device_value}{card},{device}"
else:
return f"hw:{card},{device}"
else:
logging.debug("Failed to parse card or device number from the line:")
logging.debug(line)
return None
def update_env_file(audio_device):
env_file = ".env"
if os.path.isfile(env_file):
with open(env_file, "r") as file:
lines = file.readlines()
with open(env_file, "w") as file:
updated = False
for line in lines:
if line.startswith("ALSA_AUDIO_SOURCE="):
file.write(f"ALSA_AUDIO_SOURCE={audio_device}\n")
updated = True
else:
file.write(line)
if not updated:
file.write(f"ALSA_AUDIO_SOURCE={audio_device}\n")
else:
with open(env_file, "w") as file:
file.write(f"ALSA_AUDIO_SOURCE={audio_device}\n")
# Update audio device
device_value = get_device_value()
audio_device = get_audio_device(device_value)
if device_value and audio_device:
update_env_file(audio_device)
logging.debug(f"Updated .env file with ALSA_AUDIO_SOURCE={audio_device}")
ALSA_AUDIO_SOURCE = audio_device
else:
logging.debug("No suitable audio device found")
# Define the output file
SYS_INFO_FILE = "system_info.txt"
# Truncate the output file (or create it if it doesn't exist)
with open(SYS_INFO_FILE, "w") as file:
pass
def append_command_output(command, description):
with open(SYS_INFO_FILE, "a") as file:
file.write(f"Output of {description}:\n")
result = subprocess.run(command, capture_output=True, text=True)
file.write(result.stdout)
file.write("\n\n")
# Run lsusb and append the output to the file
append_command_output(["lsusb"], "lsusb")
# Run arecord -l and append the output to the file
append_command_output(["arecord", "-l"], "arecord -l")
# Run v4l2-ctl --list-formats-ext and append the output to the file
append_command_output(["v4l2-ctl", "--list-formats-ext"], "v4l2-ctl --list-formats-ext")
logging.debug(f"System information saved to {SYS_INFO_FILE}")
def parse_v4l2_data_from_file(file_path):
formats = []
resolutions = []
with open(file_path, "r") as file:
content = file.read()
# Find the v4l2-ctl section
v4l2_start = content.find("Output of v4l2-ctl --list-formats-ext:")
if v4l2_start == -1:
return formats, resolutions
v4l2_content = content[v4l2_start:]
# Extract formats using regex
format_pattern = r"\[\d+\]:\s+'([^']+)'"
matches = re.findall(format_pattern, v4l2_content)
for i, match in enumerate(matches):
match_name = match.lower()
if match_name == "yuyv":
match_name = "yuyv422"
if match_name == "mjpg":
match_name = "mjpeg"
formats.append(match_name)
# Extract resolutions using regex
resolution_pattern = r"Size:\s+Discrete\s+([0-9x]+)"
matches = re.findall(resolution_pattern, v4l2_content)
resolutions = [match.lower() for match in matches]
# Remove duplicates from resolutions and sort
resolutions = sorted(set(resolutions))
return formats, resolutions
# Remove old ffmpeg logs
def remove_ffmpeg_logs(directory):
# Create a pattern to match the ffmpeg log files
pattern = os.path.join(directory, 'ffmpeg-*.log')
# Get all matching files
log_files = glob.glob(pattern)
# Remove each file
for log_file in log_files:
try:
os.remove(log_file)
logging.debug(f"Removed log file: {log_file}")
except Exception as e:
logging.debug(f"Error removing file {log_file}: {e}")
def get_latest_ffmpeg_log(directory):
# Create a pattern to match the ffmpeg log files
pattern = os.path.join(directory, 'ffmpeg-*.log')
# Get all matching files
log_files = glob.glob(pattern)
if not log_files:
return None
# Find the latest file based on modification time
latest_file = max(log_files, key=os.path.getmtime)
return latest_file
# Remove old ffmpeg log files
remove_ffmpeg_logs(current_directory)
def get_last_n_lines(file_path, n):
with open(file_path, 'r') as file:
lines = file.readlines()
return lines[-n:]
def get_cpu_usage():
# Get the CPU usage percentage
cpu_usage = psutil.cpu_percent(interval=1)
return cpu_usage
def get_memory_usage():
# Get the memory usage details
memory_info = psutil.virtual_memory()
return memory_info.percent, memory_info.available, memory_info.total
def display_usage():
cpu_usage = get_cpu_usage()
memory_usage_percent, memory_available, memory_total = get_memory_usage()
usage_data = {
"cpu_usage": cpu_usage,
"memory_usage_percent": memory_usage_percent,
"memory_available_mb": memory_available / (1024 * 1024),
"memory_total_mb": memory_total / (1024 * 1024)
}
usage_json = json.dumps(usage_data, indent=4)
return usage_json
def disk_usage():
try:
# Run df -h and capture the output
result = subprocess.run(['df', '-h'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if result.returncode != 0:
raise Exception("Error getting disk usage: " + result.stderr.decode())
output = result.stdout.decode()
# Parse the output (assuming you want the second partition)
lines = output.split('\n')
usb_device = range(8, len(lines))
sd_card = range(1, len(lines))
for i in usb_device:
parts = lines[i].split()
if len(parts) > 5:
filesystem = parts[0]
size = parts[1]
used = parts[2]
available = parts[3]
use_percentage = parts[4]
mounted_on = parts[5]
# Check if the filesystem matches /dev/sda1
if filesystem == '/dev/sda1':
return {
"filesystem": filesystem,
"size": size,
"used": used,
"available": available,
"use_percentage": use_percentage + "%",
"mounted_on": mounted_on
}
for i in sd_card:
parts = lines[i].split()
if len(parts) > 5:
filesystem = parts[0]
size = parts[1]
used = parts[2]
available = parts[3]
use_percentage = parts[4]
mounted_on = parts[5]
# Check if the filesystem matches /dev/mmcblk0p2
if filesystem == '/dev/mmcblk0p2':
return {
"filesystem": filesystem,
"size": size,
"used": used,
"available": available,
"use_percentage": use_percentage + "%",
"mounted_on": mounted_on
}
return {
"error": "No matching filesystem found"
}
except Exception as e:
return {'error': str(e)}
except Exception as e:
return jsonify({'error': str(e)}), 500
def remux(input_file, output_file):
try:
remux_command = [
"ffmpeg",
"-y", # Overwrite output file without prompt
"-i", input_file, # Input file
"-c", "copy", # Copy both audio and video streams
"-f", "mp4", # Output format
"-nostats", # Disable statistics display
"-threads", "4", # Use 4 threads for encoding
output_file # Output file
]
subprocess.run(remux_command, check=True)
logging.debug(f"Remuxed file {input_file} to {output_file}")
except subprocess.CalledProcessError as e:
logging.error(f"Remuxing failed for {input_file}: {e}")
def remux_and_finalize(recording_file):
"""Remuxes the recording file and updates the state when done."""
try:
logging.debug(f"Remuxing {recording_file} in background...")
remux_file = recording_file.replace('.mp4', '_remuxed.mp4')
remux(recording_file, remux_file)
os.remove(recording_file)
os.rename(remux_file, recording_file)
logging.debug(f"Successfully remuxed and replaced: {recording_file}")
except Exception as e:
logging.error(f"Error during remux and finalize: {e}")
finally:
# Update state to indicate remuxing is complete
state = load_state()
state["remux"] = False
save_state(state)
logging.debug("Remuxing finished, state updated.")
# Initialize variables
streaming = False
recording = False
file_streaming = False
stream_recording = False
# Initialize global variables
stream_record_process = None
stream_recording = False
stream_process = None
streaming = False
file_stream_process = None
file_streaming = False
state_file = 'state.json'
default_state = {"streaming": False, "recording": False, "file_streaming": False, "streaming_and_recording": False, "remux": False, "start_time": None}
# Sets the default state on startup
def load_default_state():
with open("state.json", "w") as file:
json.dump(default_state, file, indent=4)
# Sets default state
load_default_state()
# Save current state to json file
def load_state():
if os.path.exists(state_file):
with open(state_file, 'r') as f:
return json.load(f)
return default_state
def save_state(state):
with open(state_file, 'w') as f:
json.dump(state, f)
state = load_state()
def ensure_recordings_directory():
if not os.path.exists("recordings"):
os.makedirs("recordings")
def reinitialize_device():
try:
logging.debug("Reloading uvcvideo module...")
subprocess.run(["sudo", "modprobe", "-r", "uvcvideo"], check=True)
subprocess.run(["sudo", "modprobe", "uvcvideo"], check=True)
logging.debug("uvcvideo module reloaded.")
except subprocess.CalledProcessError as e:
logging.error(f"Failed to reload uvcvideo module: {e}")
def convert_size(size_bytes):
if size_bytes == 0:
return '0 B'
size_name = ('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB')
i = 0
while size_bytes >= 1024 and i < len(size_name) - 1:
size_bytes /= 1024
i += 1
return f'{size_bytes:.2f} {size_name[i]}'
def list_recordings():
ensure_recordings_directory()
recordings_dir = "recordings"
try:
# Get all files in the directory
files = []
for filename in os.listdir(recordings_dir):
if not filename == ".gitkeep":
file_path = os.path.join(recordings_dir, filename)
# Get file details
file_stats = os.stat(file_path)
modification_date = file_stats.st_mtime # Modification time as timestamp
size = file_stats.st_size # Size in bytes
# Convert modification date to readable format
modification_date_str = datetime.utcfromtimestamp(modification_date).strftime("%Y-%m-%d %H:%M:%S")
# Convert size to human-readable format
size_str = convert_size(size)
files.append({
'filename': filename,
'size': size_str,
'modified': modification_date_str,
'timestamp': modification_date
})
files.sort(key=lambda x: x['timestamp'], reverse=True)
return files
except Exception as e:
logging.debug(f"Error accessing directory: {e}")
def delete_file(directory, filename):
try:
file_path = os.path.join(directory, filename)
os.remove(file_path)
return jsonify({"message": f"File '{filename}' deleted successfully from '{directory}'."})
except FileNotFoundError:
return jsonify({"error": f"File '{filename}' not found in '{directory}'."}), 404
except PermissionError:
return jsonify({"error": f"Permission denied to delete file '{filename}' in '{directory}'."}), 403
except Exception as e:
return jsonify({"error": f"Error deleting file: {e}"}), 500
# Global timer variable
stop_timer = None
def stop_all_actions():
logging.info("Max time reached. Stopping all actions.")
stop_stream()
stop_recording()
stop_file_stream()
stop_stream_recording()
def start_max_timer():
global stop_timer
if stop_timer:
stop_timer.cancel()
if MAX_TIME:
try:
parts = list(map(int, MAX_TIME.split(':')))
if len(parts) == 2:
h, m = parts
s = 0
elif len(parts) == 3:
h, m, s = parts
else:
raise ValueError
seconds = h * 3600 + m * 60 + s
if seconds > 0:
logging.info(f"Starting max time timer for {seconds} seconds.")
stop_timer = Timer(seconds, stop_all_actions)
stop_timer.start()
except ValueError:
logging.error(f"Invalid MAX_TIME format: {MAX_TIME}. Expected HH:MM:SS or HH:MM")
def start_stream():
global stream_process, streaming
state = load_state()
if state["streaming"]:
return
logging.debug("Starting stream...")
start_max_timer()
# Reinitialize the video device before starting the recording
reinitialize_device()
stream_command = [
"ffmpeg",
"-itsoffset", str(AUDIO_OFFSET), # Adjust the offset value for audio sync
"-thread_queue_size", "1024",
"-f", "alsa", "-ac", "2", "-i", str(ALSA_AUDIO_SOURCE), # Input from ALSA
"-f", "v4l2", "-framerate", str(FRAME_RATE), "-video_size", str(VIDEO_SIZE), "-input_format", str(FORMAT), "-i", "/dev/video0", # Video input settings
"-probesize", "32", "-analyzeduration", "0", # Lower probing size and analysis duration for reduced latency
"-c:v", "libx264", "-preset", str(PRESET), "-tune", "zerolatency", "-b:v", f"{BITRATE}k", "-maxrate", f"{BITRATE}k", "-bufsize", f"{BUFFER_SIZE}k", # Video encoding settings
"-vf", "format=yuv420p", "-g", str(KEYFRAME_INTERVAL), # Keyframe interval
"-color_range", "tv",
"-profile:v", "high",
"-c:a", "aac", "-b:a", "96k", "-ar", "44100", # Audio encoding settings
"-use_wallclock_as_timestamps", "1", # Use wallclock timestamps
"-flush_packets", "1", # Flush packets
"-async", "1", # Sync audio with video
"-f", "flv", f"{RTMP_SERVER}{STREAM_KEY}" # Output to RTMP server
]
if REPORT:
stream_command.insert(1, "-report") # Insert the -report flag at index 1 in the command list if REPORT is true in the .env file
stream_process = subprocess.Popen(stream_command)
logging.debug("Stream started!")
streaming = True
state["streaming_and_recording"] = False
state["recording"] = False
state["streaming"] = True
state["start_time"] = time.time()
save_state(state)
def stop_stream():
global stream_process, streaming
state = load_state()
if not state["streaming"] and not state["streaming_and_recording"]:
logging.debug("No active stream to stop.")
return
if stream_process:
logging.debug("Stopping stream...")
stream_process.terminate()
stream_process.wait()
stream_process = None
logging.debug("Stream stopped!")
streaming = False
state["streaming"] = False
state["start_time"] = None
save_state(state)
def start_recording():
global record_process, recording
state = load_state()
if state["recording"]:
return
ensure_recordings_directory()
logging.debug("Starting recording...")
start_max_timer()
# Reinitialize the video device before starting the recording
reinitialize_device()
record_command = [
"ffmpeg",
"-itsoffset", str(AUDIO_OFFSET), # Adjust the offset value for audio sync
"-thread_queue_size", "1024",
"-f", "alsa", "-ac", "2", "-i", str(ALSA_AUDIO_SOURCE), # Input from ALSA
"-f", "v4l2", "-framerate", str(FRAME_RATE), "-video_size", str(VIDEO_SIZE), "-input_format", str(FORMAT), "-i", "/dev/video0", # Video input settings
"-c:v", "libx264", "-preset", str(PRESET), "-tune", "zerolatency", "-b:v", f"{BITRATE}k", "-maxrate", f"{BITRATE}k", "-bufsize", f"{BUFFER_SIZE}k", # Video encoding settings
"-vf", "format=yuv420p", "-g", str(KEYFRAME_INTERVAL), # Keyframe interval
"-color_range", "tv",
"-c:a", "aac", "-b:a", "96k", "-ar", "44100", # Audio encoding settings
"-use_wallclock_as_timestamps", "1", # Use wallclock timestamps
"-flush_packets", "1", # Flush packets
"-async", "1", # Sync audio with video
"-f", "mp4", f"recordings/recording_{int(time.time())}.mp4" # Output to MP4 file
]
if REPORT:
record_command.insert(1, "-report") # Insert the -report flag at index 1 in the command list if REPORT is true in the .env file
record_process = subprocess.Popen(record_command)
logging.debug("Recording started!")
recording = True
state["streaming"] = False
state["streaming_and_recording"] = False
state["recording"] = True
state["start_time"] = time.time()
save_state(state)
def stop_recording():
global record_process, recording, remux
state = load_state()
if not state["recording"]:
return
if record_process:
logging.debug("Stopping recording...")
record_process.terminate()
record_process.wait()
record_process = None
try:
# Get the latest recording file
recording_file = sorted(glob.glob('recordings/recording_*.mp4'))[-1]
# Update state to show remuxing is in progress
state["remux"] = True
state["recording"] = False # The recording process is stopped
state["start_time"] = None
save_state(state)
# Start remuxing in a background thread
Thread(target=remux_and_finalize, args=(recording_file,)).start()
except IndexError:
logging.error("Could not find a recording file to remux. Finalizing state.")
state["recording"] = False
state["remux"] = False
state["start_time"] = None
save_state(state)
recording = False
logging.debug("Recording process stopped, remuxing in background.")
def delayed_start_recording():
for _ in range(30):
if stop_event.is_set():
logging.debug("Delayed start recording process was stopped before it started.")
return
time.sleep(1)
if not stop_event.is_set():
stream_record_command = [
"ffmpeg",
"-y", # Automatically overwrite output file if it exists
"-re",
"-i", str(STREAM_M3U8_URL),
"-c:v", "copy",
"-c:a", "copy",
"-f", "mp4",
f"recordings/stream_{int(time.time())}.mp4"
]
global stream_record_process
stream_record_process = subprocess.Popen(stream_record_command)
logging.debug("Recording stream started!")
def start_stream_recording():
global stream_record_process, stream_recording, stop_event
state = load_state()
if not STREAM_M3U8_URL:
logging.error("STREAM_M3U8_URL is not set or is empty. Cannot start recording.")
return
ensure_recordings_directory()
logging.debug("Starting stream recording...")
start_max_timer()
stream_recording = True
state["recording"] = False
state["streaming"] = False
state["streaming_and_recording"] = True
state["start_time"] = time.time()
save_state(state)
stop_event.clear() # Clear the stop event before starting the thread
Thread(target=delayed_start_recording).start()
def stop_stream_recording():
global stream_record_process, stream_recording, stream_process, stop_event
state = load_state()
if not state["streaming_and_recording"]:
return
if not STREAM_M3U8_URL:
logging.error("STREAM_M3U8_URL is not set or is empty. Cannot stop recording.")
return
stop_event.set() # Signal the delayed start thread to stop
if stream_record_process:
logging.debug("Stopping recording...")
stream_record_process.terminate()
stream_record_process.wait()
stream_record_process = None
try:
# Get the latest recording file
recording_file = sorted(glob.glob('recordings/stream_*.mp4'))[-1]
# Update state to show remuxing is in progress
state["remux"] = True
state["streaming_and_recording"] = False
state["start_time"] = None
save_state(state)
# Start remuxing in a background thread
Thread(target=remux_and_finalize, args=(recording_file,)).start()
except IndexError:
logging.error("Could not find a stream recording file to remux. Finalizing state.")
state["streaming_and_recording"] = False
state["remux"] = False
state["start_time"] = None
save_state(state)
stream_recording = False
logging.debug("Stream and Recording process stopped, remuxing in background.")
def start_file_stream():
global file_stream_process, file_streaming
state = load_state()
if state["file_streaming"]:
return
if not STREAM_FILE:
logging.error("STREAM_FILE is not set or is empty. Cannot start file streaming.")
return
if os.path.isfile(STREAM_FILE) and not STREAM_FILE.endswith('.txt'):
logging.debug(f"Streaming single file: {STREAM_FILE}")
file_stream_command = [
"ffmpeg",
"-re", # Read input at native frame rate
"-stream_loop", "-1", # Loop the input file indefinitely
"-i", str(STREAM_FILE), # Input file
"-c:v", "copy", # Copy the video codec
"-c:a", "aac", # Audio codec
"-strict", "-2", # Allow experimental codecs
"-ac", "2", # Set number of audio channels
"-b:a", "96k", # Audio bitrate
"-ar", "44100", # Audio sampling rate
"-bufsize", "2M", # Set buffer size for the stream
"-f", "flv", # Output format
f"{RTMP_SERVER}{STREAM_KEY}" # RTMP server URL and stream key
]
elif STREAM_FILE.endswith('.txt') and os.path.isfile(STREAM_FILE):
logging.debug(f"Streaming playlist file: {STREAM_FILE}")
file_stream_command = [
"ffmpeg",
"-re", # Read input at native frame rate
"-f", "concat", # Use concat demuxer
"-safe", "0", # Allow unsafe file paths
"-stream_loop", "-1", # Loop the playlist indefinitely
"-i", str(STREAM_FILE), # Input playlist file
"-c:v", "copy", # Copy the video codec
"-c:a", "aac", # Audio codec
"-strict", "-2", # Allow experimental codecs
"-ac", "2", # Set number of audio channels
"-b:a", "96k", # Audio bitrate
"-ar", "44100", # Audio sampling rate
"-bufsize", "2M", # Set buffer size for the stream
"-f", "flv", # Output format
f"{RTMP_SERVER}{STREAM_KEY}" # RTMP server URL and stream key
]
else:
logging.error(f"{STREAM_FILE} not found or invalid format. Cannot start file streaming.")
return
if REPORT:
file_stream_command.insert(1, "-report") # Insert the -report flag at index 1 in the command list if REPORT is true in the .env file
start_max_timer()
file_stream_process = subprocess.Popen(file_stream_command)
logging.debug("File stream started!")
file_streaming = True
state["recording"] = False
state["streaming"] = False
state["file_streaming"] = True
state["start_time"] = time.time()
save_state(state)
def stop_file_stream():
global file_stream_process, file_streaming
state = load_state()
if not state["file_streaming"]:
return
if file_stream_process:
file_stream_process.terminate()
file_stream_process.wait()
file_stream_process = None
logging.debug("File stream stopped!")
file_streaming = False
state["file_streaming"] = False
state["start_time"] = None
save_state(state)
def shutdown_pi():
logging.debug("Rebooting...")
if streaming:
stop_stream()
if recording:
stop_recording()
if file_streaming:
stop_file_stream()
if stream_recording:
stop_stream_recording()
# Remove old ffmpeg log files
remove_ffmpeg_logs(current_directory)
subprocess.call(['sudo', 'shutdown', '-r', 'now'])
def restart_service():
logging.debug("Restarting stream_control service...")
if streaming:
stop_stream()
if recording:
stop_recording()
if file_streaming:
stop_file_stream()
if stream_recording:
stop_stream_recording()
# Reinitialize the video device before starting the recording
reinitialize_device()
# Remove old ffmpeg log files
remove_ffmpeg_logs(current_directory)
subprocess.call(['sudo', 'systemctl', 'restart', 'stream_control.service'])
def poweroff_pi():
logging.debug("Shutting down...")
if streaming:
stop_stream()
if recording:
stop_recording()
if file_streaming:
stop_file_stream()
if stream_recording:
stop_stream_recording()
# Remove old ffmpeg log files
remove_ffmpeg_logs(current_directory)
subprocess.call(['sudo', 'shutdown', '-h', 'now'])
# Function to update the .env file
def update_env_file(data):
# Open the .env file in write mode
with open('.env', 'w') as env_file:
# Write each key-value pair to the file
for key, value in data.items():
env_file.write(f"{key}={value}\n")
# Reload the .env file to update the environment variables
load_dotenv()
# Update global variables with new values
global STREAM_KEY, RTMP_SERVER, ALSA_AUDIO_SOURCE, VIDEO_SIZE, FRAME_RATE, BITRATE, KEYFRAME_INTERVAL, AUDIO_OFFSET, BUFFER_SIZE, STREAM_M3U8_URL, STREAM_FILE, FORMAT, PRESET, REPORT, MAX_TIME
STREAM_KEY = os.getenv('STREAM_KEY')
RTMP_SERVER = os.getenv('RTMP_SERVER')
ALSA_AUDIO_SOURCE = os.getenv('ALSA_AUDIO_SOURCE')
VIDEO_SIZE = os.getenv('VIDEO_SIZE')
FRAME_RATE = int(os.getenv('FRAME_RATE'))
BITRATE = int(os.getenv('BITRATE'))
KEYFRAME_INTERVAL = int(os.getenv('KEYFRAME_INTERVAL'))
AUDIO_OFFSET = os.getenv('AUDIO_OFFSET')
STREAM_M3U8_URL = os.getenv('STREAM_M3U8_URL')
STREAM_FILE = os.getenv('STREAM_FILE')
BUFFER_SIZE = BITRATE * 2
FORMAT = os.getenv('FORMAT')
PRESET = os.getenv('PRESET')
REPORT = os.getenv('REPORT')
MAX_TIME = os.getenv('MAX_TIME')
@app.route('/')
def index():
config = {
'STREAM_KEY': os.getenv('STREAM_KEY'),
'RTMP_SERVER': os.getenv('RTMP_SERVER'),
'ALSA_AUDIO_SOURCE': os.getenv('ALSA_AUDIO_SOURCE'),
'VIDEO_SIZE': os.getenv('VIDEO_SIZE'),
'FRAME_RATE': os.getenv('FRAME_RATE'),
'BITRATE': os.getenv('BITRATE'),
'KEYFRAME_INTERVAL': os.getenv('KEYFRAME_INTERVAL'),
'AUDIO_OFFSET': os.getenv('AUDIO_OFFSET'),
'STREAM_M3U8_URL': os.getenv('STREAM_M3U8_URL'),
'STREAM_FILE': os.getenv('STREAM_FILE'), # Add STREAM_FILE to config
'FORMAT': os.getenv('FORMAT'),
'PRESET': os.getenv('PRESET'),
'REPORT': os.getenv('REPORT'),
'MAX_TIME': os.getenv('MAX_TIME')
}
state = load_state()
recordings = list_recordings()
formats, resolutions = parse_v4l2_data_from_file(SYS_INFO_FILE)
return render_template('index.html', config=config, state=state, recordings=recordings, formats=formats, resolutions=resolutions)
@app.route('/delete_file', methods=['POST'])
def delete_file_route():
directory = request.form['directory']
filename = request.form['filename']
return delete_file(directory, filename)
@app.route('/load_state', methods=['GET'])
def load_state_endpoint():
state = load_state()
return jsonify(state)
@app.route('/toggle_<action>', methods=['POST'])
def toggle_action(action):
try:
state = load_state()
logging.debug(f"Current state before toggle: {state}")
if action not in state:
raise ValueError(f"Invalid action: {action}")
# Determine the current and new state for the action
current_state = state[action]
new_state = not current_state
# Call the appropriate start/stop functions based on the action and new state
if action == 'streaming':
if new_state:
start_stream()
else:
stop_stream()
elif action == 'recording':
if new_state:
start_recording()
else:
stop_recording()
elif action == 'file_streaming':
if new_state:
start_file_stream()
else:
stop_file_stream()
elif action == 'streaming_and_recording':
if new_state:
start_stream()
start_stream_recording()
else:
stop_stream()
stop_stream_recording()
# Reload the state to capture any changes made by the start/stop functions (e.g. start_time)
state = load_state()
# Update the state
state[action] = new_state
logging.debug(f"Toggled '{action}' to {state[action]}")
# Ensure mutual exclusivity
if action == 'streaming_and_recording' and new_state:
state['streaming'] = False
state['recording'] = False
state['file_streaming'] = False
elif action == 'streaming' and new_state:
state['streaming_and_recording'] = False
state['recording'] = False
state['file_streaming'] = False
elif action == 'recording' and new_state: