├── dummy.wav ├── install_dep.sh ├── DRCStandalone.py ├── brutefir_PI ├── updateFilters ├── setup_brutefir_pi └── setup_brutefir ├── DRC.plugin ├── measure2channel.sh ├── installPORC.sh ├── Makefile ├── convertFilter.sh ├── DependsWrapper.py ├── calcFilterDRC ├── gst-plugins-good-patch ├── patch-gstreamer.sh ├── audiofirfilter.h ├── audiofxbasefirfilter.h └── audiofirfilter.c ├── PORCCfgDlg.py ├── install.sh ├── ChannelSelDlg.py ├── measure1Channel ├── calcFilterPORC ├── updateBruteFIRCfg ├── .brutefir_config ├── DRCConfig.py ├── DRCCfgDlg.py ├── TargetCurveDlg.py ├── .brutefir_config51 ├── MeasureQADlg.py ├── XMLSerializer.py ├── ImpRespDlg.py ├── measure ├── alsaTools.py ├── DRCTargetCurveUI.py ├── README.md ├── DRC.py ├── DRCFileTool.py ├── DRCUi.py ├── DRC_rb3compat.py └── LICENSE.txt /dummy.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/TheBigW/DRC/HEAD/dummy.wav -------------------------------------------------------------------------------- /install_dep.sh: -------------------------------------------------------------------------------- 1 | sudo apt-get install drc python3-autopilot alsa-utils sox 2 | -------------------------------------------------------------------------------- /DRCStandalone.py: -------------------------------------------------------------------------------- 1 | from DRCUi import DRCDlg 2 | 3 | drcDlg = DRCDlg(None) 4 | drcDlg.show_ui(None,None,None) 5 | -------------------------------------------------------------------------------- /brutefir_PI/updateFilters: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PI_NAME="$2" 4 | PI_USER="$1" 5 | PI_SSH_NAME=$PI_USER@$PI_NAME 6 | 7 | scp ~/filter_l.pcm $PI_SSH_NAME:filter_l.pcm 8 | scp ~/filter_r.pcm $PI_SSH_NAME:filter_r.pcm 9 | 10 | -------------------------------------------------------------------------------- /DRC.plugin: -------------------------------------------------------------------------------- 1 | [Plugin] 2 | Loader=python3 3 | Module=DRC 4 | IAge=2 5 | Depends=rb 6 | Name=DRC 7 | Description=digital room correction 8 | Authors=Tobias Wenig 9 | Copyright=Tobias Wenig 2013 10 | Website=https://github.com/TheBigW/DRC 11 | -------------------------------------------------------------------------------- /measure2channel.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | AMPLITUDE="$1" 3 | INPUT_HW="$2" 4 | OUTPUT_HW="$3" 5 | START_FREQ="$4" 6 | END_FREQ="$5" 7 | DURATION="$6" 8 | IMP_OUT_FILE="$7" 9 | REC_CHANNEL="$8" 10 | SEPARATE_CHANNEL="$9" 11 | NUM_CHANNELS="${10}" 12 | SAMPLE_RATE="${11}" 13 | 14 | dt=$(date '+%d%m%Y%H%M%S'); 15 | ./measure1Channel 1 hw:1,0 hw:0,0 10 22050 15 ~/impout_$dt.wav 1 True 2 44100 -------------------------------------------------------------------------------- /installPORC.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PORC_DIR="$1" 4 | 5 | if [ -z "$PORC_DIR" ]; then 6 | PORC_DIR="./" 7 | fi 8 | 9 | read -p "Do you want to install PORC and dependencies (Y/N)? " -n 1 -r 10 | echo 11 | if [[ $REPLY =~ ^[Yy]$ ]] 12 | then 13 | sudo apt-get install git python-numpy python-scipy python-matplotlib 14 | sudo mkdir $PORC_DIR 15 | cd $PORC_DIR 16 | sudo git clone https://github.com/zzzzrrr/porc.git 17 | fi 18 | -------------------------------------------------------------------------------- /brutefir_PI/setup_brutefir_pi: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | PI_NAME="$2" 4 | PI_USER="$1" 5 | PI_SSH_NAME=$PI_USER@$PI_NAME 6 | 7 | scp ./setup_brutefir $PI_SSH_NAME:setup_brutefir 8 | scp /usr/share/rhythmbox/plugins/DRC/.brutefir_config $PI_SSH_NAME:.brutefir_config 9 | scp /usr/share/rhythmbox/plugins/DRC/.brutefir_defaults $PI_SSH_NAME:.brutefir_defaults 10 | ./updateFilters $PI_USER $PI_NAME 11 | 12 | #ssh $PI_SSH_NAME /home/$PI_USER/setup_brutefir 13 | echo "login to the PI using ssh and exectute: ./setup_brutefir" 14 | ssh $PI_SSH_NAME 15 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | DESTDIR= 2 | SUBDIR=/usr/lib/rhythmbox/plugins/DRC/ 3 | DATADIR=/usr/share/rhythmbox/plugins/DRC/ 4 | LOCALEDIR=/usr/share/locale/ 5 | 6 | all: 7 | clean: 8 | - rm *.pyc 9 | 10 | install: 11 | install -d $(DESTDIR)$(SUBDIR) 12 | install -d $(DESTDIR)$(DATADIR) 13 | install -m 644 *.py $(DESTDIR)$(SUBDIR) 14 | install -m 644 *.wav $(DESTDIR)$(SUBDIR) 15 | install -m 755 calcFilter* $(DESTDIR)$(DATADIR) 16 | install -m 755 updateBruteFIRCfg $(DESTDIR)$(DATADIR) 17 | install -m 755 measure* $(DESTDIR)$(DATADIR) 18 | install -m 755 installPORC.sh $(DESTDIR)$(DATADIR) 19 | install -m 644 *.glade $(DESTDIR)$(DATADIR) 20 | install -m 644 DRC.plugin $(DESTDIR)$(SUBDIR) 21 | install -m 644 LICENSE.txt $(DESTDIR)$(SUBDIR) 22 | -------------------------------------------------------------------------------- /convertFilter.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get command line parameters 4 | RATE="44100" 5 | WAV_FILTER_FILE="$1" 6 | 7 | SOXI_RESULT="$(soxi $WAV_FILTER_FILE)" 8 | regex="Channels : ([0-9])" 9 | [[ $SOXI_RESULT =~ $regex ]] 10 | NUM_WAV_CHANNELS=${BASH_REMATCH[1]} 11 | echo "runnign sox to create pcm filters for "$NUM_WAV_CHANNELS" channels" 12 | for ((i=1;i<=NUM_WAV_CHANNELS;i++)); 13 | do 14 | CURRENT_FILE=./filter_$i.pcm 15 | sox $WAV_FILTER_FILE -t raw -c 1 $CURRENT_FILE remix $i 16 | done 17 | 18 | #rebuild new wave filters 19 | sox -t raw -r $RATE -c 1 -e float -b32 filter_1.pcm -t wav /tmp/filter_l.wav 20 | sox -t raw -r $RATE -c 1 -e float -b32 filter_2.pcm -t wav /tmp/filter_r.wav 21 | sox -M /tmp/filter_l.wav /tmp/filter_r.wav ./new_filter.wav 22 | -------------------------------------------------------------------------------- /DependsWrapper.py: -------------------------------------------------------------------------------- 1 | #wrapper to provide independence from RB for standalone usage 2 | 3 | import os 4 | 5 | class DependsWrapperImpl(object): 6 | @staticmethod 7 | def find_plugin_file(parent, filename): 8 | bIsRbPlugin = False 9 | try: 10 | import rb 11 | bIsRbPlugin = True 12 | except: 13 | print("running in stand alone mode -> not using RB") 14 | pass 15 | fullpathname = None 16 | if bIsRbPlugin: 17 | fullpathname = rb.find_plugin_file(parent, filename) 18 | else: 19 | #TODO: manually implement for non-RB 20 | fullpathname = "./" 21 | for root, dirs, files in os.walk(fullpathname): 22 | for file in files: 23 | #print("checking file: ", file) 24 | if file == filename: 25 | fullpathname = file 26 | return fullpathname 27 | return fullpathname 28 | -------------------------------------------------------------------------------- /calcFilterDRC: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get command line parameters 4 | DRC_CFG_FILE="${1}" 5 | IMPULSE_FILE="$2" 6 | FILTER_FILE="$3" 7 | CURR_CHANNEL="$4" 8 | RATE="44100" 9 | # defaults 10 | TMP="/tmp" 11 | SOX="sox" 12 | 13 | filename=$(basename "$IMPULSE_FILE") 14 | extension="${filename##*.}" 15 | PCM_IMP_FILENAME=${TMP}/impulse_chanel$CURR_CHANNEL.pcm 16 | echo "extension : " $extension 17 | if [ "$extension" == "wav" ]; then 18 | REMIX_PARAM="remix "$((CURR_CHANNEL + 1)) 19 | echo "wavefile -> converting to pcm for DRC with remix param : "$REMIX_PARAM 20 | regex="Sample Rate : ([0-9]{4,7})" 21 | SOXI_RESULT="$(soxi $IMPULSE_FILE)" 22 | [[ $SOXI_RESULT =~ $regex ]] 23 | RATE=${BASH_REMATCH[1]} 24 | $SOX $IMPULSE_FILE -t raw -r $RATE -e float -b 32 -c 1 $PCM_IMP_FILENAME $REMIX_PARAM 25 | else 26 | echo "pcm filer file -> just copy" 27 | cp $IMPULSE_FILE $PCM_IMP_FILENAME 28 | fi 29 | 30 | echo DRCCfgFile : $DRC_CFG_FILE 31 | echo "calculating filters" 32 | PCM_FILTER=${TMP}/filter.pcm 33 | drc --BCInFile=$PCM_IMP_FILENAME --PSOutFile=$PCM_FILTER --TCOutFile=test.pcm "${DRC_CFG_FILE}" 34 | sox -t raw -r $RATE -c 1 -e float -b32 ${PCM_FILTER} -t wav ${FILTER_FILE} 35 | -------------------------------------------------------------------------------- /gst-plugins-good-patch/patch-gstreamer.sh: -------------------------------------------------------------------------------- 1 | GST_PLUGIN_VERSION=1.16.2 2 | apt-get source gstreamer1.0-plugins-good 3 | #sudo apt-get install auto-apt 4 | #sudo auto-apt update 5 | #sudo auto-apt updatedb && sudo auto-apt update-local 6 | sudo apt-get install libglib2.0-dev 7 | sudo apt-get install libglib2.0-dev 8 | sudo apt-get install libgstreamer1.0-dev 9 | sudo apt-get install libgstreamer-plugins-base1.0-dev 10 | sudo apt-get install liborc-0.4-dev 11 | sudo apt-get install libxext-dev 12 | sudo apt-get install automake 13 | cp *.c ./gst-plugins-good1.0-$GST_PLUGIN_VERSION/gst/audiofx 14 | cp *.h ./gst-plugins-good1.0-$GST_PLUGIN_VERSION/gst/audiofx 15 | #sudo auto-apt run ./gst-plugins-good1.0-1.4.5/configure 16 | cd ./gst-plugins-good1.0-$GST_PLUGIN_VERSION 17 | ./configure 18 | sudo make && sudo make install 19 | if [ -d "/usr/lib/i386-linux-gnu/gstreamer-1.0/" ]; then 20 | sudo cp /usr/local/lib/gstreamer-1.0/* /usr/lib/i386-linux-gnu/gstreamer-1.0/ 21 | else if [ -d "/usr/lib/arm-linux-gnueabihf/gstreamer-1.0/" ]; then 22 | sudo cp /usr/local/lib/gstreamer-1.0/* /usr/lib/arm-linux-gnueabihf/gstreamer-1.0/ 23 | else 24 | sudo cp /usr/local/lib/gstreamer-1.0/* /usr/lib/x86_64-linux-gnu/gstreamer-1.0/ 25 | 26 | fi 27 | -------------------------------------------------------------------------------- /PORCCfgDlg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gi 3 | from gi.repository import RB 4 | from gi.repository import Gtk 5 | 6 | from DependsWrapper import DependsWrapperImpl 7 | 8 | class PORCCfgDlg(): 9 | 10 | def __init__(self, parent): 11 | self.uibuilder = Gtk.Builder() 12 | self.uibuilder.add_from_file( 13 | DependsWrapperImpl.find_plugin_file(parent, "DRCUI.glade")) 14 | self.dlg = self.uibuilder.get_object("porcCfgDlg") 15 | okBtn = self.uibuilder.get_object("button_OKPORCDlg") 16 | okBtn.connect("clicked", self.on_Ok) 17 | cancelBtn = self.uibuilder.get_object("button_CancelPORCDlg") 18 | cancelBtn.connect("clicked", self.on_Cancel) 19 | 20 | self.checkbuttonMixedPhase = self.uibuilder.get_object( 21 | "checkbuttonMixedPhase") 22 | 23 | def on_Ok(self, param): 24 | self.dlg.response(Gtk.ResponseType.OK) 25 | self.dlg.set_visible(False) 26 | 27 | def on_Cancel(self, param): 28 | self.dlg.response(Gtk.ResponseType.CANCEL) 29 | self.dlg.set_visible(False) 30 | 31 | def getMixedPhaseEnabled(self): 32 | return self.checkbuttonMixedPhase.get_active() 33 | 34 | def run(self): 35 | print("running dlg...") 36 | return self.dlg.run() -------------------------------------------------------------------------------- /brutefir_PI/setup_brutefir: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | #snd-aloop 3 | sudo apt-get install brutefir alsa-utils -y; 4 | echo "runnign sox to create bruteFIR pcm filters" 5 | #sox $WAV_FILTER_FILE -t raw -c 1 ~/filter_l.pcm remix 1 6 | #sox $WAV_FILTER_FILE -t raw -c 1 ~/filter_r.pcm remix 2 7 | #create and update bruteFIR cfg if not existing, install if not existing, enable alsa loopback device etc.... 8 | echo "perform filter update" 9 | grep -q "~" ~/.brutefir_config 10 | if [ $? == 1 ]; then 11 | curr_user=${somebla-`whoami`} 12 | sudo chown $curr_user ~/.brutefir_config 13 | sudo chown $curr_user ~/.brutefir_defaults 14 | #replace local path with absolute path 15 | homeDir=~ 16 | sed -i -- 's_~/_'$homeDir'/_g' .brutefir_config 17 | fi 18 | #TODO upate brutefir cfg with correct audio devices (loopback --> alsa out) 19 | 20 | echo "adding snd-aloop to loaded modules" 21 | #insert snd-aloop into snd-aloop 22 | grep -q "snd-aloop" /etc/modules 23 | if [ $? == 1 ]; then 24 | sudo sh -c "echo \"snd-aloop\" >> /etc/modules" 25 | sudo modprobe snd-aloop 26 | fi 27 | 28 | #start brutefir automatic at startup 29 | grep -q "brutefir" /etc/rc.local 30 | if [ $? == 1 ]; then 31 | sudo sed -i -- 's:exit 0:brutefir '$homeDir'/.brutefir_config\nexit 0:g' /etc/rc.local 32 | echo "reboot to edit .brutefir_config" 33 | 34 | -------------------------------------------------------------------------------- /install.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | SCRIPT_NAME=`basename "$0"` 4 | SCRIPT_PATH=${0%`basename "$0"`} 5 | PLUGIN_PATH="${HOME}/.local/share/rhythmbox/plugins/DRC/" 6 | 7 | function uninstall { 8 | rm -rf "${PLUGIN_PATH}" 9 | echo "plugin uninstalled" 10 | exit 11 | } 12 | 13 | 14 | ################################ USAGE ####################################### 15 | 16 | usage=$( 17 | cat < converting to pcm for PORC with remix param : "$REMIX_PARAM 31 | regex="Sample Rate : ([0-9]{4,7})" 32 | sox $IMPULSE_FILE -t wav -c 1 ${EXTRACT_CHAN_FILE} $REMIX_PARAM 33 | regex="Sample Rate : ([0-9]{4,7})" 34 | SOXI_RESULT="$(soxi $IMPULSE_FILE)" 35 | [[ $SOXI_RESULT =~ $regex ]] 36 | RATE=${BASH_REMATCH[1]} 37 | fi 38 | 39 | if [ -z "$TARGET_CURVE_FILE" ]; then 40 | echo "target curve not set" 41 | else 42 | cp "$TARGET_CURVE_FILE" /tmp/target_curve.txt 43 | PORC_PARAMS="-t /tmp/target_curve.txt "$PORC_PARAMS 44 | fi 45 | 46 | #filter length 65535 : same as DRC 47 | echo "calculating filters" 48 | 49 | PCM_FILTER="/tmp/porc_tmp_filter"$CURR_CHANNEL".pcm" 50 | 51 | echo "executing porc: "$PORC $PORC_PARAMS -n $TAPS -o bin $EXTRACT_CHAN_FILE $PCM_FILTER 52 | python $PORC $PORC_PARAMS -n $TAPS -o bin $EXTRACT_CHAN_FILE $PCM_FILTER 53 | 54 | #convert result to wav 55 | sox -t raw -r $RATE -c 1 -e float -b32 ${PCM_FILTER} -t wav $FILTER_FILE 56 | -------------------------------------------------------------------------------- /updateBruteFIRCfg: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Get command line parameters 4 | ALSA_PLAY_HARDWARE="$1" 5 | RATE="44100" 6 | WAV_FILTER_FILE="$2" 7 | 8 | if [[ $# < 2 ]]; then 9 | echo "disabling brutefir: setting pass-through filters" 10 | # disable bruteFIR filter --> set -1 for all coeffs with telnet cfc command 11 | echo "cfc 0 -1;cfc 1 -1" | nc localhost 3000 12 | # make ALSA_PLAY_HARDWARE the default again 13 | else 14 | #output file parameters with soxi and parse number of channels: create one pcm file per channel 15 | SOXI_RESULT="$(soxi $WAV_FILTER_FILE)" 16 | regex="Channels : ([0-9])" 17 | [[ $SOXI_RESULT =~ $regex ]] 18 | NUM_WAV_CHANNELS=${BASH_REMATCH[1]} 19 | echo "runnign sox to create bruteFIR pcm filters for "$NUM_WAV_CHANNELS" channels" 20 | for ((i=1;i<=NUM_WAV_CHANNELS;i++)); 21 | do 22 | CURRENT_FILE=~/filter_$i.pcm 23 | sox $WAV_FILTER_FILE -t raw -c 1 $CURRENT_FILE remix $i 24 | done 25 | 26 | #create and update bruteFIR cfg if not existing, install if not existing, enable alsa loopback device etc.... 27 | #grep -q "~" ~/.brutefir_config 28 | #if [ $? == 1 ]; then 29 | # curr_user=${somebla-`whoami`} 30 | # cp /usr/share/rhythmbox/plugins/DRC/.brutefir_config ~/ 31 | # cp /usr/share/rhythmbox/plugins/DRC/.brutefir_defaults ~/ 32 | # sudo chown $curr_user ~/.brutefir_config 33 | # sudo chown $curr_user ~/.brutefir_defaults 34 | # #replace local path with absolute path 35 | # homeDir=~ 36 | # sed -i -- 's_~/_'$homeDir'/_g' .brutefir_config 37 | #fi 38 | #TODO upate brutefir cfg with correct audio devices (loopback --> alsa out) 39 | 40 | #insert snd-aloop into snd-aloop 41 | #grep -q "snd-aloop" /etc/modules 42 | #if [ $? == 1 ]; then 43 | # sudo sh -c "echo \"snd-aloop\" >> /etc/modules" 44 | # sudo modprobe snd-aloop 45 | #fi 46 | #grep -q "brutefir" /etc/rc.local 47 | #if [ $? == 1 ]; then 48 | # sudo sed -i -- 's:exit 0:brutefir '$homeDir'/.brutefir_config\nexit 0:g' /etc/rc.local 49 | #sudo apt-get install snd-aloop brutefir 50 | #sudo pkill brutefir 51 | #start brutefir as sudo 52 | #sudo brutefir ~/.brutefir_config & 53 | fi 54 | -------------------------------------------------------------------------------- /.brutefir_config: -------------------------------------------------------------------------------- 1 | ## 2 | ## DEFAULT GENERAL SETTINGS 3 | ## 4 | 5 | float_bits: 32; # internal floating point precision 6 | sampling_rate: 96000; # sampling rate in Hz of audio interfaces 7 | filter_length: 4096; # length of filters 8 | overflow_warnings: true; # echo warnings to stderr if overflow occurs 9 | show_progress: true; # echo filtering progress to stderr 10 | max_dither_table_size: 0; # maximum size in bytes of precalculated dither 11 | allow_poll_mode: false; # allow use of input poll mode 12 | modules_path: "."; # extra path where to find BruteFIR modules 13 | monitor_rate: false; # monitor sample rate 14 | powersave: false; # pause filtering when input is zero 15 | lock_memory: true; # try to lock memory if realtime prio is set 16 | sdf_length: -1; # subsample filter half length in samples 17 | safety_limit: 20; # if non-zero max dB in output before aborting 18 | convolver_config: "~/.brutefir_convolver"; # location of convolver config file 19 | 20 | 21 | ## 22 | ## LOGIC 23 | ## 24 | logic: "cli" { port: 3000; }; 25 | 26 | coeff "DRC_L" { 27 | filename: "/home/tobias/filter_1.pcm"; 28 | format: "FLOAT_LE"; # file format 29 | }; 30 | 31 | coeff "DRC_R" { 32 | filename: "/home/tobias/filter_2.pcm"; 33 | format: "FLOAT_LE"; # file format 34 | }; 35 | 36 | input "left_in", "right_in" { 37 | device: "alsa" { device: "hw:0,1"; ignore_xrun: true; }; 38 | sample: "S32_LE"; 39 | channels: 2/0,1; # number of open channels / which to use 40 | }; 41 | 42 | output "left_out", "right_out" { 43 | device: "alsa" { device: "hw:3,0"; ignore_xrun: true; }; 44 | sample: "S32_LE"; 45 | channels: 2/0,1; # number of open channels / which to use 46 | }; 47 | 48 | filter "left_DRC" { 49 | from_inputs: "left_in"; 50 | to_outputs: "left_out"; 51 | coeff:"DRC_L"; 52 | process: -1; # process index to run in (-1 means auto) 53 | delay: 0; # predelay, in blocks 54 | crossfade: false; # crossfade when coefficient is changed 55 | }; 56 | 57 | filter "right_DRC" { 58 | from_inputs: "right_in"; 59 | to_outputs: "right_out"; 60 | coeff:"DRC_R"; 61 | process: -1; # process index to run in (-1 means auto) 62 | delay: 0; # predelay, in blocks 63 | crossfade: false; # crossfade when coefficient is changed 64 | }; 65 | -------------------------------------------------------------------------------- /gst-plugins-good-patch/audiofirfilter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * GStreamer 3 | * Copyright (C) 2009 Sebastian Dröge 4 | * 5 | * This library is free software; you can redistribute it and/or 6 | * modify it under the terms of the GNU Library General Public 7 | * License as published by the Free Software Foundation; either 8 | * version 2 of the License, or (at your option) any later version. 9 | * 10 | * This library is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * Library General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Library General Public 16 | * License along with this library; if not, write to the 17 | * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 18 | * Boston, MA 02110-1301, USA. 19 | * 20 | */ 21 | 22 | #ifndef __GST_AUDIO_FIR_FILTER_H__ 23 | #define __GST_AUDIO_FIR_FILTER_H__ 24 | 25 | #include 26 | #include 27 | 28 | #include "audiofxbasefirfilter.h" 29 | 30 | G_BEGIN_DECLS 31 | 32 | #define GST_TYPE_AUDIO_FIR_FILTER \ 33 | (gst_audio_fir_filter_get_type()) 34 | #define GST_AUDIO_FIR_FILTER(obj) \ 35 | (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_FIR_FILTER,GstAudioFIRFilter)) 36 | #define GST_AUDIO_FIR_FILTER_CLASS(klass) \ 37 | (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIO_FIR_FILTER,GstAudioFIRFilterClass)) 38 | #define GST_IS_AUDIO_FIR_FILTER(obj) \ 39 | (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_FIR_FILTER)) 40 | #define GST_IS_AUDIO_FIR_FILTER_CLASS(klass) \ 41 | (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIO_FIR_FILTER)) 42 | 43 | typedef struct _GstAudioFIRFilter GstAudioFIRFilter; 44 | typedef struct _GstAudioFIRFilterClass GstAudioFIRFilterClass; 45 | 46 | /** 47 | * GstAudioFIRFilter: 48 | * 49 | * Opaque data structure. 50 | */ 51 | struct _GstAudioFIRFilter { 52 | GstAudioFXBaseFIRFilter parent; 53 | 54 | GValueArray *kernel; 55 | guint64 num_filt_channels; 56 | guint64 latency; 57 | 58 | /* < private > */ 59 | GMutex lock; 60 | }; 61 | 62 | struct _GstAudioFIRFilterClass { 63 | GstAudioFXBaseFIRFilterClass parent; 64 | 65 | void (*rate_changed) (GstElement * element, gint rate); 66 | }; 67 | 68 | GType gst_audio_fir_filter_get_type (void); 69 | 70 | G_END_DECLS 71 | 72 | #endif /* __GST_AUDIO_FIR_FILTER_H__ */ 73 | -------------------------------------------------------------------------------- /DRCConfig.py: -------------------------------------------------------------------------------- 1 | # config.py 2 | # Copyright (C) 2013 - Tobias Wenig 3 | # tobiaswenig@yahoo.com> 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see 17 | 18 | import os 19 | 20 | import gi 21 | from gi.repository import RB 22 | 23 | from XMLSerializer import Serializer 24 | 25 | DRC_CFG_FILE = "DRC.xml" 26 | 27 | 28 | class DRCConfig: 29 | def __init__(self): 30 | configDir = RB.user_cache_dir() + "/DRC" 31 | if not os.path.exists(configDir): 32 | os.makedirs(configDir) 33 | self.cfgFileName = configDir + "/" + DRC_CFG_FILE 34 | self.filterFile = "" 35 | self.recordGain = 0.5 36 | self.sweepDuration = 40 37 | self.numFilterChanels = 1 38 | self.FIRFilterMode = 0 39 | self.playHardwareIndex = 0 40 | self.recHardwareIndex = 0 41 | self.recHardwareChannelIndex = 0 42 | self.MicCalibrationFile = "" 43 | #0 - None 44 | #1 - GStreamerFIR 45 | #2 - BruteFIR 46 | self.load() 47 | 48 | def load(self): 49 | try: 50 | cfgFile = open(self.cfgFileName, 'r') 51 | cfg = Serializer.read(cfgFile, self) 52 | self.filterFile = cfg.filterFile 53 | self.sweepDuration = cfg.sweepDuration 54 | self.numFilterChanels = cfg.numFilterChanels 55 | self.FIRFilterMode = cfg.FIRFilterMode 56 | self.playHardwareIndex = cfg.playHardwareIndex 57 | self.recHardwareIndex = cfg.recHardwareIndex 58 | self.recHardwareChannelIndex = cfg.recHardwareChannelIndex 59 | self.MicCalibrationFile = cfg.MicCalibrationFile 60 | except: 61 | print("no cfg existing -> create default") 62 | self.save() 63 | pass 64 | 65 | def save(self): 66 | print("saving cfg to : " + self.cfgFileName) 67 | Serializer.write(self.cfgFileName, self) 68 | -------------------------------------------------------------------------------- /DRCCfgDlg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import gi 3 | from gi.repository import RB 4 | from gi.repository import Gtk 5 | 6 | from DependsWrapper import DependsWrapperImpl 7 | 8 | import os 9 | from DRCConfig import DRCConfig 10 | 11 | class DRCCfgDlg(): 12 | 13 | def applyConfig(self): 14 | aCfg = DRCConfig() 15 | if os.path.exists(aCfg.MicCalibrationFile): 16 | self.filechooserbuttonMicCalFile.set_filename( 17 | aCfg.MicCalibrationFile) 18 | else: 19 | self.filechooserbuttonMicCalFile.set_current_folder( 20 | "/usr/share/drc/mic") 21 | 22 | def __init__(self, parent): 23 | self.uibuilder = Gtk.Builder() 24 | self.uibuilder.add_from_file( 25 | DependsWrapperImpl.find_plugin_file(parent, "DRCUI.glade")) 26 | self.dlg = self.uibuilder.get_object("drcCfgDlg") 27 | okBtn = self.uibuilder.get_object("button_OKDRCDlg") 28 | okBtn.connect("clicked", self.on_Ok) 29 | cancelBtn = self.uibuilder.get_object("button_CancelDRCDlg") 30 | cancelBtn.connect("clicked", self.on_Cancel) 31 | self.filechooserbuttonMicCalFile = self.uibuilder.get_object( 32 | "filechooserbuttonMicCalFile") 33 | self.uibuilder.get_object( 34 | "resetBtn").connect("clicked", self.on_ResetToDefaults) 35 | self.applyConfig() 36 | self.comboboxtext_norm_method = self.uibuilder.get_object( 37 | "comboboxtext_norm_method") 38 | self.filechooserbuttonBaseCfg = self.uibuilder.get_object( 39 | "filechooserbuttonBaseCfg") 40 | self.filechooserbuttonBaseCfg.set_current_folder( 41 | "/usr/share/drc/config/44.1 kHz") 42 | self.filechooserbuttonBaseCfg.set_filename( 43 | "/usr/share/drc/config/44.1 kHz/erb-44.1.drc") 44 | 45 | def on_ResetToDefaults(self, param): 46 | self.filechooserbuttonMicCalFile.unselect_all() 47 | self.filechooserbuttonMicCalFile.set_current_folder( 48 | "/usr/share/drc/mic") 49 | 50 | def on_Ok(self, param): 51 | self.dlg.response(Gtk.ResponseType.OK) 52 | aCfg = DRCConfig() 53 | aCfg.MicCalibrationFile = self.filechooserbuttonMicCalFile.\ 54 | get_filename() 55 | aCfg.save() 56 | self.dlg.set_visible(False) 57 | 58 | def on_Cancel(self, param): 59 | self.dlg.response(Gtk.ResponseType.CANCEL) 60 | self.applyConfig() 61 | self.dlg.set_visible(False) 62 | 63 | def getMicCalibrationFile(self): 64 | return self.filechooserbuttonMicCalFile.get_filename() 65 | 66 | def getNormMethod(self): 67 | return self.comboboxtext_norm_method.get_active_text() 68 | 69 | def getBaseCfg(self): 70 | return self.filechooserbuttonBaseCfg.get_filename() 71 | 72 | def run(self): 73 | print("running dlg...") 74 | return self.dlg.run() -------------------------------------------------------------------------------- /TargetCurveDlg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # -*- coding: utf-8 -*- 3 | import gi 4 | from gi.repository import RB 5 | from gi.repository import Gtk 6 | 7 | from DependsWrapper import DependsWrapperImpl 8 | 9 | from DRCTargetCurveUI import EQControl 10 | import DRCFileTool 11 | 12 | class TargetCurveLine(): 13 | 14 | def __init__(self, grid, filename, channelNumber, noOfControls): 15 | super(TargetCurveLine, self).__init__() 16 | self.fileChooser = Gtk.FileChooserButton() 17 | audioFileFilter = Gtk.FileFilter() 18 | audioFileFilter.add_pattern("*.txt") 19 | self.fileChooser.set_filter(audioFileFilter) 20 | self.fileChooser.set_current_folder( 21 | "/usr/share/drc/target/44.1 kHz") 22 | if filename is not None: 23 | self.fileChooser.set_filename(filename) 24 | self.channelLabel = Gtk.Label() 25 | self.channelLabel.set_text(str(channelNumber)) 26 | grid.add(self.channelLabel) 27 | grid.attach_next_to(self.fileChooser, self.channelLabel, 28 | Gtk.PositionType.RIGHT, 2, 1) 29 | grid.show_all() 30 | self.rowNumber = channelNumber + 1 31 | grid.insert_row(self.rowNumber) 32 | 33 | def remove(self, grid): 34 | grid.remove(self.channelLabel) 35 | self.channelLabel = None 36 | grid.remove(self.fileChooser) 37 | self.fileChooser = None 38 | grid.remove_row(self.rowNumber) 39 | 40 | def getTargetCurveFileName(self): 41 | return self.fileChooser.get_filename() 42 | 43 | 44 | class TargetCurveDlg(): 45 | 46 | def __init__(self, parent): 47 | self.uibuilder = Gtk.Builder() 48 | self.uibuilder.add_from_file( 49 | DependsWrapperImpl.find_plugin_file(parent, "DRCUI.glade")) 50 | self.dlg = self.uibuilder.get_object("TargetCurveSelDlg") 51 | self.uibuilder.get_object("button_OKTargetCurve").connect( 52 | "clicked", self.on_Ok) 53 | self.elementGrid = self.uibuilder.get_object("elementGridTargetCurve") 54 | self.parent = parent 55 | self.uibuilder.get_object("buttonEditTargetCurve").connect("clicked", 56 | self.on_editTargetCurve) 57 | self.impRespFile = None 58 | self.defaultTargetCurveFile = "/usr/share/drc/target/44.1 kHz/flat-44.1.txt" 59 | self.channelControls = [] 60 | 61 | def setImpRespFile(self, impRespFile): 62 | #build target curve list form number of channels in 63 | #the impRespFile 64 | self.removeAll() 65 | numChannels = DRCFileTool.getNumChannels(impRespFile) 66 | 67 | for currChannel in range(0, numChannels): 68 | newChannelControls = TargetCurveLine(self.elementGrid, 69 | self.defaultTargetCurveFile, currChannel, numChannels) 70 | self.channelControls.append(newChannelControls) 71 | 72 | def removeAll(self): 73 | for control in self.channelControls: 74 | control.remove(self.elementGrid) 75 | self.channelControls = [] 76 | 77 | def getTargetCurveFileName(self, currChannel): 78 | targetCurveFileName = self.defaultTargetCurveFile 79 | if(len(self.channelControls) > currChannel): 80 | targetCurveFileName = self.channelControls[currChannel].\ 81 | getTargetCurveFileName() 82 | return targetCurveFileName 83 | 84 | def on_Ok(self, param): 85 | self.dlg.response(Gtk.ResponseType.OK) 86 | self.dlg.set_visible(False) 87 | 88 | def run(self): 89 | return self.dlg.run() 90 | 91 | def on_editTargetCurve(self, widget): 92 | #TODO take the selected channel 93 | editDlg = EQControl(self.getTargetCurveFileName(0), 94 | self.parent) 95 | editDlg.run() -------------------------------------------------------------------------------- /.brutefir_config51: -------------------------------------------------------------------------------- 1 | ## 2 | ## DEFAULT GENERAL SETTINGS 3 | ## 4 | 5 | float_bits: 32; # internal floating point precision 6 | sampling_rate: 48000; # sampling rate in Hz of audio interfaces 7 | filter_length: 4096; # length of filters 8 | overflow_warnings: true; # echo warnings to stderr if overflow occurs 9 | show_progress: true; # echo filtering progress to stderr 10 | max_dither_table_size: 0; # maximum size in bytes of precalculated dither 11 | allow_poll_mode: false; # allow use of input poll mode 12 | modules_path: "."; # extra path where to find BruteFIR modules 13 | monitor_rate: false; # monitor sample rate 14 | powersave: false; # pause filtering when input is zero 15 | lock_memory: true; # try to lock memory if realtime prio is set 16 | sdf_length: -1; # subsample filter half length in samples 17 | safety_limit: 20; # if non-zero max dB in output before aborting 18 | convolver_config: "/home/micha/.brutefir_convolver"; # location of convolver config file 19 | 20 | ## 21 | ## LOGIC 22 | ## 23 | logic: "cli" { port: 3000; }; 24 | 25 | coeff "DRC_L" { 26 | filename: "/home/micha/filter_1.pcm"; 27 | format: "FLOAT_LE"; # file format 28 | }; 29 | coeff "DRC_R" { 30 | filename: "/home/micha/filter_2.pcm"; 31 | format: "FLOAT_LE"; # file format 32 | }; 33 | 34 | coeff "DRC_C" { 35 | filename: "/home/micha/filter_3.pcm"; 36 | format: "FLOAT_LE"; # file format 37 | }; 38 | 39 | coeff "DRC_RS" { 40 | filename: "/home/micha/filter_6.pcm"; 41 | format: "FLOAT_LE"; # file format 42 | }; 43 | 44 | coeff "DRC_LS" { 45 | filename: "/home/micha/filter_5.pcm"; 46 | format: "FLOAT_LE"; # file format 47 | }; 48 | 49 | coeff "DRC_LFE" { 50 | filename: "/home/micha/filter_4.pcm"; 51 | format: "FLOAT_LE"; # file format 52 | }; 53 | 54 | 55 | input "left_in", "right_in", "center_in", "right_surround_in", "left_surround_in", "LFE_in" { 56 | device: "alsa" { device: "hw:0,1"; ignore_xrun: true; }; 57 | sample: "S16_LE"; 58 | channels: 6/0,1,2,3,4,5; # number of open channels / which to use 59 | delay: 0,0; # delay in samples for each channel 60 | maxdelay: -1; # max delay for variable delays 61 | mute: false, false; # mute active on startup for each channel 62 | }; 63 | 64 | output "left_out", "right_out", "center_out", "right_surround_out", "left_surround_out", "LFE_out" { 65 | device: "alsa" { device: "hw:2,0"; ignore_xrun: true; }; 66 | sample: "S16_LE"; 67 | channels: 8/0,1,2,3,4,5; # number of open channels / which to use 68 | delay: 0,0; # delay in samples for each channel 69 | maxdelay: -1; # max delay for variable delays 70 | mute: false, false; # mute active on startup for each channel 71 | }; 72 | 73 | filter "left_DRC" { 74 | from_inputs: "left_in"; 75 | to_outputs: "left_out"; 76 | coeff:"DRC_L"; 77 | process: -1; 78 | crossfade: false; 79 | }; 80 | 81 | filter "right_DRC" { 82 | from_inputs: "right_in"; 83 | to_outputs: "right_out"; 84 | coeff:"DRC_R"; 85 | process: -1; 86 | crossfade: false; 87 | }; 88 | 89 | filter "center_DRC" { 90 | from_inputs: "center_in"; 91 | to_outputs: "center_out"; 92 | coeff:"DRC_C"; 93 | process: -1; 94 | crossfade: false; 95 | }; 96 | 97 | filter "right_surround_DRC" { 98 | from_inputs: "right_surround_in"; 99 | to_outputs: "right_surround_out"; 100 | coeff:"DRC_RS"; 101 | process: -1; 102 | crossfade: false; 103 | }; 104 | 105 | filter "left_surround_DRC" { 106 | from_inputs: "left_surround_in"; 107 | to_outputs: "left_surround_out"; 108 | coeff:"DRC_LS"; 109 | process: -1; 110 | crossfade: false; 111 | }; 112 | 113 | filter "LFE_DRC" { 114 | from_inputs: "LFE_in"; 115 | to_outputs: "LFE_out"; 116 | coeff:-1;#"DRC_LFE"; 117 | process: -1; 118 | crossfade: false; 119 | }; 120 | 121 | -------------------------------------------------------------------------------- /MeasureQADlg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import os 3 | import subprocess 4 | from enum import Enum 5 | 6 | import DRCFileTool 7 | 8 | import gi 9 | from gi.repository import RB 10 | from gi.repository import Gtk 11 | 12 | from DependsWrapper import DependsWrapperImpl 13 | 14 | class MeasureQARetVal(Enum): 15 | Done = 0 16 | Reject = 1 17 | Proceed = 2 18 | 19 | 20 | class MeasureQADlg(): 21 | 22 | def __init__(self, parent, genSweepFile, measSweepFile, 23 | sweep_level): 24 | self.uibuilder = Gtk.Builder() 25 | self.uibuilder.add_from_file( 26 | DependsWrapperImpl.find_plugin_file(parent, "DRCUI.glade")) 27 | self.dlg = self.uibuilder.get_object("measureQualityDlg") 28 | self.uibuilder.get_object("button_doneMeasQA").connect( 29 | "clicked", self.on_button_doneMeasQA) 30 | self.uibuilder.get_object("button_rejectMeasQA").connect( 31 | "clicked", self.on_button_rejectMeasQA) 32 | self.uibuilder.get_object("button_ProceedMeasQA").connect( 33 | "clicked", self.on_button_ProceedMeasQA) 34 | btnViewAudacity = self.uibuilder.get_object("buttonViewRecSweep") 35 | btnViewAudacity.connect("clicked", self.on_viewRecSweep) 36 | self.genSweepFile = genSweepFile 37 | self.measSweepFile = measSweepFile 38 | 39 | def evalData(self): 40 | audioParams = DRCFileTool.LoadAudioFile(self.genSweepFile, 1) 41 | self.setEvalData(audioParams, "labelInputSweepData") 42 | audioParams = DRCFileTool.LoadAudioFile(self.measSweepFile, 1) 43 | minMaxRec = self.setEvalData(audioParams, 44 | "labelRecordedSweepData") 45 | audioParams = DRCFileTool.LoadAudioFile(self.impRespFile, 1) 46 | self.setEvalData(audioParams, "labelImpResponseData") 47 | # TODO: add evaluation 48 | label = self.uibuilder.get_object("labelRecomendationResult") 49 | result = "check values : recorded results seem to be fine to proceed" 50 | if (minMaxRec[1] - minMaxRec[0]) < 0.1: 51 | result = "check values : recorded volume seems to be quite low: " \ 52 | "check proper input device or adjust gain" 53 | label.set_text(result) 54 | 55 | def on_viewRecSweep(self, param): 56 | scriptName = "audacity" 57 | measSweepWaveFile = os.path.splitext(self.measSweepFile)[0] + ".wav" 58 | commandLine = [scriptName, measSweepWaveFile] 59 | subprocess.Popen(commandLine) 60 | 61 | def setEvalData(self, dataInfo, labelID): 62 | label = self.uibuilder.get_object(labelID) 63 | text = "Min/Pos: " + str(dataInfo.minSampleValue) + "/" + \ 64 | str(dataInfo.minSampleValuePos) + \ 65 | " Max/Pos: " + str(dataInfo.maxSampleValue) + "/" + \ 66 | str(dataInfo.maxSampleValuePos) 67 | label.set_text(text) 68 | return [dataInfo.minSampleValue[0], dataInfo.maxSampleValue[0]] 69 | 70 | def setImpRespFileName(self, impRespFile): 71 | self.impRespFile = impRespFile 72 | self.uibuilder.get_object("entryImpRespFileName").set_text( 73 | self.impRespFile) 74 | 75 | def on_button_doneMeasQA(self, param): 76 | self.Result = MeasureQARetVal.Done 77 | self.dlg.response(Gtk.ResponseType.OK) 78 | self.dlg.set_visible(False) 79 | 80 | def on_button_rejectMeasQA(self, param): 81 | self.Result = MeasureQARetVal.Reject 82 | os.remove(self.impRespFile) 83 | self.dlg.response(Gtk.ResponseType.OK) 84 | self.dlg.set_visible(False) 85 | 86 | def on_button_ProceedMeasQA(self, param): 87 | self.Result = MeasureQARetVal.Proceed 88 | self.dlg.response(Gtk.ResponseType.OK) 89 | self.dlg.set_visible(False) 90 | 91 | def run(self): 92 | print("running dlg...") 93 | self.evalData() 94 | retVal = self.dlg.run() 95 | impRespFileName = self.uibuilder.get_object( 96 | "entryImpRespFileName").get_text() 97 | #TODO file hanlding specific on return code 98 | if impRespFileName != self.impRespFile: 99 | os.rename(self.impRespFile, impRespFileName) 100 | self.impRespFile = impRespFileName 101 | print(("returning : " + str(retVal) + "result: ", self.Result)) 102 | return retVal -------------------------------------------------------------------------------- /XMLSerializer.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import lxml.etree as ET 3 | 4 | 5 | class Serializer(object): 6 | def __init__(self): 7 | return None 8 | 9 | @staticmethod 10 | def getSerializeMembers(SerializeObject): 11 | strSerializeMembers = [] 12 | for member in dir(SerializeObject): 13 | strMember = str(member) 14 | strType = str(type(getattr(SerializeObject, strMember))) 15 | print(strMember + " : " + strType) 16 | if (strType.find("descriptor") == -1) and ( 17 | strType.find("function") == -1) and ( 18 | strType.find("method") == -1) and ( 19 | strMember.find("__") != 0): 20 | strSerializeMembers.append(strMember) 21 | # print( "Serialize considered members : " + str(strSerializeMembers) ) 22 | return strSerializeMembers 23 | 24 | @staticmethod 25 | def SerializeArray(XMLParent, arrayInst): 26 | for arrayIndex, arrayItem in enumerate(arrayInst): 27 | Serializer.SerializeMember(XMLParent, "elem" + str(arrayIndex), 28 | arrayItem) 29 | 30 | @staticmethod 31 | def SerializeMember(XMLParent, MemberName, newValue): 32 | strType = str(type(newValue)) 33 | # print( "serialize type : " + strType ) 34 | if strType.find("instance") != -1: 35 | XMLParent = ET.SubElement(XMLParent, MemberName) 36 | Serializer.SerializeClass(newValue, XMLParent) 37 | elif strType.find("list") != -1: 38 | newElem = ET.SubElement(XMLParent, MemberName) 39 | Serializer.SerializeArray(newElem, newValue) 40 | else: 41 | newElem = ET.SubElement(XMLParent, MemberName) 42 | newElem.text = str(newValue) 43 | 44 | @staticmethod 45 | def SerializeClass(SerializeObject, rootElem=None): 46 | strSerMemberNames = Serializer.getSerializeMembers(SerializeObject) 47 | for strElem in strSerMemberNames: 48 | Serializer.SerializeMember(rootElem, strElem, 49 | getattr(SerializeObject, strElem)) 50 | 51 | @staticmethod 52 | def Serialize(SerializeObject): 53 | strClassName = SerializeObject.__class__.__name__ 54 | rootElem = ET.Element(strClassName) 55 | Serializer.SerializeClass(SerializeObject, rootElem) 56 | return ET.tostring(rootElem) 57 | 58 | @staticmethod 59 | def read(fileName, SerializeObject): 60 | root = ET.parse(fileName) 61 | return Serializer.DeserializeClass(SerializeObject, root.getroot()) 62 | 63 | @staticmethod 64 | def write(fileName, SerializeObject): 65 | strClassName = SerializeObject.__class__.__name__ 66 | rootElem = ET.Element(strClassName) 67 | Serializer.SerializeClass(SerializeObject, rootElem) 68 | ET.ElementTree(rootElem).write(fileName) 69 | 70 | @staticmethod 71 | def DeserializeArray(XMLParent, value): 72 | # array needs to have at least one value for correct type 73 | # information, else values are read and treated as string 74 | arrayInst = [] 75 | for arrayIndex, arrayNode in enumerate(XMLParent): 76 | arrayInst.append(Serializer.DeserializeMember(arrayNode, value[0])) 77 | return arrayInst 78 | 79 | @staticmethod 80 | def DeserializeMember(XMLElem, value): 81 | theType = type(value) 82 | strType = str(theType) 83 | print("Deserializing : " + strType) 84 | if strType.find("instance") != -1: 85 | return Serializer.DeserializeClass(value, XMLElem) 86 | elif strType.find("list") != -1: 87 | return Serializer.DeserializeArray(XMLElem, value) 88 | else: 89 | return theType(XMLElem.text) 90 | 91 | @staticmethod 92 | def DeserializeClass(SerializeObject, rootElem): 93 | strSerMemberNames = Serializer.getSerializeMembers(SerializeObject) 94 | for strElem, xmlChildElem in zip(strSerMemberNames, rootElem): 95 | setattr(SerializeObject, strElem, 96 | Serializer.DeserializeMember(xmlChildElem, 97 | getattr(SerializeObject, 98 | strElem))) 99 | return SerializeObject 100 | 101 | @staticmethod 102 | def DeSerialize(strXmlString, SerializeObject): 103 | root = ET.fromstring(strXmlString) 104 | return Serializer.DeserializeClass(SerializeObject, root) 105 | -------------------------------------------------------------------------------- /gst-plugins-good-patch/audiofxbasefirfilter.h: -------------------------------------------------------------------------------- 1 | /* -*- c-basic-offset: 2 -*- 2 | * 3 | * GStreamer 4 | * Copyright (C) 1999-2001 Erik Walthinsen 5 | * 2006 Dreamlab Technologies Ltd. 6 | * 2009 Sebastian Dröge 7 | * 8 | * This library is free software; you can redistribute it and/or 9 | * modify it under the terms of the GNU Library General Public 10 | * License as published by the Free Software Foundation; either 11 | * version 2 of the License, or (at your option) any later version. 12 | * 13 | * This library is distributed in the hope that it will be useful, 14 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 16 | * Library General Public License for more details. 17 | * 18 | * You should have received a copy of the GNU Library General Public 19 | * License along with this library; if not, write to the 20 | * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 21 | * Boston, MA 02110-1301, USA. 22 | * 23 | */ 24 | 25 | #ifndef __GST_AUDIO_FX_BASE_FIR_FILTER_H__ 26 | #define __GST_AUDIO_FX_BASE_FIR_FILTER_H__ 27 | 28 | #include 29 | #include 30 | #include 31 | 32 | G_BEGIN_DECLS 33 | 34 | #define GST_TYPE_AUDIO_FX_BASE_FIR_FILTER \ 35 | (gst_audio_fx_base_fir_filter_get_type()) 36 | #define GST_AUDIO_FX_BASE_FIR_FILTER(obj) \ 37 | (G_TYPE_CHECK_INSTANCE_CAST((obj),GST_TYPE_AUDIO_FX_BASE_FIR_FILTER,GstAudioFXBaseFIRFilter)) 38 | #define GST_AUDIO_FX_BASE_FIR_FILTER_CLASS(klass) \ 39 | (G_TYPE_CHECK_CLASS_CAST((klass),GST_TYPE_AUDIO_FX_BASE_FIR_FILTER,GstAudioFXBaseFIRFilterClass)) 40 | #define GST_IS_AUDIO_FX_BASE_FIR_FILTER(obj) \ 41 | (G_TYPE_CHECK_INSTANCE_TYPE((obj),GST_TYPE_AUDIO_FX_BASE_FIR_FILTER)) 42 | #define GST_IS_AUDIO_FX_BASE_FIR_FILTER_CLASS(klass) \ 43 | (G_TYPE_CHECK_CLASS_TYPE((klass),GST_TYPE_AUDIO_FX_BASE_FIR_FILTER)) 44 | 45 | typedef struct _GstAudioFXBaseFIRFilter GstAudioFXBaseFIRFilter; 46 | typedef struct _GstAudioFXBaseFIRFilterClass GstAudioFXBaseFIRFilterClass; 47 | 48 | typedef guint (*GstAudioFXBaseFIRFilterProcessFunc) (GstAudioFXBaseFIRFilter *, const guint8 *, guint8 *, guint); 49 | 50 | /** 51 | * GstAudioFXBaseFIRFilter: 52 | * 53 | * Opaque data structure. 54 | */ 55 | struct _GstAudioFXBaseFIRFilter { 56 | GstAudioFilter element; 57 | 58 | /* properties */ 59 | gdouble *kernel; /* filter kernel -- time domain */ 60 | guint kernel_length; /* length of the filter kernel -- time domain */ 61 | 62 | guint64 latency; /* pre-latency of the filter kernel */ 63 | gboolean low_latency; /* work in slower low latency mode */ 64 | 65 | gboolean drain_on_changes; /* If the filter should be drained when 66 | * coeficients change */ 67 | 68 | /* < private > */ 69 | GstAudioFXBaseFIRFilterProcessFunc process; 70 | 71 | gdouble *buffer; /* buffer for storing samples of previous buffers */ 72 | guint buffer_fill; /* fill level of buffer */ 73 | guint buffer_length; /* length of the buffer -- meaning depends on processing mode */ 74 | 75 | /* FFT convolution specific data */ 76 | GstFFTF64 *fft; 77 | GstFFTF64 *ifft; 78 | GstFFTF64Complex *frequency_response; /* filter kernel -- frequency domain */ 79 | guint frequency_response_length; /* length of filter kernel -- frequency domain */ 80 | GstFFTF64Complex *fft_buffer; /* FFT buffer, has the length of the frequency response */ 81 | guint block_length; /* Length of the processing blocks -- time domain */ 82 | 83 | GstClockTime start_ts; /* start timestamp after a discont */ 84 | guint64 start_off; /* start offset after a discont */ 85 | guint64 nsamples_out; /* number of output samples since last discont */ 86 | guint64 nsamples_in; /* number of input samples since last discont */ 87 | gint channels; 88 | guint kernel_channels; /* number of channels within the kernel*/ 89 | GMutex lock; 90 | }; 91 | 92 | struct _GstAudioFXBaseFIRFilterClass { 93 | GstAudioFilterClass parent_class; 94 | }; 95 | 96 | GType gst_audio_fx_base_fir_filter_get_type (void); 97 | void gst_audio_fx_base_fir_filter_set_kernel (GstAudioFXBaseFIRFilter *filter, gdouble *kernel, 98 | guint kernel_length, guint64 latency, const GstAudioInfo * info); 99 | void gst_audio_fx_base_fir_filter_set_multi_kernel (GstAudioFXBaseFIRFilter *filter, gdouble *kernel, 100 | guint kernel_length, guint64 latency, const GstAudioInfo * info, guint kernel_channels); 101 | 102 | void gst_audio_fx_base_fir_filter_push_residue (GstAudioFXBaseFIRFilter *filter); 103 | 104 | G_END_DECLS 105 | 106 | #endif /* __GST_AUDIO_FX_BASE_FIR_FILTER_H__ */ 107 | -------------------------------------------------------------------------------- /ImpRespDlg.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # -*- coding: utf-8 -*- 3 | import gi 4 | from gi.repository import RB 5 | from gi.repository import Gtk 6 | 7 | from DependsWrapper import DependsWrapperImpl 8 | 9 | import os 10 | 11 | class ImpResLine(): 12 | 13 | def __init__(self, grid, measureResultsDir, filename, noOfControls): 14 | super(ImpResLine, self).__init__() 15 | self.fileChooser = Gtk.FileChooserButton() 16 | self.fileChooser.set_current_folder( 17 | measureResultsDir) 18 | audioFileFilter = Gtk.FileFilter() 19 | audioFileFilter.add_pattern("*.wav") 20 | audioFileFilter.add_pattern("*.pcm") 21 | audioFileFilter.add_pattern("*.raw") 22 | self.fileChooser.set_filter(audioFileFilter) 23 | if filename is not None: 24 | self.fileChooser.set_filename(filename) 25 | grid.add(self.fileChooser) 26 | self.weightEntry = Gtk.Entry() 27 | grid.attach_next_to(self.weightEntry, self.fileChooser, 28 | Gtk.PositionType.RIGHT, 2, 1) 29 | self.distanceEntry = Gtk.Entry() 30 | grid.attach_next_to(self.distanceEntry, self.weightEntry, 31 | Gtk.PositionType.RIGHT, 2, 1) 32 | grid.show_all() 33 | self.rowPosition = noOfControls 34 | grid.insert_row(self.rowPosition) 35 | 36 | def remove(self, grid): 37 | grid.remove(self.fileChooser) 38 | self.fileChooser = None 39 | grid.remove(self.weightEntry) 40 | self.weightEntry = None 41 | grid.remove(self.distanceEntry) 42 | self.distanceEntry = None 43 | grid.remove_row(self.rowPosition) 44 | 45 | class ImpRespFileInfo(): 46 | 47 | def __init__(self): 48 | super(ImpRespFileInfo, self).__init__() 49 | self.fileName = "" 50 | self.centerDistanceInCentimeter = 0.0 51 | self.weightingFactor = 0.0 52 | 53 | 54 | class ImpRespDlg(): 55 | 56 | def __init__(self, drcDlg, resultsDir): 57 | self.uibuilder = Gtk.Builder() 58 | self.resultsDir = resultsDir 59 | self.uibuilder.add_from_file( 60 | DependsWrapperImpl.find_plugin_file(drcDlg.parent, "DRCUI.glade")) 61 | self.dlg = self.uibuilder.get_object("impRespSelDlg") 62 | self.uibuilder.get_object("button_OKImpRespSelDlg").connect( 63 | "clicked", self.on_Ok) 64 | self.uibuilder.get_object("openFiles").connect( 65 | "clicked", self.on_AddFiles) 66 | self.uibuilder.get_object("buttonRemoveFile").connect( 67 | "clicked", self.on_RemoveFile) 68 | self.elementGrid = self.uibuilder.get_object("elementGrid") 69 | self.drcDlg = drcDlg 70 | self.mesureResultsDir = self.drcDlg.getMeasureResultsDir() 71 | self.fileControlList = [] 72 | 73 | def loadAllImpRespFromFolder(self, directory): 74 | allFiles = os.listdir(directory) 75 | wavFiles = [] 76 | for filename in allFiles: 77 | if filename.endswith(".wav"): 78 | wavFiles.append(filename) 79 | self.setFiles(wavFiles) 80 | 81 | def on_RemoveFile(self, button): 82 | self.fileControlList[-1].remove(self.elementGrid) 83 | del self.fileControlList[-1] 84 | 85 | def on_AddFiles(self, fileChooserBtn): 86 | impRespFilesDlg = Gtk.FileChooserDialog("Please choose a file", 87 | self.dlg, Gtk.FileChooserAction.OPEN, 88 | (Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, 89 | Gtk.STOCK_OPEN, Gtk.ResponseType.OK)) 90 | impRespFilesDlg.set_current_folder(self.mesureResultsDir) 91 | impRespFilesDlg.set_select_multiple(True) 92 | impRespFilesDlg.run() 93 | allFiles = impRespFilesDlg.get_filenames() 94 | self.setFiles(allFiles) 95 | impRespFilesDlg.destroy() 96 | 97 | def removeAll(self): 98 | for control in self.fileControlList: 99 | control.remove(self.elementGrid) 100 | self.fileControlList = [] 101 | 102 | def setFiles(self, fileList): 103 | numFiles = len(fileList) 104 | self.fileControlList = [] 105 | for impRespFile in fileList: 106 | impRespL = ImpResLine( 107 | self.elementGrid, self.mesureResultsDir, 108 | impRespFile, numFiles) 109 | self.fileControlList.append(impRespL) 110 | impRespL.weightEntry.set_text(str(1.0 / float(numFiles))) 111 | impRespL.distanceEntry.set_text(str(float(0.0))) 112 | 113 | def on_Ok(self, param): 114 | self.dlg.response(Gtk.ResponseType.OK) 115 | self.dlg.set_visible(False) 116 | 117 | def getImpRespFiles(self): 118 | impRespFiles = [] 119 | for fileControl in self.fileControlList: 120 | impRespInfo = ImpRespFileInfo() 121 | impRespInfo.fileName = fileControl.fileChooser.get_filename() 122 | impRespInfo.weightingFactor = float( 123 | fileControl.weightEntry.get_text()) 124 | impRespInfo.centerDistanceInCentimeter = float( 125 | fileControl.distanceEntry.get_text()) 126 | impRespFiles.append(impRespInfo) 127 | print(("impRespInfo:", impRespInfo.fileName, 128 | impRespInfo.weightingFactor, 129 | impRespInfo.centerDistanceInCentimeter)) 130 | return impRespFiles 131 | 132 | def run(self): 133 | print("running dlg...") 134 | return self.dlg.run() -------------------------------------------------------------------------------- /measure: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Automatic measuring script 4 | # Copyright (C) 2002-2005 Denis Sbragion 5 | 6 | # This program may be freely redistributed under the terms of 7 | # the GNU GPL and is provided to you as is, without any warranty 8 | # of any kind. Please read the file "COPYING" for details. 9 | 10 | # Useful programs 11 | ECHO="echo" 12 | RM="rm" 13 | GLSWEEP="glsweep" 14 | SOX="sox" 15 | LSCONV="lsconv" 16 | ARECORD="arecord" 17 | SYNC="sync" 18 | SLEEP="sleep" 19 | #TEST_MODE=true 20 | 21 | # Default parameters 22 | TMP="/tmp" 23 | LEADIN="0.05" 24 | LEADOUT="0.005" 25 | MINGAIN="0.1" 26 | DLSTART="0.9" 27 | 28 | $ECHO 29 | $ECHO "Automatic measuring script." 30 | $ECHO "Copyright (C) 2002-2005 Denis Sbragion" 31 | $ECHO 32 | $ECHO "This program may be freely redistributed under the terms of" 33 | $ECHO "the GNU GPL and is provided to you as is, without any warranty" 34 | $ECHO "of any kind. Please read the file "COPYING" for details." 35 | $ECHO 36 | 37 | # Command line check 38 | if [[ $# < 12 ]]; then 39 | $ECHO "Usage:" 40 | $ECHO " measure bits rate startf endf lslen lssil indev outdev impfile amplitude recording_channel overall_output_channels current output channel" 41 | $ECHO 42 | $ECHO " bits: measuring bits (16, 24 or 32)" 43 | $ECHO " rate: sample rate" 44 | $ECHO " startf: sweep start frequency in Hz" 45 | $ECHO " endf: sweep end frequency in Hz" 46 | $ECHO " lslen: log sweep length in seconds" 47 | $ECHO " lssil: log sweep silence length in seconds" 48 | $ECHO " indev: ALSA input device" 49 | $ECHO " outdev: ALSA output device" 50 | $ECHO " amplitude of sweep file 0.1 .. 1" 51 | $ECHO " recording chanel to use (device dependend 1..n)" 52 | $ECHO " overall number of audio channels (device dependend 2..n)" 53 | $ECHO " overall number of audio channels (current audio channel to measure in the range of overall audio channels)" 54 | $ECHO 55 | $ECHO "example for a typical stereo measurement:" 56 | $ECHO "example: measure 32 44100 5 21000 45 2 hw:1,0 hw:1,0 impulse.pcm 0.5 2 0" 57 | $ECHO 58 | exit 0 59 | fi 60 | 61 | # Get command line parameters 62 | BITS="$1" 63 | RATE="$2" 64 | STARTF="$3" 65 | ENDF="$4" 66 | LSLEN="$5" 67 | LSSIL="$6" 68 | INDEV="$7" 69 | OUTDEV="$8" 70 | IMPFILE="$9" 71 | AMPLITUDE="${10}" 72 | REC_CHANNEL="${11}" 73 | OVERALL_CHANNELS="${12}" 74 | CURRENT_CHANNEL="${13}" 75 | SWEEPFILE="sweep.pcm" 76 | ARECORDFMT="S32_LE" 77 | SOXFMT="-e signed-integer -b 32" 78 | #PLAY_AC3=true 79 | 80 | # Generate the log sweep 81 | $ECHO "all parameters " $BITS $RATE $STARTF $ENDF $LSLEN $LSSIL $INDEV $OUTDEV $IMPFILE $AMPLITUDE $REC_CHANNEL $OVERALL_CHANNELS $CURRENT_CHANNEL 82 | 83 | PLAY_SWEEP=${TMP}/msplaysweep.wav 84 | PLAY_SWEEP_AC3=${TMP}/msplaysweep.ac3 85 | 86 | # determine channel to play the sweep to 87 | if [ -z "$CURRENT_CHANNEL" ]; then 88 | PLAY_SWEEP_PARAM="" 89 | else 90 | PLAY_SWEEP_PARAM="remix" 91 | #TODO construct remix string based on CURRENT_CHANNEL and OVERALL_CHANNELS 92 | for ((i=0;i 0: 20 | # print("arecord: result : "+str(result)) 21 | iValue = int(result[0]) 22 | self.progressBar.set_fraction(iValue / 100) 23 | 24 | def start(self, recHW, chanel, mode=None): 25 | try: 26 | self.stop() 27 | if mode is None: 28 | mode = "S32_LE" 29 | # maybe using plughw and see if it removes the dependencies to 30 | # use that at all 31 | volAlsaCmd = ["arecord", "-D" + recHW, "-c" + chanel, "-d0", 32 | "-f" + mode, "/dev/null", "-vvv"] 33 | print("starting volume monitoring with : " + str(volAlsaCmd)) 34 | self.proc = subprocess.Popen(volAlsaCmd, stdout=subprocess.PIPE, 35 | stderr=subprocess.STDOUT) 36 | self.pattern = re.compile("(\d*)%", re.MULTILINE) 37 | self.t = threading.Thread(None, target=self.reader_thread).start() 38 | except Exception as inst: 39 | print('unexpected exception', sys.exc_info()[0], type(inst), inst) 40 | 41 | def stop(self): 42 | print("stoping volume monitoring") 43 | if self.t is not None: 44 | self.t.terminate() 45 | if self.proc is not None: 46 | self.proc.terminate() 47 | self.progressBar.set_fraction(0.0) 48 | self.proc = None 49 | self.t = None 50 | 51 | def getDeviceListFromAlsaOutput(command): 52 | p = subprocess.Popen([command, "-l"], 0, None, None, subprocess.PIPE, 53 | subprocess.PIPE) 54 | (out, err) = p.communicate() 55 | pattern = re.compile( 56 | "\w* (\d*):\s.*?\[(.*?)\],\s.*?\s(\d*):.*?\s\[(.*?)\]", re.MULTILINE) 57 | alsaHardwareList = pattern.findall(str(out)) 58 | print("found pattern : " + str(alsaHardwareList)) 59 | return alsaHardwareList 60 | 61 | def execCommand(params): 62 | print(("executing: " + str(params))) 63 | p = subprocess.Popen(params, 0, None, None, subprocess.PIPE, 64 | subprocess.PIPE) 65 | return p.communicate() 66 | 67 | def getAlsaRangedValue(valueString, inputStr): 68 | pattern = re.compile(valueString + ":\s\[?(\d{1,6})\s?(\d{1,6})?\]?", 69 | re.MULTILINE) 70 | found = pattern.findall(str(inputStr)) 71 | print ("found: ", found ) 72 | # workaround to remove empty match in case of just single number 73 | # because I was not clever enough to have a clean 74 | # conditional regex... 75 | if len(found[0]) > 1 and not found[0][1]: 76 | result = [found[0][0]] 77 | else: 78 | result = [found[0][0], found[0][1]] 79 | print("result for " + valueString + " : ", result) 80 | return result 81 | 82 | class AlsaDevInfo(): 83 | def __init__(self): 84 | self.MaxChannel = 0 85 | self.MinChannel = 0 86 | self.supportedModes = None 87 | self.MinRate = 0 88 | self.MaxRate = 0 89 | 90 | def setDefaults(self): 91 | self.MaxChannel = 2 92 | self.MinChannel = 0 93 | self.supportedModes = ["S32_LE"] 94 | self.MinRate = 44100 95 | self.MaxRate = 44100 96 | 97 | def getAlsaDeviceInfo(params): 98 | result = AlsaDevInfo() 99 | try: 100 | (out, err) = execCommand(params) 101 | print(("hw infos : err : " + str(err) + " out : " + str(out))) 102 | # I rely on alsa output as e.g. CHANNELS to be not translated 103 | channels = getAlsaRangedValue("CHANNELS",err) 104 | result.MaxChannel = int(channels[0] if (len(channels) < 2) else channels[1]) 105 | result.MinChannel = int(channels[0]) 106 | pattern = re.compile("(\D\d+_\w*)", re.MULTILINE) 107 | result.supportedModes = pattern.findall(str(err)) 108 | #parse rate 109 | rates = getAlsaRangedValue("RATE", err) 110 | result.MaxRate = int(rates[0] if (len(rates) < 2) else rates[1]) 111 | result.MinRate = int(rates[0]) 112 | 113 | print(("numChannels : ", result.MaxChannel, result.MinChannel)) 114 | print(("supportedModes : ", str(result.supportedModes))) 115 | print(("rates : ", result.MaxRate, result.MinRate)) 116 | return result 117 | except Exception as inst: 118 | print(( 119 | 'failed to get rec hardware info...', 120 | sys.exc_info()[0], type(inst), inst)) 121 | #proceed at least with reasonable defaults almost evrt device can meet 122 | result.setDefaults(); 123 | return result 124 | 125 | def getRecordingDeviceInfo(recHwString): 126 | params = ['arecord', '-D', recHwString, 127 | '--dump-hw-params', '-d 1'] 128 | return getAlsaDeviceInfo(params) 129 | 130 | def getPlayDeviceInfo(playHwString): 131 | #TODO create dummy wave file by recording for a very short period 132 | dummyWaveFile="/usr/lib/rhythmbox/plugins/DRC/dummy.wav" 133 | params = ['aplay', '-D', playHwString, 134 | '--dump-hw-params', dummyWaveFile] 135 | #TODO implement fallback in case this fails - provide default parameters 136 | return getAlsaDeviceInfo(params) 137 | 138 | class AlsaDevice(): 139 | def __init__(self, alsaLine): 140 | self.alsaHW = "hw:" + str(alsaLine[0]) + "," + str(alsaLine[2]) 141 | self.alsaDevName = alsaLine[1]+" : " + alsaLine[3] 142 | self.validToUse = True 143 | self.MaxChannel = None 144 | self.samplingRates = [] 145 | 146 | def fromDevInfo(self, devInfo): 147 | self.MaxChannel = devInfo.MaxChannel 148 | self.MinChannel = devInfo.MinChannel 149 | self.supportedModes = devInfo.supportedModes 150 | self.MinRate = devInfo.MinRate 151 | self.MaxRate = devInfo.MaxRate 152 | 153 | class AlsaPlayDev(AlsaDevice): 154 | def __init__(self, alsaLine): 155 | AlsaDevice.__init__(self, alsaLine) 156 | 157 | def loadDeviceInfo(self): 158 | try: 159 | #loading is only needed once 160 | if self.MaxChannel is None: 161 | self.isDigitalOut = self.alsaDevName.lower().find("digital") > -1 or self.alsaDevName.lower().find("hdmi") > -1 or self.alsaDevName.find("S/PDIF") > -1 or self.alsaDevName.find("IEC958") > -1 162 | devInfo = getPlayDeviceInfo(self.alsaHW) 163 | AlsaDevice.fromDevInfo(self,devInfo) 164 | except Exception as inst: 165 | print(( 166 | 'failed to play hardware for AlsaPlayDev', 167 | sys.exc_info()[0], type(inst), inst)) 168 | 169 | 170 | class AlsaRecDev(AlsaDevice): 171 | def __init__(self, alsaLine): 172 | AlsaDevice.__init__(self, alsaLine) 173 | self.validToUse = False 174 | try: 175 | devInfo = getRecordingDeviceInfo(self.alsaHW) 176 | AlsaDevice.fromDevInfo(self,devInfo) 177 | #TODO I limit for rec devices that can deliver 32 bit; to be checked to support 16 bit too 178 | self.validToUse = "S32_LE" in self.supportedModes 179 | except Exception as inst: 180 | print(( 181 | 'failed to get rec hardware for AlsaRecDev', 182 | sys.exc_info()[0], type(inst), inst)) 183 | 184 | def loadDeviceInfo(self): 185 | print("nothing to do for rec device") 186 | 187 | class AlsaDevices(): 188 | def __init__(self): 189 | self.alsaPlayDevs = [] 190 | alsaPlayDev = getDeviceListFromAlsaOutput("aplay") 191 | for alsaDevLine in alsaPlayDev: 192 | self.alsaPlayDevs.append( AlsaPlayDev(alsaDevLine) ) 193 | self.alsaRecDevs = [] 194 | alsaRecDev = getDeviceListFromAlsaOutput("arecord") 195 | for alsaDevLine in alsaRecDev: 196 | self.alsaRecDevs.append( AlsaRecDev(alsaDevLine) ) 197 | 198 | 199 | def fillComboFromDeviceList(combo, alsaHardwareList, active): 200 | for alsaDev in alsaHardwareList: 201 | if alsaDev.validToUse: 202 | combo.append_text( alsaDev.alsaDevName ) 203 | combo.set_active(active) 204 | -------------------------------------------------------------------------------- /DRCTargetCurveUI.py: -------------------------------------------------------------------------------- 1 | # DRCTargetCurveUI.py 2 | # Copyright (C) 2013 - Tobias Wenig 3 | # tobiaswenig@yahoo.com> 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see 17 | 18 | import inspect 19 | import re 20 | 21 | import gi 22 | from gi.repository import RB 23 | from gi.repository import Gtk 24 | 25 | from DependsWrapper import DependsWrapperImpl 26 | 27 | def loadTargetCurveFile(targetCurveFile): 28 | pattern = re.compile("\n?(\d*\.?\d*)\s+(.*)\n?") 29 | curveValueArray = [] 30 | 31 | with open(targetCurveFile) as fp: 32 | for line in fp: 33 | print("searching line:" + line) 34 | values = pattern.findall(line) 35 | print("found data:" + str(values)) 36 | curveValueArray.append(values[0]) 37 | return curveValueArray 38 | 39 | 40 | def writeTargetCurveFile(targetCurveFile, data): 41 | ''' 42 | enforce DRC curve expectations : The first line must have a frequency equal 43 | to 0, the last line must have a frequency equal to BCSampleRate / 2 . A 44 | post 45 | filter definition file must have the following format:''' 46 | data.sort() 47 | if data[0][0] != 0: 48 | data.insert(0, (0, -100.0)) 49 | if data[-1][0] != 22050: 50 | data.append((22050, -100.0)) 51 | with open(targetCurveFile, "w") as fp: 52 | for lineData in data: 53 | print("{:.2f} {:.2f}".format(lineData[0], lineData[1]), file=fp) 54 | 55 | 56 | class LabeledEdit: 57 | def __init__(self, box, text, value, strDescription=None): 58 | label = Gtk.Label(text) 59 | box.add(label) 60 | self.entry = Gtk.Entry() 61 | if strDescription is not None: 62 | self.entry.set_tooltip_text(strDescription) 63 | label.set_tooltip_text(strDescription) 64 | self.entry.set_text(value) 65 | box.add(self.entry) 66 | newToolTip = Gtk.Tooltip() 67 | print(inspect.getdoc(newToolTip)) 68 | # newToolTip.set_tip(self.entry, "some tooltip") 69 | 70 | 71 | class AddDialog(Gtk.Dialog): 72 | params = [] 73 | 74 | def __init__(self, parent, params=None): 75 | if None != params: 76 | self.params = params 77 | else: 78 | self.params = [(100, 0)] 79 | super(Gtk.Dialog, self).__init__() 80 | okBtn = self.add_button(Gtk.STOCK_OK, Gtk.ResponseType.OK) 81 | okBtn.connect("clicked", self.on_ok) 82 | self.set_default_size(150, 100) 83 | box = self.get_content_area() 84 | self.freqLE = LabeledEdit(box, "frequency", str(self.params[0][0]), 85 | "Frequency of the EQBand") 86 | self.gainLE = LabeledEdit(box, "Gain", str(self.params[0][1]), 87 | "Gain of the EQBand") 88 | self.show_all() 89 | 90 | def on_ok(self, param): 91 | self.params = [(float(self.freqLE.entry.get_text()), 92 | float(self.gainLE.entry.get_text()))] 93 | 94 | 95 | class EQGroupControl(Gtk.VBox): 96 | def __init__(self, frequency, amplitude, parent): 97 | super(Gtk.VBox, self).__init__(False) 98 | self.frequency = frequency 99 | self.parent = parent 100 | self.slider = Gtk.VScale() 101 | self.slider.set_range(-100, 0) 102 | self.slider.set_inverted(True) 103 | self.slider.set_value_pos(Gtk.PositionType.TOP) 104 | self.slider.set_size_request(100, 300) 105 | self.slider.set_value(amplitude) 106 | self.labelFreq = Gtk.Label("f=" + str(frequency) + "Hz") 107 | remBtn = Gtk.Button("Remove") 108 | remBtn.connect("clicked", self.on_remove_band) 109 | self.add(self.slider) 110 | self.add(self.labelFreq) 111 | self.add(remBtn) 112 | self.show_all() 113 | 114 | def on_remove_band(self, param): 115 | self.parent.on_remove_band(self) 116 | 117 | def getAmplitude(self): 118 | return self.slider.get_value() 119 | 120 | def getFrequency(self): 121 | return float(self.frequency) 122 | 123 | 124 | class EQControl(): 125 | def __init__(self, targetCurveFile, parent): 126 | # self.set_title( "N Bands parametric EQ" ) 127 | self.targetCurveFilename = targetCurveFile 128 | addBtn = self.uibuilder = Gtk.Builder() 129 | self.uibuilder.add_from_file( 130 | DependsWrapperImpl.find_plugin_file(parent, "DRCUI.glade")) 131 | self.dlg = self.uibuilder.get_object("EQDlg") 132 | addBtn = self.uibuilder.get_object("buttonAddEQBand") 133 | addBtn.connect("clicked", self.add_new_eq_band) 134 | closeBtn = self.uibuilder.get_object("button_CloseEQ") 135 | closeBtn.connect("clicked", self.on_Ok) 136 | saveTargetCurveButton = self.uibuilder.get_object( 137 | "saveTargetCurveButton") 138 | saveTargetCurveButton.connect("file-set", self.on_file_selected) 139 | data = loadTargetCurveFile(targetCurveFile) 140 | self.eqBox = self.uibuilder.get_object("EQBox") 141 | self.rebuild_eq_controls(data) 142 | 143 | def getTargetCurveFile(self): 144 | return self.targetCurveFilename 145 | 146 | def on_file_selected(self, widget): 147 | self.targetCurveFilename = widget.get_filename() 148 | params = self.getEqParamListFromUI() 149 | # open file safe dialog and safe 150 | writeTargetCurveFile(self.targetCurveFilename, params) 151 | 152 | def rebuild_eq_controls(self, params): 153 | numEqBands = len(params) 154 | # remove all controls 155 | eqBandctrls = self.eqBox.get_children() 156 | print("children : ", len(eqBandctrls)) 157 | numBands = len(eqBandctrls) 158 | for i in range(0, numBands): 159 | self.eqBox.remove(eqBandctrls[i]) 160 | for i in range(0, numEqBands): 161 | self.eqBox.add( 162 | EQGroupControl(params[i][0], float(params[i][1]), self)) 163 | self.eqBox.show_all() 164 | 165 | def getEqParamListFromUI(self): 166 | params = [] 167 | eqBandctrls = self.eqBox.get_children() 168 | print("children : ", len(eqBandctrls)) 169 | numBands = len(eqBandctrls) 170 | for i in range(0, numBands): 171 | control = eqBandctrls[i] 172 | params.append((control.getFrequency(), control.getAmplitude())) 173 | # update UI in case of loudnes adaptation 174 | print("num bands :", len(params)) 175 | return params 176 | 177 | def add_new_eq_band(self, param): 178 | dlg = AddDialog(self) 179 | if dlg.run() == Gtk.ResponseType.OK: 180 | params = self.getEqParamListFromUI() 181 | frequency = dlg.params[0][0] 182 | if frequency <= 22050: 183 | print("params : " + str(params)) 184 | params.append(dlg.params[0]) 185 | print("params : " + str(params)) 186 | params.sort(key=lambda tup: tup[0]) 187 | self.rebuild_eq_controls(params) 188 | else: 189 | print("invalid frequency > 22050") 190 | dlg.destroy() 191 | 192 | def on_remove_band(self, eqbandCtrl): 193 | params = self.getEqParamListFromUI() 194 | numParams = len(params) 195 | param = None 196 | for i in range(0, numParams): 197 | print("checking : " + str(eqbandCtrl.frequency) + " for : " + str( 198 | params[i])) 199 | if eqbandCtrl.getFrequency() == params[i][0]: 200 | param = params[i] 201 | break 202 | print("attempt to remove : " + str(param)) 203 | params.remove(param) 204 | self.rebuild_eq_controls(params) 205 | 206 | def on_Ok(self, param): 207 | self.dlg.response(Gtk.ResponseType.OK) 208 | self.dlg.set_visible(False) 209 | 210 | def run(self): 211 | print("running dlg...") 212 | return self.dlg.run() 213 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | DRC 2 | ============ 3 | 4 | A rhythmbox plugin for digital room correction. 5 | 6 | As the room in which audio systems play influences the sound quite a bit the performasnce of speaker systems is usually degraded. Fortunately there are mechanisms that compensate for that: DRC (Digital Room Correction). It works in a way that a defined signal (log sweep) is played and its response is messured. From this the impulse response can be calculated to correct the influence of the room. 7 | For a more advanced explanation google e.g. for the DRC tool documentation( "DRC: Digital Room Correction docu" ). 8 | 9 | It can handle 32bit float mono filters as e.g. produced by PORC (search PORC on github) or DRCDesigner (also on github) and allows for one measuring/filter creation as well. Once the filter (from the plugin or external tools) is produced it can be loaded with this plugin to alow for music correction during play. 10 | 11 | There are 3 steps in the process of DRC which can be executed independently. If no other tools are used (e.g. DRCDesigner, Room EQ Wizard, Dirac, Accurate) the complete steps from measurment, filter calculation and fillter usage can be done by this plugin. 12 | In case of strating from scratch just exectute all 3 stages of the procedure. Each step produces the output of the next step. 13 | 14 |

