Skip to content

File ALSASeqMIDIDriver.h

File List > cpp > sync > ALSASeqMIDIDriver.h

Go to the documentation of this file

/*
 * SPDX-FileCopyrightText: 2026 Stagelab Coop SCCL
 * SPDX-License-Identifier: GPL-3.0-or-later
 * SPDX-FileContributor: Ion Reguera <ion@stagelab.coop>
 *
 * This file is part of cuems-videocomposer.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
 */

#ifndef VIDEOCOMPOSER_ALSASEQMIDIDRIVER_H
#define VIDEOCOMPOSER_ALSASEQMIDIDRIVER_H

#include "MIDIDriver.h"
#include "MTCDecoder.h"
#include <string>
#include <memory>
#include <thread>
#include <mutex>
#include <atomic>
#include <cstdint>

// Forward declarations for ALSA
struct snd_seq;
typedef struct _snd_seq snd_seq_t;

namespace videocomposer {

class ALSASeqMIDIDriver : public MIDIDriver {
public:
    ALSASeqMIDIDriver();
    virtual ~ALSASeqMIDIDriver();

    // MIDIDriver interface
    bool open(const std::string& portId) override;
    void close() override;
    bool isConnected() const override;
    int64_t pollFrame() override;
    const char* getName() const override { return "ALSA-Sequencer"; }
    bool isSupported() const override;

    void setFramerate(double fps) { framerate_ = fps; }

    void setClockAdjustment(bool enabled) { midiClkAdj_ = enabled; }

    void setDelay(double delay) { delay_ = delay; }

    void setVerbose(bool verbose) { verbose_ = verbose; }

    int detectDevices(bool verbose = false);

    bool connectToMidiThrough();

private:
    // ALSA sequencer functions
    bool openSequencer();
    void closeSequencer();
    bool createPort();
    bool connectToPort(const std::string& portName);
    void processEvent(void* event);

    // Background thread function
    void runThread();

    snd_seq_t* seq_;
    int portId_;
    MTCDecoder mtcDecoder_;
    double framerate_;

    // Thread management
    std::thread thread_;
    std::mutex mutex_;
    std::atomic<bool> stopThread_;
    std::atomic<bool> connected_;

    // Frame tracking
    int64_t lastFrame_;
    int64_t currentFrame_;
    int stopCount_;

    // Configuration
    bool midiClkAdj_;
    double delay_;
    bool verbose_;
};

} // namespace videocomposer

#endif // VIDEOCOMPOSER_ALSASEQMIDIDRIVER_H