|
| 1 | +import gc |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import os.path |
| 5 | +from threading import Lock |
| 6 | +from typing import List |
| 7 | + |
| 8 | +import ffmpeg |
| 9 | +import numpy as np |
| 10 | +from cv2 import cv2 |
| 11 | +from memory import get_current_memory |
| 12 | + |
| 13 | +# logging |
| 14 | +logger = logging.getLogger(__name__) |
| 15 | +logger.setLevel(logging.DEBUG) |
| 16 | +formatter = logging.Formatter("%(asctime)s [%(levelname)s] %(name)s: %(message)s") |
| 17 | +handler = logging.StreamHandler() |
| 18 | +handler.setFormatter(formatter) |
| 19 | +logger.addHandler(handler) |
| 20 | + |
| 21 | + |
| 22 | +class VideoEncoder: |
| 23 | + """ |
| 24 | + This class exposes methods for opening, processing and saving a video. |
| 25 | + """ |
| 26 | + |
| 27 | + lock = Lock() |
| 28 | + |
| 29 | + @staticmethod |
| 30 | + def load(path) -> List: |
| 31 | + # todo: |
| 32 | + # - support multiple files |
| 33 | + # - support multiple processes |
| 34 | + # - support multiple threads |
| 35 | + # - support logging time |
| 36 | + logger.debug(f"Loading file://{os.path.abspath(path)}") |
| 37 | + frames = [] |
| 38 | + cap = cv2.VideoCapture(path) |
| 39 | + ret = True |
| 40 | + while ret: |
| 41 | + # read one frame from the 'capture' object; img is (H, W, C) [height width channels?] |
| 42 | + ret, img = cap.read() |
| 43 | + if ret: |
| 44 | + frames.append(img) |
| 45 | + logger.debug(get_current_memory()) |
| 46 | + gc.collect() |
| 47 | + logger.debug("VideoEncoder.load - garbage collected") |
| 48 | + return frames |
| 49 | + |
| 50 | + @staticmethod |
| 51 | + def get_fps(path) -> float: |
| 52 | + # todo: verify it's not loaded into memory |
| 53 | + """ |
| 54 | + Return the FPS of a video file without loading it in to memory |
| 55 | + :param path: |
| 56 | + :return: |
| 57 | + """ |
| 58 | + return cv2.VideoCapture(path).get(cv2.CAP_PROP_FPS) |
| 59 | + |
| 60 | + @staticmethod |
| 61 | + def get_total_frames(path) -> int: |
| 62 | + return int(cv2.VideoCapture(path).get(cv2.CAP_PROP_FRAME_COUNT)) |
| 63 | + |
| 64 | + @staticmethod |
| 65 | + def save(path: str, frames: List[np.array], fps: float, size: tuple) -> None: |
| 66 | + """ |
| 67 | + Save video to disk |
| 68 | + :param path: path to save image to |
| 69 | + :param frames: list of numpy arrays, each representing a single video frame |
| 70 | + :param size: a tuple (width, height) |
| 71 | + :param fps: int |
| 72 | + :return: |
| 73 | + """ |
| 74 | + # Options: mp4v, avc1 |
| 75 | + fourcc = cv2.VideoWriter_fourcc(*"mp4v") |
| 76 | + video = cv2.VideoWriter(path, fourcc, fps, size) |
| 77 | + # todo: how to optimize? maybe by using separate file+thread per 10 seconds of video? |
| 78 | + length = len(frames) |
| 79 | + for i, frame in enumerate(frames): |
| 80 | + # todo: make percentage available to invoker of method |
| 81 | + percentage = round((i + 1) / length * 100, 2) |
| 82 | + logger.debug(percentage) |
| 83 | + video.write(frame) |
| 84 | + |
| 85 | + video.release() |
| 86 | + |
| 87 | + logger.info(get_current_memory()) |
| 88 | + del video |
| 89 | + gc.collect() |
| 90 | + logger.info("VideoEncoder.save - garbage collected") |
| 91 | + logger.info(get_current_memory()) |
| 92 | + |
| 93 | + @staticmethod |
| 94 | + def merge_av(audio_path, video_path, output_path): |
| 95 | + if not audio_path: |
| 96 | + logger.info("no audio provided") |
| 97 | + if not video_path: |
| 98 | + logger.info("no video provided") |
| 99 | + return |
| 100 | + logger.debug(f"Merging audio and video: \n a: {audio_path} \n v: {video_path}") |
| 101 | + audio = ffmpeg.input(audio_path).audio |
| 102 | + video = ffmpeg.input(video_path).video |
| 103 | + out = ffmpeg.output( |
| 104 | + audio, |
| 105 | + video, |
| 106 | + output_path, |
| 107 | + vcodec="copy", |
| 108 | + acodec="aac", |
| 109 | + strict="experimental", |
| 110 | + ) |
| 111 | + out.run() |
| 112 | + logger.info(f"saved to file://{os.path.abspath(output_path)}") |
| 113 | + |
| 114 | + logger.info(get_current_memory()) |
0 commit comments