From 91da2b8342bc3949a2e4a60dcb75d6a0eb36bbaa Mon Sep 17 00:00:00 2001 From: serifpersia Date: Fri, 18 Jul 2025 19:34:05 +0200 Subject: [PATCH] routing and single latency update --- run_tascam_streamer.sh | 118 ------- tascam_controls/src/mainwindow.cpp | 34 +- tascam_controls/src/mainwindow.h | 1 - tascam_fifo_streamer.c | 530 ----------------------------- us144mkii.c | 242 ++++++------- 5 files changed, 140 insertions(+), 785 deletions(-) delete mode 100755 run_tascam_streamer.sh delete mode 100644 tascam_fifo_streamer.c diff --git a/run_tascam_streamer.sh b/run_tascam_streamer.sh deleted file mode 100755 index 9971877..0000000 --- a/run_tascam_streamer.sh +++ /dev/null @@ -1,118 +0,0 @@ -#!/bin/bash - -# MIT License -# Copyright (c) 2025 serifpersia -# -# Interactive launcher for the TASCAM US-144MKII FIFO streamer. -# Prompts for sample rate, latency profile, and logging options, -# then configures PulseAudio and the C streamer binary accordingly. - -# --- Configuration --- -SINK_NAME="TASCAM-US144MKII-OUT" -FIFO_PLAYBACK_PATH="/tmp/tascam-audio-playback" -STREAMER_BINARY="./tascam_streamer" # Assumes the C program is in the same directory -CHANNELS="2" -FORMAT="s24le" - -# --- Cleanup Function --- -cleanup() { - echo "" - echo "--- Running cleanup... ---" - - pkill -f "$STREAMER_BINARY" 2>/dev/null - sleep 0.5 - - echo "Unloading PulseAudio module..." - pactl unload-module module-pipe-sink 2>/dev/null - - echo "Removing FIFO file..." - rm -f "$FIFO_PLAYBACK_PATH" - - echo "--- Cleanup complete. ---" - exit 0 -} - -# Trap signals to ensure cleanup runs -trap cleanup SIGINT TERM EXIT - -# --- Interactive Setup --- -echo "--- TASCAM Streamer Interactive Setup ---" - -# 1. Select Sample Rate -rates=("44100" "48000" "88200" "96000") -PS3="Please select a sample rate: " -select rate_choice in "${rates[@]}"; do - if [[ -n "$rate_choice" ]]; then - SELECTED_RATE="$rate_choice" - echo "Selected rate: $SELECTED_RATE Hz" - break - else - echo "Invalid selection. Please try again." - fi -done -echo "" - -# 2. Select Latency Profile -profiles=("0: Lowest" "1: Low" "2: Normal" "3: High" "4: Highest") -PS3="Please select a latency profile: " -select profile_choice in "${profiles[@]}"; do - if [[ -n "$profile_choice" ]]; then - SELECTED_PROFILE_INDEX=$((REPLY - 1)) - echo "Selected profile: $profile_choice" - break - else - echo "Invalid selection. Please try again." - fi -done -echo "" - -# 3. Select Logging Mode -LOG_MODE_FLAG="" -LOG_INTERVAL_FLAG="" -read -p "Use minimal logging instead of the live dashboard? (y/n) [default: n]: " minimal_choice -if [[ "$minimal_choice" == "y" || "$minimal_choice" == "Y" ]]; then - LOG_MODE_FLAG="--minimal-log" - read -p "Enter log interval in milliseconds [default: 1000]: " interval_ms - if [[ -z "$interval_ms" ]]; then - interval_ms=1000 # Set default if user enters nothing - fi - LOG_INTERVAL_FLAG="--log-interval $interval_ms" - LOG_MODE_SUMMARY="Minimal (updates every ${interval_ms}ms)" -else - LOG_MODE_SUMMARY="Live Dashboard (updates every 100ms)" -fi - -echo "---------------------------------------------" -echo "Configuration:" -echo " Rate: $SELECTED_RATE Hz" -echo " Profile: $SELECTED_PROFILE_INDEX ($profile_choice)" -echo " Logging: $LOG_MODE_SUMMARY" -echo "---------------------------------------------" - -# --- Main Execution --- -rm -f "$FIFO_PLAYBACK_PATH" -echo "Creating playback FIFO at $FIFO_PLAYBACK_PATH..." -mkfifo "$FIFO_PLAYBACK_PATH" - -echo "Loading PulseAudio pipe-sink module..." -SINK_MODULE_ID=$(pactl load-module module-pipe-sink file="$FIFO_PLAYBACK_PATH" sink_name="$SINK_NAME" format=$FORMAT rate=$SELECTED_RATE channels=$CHANNELS) -if [ -z "$SINK_MODULE_ID" ]; then - echo "Error: Failed to load PulseAudio pipe-sink module. Aborting." - exit 1 -fi -echo "Playback Sink ('$SINK_NAME') loaded with ID: $SINK_MODULE_ID" -echo "You can now select '$SINK_NAME' as an output device in your sound settings." -echo "---------------------------------------------" - -echo "Starting C streamer binary..." -# Launch the C program with all selected arguments. -# The log flags will be empty strings if not selected, which bash ignores. -sudo "$STREAMER_BINARY" \ - -r "$SELECTED_RATE" \ - -p "$SELECTED_PROFILE_INDEX" \ - --pipe "$FIFO_PLAYBACK_PATH" \ - $LOG_MODE_FLAG \ - $LOG_INTERVAL_FLAG - -echo "Streamer exited. Waiting for cleanup..." -wait diff --git a/tascam_controls/src/mainwindow.cpp b/tascam_controls/src/mainwindow.cpp index b4c18bf..b5cb464 100644 --- a/tascam_controls/src/mainwindow.cpp +++ b/tascam_controls/src/mainwindow.cpp @@ -147,24 +147,20 @@ void MainWindow::initUi() { middlePanel->addWidget(widget); }; - auto latencyPair = createControlWidget("Latency Profile", {"low latency", "normal latency", "high latency"}); - m_latencyCombo = latencyPair.second; - addSection("AUDIO PERFORMANCE", latencyPair.first); - - auto capture12Pair = createControlWidget("ch1 and ch2", {"Analog In", "Digital In"}); + auto capture12Pair = createControlWidget("ch1 and ch2", {"analog inputs", "digital inputs"}); m_capture12Combo = capture12Pair.second; - auto capture34Pair = createControlWidget("ch3 and ch4", {"Analog In", "Digital In"}); + auto capture34Pair = createControlWidget("ch3 and ch4", {"analog inputs", "digital inputs"}); m_capture34Combo = capture34Pair.second; addSection("INPUTS", capture12Pair.first); middlePanel->addWidget(capture34Pair.first); - auto lineOutPair = createControlWidget("ch1 and ch2", {"Playback 1-2", "Playback 3-4"}); + auto lineOutPair = createControlWidget("ch1 and ch2", {"ch1 and ch2", "ch3 and ch4"}); m_lineOutCombo = lineOutPair.second; - addSection("LINE", lineOutPair.first); + addSection("LINE OUTPUTS", lineOutPair.first); - auto digitalOutPair = createControlWidget("ch3 and ch4", {"Playback 1-2", "Playback 3-4"}); + auto digitalOutPair = createControlWidget("ch3 and ch4", {"ch1 and ch2", "ch3 and ch4"}); m_digitalOutCombo = digitalOutPair.second; - addSection("DIGITAL", digitalOutPair.first); + addSection("DIGITAL OUTPUTS", digitalOutPair.first); middlePanel->addStretch(); @@ -183,11 +179,10 @@ void MainWindow::initUi() { topLevelLayout->addLayout(middlePanel, 3); topLevelLayout->addLayout(rightPanel, 3); - connect(m_latencyCombo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Latency Profile", index); }); - connect(m_lineOutCombo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Line Out Source", index); }); - connect(m_digitalOutCombo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Digital Out Source", index); }); - connect(m_capture12Combo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Capture 1-2 Source", index); }); - connect(m_capture34Combo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Capture 3-4 Source", index); }); + connect(m_lineOutCombo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Line OUTPUTS Source", index); }); + connect(m_digitalOutCombo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("Digital OUTPUTS Source", index); }); + connect(m_capture12Combo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("ch1 and ch2 Source", index); }); + connect(m_capture34Combo, &QComboBox::currentIndexChanged, this, [this](int index){ onControlChanged("ch3 and ch4 Source", index); }); } void MainWindow::loadDynamicSettings() { @@ -200,11 +195,10 @@ void MainWindow::loadDynamicSettings() { long rate_val = m_alsa.getControlValue("Sample Rate"); m_infoLabels["sample_rate"]->setText(rate_val > 0 ? QString("%1 kHz").arg(rate_val / 1000.0, 0, 'f', 1) : "N/A (inactive)"); - updateCombo(m_latencyCombo, "Latency Profile"); - updateCombo(m_lineOutCombo, "Line Out Source"); - updateCombo(m_digitalOutCombo, "Digital Out Source"); - updateCombo(m_capture12Combo, "Capture 1-2 Source"); - updateCombo(m_capture34Combo, "Capture 3-4 Source"); + updateCombo(m_lineOutCombo, "Line OUTPUTS Source"); + updateCombo(m_digitalOutCombo, "Digital OUTPUTS Source"); + updateCombo(m_capture12Combo, "ch1 and ch2 Source"); + updateCombo(m_capture34Combo, "ch3 and ch4 Source"); } void MainWindow::updateCombo(QComboBox* combo, const std::string& controlName) { diff --git a/tascam_controls/src/mainwindow.h b/tascam_controls/src/mainwindow.h index f87194e..ec71c3f 100644 --- a/tascam_controls/src/mainwindow.h +++ b/tascam_controls/src/mainwindow.h @@ -34,7 +34,6 @@ private: QPixmap m_background; QMap m_infoLabels; - QComboBox* m_latencyCombo; QComboBox* m_capture12Combo; QComboBox* m_capture34Combo; QComboBox* m_lineOutCombo; diff --git a/tascam_fifo_streamer.c b/tascam_fifo_streamer.c deleted file mode 100644 index 3161273..0000000 --- a/tascam_fifo_streamer.c +++ /dev/null @@ -1,530 +0,0 @@ -// MIT License -// Copyright (c) 2025 serifpersia -// -// Final verification tool by an AI assistant. This version is a fully functional, -// multi-rate, multi-profile FIFO audio player with selectable logging modes for -// either deep diagnostics or minimal-overhead monitoring. - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// --- Device and Endpoint Configuration --- -#define TASCAM_VID 0x0644 -#define TASCAM_PID 0x8020 -#define EP_AUDIO_OUT 0x02 -#define EP_PLAYBACK_FEEDBACK 0x81 -#define EP_CAPTURE_DATA 0x86 - -// --- USB Request Types --- -#define RT_H2D_CLASS_EP 0x22 -#define RT_D2H_VENDOR_DEV 0xc0 -#define RT_H2D_VENDOR_DEV 0x40 - -// --- UAC / Vendor Requests --- -#define UAC_SET_CUR 0x01 -#define UAC_SAMPLING_FREQ_CONTROL 0x0100 -#define VENDOR_REQ_REGISTER_WRITE 65 -#define VENDOR_REQ_MODE_CONTROL 73 - -// --- Streaming Configuration --- -#define BYTES_PER_SAMPLE 3 -#define DEVICE_CHANNELS 4 -#define PIPE_CHANNELS 2 -#define DEVICE_FRAME_SIZE (DEVICE_CHANNELS * BYTES_PER_SAMPLE) -#define PIPE_FRAME_SIZE (PIPE_CHANNELS * BYTES_PER_SAMPLE) -#define ISO_PLAYBACK_PACKETS_PER_TRANSFER 40 -#define NUM_PLAYBACK_TRANSFERS 4 -#define NUM_FEEDBACK_TRANSFERS 4 -#define FEEDBACK_PACKET_SIZE 3 -#define MAX_FEEDBACK_PACKETS_PER_URB 5 -#define USB_TIMEOUT 1000 - -// --- Feedback Synchronization Engine --- -#define FEEDBACK_ACCUMULATOR_SIZE 128 -#define WARMUP_THRESHOLD (ISO_PLAYBACK_PACKETS_PER_TRANSFER * 2) - -// --- Data Structures for Rate/Profile Configuration --- -struct latency_profile_config { - const char *name; - int feedback_packets_per_urb; - int asio_buffer_size_frames; - double expected_feedback_ms; -}; - -struct sample_rate_config { - int rate; - const unsigned char rate_data[3]; - uint16_t rate_vendor_wValue; - const unsigned int (*feedback_patterns)[8]; - unsigned int feedback_base_value; - unsigned int feedback_max_value; - const struct latency_profile_config profiles[5]; -}; - -// --- Pre-calculated Pattern Tables --- -static const unsigned int patterns_44khz[5][8] = { - {5, 5, 5, 6, 5, 5, 5, 6}, {5, 5, 6, 5, 5, 6, 5, 6}, - {5, 6, 5, 6, 5, 6, 5, 6}, {6, 5, 6, 6, 5, 6, 5, 6}, - {6, 6, 6, 5, 6, 6, 6, 5} -}; -static const unsigned int patterns_48khz[5][8] = { - {5, 6, 6, 6, 5, 6, 6, 6}, {5, 6, 6, 6, 6, 6, 6, 6}, - {6, 6, 6, 6, 6, 6, 6, 6}, {7, 6, 6, 6, 6, 6, 6, 6}, - {7, 6, 6, 6, 7, 6, 6, 6} -}; -static const unsigned int patterns_88khz[5][8] = { - {10, 11, 11, 11, 10, 11, 11, 11}, {10, 11, 11, 11, 11, 11, 11, 11}, - {11, 11, 11, 11, 11, 11, 11, 11}, {12, 11, 11, 11, 11, 11, 11, 11}, - {12, 11, 11, 11, 12, 11, 11, 11} -}; -static const unsigned int patterns_96khz[5][8] = { - {11, 12, 12, 12, 11, 12, 12, 12}, {11, 12, 12, 12, 12, 12, 12, 12}, - {12, 12, 12, 12, 12, 12, 12, 12}, {13, 12, 12, 12, 12, 12, 12, 12}, - {13, 12, 12, 12, 13, 12, 12, 12} -}; - -// --- Global Configuration Table --- -static const struct sample_rate_config g_rate_configs[] = { - { 44100, {0x44, 0xac, 0x00}, 0x1000, patterns_44khz, 42, 46, { {"Lowest",1,49,2.0}, {"Low",1,64,2.0}, {"Normal",2,128,2.0}, {"High",5,256,5.0}, {"Highest",5,512,5.0} } }, - { 48000, {0x80, 0xbb, 0x00}, 0x1002, patterns_48khz, 46, 50, { {"Lowest",1,48,1.0}, {"Low",1,64,2.0}, {"Normal",2,128,2.0}, {"High",5,256,5.0}, {"Highest",5,512,5.0} } }, - { 88200, {0x88, 0x58, 0x01}, 0x1008, patterns_88khz, 86, 90, { {"Lowest",1,98,1.0}, {"Low",1,128,2.0}, {"Normal",2,256,2.0}, {"High",5,512,5.0}, {"Highest",5,1024,5.0} } }, - { 96000, {0x00, 0x77, 0x01}, 0x100a, patterns_96khz, 94, 98, { {"Lowest",1,96,1.0}, {"Low",1,128,2.0}, {"Normal",2,256,2.0}, {"High",5,512,5.0}, {"Highest",5,1024,5.0} } } -}; -#define NUM_SUPPORTED_RATES (sizeof(g_rate_configs) / sizeof(g_rate_configs[0])) -#define NUM_PROFILES 5 - -// --- Global State --- -static volatile bool is_running = true; - -struct stream_state { - int fifo_fd; - pthread_mutex_t lock; - const struct sample_rate_config *rate_cfg; - const struct latency_profile_config *profile_cfg; - unsigned int feedback_accumulator_pattern[FEEDBACK_ACCUMULATOR_SIZE]; - unsigned int feedback_pattern_out_idx; - unsigned int feedback_pattern_in_idx; - bool feedback_synced; - bool feedback_warmed_up; - int last_feedback_value; - struct timeval last_feedback_completion_time; - double last_feedback_interval_ms; - double min_feedback_interval_ms; - double max_feedback_interval_ms; - double avg_feedback_interval_sum; - unsigned long feedback_interval_count; - unsigned long underrun_count; - unsigned long overrun_count; -}; - -struct logging_thread_args { - struct stream_state *state; - bool minimal_log; - int log_interval_ms; -}; - -// --- Function Prototypes --- -void print_usage(const char *prog_name); -int perform_initialization_sequence(libusb_device_handle *handle, const struct sample_rate_config *rate_config); -static void LIBUSB_CALL iso_playback_callback(struct libusb_transfer *transfer); -static void LIBUSB_CALL feedback_callback(struct libusb_transfer *transfer); -void *logging_thread_func(void *arg); -double timeval_diff_ms(struct timeval *start, struct timeval *end); - -void sigint_handler(int signum) { - if (is_running) { - printf("\n\n\n\n\nCtrl+C detected, stopping...\n"); - is_running = false; - } -} - -int main(int argc, char *argv[]) { - int sample_rate = 0; - int profile_index = -1; - const char *pipe_path = NULL; - bool minimal_log = false; - int log_interval_ms = 100; // Default to 100ms for dashboard - - for (int i = 1; i < argc; i++) { - if (strcmp(argv[i], "-r") == 0 && i + 1 < argc) sample_rate = atoi(argv[++i]); - else if (strcmp(argv[i], "-p") == 0 && i + 1 < argc) profile_index = atoi(argv[++i]); - else if (strcmp(argv[i], "--pipe") == 0 && i + 1 < argc) pipe_path = argv[++i]; - else if (strcmp(argv[i], "--minimal-log") == 0) minimal_log = true; - else if (strcmp(argv[i], "--log-interval") == 0 && i + 1 < argc) log_interval_ms = atoi(argv[++i]); - } - - if (sample_rate == 0 || profile_index < 0 || !pipe_path) { - print_usage(argv[0]); - return 1; - } - - const struct sample_rate_config *rate_config = NULL; - for (unsigned int i = 0; i < NUM_SUPPORTED_RATES; i++) { - if (g_rate_configs[i].rate == sample_rate) { - rate_config = &g_rate_configs[i]; - break; - } - } - - if (!rate_config) { - fprintf(stderr, "Error: Sample rate %d is not supported.\n", sample_rate); - print_usage(argv[0]); - return 1; - } - if (profile_index >= NUM_PROFILES) { - fprintf(stderr, "Error: Invalid profile index %d.\n", profile_index); - print_usage(argv[0]); - return 1; - } - const struct latency_profile_config *profile_config = &rate_config->profiles[profile_index]; - - libusb_device_handle *handle = NULL; - struct libusb_transfer *playback_transfers[NUM_PLAYBACK_TRANSFERS] = {0}; - struct libusb_transfer *feedback_transfers[NUM_FEEDBACK_TRANSFERS] = {0}; - struct stream_state state = { .fifo_fd = -1 }; - struct logging_thread_args log_args = { &state, minimal_log, log_interval_ms }; - pthread_t logging_thread = 0; - bool kernel_driver_was_active[2] = {false, false}; - int r = 0; - - const int max_frames_per_packet = (rate_config->rate / 8000) + 2; - const int playback_packet_max_size = max_frames_per_packet * DEVICE_FRAME_SIZE; - const int playback_transfer_size = playback_packet_max_size * ISO_PLAYBACK_PACKETS_PER_TRANSFER; - const int feedback_transfer_size = FEEDBACK_PACKET_SIZE * MAX_FEEDBACK_PACKETS_PER_URB; - - printf("--- TASCAM US-144MKII FIFO Streamer ---\n"); - printf("Profile: %d, Rate: %d Hz, Latency: %s (%d-sample buffer)\n", - profile_index, rate_config->rate, profile_config->name, profile_config->asio_buffer_size_frames); - printf("Config: Feedback URB contains %d packet(s), expected interval %.1f ms.\n", - profile_config->feedback_packets_per_urb, profile_config->expected_feedback_ms); - printf("Pipe: Reading 24-bit stereo audio from %s\n", pipe_path); - - pthread_mutex_init(&state.lock, NULL); - state.rate_cfg = rate_config; - state.profile_cfg = profile_config; - state.min_feedback_interval_ms = DBL_MAX; - - state.fifo_fd = open(pipe_path, O_RDONLY | O_NONBLOCK); - if (state.fifo_fd < 0) { - perror("Error opening FIFO pipe"); - return 1; - } - - signal(SIGINT, sigint_handler); - if (libusb_init(NULL) < 0) { r = 1; goto cleanup; } - - handle = libusb_open_device_with_vid_pid(NULL, TASCAM_VID, TASCAM_PID); - if (!handle) { fprintf(stderr, "Device not found\n"); r = 1; goto cleanup; } - - for (int i = 0; i < 2; i++) { - if (libusb_kernel_driver_active(handle, i)) { - kernel_driver_was_active[i] = true; - if ((r = libusb_detach_kernel_driver(handle, i)) != 0) { - fprintf(stderr, "Could not detach kernel driver for interface %d: %s\n", i, libusb_error_name(r)); - r = 1; goto cleanup; - } - } - } - - if (perform_initialization_sequence(handle, rate_config) != 0) { - fprintf(stderr, "Device configuration failed.\n"); r = 1; goto cleanup; - } - - printf("Starting streams... (waiting for buffer warm-up)\n"); - for (int i = 0; i < NUM_PLAYBACK_TRANSFERS; i++) { - playback_transfers[i] = libusb_alloc_transfer(ISO_PLAYBACK_PACKETS_PER_TRANSFER); - unsigned char *buf = malloc(playback_transfer_size); - memset(buf, 0, playback_transfer_size); - libusb_fill_iso_transfer(playback_transfers[i], handle, EP_AUDIO_OUT, buf, playback_transfer_size, ISO_PLAYBACK_PACKETS_PER_TRANSFER, iso_playback_callback, &state, USB_TIMEOUT); - int nominal_packet_size = (rate_config->rate / 8000) * DEVICE_FRAME_SIZE; - libusb_set_iso_packet_lengths(playback_transfers[i], nominal_packet_size); - libusb_submit_transfer(playback_transfers[i]); - } - - for (int i = 0; i < NUM_FEEDBACK_TRANSFERS; i++) { - feedback_transfers[i] = libusb_alloc_transfer(profile_config->feedback_packets_per_urb); - unsigned char *buf = malloc(feedback_transfer_size); - libusb_fill_iso_transfer(feedback_transfers[i], handle, EP_PLAYBACK_FEEDBACK, buf, feedback_transfer_size, profile_config->feedback_packets_per_urb, feedback_callback, &state, USB_TIMEOUT); - libusb_set_iso_packet_lengths(feedback_transfers[i], FEEDBACK_PACKET_SIZE); - libusb_submit_transfer(feedback_transfers[i]); - } - - if (pthread_create(&logging_thread, NULL, logging_thread_func, &log_args) != 0) { - fprintf(stderr, "Failed to create logging thread.\n"); - is_running = false; - } - - printf("Draining stale data from FIFO pipe to ensure stream alignment...\n"); - char drain_buf[4096]; - while (read(state.fifo_fd, drain_buf, sizeof(drain_buf)) > 0); - - printf("\n--- Playback active. Press Ctrl+C to stop. ---\n"); - if (!minimal_log) printf("\n\n\n\n\n"); // Space for dashboard - - while (is_running) { - libusb_handle_events_timeout_completed(NULL, &(struct timeval){0, 100000}, NULL); - } - -cleanup: - is_running = false; - if (logging_thread) pthread_join(logging_thread, NULL); - for (int i = 0; i < NUM_PLAYBACK_TRANSFERS; i++) if (playback_transfers[i]) libusb_cancel_transfer(playback_transfers[i]); - for (int i = 0; i < NUM_FEEDBACK_TRANSFERS; i++) if (feedback_transfers[i]) libusb_cancel_transfer(feedback_transfers[i]); - if (handle) { - struct timeval tv = {0, 100000}; - libusb_handle_events_timeout_completed(NULL, &tv, NULL); - libusb_release_interface(handle, 1); - libusb_release_interface(handle, 0); - for(int i = 0; i < 2; i++) if (kernel_driver_was_active[i]) libusb_attach_kernel_driver(handle, i); - libusb_close(handle); - } - for (int i = 0; i < NUM_PLAYBACK_TRANSFERS; i++) if (playback_transfers[i]) { if (playback_transfers[i]->buffer) free(playback_transfers[i]->buffer); libusb_free_transfer(playback_transfers[i]); } - for (int i = 0; i < NUM_FEEDBACK_TRANSFERS; i++) if (feedback_transfers[i]) { if (feedback_transfers[i]->buffer) free(feedback_transfers[i]->buffer); libusb_free_transfer(feedback_transfers[i]); } - if (state.fifo_fd >= 0) close(state.fifo_fd); - pthread_mutex_destroy(&state.lock); - if (r != 1) libusb_exit(NULL); - printf("Cleanup complete.\n"); - return r; -} - -void print_usage(const char *prog_name) { - fprintf(stderr, "Usage: %s -r -p --pipe [options]\n", prog_name); - fprintf(stderr, "Required:\n"); - fprintf(stderr, " -r : 44100, 48000, 88200, 96000\n"); - fprintf(stderr, " -p : 0-4 (Lowest, Low, Normal, High, Highest)\n"); - fprintf(stderr, " --pipe : Path to the named pipe for audio input\n"); - fprintf(stderr, "Optional:\n"); - fprintf(stderr, " --minimal-log : Switch to a simple, single-line status summary.\n"); - fprintf(stderr, " --log-interval : Set summary update frequency (default: 100ms).\n"); -} - -double timeval_diff_ms(struct timeval *start, struct timeval *end) { - return (end->tv_sec - start->tv_sec) * 1000.0 + (end->tv_usec - start->tv_usec) / 1000.0; -} - -void *logging_thread_func(void *arg) { - struct logging_thread_args *args = (struct logging_thread_args *)arg; - struct stream_state *state = args->state; - const int bar_width = 20; - - while (is_running) { - usleep(args->log_interval_ms * 1000); - pthread_mutex_lock(&state->lock); - - const char *health = (state->underrun_count > 0 || state->overrun_count > 0) ? "\033[1;31mUNSTABLE\033[0m" : "\033[1;32mSTABLE\033[0m"; - const char *sync_status_str; - if (state->feedback_synced) { - sync_status_str = state->feedback_warmed_up ? "\033[1;32mACQUIRED\033[0m" : "\033[1;33mWARM-UP\033[0m"; - } else { - sync_status_str = "\033[1;31mLOST/OFF\033[0m"; - } - - double avg_interval = (state->feedback_interval_count > 0) ? state->avg_feedback_interval_sum / state->feedback_interval_count : 0.0; - - if (args->minimal_log) { - printf("Health: %s, Sync: %s, Avg Interval: %.2fms, Underruns: %lu, Overruns: %lu \r", - (state->underrun_count > 0 || state->overrun_count > 0) ? "UNSTABLE" : "STABLE", - state->feedback_warmed_up ? "ACQUIRED" : "WARMING", - avg_interval, state->underrun_count, state->overrun_count); - } else { - size_t fill = (state->feedback_pattern_in_idx - state->feedback_pattern_out_idx + FEEDBACK_ACCUMULATOR_SIZE) % FEEDBACK_ACCUMULATOR_SIZE; - int filled_chars = (int)((double)fill / FEEDBACK_ACCUMULATOR_SIZE * bar_width); - - printf("\033[5A\033[K\n\033[K\n\033[K\n\033[K\n\033[K\n\033[5A"); - printf("--- TASCAM US-144MKII Stream Health ---\n"); - printf(" Health: %-18s Sync: %-18s Feedback: %-3d\n", health, sync_status_str, state->last_feedback_value); - printf(" Buffer: ["); - for(int i=0; i Now: %4.2f Min: %4.2f Avg: %4.2f Max: %4.2f\n", - state->last_feedback_interval_ms, - state->min_feedback_interval_ms == DBL_MAX ? 0.0 : state->min_feedback_interval_ms, - avg_interval, state->max_feedback_interval_ms); - printf(" Errors -> Underruns: %-5lu Overruns: %lu\n", state->underrun_count, state->overrun_count); - } - fflush(stdout); - pthread_mutex_unlock(&state->lock); - } - return NULL; -} - -static void LIBUSB_CALL feedback_callback(struct libusb_transfer *transfer) { - if (!is_running) return; - struct stream_state *state = transfer->user_data; - struct timeval now; - gettimeofday(&now, NULL); - - if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { - if (transfer->status != LIBUSB_TRANSFER_CANCELLED) { - pthread_mutex_lock(&state->lock); - if (state->feedback_synced) printf("\nSync Lost (URB Error: %s)!\n", libusb_error_name(transfer->status)); - state->feedback_synced = false; - state->feedback_warmed_up = false; - pthread_mutex_unlock(&state->lock); - } - goto resubmit; - } - - pthread_mutex_lock(&state->lock); - if (state->last_feedback_completion_time.tv_sec > 0) { - state->last_feedback_interval_ms = timeval_diff_ms(&state->last_feedback_completion_time, &now); - if (state->feedback_warmed_up) { - if (state->last_feedback_interval_ms < state->min_feedback_interval_ms) state->min_feedback_interval_ms = state->last_feedback_interval_ms; - if (state->last_feedback_interval_ms > state->max_feedback_interval_ms) state->max_feedback_interval_ms = state->last_feedback_interval_ms; - state->avg_feedback_interval_sum += state->last_feedback_interval_ms; - state->feedback_interval_count++; - } - } - state->last_feedback_completion_time = now; - - bool was_synced = state->feedback_synced; - bool sync_lost_this_urb = false; - - for (int p = 0; p < transfer->num_iso_packets; p++) { - struct libusb_iso_packet_descriptor *pack = &transfer->iso_packet_desc[p]; - if (pack->status != 0 || pack->actual_length < 1) { - sync_lost_this_urb = true; - continue; - } - size_t packet_offset = p * FEEDBACK_PACKET_SIZE; - uint8_t feedback_value = transfer->buffer[packet_offset]; - state->last_feedback_value = feedback_value; - - if (feedback_value >= state->rate_cfg->feedback_base_value && feedback_value <= state->rate_cfg->feedback_max_value) { - int pattern_index = feedback_value - state->rate_cfg->feedback_base_value; - const unsigned int *pattern = state->rate_cfg->feedback_patterns[pattern_index]; - size_t fill_level = (state->feedback_pattern_in_idx - state->feedback_pattern_out_idx + FEEDBACK_ACCUMULATOR_SIZE) % FEEDBACK_ACCUMULATOR_SIZE; - if (fill_level > (FEEDBACK_ACCUMULATOR_SIZE - 16)) state->overrun_count++; - for (int i = 0; i < 8; i++) { - unsigned int in_idx = (state->feedback_pattern_in_idx + i) % FEEDBACK_ACCUMULATOR_SIZE; - state->feedback_accumulator_pattern[in_idx] = pattern[i]; - } - state->feedback_pattern_in_idx = (state->feedback_pattern_in_idx + 8) % FEEDBACK_ACCUMULATOR_SIZE; - } else { - sync_lost_this_urb = true; - } - } - - if (sync_lost_this_urb) { - if (was_synced) printf("\nSync Lost (Bad Packet)!\n"); - state->feedback_synced = false; - state->feedback_warmed_up = false; - } else { - if (!was_synced) printf("\nSync Acquired!\n"); - state->feedback_synced = true; - size_t fill_level = (state->feedback_pattern_in_idx - state->feedback_pattern_out_idx + FEEDBACK_ACCUMULATOR_SIZE) % FEEDBACK_ACCUMULATOR_SIZE; - if (!state->feedback_warmed_up && fill_level >= WARMUP_THRESHOLD) { - state->feedback_warmed_up = true; - state->min_feedback_interval_ms = DBL_MAX; - state->max_feedback_interval_ms = 0.0; - state->avg_feedback_interval_sum = 0.0; - state->feedback_interval_count = 0; - printf("\nBuffer warmed up. Measuring steady-state performance.\n"); - } - } - pthread_mutex_unlock(&state->lock); - -resubmit: - if (is_running) libusb_submit_transfer(transfer); -} - -static void LIBUSB_CALL iso_playback_callback(struct libusb_transfer *transfer) { - if (!is_running) return; - struct stream_state *state = transfer->user_data; - - if (transfer->status != LIBUSB_TRANSFER_COMPLETED) { - if (transfer->status != LIBUSB_TRANSFER_CANCELLED) { - fprintf(stderr, "\nPlayback callback error: %s\n", libusb_error_name(transfer->status)); - is_running = false; - } - return; - } - - pthread_mutex_lock(&state->lock); - int nominal_frames = state->rate_cfg->rate / 8000; - - if (!state->feedback_warmed_up) { - libusb_set_iso_packet_lengths(transfer, nominal_frames * DEVICE_FRAME_SIZE); - memset(transfer->buffer, 0, transfer->length); - pthread_mutex_unlock(&state->lock); - goto resubmit_playback; - } - - unsigned char *buf_ptr = transfer->buffer; - size_t total_bytes_in_urb = 0; - - for (int i = 0; i < transfer->num_iso_packets; i++) { - unsigned int frames_for_packet; - if (state->feedback_pattern_out_idx == state->feedback_pattern_in_idx) { - state->underrun_count++; - frames_for_packet = nominal_frames; - } else { - frames_for_packet = state->feedback_accumulator_pattern[state->feedback_pattern_out_idx]; - state->feedback_pattern_out_idx = (state->feedback_pattern_out_idx + 1) % FEEDBACK_ACCUMULATOR_SIZE; - } - size_t bytes_for_packet = frames_for_packet * DEVICE_FRAME_SIZE; - size_t bytes_to_read_from_pipe = frames_for_packet * PIPE_FRAME_SIZE; - - ssize_t bytes_read = read(state->fifo_fd, buf_ptr, bytes_to_read_from_pipe); - - if (bytes_read > 0) { - int frames_read = bytes_read / PIPE_FRAME_SIZE; - for (int f = frames_read - 1; f >= 0; f--) { - unsigned char* src = buf_ptr + f * PIPE_FRAME_SIZE; - unsigned char* dst = buf_ptr + f * DEVICE_FRAME_SIZE; - memmove(dst, src, PIPE_FRAME_SIZE); - memset(dst + PIPE_FRAME_SIZE, 0, DEVICE_FRAME_SIZE - PIPE_FRAME_SIZE); - } - if ((size_t)bytes_read < bytes_to_read_from_pipe) { - memset(buf_ptr + (frames_read * DEVICE_FRAME_SIZE), 0, bytes_for_packet - (frames_read * DEVICE_FRAME_SIZE)); - } - } else { - memset(buf_ptr, 0, bytes_for_packet); - } - - buf_ptr += bytes_for_packet; - transfer->iso_packet_desc[i].length = bytes_for_packet; - total_bytes_in_urb += bytes_for_packet; - } - pthread_mutex_unlock(&state->lock); - - transfer->length = total_bytes_in_urb; - -resubmit_playback: - if (is_running && libusb_submit_transfer(transfer) < 0) { - fprintf(stderr, "\nError resubmitting playback transfer\n"); - is_running = false; - } -} - -int perform_initialization_sequence(libusb_device_handle *handle, const struct sample_rate_config *rate_config) { - unsigned char buf[64]; int r; - printf("\n--- STARTING DEVICE CONFIGURATION (per Spec v5.0) ---\n"); - #define CHECK(desc, call) r = (call); if (r < 0) { fprintf(stderr, " [FAIL] %s: %s\n", desc, libusb_error_name(r)); return -1; } else { printf(" [OK] %s (returned %d)\n", desc, r); } - printf(" [INFO] Step 1: Set Interfaces\n"); - r = libusb_set_configuration(handle, 1); if (r < 0 && r != LIBUSB_ERROR_BUSY) { fprintf(stderr, " [FAIL] Set Configuration 1: %s\n", libusb_error_name(r)); return -1; } - for (int i=0; i<=1; i++) { r = libusb_claim_interface(handle, i); if (r < 0) { fprintf(stderr, " [FAIL] Claim Interface %d: %s\n", i, libusb_error_name(r)); return -1; } r = libusb_set_interface_alt_setting(handle, i, 1); if (r < 0) { fprintf(stderr, " [FAIL] Set Alt Setting on Intf %d: %s\n", i, libusb_error_name(r)); return -1; } } - printf(" [OK] Step 1: Interfaces set and claimed.\n"); - printf("\n-- Step 2: Initial Handshake --\n"); CHECK("Status Check", libusb_control_transfer(handle, RT_D2H_VENDOR_DEV, VENDOR_REQ_MODE_CONTROL, 0x0000, 0x0000, buf, 1, USB_TIMEOUT)); - printf("\n-- Step 3: Set Initial Mode --\n"); CHECK("Set Initial Mode", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_MODE_CONTROL, 0x0010, 0x0000, NULL, 0, USB_TIMEOUT)); - printf("\n-- Step 4: Set Sample Rate to %d Hz --\n", rate_config->rate); - CHECK("Set Rate on Capture EP (0x86)", libusb_control_transfer(handle, RT_H2D_CLASS_EP, UAC_SET_CUR, UAC_SAMPLING_FREQ_CONTROL, EP_CAPTURE_DATA, (unsigned char*)rate_config->rate_data, 3, USB_TIMEOUT)); - CHECK("Set Rate on Playback EP (0x02)", libusb_control_transfer(handle, RT_H2D_CLASS_EP, UAC_SET_CUR, UAC_SAMPLING_FREQ_CONTROL, EP_AUDIO_OUT, (unsigned char*)rate_config->rate_data, 3, USB_TIMEOUT)); - printf("\n-- Step 5: Configure Internal Registers --\n"); CHECK("Reg Write 1 (0x0d04)", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_REGISTER_WRITE, 0x0d04, 0x0101, NULL, 0, USB_TIMEOUT)); CHECK("Reg Write 2 (0x0e00)", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_REGISTER_WRITE, 0x0e00, 0x0101, NULL, 0, USB_TIMEOUT)); CHECK("Reg Write 3 (0x0f00)", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_REGISTER_WRITE, 0x0f00, 0x0101, NULL, 0, USB_TIMEOUT)); - CHECK("Reg Write 4 (Rate-Dep)", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_REGISTER_WRITE, rate_config->rate_vendor_wValue, 0x0101, NULL, 0, USB_TIMEOUT)); - CHECK("Reg Write 5 (0x110b)", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_REGISTER_WRITE, 0x110b, 0x0101, NULL, 0, USB_TIMEOUT)); - printf("\n-- Step 6: Enable Streaming --\n"); CHECK("Enable Streaming", libusb_control_transfer(handle, RT_H2D_VENDOR_DEV, VENDOR_REQ_MODE_CONTROL, 0x0030, 0x0000, NULL, 0, USB_TIMEOUT)); - printf("\n--- CONFIGURATION COMPLETE ---\n\n"); return 0; -} diff --git a/us144mkii.c b/us144mkii.c index 98618cd..00dd798 100644 --- a/us144mkii.c +++ b/us144mkii.c @@ -78,7 +78,7 @@ static int dev_idx; /* --- Capture Decoding Defines --- */ #define DECODED_CHANNELS_PER_FRAME 4 -#define DECODED_SAMPLE_SIZE 4 /* 32-bit */ +#define DECODED_SAMPLE_SIZE 4 #define FRAMES_PER_DECODE_BLOCK 8 #define RAW_BYTES_PER_DECODE_BLOCK 512 @@ -100,6 +100,7 @@ struct tascam_card { u64 playback_frames_consumed; snd_pcm_uframes_t driver_playback_pos; u64 last_period_pos; + u8 *playback_routing_buffer; /* Capture stream */ struct snd_pcm_substream *capture_substream; @@ -114,13 +115,13 @@ struct tascam_card { volatile size_t capture_ring_buffer_write_ptr; u8 *capture_decode_raw_block; s32 *capture_decode_dst_block; - struct work_struct capture_work; // For deferred processing + s32 *capture_routing_buffer; + struct work_struct capture_work; /* Shared state & Routing Matrix */ spinlock_t lock; atomic_t active_urbs; int current_rate; - unsigned int latency_profile; unsigned int line_out_source; /* 0: Playback 1-2, 1: Playback 3-4 */ unsigned int digital_out_source; /* 0: Playback 1-2, 1: Playback 3-4 */ unsigned int capture_12_source; /* 0: Analog In, 1: Digital In */ @@ -160,48 +161,9 @@ static ssize_t driver_version_show(struct device *dev, static DEVICE_ATTR_RO(driver_version); /* --- ALSA Control Definitions --- */ -static const char * const latency_profile_texts[] = {"Low", "Normal", "High"}; static const char * const playback_source_texts[] = {"Playback 1-2", "Playback 3-4"}; static const char * const capture_source_texts[] = {"Analog In", "Digital In"}; -static int tascam_latency_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) -{ - uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; - uinfo->count = 1; - uinfo->value.enumerated.items = 3; - if (uinfo->value.enumerated.item >= 3) - uinfo->value.enumerated.item = 2; - strcpy(uinfo->value.enumerated.name, latency_profile_texts[uinfo->value.enumerated.item]); - return 0; -} - -static int tascam_latency_get(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) -{ - struct tascam_card *tascam = snd_kcontrol_chip(kcontrol); - ucontrol->value.enumerated.item[0] = tascam->latency_profile; - return 0; -} - -static int tascam_latency_put(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_value *ucontrol) -{ - struct tascam_card *tascam = snd_kcontrol_chip(kcontrol); - unsigned int new_profile = ucontrol->value.enumerated.item[0]; - - if (new_profile >= 3) - return -EINVAL; - - if (tascam->latency_profile != new_profile) { - tascam->latency_profile = new_profile; - return 1; - } - return 0; -} - -static const struct snd_kcontrol_new tascam_latency_control = { - .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Latency Profile", - .info = tascam_latency_info, .get = tascam_latency_get, .put = tascam_latency_put, -}; - static int tascam_playback_source_info(struct snd_kcontrol *kcontrol, struct snd_ctl_elem_info *uinfo) { uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED; @@ -232,7 +194,7 @@ static int tascam_line_out_put(struct snd_kcontrol *kcontrol, struct snd_ctl_ele } static const struct snd_kcontrol_new tascam_line_out_control = { - .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Line Out Source", + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Line OUTPUTS Source", .info = tascam_playback_source_info, .get = tascam_line_out_get, .put = tascam_line_out_put, }; @@ -255,7 +217,7 @@ static int tascam_digital_out_put(struct snd_kcontrol *kcontrol, struct snd_ctl_ } static const struct snd_kcontrol_new tascam_digital_out_control = { - .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Digital Out Source", + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Digital OUTPUTS Source", .info = tascam_playback_source_info, .get = tascam_digital_out_get, .put = tascam_digital_out_put, }; @@ -289,7 +251,7 @@ static int tascam_capture_12_put(struct snd_kcontrol *kcontrol, struct snd_ctl_e } static const struct snd_kcontrol_new tascam_capture_12_control = { - .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Capture 1-2 Source", + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "ch1 and ch2 Source", .info = tascam_capture_source_info, .get = tascam_capture_12_get, .put = tascam_capture_12_put, }; @@ -312,7 +274,7 @@ static int tascam_capture_34_put(struct snd_kcontrol *kcontrol, struct snd_ctl_e } static const struct snd_kcontrol_new tascam_capture_34_control = { - .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "Capture 3-4 Source", + .iface = SNDRV_CTL_ELEM_IFACE_MIXER, .name = "ch3 and ch4 Source", .info = tascam_capture_source_info, .get = tascam_capture_34_get, .put = tascam_capture_34_put, }; @@ -362,6 +324,75 @@ static const struct snd_kcontrol_new tascam_samplerate_control = { .access = SNDRV_CTL_ELEM_ACCESS_READ, }; +/** + * process_playback_routing_us144mkii + * @tascam: The driver instance. + * @src_buffer: Buffer containing 4 channels of S24_3LE audio from ALSA. + * @dst_buffer: Buffer to be filled with 4 channels of S24_3LE audio for the USB device. + * @frames: Number of frames to process. + */ +static void process_playback_routing_us144mkii(struct tascam_card *tascam, const u8 *src_buffer, u8 *dst_buffer, size_t frames) +{ + size_t f; + const u8 *src_12, *src_34; + u8 *dst_line, *dst_digital; + + for (f = 0; f < frames; ++f) { + src_12 = src_buffer + f * BYTES_PER_FRAME; + src_34 = src_12 + (2 * BYTES_PER_SAMPLE); + dst_line = dst_buffer + f * BYTES_PER_FRAME; + dst_digital = dst_line + (2 * BYTES_PER_SAMPLE); + + // LINE OUTPUTS (ch1/2 on device) + if (tascam->line_out_source == 0) // "ch1 and ch2" + memcpy(dst_line, src_12, 2 * BYTES_PER_SAMPLE); + else // "ch3 and ch4" + memcpy(dst_line, src_34, 2 * BYTES_PER_SAMPLE); + + // DIGITAL OUTPUTS (ch3/4 on device) + if (tascam->digital_out_source == 0) // "ch1 and ch2" + memcpy(dst_digital, src_12, 2 * BYTES_PER_SAMPLE); + else // "ch3 and ch4" + memcpy(dst_digital, src_34, 2 * BYTES_PER_SAMPLE); + } +} + +/** + * process_capture_routing_us144mkii + * @tascam: The driver instance. + * @decoded_block: Buffer containing 4 channels of S32LE decoded audio from device. + * @routed_block: Buffer to be filled with 4 channels of S32LE audio for ALSA. + */ +static void process_capture_routing_us144mkii(struct tascam_card *tascam, const s32 *decoded_block, s32 *routed_block) +{ + int f; + const s32 *src_frame; + s32 *dst_frame; + + for (f = 0; f < FRAMES_PER_DECODE_BLOCK; f++) { + src_frame = decoded_block + (f * DECODED_CHANNELS_PER_FRAME); + dst_frame = routed_block + (f * DECODED_CHANNELS_PER_FRAME); + + // ch1 and ch2 Source + if (tascam->capture_12_source == 0) { // analog inputs + dst_frame[0] = src_frame[0]; // Analog L + dst_frame[1] = src_frame[1]; // Analog R + } else { // digital inputs + dst_frame[0] = src_frame[2]; // Digital L + dst_frame[1] = src_frame[3]; // Digital R + } + + // ch3 and ch4 Source + if (tascam->capture_34_source == 0) { // analog inputs + dst_frame[2] = src_frame[0]; // Analog L (Duplicate) + dst_frame[3] = src_frame[1]; // Analog R (Duplicate) + } else { // digital inputs + dst_frame[2] = src_frame[2]; // Digital L + dst_frame[3] = src_frame[3]; // Digital R + } + } +} + /* --- Rate-to-Packet Fixing Data (Verified) --- */ static const unsigned int patterns_48khz[5][8] = { {5, 6, 6, 6, 5, 6, 6, 6}, {5, 6, 6, 6, 6, 6, 6, 6}, @@ -444,12 +475,11 @@ static void tascam_free_urbs(struct tascam_card *tascam) } } + kfree(tascam->playback_routing_buffer); + tascam->playback_routing_buffer = NULL; + kfree(tascam->capture_routing_buffer); + tascam->capture_routing_buffer = NULL; kfree(tascam->capture_decode_dst_block); - tascam->capture_decode_dst_block = NULL; - kfree(tascam->capture_decode_raw_block); - tascam->capture_decode_raw_block = NULL; - kfree(tascam->capture_ring_buffer); - tascam->capture_ring_buffer = NULL; } /** @@ -542,6 +572,14 @@ static int tascam_alloc_urbs(struct tascam_card *tascam) if (!tascam->capture_decode_dst_block) goto error; + tascam->playback_routing_buffer = kmalloc(tascam->playback_urb_alloc_size, GFP_KERNEL); + if (!tascam->playback_routing_buffer) + goto error; + + tascam->capture_routing_buffer = kmalloc(FRAMES_PER_DECODE_BLOCK * DECODED_CHANNELS_PER_FRAME * DECODED_SAMPLE_SIZE, GFP_KERNEL); + if (!tascam->capture_routing_buffer) + goto error; + return 0; error: @@ -742,12 +780,7 @@ static int tascam_playback_prepare(struct snd_pcm_substream *substream) for (i = 0; i < FEEDBACK_ACCUMULATOR_SIZE; i++) tascam->feedback_accumulator_pattern[i] = nominal_frames_per_packet; - switch (tascam->latency_profile) { - case 0: feedback_packets = 1; break; /* Low */ - case 1: feedback_packets = 2; break; /* Normal */ - case 2: feedback_packets = 5; break; /* High */ - default: feedback_packets = 2; - } + feedback_packets = 1; /* Lowest latency */ for (i = 0; i < NUM_FEEDBACK_URBS; i++) { struct urb *f_urb = tascam->feedback_urbs[i]; @@ -944,7 +977,7 @@ static void playback_urb_complete(struct urb *urb) struct snd_pcm_substream *substream; struct snd_pcm_runtime *runtime; unsigned long flags; - char *src_buf, *dst_buf; + u8 *src_buf, *dst_buf; size_t total_bytes_for_urb = 0; snd_pcm_uframes_t offset_frames; snd_pcm_uframes_t frames_to_copy; @@ -990,30 +1023,22 @@ static void playback_urb_complete(struct urb *urb) spin_unlock_irqrestore(&tascam->lock, flags); if (total_bytes_for_urb > 0) { - int f; - src_buf = runtime->dma_area; - dst_buf = urb->transfer_buffer; + src_buf = runtime->dma_area + frames_to_bytes(runtime, offset_frames); + dst_buf = tascam->playback_routing_buffer; - for (f = 0; f < frames_to_copy; ++f) { - snd_pcm_uframes_t current_frame_pos = (offset_frames + f) % runtime->buffer_size; - char *src_frame = src_buf + frames_to_bytes(runtime, current_frame_pos); - char *dst_frame = dst_buf + (f * BYTES_PER_FRAME); - - char *src_12 = src_frame; - char *src_34 = src_frame + 6; - char *dst_line_out = dst_frame; - char *dst_digital_out = dst_frame + 6; - - if (tascam->line_out_source == 0) - memcpy(dst_line_out, src_12, 6); - else - memcpy(dst_line_out, src_34, 6); - - if (tascam->digital_out_source == 0) - memcpy(dst_digital_out, src_12, 6); - else - memcpy(dst_digital_out, src_34, 6); + /* Handle ring buffer wrap-around */ + if (offset_frames + frames_to_copy > runtime->buffer_size) { + size_t first_chunk_bytes = frames_to_bytes(runtime, runtime->buffer_size - offset_frames); + size_t second_chunk_bytes = total_bytes_for_urb - first_chunk_bytes; + memcpy(dst_buf, src_buf, first_chunk_bytes); + memcpy(dst_buf + first_chunk_bytes, runtime->dma_area, second_chunk_bytes); + } else { + memcpy(dst_buf, src_buf, total_bytes_for_urb); } + + /* Apply routing to the contiguous data in our routing buffer */ + process_playback_routing_us144mkii(tascam, dst_buf, dst_buf, frames_to_copy); + memcpy(urb->transfer_buffer, dst_buf, total_bytes_for_urb); } urb->dev = tascam->dev; @@ -1216,16 +1241,16 @@ static void tascam_capture_work_handler(struct work_struct *work) struct snd_pcm_substream *substream = tascam->capture_substream; struct snd_pcm_runtime *runtime; unsigned long flags; + u8 *raw_block = tascam->capture_decode_raw_block; + s32 *decoded_block = tascam->capture_decode_dst_block; + s32 *routed_block = tascam->capture_routing_buffer; if (!substream || !substream->runtime) return; runtime = substream->runtime; - u8 *raw_block = tascam->capture_decode_raw_block; - s32 *decoded_block = tascam->capture_decode_dst_block; - - if (!raw_block || !decoded_block) { - dev_err(tascam->card->dev, "Capture decode buffers not allocated!\n"); + if (!raw_block || !decoded_block || !routed_block) { + dev_err(tascam->card->dev, "Capture decode/routing buffers not allocated!\n"); return; } @@ -1251,43 +1276,31 @@ static void tascam_capture_work_handler(struct work_struct *work) break; decode_tascam_capture_block(raw_block, decoded_block); + process_capture_routing_us144mkii(tascam, decoded_block, routed_block); spin_lock_irqsave(&tascam->lock, flags); if (atomic_read(&tascam->capture_active)) { int f; for (f = 0; f < FRAMES_PER_DECODE_BLOCK; ++f) { - s32 *decoded_frame = decoded_block + (f * DECODED_CHANNELS_PER_FRAME); - char *dst_frame = runtime->dma_area + frames_to_bytes(runtime, tascam->driver_capture_pos); + // Get a pointer to the start of the current frame in the ALSA buffer + u8 *dst_frame_start = runtime->dma_area + frames_to_bytes(runtime, tascam->driver_capture_pos); + // Get a pointer to the start of the current routed frame (which contains 4 s32 channels) + s32 *routed_frame_start = routed_block + (f * NUM_CHANNELS); + int c; - s32 *src_analog = decoded_frame; - s32 *src_digital = decoded_frame + 2; + for (c = 0; c < NUM_CHANNELS; c++) { + // Pointer to the destination for the current channel (3 bytes) + u8 *dst_channel = dst_frame_start + (c * BYTES_PER_SAMPLE); + // Pointer to the source s32 for the current channel + s32 *src_channel_s32 = routed_frame_start + c; - /* The decoded samples are in S32_LE format. The ALSA format is - * S24_3LE. We copy the 3 least significant bytes by starting - * the memcpy from the second byte of the 32-bit integer. - */ - if (tascam->capture_12_source == 0) { - memcpy(dst_frame, ((char *)src_analog) + 1, 3); // Ch1 from Analog 1 - memcpy(dst_frame + 3, ((char *)(src_analog + 1)) + 1, 3); // Ch2 from Analog 2 - } else { - memcpy(dst_frame, ((char *)src_digital) + 1, 3); // Ch1 from Digital 1 - memcpy(dst_frame + 3, ((char *)(src_digital + 1)) + 1, 3); // Ch2 from Digital 2 + // The s32 sample is formatted as [0x00, LSB, Mid, MSB]. + // We need to copy the 3 significant bytes, skipping the first 0x00 byte. + memcpy(dst_channel, ((char *)src_channel_s32) + 1, 3); } - /* Since the device has only two analog inputs, channels 3-4 can be - * sourced from a copy of the analog inputs or the digital input. - */ - if (tascam->capture_34_source == 0) { - memcpy(dst_frame + 6, ((char *)src_analog) + 1, 3); // Ch3 from Analog 1 - memcpy(dst_frame + 9, ((char *)(src_analog + 1)) + 1, 3); // Ch4 from Analog 2 - } else { - memcpy(dst_frame + 6, ((char *)src_digital) + 1, 3); // Ch3 from Digital 1 - memcpy(dst_frame + 9, ((char *)(src_digital + 1)) + 1, 3); // Ch4 from Digital 2 - } - - tascam->driver_capture_pos++; - if (tascam->driver_capture_pos >= runtime->buffer_size) - tascam->driver_capture_pos = 0; + // Advance the driver's position in the ALSA buffer + tascam->driver_capture_pos = (tascam->driver_capture_pos + 1) % runtime->buffer_size; } } spin_unlock_irqrestore(&tascam->lock, flags); @@ -1346,8 +1359,6 @@ static int tascam_create_pcm(struct tascam_card *tascam) if (err < 0) return err; - err = snd_ctl_add(tascam->card, snd_ctl_new1(&tascam_latency_control, tascam)); - if (err < 0) return err; err = snd_ctl_add(tascam->card, snd_ctl_new1(&tascam_line_out_control, tascam)); if (err < 0) return err; err = snd_ctl_add(tascam->card, snd_ctl_new1(&tascam_digital_out_control, tascam)); @@ -1474,7 +1485,6 @@ static int tascam_probe(struct usb_interface *intf, const struct usb_device_id * spin_lock_init(&tascam->lock); atomic_set(&tascam->active_urbs, 0); INIT_WORK(&tascam->capture_work, tascam_capture_work_handler); - tascam->latency_profile = 1; tascam->line_out_source = 0; tascam->digital_out_source = 1; tascam->capture_12_source = 0;