|
| 1 | +import subprocess |
| 2 | +import os |
| 3 | +from datetime import datetime |
| 4 | +from sys import platform |
| 5 | +import pyaudio |
| 6 | +import wave |
| 7 | + |
| 8 | +from openadapt.config import CAPTURE_DIR_PATH |
| 9 | + |
| 10 | + |
| 11 | +class Capture: |
| 12 | + """Capture the screen, audio, and camera on Linux.""" |
| 13 | + |
| 14 | + def __init__(self) -> None: |
| 15 | + """Initialize the capture object.""" |
| 16 | + if not platform.startswith("linux"): |
| 17 | + assert platform == "linux", platform |
| 18 | + |
| 19 | + self.is_recording = False |
| 20 | + self.audio_out = None |
| 21 | + self.video_out = None |
| 22 | + self.audio_stream = None |
| 23 | + self.audio_frames = [] |
| 24 | + |
| 25 | + # Initialize PyAudio |
| 26 | + self.audio = pyaudio.PyAudio() |
| 27 | + |
| 28 | + def get_screen_resolution(self) -> tuple: |
| 29 | + """Get the screen resolution dynamically using xrandr.""" |
| 30 | + try: |
| 31 | + # Get screen resolution using xrandr |
| 32 | + output = subprocess.check_output( |
| 33 | + "xrandr | grep '*' | awk '{print $1}'", shell=True |
| 34 | + ) |
| 35 | + resolution = output.decode("utf-8").strip() |
| 36 | + width, height = resolution.split("x") |
| 37 | + return int(width), int(height) |
| 38 | + except subprocess.CalledProcessError as e: |
| 39 | + raise RuntimeError(f"Failed to get screen resolution: {e}") |
| 40 | + |
| 41 | + def start(self, audio: bool = True, camera: bool = False) -> None: |
| 42 | + """Start capturing the screen, audio, and camera. |
| 43 | +
|
| 44 | + Args: |
| 45 | + audio (bool, optional): Whether to capture audio (default: True). |
| 46 | + camera (bool, optional): Whether to capture the camera (default: False). |
| 47 | + """ |
| 48 | + if self.is_recording: |
| 49 | + raise RuntimeError("Recording is already in progress") |
| 50 | + |
| 51 | + self.is_recording = True |
| 52 | + capture_dir = CAPTURE_DIR_PATH |
| 53 | + if not os.path.exists(capture_dir): |
| 54 | + os.mkdir(capture_dir) |
| 55 | + |
| 56 | + # Get the screen resolution dynamically |
| 57 | + screen_width, screen_height = self.get_screen_resolution() |
| 58 | + |
| 59 | + # Start video capture using ffmpeg |
| 60 | + video_filename = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".mp4" |
| 61 | + self.video_out = os.path.join(capture_dir, video_filename) |
| 62 | + self._start_video_capture(screen_width, screen_height) |
| 63 | + |
| 64 | + # Start audio capture |
| 65 | + if audio: |
| 66 | + audio_filename = datetime.now().strftime("%Y-%m-%d-%H-%M-%S") + ".wav" |
| 67 | + self.audio_out = os.path.join(capture_dir, audio_filename) |
| 68 | + self._start_audio_capture() |
| 69 | + |
| 70 | + def _start_video_capture(self, width: int, height: int) -> None: |
| 71 | + """Start capturing the screen using ffmpeg with the dynamic resolution.""" |
| 72 | + cmd = [ |
| 73 | + "ffmpeg", |
| 74 | + "-f", |
| 75 | + "x11grab", # Capture X11 display |
| 76 | + "-video_size", |
| 77 | + f"{width}x{height}", # Use dynamic screen resolution |
| 78 | + "-framerate", |
| 79 | + "30", # Set frame rate |
| 80 | + "-i", |
| 81 | + ":0.0", # Capture from display 0 |
| 82 | + "-c:v", |
| 83 | + "libx264", # Video codec |
| 84 | + "-preset", |
| 85 | + "ultrafast", # Speed/quality tradeoff |
| 86 | + "-y", |
| 87 | + self.video_out, # Output file |
| 88 | + ] |
| 89 | + self.video_proc = subprocess.Popen(cmd) |
| 90 | + |
| 91 | + def _start_audio_capture(self) -> None: |
| 92 | + """Start capturing audio using PyAudio.""" |
| 93 | + self.audio_stream = self.audio.open( |
| 94 | + format=pyaudio.paInt16, |
| 95 | + channels=2, |
| 96 | + rate=44100, |
| 97 | + input=True, |
| 98 | + frames_per_buffer=1024, |
| 99 | + stream_callback=self._audio_callback, |
| 100 | + ) |
| 101 | + self.audio_frames = [] |
| 102 | + self.audio_stream.start_stream() |
| 103 | + |
| 104 | + def _audio_callback( |
| 105 | + self, in_data: bytes, frame_count: int, time_info: dict, status: int |
| 106 | + ) -> tuple: |
| 107 | + """Callback function to process audio data.""" |
| 108 | + self.audio_frames.append(in_data) |
| 109 | + return (None, pyaudio.paContinue) |
| 110 | + |
| 111 | + def stop(self) -> None: |
| 112 | + """Stop capturing the screen, audio, and camera.""" |
| 113 | + if self.is_recording: |
| 114 | + # Stop the video capture |
| 115 | + self.video_proc.terminate() |
| 116 | + |
| 117 | + # Stop audio capture |
| 118 | + if self.audio_stream: |
| 119 | + self.audio_stream.stop_stream() |
| 120 | + self.audio_stream.close() |
| 121 | + self.audio.terminate() |
| 122 | + self.save_audio() |
| 123 | + |
| 124 | + self.is_recording = False |
| 125 | + |
| 126 | + def save_audio(self) -> None: |
| 127 | + """Save the captured audio to a WAV file.""" |
| 128 | + if self.audio_out: |
| 129 | + with wave.open(self.audio_out, "wb") as wf: |
| 130 | + wf.setnchannels(2) |
| 131 | + wf.setsampwidth(self.audio.get_sample_size(pyaudio.paInt16)) |
| 132 | + wf.setframerate(44100) |
| 133 | + wf.writeframes(b"".join(self.audio_frames)) |
| 134 | + |
| 135 | + |
| 136 | +if __name__ == "__main__": |
| 137 | + capture = Capture() |
| 138 | + capture.start(audio=True, camera=False) |
| 139 | + input("Press enter to stop") |
| 140 | + capture.stop() |
0 commit comments