1) measure room response

15 | 16 | measuring plays a configurable sine sweep and measures its room response. For that purpose calibrated measurment equipment is needed. For DRC measurements it is recomended to have the microphone directed towards the speakers with its front centered at the usual listening position (middle of the head). I use a calibrated Behringer ECM8000 and a Focusrite 2i2 USB audio interface. The recording device needs to suport recording in the 32bit float format (S32_LE). All other devices will be shown but the measure-button will stay disabled. In case you already have a recorded Impulse response just proceed with step 2 (calculating your filter). 17 | You need to select the proper input/output device and for input the correct channel where your microphone is connected. The recorded signal is monitored for quality and a dialog is shown with the evaluation results after measurement. 18 | 19 | output: impulse response file which can be loaded to the filter correction 20 | 21 |

Caution:

22 | 23 | It is advisable to start sweep play with lower volumes to not damage the equipment or you ears! The volume can be slowly turned up until a maximum is reached that does not make the furniture in your room vibrate as this will also cause artefacts. 24 | 25 | Generally the longer and the louder the measurmenet is done the better the results (signal to noise ratio). Usually a 20s sweep gives good results already. 26 | 27 |

2) calculate the needed filter to correct room response

28 | 29 | Calculating the filter depends on installed tools. Supported at the moment are PORC and DRC. Any way of created impulse response audio file can be used: either created by previous measurement step or by a another external tool. 30 | 31 | output: a 32 bit audio file containing the filter than can be loaded for the room correction 32 | 33 |

