"""Calculate audio stats.""" import re import ffmpeg from video.connectors import s3 as s3_connector from video.constants import job_io_fields from video.logic.activity_task_logger import activity_task_logger from video.utils import text INPUT_FIELDS = [ job_io_fields.INPUT_VIDEO_S3_BUCKET, job_io_fields.INPUT_VIDEO_S3_KEY, ] @activity_task_logger(INPUT_FIELDS) def calculate_audio_stats(inputs): """Calculate audio stats. Args: inputs (dict): Inputs. Returns: dict: Outputs. """ s3_bucket = inputs[job_io_fields.INPUT_VIDEO_S3_BUCKET] s3_key = inputs[job_io_fields.INPUT_VIDEO_S3_KEY] output_options = { 'vn': None, # don't process video stream } video_s3_url = s3_connector.get_url_for_s3_object(s3_bucket, s3_key) (stdout, stderr) = ( ffmpeg .input(video_s3_url) .filter('astats') .output('pipe:', format='null', **output_options) .run(capture_stderr=True) ) rms_level_db_regex = r'RMS level dB:\s(.*)' left_channel_start_regex = 'Channel: 1' right_channel_start_regex = 'Channel: 2' stderr_lines = text.bytes_to_lines_of_text(stderr) outputs = { job_io_fields.LEFT_AUDIO_CHANNEL_RMS_VOLUME_DECIBELS: None, job_io_fields.RIGHT_AUDIO_CHANNEL_RMS_VOLUME_DECIBELS: None, } left_audio_channel_rms_volume = None right_audio_channel_rms_volume = None current_channel = None for line in stderr_lines: left_channel_start_match = re.search(left_channel_start_regex, line) if left_channel_start_match: current_channel = 'left' continue right_channel_start_match = re.search(right_channel_start_regex, line) if right_channel_start_match: current_channel = 'right' continue rms_level_db_match = re.search(rms_level_db_regex, line) if not rms_level_db_match: continue if current_channel == 'left': [left_audio_channel_rms_volume] = rms_level_db_match.groups() if left_audio_channel_rms_volume == '-inf': left_audio_channel_rms_volume = -60 outputs[job_io_fields.LEFT_AUDIO_CHANNEL_RMS_VOLUME_DECIBELS] = ( float(left_audio_channel_rms_volume)) elif current_channel == 'right': [right_audio_channel_rms_volume] = rms_level_db_match.groups() if right_audio_channel_rms_volume == '-inf': right_audio_channel_rms_volume = -60 outputs[job_io_fields.RIGHT_AUDIO_CHANNEL_RMS_VOLUME_DECIBELS] = ( float(right_audio_channel_rms_volume)) if None not in [ left_audio_channel_rms_volume, right_audio_channel_rms_volume]: return outputs return outputs