Use ffmpeg with volumedetect filter to get the mean volume of the input file.
171216
def parse_volumedetect_stats(self):
        
        logger.info(
            "Running first pass volumedetect filter for stream {}".format(self.stream_id)
        )

        filter_str = '[0:{}]volumedetect'.format(self.stream_id)

        cmd = [
            self.media_file.ffmpeg_normalize.ffmpeg_exe, '-nostdin', '-y',
            '-i', self.media_file.input_file,
            '-filter_complex', filter_str,
            '-vn', '-sn', '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        for progress in cmd_runner.run_ffmpeg_command():
            yield progress
        output = cmd_runner.get_output()

        logger.debug("Volumedetect command output:")
        logger.debug(output)

        mean_volume_matches = re.findall(r"mean_volume: ([\-\d\.]+) dB", output)
        if mean_volume_matches:
            self.loudness_statistics['mean'] = float(mean_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get mean volume for {}".format(self.media_file.input_file)
            )

        max_volume_matches = re.findall(r"max_volume: ([\-\d\.]+) dB", output)
        if max_volume_matches:
            self.loudness_statistics['max'] = float(max_volume_matches[0])
        else:
            raise FFmpegNormalizeError(
                "Could not get max volume for {}".format(self.media_file.input_file)
            )
45631
def format_ffmpeg_filter(name, params):
  
  return "%s=%s" % (name,
                    ":".join("%s=%s" % (k, v) for k, v in params.items()))
53613
def fdfilter(data, *filt, **kwargs):
    
    # parse keyword args
    inplace = kwargs.pop('inplace', False)
    analog = kwargs.pop('analog', False)
    fs = kwargs.pop('sample_rate', None)
    if kwargs:
        raise TypeError("filter() got an unexpected keyword argument '%s'"
                        % list(kwargs.keys())[0])

    # parse filter
    if fs is None:
        fs = 2 * (data.shape[-1] * data.df).to('Hz').value
    form, filt = parse_filter(filt, analog=analog, sample_rate=fs)
    lti = signal.lti(*filt)

    # generate frequency response
    freqs = data.frequencies.value.copy()
    fresp = numpy.nan_to_num(abs(lti.freqresp(w=freqs)[1]))

    # apply to array
    if inplace:
        data *= fresp
        return data
    new = data * fresp
    return new
1244775
def ffprobe(input_file, verbose=False):
    """"""
    if isinstance(input_file, FileObject):
        exists = input_file.exists
        path = input_file.path
    elif type(input_file) in string_types:
        exists = os.path.exists(input_file)
        path = input_file
    else:
        raise TypeError("input_path must be of string or FileObject type")
    if not exists:
        logging.error("ffprobe: file does not exist ({})".format(input_file))
        return False
    cmd = [
            "ffprobe",
            "-show_format",
            "-show_streams",
            "-print_format", "json",
            path
        ]
    FNULL = open(os.devnull, "w")
    if verbose:
        logging.debug("Executing {}".format(" ".join(cmd)))
    proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    res = decode_if_py3(proc.stdout.read())
    proc.wait()
    if proc.returncode:
        if verbose:
            logging.error("Unable to read media file {}\n\n{}\n\n".format(input_file, indent(proc.stderr.read())))
        else:
            logging.warning("Unable to read media file {}".format(input_file))
        return False
    return json.loads(res)
1366436
function ffmpeg(os) {
  var stdio = os.stdio===undefined? STDIO:os.stdio;
  return new Promise((fres, frej) => cp.exec(command(os), {stdio}, (err, stdout, stderr) => {
    if(err) frej(err);
    else fres({stdout, stderr});
  }));
}
412445
def ffmpeg_has_loudnorm():
    
    cmd_runner = CommandRunner([get_ffmpeg_exe(), '-filters'])
    cmd_runner.run_command()
    output = cmd_runner.get_output()
    if 'loudnorm' in output:
        return True
    else:
        logger.warning(
            "Your ffmpeg version does not support the 'loudnorm' filter. "
            "Please make sure you are running ffmpeg v3.1 or above."
        )
        return False
567326
def get_waveform_amplitude(mean_masks, mean_waveforms):
    """"""

    assert mean_waveforms.ndim == 2
    n_samples, n_channels = mean_waveforms.shape

    assert mean_masks.ndim == 1
    assert mean_masks.shape == (n_channels,)

    mean_waveforms = mean_waveforms * mean_masks
    assert mean_waveforms.shape == (n_samples, n_channels)

    # Amplitudes.
    m, M = mean_waveforms.min(axis=0), mean_waveforms.max(axis=0)
    return M - m
1361872
def get_speaker_volume(self):
        """"""
        if not self.camera_extended_properties:
            return None

        speaker = self.camera_extended_properties.get('speaker')
        if not speaker:
            return None

        return speaker.get('volume')
870524
def detect(filename, include_confidence=False):
    
    f = open(filename)
    detection = chardet.detect(f.read())
    f.close()
    encoding = detection.get('encoding')
    confidence = detection.get('confidence')
    if include_confidence:
        return (encoding, confidence)
    return encoding
1204926
def audioread(filename):
    
    try:
        if '.wav' in filename.lower():
            fs, signal = wv.read(filename)
        elif '.call' in filename.lower():
            with open(filename, 'rb') as f:
                signal = np.fromfile(f, dtype=np.int16)
            fs = 333333
        else:
            raise IOError("Unsupported audio format for file: {}".format(filename))
    except:
        print u"Problem reading wav file"
        raise
    signal = signal.astype(float)
    return fs, signal
319996
@Override
    public AudioFileFormat getAudioFileFormat(InputStream inputStream, long medialength) throws UnsupportedAudioFileException, IOException {
        return getAudioFileFormat(inputStream, (int) medialength, AudioSystem.NOT_SPECIFIED);
    }
335457
def parse_streams(self):
        
        logger.debug("Parsing streams of {}".format(self.input_file))

        cmd = [
            self.ffmpeg_normalize.ffmpeg_exe, '-i', self.input_file,
            '-c', 'copy', '-t', '0', '-map', '0',
            '-f', 'null', NUL
        ]

        cmd_runner = CommandRunner(cmd)
        cmd_runner.run_command()
        output = cmd_runner.get_output()

        logger.debug("Stream parsing command output:")
        logger.debug(output)

        output_lines = [line.strip() for line in output.split('\n')]

        for line in output_lines:

            if not line.startswith('Stream'):
                continue

            stream_id_match = re.search(r'#0:([\d]+)', line)
            if stream_id_match:
                stream_id = int(stream_id_match.group(1))
                if stream_id in self._stream_ids():
                    continue
            else:
                continue

            if 'Audio' in line:
                logger.debug("Found audio stream at index {}".format(stream_id))
                sample_rate_match = re.search(r'(\d+) Hz', line)
                sample_rate = int(sample_rate_match.group(1)) if sample_rate_match else None
                bit_depth_match = re.search(r's(\d+)p?,', line)
                bit_depth = int(bit_depth_match.group(1)) if bit_depth_match else None
                self.streams['audio'][stream_id] = AudioStream(self, stream_id, sample_rate, bit_depth)

            elif 'Video' in line:
                logger.debug("Found video stream at index {}".format(stream_id))
                self.streams['video'][stream_id] = VideoStream(self, stream_id)

            elif 'Subtitle' in line:
                logger.debug("Found subtitle stream at index {}".format(stream_id))
                self.streams['subtitle'][stream_id] = SubtitleStream(self, stream_id)

        if not self.streams['audio']:
            raise FFmpegNormalizeError(
                "Input file {} does not contain any audio streams"
                .format(self.input_file))

        if os.path.splitext(self.output_file)[1].lower() in ['.wav', '.mp3', '.aac']:
            logger.warning(
                "Output file only supports one stream. "
                "Keeping only first audio stream."
            )
            first_stream = list(self.streams['audio'].values())[0]
            self.streams['audio'] = {first_stream.stream_id: first_stream}
            self.streams['video'] = {}
            self.streams['subtitle'] = {}
536414
def get_second_pass_opts_peakrms(self):
        
        normalization_type = self.media_file.ffmpeg_normalize.normalization_type
        target_level = self.media_file.ffmpeg_normalize.target_level

        if normalization_type == 'peak':
            adjustment = 0 + target_level - \
                self.loudness_statistics['max']
        elif normalization_type == 'rms':
            adjustment = target_level - \
                self.loudness_statistics['mean']
        else:
            raise FFmpegNormalizeError(
                "Can only set adjustment for peak and RMS normalization"
            )

        logger.info(
            "Adjusting stream {} by {} dB to reach {}"
            .format(self.stream_id, adjustment, target_level)
        )

        if self.loudness_statistics['max'] + adjustment > 0:
            logger.warning(
                "Adjusting will lead to clipping of {} dB"
                .format(self.loudness_statistics['max'] + adjustment)
            )

        return 'volume={}dB'.format(adjustment)
1024405
def getParser():
    ""
    parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
                                     description=__description__)
    parser.add_argument('output', help='Target volume.')
    parser.add_argument('inputs', nargs='+', help='Source volume(s).')
    parser.add_argument('-o', '--operation', dest='operation', choices=['sum', 'avg', 'max', 'min'], default='avg', help='Combinatorial operation to conduct.')
    parser.add_argument('-v', dest='verbose', action='store_true', help='Display more information.')
    parser.add_argument('-d', dest='debug', action='store_true', help='Display debug information.')
    parser.add_argument('-f', dest='force', action='store_true', help='Silently override existing output images.')
    return parser