3) apply the filter to the played music

34 | 35 | load filter and enjoy :) --> no further dependencies 36 | 37 | for installation just copy all files to ${HOME}/.local/share/rhythmbox/plugins/DRC or copy the complete package to any folder and install as super user with "make install". 38 | 39 |

Limitations

40 | 41 | only fraction of DRC configurable capabilities is there, but files are available for edit in the plugin folder (for DRC adapt erb44100.drc) 42 | 43 |

Dependencies

44 | genarly depends on python3-lxml for configuration support (needed to load the module). It is recommended to install audacity for direct evaluation of the recorded signal. 45 |

For measurment funtionality

46 | 47 | depends on packages: sox, alsa-utils (uses aplay, arecord) 48 | for installation on Ubuntu: sudo apt-get install alsa-utils sox 49 | 50 |

Filter creation functionality

51 | 52 | DRC : depends on packages: sox, drc : sudo apt-get install sox drc 53 | PORC : depends on packages: sox, porc 54 | for porc: sudo apt-get install python-numpy, python-scipy, python-matplotlib 55 | PORC can be found on github. To use it just download the complet package an get it running by installing all dependencies (mostly python libs). The plugin expects porc to be installed in 56 | the plugin folder under a separate folder (./porc/porc.py). 57 | 58 | for those with some courage to try some new functionality: DRC supports multi channel correction, meaning a separate measure/filter per audio channel. To support this gstreamer plugins-good need to be patched as long as this change gets not a part of the gstreamer-plugins-good (see gst-plugins-good-patch folder) - I use it this way myself on Ubuntu 14.04/15.04. 59 | 60 |

