def test_test_wav_xscope(): #create test noise file. Note we round to a frame because test_wav_xscope can only handle full frames length_rounded_to_frame = round( (float(TEST_LEN_SECONDS) * 16000.0 / 240.0)) * 240 / 16000 print(f"Generating a {length_rounded_to_frame}s test file") filenames = [] for ch in range(4): filename = f"noise_ch{ch}.wav" filenames.append(filename) sh.sox( f"-n -c 1 -b 32 -r 16000 -e signed-integer {filename} synth {length_rounded_to_frame} whitenoise vol 1.0" .split()) sh.sox(f"-M {' '.join(filenames)} {input_file} remix 1 2 3 4".split()) for filename in filenames: os.remove(filename) print(f"acquire") with xtagctl.acquire("XCORE-AI-EXPLORER") as adapter_id: print(f"Running on {adapter_id}") xscope_fileio.run_on_target(adapter_id, test_wav_exe) in_rate, in_wav_data = scipy.io.wavfile.read(input_file, 'r') out_rate, out_wav_data = scipy.io.wavfile.read(output_file, 'r') assert (in_rate == out_rate) print(in_wav_data.shape, out_wav_data.shape) if not np.array_equal(in_wav_data, out_wav_data): for idx in range(256): print(in_wav_data[idx], out_wav_data[idx]) assert 0 print("TEST PASSED")
def convertSample(file_name): info = file_info(file_name).replace(file_name + ': ', '') if regexMatch('Audio file with', info): info = info.replace('Audio file with ', '') else: aac_match = regexMatch("ISO Media, Apple iTunes (.*)", info) if aac_match: encoding = aac_match.group(1) print("!! Error: Unsupported Apple audio encoding:", encoding) rm(file_name) return None print("!! Error: Downloaded 'audio' file", "'"+file_name+"'", "with attributes:") print(" ", info) return None mp3_match = regexMatch("ID3 version (.*) contains:(.*)", info) if mp3_match: id3_version, encoding = mp3_match.groups() new_file_name = file_name.replace('.unknown', '.mp3') elif False: new_file_name = '' else: print("!! Error: Unrecognized audio container:", info) return None mv(file_name, new_file_name) flac_file_name = file_name.replace('.unknown', '.flac') sox(new_file_name, flac_file_name) rm(new_file_name) return flac_file_name
def end_recording(self): self.process.terminate() if platform == "darwin": try: # see sh module issue 399 self.process.wait() except sh.SignalException_SIGTERM: pass # xplay leaves the header unpopulated on terminate so fix it sh.sox(f"--ignore-length {self.record_file} {self.tmp_wav_file}". split()) capture_len = float(sh.soxi(f"-D {self.tmp_wav_file}".split())) assert capture_len > ( self.start_trim_s + self.end_trim_s ), f"Not enough recorded audio: {capture_len}s, {self.start_trim_s + self.end_trim_s}s needed" sh.sox( f"{self.tmp_wav_file} {self.record_file} trim {self.start_trim_s} {-self.end_trim_s}" .split())
def postprocess(recording): tmpdir = recording.tmpfolder curdir = os.getcwd() try: print "Changing dir to %s" % tmpdir os.chdir(tmpdir) committed = recording.song.blob.committed() sox("-m", "audio.wav", "-t", "mp3", "-v", "0.15", committed, "mixed.wav") ffmpeg("-i", "mixed.wav", "-f", "image2", "-r", "1", "-i", "frame%d.png", "-acodec", "libvorbis", "video.ogv") recording.blob = Blob() with recording.blob.open("w") as saveto: with open("video.ogv") as savefrom: shutil.copyfileobj(savefrom, saveto) print "%s/%s" % (tmpdir, "video.ogv") # shutil.rmtree(tmpdir) transaction.commit() finally: os.chdir(curdir)
def execute(working_dir: str, frequency: str, duration: timedelta, sh=sh): signal_path = os.path.join(working_dir, "signal.wav") product_path = os.path.join(working_dir, "product.png") normalized_signal_path = os.path.join(working_dir, "normalized_signal.wav") qpsk_path = os.path.join(working_dir, "qpsk") dump_prefix_path = os.path.join(working_dir, "dump") dump_path = dump_prefix_path + ".dec" product_raw_prefix_path = os.path.join(working_dir, "product_raw") product_raw_path = product_raw_prefix_path + ".bmp" # Record signal fm_proc = sh.rtl_fm( # Modulation raw "-M", "raw", # Set frequency (in Hz, e.g. 137MHz) "-f", frequency, # Enable bias-T "-T", # Specify sampling rate (e.g. 48000 Hz) "-s", 48000, # Almost maximal possible value. Probably is wrong for other SDR then rtl-sdr "-g", 48, # Copy-paste from suspects www "-p", 1, _timeout=duration.total_seconds(), _timeout_signal=signal.SIGTERM, _piped=True ) with suppress(sh.TimeoutException): sh.sox(fm_proc, # Type of input "-t", "raw", "-r", "288k", # Channels - 2 - stereo "-c", 2, # Sample size "-b", 16, # Signed integer encoding "-e", "s", # Verbosity level (0 - silence, 1 - failure messages, 2 - warnings, 3 - processing phases, 4 - debug) "-V3", # Read from stdin (from pipe) "-", # Type of output "-t", "wav", signal_path, # Resampling rate "rate", "96k" ) # Normalize signal sh.sox( signal_path, normalized_signal_path, # Normalize to 0dBfs "gain", "-n" ) # Demodulating sh.meteor_demod( sh.yes(_piped=True), "-o", qpsk_path, "-B", normalized_signal_path ) # Keep original file timestamp sh.touch("-r", signal_path, qpsk_path) # Decode QPSK sh.medet( qpsk_path, dump_prefix_path, # Make doceded dump (fastest) "-cd" ) # Generate images sh.medet(dump_path, product_raw_prefix_path, # APID for red "-r", 66, # APID for green "-g", 65, # APID for blue "-b", 64, # Use dump "-d" ) # Convert to PNG sh.convert(product_raw_path, product_path) return [ ("SIGNAL", signal_path), ("PRODUCT", product_path) ]
def execute(working_dir: str, frequency: str, duration: timedelta, sh=sh): raw_path = os.path.join(working_dir, "signal.raw") signal_path = os.path.join(working_dir, "signal.wav") product_path = os.path.join(working_dir, "product.png") log_path = os.path.join(working_dir, "session.log") sample_rate = 48000 # Let's log the operations done by the tools to a log file. We need to flush it # frequently, because this file stream is also used capture tools output. Without # flush, the logging order gets completely messed up. logfile = open(log_path, "w") logfile.write("---rtl_fm log-------\n") logfile.flush() # Run rtl_fm/rx_fm - this records the actual samples from the RTL device with suppress(sh.TimeoutException): sh.rtl_fm( # Specify frequency (in Hz, e.g. 137MHz) "-f", frequency, # Specify sampling rate (e.g. 48000 Hz) "-s", sample_rate, # Maximal possible value. Probably is wrong for other SDR then rtl-sdr "-g", 49.6, # Copy-paste from suspects www "-p", 1, # Higher quality downsampling - possible value 0 or 9. 9 is experimental. "-F", 9, # Enable bias-T "-T", # How arctan is computed. We don't test other options. "-A", "fast", # dc blocking filter (?) "-E", "DC", # Output to pipe, optional in this command raw_path, _timeout=duration.total_seconds(), _timeout_signal=signal.SIGTERM, # rtl_fm and rx_fm both print messages on stderr _err=logfile) logfile.flush() logfile.write("---sox log-------\n") logfile.flush() # Run sox - this convert raw samples into audible WAV sh.sox( # Type of input "-t", "raw", # Sample size in bits "-b16", # Signed integer encoding "-es", "-r", sample_rate, # Number of channels of audio data - 1 - mono "-c1", # Verbosity level (0 - silence, 1 - failure messages, 2 - warnings, 3 - processing phases, 4 - debug) "-V3", # Read from the raw file (instead of stdin via pipe) raw_path, # Output path signal_path, # Resampling rate "rate", "11025", _out=logfile) logfile.flush() logfile.write("---noaa-apt log-------\n") logfile.flush() # Run noaa_apt - this decodes APT from the audio file into PNG image. sh.noaa_apt("-o", product_path, "--false-color", "--contrast", "telemetry", signal_path, _out=logfile) logfile.flush() logfile.close() return [("SIGNAL", signal_path), ("PRODUCT", product_path), ("LOG", log_path), ("RAW", raw_path)]