517870
def median_fltr(dem, fsize=7, origmask=False):
    
    print("Applying median filter with size %s" % fsize)
    from scipy.ndimage.filters import median_filter
    dem_filt_med = median_filter(dem.filled(np.nan), fsize)
    #Now mask all nans
    out = np.ma.fix_invalid(dem_filt_med, copy=False, fill_value=dem.fill_value)
    if origmask:
        out = np.ma.array(out, mask=dem.mask, fill_value=dem.fill_value)
    out.set_fill_value(dem.fill_value)
    return out
685395
def file_reader(self):
        """"""
        self.update_config()
        path = self.config['path']
        # open file to get dimensions
        with self.subprocess(
                ['ffmpeg', '-v', 'info', '-y', '-an', '-vn', '-i', path, '-'],
                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                stdin=open(os.devnull), universal_newlines=True) as sp:
            for line in sp.stderr.read().splitlines():
                match = re.search('(\d{2,})x(\d{2,})', line)
                if match:
                    xlen, ylen = map(int, match.groups())
                    break
            else:
                self.logger.critical('Failed to open %s', path)
                return
        # read file repeatedly to allow looping
        while True:
            # can change config once per outer loop
            self.update_config()
            bit16 = self.config['16bit']
            self.frame_type = self.config['type']
            self.metadata = Metadata().from_file(path)
            audit = self.metadata.get('audit')
            audit += 'data = %s\n' % path
            audit += '    type: %s, 16bit: %s\n' % (self.frame_type, bit16)
            self.metadata.set('audit', audit)
            bps = {'RGB': 3, 'Y': 1}[self.frame_type]
            pix_fmt = {'RGB': ('rgb24', 'rgb48le'),
                       'Y':   ('gray', 'gray16le')}[self.frame_type][bit16]
            bytes_per_line = xlen * ylen * bps
            if bit16:
                bytes_per_line *= 2
            # open file to read data
            with self.subprocess(
                    ['ffmpeg', '-v', 'warning', '-an', '-i', path,
                     '-f', 'image2pipe', '-pix_fmt', pix_fmt,
                     '-c:v', 'rawvideo', '-'],
                    stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                    stdin=open(os.devnull), bufsize=bytes_per_line) as sp:
                while True:
                    try:
                        raw_data = sp.stdout.read(bytes_per_line)
                    except Exception as ex:
                        self.logger.exception(ex)
                        return
                    if len(raw_data) < bytes_per_line:
                        break
                    if bit16:
                        image = numpy.fromstring(raw_data, dtype=numpy.uint16)
                        image = image.astype(pt_float) / pt_float(256.0)
                    else:
                        image = numpy.fromstring(raw_data, dtype=numpy.uint8)
                    yield image.reshape((ylen, xlen, bps))
            self.update_config()
            if self.frame_no == 0 or self.config['looping'] == 'off':
                return