experimenal functions and further development

61 | There are 2 experimental functions which only work to a limited extend: brutefir support and iterative measurements. Both shall be understood as an outlook and are not fully supported yet. brutefir support at least creates a split of the current filter suitable for brutefir use directly in the home directory. Brutefir is a good way to achieve system wide DRC while the rhythmbox related application is limited just to RB. It works and I also ahve it in use on the PI and my PC, but brutefir setup needs still some manual steps (setup alsa-loop etc..) 62 |

averaged multi-measurements

63 | Usually one good measurement approved by the QA - Dialog is sufficient to calculate a good correction filter (easiest default). It is possible to perform multiple measurements even across multiple positions and average the result. This can even be used to achieve a higher weight of the direct sounds vs the reflected sound. A good approach is to have one central measurement at the listening position and multiple (up to 5) in 10 centimeter distance on the axis centered towards the speakers. The weight of the measurements shall be adapted according to the distance (central listening position measurement with the heighest weighting factor). 64 | 65 |

general notes on room accoustics

66 | Even though DRC is a great tool to help with room accoustical problems it can't do miracles. It is recommended to do proper accoustical treatment for early reflections. All room correction only measures the sound getting toi the mic and cannot distinguish direct and reflected sound. For good stereo imaging it shall be evaluated to minimize early reflections. Accoustical treatment helps only in higher frequencies or at least is great effort (absorbers with huge volume) for deeper frequencies. 67 | 68 |

Bass in small rooms

69 | Especially the bass response below 80Hz is critical as it is almost impossible to counter act with accoustical treatment. Speaker placement and/or usage of 2/4 subwoofers can help to minimize such problems. If needed I could (and will) describe in more detail how I achieved that in my listening room. 70 | 71 |

usage on the raspberry PI

72 | Rhythmbox and room correction work on the raspberry PI! It can be insatlled on raspbian and the gstreamer as well as the brutefir FIR filtering works stable with no too significant CPU-load drain. Measuring on the PI works flawless. The PI only has issues with multi-channel USB soundcards. 73 | 74 |

Known issues

75 |

1) After measuring and filter calculation the filter can be directly applied. On some distributions this can cause audible issues and does not work. This can be worked around by just restarting rhythmbox.

76 |

2) for some reasons RB is not able to play continously once the FIR filter is set. A workaround got introduced that resets each track once started. That causes small gaps which are audible once continous tracks with gapless transition are played. Working on it :). One immediate fix is to jus use the brutefir convolution approach

77 | 78 |

usage for home cinema measurements

79 | The plugin now supports 5.1 maeasurements! See TODO for some limitations. 80 | 81 |

usage as standalone python application

82 | A standalone mode without rhythmbox can be used by starting 83 | 84 | python3 DRCStandalone.py 85 | 86 |

TODO

87 |

- better documentation

88 |

- 5.1 drc filter creation seems not yet to produce good result for the LFE channel, even with adapted target curve (for now just disabled correction for the LFE in the brutefir config)

89 |

- 5.1 measurement only supports digital output as AC3. TODO: also offer option for multichannel analog interfaces

90 |

- read device capabilities rather from /proc/asound than using aplay/arecord