129016
def detect(self, volume_system, vstype='detect'):
        """"""

        try:
            cmd = ['mmls']
            if volume_system.parent.offset:
                cmd.extend(['-o', str(volume_system.parent.offset // volume_system.disk.block_size)])
            if vstype in ('dos', 'mac', 'bsd', 'sun', 'gpt'):
                cmd.extend(['-t', vstype])
            cmd.append(volume_system.parent.get_raw_path())
            output = _util.check_output_(cmd, stderr=subprocess.STDOUT)
            volume_system.volume_source = 'multi'

        except Exception as e:
            # some bug in sleuthkit makes detection sometimes difficult, so we hack around it:
            if hasattr(e, 'output') and "(GPT or DOS at 0)" in e.output.decode() and vstype != 'gpt':
                volume_system.vstype = 'gpt'
                # noinspection PyBroadException
                try:
                    logger.warning("Error in retrieving volume info: mmls couldn't decide between GPT and DOS, "
                                   "choosing GPT for you. Use --vstype=dos to force DOS.", exc_info=True)
                    cmd = ['mmls', '-t', 'gpt', self.parent.get_raw_path()]
                    output = _util.check_output_(cmd, stderr=subprocess.STDOUT)
                    volume_system.volume_source = 'multi'
                except Exception as e:
                    logger.exception("Failed executing mmls command")
                    raise SubsystemError(e)
            else:
                logger.exception("Failed executing mmls command")
                raise SubsystemError(e)

        output = output.split("Description", 1)[-1]
        for line in output.splitlines():
            if not line:
                continue
            # noinspection PyBroadException
            try:
                values = line.split(None, 5)

                # sometimes there are only 5 elements available
                description = ''
                index, slot, start, end, length = values[0:5]
                if len(values) > 5:
                    description = values[5]

                volume = volume_system._make_subvolume(
                    index=self._format_index(volume_system, int(index[:-1])),
                    offset=int(start) * volume_system.disk.block_size,
                    size=int(length) * volume_system.disk.block_size
                )
                volume.info['fsdescription'] = description
            except Exception:
                logger.exception("Error while parsing mmls output")
                continue

            if slot.lower() == 'meta':
                volume.flag = 'meta'
                logger.info("Found meta volume: block offset: {0}, length: {1}".format(start, length))
            elif slot.lower().startswith('-----'):
                volume.flag = 'unalloc'
                logger.info("Found unallocated space: block offset: {0}, length: {1}".format(start, length))
            else:
                volume.flag = 'alloc'
                if ":" in slot:
                    volume.slot = _util.determine_slot(*slot.split(':'))
                else:
                    volume.slot = _util.determine_slot(-1, slot)
                volume_system._assign_disktype_data(volume)
                logger.info("Found allocated {2}: block offset: {0}, length: {1} ".format(start, length,
                                                                                          volume.info['fsdescription']))

            yield volume