91 | 92 | Thanks to all the great guys doing amazing SW stuff in the web! This tool is just trying to put it together in an easy usable way. 93 | -------------------------------------------------------------------------------- /DRC.py: -------------------------------------------------------------------------------- 1 | # DRC.py 2 | # Copyright (C) 2013 - Tobias Wenig 3 | # tobiaswenig@yahoo.com> 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see 17 | 18 | import os 19 | import sys 20 | 21 | from gi.repository import GObject, Gst, Peas, RB 22 | 23 | from DRCUi import DRCDlg 24 | from DRC_rb3compat import ActionGroup 25 | from DRC_rb3compat import ApplicationShell 26 | from DRCConfig import DRCConfig 27 | from threading import Timer 28 | 29 | import DRCFileTool 30 | 31 | ui_string = """ 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | """ 42 | 43 | 44 | class DRCPlugin(GObject.Object, Peas.Activatable): 45 | object = GObject.property(type=GObject.Object) 46 | 47 | def __init__(self): 48 | super(DRCPlugin, self).__init__() 49 | 50 | def set_kernel(self, filter_array): 51 | hasMultiKernel = True 52 | try: 53 | self.fir_filter.set_property('num-filter-channels', 2 ) 54 | filter = filter_array[0] + filter_array[1] 55 | self.fir_filter.set_property('kernel', filter) 56 | print("filter channels set") 57 | except Exception as inst: 58 | print(( 59 | 'setting multi chanel filter: attempting to set single kernel', 60 | sys.exc_info()[0], type(inst), inst)) 61 | hasMultiKernel = False 62 | self.fir_filter.set_property('kernel', filter_array[0]) 63 | pass 64 | print("kernel set") 65 | return hasMultiKernel 66 | 67 | def updateFilter(self, filterFileName=None): 68 | aCfg = DRCConfig() 69 | if filterFileName is None: 70 | filterFileName = aCfg.filterFile 71 | if aCfg.FIRFilterMode == 1: 72 | #gstFIR 73 | self.set_filter() 74 | hasMultiKernel = False 75 | try: 76 | source = self.shell_player.get_playing_source() 77 | self.shell_player.pause() 78 | #in case of a multichannel kernel with > 2 channels only 79 | #the first 2 channels shall be used for gstreamer filtering 80 | #as gstreamer FIR only supports at maximum 2 channels 81 | audioParams = DRCFileTool.LoadAudioFileStereoChannels( 82 | filterFileName, aCfg.numFilterChanels, 2) 83 | filter_array = audioParams.data 84 | # pass the filter data to the fir filter 85 | num_filter_coeff = len(filter_array) 86 | if num_filter_coeff > 0: 87 | hasMultiKernel = self.set_kernel(filter_array) 88 | self.set_filter() 89 | if self.entry is not None: 90 | self.shell_player.play_entry(self.entry, source) 91 | except Exception as inst: 92 | print(('error updating filter', sys.exc_info()[0], type(inst), 93 | inst)) 94 | pass 95 | return hasMultiKernel 96 | elif aCfg.FIRFilterMode == 2: 97 | #bruteFIF 98 | #nothing ToDO 99 | self.remove_Filter() 100 | else: 101 | #None : disable all filtering 102 | self.remove_Filter() 103 | return True 104 | 105 | def do_activate(self): 106 | try: 107 | self.duration = 0 108 | self.entry = None 109 | self.selfAllowTriggered = False 110 | self.filterSet = False 111 | self.shell = self.object 112 | self.shell_player = self.shell.props.shell_player 113 | self.player = self.shell_player.props.player 114 | self.fir_filter = Gst.ElementFactory.make('audiofirfilter', 115 | 'MyFIRFilter') 116 | # open filter files 117 | self.hasMultiKernel = self.updateFilter() 118 | # print( str(dir( self.shell.props)) ) 119 | except Exception as inst: 120 | print(('filter not set', sys.exc_info()[0], type(inst), inst)) 121 | pass 122 | aCfg = DRCConfig() 123 | if aCfg.FIRFilterMode == 1: 124 | #only for gst-FIR filter the skip-workaround is needed 125 | self.psc_id = self.shell_player.connect('playing-song-changed', 126 | self.playing_song_changed) 127 | # no possible workaround as somehow never reaches end of song :( 128 | self.shell_player.connect('elapsed-changed', self.elapsed_changed) 129 | # finally add UI 130 | self.add_ui(self, self.shell) 131 | 132 | def add_ui(self, plugin, shell): 133 | self.drcDlg = DRCDlg(self) 134 | print("starting add_ui") 135 | action_group = ActionGroup(shell, 'DRCActionGroup') 136 | action_group.add_action(func=self.drcDlg.show_ui, 137 | action_name='DRC', label=('_DRC'), 138 | action_type='app') 139 | self._appshell = ApplicationShell(shell) 140 | self._appshell.insert_action_group(action_group) 141 | self._appshell.add_app_menuitems(ui_string, 'DRCActionGroup') 142 | print("add_ui done") 143 | 144 | def set_filter(self): 145 | try: 146 | if not self.filterSet: 147 | print('adding filter') 148 | self.player.add_filter(self.fir_filter) 149 | print('done setting filter') 150 | self.filterSet = True 151 | except Exception as inst: 152 | print(('unexpected exception', sys.exc_info()[0], type(inst), inst)) 153 | pass 154 | 155 | def remove_Filter(self): 156 | try: 157 | if self.filterSet: 158 | self.player.remove_filter(self.fir_filter) 159 | print('filter disabled') 160 | self.filterSet = False 161 | except: 162 | pass 163 | 164 | def do_deactivate(self): 165 | print('entering do_deactivate') 166 | self.shell_player.disconnect(self.psc_id) 167 | 168 | try: 169 | self.remove_Filter() 170 | self._appshell.cleanup() 171 | except: 172 | pass 173 | 174 | del self.shell_player 175 | del self.shell 176 | del self.fir_filter 177 | 178 | def elapsed_changed(self, sp, elapsed): 179 | # workaround due to FIR filter issues during playing back multiple 180 | # songs 181 | # switching as well as new song select in UI seems to fix that 182 | # print("elapsed : " + str(elapsed) ) 183 | diff = self.duration - elapsed 184 | # print("diff : " + str(diff)) 185 | # allowing self triggered skip forth and back after last 15 seconds 186 | # to bad that diff is unreliable.. no idea why 0 never marks the 187 | # real end 188 | if self.duration < 1: 189 | return 190 | if diff <= 15 and diff > -1: 191 | print("end of song reached : allow triggering") 192 | self.selfAllowTriggered = True 193 | self.duration = 0 194 | else: 195 | self.selfAllowTriggered = False 196 | 197 | def change_song_timer(self, sp, entry): 198 | print("timer elapsed - perform start/play") 199 | source = sp.get_playing_source() 200 | sp.stop() 201 | sp.play_entry(entry, source) 202 | self.selfAllowTriggered = False 203 | 204 | def playing_song_changed(self, sp, entry): 205 | self.duration = sp.get_playing_song_duration() 206 | # print("playing song duration: " + str(self.duration)) 207 | if entry is None or not self.selfAllowTriggered: 208 | return 209 | # workaround due to FIR filter issues during playing back multiple 210 | # songs 211 | # switching as well as new song select in UI seems to fix that 212 | '''TODO: this will fail for manually selecting last song in list in UI 213 | clean way would be to check has-prev/has-next but seems to be 214 | useless: 215 | returns true even if no son is previous in current UI list... 216 | ''' 217 | t = Timer(1.5, self.change_song_timer, args=[sp,entry]) 218 | t.start() 219 | print("timer done") 220 | 221 | def find_file(self, filename): 222 | info = self.plugin_info 223 | data_dir = info.get_data_dir() 224 | path = os.path.join(data_dir, filename) 225 | 226 | if os.path.exists(path): 227 | return path 228 | 229 | return RB.file(filename) 230 | -------------------------------------------------------------------------------- /gst-plugins-good-patch/audiofirfilter.c: -------------------------------------------------------------------------------- 1 | /* 2 | * GStreamer 3 | * Copyright (C) 2009 Sebastian Dröge 4 | * 5 | * This library is free software; you can redistribute it and/or 6 | * modify it under the terms of the GNU Library General Public 7 | * License as published by the Free Software Foundation; either 8 | * version 2 of the License, or (at your option) any later version. 9 | * 10 | * This library is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 13 | * Library General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Library General Public 16 | * License along with this library; if not, write to the 17 | * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, 18 | * Boston, MA 02110-1301, USA. 19 | * 20 | */ 21 | 22 | /** 23 | * SECTION:element-audiofirfilter 24 | * 25 | * audiofirfilter implements a generic audio FIR filter. Before usage the 26 | * "kernel" property has to be set to the filter kernel that should be 27 | * used and the "latency" property has to be set to the latency (in samples) 28 | * that is introduced by the filter kernel. Setting a latency of n samples 29 | * will lead to the first n samples being dropped from the output and 30 | * n samples added to the end. 31 | * 32 | * The filter kernel describes the impulse response of the filter. To 33 | * calculate the frequency response of the filter you have to calculate 34 | * the Fourier Transform of the impulse response. 35 | * 36 | * To change the filter kernel whenever the sampling rate changes the 37 | * "rate-changed" signal can be used. This should be done for most 38 | * FIR filters as they're depending on the sampling rate. 39 | * 40 | * 41 | * Example application 42 | * 43 | * 44 | * 45 | * 46 | */ 47 | 48 | /* FIXME 0.11: suppress warnings for deprecated API such as GValueArray 49 | * with newer GLib versions (>= 2.31.0) */ 50 | #define GLIB_DISABLE_DEPRECATION_WARNINGS 51 | 52 | #ifdef HAVE_CONFIG_H 53 | #include "config.h" 54 | #endif 55 | 56 | #include 57 | #include 58 | #include 59 | #include 60 | 61 | #include "audiofirfilter.h" 62 | 63 | #include "gst/glib-compat-private.h" 64 | 65 | #define GST_CAT_DEFAULT gst_audio_fir_filter_debug 66 | GST_DEBUG_CATEGORY_STATIC (GST_CAT_DEFAULT); 67 | 68 | enum 69 | { 70 | SIGNAL_RATE_CHANGED, 71 | LAST_SIGNAL 72 | }; 73 | 74 | enum 75 | { 76 | PROP_0, 77 | PROP_KERNEL, 78 | PROP_LATENCY, 79 | PROP_NUM_FILT_CHAN 80 | }; 81 | 82 | static guint gst_audio_fir_filter_signals[LAST_SIGNAL] = { 0, }; 83 | 84 | #define gst_audio_fir_filter_parent_class parent_class 85 | G_DEFINE_TYPE (GstAudioFIRFilter, gst_audio_fir_filter, 86 | GST_TYPE_AUDIO_FX_BASE_FIR_FILTER); 87 | 88 | static void gst_audio_fir_filter_set_property (GObject * object, guint prop_id, 89 | const GValue * value, GParamSpec * pspec); 90 | static void gst_audio_fir_filter_get_property (GObject * object, guint prop_id, 91 | GValue * value, GParamSpec * pspec); 92 | static void gst_audio_fir_filter_finalize (GObject * object); 93 | 94 | static gboolean gst_audio_fir_filter_setup (GstAudioFilter * base, 95 | const GstAudioInfo * info); 96 | 97 | 98 | static void 99 | gst_audio_fir_filter_class_init (GstAudioFIRFilterClass * klass) 100 | { 101 | GObjectClass *gobject_class = (GObjectClass *) klass; 102 | GstElementClass *gstelement_class = (GstElementClass *) klass; 103 | GstAudioFilterClass *filter_class = (GstAudioFilterClass *) klass; 104 | 105 | GST_DEBUG_CATEGORY_INIT (gst_audio_fir_filter_debug, "audiofirfilter", 0, 106 | "Generic audio FIR filter plugin"); 107 | 108 | gobject_class->set_property = gst_audio_fir_filter_set_property; 109 | gobject_class->get_property = gst_audio_fir_filter_get_property; 110 | gobject_class->finalize = gst_audio_fir_filter_finalize; 111 | 112 | g_object_class_install_property (gobject_class, PROP_KERNEL, 113 | g_param_spec_value_array ("kernel", "Filter Kernel", 114 | "Filter kernel for the FIR filter", 115 | g_param_spec_double ("Element", "Filter Kernel Element", 116 | "Element of the filter kernel", -G_MAXDOUBLE, G_MAXDOUBLE, 0.0, 117 | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS), 118 | G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); 119 | 120 | g_object_class_install_property (gobject_class, PROP_LATENCY, 121 | g_param_spec_uint64 ("latency", "Latency", 122 | "Filter latency in samples", 123 | 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS)); 124 | 125 | g_object_class_install_property (gobject_class, PROP_NUM_FILT_CHAN, 126 | g_param_spec_uint64 ("num-filter-channels", "number of filter channels", 127 | "number of channels in the filter file", 128 | 0, G_MAXUINT64, 0, G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));; 129 | 130 | filter_class->setup = GST_DEBUG_FUNCPTR (gst_audio_fir_filter_setup); 131 | 132 | /** 133 | * GstAudioFIRFilter::rate-changed: 134 | * @filter: the filter on which the signal is emitted 135 | * @rate: the new sampling rate 136 | * 137 | * Will be emitted when the sampling rate changes. The callbacks 138 | * will be called from the streaming thread and processing will 139 | * stop until the event is handled. 140 | */ 141 | gst_audio_fir_filter_signals[SIGNAL_RATE_CHANGED] = 142 | g_signal_new ("rate-changed", G_TYPE_FROM_CLASS (klass), 143 | G_SIGNAL_RUN_LAST, G_STRUCT_OFFSET (GstAudioFIRFilterClass, rate_changed), 144 | NULL, NULL, NULL, G_TYPE_NONE, 1, G_TYPE_INT); 145 | 146 | gst_element_class_set_static_metadata (gstelement_class, 147 | "Audio FIR filter", "Filter/Effect/Audio", 148 | "Generic audio FIR filter with custom filter kernel", 149 | "Sebastian Dröge "); 150 | } 151 | 152 | static void 153 | clean_kernels (GstAudioFIRFilter * self) 154 | { 155 | if (self->kernel) 156 | { 157 | g_value_array_free (self->kernel); 158 | } 159 | self->kernel = NULL; 160 | } 161 | 162 | static void 163 | gst_audio_fir_filter_update_multi_kernel (GstAudioFIRFilter * self, GValueArray * va) 164 | { 165 | guint num_overall_filter_values = 0; 166 | guint channel_filter_length = 0; 167 | guint i = 0,j = 0; 168 | gdouble *kernel = NULL; 169 | GST_WARNING("try to set multi kernel"); 170 | if (va) { 171 | clean_kernels(self); 172 | self->kernel = va; 173 | num_overall_filter_values = va->n_values; 174 | channel_filter_length = num_overall_filter_values / self->num_filt_channels; 175 | kernel = g_new (gdouble, num_overall_filter_values); 176 | for (i = 0; i < self->num_filt_channels; i++ ) { 177 | for(j = 0; j < channel_filter_length; j++){ 178 | guint currFilterPos = (i*channel_filter_length) + j; 179 | GValue* v = g_value_array_get_nth (va, currFilterPos); 180 | kernel[currFilterPos] = g_value_get_double (v); 181 | //GST_WARNING( "setting %f in kernel; index = %i; channel = %i", kernel[currFilterPos], j, i ); 182 | } 183 | } 184 | } 185 | gst_audio_fx_base_fir_filter_set_multi_kernel (GST_AUDIO_FX_BASE_FIR_FILTER (self), 186 | kernel, channel_filter_length, self->latency, NULL, self->num_filt_channels); 187 | } 188 | 189 | static void 190 | gst_audio_fir_filter_update_kernel (GstAudioFIRFilter * self, GValueArray * va) 191 | { 192 | if( self->num_filt_channels > 1 ) 193 | { 194 | gst_audio_fir_filter_update_multi_kernel (self, va); 195 | return; 196 | } 197 | gdouble *kernel; 198 | guint i; 199 | 200 | if (va) { 201 | clean_kernels(self); 202 | self->kernel = va; 203 | } 204 | 205 | kernel = g_new (gdouble, self->kernel->n_values); 206 | 207 | for (i = 0; i < self->kernel->n_values; i++) { 208 | GValue *v = g_value_array_get_nth (self->kernel, i); 209 | kernel[i] = g_value_get_double (v); 210 | //GST_WARNING( "setting %f in kernel; index = %i", kernel[i], i ); 211 | } 212 | 213 | //reset the number of kernels 214 | GstAudioFXBaseFIRFilter *base_self = GST_AUDIO_FX_BASE_FIR_FILTER (self); 215 | base_self->kernel_channels=1; 216 | 217 | gst_audio_fx_base_fir_filter_set_kernel (base_self, 218 | kernel, self->kernel->n_values, self->latency, NULL); 219 | } 220 | 221 | static void 222 | gst_audio_fir_filter_init (GstAudioFIRFilter * self) 223 | { 224 | GValue v = { 0, }; 225 | GValueArray *va; 226 | 227 | self->latency = 0; 228 | self->num_filt_channels = 1; 229 | va = g_value_array_new (1); 230 | 231 | g_value_init (&v, G_TYPE_DOUBLE); 232 | g_value_set_double (&v, 1.0); 233 | g_value_array_append (va, &v); 234 | g_value_unset (&v); 235 | gst_audio_fir_filter_update_kernel (self, va); 236 | 237 | g_mutex_init (&self->lock); 238 | } 239 | 240 | /* GstAudioFilter vmethod implementations */ 241 | 242 | /* get notified of caps and plug in the correct process function */ 243 | static gboolean 244 | gst_audio_fir_filter_setup (GstAudioFilter * base, const GstAudioInfo * info) 245 | { 246 | GstAudioFIRFilter *self = GST_AUDIO_FIR_FILTER (base); 247 | gint new_rate = GST_AUDIO_INFO_RATE (info); 248 | 249 | if (GST_AUDIO_FILTER_RATE (self) != new_rate) { 250 | g_signal_emit (G_OBJECT (self), 251 | gst_audio_fir_filter_signals[SIGNAL_RATE_CHANGED], 0, new_rate); 252 | } 253 | 254 | return GST_AUDIO_FILTER_CLASS (parent_class)->setup (base, info); 255 | } 256 | 257 | static void 258 | gst_audio_fir_filter_finalize (GObject * object) 259 | { 260 | GstAudioFIRFilter *self = GST_AUDIO_FIR_FILTER (object); 261 | 262 | g_mutex_clear (&self->lock); 263 | 264 | clean_kernels(self); 265 | 266 | G_OBJECT_CLASS (parent_class)->finalize (object); 267 | } 268 | 269 | static void 270 | gst_audio_fir_filter_set_property (GObject * object, guint prop_id, 271 | const GValue * value, GParamSpec * pspec) 272 | { 273 | GstAudioFIRFilter *self = GST_AUDIO_FIR_FILTER (object); 274 | g_return_if_fail (GST_IS_AUDIO_FIR_FILTER (self)); 275 | switch (prop_id) { 276 | case PROP_KERNEL: 277 | g_mutex_lock (&self->lock); 278 | /* update kernel already pushes residues */ 279 | gst_audio_fir_filter_update_kernel (self, g_value_dup_boxed (value)); 280 | g_mutex_unlock (&self->lock); 281 | break; 282 | case PROP_LATENCY: 283 | g_mutex_lock (&self->lock); 284 | self->latency = g_value_get_uint64 (value); 285 | gst_audio_fir_filter_update_kernel (self, NULL); 286 | g_mutex_unlock (&self->lock); 287 | break; 288 | case PROP_NUM_FILT_CHAN: 289 | g_mutex_lock (&self->lock); 290 | self->num_filt_channels = g_value_get_uint64 (value); 291 | gst_audio_fir_filter_update_kernel (self, NULL); 292 | g_mutex_unlock (&self->lock); 293 | break; 294 | default: 295 | G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); 296 | break; 297 | } 298 | } 299 | 300 | static void 301 | gst_audio_fir_filter_get_property (GObject * object, guint prop_id, 302 | GValue * value, GParamSpec * pspec) 303 | { 304 | GstAudioFIRFilter *self = GST_AUDIO_FIR_FILTER (object); 305 | 306 | switch (prop_id) { 307 | case PROP_KERNEL: 308 | g_value_set_boxed (value, self->kernel); 309 | break; 310 | case PROP_LATENCY: 311 | g_value_set_uint64 (value, self->latency); 312 | break; 313 | case PROP_NUM_FILT_CHAN: 314 | g_value_set_uint64 (value, self->num_filt_channels); 315 | break; 316 | default: 317 | G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec); 318 | break; 319 | } 320 | } 321 | -------------------------------------------------------------------------------- /DRCFileTool.py: -------------------------------------------------------------------------------- 1 | # DRC.py 2 | # Copyright (C) 2013 - Tobias Wenig 3 | # tobiaswenig@yahoo.com> 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see 17 | import os 18 | import subprocess 19 | import struct 20 | import math 21 | from array import array 22 | 23 | 24 | class WaveParams: 25 | def __init__(self, numChannels=None): 26 | if numChannels is None: 27 | self.numChannels = 2 28 | else: 29 | self.numChannels = numChannels 30 | self.DataOffset = 0 31 | self.sampleByteSize = 4 32 | self.maxSampleValue = [] 33 | self.minSampleValue = [] 34 | self.maxSampleValuePos = [] 35 | self.minSampleValuePos = [] 36 | self.data = [] 37 | for chanel in range(0, self.numChannels): 38 | dataArr = [] 39 | self.data.append(dataArr) 40 | self.maxSampleValue.append(-1) 41 | self.minSampleValue.append(1) 42 | self.maxSampleValuePos.append(-1) 43 | self.minSampleValuePos.append(-1) 44 | 45 | 46 | # WavHeader.py 47 | # Extract basic header information from a WAV file 48 | # ...taken from http://blog.theroyweb.com/extracting-wav-file-header 49 | # -information-using-a-python-script 50 | # slightly modified to pass out parse result 51 | def PrintWavHeader(strWAVFile): 52 | """ Extracts data in the first 44 bytes in a WAV file and writes it 53 | out in a human-readable format 54 | """ 55 | 56 | def DumpHeaderOutput(structHeaderFields): 57 | for key in structHeaderFields.keys(): 58 | print(("%s: " % (key), structHeaderFields[key])) 59 | # end for 60 | 61 | # Open file 62 | fileIn = open(strWAVFile, 'rb') 63 | # end try 64 | # Read in all data 65 | bufHeader = fileIn.read(38) 66 | # Verify that the correct identifiers are present 67 | # print( "bufHeader[0:4]", bufHeader[0:4].decode("utf-8"), " : ", 68 | # str(bufHeader[0:4].decode("utf-8")) == 'RIFF' ) 69 | if (bufHeader[0:4].decode("utf-8") != "RIFF") or \ 70 | (bufHeader[12:16].decode("utf-8") != "fmt "): 71 | print("Input file not a standard WAV file") 72 | return 73 | # endif 74 | stHeaderFields = {'ChunkSize': 0, 'Format': '', 75 | 'Subchunk1Size': 0, 'AudioFormat': 0, 76 | 'NumChannels': 0, 'SampleRate': 0, 77 | 'ByteRate': 0, 'BlockAlign': 0, 78 | 'BitsPerSample': 0, 'Filename': ''} 79 | # Parse fields 80 | stHeaderFields['ChunkSize'] = struct.unpack('= inputFileSize: 106 | break 107 | # endif 108 | # end while 109 | # Dump subchunk list 110 | print("Subchunks Found: ") 111 | for chunkName in chunksList: 112 | print(("%s, " % (chunkName), )) 113 | # end for 114 | print("\n") 115 | # Dump data chunk information 116 | if dataChunkLocation != 0: 117 | fileIn.seek(dataChunkLocation) 118 | bufHeader = fileIn.read(8) 119 | print(("Data Chunk located at offset [%s] of data length [%s] bytes" % 120 | (dataChunkLocation, struct.unpack(' floatSample: 178 | params.minSampleValue[chanel] = floatSample 179 | params.minSampleValuePos[chanel] = len(params.data[chanel]) 180 | params.data[chanel].append(floatSample) 181 | else: 182 | print("buffer underrun for chanel : ", chanel, "at sample:", len(params.data[chanel]) ) 183 | print("addin 0 sample to compensate and keep length consistent across chanels") 184 | params.data[chanel].append(0.0) 185 | # dump the filter to check 186 | if params.numChannels > 1: 187 | print(("loaded r/l: " + str(len(params.data[0])) + "/" + 188 | str(len(params.data[1])) + " samples per channel successfully")) 189 | else: 190 | print(("loaded one chanel filter: " + str(len(params.data[0])) + 191 | " with samples successfully")) 192 | print(("numChanels : ", params.numChannels, "maxPos : ", 193 | str(params.maxSampleValuePos), "maxValue : ", 194 | str(params.maxSampleValue), "file: ", filename)) 195 | 196 | #dumpSoundDataToFile(params.data[0], /tmp/filterdmp.pcm, True) 197 | return params 198 | 199 | 200 | def WriteWaveFile(params, outFileName): 201 | #poor mans way to write a wave file - we write 2 temporary pcm files 202 | #and convert to wav using sox :) 203 | commandLine = ['sox', '-M'] 204 | pcmParams = ['-traw', '-c1', '-r41100', '-efloat', '-b32'] 205 | #TODO : do properly once prototype works 206 | for chanel in range(0, params.numChannels): 207 | strFileName = "/tmp/channel_" + str(chanel) + ".pcm" 208 | commandLine.extend(pcmParams) 209 | print(("numChanels : ", params.numChannels, "chanel: ", chanel)) 210 | dumpSoundDataToFile(params.data[chanel], strFileName) 211 | commandLine.append(strFileName) 212 | if params.numChannels > 1: 213 | commandLine.extend(['-twav']) 214 | else: 215 | commandLine = ['sox', '-traw', '-c1', '-r41100', 216 | '-efloat', '-b32'] 217 | commandLine.append(strFileName) 218 | commandLine.extend(['-twav']) 219 | commandLine.append(outFileName) 220 | print(("executing sox to create wave file : " + str(commandLine))) 221 | p = subprocess.Popen(commandLine, 0, None, None, subprocess.PIPE, 222 | subprocess.PIPE) 223 | (out, err) = p.communicate() 224 | print(("output from sox conversion : " + str(out) + " error : " + str(err))) 225 | 226 | 227 | def LoadWaveFile(filename): 228 | #we have some trouble with or very limited wavefile handling 229 | #as we can load sox creaed wave files we use sox to make sure that we have a format we can handle 230 | strTmpWaveFileName = '/tmp/tmpWaveFile.wav' 231 | commandLine = ['sox'] 232 | commandLine.append(filename) 233 | commandLine.extend(['-twav', '-r 44100']) 234 | commandLine.append( strTmpWaveFileName ) 235 | print(("executing sox to create tmp wave file for loading: " + str(commandLine))) 236 | p = subprocess.Popen(commandLine, 0, None, None, subprocess.PIPE, 237 | subprocess.PIPE) 238 | (out, err) = p.communicate() 239 | print(("output from sox conversion : " + str(out) + " error : " + str(err))) 240 | params = PrintWavHeader(strTmpWaveFileName) 241 | print(("LoadWaveFile: numChannels : ", params.numChannels)) 242 | params = LoadRawFile(strTmpWaveFileName, params) 243 | return params 244 | 245 | 246 | def fillTestFilter(filter_kernel): 247 | filter_array = filter_kernel 248 | itFilter = iter(filter_array) 249 | next(itFilter) 250 | for i in itFilter: 251 | filter_array.insert(0, i) 252 | next(itFilter) 253 | print(("test filter : " + str(filter_array))) 254 | return filter_array 255 | 256 | 257 | def LoadAudioFile(filename, numChannels): 258 | # return fillTestFilter( [0.25, 0.23, 0.15, 0.06, 0, -0.06, -0.06, 259 | # -0.02, 0.0, 0.01, 0.01, 0] ) + fillTestFilter([0.25, 0.06, 0, -0.06, 260 | # -0.06, -0.02, 0, 0.01, 0.01, 0.0, 0.0, 0.0]) 261 | print(("LoadAudioFile: ", filename, " numChanels : ", numChannels)) 262 | if filename != '': 263 | fileExt = os.path.splitext(filename)[-1] 264 | print("ext = " + fileExt) 265 | if fileExt == ".wav": 266 | return LoadWaveFile(filename) 267 | params = WaveParams(numChannels) 268 | return LoadRawFile(filename, params) 269 | 270 | 271 | def LoadAudioFileStereoChannels(filename, numChannels, numChannelsToLoad): 272 | data = LoadAudioFile(filename, numChannels) 273 | if data.numChannels > 2: 274 | #TODO extract first 2 channels and re-package 275 | print(("work in progress ... ")) 276 | return data 277 | -------------------------------------------------------------------------------- /DRCUi.py: -------------------------------------------------------------------------------- 1 | # DRCUi.py 2 | # Copyright (C) 2013 - Tobias Wenig 3 | # tobiaswenig@yahoo.com> 4 | # 5 | # This program is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This program is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this program. If not, see 17 | import os 18 | import datetime 19 | import subprocess 20 | 21 | import gi 22 | from gi.repository import Gtk 23 | from gi.repository import RB 24 | 25 | from DependsWrapper import DependsWrapperImpl 26 | 27 | from DRCConfig import DRCConfig 28 | from MeasureQADlg import MeasureQADlg 29 | from MeasureQADlg import MeasureQARetVal 30 | from TargetCurveDlg import TargetCurveDlg 31 | from ChannelSelDlg import ChanelSelDlg 32 | from PORCCfgDlg import PORCCfgDlg 33 | from DRCCfgDlg import DRCCfgDlg 34 | from ImpRespDlg import ImpRespDlg 35 | from alsaTools import InputVolumeProcess, AlsaDevices, AlsaDevice 36 | import alsaTools 37 | 38 | import DRCFileTool 39 | 40 | class DRCDlg: 41 | def initUI(self): 42 | aCfg = DRCConfig() 43 | self.uibuilder = Gtk.Builder() 44 | self.uibuilder.add_from_file( 45 | DependsWrapperImpl.find_plugin_file(self.parent, "DRCUI.glade")) 46 | self.dlg = self.uibuilder.get_object("DRCDlg") 47 | self.dlg.connect("close", self.on_close) 48 | audioFileFilter = Gtk.FileFilter() 49 | audioFileFilter.add_pattern("*.wav") 50 | audioFileFilter.add_pattern("*.pcm") 51 | audioFileFilter.add_pattern("*.raw") 52 | self.filechooserbtn = self.uibuilder.get_object( 53 | "drcfilterchooserbutton") 54 | self.filechooserbtn.set_filter(audioFileFilter) 55 | if os.path.isfile(aCfg.filterFile): 56 | self.filechooserbtn.set_filename(aCfg.filterFile) 57 | else: 58 | self.filechooserbtn.set_current_folder(self.getFilterResultsDir()) 59 | 60 | self.filechooserbtn.connect("file-set", self.on_file_selected) 61 | self.entrySweepDuration = self.uibuilder.get_object( 62 | "entrySweepDuration") 63 | self.entrySweepDuration.set_text(str(aCfg.sweepDuration)) 64 | 65 | self.progressbarInputVolume = self.uibuilder.get_object( 66 | "progressbarInputVolume") 67 | 68 | self.alsaPlayHardwareCombo = self.uibuilder.get_object("comboOutput") 69 | self.alsaRecHardwareCombo = self.uibuilder.get_object("comboRecord") 70 | self.comboSampleRate = self.uibuilder.get_object("comboSampleRate") 71 | 72 | self.execMeasureBtn = self.uibuilder.get_object("buttonMeassure") 73 | self.execMeasureBtn.connect("clicked", self.on_execMeasure) 74 | 75 | self.alsaDevices = AlsaDevices() 76 | alsaTools.fillComboFromDeviceList(self.alsaPlayHardwareCombo, 77 | self.alsaDevices.alsaPlayDevs, 78 | aCfg.playHardwareIndex) 79 | alsaTools.fillComboFromDeviceList(self.alsaRecHardwareCombo, 80 | self.alsaDevices.alsaRecDevs, 81 | aCfg.recHardwareIndex) 82 | self.alsaRecHardwareCombo.connect("changed", self.on_recDeviceChanged) 83 | self.comboInputChanel = self.uibuilder.get_object("comboInputChanel") 84 | self.comboInputChanel.set_active(aCfg.recHardwareChannelIndex) 85 | # fill the number of input channels 86 | self.updateRecDeviceInfo() 87 | self.comboInputChanel.connect("changed", self.on_InputChanelChanged) 88 | 89 | calcDRCBtn = self.uibuilder.get_object("buttonCalculateFilter") 90 | calcDRCBtn.connect("clicked", self.on_calculateDRC) 91 | 92 | slider = self.uibuilder.get_object("scaleSweepAmplitude") 93 | slider.set_range(0.1, 1) 94 | slider.set_value_pos(Gtk.PositionType.TOP) 95 | self.sweep_level = aCfg.recordGain 96 | slider.set_value(self.sweep_level) 97 | slider.connect("value_changed", self.slider_changed) 98 | 99 | apply_closeBtn = self.uibuilder.get_object("apply_closeBtn") 100 | apply_closeBtn.connect("clicked", self.on_apply_settings) 101 | 102 | cancel_closeBtn = self.uibuilder.get_object("cancelButton") 103 | cancel_closeBtn.connect("clicked", self.on_Cancel) 104 | 105 | self.buttonSetImpRespFile = self.uibuilder.get_object( 106 | "buttonSetImpRespFile") 107 | 108 | self.buttonSetImpRespFile.connect("clicked", self.on_setImpRespFiles) 109 | 110 | self.comboDRC = self.uibuilder.get_object("combo_drc_type") 111 | self.cfgDRCButton = self.uibuilder.get_object("cfgDRCButton") 112 | self.cfgDRCButton.connect("clicked", self.on_cfgDRC) 113 | self.comboDRC.append_text("DRC") 114 | self.comboDRC.append_text("PORC") 115 | self.comboDRC.set_active(0) 116 | self.comboDRC.connect("changed", self.on_DRCTypeChanged) 117 | self.on_DRCTypeChanged(self.comboDRC) 118 | self.drcCfgDlg = DRCCfgDlg(self.parent) 119 | self.porcCfgDlg = PORCCfgDlg(self.parent) 120 | self.channelSelDlg = ChanelSelDlg(self.parent) 121 | self.impRespDlg = ImpRespDlg(self, self.getMeasureResultsDir()) 122 | self.targetCurveDlg = TargetCurveDlg(self.parent) 123 | 124 | self.exec_2ChannelMeasure = self.uibuilder.get_object( 125 | "checkbutton_2ChannelMeasure") 126 | self.exec_2ChannelMeasure.set_sensitive(True) 127 | 128 | self.spinbutton_NumChannels = self.uibuilder.get_object( 129 | "spinbutton_NumChannels") 130 | 131 | self.notebook = self.uibuilder.get_object("notebook1") 132 | self.volumeUpdateBlocked = False 133 | self.mode = None 134 | self.inputVolumeUpdate = InputVolumeProcess( 135 | self.progressbarInputVolume) 136 | self.comboboxFIRFilterMode = self.uibuilder.get_object( 137 | "comboboxFIRFilterMode") 138 | self.comboboxFIRFilterMode.set_active(aCfg.FIRFilterMode) 139 | self.comboboxFIRFilterMode.connect("changed", 140 | self.on_FIRFilterModeChanged) 141 | 142 | self.uibuilder.get_object("buttonTargetCurve").connect("clicked", 143 | self.on_EditTargetCurve) 144 | 145 | def __init__(self, parent): 146 | self.parent = parent 147 | 148 | def on_EditTargetCurve(self, button): 149 | impRespFile = self.impRespDlg.getImpRespFiles()[0].fileName 150 | self.targetCurveDlg.setImpRespFile(impRespFile) 151 | self.targetCurveDlg.run() 152 | 153 | def startInputVolumeUpdate(self, channel=None): 154 | if channel is None: 155 | channel = self.comboInputChanel.get_active_text() 156 | if not self.volumeUpdateBlocked: 157 | self.inputVolumeUpdate.start(self.getAlsaRecordHardwareString(), 158 | channel, self.mode) 159 | 160 | def on_setImpRespFiles(self, button): 161 | self.impRespDlg.run() 162 | 163 | def on_InputChanelChanged(self, combo): 164 | self.startInputVolumeUpdate(combo.get_active_text()) 165 | 166 | def getAlsaPlayHardwareString(self): 167 | alsHardwareSelIndex = self.alsaPlayHardwareCombo.get_active() 168 | alsaPlayHw="hw:0,0" 169 | if len(self.alsaDevices.alsaPlayDevs) > alsHardwareSelIndex: 170 | alsaPlayHw = self.alsaDevices.alsaPlayDevs[alsHardwareSelIndex].alsaHW 171 | else: 172 | print( "getAlsaPlayHardwareString:!!!!no recording device found!!!! : ", numAlsaRecDev, alsHardwareSelIndex ) 173 | 174 | return alsaPlayHw 175 | 176 | def getAlsaRecordHardwareString(self): 177 | alsHardwareSelIndex = int(self.alsaRecHardwareCombo.get_active()) 178 | alsaRecHw="hw:0,0" 179 | numAlsaRecDev = int(len(self.alsaDevices.alsaRecDevs)) 180 | if numAlsaRecDev > alsHardwareSelIndex: 181 | alsaRecHw = self.alsaDevices.alsaRecDevs[alsHardwareSelIndex].alsaHW 182 | else: 183 | print( "getAlsaRecordHardwareString:!!!!no recording device found!!!! : ", numAlsaRecDev, alsHardwareSelIndex ) 184 | return alsaRecHw 185 | 186 | def updateRecDeviceInfo(self): 187 | self.comboInputChanel.remove_all() 188 | self.volumeUpdateBlocked = True 189 | alsHardwareSelIndex = self.alsaRecHardwareCombo.get_active() 190 | currAlsaDev = "hw:0,0" 191 | if len(self.alsaDevices.alsaRecDevs) > alsHardwareSelIndex: 192 | currAlsaDev = self.alsaDevices.alsaRecDevs[alsHardwareSelIndex] 193 | currAlsaDev.loadDeviceInfo() 194 | for chanel in range(0, currAlsaDev.MaxChannel): 195 | self.comboInputChanel.append_text(str(chanel+1)) 196 | 197 | self.comboInputChanel.set_active(0) 198 | self.comboSampleRate.remove_all() 199 | all_rates = [44100,48000,96000,192000] 200 | for rate in all_rates: 201 | if rate >= currAlsaDev.MinRate and rate <= currAlsaDev.MaxRate: 202 | self.comboSampleRate.append_text(str(rate)) 203 | self.comboSampleRate.set_active(0) 204 | self.volumeUpdateBlocked = False 205 | else: 206 | print( "!!!!updateRecDeviceInfo:no recording device found!!!! : ", numAlsaRecDev, alsHardwareSelIndex ) 207 | 208 | 209 | def on_recDeviceChanged(self, combo): 210 | self.updateRecDeviceInfo() 211 | 212 | def on_cfgDRC(self, button): 213 | drcMethod = self.comboDRC.get_active_text() 214 | if drcMethod == "DRC": 215 | self.drcCfgDlg.run() 216 | else: 217 | self.porcCfgDlg.run() 218 | 219 | def on_DRCTypeChanged(self, combo): 220 | drcMethod = combo.get_active_text() 221 | if drcMethod == "DRC": 222 | self.cfgDRCButton.set_label("configure DRC") 223 | else: 224 | self.cfgDRCButton.set_label("configure PORC") 225 | drcScript = [DependsWrapperImpl.find_plugin_file(self.parent, "calcFilterDRC")] 226 | pluginPath = os.path.dirname(os.path.abspath(drcScript[0])) 227 | porcTargetCurve = pluginPath + "/porc/data/tact30f.txt" 228 | if not os.path.exists(porcTargetCurve): 229 | print("installing PORC") 230 | installScript = DependsWrapperImpl.find_plugin_file(self.parent, 231 | "installPORC.sh") 232 | pluginPath = os.path.dirname(installScript) 233 | porcInstCommand = "xterm -e " + installScript + " " + \ 234 | pluginPath 235 | subprocess.call(porcInstCommand, shell=True) 236 | 237 | def slider_changed(self, hscale): 238 | self.sweep_level = hscale.get_value() 239 | 240 | def set_filter(self): 241 | DrcFilename = self.filechooserbtn.get_filename() 242 | self.parent.updateFilter(DrcFilename) 243 | 244 | def on_file_selected(self, widget): 245 | filterFile = widget.get_filename() 246 | if os.path.isfile(filterFile): 247 | self.saveSettings() 248 | 249 | def saveSettings(self): 250 | aCfg = DRCConfig() 251 | aCfg.filterFile = self.filechooserbtn.get_filename() 252 | aCfg.recordGain = self.sweep_level 253 | aCfg.sweepDuration = int(self.entrySweepDuration.get_text()) 254 | aCfg.FIRFilterMode = self.comboboxFIRFilterMode.get_active() 255 | aCfg.playHardwareIndex = self.alsaPlayHardwareCombo.get_active() 256 | aCfg.recHardwareIndex = self.alsaRecHardwareCombo.get_active() 257 | aCfg.recHardwareChannelIndex = self.comboInputChanel.get_active() 258 | fileExt = os.path.splitext(aCfg.filterFile)[-1] 259 | print(("ext = " + fileExt)) 260 | if fileExt != ".wav": 261 | if self.channelSelDlg.run() == Gtk.ResponseType.OK: 262 | aCfg.numFilterChanels = self.channelSelDlg.getNumChannels() 263 | aCfg.save() 264 | 265 | def on_apply_settings(self, some_param): 266 | self.saveSettings() 267 | self.dlg.set_visible(False) 268 | 269 | def updateBruteFIRCfg(self, enable): 270 | updateBruteFIRScript = [DependsWrapperImpl.find_plugin_file(self.parent, "updateBruteFIRCfg")] 271 | if enable is True: 272 | self.comboboxFIRFilterMode.set_active(2) 273 | updateBruteFIRScript.append(self.getAlsaPlayHardwareString()) 274 | updateBruteFIRScript.append(self.filechooserbtn.get_filename()) 275 | print('create bruteFIRConfig and start/install bruteFIR') 276 | updateBruteFIRCommand = "xterm -e " + " ".join(updateBruteFIRScript) 277 | subprocess.call(updateBruteFIRCommand, shell=True) 278 | 279 | def on_applyFilterBruteFIR(self): 280 | self.updateBruteFIRCfg(True) 281 | self.saveSettings() 282 | self.set_filter() 283 | 284 | def on_applyFilterGST(self): 285 | self.comboboxFIRFilterMode.set_active(1) 286 | self.saveSettings() 287 | self.set_filter() 288 | self.updateBruteFIRCfg(False) 289 | 290 | def disableFiltering(self): 291 | self.comboboxFIRFilterMode.set_active(0) 292 | self.saveSettings() 293 | self.set_filter() 294 | self.updateBruteFIRCfg(False) 295 | 296 | def on_FIRFilterModeChanged(self, some_param): 297 | FIRFilterMode = self.comboboxFIRFilterMode.get_active() 298 | if FIRFilterMode is 0: 299 | self.disableFiltering() 300 | elif FIRFilterMode is 1: 301 | self.on_applyFilterGST() 302 | else: 303 | self.on_applyFilterBruteFIR() 304 | 305 | def getMeasureResultsDir(self): 306 | cachedir = RB.user_cache_dir() + "/DRC" 307 | measureResultsDir = cachedir + "/MeasureResults" 308 | if not os.path.exists(measureResultsDir): 309 | os.makedirs(measureResultsDir) 310 | return measureResultsDir 311 | 312 | def on_execMeasure(self, param): 313 | self.inputVolumeUpdate.stop() 314 | 315 | # TODO: make the measure script output the volume and parse from 316 | # there during measurement 317 | scriptName = DependsWrapperImpl.find_plugin_file(self.parent, "measure1Channel") 318 | #create new folder for this complete measurement 319 | strResultsDir = self.getMeasureResultsDir() + "/" +\ 320 | datetime.datetime.now().strftime("%Y%m%d%H%M%S_") + \ 321 | str(self.entrySweepDuration.get_text()) 322 | os.makedirs(strResultsDir) 323 | raw_sweep_file_base_name = "/tmp/msrawsweep.pcm" 324 | raw_sweep_recorded_base_name = "/tmp/msrecsweep0.pcm" 325 | evalDlg = MeasureQADlg(self.parent, raw_sweep_file_base_name, 326 | raw_sweep_recorded_base_name, self.sweep_level) 327 | iterLoopMeasure = 0 328 | acquiredImpResFiles = [] 329 | while(True): 330 | impOutputFile = strResultsDir + "/" + str(iterLoopMeasure) + ".wav" 331 | # execute measure script to generate filters 332 | commandLine = [scriptName, str(self.sweep_level), 333 | self.getAlsaRecordHardwareString(), 334 | self.getAlsaPlayHardwareString(), 335 | "10", 336 | "22050", 337 | str(self.entrySweepDuration.get_text()), 338 | impOutputFile, 339 | self.comboInputChanel.get_active_text(), 340 | str(self.exec_2ChannelMeasure.get_active()), 341 | str(int(self.spinbutton_NumChannels.get_value())), 342 | str(self.comboSampleRate.get_active_text())] 343 | p = subprocess.Popen(commandLine, 0, None, None, subprocess.PIPE, 344 | subprocess.PIPE) 345 | (out, err) = p.communicate() 346 | print(("output from measure script : " + str(out) + " error : " 347 | + str(None))) 348 | # quality check:sweep file and measured result 349 | evalDlg.setImpRespFileName(impOutputFile) 350 | evalDlg.run() 351 | iterLoopMeasure += 1 352 | if evalDlg.Result == MeasureQARetVal.Reject: 353 | continue 354 | acquiredImpResFiles.append(evalDlg.impRespFile) 355 | if evalDlg.Result == MeasureQARetVal.Done: 356 | break 357 | self.impRespDlg.removeAll() 358 | self.impRespDlg.setFiles(acquiredImpResFiles) 359 | self.notebook.next_page() 360 | 361 | def changeCfgParamDRC(self, bufferStr, changeArray): 362 | newBuff = bufferStr 363 | for i in range(0, len(changeArray)): 364 | changeParams = changeArray[i] 365 | searchStr = changeParams[0] + " = " 366 | paramStart = bufferStr.find(searchStr) 367 | if paramStart > -1: 368 | paramEnd = bufferStr.find("\n", paramStart) 369 | if paramEnd > -1: 370 | newBuff = bufferStr[0:paramStart + len(searchStr)] + \ 371 | changeParams[1] + bufferStr[ 372 | paramEnd:len(bufferStr)] 373 | bufferStr = newBuff 374 | return newBuff 375 | 376 | def getTmpCfgDir(self): 377 | cachedir = RB.user_cache_dir() + "/DRC" 378 | tmpCfgDir = cachedir + "/TmpDRCCfg" 379 | if not os.path.exists(tmpCfgDir): 380 | os.makedirs(tmpCfgDir) 381 | return tmpCfgDir 382 | 383 | def prepareDRC(self, impRespFile, filterResultFile, targetCurveFile): 384 | drcScript = [DependsWrapperImpl.find_plugin_file(self.parent, "calcFilterDRC")] 385 | drcCfgFileName = os.path.basename(self.drcCfgDlg.getBaseCfg()) 386 | print(("drcCfgBaseName : " + drcCfgFileName)) 387 | drcCfgSrcFile = self.drcCfgDlg.getBaseCfg() 388 | drcCfgDestFile = self.getTmpCfgDir() + "/" + drcCfgFileName 389 | drcScript.append(drcCfgDestFile) 390 | print(("drcCfgDestFile : " + drcCfgDestFile)) 391 | # update filter file 392 | srcDrcCfgFile = open(drcCfgSrcFile, "r") 393 | srcData = srcDrcCfgFile.read() 394 | micCalFile = self.drcCfgDlg.getMicCalibrationFile() 395 | normMethod = self.drcCfgDlg.getNormMethod() 396 | changeCfgFileArray = [["BCInFile", impRespFile], 397 | ["PSPointsFile", 398 | targetCurveFile], 399 | ["PSNormType", normMethod] 400 | ] 401 | if micCalFile is not None: 402 | changeCfgFileArray.append(["MCFilterType", "M"]) 403 | changeCfgFileArray.append(["MCPointsFile", micCalFile]) 404 | else: 405 | changeCfgFileArray.append(["MCFilterType", "N"]) 406 | destData = self.changeCfgParamDRC(srcData, changeCfgFileArray) 407 | destDrcCfgFile = open(drcCfgDestFile, "w") 408 | destDrcCfgFile.write(destData) 409 | destDrcCfgFile.close() 410 | return drcScript 411 | 412 | def showMsgBox(self, msg): 413 | dlg = Gtk.MessageDialog(self.dlg, Gtk.DialogFlags.MODAL, 414 | Gtk.MessageType.INFO, Gtk.ButtonsType.CLOSE, 415 | msg) 416 | dlg.run() 417 | dlg.destroy() 418 | 419 | def getFilterResultsDir(self): 420 | cachedir = RB.user_cache_dir() + "/DRC" 421 | filterResultsDir = cachedir + "/DRCFilters" 422 | if not os.path.exists(filterResultsDir): 423 | print( 424 | ("DRC cache dir does not exist : creating -> " + 425 | filterResultsDir)) 426 | os.makedirs(filterResultsDir) 427 | return filterResultsDir 428 | 429 | def getSampleShift(self, distanceInCentimeter): 430 | return int((1.2849 * distanceInCentimeter) + 0.5) 431 | 432 | def calculateAvgImpResponse(self, files): 433 | projectDir = os.path.dirname(os.path.abspath(files[0].fileName)) 434 | impOutputFile = projectDir + "/impOutputFile"\ 435 | + datetime.datetime.now().strftime("%Y%m%d%H%M%S_") + "avg.wav" 436 | firstFileParam = DRCFileTool.LoadWaveFile(files[0].fileName) 437 | maxValueStartOffset = min(firstFileParam.maxSampleValuePos[0], 438 | int(len(firstFileParam.data[0]) / 2)) 439 | maxValueEndOffset = int(maxValueStartOffset) 440 | avgImpulseLength = len(firstFileParam.data[0]) 441 | #loop over all impulse responses for all chanels and 442 | #calculate average response 443 | result = DRCFileTool.WaveParams() 444 | avgData = [] 445 | for currFileInfo in files: 446 | params = DRCFileTool.LoadWaveFile(currFileInfo.fileName) 447 | result = DRCFileTool.WaveParams(params.numChannels) 448 | for chanel in range(0, params.numChannels): 449 | if len(avgData) <= chanel: 450 | arr = [float(0.0)] * avgImpulseLength 451 | avgData.append(arr) 452 | impulseStart = params.maxSampleValuePos[chanel] - \ 453 | maxValueStartOffset + self.getSampleShift( 454 | currFileInfo.centerDistanceInCentimeter) 455 | print(("impulseStart:", impulseStart)) 456 | samplesUntilEnd = avgImpulseLength - impulseStart 457 | for index in range(0, samplesUntilEnd): 458 | avgValue = float(params.data[chanel][ 459 | impulseStart + index] * 460 | currFileInfo.weightingFactor) 461 | avgData[chanel][index] += avgValue 462 | #print(("avgData[chanel][index] : ", 463 | # avgData[chanel][index], 464 | # params.data[chanel][impulseStart + index])) 465 | #write the avg result to the result 466 | result.data = avgData 467 | print(("numChans Avg :", params.numChannels, result.numChannels, 468 | impOutputFile)) 469 | DRCFileTool.WriteWaveFile(result, impOutputFile) 470 | return impOutputFile 471 | 472 | def on_calculateDRC(self, param): 473 | drcMethod = self.comboDRC.get_active_text() 474 | drcScript = [DependsWrapperImpl.find_plugin_file(self.parent, "calcFilterDRC")] 475 | pluginPath = os.path.dirname(os.path.abspath(drcScript[0])) 476 | filterResultFile = self.getFilterResultsDir() + "/Filter" + str( 477 | drcMethod) + datetime.datetime.now().strftime( 478 | "%Y%m%d%H%M%S") + ".wav" 479 | impRespFiles = self.impRespDlg.getImpRespFiles() 480 | #get number of channels from impRespFiles and loop over 481 | numChannels = DRCFileTool.getNumChannels(impRespFiles[0].fileName) 482 | #go through all impRespFiles, average them and pass the 483 | #result to the impRespFile 484 | avgImpRespFile = self.calculateAvgImpResponse(impRespFiles) 485 | soxMergeCall = ["sox", "-M"] 486 | channelFilterFile = "" 487 | for currChannel in range(0, numChannels): 488 | channelFilterFile = "/tmp/filter" + str(currChannel) + ".wav" 489 | soxMergeCall.append(channelFilterFile) 490 | #get target curve filename per channel 491 | targetCurveFileName = self.targetCurveDlg.getTargetCurveFileName( 492 | currChannel) 493 | if avgImpRespFile is None: 494 | self.showMsgBox("no file loaded") 495 | return 496 | if drcMethod == "DRC": 497 | drcScript = self.prepareDRC(avgImpRespFile, channelFilterFile, 498 | targetCurveFileName) 499 | drcScript.append(avgImpRespFile) 500 | drcScript.append(channelFilterFile) 501 | drcScript.append(str(currChannel)) 502 | elif drcMethod == "PORC": 503 | drcScript = [DependsWrapperImpl.find_plugin_file(self.parent, "calcFilterPORC")] 504 | porcCommand = pluginPath + "/porc/porc.py" 505 | if not os.path.isfile(porcCommand): 506 | self.showMsgBox( 507 | "porc.py not found. Please download from github and " 508 | "install in the DRC plugin subfolder 'porc'") 509 | return 510 | drcScript.append(porcCommand) 511 | drcScript.append(avgImpRespFile) 512 | drcScript.append(channelFilterFile) 513 | drcScript.append(str(currChannel)) 514 | drcScript.append(targetCurveFileName) 515 | if self.porcCfgDlg.getMixedPhaseEnabled(): 516 | drcScript.append("--mixed") 517 | print(("drc command line: " + str(drcScript))) 518 | p = subprocess.Popen(drcScript, 0, None, None, subprocess.PIPE, 519 | subprocess.PIPE) 520 | (out, err) = p.communicate() 521 | print(("output from filter calculate script : " + str(out))) 522 | #use sox to merge all results to one filter file 523 | soxMergeCall.append(filterResultFile) 524 | p = subprocess.Popen(soxMergeCall, 0, None, None, subprocess.PIPE, 525 | subprocess.PIPE) 526 | print(("output from sox filter merge : " + str(out))) 527 | self.filechooserbtn.set_filename(filterResultFile) 528 | self.set_filter() 529 | self.notebook.next_page() 530 | 531 | def on_close(self, shell): 532 | print("closing ui") 533 | self.inputVolumeUpdate.stop() 534 | self.dlg.set_visible(False) 535 | return True 536 | 537 | def show_ui(self, shell, state, dummy): 538 | print("showing UI") 539 | self.initUI() 540 | self.startInputVolumeUpdate() 541 | if shell is None: 542 | self.dlg.run() 543 | else: 544 | self.dlg.show_all() 545 | self.dlg.present() 546 | self.inputVolumeUpdate.stop() 547 | print("done showing UI") 548 | 549 | def on_destroy(self, widget, data): 550 | self.on_close(None) 551 | return True 552 | 553 | def on_Cancel(self, some_param): 554 | self.dlg.set_visible(False) 555 | self.inputVolumeUpdate.stop() 556 | -------------------------------------------------------------------------------- /DRC_rb3compat.py: -------------------------------------------------------------------------------- 1 | # -*- Mode: python; coding: utf-8; tab-width: 4; indent-tabs-mode: nil; -*- 2 | # 3 | # IMPORTANT - WHILST THIS MODULE IS USED BY SEVERAL OTHER PLUGINS 4 | # THE MASTER AND MOST UP-TO-DATE IS FOUND IN THE COVERART BROWSER 5 | # PLUGIN - https://github.com/fossfreedom/coverart-browser 6 | # PLEASE SUBMIT CHANGES BACK TO HELP EXPAND THIS API 7 | # 8 | # Copyright (C) 2012-2015 - fossfreedom 9 | # 10 | # This program is free software; you can redistribute it and/or modify 11 | # it under the terms of the GNU General Public License as published by 12 | # the Free Software Foundation; either version 2, or (at your option) 13 | # any later version. 14 | # 15 | # This program is distributed in the hope that it will be useful, 16 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 17 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 18 | # GNU General Public License for more details. 19 | # 20 | # You should have received a copy of the GNU General Public License 21 | # along with this program; if not, write to the Free Software 22 | # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 23 | 24 | import sys 25 | import xml.etree.ElementTree as ET 26 | 27 | from gi.repository import Gtk 28 | from gi.repository import Gio 29 | from gi.repository import GLib 30 | from gi.repository import GObject 31 | from gi.repository import RB 32 | 33 | import rb 34 | 35 | 36 | def gtk_version(): 37 | """ 38 | returns float of the major and minor parts of the GTK version 39 | e.g. return float(3.10) 40 | """ 41 | 42 | return float(str(Gtk.get_major_version()) + "." + 43 | str(Gtk.get_minor_version())) 44 | 45 | 46 | def pygobject_version(): 47 | """ 48 | returns float of the major and minor parts of a pygobject version 49 | e.g. version (3, 9, 5) return float(3.9) 50 | """ 51 | to_number = lambda t: ".".join(str(v) for v in t) 52 | 53 | str_version = to_number(GObject.pygobject_version) 54 | 55 | return float(str_version.rsplit('.', 1)[0]) 56 | 57 | 58 | def compare_pygobject_version(version): 59 | """ 60 | return True if version is less than pygobject_version 61 | i.e. 3.9 < 3.11 62 | """ 63 | to_number = lambda t: ".".join(str(v) for v in t) 64 | 65 | str_version = to_number(GObject.pygobject_version) 66 | 67 | split = str_version.rsplit('.', 2) 68 | split_compare = version.rsplit('.', 2) 69 | 70 | if int(split_compare[0]) < int(split[0]): 71 | return True 72 | 73 | if int(split_compare[1]) < int(split[1]): 74 | return True 75 | 76 | return False 77 | 78 | 79 | PYVER = sys.version_info[0] 80 | 81 | if PYVER >= 3: 82 | import urllib.request 83 | import urllib.parse 84 | import urllib.error 85 | else: 86 | import urllib 87 | from urlparse import urlparse as rb2urlparse 88 | 89 | if PYVER >= 3: 90 | import http.client 91 | # pyflakes doesnt like python2 unicode so lets give it something 92 | # to chew on 93 | 94 | def unicode(a, b): 95 | return (a, b) 96 | 97 | else: 98 | import httplib 99 | 100 | 101 | def responses(): 102 | if PYVER >= 3: 103 | return http.client.responses 104 | else: 105 | return httplib.responses 106 | 107 | 108 | def unicodestr(param, charset): 109 | if PYVER >= 3: 110 | return param # str(param, charset) 111 | else: 112 | return unicode(param, charset) 113 | 114 | 115 | def unicodeencode(param, charset): 116 | if PYVER >= 3: 117 | return param # str(param).encode(charset) 118 | else: 119 | return unicode(param).encode(charset) 120 | 121 | 122 | def unicodedecode(param, charset): 123 | if PYVER >= 3: 124 | return param 125 | else: 126 | return param.decode(charset) 127 | 128 | 129 | def urlparse(uri): 130 | if PYVER >= 3: 131 | return urllib.parse.urlparse(uri) 132 | else: 133 | return rb2urlparse(uri) 134 | 135 | 136 | def url2pathname(url): 137 | if PYVER >= 3: 138 | return urllib.request.url2pathname(url) 139 | else: 140 | return urllib.url2pathname(url) 141 | 142 | 143 | def urlopen(filename): 144 | if PYVER >= 3: 145 | return urllib.request.urlopen(filename) 146 | else: 147 | return urllib.urlopen(filename) 148 | 149 | 150 | def pathname2url(filename): 151 | if PYVER >= 3: 152 | return urllib.request.pathname2url(filename) 153 | else: 154 | return urllib.pathname2url(filename) 155 | 156 | 157 | def unquote(uri): 158 | if PYVER >= 3: 159 | return urllib.parse.unquote(uri) 160 | else: 161 | return urllib.unquote(uri) 162 | 163 | 164 | def quote(uri, safe=None): 165 | if PYVER >= 3: 166 | if safe: 167 | return urllib.parse.quote(uri, safe=safe) 168 | else: 169 | return urllib.parse.quote(uri) 170 | else: 171 | if safe: 172 | return urllib.quote(uri, safe=safe) 173 | else: 174 | return urllib.quote(uri) 175 | 176 | 177 | def quote_plus(uri): 178 | if PYVER >= 3: 179 | return urllib.parse.quote_plus(uri) 180 | else: 181 | return urllib.quote_plus(uri) 182 | 183 | 184 | def is_rb3(*args): 185 | if hasattr(RB.Shell.props, 'ui_manager'): 186 | return False 187 | else: 188 | return True 189 | 190 | 191 | class Menu(GObject.Object): 192 | """ 193 | Menu object used to create window popup menus 194 | """ 195 | __gsignals__ = { 196 | 'pre-popup': (GObject.SIGNAL_RUN_LAST, None, ()) 197 | } 198 | 199 | def __init__(self, plugin, shell): 200 | """ 201 | Initializes the menu. 202 | """ 203 | super(Menu, self).__init__() 204 | self.plugin = plugin 205 | self.shell = shell 206 | self._unique_num = 0 207 | 208 | self._rbmenu_items = {} 209 | self._rbmenu_objects = {} 210 | 211 | def add_menu_item(self, menubar, section_name, action): 212 | """ 213 | add a new menu item to the popup 214 | :param menubar: `str` is the name GtkMenu (or ignored for RB2.99+) 215 | :param section_name: `str` is the name of the section to add the item 216 | to (RB2.99+) 217 | :param action: `Action` to associate with the menu item 218 | """ 219 | return self.insert_menu_item(menubar, section_name, -1, action) 220 | 221 | def insert_menu_item(self, menubar, section_name, position, action): 222 | """ 223 | add a new menu item to the popup 224 | :param menubar: `str` is the name GtkMenu (or ignored for RB2.99+) 225 | :param section_name: `str` is the name of the section to add the item 226 | to (RB2.99+) 227 | :param position: `int` position to add to GtkMenu (ignored for RB2.99+) 228 | :param action: `Action` to associate with the menu item 229 | """ 230 | label = action.label 231 | 232 | if is_rb3(self.shell): 233 | app = self.shell.props.application 234 | item = Gio.MenuItem() 235 | action.associate_menuitem(item) 236 | item.set_label(label) 237 | 238 | if not section_name in self._rbmenu_items: 239 | self._rbmenu_items[section_name] = [] 240 | self._rbmenu_items[section_name].append(label) 241 | 242 | app.add_plugin_menu_item(section_name, label, item) 243 | else: 244 | item = Gtk.MenuItem(label=label) 245 | action.associate_menuitem(item) 246 | self._rbmenu_items[label] = item 247 | bar = self.get_menu_object(menubar) 248 | 249 | if position == -1: 250 | bar.append(item) 251 | else: 252 | bar.insert(item, position) 253 | bar.show_all() 254 | uim = self.shell.props.ui_manager 255 | uim.ensure_update() 256 | 257 | return item 258 | 259 | def insert_separator(self, menubar, at_position): 260 | """ 261 | add a separator to the popup (only required for RB2.98 and earlier) 262 | :param menubar: `str` is the name GtkMenu (or ignored for RB2.99+) 263 | :param position: `int` position to add to GtkMenu (ignored for RB2.99+) 264 | """ 265 | if not is_rb3(self.shell): 266 | menu_item = Gtk.SeparatorMenuItem().new() 267 | menu_item.set_visible(True) 268 | self._rbmenu_items['separator' + str(self._unique_num)] = menu_item 269 | self._unique_num = self._unique_num + 1 270 | bar = self.get_menu_object(menubar) 271 | bar.insert(menu_item, at_position) 272 | bar.show_all() 273 | uim = self.shell.props.ui_manager 274 | uim.ensure_update() 275 | 276 | def remove_menu_items(self, menubar, section_name): 277 | """ 278 | utility function to remove all menuitems associated with the menu 279 | section 280 | :param menubar: `str` is the name of the GtkMenu containing the menu 281 | items (ignored for RB2.99+) 282 | :param section_name: `str` is the name of the section containing the 283 | menu items (for RB2.99+ only) 284 | """ 285 | if is_rb3(self.shell): 286 | if not section_name in self._rbmenu_items: 287 | return 288 | 289 | app = self.shell.props.application 290 | 291 | for menu_item in self._rbmenu_items[section_name]: 292 | app.remove_plugin_menu_item(section_name, menu_item) 293 | 294 | if self._rbmenu_items[section_name]: 295 | del self._rbmenu_items[section_name][:] 296 | 297 | else: 298 | 299 | if not self._rbmenu_items: 300 | return 301 | 302 | uim = self.shell.props.ui_manager 303 | bar = self.get_menu_object(menubar) 304 | 305 | for menu_item in self._rbmenu_items: 306 | bar.remove(self._rbmenu_items[menu_item]) 307 | 308 | bar.show_all() 309 | uim.ensure_update() 310 | 311 | def load_from_file(self, rb2_ui_filename, rb3_ui_filename): 312 | """ 313 | utility function to load the menu structure 314 | :param rb2_ui_filename: `str` RB2.98 and below UI file 315 | :param rb3_ui_filename: `str` RB2.99 and higher UI file 316 | """ 317 | self.builder = Gtk.Builder() 318 | try: 319 | from coverart_browser_prefs import CoverLocale 320 | 321 | cl = CoverLocale() 322 | 323 | self.builder.set_translation_domain(cl.Locale.LOCALE_DOMAIN) 324 | except: 325 | pass 326 | 327 | if is_rb3(self.shell): 328 | ui_filename = rb3_ui_filename 329 | else: 330 | ui_filename = rb2_ui_filename 331 | 332 | self.ui_filename = ui_filename 333 | 334 | self.builder.add_from_file(rb.find_plugin_file(self.plugin, 335 | ui_filename)) 336 | 337 | def _connect_rb3_signals(self, signals): 338 | def _menu_connect(action_name, func): 339 | action = Gio.SimpleAction(name=action_name) 340 | action.connect('activate', func) 341 | action.set_enabled(True) 342 | self.shell.props.window.add_action(action) 343 | 344 | for key, value in signals.items(): 345 | _menu_connect(key, value) 346 | 347 | def _connect_rb2_signals(self, signals): 348 | def _menu_connect(menu_item_name, func): 349 | menu_item = self.get_menu_object(menu_item_name) 350 | menu_item.connect('activate', func) 351 | 352 | for key, value in signals.items(): 353 | _menu_connect(key, value) 354 | 355 | def connect_signals(self, signals): 356 | """ 357 | connect all signal handlers with their menuitem counterparts 358 | :param signals: `dict` key is the name of the menuitem 359 | and value is the function callback when the menu is activated 360 | """ 361 | if is_rb3(self.shell): 362 | self._connect_rb3_signals(signals) 363 | else: 364 | self._connect_rb2_signals(signals) 365 | 366 | def get_gtkmenu(self, source, popup_name): 367 | """ 368 | utility function to obtain the GtkMenu from the menu UI file 369 | :param popup_name: `str` is the name menu-id in the UI file 370 | """ 371 | if popup_name in self._rbmenu_objects: 372 | return self._rbmenu_objects[popup_name] 373 | item = self.builder.get_object(popup_name) 374 | 375 | if is_rb3(self.shell): 376 | app = self.shell.props.application 377 | app.link_shared_menus(item) 378 | popup_menu = Gtk.Menu.new_from_model(item) 379 | popup_menu.attach_to_widget(source, None) 380 | else: 381 | popup_menu = item 382 | 383 | self._rbmenu_objects[popup_name] = popup_menu 384 | 385 | return popup_menu 386 | 387 | def get_menu_object(self, menu_name_or_link): 388 | """ 389 | utility function returns the GtkMenuItem/Gio.MenuItem 390 | :param menu_name_or_link: `str` to search for in the UI file 391 | """ 392 | if menu_name_or_link in self._rbmenu_objects: 393 | return self._rbmenu_objects[menu_name_or_link] 394 | item = self.builder.get_object(menu_name_or_link) 395 | if is_rb3(self.shell): 396 | if item: 397 | popup_menu = item 398 | else: 399 | app = self.shell.props.application 400 | popup_menu = app.get_plugin_menu(menu_name_or_link) 401 | else: 402 | popup_menu = item 403 | print(menu_name_or_link) 404 | self._rbmenu_objects[menu_name_or_link] = popup_menu 405 | 406 | return popup_menu 407 | 408 | def set_sensitive(self, menu_or_action_item, enable): 409 | """ 410 | utility function to enable/disable a menu-item 411 | :param menu_or_action_item: `GtkMenuItem` or `Gio.SimpleAction` 412 | that is to be enabled/disabled 413 | :param enable: `bool` value to enable/disable 414 | """ 415 | 416 | if is_rb3(self.shell): 417 | item = self.shell.props.window.lookup_action(menu_or_action_item) 418 | item.set_enabled(enable) 419 | else: 420 | item = self.get_menu_object(menu_or_action_item) 421 | item.set_sensitive(enable) 422 | 423 | def popup(self, source, menu_name, button, time): 424 | """ 425 | utility function to show the popup menu 426 | """ 427 | self.emit('pre-popup') 428 | menu = self.get_gtkmenu(source, menu_name) 429 | menu.popup(None, None, None, None, button, time) 430 | 431 | 432 | class ActionGroup(object): 433 | """ 434 | container for all Actions used to associate with menu items 435 | """ 436 | 437 | # action_state 438 | STANDARD = 0 439 | TOGGLE = 1 440 | 441 | def __init__(self, shell, group_name): 442 | """ 443 | constructor 444 | :param shell: `RBShell` 445 | :param group_name: `str` unique name for the object to create 446 | """ 447 | self.group_name = group_name 448 | self.shell = shell 449 | 450 | self._actions = {} 451 | 452 | if is_rb3(self.shell): 453 | self.actiongroup = Gio.SimpleActionGroup() 454 | else: 455 | self.actiongroup = Gtk.ActionGroup(group_name) 456 | uim = self.shell.props.ui_manager 457 | uim.insert_action_group(self.actiongroup) 458 | 459 | @property 460 | def name(self): 461 | return self.group_name 462 | 463 | def remove_actions(self): 464 | """ 465 | utility function to remove all actions associated with the ActionGroup 466 | """ 467 | for action in self.actiongroup.list_actions(): 468 | self.actiongroup.remove_action(action) 469 | 470 | def get_action(self, action_name): 471 | """ 472 | utility function to obtain the Action from the ActionGroup 473 | 474 | :param action_name: `str` is the Action unique name 475 | """ 476 | return self._actions[action_name] 477 | 478 | def add_action_with_accel(self, func, action_name, accel, **args): 479 | """ 480 | Creates an Action with an accelerator and adds it to the ActionGroup 481 | 482 | :param func: function callback used when user activates the action 483 | :param action_name: `str` unique name to associate with an action 484 | :param accel: `str` accelerator 485 | :param args: dict of arguments - this is passed to the function 486 | callback 487 | 488 | Notes: 489 | see notes for add_action 490 | """ 491 | args['accel'] = accel 492 | return self.add_action(func, action_name, **args) 493 | 494 | def add_action(self, func, action_name, **args): 495 | """ 496 | Creates an Action and adds it to the ActionGroup 497 | 498 | :param func: function callback used when user activates the action 499 | :param action_name: `str` unique name to associate with an action 500 | :param args: dict of arguments - this is passed to the function 501 | callback 502 | 503 | Notes: 504 | key value of "label" is the visual menu label to display 505 | key value of "action_type" is the RB2.99 Gio.Action type 506 | ("win" or "app") by default it assumes all actions are "win" type 507 | key value of "action_state" determines what action state to create 508 | """ 509 | if 'label' in args: 510 | label = args['label'] 511 | else: 512 | label = action_name 513 | 514 | if 'accel' in args: 515 | accel = args['accel'] 516 | else: 517 | accel = None 518 | 519 | state = ActionGroup.STANDARD 520 | if 'action_state' in args: 521 | state = args['action_state'] 522 | 523 | if is_rb3(self.shell): 524 | if state == ActionGroup.TOGGLE: 525 | action = Gio.SimpleAction.new_stateful(action_name, None, 526 | GLib.Variant('b', 527 | False)) 528 | else: 529 | action = Gio.SimpleAction.new(action_name, None) 530 | 531 | action_type = 'win' 532 | if 'action_type' in args: 533 | if args['action_type'] == 'app': 534 | action_type = 'app' 535 | 536 | app = Gio.Application.get_default() 537 | 538 | if action_type == 'app': 539 | app.add_action(action) 540 | else: 541 | self.shell.props.window.add_action(action) 542 | self.actiongroup.add_action(action) 543 | 544 | if accel: 545 | app.add_accelerator(accel, action_type + "." + action_name, 546 | None) 547 | else: 548 | if 'stock_id' in args: 549 | stock_id = args['stock_id'] 550 | else: 551 | stock_id = Gtk.STOCK_CLEAR 552 | 553 | if state == ActionGroup.TOGGLE: 554 | action = Gtk.ToggleAction(label=label, 555 | name=action_name, 556 | tooltip='', stock_id=stock_id) 557 | else: 558 | action = Gtk.Action(label=label, 559 | name=action_name, 560 | tooltip='', stock_id=stock_id) 561 | 562 | if accel: 563 | self.actiongroup.add_action_with_accel(action, accel) 564 | else: 565 | self.actiongroup.add_action(action) 566 | 567 | act = Action(self.shell, action) 568 | act.connect('activate', func, args) 569 | 570 | act.label = label 571 | act.accel = accel 572 | 573 | self._actions[action_name] = act 574 | 575 | return act 576 | 577 | 578 | class ApplicationShell(object): 579 | """ 580 | Unique class that mirrors RB.Application & RB.Shell menu functionality 581 | """ 582 | # storage for the instance reference 583 | __instance = None 584 | 585 | class __impl: 586 | """ Implementation of the singleton interface """ 587 | 588 | def __init__(self, shell): 589 | self.shell = shell 590 | 591 | if is_rb3(self.shell): 592 | self._uids = {} 593 | else: 594 | self._uids = [] 595 | 596 | self._action_groups = {} 597 | 598 | def insert_action_group(self, action_group): 599 | """ 600 | Adds an ActionGroup to the ApplicationShell 601 | 602 | :param action_group: `ActionGroup` to add 603 | """ 604 | self._action_groups[action_group.name] = action_group 605 | 606 | def lookup_action(self, action_group_name, action_name, 607 | action_type='app'): 608 | """ 609 | looks up (finds) an action created by another plugin. 610 | If found returns an Action or None if no matching Action. 611 | 612 | :param action_group_name: `str` is the Gtk.ActionGroup name 613 | (ignored for RB2.99+) 614 | :param action_name: `str` unique name for the action to look for 615 | :param action_type: `str` RB2.99+ action type ("win" or "app") 616 | """ 617 | 618 | if is_rb3(self.shell): 619 | if action_type == "app": 620 | action = \ 621 | self.shell.props.application.lookup_action(action_name) 622 | else: 623 | action = self.shell.props.window.lookup_action(action_name) 624 | else: 625 | uim = self.shell.props.ui_manager 626 | ui_actiongroups = uim.get_action_groups() 627 | 628 | actiongroup = None 629 | for actiongroup in ui_actiongroups: 630 | if actiongroup.get_name() == action_group_name: 631 | break 632 | 633 | action = None 634 | if actiongroup: 635 | action = actiongroup.get_action(action_name) 636 | 637 | if action: 638 | return Action(self.shell, action) 639 | else: 640 | return None 641 | 642 | def add_app_menuitems(self, ui_string, group_name, menu='tools'): 643 | """ 644 | utility function to add application menu items. 645 | 646 | For RB2.99 all application menu items are added to the "tools" 647 | section of the application menu. All Actions are assumed to be of 648 | action_type "app". 649 | 650 | For RB2.98 or less, it is added however the UI_MANAGER string 651 | is defined. 652 | 653 | :param ui_string: `str` is the Gtk UI definition. There is not an 654 | equivalent UI definition in RB2.99 but we can parse out menu items 655 | since this string is in XML format 656 | 657 | :param group_name: `str` unique name of the ActionGroup to add menu 658 | items to 659 | :param menu: `str` RB2.99 menu section to add to - nominally either 660 | 'tools' or 'view' 661 | """ 662 | if is_rb3(self.shell): 663 | root = ET.fromstring(ui_string) 664 | for elem in root.findall(".//menuitem"): 665 | action_name = elem.attrib['action'] 666 | 667 | group = self._action_groups[group_name] 668 | act = group.get_action(action_name) 669 | 670 | item = Gio.MenuItem() 671 | item.set_detailed_action('app.' + action_name) 672 | item.set_label(act.label) 673 | item.set_attribute_value("accel", GLib.Variant("s", 674 | act.accel)) 675 | app = Gio.Application.get_default() 676 | index = menu + action_name 677 | app.add_plugin_menu_item(menu, 678 | index, item) 679 | self._uids[index] = menu 680 | else: 681 | uim = self.shell.props.ui_manager 682 | self._uids.append(uim.add_ui_from_string(ui_string)) 683 | uim.ensure_update() 684 | 685 | def add_browser_menuitems(self, ui_string, group_name): 686 | """ 687 | utility function to add popup menu items to existing browser popups 688 | 689 | For RB2.99 all menu items are are assumed to be of action_type 690 | "win". 691 | 692 | For RB2.98 or less, it is added however the UI_MANAGER string 693 | is defined. 694 | 695 | :param ui_string: `str` is the Gtk UI definition. There is not an 696 | equivalent UI definition in RB2.99 but we can parse out menu items 697 | since this string is in XML format 698 | 699 | :param group_name: `str` unique name of the ActionGroup to add menu 700 | items to 701 | """ 702 | if is_rb3(self.shell): 703 | root = ET.fromstring(ui_string) 704 | for elem in root.findall("./popup"): 705 | popup_name = elem.attrib['name'] 706 | 707 | menuelem = elem.find('.//menuitem') 708 | action_name = menuelem.attrib['action'] 709 | 710 | group = self._action_groups[group_name] 711 | act = group.get_action(action_name) 712 | 713 | item = Gio.MenuItem() 714 | item.set_detailed_action('win.' + action_name) 715 | item.set_label(act.label) 716 | app = Gio.Application.get_default() 717 | 718 | if popup_name == 'QueuePlaylistViewPopup': 719 | plugin_type = 'queue-popup' 720 | elif popup_name == 'BrowserSourceViewPopup': 721 | plugin_type = 'browser-popup' 722 | elif popup_name == 'PlaylistViewPopup': 723 | plugin_type = 'playlist-popup' 724 | elif popup_name == 'PodcastViewPopup': 725 | plugin_type = 'podcast-episode-popup' 726 | else: 727 | print("unknown type %s" % plugin_type) 728 | 729 | index = plugin_type + action_name 730 | app.add_plugin_menu_item(plugin_type, index, item) 731 | self._uids[index] = plugin_type 732 | else: 733 | uim = self.shell.props.ui_manager 734 | self._uids.append(uim.add_ui_from_string(ui_string)) 735 | uim.ensure_update() 736 | 737 | def cleanup(self): 738 | """ 739 | utility remove any menuitems created. 740 | """ 741 | if is_rb3(self.shell): 742 | for uid in self._uids: 743 | Gio.Application.get_default().remove_plugin_menu_item( 744 | self._uids[uid], uid) 745 | else: 746 | uim = self.shell.props.ui_manager 747 | for uid in self._uids: 748 | uim.remove_ui(uid) 749 | uim.ensure_update() 750 | 751 | def __init__(self, shell): 752 | """ Create singleton instance """ 753 | # Check whether we already have an instance 754 | if ApplicationShell.__instance is None: 755 | # Create and remember instance 756 | ApplicationShell.__instance = ApplicationShell.__impl(shell) 757 | 758 | # Store instance reference as the only member in the handle 759 | self.__dict__['_ApplicationShell__instance'] = \ 760 | ApplicationShell.__instance 761 | 762 | def __getattr__(self, attr): 763 | """ Delegate access to implementation """ 764 | return getattr(self.__instance, attr) 765 | 766 | def __setattr__(self, attr, value): 767 | """ Delegate access to implementation """ 768 | return setattr(self.__instance, attr, value) 769 | 770 | 771 | class Action(object): 772 | """ 773 | class that wraps around either a Gio.Action or a Gtk.Action 774 | """ 775 | 776 | def __init__(self, shell, action): 777 | """ 778 | constructor. 779 | 780 | :param shell: `RBShell` 781 | :param action: `Gio.Action` or `Gtk.Action` 782 | """ 783 | self.shell = shell 784 | self.action = action 785 | 786 | self._label = '' 787 | self._accel = '' 788 | self._current_state = False 789 | self._do_update_state = True 790 | 791 | def connect(self, address, func, args): 792 | self._connect_func = func 793 | self._connect_args = args 794 | 795 | if address == 'activate': 796 | func = self._activate 797 | 798 | if is_rb3(self.shell): 799 | self.action.connect(address, func, args) 800 | else: 801 | self.action.connect(address, func, None, args) 802 | 803 | def _activate(self, action, *args): 804 | if self._do_update_state: 805 | self._current_state = not self._current_state 806 | self.set_state(self._current_state) 807 | 808 | self._connect_func(action, None, self._connect_args) 809 | 810 | @property 811 | def label(self): 812 | """ 813 | get the menu label associated with the Action 814 | 815 | for RB2.99+ actions dont have menu labels so this is managed 816 | manually 817 | """ 818 | if not is_rb3(self.shell): 819 | return self.action.get_label() 820 | else: 821 | return self._label 822 | 823 | @label.setter 824 | def label(self, new_label): 825 | if not is_rb3(self.shell): 826 | self.action.set_label(new_label) 827 | 828 | self._label = new_label 829 | 830 | @property 831 | def accel(self): 832 | """ 833 | get the accelerator associated with the Action 834 | """ 835 | return self._accel 836 | 837 | @accel.setter 838 | def accel(self, new_accelerator): 839 | if new_accelerator: 840 | self._accel = new_accelerator 841 | else: 842 | self._accel = '' 843 | 844 | def get_sensitive(self): 845 | """ 846 | get the sensitivity (enabled/disabled) state of the Action 847 | 848 | returns boolean 849 | """ 850 | if is_rb3(self.shell): 851 | return self.action.get_enabled() 852 | else: 853 | return self.action.get_sensitive() 854 | 855 | def set_state(self, value): 856 | """ 857 | set the state of a stateful action - this is applicable only 858 | to RB2.99+ 859 | """ 860 | if is_rb3(self.shell) and self.action.props.state_type: 861 | self.action.change_state(GLib.Variant('b', value)) 862 | 863 | def activate(self): 864 | """ 865 | invokes the activate signal for the action 866 | """ 867 | if is_rb3(self.shell): 868 | self.action.activate(None) 869 | else: 870 | self.action.activate() 871 | 872 | def set_active(self, value): 873 | """ 874 | activate or deactivate a stateful action signal 875 | For consistency with earlier RB versions, this will fire the 876 | activate signal for the action 877 | 878 | :param value: `boolean` state value 879 | """ 880 | 881 | if is_rb3(self.shell): 882 | self.action.change_state(GLib.Variant('b', value)) 883 | self._current_state = value 884 | self._do_update_state = False 885 | self.activate() 886 | self._do_update_state = True 887 | else: 888 | self.action.set_active(value) 889 | 890 | def get_active(self): 891 | """ 892 | get the state of the action 893 | 894 | returns `boolean` state value 895 | """ 896 | if is_rb3(self.shell): 897 | returnval = self._current_state 898 | else: 899 | returnval = self.action.get_active() 900 | 901 | return returnval 902 | 903 | def associate_menuitem(self, menuitem): 904 | """ 905 | links a menu with the action 906 | 907 | """ 908 | if is_rb3(self.shell): 909 | menuitem.set_detailed_action('win.' + self.action.get_name()) 910 | else: 911 | menuitem.set_related_action(self.action) 912 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. {http://fsf.org/} 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | --------------------------------------------------------------------------------