id
int64
0
877k
file_name
stringlengths
3
109
file_path
stringlengths
13
185
content
stringlengths
31
9.38M
size
int64
31
9.38M
language
stringclasses
1 value
extension
stringclasses
11 values
total_lines
int64
1
340k
avg_line_length
float64
2.18
149k
max_line_length
int64
7
2.22M
alphanum_fraction
float64
0
1
repo_name
stringlengths
6
66
repo_stars
int64
94
47.3k
repo_forks
int64
0
12k
repo_open_issues
int64
0
3.4k
repo_license
stringclasses
11 values
repo_extraction_date
stringclasses
197 values
exact_duplicates_redpajama
bool
2 classes
near_duplicates_redpajama
bool
2 classes
exact_duplicates_githubcode
bool
2 classes
exact_duplicates_stackv2
bool
1 class
exact_duplicates_stackv1
bool
2 classes
near_duplicates_githubcode
bool
2 classes
near_duplicates_stackv1
bool
2 classes
near_duplicates_stackv2
bool
1 class
1,532,204
overlaycontroller.h
openvrmc_OpenVR-MotionCompensation/client_overlay/src/overlaycontroller.h
#pragma once #include <openvr.h> #include <QtCore/QtCore> #include <QObject> #include <QSettings> #include <QQmlEngine> #include <QtGui/QOpenGLContext> #include <QOffscreenSurface> #include <QOpenGLFramebufferObject> #include <QQuickWindow> #include <QQuickItem> #include <QQuickRenderControl> #include <QSoundEffect> #include <memory> #include <atomic> #include "logging.h" #include "tabcontrollers/DeviceManipulationTabController.h" // application namespace namespace motioncompensation { class OverlayController : public QObject { Q_OBJECT Q_PROPERTY(bool desktopMode READ isDesktopMode) public: static constexpr const char* applicationKey = "ovrmc.VRMotionCompensation"; static constexpr const char* applicationName = "OpenVR Motion Compensation"; static constexpr const char* applicationVersionString = "v0.3.6"; private: vr::VROverlayHandle_t m_ulOverlayHandle = vr::k_ulOverlayHandleInvalid; vr::VROverlayHandle_t m_ulOverlayThumbnailHandle = vr::k_ulOverlayHandleInvalid; std::unique_ptr<QQuickRenderControl> m_pRenderControl; std::unique_ptr<QQuickWindow> m_pWindow; std::unique_ptr<QOpenGLFramebufferObject> m_pFbo; std::unique_ptr<QOpenGLContext> m_pOpenGLContext; std::unique_ptr<QOffscreenSurface> m_pOffscreenSurface; std::unique_ptr<QTimer> m_pPumpEventsTimer; std::unique_ptr<QTimer> m_pRenderTimer; bool dashboardVisible = false; QPoint m_ptLastMouse; Qt::MouseButtons m_lastMouseButtons = 0; vrmotioncompensation::VRMotionCompensation m_vrMotionCompensation; bool desktopMode; bool noSound; QUrl m_runtimePathUrl; std::atomic_uint32_t m_uniqueNumber = 0; QSoundEffect activationSoundEffect; QSoundEffect focusChangedSoundEffect; public: // I know it's an ugly hack to make them public to enable external access, but I am too lazy to implement getters. DeviceManipulationTabController deviceManipulationTabController; private: OverlayController(bool desktopMode, bool noSound) : QObject(), desktopMode(desktopMode), noSound(noSound) { } public: virtual ~OverlayController(); void Init(QQmlEngine* qmlEngine); void Shutdown(); vrmotioncompensation::VRMotionCompensation& vrMotionCompensation() { return m_vrMotionCompensation; } bool isDashboardVisible() { return dashboardVisible; } void SetWidget(QQuickItem* quickItem, const std::string& name, const std::string& key = ""); bool isDesktopMode() { return desktopMode; }; Q_INVOKABLE QString getVersionString(); Q_INVOKABLE QUrl getVRRuntimePathUrl(); Q_INVOKABLE bool soundDisabled(); const vr::VROverlayHandle_t& overlayHandle(); const vr::VROverlayHandle_t& overlayThumbnailHandle(); public slots: void renderOverlay(); void OnRenderRequest(); void OnTimeoutPumpEvents(); void showKeyboard(QString existingText, unsigned long userValue = 0); void playActivationSound(); void playFocusChangedSound(); signals: void keyBoardInputSignal(QString input, unsigned long userValue = 0); private: static QSettings* _appSettings; static std::unique_ptr<OverlayController> singleton; public: static OverlayController* getInstance() { return singleton.get(); } static OverlayController* createInstance(bool desktopMode, bool noSound) { singleton.reset(new motioncompensation::OverlayController(desktopMode, noSound)); return singleton.get(); } static QSettings* appSettings() { return _appSettings; } static void setAppSettings(QSettings* settings) { _appSettings = settings; } }; } // namespace motioncompensation
3,576
C++
.h
108
30.231481
123
0.792782
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,205
DeviceManipulationTabController.h
openvrmc_OpenVR-MotionCompensation/client_overlay/src/tabcontrollers/DeviceManipulationTabController.h
#pragma once #include <QObject> #include <QString> #include <memory> #include <openvr.h> #include <vrmotioncompensation.h> #include <vrmotioncompensation_types.h> #include <vector> #include "src/QGlobalShortcut/qglobalshortcut.h" class QQuickWindow; // application namespace namespace motioncompensation { // forward declaration class OverlayController; struct DeviceInfo { std::string serial = ""; vr::ETrackedDeviceClass deviceClass = vr::TrackedDeviceClass_Invalid; uint32_t openvrId = 0; int deviceStatus = 0; // 0: Normal, 1: Disconnected/Suspended vrmotioncompensation::MotionCompensationDeviceMode deviceMode = vrmotioncompensation::MotionCompensationDeviceMode::Default; }; class DeviceManipulationTabController : public QObject { Q_OBJECT struct ShortcutStruct { Qt::Key key; Qt::KeyboardModifiers modifiers; QGlobalShortcut* shortcut; QString description; void (DeviceManipulationTabController::* method)(); QMetaObject::Connection connectionHandler; bool isConnected; ShortcutStruct() { key = Qt::Key::Key_unknown; modifiers = Qt::KeyboardModifier::NoModifier; shortcut = nullptr; description = "No description provided"; method = nullptr; isConnected = false; } }; private: OverlayController* parent; QQuickWindow* widget; // Shortcut related ShortcutStruct shortcut[2]; // Device and ID storage std::vector<std::shared_ptr<DeviceInfo>> deviceInfos; // Holds all device infos. The index represents the OpenVR ID. Therefore there are many empty fields in this array std::map<uint32_t, uint32_t> TrackerArrayIdToDeviceId; std::map<uint32_t, uint32_t> HMDArrayIdToDeviceId; // Settings vrmotioncompensation::MotionCompensationMode _motionCompensationMode = vrmotioncompensation::MotionCompensationMode::ReferenceTracker; QString _RefTrackerSerial = ""; QString _HMDSerial = ""; double _LPFBeta = 0.2; uint32_t _samples = 100; bool _setZeroMode = false; vrmotioncompensation::MMFstruct_OVRMC_v1 _offset; bool _MotionCompensationIsOn = false; // Debug int DebugLoggerStatus = 0; // 0 = Off; 1 = Standby; 2 = Running QString debugModeButtonString; // Error return string QString m_deviceModeErrorString; // Threads std::thread identifyThread; unsigned settingsUpdateCounter = 0; public: ~DeviceManipulationTabController(); void initStage1(); void Beenden(); void initStage2(OverlayController* parent, QQuickWindow* widget); void eventLoopTick(vr::TrackedDevicePose_t* devicePoses); bool SearchDevices(); void handleEvent(const vr::VREvent_t& vrEvent); void reloadMotionCompensationSettings(); void saveMotionCompensationSettings(); void saveMotionCompensationShortcuts(); // Shortcut related functions void InitShortcuts(); void NewShortcut(int id, void (DeviceManipulationTabController::* method)(), QString description); void ConnectShortcut(int id); void DisconnectShortcut(int id); Q_INVOKABLE void newKey(int id, Qt::Key key, Qt::KeyboardModifiers modifier); Q_INVOKABLE void removeKey(int id); Q_INVOKABLE QString getStringFromKey(Qt::Key key); Q_INVOKABLE QString getStringFromModifiers(Qt::KeyboardModifiers key); Q_INVOKABLE Qt::Key getKey_AsKey(int id); Q_INVOKABLE QString getKey_AsString(int id); Q_INVOKABLE Qt::KeyboardModifiers getModifiers_AsModifiers(int id); Q_INVOKABLE QString getModifiers_AsString(int id); Q_INVOKABLE QString getKeyDescription(int id); // General getter and setter Q_INVOKABLE unsigned getDeviceCount(); Q_INVOKABLE QString getDeviceSerial(unsigned index); Q_INVOKABLE unsigned getOpenVRId(unsigned index); Q_INVOKABLE int getDeviceClass(unsigned index); Q_INVOKABLE int getDeviceState(unsigned index); Q_INVOKABLE int getDeviceMode(unsigned index); // Getter and setter related to the HMD and Tracker drop downs Q_INVOKABLE void setTrackerArrayID(unsigned deviceID, unsigned ArrayID); Q_INVOKABLE int getTrackerDeviceID(unsigned ArrayID); void setReferenceTracker(unsigned openVRId); Q_INVOKABLE void setHMDArrayID(unsigned deviceID, unsigned ArrayID); Q_INVOKABLE int getHMDDeviceID(unsigned ArrayID); void setHMD(unsigned openVRId); // General functions Q_INVOKABLE bool updateDeviceInfo(unsigned OpenVRId); void toggleMotionCompensationMode(); Q_INVOKABLE bool applySettings(unsigned Dindex, unsigned RTindex, bool EnableMotionCompensation); bool applySettings_ovrid(unsigned MCid, unsigned RTid, bool EnableMotionCompensation); void resetRefZeroPose(); Q_INVOKABLE QString getDeviceModeErrorString(); Q_INVOKABLE bool isDesktopModeActive(); // Settings Q_INVOKABLE bool setLPFBeta(double value); Q_INVOKABLE double getLPFBeta(); Q_INVOKABLE bool setSamples(unsigned value); Q_INVOKABLE unsigned getSamples(); Q_INVOKABLE void setZeroMode(bool setZero); Q_INVOKABLE bool getZeroMode(); Q_INVOKABLE void increaseLPFBeta(double value); Q_INVOKABLE void increaseSamples(int value); Q_INVOKABLE void setHMDtoRefTranslationOffset(unsigned axis, double value); Q_INVOKABLE void setHMDtoRefRotationOffset(unsigned axis, double value); Q_INVOKABLE void increaseRefTranslationOffset(unsigned axis, double value); Q_INVOKABLE void increaseRefRotationOffset(unsigned axis, double value); Q_INVOKABLE double getHMDtoRefTranslationOffset(unsigned axis); Q_INVOKABLE double getHMDtoRefRotationOffset(unsigned axis); Q_INVOKABLE void setMotionCompensationMode(unsigned NewMode); Q_INVOKABLE int getMotionCompensationMode(); // Debug mode Q_INVOKABLE bool setDebugMode(bool TestForStandby); Q_INVOKABLE QString getDebugModeButtonText(); public slots: signals: void deviceCountChanged(); void deviceInfoChanged(unsigned index); void settingChanged(); void offsetChanged(); void debugModeChanged(); }; } // namespace motioncompensation
5,897
C++
.h
147
36.911565
171
0.793551
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,206
qglobalshortcut.h
openvrmc_OpenVR-MotionCompensation/client_overlay/src/QGlobalShortcut/qglobalshortcut.h
#ifndef QGLOBALSHORTCUTPRIVATE_H #define QGLOBALSHORTCUTPRIVATE_H #include <QObject> #include <QAbstractNativeEventFilter> class QKeySequence; class QGlobalShortcutPrivate; class QGlobalShortcut : public QObject, public QAbstractNativeEventFilter { Q_OBJECT public: explicit QGlobalShortcut(QObject *parent = nullptr); ~QGlobalShortcut(); bool nativeEventFilter(const QByteArray &eventType, void *message, long *result) override; QKeySequence shortcut(); bool isEmpty(); bool isEnabled(); signals: void activated(); public slots: bool setShortcut(const QKeySequence &keySequence); bool unsetShortcut(); void setEnabled(bool enable); private: QGlobalShortcutPrivate *sPrivate; }; #endif // QGLOBALSHORTCUTPRIVATE_H
771
C++
.h
26
26.461538
94
0.79212
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,207
vrmotioncompensation_types.h
openvrmc_OpenVR-MotionCompensation/lib_vrmotioncompensation/include/vrmotioncompensation_types.h
#pragma once #include <stdint.h> namespace vrmotioncompensation { enum class MotionCompensationMode : uint32_t { Disabled = 0, ReferenceTracker = 1, }; enum class MotionCompensationDeviceMode : uint32_t { Default = 0, ReferenceTracker = 1, MotionCompensated = 2, }; struct DeviceInfo { uint32_t OpenVRId; vr::ETrackedDeviceClass deviceClass; MotionCompensationDeviceMode deviceMode; }; struct MMFstruct_OVRMC_v1 { /*#define FLAG_ENABLE_MC 0 #define FLAG_RESETZEROPOSE 1*/ vr::HmdVector3d_t Translation; vr::HmdVector3d_t Rotation; vr::HmdQuaternion_t QRotation; uint32_t Flags_1; uint32_t Flags_2; double Reserved_double[10]; int Reserved_int[10]; MMFstruct_OVRMC_v1() { Translation = { 0, 0, 0 }; Rotation = { 0, 0, 0 }; QRotation = { 0, 0, 0, 0 }; Flags_1 = 0; Flags_2 = 0; } }; } // end namespace vrmotioncompensation
897
C++
.h
42
18.571429
51
0.715466
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,209
ipc_protocol.h
openvrmc_OpenVR-MotionCompensation/lib_vrmotioncompensation/include/ipc_protocol.h
#pragma once #include "vrmotioncompensation_types.h" #include <utility> #define IPC_PROTOCOL_VERSION 3 namespace vrmotioncompensation { namespace ipc { enum class RequestType : uint32_t { None, // IPC connection handling IPC_ClientConnect, IPC_ClientDisconnect, IPC_Ping, DeviceManipulation_GetDeviceInfo, DeviceManipulation_MotionCompensationMode, DeviceManipulation_SetMotionCompensationProperties, DeviceManipulation_ResetRefZeroPose, DeviceManipulation_SetOffsets, DebugLogger_Settings, }; enum class ReplyType : uint32_t { None, IPC_ClientConnect, IPC_Ping, GenericReply, DeviceManipulation_GetDeviceInfo }; enum class ReplyStatus : uint32_t { None, Ok, UnknownError, InvalidId, AlreadyInUse, InvalidType, NotFound, SharedMemoryError, InvalidVersion, MissingProperty, InvalidOperation, NotTracking }; struct Request_IPC_ClientConnect { uint32_t messageId; uint32_t ipcProcotolVersion; char queueName[128]; }; struct Request_IPC_ClientDisconnect { uint32_t clientId; uint32_t messageId; }; struct Request_IPC_Ping { uint32_t clientId; uint32_t messageId; uint64_t nonce; }; struct Request_OpenVR_GenericClientMessage { uint32_t clientId; uint32_t messageId; // Used to associate with Reply }; struct Request_OpenVR_GenericDeviceIdMessage { uint32_t clientId; uint32_t messageId; // Used to associate with Reply uint32_t OpenVRId; }; struct Request_DeviceManipulation_MotionCompensationMode { uint32_t clientId; uint32_t messageId; // Used to associate with Reply uint32_t MCdeviceId; // Motion compensated device ID uint32_t RTdeviceId; // Reference tracker device ID MotionCompensationMode CompensationMode; }; struct Request_DeviceManipulation_SetMotionCompensationProperties { uint32_t clientId; uint32_t messageId; // Used to associate with Reply double LPFBeta; uint32_t samples; bool setZero; //MMFstruct_v1 offsets; }; struct Request_DeviceManipulation_ResetRefZeroPose { uint32_t clientId; uint32_t messageId; // Used to associate with Reply }; struct Request_DeviceManipulation_SetOffsets { uint32_t clientId; uint32_t messageId; // Used to associate with Reply MMFstruct_OVRMC_v1 offsets; }; struct Request_DebugLogger_Settings { uint32_t clientId; uint32_t messageId; // Used to associate with Reply uint32_t MaxDebugPoints; bool enabled; }; struct Request { Request() { } Request(RequestType type) : type(type) { timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } Request(RequestType type, uint64_t timestamp) : type(type), timestamp(timestamp) { } void refreshTimestamp() { timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } RequestType type = RequestType::None; int64_t timestamp = 0; // milliseconds since epoch union MsgUnion { Request_IPC_ClientConnect ipc_ClientConnect; Request_IPC_ClientDisconnect ipc_ClientDisconnect; Request_IPC_Ping ipc_Ping; Request_OpenVR_GenericClientMessage ovr_GenericClientMessage; Request_OpenVR_GenericDeviceIdMessage ovr_GenericDeviceIdMessage; Request_DeviceManipulation_MotionCompensationMode dm_MotionCompensationMode; Request_DeviceManipulation_SetMotionCompensationProperties dm_SetMotionCompensationProperties; Request_DeviceManipulation_ResetRefZeroPose dm_ResetRefZeroPose; Request_DeviceManipulation_SetOffsets dm_SetOffsets; Request_DebugLogger_Settings dl_Settings; MsgUnion() { } } msg; }; struct Reply_IPC_ClientConnect { uint32_t clientId; uint32_t ipcProcotolVersion; }; struct Reply_IPC_Ping { uint64_t nonce; }; struct Reply_DeviceManipulation_GetDeviceInfo { uint32_t OpenVRId; vr::ETrackedDeviceClass deviceClass; MotionCompensationDeviceMode deviceMode; }; struct Reply { Reply() { } Reply(ReplyType type) : type(type) { timestamp = std::chrono::duration_cast <std::chrono::milliseconds>(std::chrono::system_clock::now().time_since_epoch()).count(); } Reply(ReplyType type, uint64_t timestamp) : type(type), timestamp(timestamp) { } ReplyType type = ReplyType::None; uint64_t timestamp = 0; // milliseconds since epoch uint32_t messageId; ReplyStatus status; union MsgUnion { Reply_IPC_ClientConnect ipc_ClientConnect; Reply_IPC_Ping ipc_Ping; Reply_DeviceManipulation_GetDeviceInfo dm_deviceInfo; MsgUnion() { } } msg; }; } // end namespace ipc } // end namespace vrmotioncompensation
4,861
C++
.h
186
22.311828
132
0.743601
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,210
vrmotioncompensation.h
openvrmc_OpenVR-MotionCompensation/lib_vrmotioncompensation/include/vrmotioncompensation.h
#pragma once #include <stdint.h> #include <string> #include <future> #include <mutex> #include <thread> #include <map> #include <memory> #include <random> #include <string> #include <openvr.h> #include <boost/interprocess/ipc/message_queue.hpp> namespace vr { // Copied from openvr_driver.h struct DriverPose_t { /* Time offset of this pose, in seconds from the actual time of the pose, * relative to the time of the PoseUpdated() call made by the driver. */ double poseTimeOffset; /* Generally, the pose maintained by a driver * is in an inertial coordinate system different * from the world system of x+ right, y+ up, z+ back. * Also, the driver is not usually tracking the "head" position, * but instead an internal IMU or another reference point in the HMD. * The following two transforms transform positions and orientations * to app world space from driver world space, * and to HMD head space from driver local body space. * * We maintain the driver pose state in its internal coordinate system, * so we can do the pose prediction math without having to * use angular acceleration. A driver's angular acceleration is generally not measured, * and is instead calculated from successive samples of angular velocity. * This leads to a noisy angular acceleration values, which are also * lagged due to the filtering required to reduce noise to an acceptable level. */ vr::HmdQuaternion_t qWorldFromDriverRotation; double vecWorldFromDriverTranslation[3]; vr::HmdQuaternion_t qDriverFromHeadRotation; double vecDriverFromHeadTranslation[3]; /* State of driver pose, in meters and radians. */ /* Position of the driver tracking reference in driver world space * +[0] (x) is right * +[1] (y) is up * -[2] (z) is forward */ double vecPosition[3]; /* Velocity of the pose in meters/second */ double vecVelocity[3]; /* Acceleration of the pose in meters/second */ double vecAcceleration[3]; /* Orientation of the tracker, represented as a quaternion */ vr::HmdQuaternion_t qRotation; /* Angular velocity of the pose in axis-angle * representation. The direction is the angle of * rotation and the magnitude is the angle around * that axis in radians/second. */ double vecAngularVelocity[3]; /* Angular acceleration of the pose in axis-angle * representation. The direction is the angle of * rotation and the magnitude is the angle around * that axis in radians/second^2. */ double vecAngularAcceleration[3]; ETrackingResult result; bool poseIsValid; bool willDriftInYaw; bool shouldApplyHeadModel; bool deviceIsConnected; }; } // end namespace vr #include <ipc_protocol.h> namespace vrmotioncompensation { class vrmotioncompensation_exception : public std::runtime_error { public: const int errorcode = 0; using std::runtime_error::runtime_error; vrmotioncompensation_exception(const std::string& msg, int code) : std::runtime_error(msg), errorcode(code) { } }; class vrmotioncompensation_connectionerror : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_invalidversion : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_invalidid : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_invalidtype : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_notfound : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_sharedmemoryerror : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_alreadyinuse : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class vrmotioncompensation_toomanydevices : public vrmotioncompensation_exception { using vrmotioncompensation_exception::vrmotioncompensation_exception; }; class VRMotionCompensation { public: VRMotionCompensation(const std::string& driverQueue = "driver_vrmotioncompensation.server_queue", const std::string& clientQueue = "driver_vrmotioncompensation.client_queue."); ~VRMotionCompensation(); void connect(); bool isConnected() const; void disconnect(); void ping(bool modal = true, bool enableReply = false); void getDeviceInfo(uint32_t deviceId, DeviceInfo& info);; void setDeviceMotionCompensationMode(uint32_t MCdeviceId, uint32_t RTdeviceId, MotionCompensationMode Mode = MotionCompensationMode::Disabled, bool modal = true); void setMoticonCompensationSettings(double LPF_Beta, uint32_t samples, bool setZero); void resetRefZeroPose(); void setOffsets(MMFstruct_OVRMC_v1 offsets); void startDebugLogger(bool enable, bool modal = true); private: std::recursive_mutex _mutex; uint32_t m_clientId = 0; bool _ipcThreadRunning = false; volatile bool _ipcThreadStop = false; std::thread _ipcThread; static void _ipcThreadFunc(VRMotionCompensation* _this); std::random_device _ipcRandomDevice; std::uniform_int_distribution<uint32_t> _ipcRandomDist; struct _ipcPromiseMapEntry { _ipcPromiseMapEntry() : isValid(false) { } _ipcPromiseMapEntry(std::promise<ipc::Reply>&& _promise, bool isValid = true) : promise(std::move(_promise)), isValid(isValid) { } bool isValid; std::promise<ipc::Reply> promise; }; std::map<uint32_t, _ipcPromiseMapEntry> _ipcPromiseMap; std::string _ipcServerQueueName; std::string _ipcClientQueueName; boost::interprocess::message_queue* _ipcServerQueue = nullptr; boost::interprocess::message_queue* _ipcClientQueue = nullptr; }; } // end namespace vrmotioncompensation
6,035
C++
.h
158
35.35443
178
0.78345
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,211
logging.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/logging.h
#pragma once // easylogging includes #ifdef NDEBUG #undef NDEBUG //#define ELPP_THREAD_SAFE //#define ELPP_NO_DEFAULT_LOG_FILE #include <easylogging++.h> #define NDEBUG #else //#define ELPP_THREAD_SAFE //#define ELPP_NO_DEFAULT_LOG_FILE #include <easylogging++.h> #endif
272
C++
.h
13
19.846154
34
0.782946
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,212
driver_ipc_shm.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/com/shm/driver_ipc_shm.h
#pragma once #include <thread> #include <string> #include <map> #include <mutex> #include <memory> #include <boost/interprocess/ipc/message_queue.hpp> // driver namespace namespace vrmotioncompensation { // forward declarations namespace ipc { struct Reply; } namespace driver { // forward declarations class ServerDriver; class IpcShmCommunicator { public: void init(ServerDriver* driver); void shutdown(); private: static void _ipcThreadFunc(IpcShmCommunicator* _this, ServerDriver* driver); void sendReply(uint32_t clientId, const ipc::Reply& reply); std::mutex _sendMutex; ServerDriver* _driver = nullptr; std::thread _ipcThread; volatile bool _ipcThreadRunning = false; volatile bool _ipcThreadStopFlag = false; std::string _ipcQueueName = "driver_vrmotioncompensation.server_queue"; uint32_t _ipcClientIdNext = 1; std::map<uint32_t, std::shared_ptr<boost::interprocess::message_queue>> _ipcEndpoints; // This is not exactly multi-user safe, maybe I fix it in the future uint32_t _setMotionCompensationClientId = 0; uint32_t _setMotionCompensationMessageId = 0; }; } // end namespace driver } // end namespace vrmotioncompensation
1,213
C++
.h
41
26.707317
89
0.759243
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,213
DeviceManipulationHandle.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/DeviceManipulationHandle.h
#pragma once #include <openvr_driver.h> #include <vrmotioncompensation_types.h> #include "../hooks/common.h" // driver namespace namespace vrmotioncompensation { namespace driver { // forward declarations class ServerDriver; class InterfaceHooks; class MotionCompensationManager; // Stores manipulation information about an Open VR device class DeviceManipulationHandle { private: bool m_isValid = false; ServerDriver* m_parent; MotionCompensationManager& m_motionCompensationManager; vr::ETrackedDeviceClass m_eDeviceClass = vr::TrackedDeviceClass_Invalid; uint32_t m_openvrId = vr::k_unTrackedDeviceIndexInvalid; std::string m_serialNumber; std::shared_ptr<InterfaceHooks> m_serverDriverHooks; MotionCompensationDeviceMode m_deviceMode = MotionCompensationDeviceMode::Default; public: DeviceManipulationHandle(const char* serial, vr::ETrackedDeviceClass eDeviceClass); bool isValid() const { return m_isValid; } void setValid(bool isValid); vr::ETrackedDeviceClass deviceClass() const { return m_eDeviceClass; } uint32_t openvrId() const { return m_openvrId; } void setOpenvrId(uint32_t id) { m_openvrId = id; } const std::string& serialNumber() { return m_serialNumber; } void setServerDriverHooks(std::shared_ptr<InterfaceHooks> hooks) { m_serverDriverHooks = hooks; } MotionCompensationDeviceMode getDeviceMode() const { return m_deviceMode; } void setMotionCompensationDeviceMode(MotionCompensationDeviceMode DeviceMode); bool handlePoseUpdate(uint32_t& unWhichDevice, vr::DriverPose_t& newPose, uint32_t unPoseStructSize); //vr::HmdVector3d_t ToEulerAngles(vr::HmdQuaternion_t q); }; } // end namespace driver } // end namespace vrmotioncompensation
1,828
C++
.h
62
25.725806
104
0.764874
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,214
Debugger.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/Debugger.h
#pragma once #include <openvr_driver.h> #include <boost/timer/timer.hpp> #include <boost/chrono/chrono.hpp> #include <boost/chrono/system_clocks.hpp> #define MAX_DEBUG_ENTRIES 50000 #define MAX_DEBUG_VECTORS 24 #define MAX_DEBUG_QUATERNIONS 8 namespace vrmotioncompensation { namespace driver { class Debugger { private: struct DebugData { std::string Name = ""; bool InUse = false; }; struct DebugDataV3 : DebugData { vr::HmdVector3d_t Data[MAX_DEBUG_ENTRIES]; }; struct DebugDataQ4 : DebugData { vr::HmdQuaternion_t Data[MAX_DEBUG_ENTRIES]; }; template< class Clock > class timer { typename Clock::time_point tstart; public: timer() { } typename Clock::duration elapsed() const { return Clock::now() - tstart; } double seconds() const { return elapsed().count() * ((double)Clock::period::num / Clock::period::den); } void start() { tstart = Clock::now(); } }; public: Debugger(); ~Debugger(); void Start(); void Stop(); bool IsRunning(); void CountUp(); void AddDebugData(vr::HmdVector3d_t Data, int ID); void AddDebugData(vr::HmdQuaternion_t Data, int ID); void AddDebugData(const double Data[3], int ID); void SetDebugNameV3(std::string Name, int ID); void SetDebugNameQ4(std::string Name, int ID); void WriteFile(); void gotRef(); void gotHmd(); bool hasRef(); bool hasHmd(); private: int DebugCounter = 0; DebugDataV3 DebugDataV3[MAX_DEBUG_VECTORS]; DebugDataQ4 DebugDataQ4[MAX_DEBUG_QUATERNIONS]; timer<boost::chrono::high_resolution_clock> DebugTimer; double DebugTiming[MAX_DEBUG_ENTRIES]; bool DebuggerRunning = false; bool Ref = false; bool Hmd = false; bool WroteToFile = false; std::recursive_mutex _mut; }; } }
1,866
C++
.h
79
19.56962
82
0.680272
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,215
MotionCompensationManager.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/devicemanipulation/MotionCompensationManager.h
#pragma once #include <openvr_driver.h> #include <vrmotioncompensation_types.h> #include <openvr_math.h> #include "../logging.h" #include "Debugger.h" #include <boost/timer/timer.hpp> #include <boost/chrono/chrono.hpp> #include <boost/chrono/system_clocks.hpp> #include <boost/interprocess/windows_shared_memory.hpp> #include <boost/interprocess/mapped_region.hpp> // driver namespace namespace vrmotioncompensation { namespace driver { // forward declarations class ServerDriver; class DeviceManipulationHandle; class Spinlock { // Source: https://rigtorp.se/spinlock/ std::atomic<bool> lock_ = { 0 }; public: void lock() noexcept { for (;;) { // Optimistically assume the lock is free on the first try if (!lock_.exchange(true, std::memory_order_acquire)) { return; } // Wait for lock to be released without generating cache misses while (lock_.load(std::memory_order_relaxed)) { // Issue X86 PAUSE or ARM YIELD instruction to reduce contention between // hyper-threads YieldProcessor(); } } } bool try_lock() noexcept { // First do a relaxed load to check if lock is free in order to prevent // unnecessary cache misses if someone does while(!try_lock()) return !lock_.load(std::memory_order_relaxed) && !lock_.exchange(true, std::memory_order_acquire); } void unlock() noexcept { lock_.store(false, std::memory_order_release); } }; /*class Spinlock { std::atomic_flag _Flag = ATOMIC_FLAG_INIT; public: void lock() noexcept { while (_Flag.test_and_set(std::memory_order_acquire)) { // pause insn YieldProcessor(); } } void unlock() noexcept { _Flag.clear(std::memory_order_release); } };*/ class MotionCompensationManager { public: MotionCompensationManager(ServerDriver* parent); bool setMotionCompensationMode(MotionCompensationMode Mode, int MCdevice, int RTdevice); void setNewMotionCompensatedDevice(int McDevice); void setNewReferenceTracker(int RtDevice); MotionCompensationMode getMotionCompensationMode() { return _Mode; } void setAlpha(uint32_t samples); void setLpfBeta(double NewBeta) { _LpfBeta = NewBeta; } double getLPFBeta() { return _LpfBeta; } int getMCdeviceID() { return _McDeviceID; } int getRTdeviceID() { return _RtDeviceID; } void setZeroMode(bool setZero); void setOffsets(MMFstruct_OVRMC_v1 offsets); bool isZeroPoseValid(); void resetZeroPose(); void setZeroPose(const vr::DriverPose_t& pose); void updateRefPose(const vr::DriverPose_t& pose); bool applyMotionCompensation(vr::DriverPose_t& pose); void runFrame(); private: double vecVelocity(double time, const double vecPosition, const double Old_vecPosition); double vecAcceleration(double time, const double vecVelocity, const double Old_vecVelocity); double rotVelocity(double time, const double vecAngle, const double Old_vecAngle); double DEMA(const double RawData, int Axis); vr::HmdVector3d_t LPF(const double RawData[3], vr::HmdVector3d_t SmoothData); vr::HmdVector3d_t LPF(vr::HmdVector3d_t RawData, vr::HmdVector3d_t SmoothData); vr::HmdQuaternion_t lowPassFilterQuaternion(vr::HmdQuaternion_t RawData, vr::HmdQuaternion_t SmoothData); vr::HmdQuaternion_t slerp(vr::HmdQuaternion_t q1, vr::HmdQuaternion_t q2, double lambda); vr::HmdVector3d_t toEulerAngles(vr::HmdQuaternion_t q); const double angleDifference(double angle1, double angle2); vr::HmdVector3d_t transform(vr::HmdVector3d_t VecRotation, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t point); vr::HmdVector3d_t transform(vr::HmdQuaternion_t quat, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t point); vr::HmdVector3d_t transform(vr::HmdVector3d_t VecRotation, vr::HmdVector3d_t VecPosition, vr::HmdVector3d_t centerOfRotation, vr::HmdVector3d_t point); std::string _vecToStr(char* name, vr::HmdVector3d_t & v) { std::stringstream ss; ss << name << ": [" << v.v[0] << ", " << v.v[1] << ", " << v.v[2] << "]"; return ss.str(); } std::string _vecToStr(char* name, double v[3]) { std::stringstream ss; ss << name << ": [" << v[0] << ", " << v[1] << ", " << v[2] << "]"; return ss.str(); } std::string _quatToStr(const char* name, const vr::HmdQuaternion_t & q) { std::stringstream ss; ss << name << ": [" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << "]"; return ss.str(); } inline void _copyVec(double(&d)[3], const double(&s)[3]) { d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; } inline void _copyVec(vr::HmdVector3d_t & d, const double(&s)[3]) { d.v[0] = s[0]; d.v[1] = s[1]; d.v[2] = s[2]; } inline void _zeroVec(double(&d)[3]) { d[0] = d[1] = d[2] = 0.0; } inline void _zeroVec(vr::HmdVector3d_t & d) { d.v[0] = d.v[1] = d.v[2] = 0.0; } ServerDriver* m_parent; boost::interprocess::windows_shared_memory _shdmem; boost::interprocess::mapped_region _region; int _McDeviceID = -1; int _RtDeviceID = -1; long long _RefTrackerLastTime = -1; vr::DriverPose_t _RefTrackerLastPose; vr::HmdVector3d_t _RotEulerFilterOld = {0, 0, 0}; double _LpfBeta = 0.2; double _Alpha = -1.0; uint32_t _Samples = 100; bool _SetZeroMode = false; Spinlock _ZeroLock, _RefLock, _RefVelLock; bool _Enabled = false; MotionCompensationMode _Mode = MotionCompensationMode::Disabled; // Offset data MMFstruct_OVRMC_v1 _Offset; MMFstruct_OVRMC_v1* _Poffset = nullptr; // Zero position vr::HmdVector3d_t _ZeroPos = { 0, 0, 0 }; vr::HmdQuaternion_t _ZeroRot = { 1, 0, 0, 0 }; bool _ZeroPoseValid = false; // Reference position vr::HmdVector3d_t _RefPos = { 0, 0, 0 }; vr::HmdVector3d_t _Filter_vecPosition[2] = { 0, 0, 0 }; vr::HmdVector3d_t _RefVel = { 0, 0, 0 }; vr::HmdVector3d_t _RefAcc = { 0, 0, 0 }; vr::HmdQuaternion_t _RefRot = { 1, 0, 0, 0 }; vr::HmdQuaternion_t _RefRotInv = { 1, 0, 0, 0 }; vr::HmdQuaternion_t _Filter_rotPosition[2] = { 1, 0, 0, 0 }; vr::HmdVector3d_t _RefRotVel = { 0, 0, 0 }; vr::HmdVector3d_t _RefRotAcc = { 0, 0, 0 }; bool _RefPoseValid = false; int _RefPoseValidCounter = 0; }; } }
6,420
C++
.h
196
28.306122
154
0.663302
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,216
ServerDriver.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/driver/ServerDriver.h
#pragma once #include <memory> #include <mutex> #include <queue> #include <openvr_driver.h> #include <vrmotioncompensation_types.h> #include "../hooks/common.h" #include "../logging.h" #include "../com/shm/driver_ipc_shm.h" #include "../devicemanipulation/MotionCompensationManager.h" // driver namespace namespace vrmotioncompensation { namespace driver { // forward declarations class ServerDriver; class InterfaceHooks; class VirtualDeviceDriver; class DeviceManipulationHandle; /** * Implements the IServerTrackedDeviceProvider interface. * * Its the main entry point of the driver. It's a singleton which manages all devices owned by this driver, * and also handles the whole "hacking into OpenVR" stuff. */ class ServerDriver : public vr::IServerTrackedDeviceProvider { public: ServerDriver(); virtual ~ServerDriver(); //// from IServerTrackedDeviceProvider //// /** initializes the driver. This will be called before any other methods are called. */ virtual vr::EVRInitError Init(vr::IVRDriverContext* pDriverContext) override; /** cleans up the driver right before it is unloaded */ virtual void Cleanup() override; /** Returns the version of the ITrackedDeviceServerDriver interface used by this driver */ virtual const char* const* GetInterfaceVersions() { return vr::k_InterfaceVersions; } /** Allows the driver do to some work in the main loop of the server. Call frequency seems to be around 90Hz. */ virtual void RunFrame() override; /** Returns true if the driver wants to block Standby mode. */ virtual bool ShouldBlockStandbyMode() override { return false; } /** Called when the system is entering Standby mode */ virtual void EnterStandby() override { } /** Called when the system is leaving Standby mode */ virtual void LeaveStandby() override { } //// self //// static ServerDriver* getInstance() { return singleton; } static std::string getInstallDirectory() { return installDir; } DeviceManipulationHandle* getDeviceManipulationHandleById(uint32_t unWhichDevice); // internal API /* Motion Compensation related */ MotionCompensationManager& motionCompensation() { return m_motionCompensation; } //// function hooks related //// void hooksTrackedDeviceAdded(void* serverDriverHost, int version, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass& eDeviceClass, void* pDriver); void hooksTrackedDeviceActivated(void* serverDriver, int version, uint32_t unObjectId); bool hooksTrackedDevicePoseUpdated(void* serverDriverHost, int version, uint32_t& unWhichDevice, vr::DriverPose_t& newPose, uint32_t& unPoseStructSize); private: static ServerDriver* singleton; static std::string installDir; //// ipc shm related //// IpcShmCommunicator shmCommunicator; //// device manipulation related //// std::recursive_mutex _deviceManipulationHandlesMutex; std::map<void*, std::shared_ptr<DeviceManipulationHandle>> _deviceManipulationHandles; DeviceManipulationHandle* _openvrIdDeviceManipulationHandle[vr::k_unMaxTrackedDeviceCount]; int _deviceVersionMap[vr::k_unMaxTrackedDeviceCount]; //// motion compensation related //// MotionCompensationManager m_motionCompensation; //// function hooks related //// std::shared_ptr<InterfaceHooks> _driverContextHooks; }; } // end namespace driver } // end namespace vrmotioncompensation
3,496
C++
.h
93
33.913978
158
0.753846
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,217
WatchdogProvider.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/driver/WatchdogProvider.h
#pragma once #include <openvr_driver.h> // driver namespace namespace vrmotioncompensation { namespace driver { /** * Implements the IVRWatchdogProvider interface. * * Its only purpose seems to be to start SteamVR by calling WatchdogWakeUp() from the IVRWatchdogHost interface. * Valve probably uses this interface to start SteamVR whenever a button is pressed on the controller or hmd. * We must implement it but currently we don't use it for anything. */ class WatchdogProvider : public vr::IVRWatchdogProvider { public: /** initializes the driver in watchdog mode. */ virtual vr::EVRInitError Init(vr::IVRDriverContext* pDriverContext) override; /** cleans up the driver right before it is unloaded */ virtual void Cleanup() override; }; } }
785
C++
.h
24
30.041667
113
0.763852
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,218
ITrackedDeviceServerDriver005Hooks.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/ITrackedDeviceServerDriver005Hooks.h
#pragma once #include "common.h" #include <openvr_driver.h> #include <memory> #include <map> namespace vrmotioncompensation { namespace driver { // forward declarations class ServerDriver; class ITrackedDeviceServerDriver005Hooks : public InterfaceHooks { public: typedef vr::EVRInitError(*activate_t)(void*, uint32_t unObjectId); static std::shared_ptr<InterfaceHooks> createHooks(void* iptr); virtual ~ITrackedDeviceServerDriver005Hooks(); private: HookData<activate_t> activateHook; void* activateAddress = nullptr; ITrackedDeviceServerDriver005Hooks(void* iptr); template<typename T> struct _hookedAdressMapEntry { unsigned useCount = 0; HookData<T> hookData; }; static std::map<void*, _hookedAdressMapEntry<activate_t>> _hookedActivateAdressMap; static vr::EVRInitError _activate(void*, uint32_t unObjectId); }; } }
893
C++
.h
32
24.65625
86
0.768235
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,219
IVRServerDriverHost006Hooks.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost006Hooks.h
#pragma once #include "common.h" #include <memory> #include <openvr_driver.h> namespace vrmotioncompensation { namespace driver { class IVRServerDriverHost006Hooks : public InterfaceHooks { public: typedef bool(*trackedDeviceAdded_t)(void*, const char*, vr::ETrackedDeviceClass, void*); typedef void(*trackedDevicePoseUpdated_t)(void*, uint32_t, const vr::DriverPose_t&, uint32_t); static std::shared_ptr<InterfaceHooks> createHooks(void* iptr); virtual ~IVRServerDriverHost006Hooks(); static void trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); private: bool _isHooked = false; IVRServerDriverHost006Hooks(void* iptr); static HookData<trackedDeviceAdded_t> trackedDeviceAddedHook; static HookData<trackedDevicePoseUpdated_t> trackedDevicePoseUpdatedHook; static bool _trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver); static void _trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); }; } }
1,169
C++
.h
26
41.769231
141
0.792769
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,220
IVRDriverContextHooks.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRDriverContextHooks.h
#pragma once #include "common.h" #include <openvr_driver.h> #include <memory> #include <map> namespace vrmotioncompensation { namespace driver { // forward declarations class ServerDriver; class IVRDriverContextHooks : public InterfaceHooks { public: typedef void* (*getGenericInterface_t)(vr::IVRDriverContext*, const char* pchInterfaceVersion, vr::EVRInitError* peError); static std::shared_ptr<InterfaceHooks> getInterfaceHook(std::string interfaceVersion); static std::shared_ptr<InterfaceHooks> createHooks(void* iptr); virtual ~IVRDriverContextHooks(); private: bool _isHooked = false; IVRDriverContextHooks(void* iptr); static HookData<getGenericInterface_t> getGenericInterfaceHook; static std::map<std::string, std::shared_ptr<InterfaceHooks>> _hookedInterfaces; static void* _getGenericInterface(vr::IVRDriverContext*, const char* pchInterfaceVersion, vr::EVRInitError* peError); }; } }
951
C++
.h
27
32.222222
125
0.785558
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,221
IVRServerDriverHost004Hooks.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost004Hooks.h
#pragma once #include "common.h" #include <memory> #include <openvr_driver.h> namespace vrmotioncompensation { namespace driver { class IVRServerDriverHost004Hooks : public InterfaceHooks { public: typedef bool(*trackedDeviceAdded_t)(void*, const char*, vr::ETrackedDeviceClass, void*); typedef void(*trackedDevicePoseUpdated_t)(void*, uint32_t, const vr::DriverPose_t&, uint32_t); static std::shared_ptr<InterfaceHooks> createHooks(void* iptr); virtual ~IVRServerDriverHost004Hooks(); static void trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); private: bool _isHooked = false; IVRServerDriverHost004Hooks(void* iptr); static HookData<trackedDeviceAdded_t> trackedDeviceAddedHook; static HookData<trackedDevicePoseUpdated_t> trackedDevicePoseUpdatedHook; static bool _trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver); static void _trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); }; } }
1,167
C++
.h
26
41.769231
141
0.79417
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,222
IVRServerDriverHost005Hooks.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/IVRServerDriverHost005Hooks.h
#pragma once #include "common.h" #include <memory> #include <openvr_driver.h> namespace vrmotioncompensation { namespace driver { class IVRServerDriverHost005Hooks : public InterfaceHooks { public: typedef bool(*trackedDeviceAdded_t)(void*, const char*, vr::ETrackedDeviceClass, void*); typedef void(*trackedDevicePoseUpdated_t)(void*, uint32_t, const vr::DriverPose_t&, uint32_t); static std::shared_ptr<InterfaceHooks> createHooks(void* iptr); virtual ~IVRServerDriverHost005Hooks(); static void trackedDevicePoseUpdatedOrig(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); private: bool _isHooked = false; IVRServerDriverHost005Hooks(void* iptr); static HookData<trackedDeviceAdded_t> trackedDeviceAddedHook; static HookData<trackedDevicePoseUpdated_t> trackedDevicePoseUpdatedHook; static bool _trackedDeviceAdded(void* _this, const char* pchDeviceSerialNumber, vr::ETrackedDeviceClass eDeviceClass, void* pDriver); static void _trackedDevicePoseUpdated(void* _this, uint32_t unWhichDevice, const vr::DriverPose_t& newPose, uint32_t unPoseStructSize); }; } }
1,169
C++
.h
26
41.769231
141
0.792769
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,223
common.h
openvrmc_OpenVR-MotionCompensation/driver_vrmotioncompensation/src/hooks/common.h
#pragma once #include <string> #include <stdint.h> #include <MinHook.h> #include "../logging.h" namespace vrmotioncompensation { namespace driver { #define CREATE_MH_HOOK(detourInfo, detourFunc, logName, objPtr, vtableOffset) {\ detourInfo.targetFunc = (*((void***)objPtr))[vtableOffset]; \ MH_STATUS mhError = MH_CreateHook(detourInfo.targetFunc, (void*)&detourFunc, reinterpret_cast<LPVOID*>(&detourInfo.origFunc)); \ if (mhError == MH_OK) { \ mhError = MH_EnableHook(detourInfo.targetFunc); \ if (mhError == MH_OK) { \ detourInfo.enabled = true; \ LOG(INFO) << logName << " hook is enabled (Address: " << std::hex << detourInfo.targetFunc << std::dec << ")"; \ } else { \ MH_RemoveHook(detourInfo.targetFunc); \ LOG(ERROR) << "Error while enabling " << logName << " hook: " << MH_StatusToString(mhError); \ } \ } else { \ LOG(ERROR) << "Error while creating " << logName << " hook: " << MH_StatusToString(mhError); \ }\ } #define REMOVE_MH_HOOK(detourInfo) {\ if (detourInfo.enabled) { \ MH_RemoveHook(detourInfo.targetFunc); \ detourInfo.enabled = false; \ }\ } //forward declarations class ServerDriver; class IVRDriverContextHooks; class IVRServerDriverHost004Hooks; template<class T> struct HookData { bool enabled = false; void* targetFunc = nullptr; T origFunc = nullptr; }; class InterfaceHooks { public: virtual ~InterfaceHooks() { } static std::shared_ptr<InterfaceHooks> hookInterface(void* interfaceRef, std::string interfaceVersion); static void setServerDriver(ServerDriver* driver) { serverDriver = driver; } protected: static ServerDriver* serverDriver; }; } }
1,734
C++
.h
58
26.224138
131
0.682692
openvrmc/OpenVR-MotionCompensation
36
16
4
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,224
Log.cpp
WebRTSP_WebRTSP/Http/Log.cpp
#include "Log.h" #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_sinks.h> static std::shared_ptr<spdlog::logger> HttpServerLogger; void InitHttpServerLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); HttpServerLogger = std::make_shared<spdlog::logger>("HttpServer", sink); HttpServerLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& HttpServerLog() { if(!HttpServerLogger) #ifndef NDEBUG InitHttpServerLogger(spdlog::level::debug); #else InitHttpServerLogger(spdlog::level::info); #endif return HttpServerLogger; }
653
C++
.cpp
20
29.4
78
0.748397
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
true
false
1,532,225
HttpMicroServer.cpp
WebRTSP_WebRTSP/Http/HttpMicroServer.cpp
#include "HttpMicroServer.h" #include <fcntl.h> #include <sys/stat.h> #include <microhttpd.h> #include <CxxPtr/CPtr.h> #include <CxxPtr/GlibPtr.h> #include "Log.h" namespace { const auto Log = HttpServerLog; struct MHDFree { void operator() (char* str) { MHD_free(str); } }; typedef std::unique_ptr< char, MHDFree> MHDCharPtr; const char *const ConfigFile = "/Config.js"; const char *const IndexFile = "/index.html"; const char* AuthCookieName = "WebRTSP-Auth"; const char* AuthCookieStaticAttributes = "; HttpOnly; SameSite=Strict; Secure; Path=/"; #ifdef NDEBUG const unsigned AuthCookieMaxAge = 30 * 24 * 60 * 60; // seconds const unsigned AuthCookieCleanupInterval = 15; // seconds #else const unsigned AuthCookieMaxAge = 5; // seconds const unsigned AuthCookieCleanupInterval = 1; // seconds #endif const MHD_DigestAuthAlgorithm DigestAlgorithm = MHD_DIGEST_ALG_MD5; //const MHD_DigestAuthAlgorithm DigestAlgorithm = MHD_DIGEST_ALG_AUTO; size_t NoUnescape(void*, struct MHD_Connection*, char* s) { return strlen(s); } } namespace http { struct MicroServer::Private { static const std::string AccessDeniedResponse; static const std::string NotFoundResponse; static const Config FixConfig(const Config&); Private( MicroServer*, const Config&, const std::string& configJsc, const MicroServer::OnNewAuthToken&, GMainContext* context); ~Private(); bool init(); MHD_Result httpCallback( struct MHD_Connection* connection, const char* url, const char* method, const char* version, const char* uploadData, size_t* uploadDataSize, void ** conCls); bool isValidCookie(const char* cookie); void addCookie(MHD_Response*); void refreshCookie(MHD_Response* response, const std::string& inCookie); void addExpiredCookie(MHD_Response*) const; MHD_Result queueAccessDeniedResponse( MHD_Connection* connection, bool expireCookie, bool isStale) const; MHD_Result queueNotFoundResponse(MHD_Connection* connection) const; void postToken( const std::string& token, std::chrono::steady_clock::time_point expiresAt) const; void cleanupCookies(); MicroServer *const owner; const Config config; const std::string wwwRootPath; const std::string configJsPath; MHD_Daemon* daemon = nullptr; std::vector<uint8_t> configJsBuffer; const MicroServer::OnNewAuthToken onNewAuthTokenCallback; GMainContext* context; std::unordered_map<std::string, const MicroServer::AuthCookieData> authCookies; std::chrono::steady_clock::time_point nextAuthCookiesCleanupTime = std::chrono::steady_clock::time_point::min(); }; const std::string MicroServer::Private::AccessDeniedResponse = "Access denied"; const std::string MicroServer::Private::NotFoundResponse = "Not found"; const Config MicroServer::Private::FixConfig(const Config& config) { if(config.indexPaths.empty()) { Config tmpConfig = config; tmpConfig.indexPaths.emplace("/", !config.passwd.empty()); return tmpConfig; } else { return config; } } MicroServer::Private::Private( MicroServer* owner, const Config& config, const std::string& configJs, const OnNewAuthToken& onNewAuthTokenCallback, GMainContext* context) : owner(owner), config(FixConfig(config)), wwwRootPath(GCharPtr(g_canonicalize_filename(config.wwwRoot.c_str(), nullptr)).get()), configJsPath(GCharPtr(g_build_filename(wwwRootPath.c_str(), ConfigFile, nullptr)).get()), configJsBuffer(configJs.begin(), configJs.end()), onNewAuthTokenCallback(onNewAuthTokenCallback), context(context) { } bool MicroServer::Private::init() { assert(!daemon); if(daemon) return false; auto callback = [] ( void* cls, struct MHD_Connection* connection, const char* url, const char* method, const char* version, const char* uploadData, size_t* uploadDataSize, void ** conCls) -> MHD_Result { Private* p =static_cast<Private*>(cls); return p->httpCallback(connection, url, method, version, uploadData, uploadDataSize, conCls); }; Log()->info("Starting HTTP server on port {} in \"{}\"", config.port, wwwRootPath); daemon = MHD_start_daemon( MHD_USE_AUTO | MHD_USE_INTERNAL_POLLING_THREAD | MHD_USE_ERROR_LOG, config.port, nullptr, nullptr, callback, this, MHD_OPTION_NONCE_NC_SIZE, 1000, MHD_OPTION_UNESCAPE_CALLBACK, NoUnescape, nullptr, MHD_OPTION_END); return daemon != nullptr; } MicroServer::Private::~Private() { MHD_stop_daemon(daemon); } void MicroServer::Private::postToken( const std::string& token, std::chrono::steady_clock::time_point expiresAt) const { if(!onNewAuthTokenCallback) { Log()->warn("Auth token callback is missing"); return; } GSourcePtr idleSourcePtr(g_idle_source_new()); GSource* idleSource = idleSourcePtr.get(); struct CallbackData { const MicroServer::OnNewAuthToken onNewAuthTokenCallback; std::string token; std::chrono::steady_clock::time_point expiresAt; }; CallbackData* callbackData = new CallbackData { onNewAuthTokenCallback, token, expiresAt }; g_source_set_callback( idleSource, [] (gpointer userData) -> gboolean { const CallbackData* callbackData = reinterpret_cast<CallbackData*>(userData); callbackData->onNewAuthTokenCallback( callbackData->token, callbackData->expiresAt); return false; }, callbackData, [] (gpointer userData) { delete reinterpret_cast<CallbackData*>(userData); }) ; g_source_attach(idleSource, context); } bool MicroServer::Private::isValidCookie(const char* inCookie) { if(!inCookie) return false; auto it = authCookies.find(inCookie); if(it == authCookies.end()) return false; const AuthCookieData& cookieData = it->second; if(cookieData.expiresAt < std::chrono::steady_clock::now()) { authCookies.erase(it); return false; } // FIXME! add check of source IP address return true; } void MicroServer::Private::addCookie(MHD_Response* response) { GCharPtr randomPtr(g_uuid_string_random()); // FIXME! use something more sequre const std::string random = randomPtr.get(); std::string cookie = AuthCookieName; cookie += "=" + random; cookie += "; Max-Age="; cookie += std::to_string(AuthCookieMaxAge); cookie += AuthCookieStaticAttributes; MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie.c_str()); const std::chrono::steady_clock::time_point expiresAt = std::chrono::steady_clock::now() + std::chrono::seconds(AuthCookieMaxAge); authCookies.emplace(random, AuthCookieData { expiresAt }); postToken(random, expiresAt); Log()->debug("Added auth cookie \"{}\"", random); } void MicroServer::Private::refreshCookie(MHD_Response* response, const std::string& inCookie) { Log()->debug("Refreshing auth cookie \"{}\"...", inCookie); std::string cookie = AuthCookieName; cookie += "=" + inCookie; cookie += "; Max-Age="; cookie += std::to_string(AuthCookieMaxAge); cookie += AuthCookieStaticAttributes; MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie.c_str()); const std::chrono::steady_clock::time_point expiresAt = std::chrono::steady_clock::now() + std::chrono::seconds(AuthCookieMaxAge); authCookies.emplace(inCookie, AuthCookieData { expiresAt }); postToken(inCookie, expiresAt); } void MicroServer::Private::addExpiredCookie(MHD_Response* response) const { Log()->debug("Expiring auth cookie..."); std::string cookie = AuthCookieName; cookie += "= "; cookie += "; Max-Age=0"; cookie += AuthCookieStaticAttributes; MHD_add_response_header(response, MHD_HTTP_HEADER_SET_COOKIE, cookie.c_str()); } MHD_Result MicroServer::Private::queueAccessDeniedResponse( MHD_Connection* connection, bool expireCookie, bool isStale) const { MHD_Response* response = MHD_create_response_from_buffer( AccessDeniedResponse.size(), (void*)AccessDeniedResponse.c_str(), MHD_RESPMEM_PERSISTENT); if(expireCookie) addExpiredCookie(response); const MHD_Result queueResult = MHD_queue_auth_fail_response2( connection, config.realm.c_str(), config.opaque.c_str(), response, isStale ? MHD_YES : MHD_NO, DigestAlgorithm); MHD_destroy_response(response); return queueResult; } MHD_Result MicroServer::Private::queueNotFoundResponse(MHD_Connection* connection) const { MHD_Response* response = MHD_create_response_from_buffer( NotFoundResponse.size(), (void*)NotFoundResponse.c_str(), MHD_RESPMEM_PERSISTENT); MHD_Result queueResult = MHD_queue_response(connection, MHD_HTTP_NOT_FOUND, response); MHD_destroy_response(response); return queueResult; } void MicroServer::Private::cleanupCookies() { const auto now = std::chrono::steady_clock::now(); if(nextAuthCookiesCleanupTime > now) return; for(auto it = authCookies.begin(); it != authCookies.end();) { if(it->second.expiresAt < now) it = authCookies.erase(it); else ++it; } nextAuthCookiesCleanupTime = now + std::chrono::seconds(AuthCookieCleanupInterval); } // running on worker thread! MHD_Result MicroServer::Private::httpCallback( struct MHD_Connection* connection, const char *const url, const char *const method, const char *const version, const char *const uploadData, size_t* uploadDataSize, void ** conCls) { if(0 != strcmp(method, MHD_HTTP_METHOD_GET)) return MHD_NO; if(*conCls == nullptr) { // first phase, skipping *conCls = GINT_TO_POINTER(TRUE); return MHD_YES; } Log()->debug("Serving \"{}\"...", url); auto it = config.indexPaths.find(url); const bool isIndexPath = it != config.indexPaths.end(); const bool pathAuthRequired = isIndexPath ? it->second : false; cleanupCookies(); bool addAuthCookie = false; const char* inAuthCookie= MHD_lookup_connection_value(connection, MHD_COOKIE_KIND, AuthCookieName); const bool authCookieValid = isValidCookie(inAuthCookie); if(inAuthCookie) { if(authCookieValid) Log()->debug("Got valid auth cookie \"{}\"", inAuthCookie); else Log()->debug("Got invalid auth cookie \"{}\"", inAuthCookie); } MHDCharPtr userNamePtr(MHD_digest_auth_get_username(connection)); const char* userName = userNamePtr.get(); if((userName || pathAuthRequired) && isIndexPath && !authCookieValid) { if(!config.passwd.empty()) { if(!userName) { Log()->debug("User name is missing"); return queueAccessDeniedResponse(connection, inAuthCookie, false); } auto it = config.passwd.find(userName); if(it == config.passwd.end()) { Log()->error("User \"{}\" not allowed", userName); return queueAccessDeniedResponse(connection, inAuthCookie, false); } const int authCheckResult = MHD_digest_auth_check2( connection, config.realm.c_str(), it->first.c_str(), it->second.c_str(), 300, DigestAlgorithm); if(authCheckResult == MHD_YES) { Log()->info("User \"{}\" authorized...", userName); addAuthCookie = true; } else if(pathAuthRequired || authCheckResult == MHD_INVALID_NONCE) { Log()->error("User \"{}\" authentication failed for \"{}\"", userName, url); return queueAccessDeniedResponse(connection, inAuthCookie, authCheckResult == MHD_INVALID_NONCE); } } else { // don't expose protected paths without auth Log()->debug("Ignored request to protectd path without auth"); return queueNotFoundResponse(connection); } } GCharPtr safePathPtr; if(isIndexPath) { Log()->debug("Routing \"{}\" to \"{}\"...", url, IndexFile); safePathPtr.reset(g_build_filename(wwwRootPath.c_str(), IndexFile, nullptr)); } else { GCharPtr fullPathPtr(g_build_filename(wwwRootPath.c_str(), url, nullptr)); safePathPtr.reset(g_canonicalize_filename(fullPathPtr.get(), nullptr)); if(!g_str_has_prefix(safePathPtr.get(), wwwRootPath.c_str())) { Log()->error("Try to escape from WWW dir detected: {}\n", url); return MHD_NO; } } MHD_Response* response = nullptr; if(configJsPath == safePathPtr.get()) { response = MHD_create_response_from_buffer( configJsBuffer.size(), configJsBuffer.data(), MHD_RESPMEM_PERSISTENT); } else { const int fd = open(safePathPtr.get(), O_RDONLY); FDAutoClose fdAutoClose(fd); struct stat fileStat = {}; if(fd != -1 && fstat(fd, &fileStat) == -1) return MHD_NO; if(fd == -1 || !S_ISREG(fileStat.st_mode)) { return queueNotFoundResponse(connection); } response = MHD_create_response_from_fd64(fileStat.st_size, fd); if(!response) return MHD_NO; fdAutoClose.cancel(); } if(addAuthCookie) { addCookie(response); } else if(authCookieValid) { refreshCookie(response, inAuthCookie); } if(g_str_has_suffix(safePathPtr.get(), ".js") || g_str_has_suffix(safePathPtr.get(), ".mjs")) MHD_add_response_header(response, MHD_HTTP_HEADER_CONTENT_TYPE, "text/javascript"); MHD_Result queueResult = MHD_queue_response(connection, MHD_HTTP_OK, response); MHD_destroy_response(response); return queueResult; } MicroServer::MicroServer( const Config& config, const std::string& configJs, const OnNewAuthToken& onNewAuthTokenCallback, GMainContext* context) noexcept : _p(std::make_unique<Private>(this, config, configJs, onNewAuthTokenCallback, context)) { } MicroServer::~MicroServer() { } bool MicroServer::init() noexcept { return _p->init(); } }
14,784
C++
.cpp
400
30.115
113
0.655146
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,226
ClientSession.cpp
WebRTSP_WebRTSP/Client/ClientSession.cpp
#include "ClientSession.h" #include "RtspSession/StatusCode.h" #include "Log.h" static const auto Log = ClientSessionLog; struct ClientSession::Private { Private( ClientSession* owner, const std::string& uri, const CreatePeer& createPeer); ClientSession* owner; std::string uri; std::unique_ptr<WebRTCPeer> receiver; rtsp::MediaSessionId session; void receiverPrepared(); void iceCandidate(unsigned, const std::string&); void eos(); }; ClientSession::Private::Private( ClientSession* owner, const std::string& uri, const CreatePeer& createPeer) : owner(owner), uri(uri), receiver(createPeer()) { } void ClientSession::Private::receiverPrepared() { if(receiver->sdp().empty()) { owner->disconnect(); return; } owner->requestPlay( uri, session, receiver->sdp()); } void ClientSession::Private::iceCandidate( unsigned mlineIndex, const std::string& candidate) { owner->requestSetup( uri, rtsp::IceCandidateContentType, session, std::to_string(mlineIndex) + "/" + candidate + "\r\n"); } void ClientSession::Private::eos() { Log()->trace("[{}] Eos", owner->sessionLogId); owner->onEos(); // FIXME! send TEARDOWN and remove Media Session instead } ClientSession::ClientSession( const std::string& uri, const WebRTCConfigPtr& webRTCConfig, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : rtsp::ClientSession(webRTCConfig, sendRequest, sendResponse), _p(new Private(this, uri, createPeer)) { } ClientSession::ClientSession( const WebRTCConfigPtr& webRTCConfig, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : ClientSession(std::string(), webRTCConfig, createPeer, sendRequest, sendResponse) { } ClientSession::~ClientSession() { } void ClientSession::setUri(const std::string& uri) { _p->uri = uri; } bool ClientSession::onConnected() noexcept { requestOptions(!_p->uri.empty() ? _p->uri : "*"); return true; } rtsp::CSeq ClientSession::requestDescribe() noexcept { assert(!_p->uri.empty()); return rtsp::ClientSession::requestDescribe(_p->uri); } bool ClientSession::onOptionsResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(!rtsp::ClientSession::onOptionsResponse(request, response)) return false; if(!_p->uri.empty()) requestDescribe(); return true; } bool ClientSession::onDescribeResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; _p->session = ResponseSession(response); if(_p->session.empty()) return false; _p->receiver->prepare( webRTCConfig(), std::bind( &ClientSession::Private::receiverPrepared, _p.get()), std::bind( &ClientSession::Private::iceCandidate, _p.get(), std::placeholders::_1, std::placeholders::_2), std::bind( &ClientSession::Private::eos, _p.get())); const std::string& sdp = response.body; if(sdp.empty()) return false; _p->receiver->setRemoteSdp(sdp); return true; } bool ClientSession::onSetupResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; if(ResponseSession(response) != _p->session) return false; return true; } bool ClientSession::onPlayResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; if(ResponseSession(response) != _p->session) return false; _p->receiver->play(); return true; } bool ClientSession::onTeardownResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(ResponseSession(response) != _p->session) return false; return false; } bool ClientSession::onSetupRequest(std::unique_ptr<rtsp::Request>& requestPtr) noexcept { if(RequestSession(*requestPtr) != _p->session) return false; if(RequestContentType(*requestPtr) != rtsp::IceCandidateContentType) return false; const std::string& ice = requestPtr->body; std::string::size_type pos = 0; while(pos < ice.size()) { const std::string::size_type lineEndPos = ice.find("\r\n", pos); if(lineEndPos == std::string::npos) return false; const std::string line = ice.substr(pos, lineEndPos - pos); const std::string::size_type delimiterPos = line.find("/"); if(delimiterPos == std::string::npos || 0 == delimiterPos) return false; try{ const int idx = std::stoi(line.substr(0, delimiterPos)); if(idx < 0) return false; const std::string candidate = line.substr(delimiterPos + 1); if(candidate.empty()) return false; Log()->trace("[{}] Adding ice candidate \"{}\"", sessionLogId, candidate); _p->receiver->addIceCandidate(idx, candidate); } catch(...) { return false; } pos = lineEndPos + 2; } sendOkResponse(requestPtr->cseq, rtsp::RequestSession(*requestPtr)); return true; }
5,628
C++
.cpp
186
24.419355
87
0.653732
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,227
Log.cpp
WebRTSP_WebRTSP/Client/Log.cpp
#include "Log.h" #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_sinks.h> static std::shared_ptr<spdlog::logger> WsClientLogger; static std::shared_ptr<spdlog::logger> ClientSessionLogger; void InitWsClientLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); WsClientLogger = std::make_shared<spdlog::logger>("WsClient", sink); WsClientLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& WsClientLog() { if(!WsClientLogger) #ifndef NDEBUG InitWsClientLogger(spdlog::level::debug); #else InitWsClientLogger(spdlog::level::info); #endif return WsClientLogger; } void InitClientSessionLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); ClientSessionLogger = std::make_shared<spdlog::logger>("ClientSession", sink); ClientSessionLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& ClientSessionLog() { if(!ClientSessionLogger) #ifndef NDEBUG InitClientSessionLogger(spdlog::level::debug); #else InitClientSessionLogger(spdlog::level::info); #endif return ClientSessionLogger; }
1,229
C++
.cpp
37
29.891892
82
0.749576
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,228
ClientRecordSession.cpp
WebRTSP_WebRTSP/Client/ClientRecordSession.cpp
#include "ClientRecordSession.h" #include "RtspSession/StatusCode.h" #include "RtspSession/IceCandidate.h" #include "Log.h" static const auto Log = ClientSessionLog; struct ClientRecordSession::Private { Private( ClientRecordSession* owner, const std::string& targetUri, const std::string& recordToken, const CreatePeer& createPeer); ClientRecordSession* owner; std::string targetUri; std::string sourceUri; std::string recordToken; const CreatePeer createPeer; std::unique_ptr<WebRTCPeer> streamer; std::deque<rtsp::IceCandidate> iceCandidates; rtsp::CSeq recordRequested = false; rtsp::MediaSessionId session; void streamerPrepared(); void iceCandidate(unsigned, const std::string&); void eos(); }; ClientRecordSession::Private::Private( ClientRecordSession* owner, const std::string& targetUri, const std::string& recordToken, const CreatePeer& createPeer) : owner(owner), targetUri(targetUri), recordToken(recordToken), createPeer(createPeer) { } void ClientRecordSession::Private::streamerPrepared() { if(streamer->sdp().empty()) { owner->disconnect(); return; } owner->requestRecord(targetUri, streamer->sdp(), recordToken); recordRequested = true; } void ClientRecordSession::Private::iceCandidate( unsigned mlineIndex, const std::string& candidate) { if(session.empty()) { iceCandidates.emplace_back(rtsp::IceCandidate { mlineIndex, candidate }); } else { owner->requestSetup( targetUri, rtsp::IceCandidateContentType, session, std::to_string(mlineIndex) + "/" + candidate + "\r\n"); } } void ClientRecordSession::Private::eos() { Log()->trace("[{}] Eos", owner->sessionLogId); owner->onEos(); // FIXME! send TEARDOWN and remove Media Session instead } ClientRecordSession::ClientRecordSession( const std::string& targetUri, const std::string& recordToken, const WebRTCConfigPtr& webRTCConfig, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : rtsp::ClientSession(webRTCConfig, sendRequest, sendResponse), _p(new Private(this, targetUri, recordToken, createPeer)) { } ClientRecordSession::~ClientRecordSession() { } bool ClientRecordSession::onConnected() noexcept { requestOptions(!_p->targetUri.empty() ? _p->targetUri : "*"); return true; } bool ClientRecordSession::onRecordResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(response.statusCode != rtsp::StatusCode::OK) return false; if(ResponseContentType(response) != rtsp::SdpContentType) return false; rtsp::MediaSessionId session = ResponseSession(response); if(session.empty()) return false; _p->streamer->setRemoteSdp(response.body); _p->session = session; if(!_p->iceCandidates.empty()) { std::string iceCandidates; for(const rtsp::IceCandidate& c : _p->iceCandidates) { iceCandidates += std::to_string(c.mlineIndex) + "/" + c.candidate + "\r\n"; } if(!iceCandidates.empty()) { requestSetup( _p->targetUri, rtsp::IceCandidateContentType, _p->session, iceCandidates); } _p->iceCandidates.clear(); } _p->streamer->play(); return true; } bool ClientRecordSession::onSetupResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; if(ResponseSession(response) != _p->session) return false; const std::string contentType = RequestContentType(request); if(contentType == rtsp::IceCandidateContentType) ; else return false; return true; } bool ClientRecordSession::onTeardownResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { return true; } bool ClientRecordSession::onSetupRequest(std::unique_ptr<rtsp::Request>& requestPtr) noexcept { if(RequestSession(*requestPtr) != _p->session) return false; if(RequestContentType(*requestPtr) != rtsp::IceCandidateContentType) return false; const std::string& ice = requestPtr->body; std::string::size_type pos = 0; while(pos < ice.size()) { const std::string::size_type lineEndPos = ice.find("\r\n", pos); if(lineEndPos == std::string::npos) return false; const std::string line = ice.substr(pos, lineEndPos - pos); const std::string::size_type delimiterPos = line.find("/"); if(delimiterPos == std::string::npos || 0 == delimiterPos) return false; try{ const int idx = std::stoi(line.substr(0, delimiterPos)); if(idx < 0) return false; const std::string candidate = line.substr(delimiterPos + 1); if(candidate.empty()) return false; Log()->trace("[{}] Adding ice candidate \"{}\"", sessionLogId, candidate); _p->streamer->addIceCandidate(idx, candidate); } catch(...) { return false; } pos = lineEndPos + 2; } sendOkResponse(requestPtr->cseq, rtsp::RequestSession(*requestPtr)); return true; } bool ClientRecordSession::isStreaming() const noexcept { return _p->streamer != nullptr; } void ClientRecordSession::startRecord(const std::string& sourceUri) noexcept { assert(!_p->streamer); if(_p->streamer) { return; } _p->streamer = _p->createPeer(sourceUri); assert(_p->streamer); if(!_p->streamer) { return; } assert(!_p->recordRequested); _p->streamer->prepare( webRTCConfig(), std::bind( &ClientRecordSession::Private::streamerPrepared, _p.get()), std::bind( &ClientRecordSession::Private::iceCandidate, _p.get(), std::placeholders::_1, std::placeholders::_2), std::bind( &ClientRecordSession::Private::eos, _p.get())); } void ClientRecordSession::stopRecord() noexcept { if(!_p->streamer) { assert(!_p->recordRequested); return; } _p->streamer->stop(); _p->streamer.reset(); if(_p->recordRequested) { assert(!_p->session.empty()); if(!_p->session.empty()) { requestTeardown(_p->targetUri, _p->session); _p->session.clear(); _p->recordRequested = false; } else { // FIXME? didn't get response to RECORD request yet disconnect(); } } }
6,870
C++
.cpp
215
25.288372
93
0.639478
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,229
WsClient.cpp
WebRTSP_WebRTSP/Client/WsClient.cpp
#include "WsClient.h" #include <deque> #include <algorithm> #include <CxxPtr/libwebsocketsPtr.h> #include "Helpers/MessageBuffer.h" #include "RtspParser/RtspSerialize.h" #include "RtspParser/RtspParser.h" #include "Log.h" namespace client { namespace { enum { RX_BUFFER_SIZE = 512, PING_INTERVAL = 30, INCOMING_MESSAGE_WAIT_INTERVAL = PING_INTERVAL + 5, }; enum { PROTOCOL_ID, }; #if LWS_LIBRARY_VERSION_MAJOR < 3 enum { LWS_CALLBACK_CLIENT_CLOSED = LWS_CALLBACK_CLOSED }; #endif struct SessionData { bool terminateSession = false; MessageBuffer incomingMessage; std::deque<MessageBuffer> sendMessages; std::unique_ptr<rtsp::Session> rtspSession; }; // Should contain only POD types, // since created inside libwebsockets on session create. struct SessionContextData { lws* wsi; SessionData* data; }; const auto Log = WsClientLog; } struct WsClient::Private { Private( WsClient*, const Config&, GMainLoop*, const CreateSession&, const Disconnected&); bool init(); int httpCallback(lws*, lws_callback_reasons, void* user, void* in, size_t len); int wsCallback(lws*, lws_callback_reasons, void* user, void* in, size_t len); bool onMessage(SessionContextData*, const MessageBuffer&); void send(SessionContextData*, MessageBuffer*); void sendRequest(SessionContextData*, const rtsp::Request*); void sendResponse(SessionContextData*, const rtsp::Response*); void connect(); bool onConnected(SessionContextData*); WsClient *const owner; Config config; GMainLoop* loop = nullptr; CreateSession createSession; Disconnected disconnected; LwsContextPtr contextPtr; lws* connection = nullptr; bool connected = false; }; WsClient::Private::Private( WsClient* owner, const Config& config, GMainLoop* loop, const WsClient::CreateSession& createSession, const Disconnected& disconnected) : owner(owner), config(config), loop(loop), createSession(createSession), disconnected(disconnected) { } int WsClient::Private::wsCallback( lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) { SessionContextData* scd = static_cast<SessionContextData*>(user); switch(reason) { case LWS_CALLBACK_CLIENT_ESTABLISHED: { Log()->info("Connection to server established."); std::unique_ptr<rtsp::Session> session = createSession( std::bind(&Private::sendRequest, this, scd, std::placeholders::_1), std::bind(&Private::sendResponse, this, scd, std::placeholders::_1)); if(!session) return -1; scd->data = new SessionData { .terminateSession = false, .incomingMessage ={}, .sendMessages = {}, .rtspSession = std::move(session)}; scd->wsi = wsi; connected = true; if(!onConnected(scd)) return -1; break; } case LWS_CALLBACK_CLIENT_RECEIVE_PONG: Log()->trace("PONG"); break; case LWS_CALLBACK_CLIENT_RECEIVE: if(scd->data->incomingMessage.onReceive(wsi, in, len)) { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(scd->data->incomingMessage.size()); std::remove_copy( scd->data->incomingMessage.data(), scd->data->incomingMessage.data() + scd->data->incomingMessage.size(), std::back_inserter(logMessage), '\r'); Log()->trace("-> WsClient: {}", logMessage); } if(!onMessage(scd, scd->data->incomingMessage)) return -1; scd->data->incomingMessage.clear(); } break; case LWS_CALLBACK_CLIENT_WRITEABLE: if(scd->data->terminateSession) return -1; if(!scd->data->sendMessages.empty()) { MessageBuffer& buffer = scd->data->sendMessages.front(); if(!buffer.writeAsText(wsi)) { Log()->error("Write failed."); return -1; } scd->data->sendMessages.pop_front(); if(!scd->data->sendMessages.empty()) lws_callback_on_writable(wsi); } break; case LWS_CALLBACK_CLIENT_CLOSED: Log()->info("Connection to server is closed."); delete scd->data; scd = nullptr; connection = nullptr; connected = false; if(disconnected) disconnected(*this->owner); break; case LWS_CALLBACK_CLIENT_CONNECTION_ERROR: Log()->error("Can not connect to server."); delete scd->data; scd = nullptr; connection = nullptr; connected = false; if(disconnected) disconnected(*this->owner); break; default: break; } return 0; } bool WsClient::Private::init() { auto WsCallback = [] (lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) -> int { lws_context* context = lws_get_context(wsi); Private* p = static_cast<Private*>(lws_context_user(context)); return p->wsCallback(wsi, reason, user, in, len); }; static const lws_protocols protocols[] = { { "webrtsp", WsCallback, sizeof(SessionContextData), RX_BUFFER_SIZE, PROTOCOL_ID, nullptr }, { nullptr, nullptr, 0, 0, 0, nullptr } /* terminator */ }; lws_context_creation_info wsInfo {}; wsInfo.gid = -1; wsInfo.uid = -1; wsInfo.port = CONTEXT_PORT_NO_LISTEN; wsInfo.options = LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT; wsInfo.options |= LWS_SERVER_OPTION_GLIB; wsInfo.foreign_loops = reinterpret_cast<void**>(&loop); wsInfo.protocols = protocols; #if LWS_LIBRARY_VERSION_NUMBER < 4000000 wsInfo.ws_ping_pong_interval = PING_INTERVAL; #else lws_retry_bo_t retryPolicy {}; retryPolicy.secs_since_valid_ping = PING_INTERVAL; retryPolicy.secs_since_valid_hangup = INCOMING_MESSAGE_WAIT_INTERVAL; wsInfo.retry_and_idle_policy = &retryPolicy; #endif wsInfo.user = this; contextPtr.reset(lws_create_context(&wsInfo)); lws_context* context = contextPtr.get(); if(!context) return false; return true; } void WsClient::Private::connect() { if(connection) return; if(config.server.empty() || !config.serverPort) { Log()->error("Missing required connect parameter."); return; } char hostAndPort[config.server.size() + 1 + 5 + 1]; snprintf(hostAndPort, sizeof(hostAndPort), "%s:%u", config.server.c_str(), config.serverPort); Log()->info("Connecting to {}...", &hostAndPort[0]); struct lws_client_connect_info connectInfo = {}; connectInfo.context = contextPtr.get(); connectInfo.address = config.server.c_str(); connectInfo.port = config.serverPort; connectInfo.path = "/"; connectInfo.protocol = "webrtsp"; connectInfo.host = hostAndPort; if(config.useTls) connectInfo.ssl_connection = LCCSCF_USE_SSL; connection = lws_client_connect_via_info(&connectInfo); connected = false; } bool WsClient::Private::onConnected(SessionContextData* scd) { return scd->data->rtspSession->onConnected(); } bool WsClient::Private::onMessage( SessionContextData* scd, const MessageBuffer& message) { if(rtsp::IsRequest(message.data(), message.size())) { std::unique_ptr<rtsp::Request> requestPtr = std::make_unique<rtsp::Request>(); if(!rtsp::ParseRequest(message.data(), message.size(), requestPtr.get())) { Log()->error( "Fail parse request:\n{}\nForcing session disconnect...", std::string(message.data(), message.size())); return false; } if(!scd->data->rtspSession->handleRequest(requestPtr)) { Log()->debug( "Fail handle request:\n{}\nForcing session disconnect...", std::string(message.data(), message.size())); return false; } } else { std::unique_ptr<rtsp::Response > responsePtr = std::make_unique<rtsp::Response>(); if(!rtsp::ParseResponse(message.data(), message.size(), responsePtr.get())) { Log()->error( "Fail parse response:\n{}\nForcing session disconnect...", std::string(message.data(), message.size())); return false; } if(!scd->data->rtspSession->handleResponse(responsePtr)) { Log()->error( "Fail handle response:\n{}\nForcing session disconnect...", std::string(message.data(), message.size())); return false; } } return true; } void WsClient::Private::send(SessionContextData* scd, MessageBuffer* message) { assert(!message->empty()); scd->data->sendMessages.emplace_back(std::move(*message)); lws_callback_on_writable(scd->wsi); } void WsClient::Private::sendRequest( SessionContextData* scd, const rtsp::Request* request) { if(!request) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); return; } const std::string serializedRequest = rtsp::Serialize(*request); if(serializedRequest.empty()) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); } else { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(serializedRequest.size()); std::remove_copy( serializedRequest.begin(), serializedRequest.end(), std::back_inserter(logMessage), '\r'); Log()->trace("WsClient -> : {}", logMessage); } MessageBuffer requestMessage; requestMessage.assign(serializedRequest); send(scd, &requestMessage); } } void WsClient::Private::sendResponse( SessionContextData* scd, const rtsp::Response* response) { if(!response) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); return; } const std::string serializedResponse = rtsp::Serialize(*response); if(serializedResponse.empty()) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); } else { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(serializedResponse.size()); std::remove_copy( serializedResponse.begin(), serializedResponse.end(), std::back_inserter(logMessage), '\r'); Log()->trace("WsClient -> : {}", logMessage); } MessageBuffer responseMessage; responseMessage.assign(serializedResponse); send(scd, &responseMessage); } } WsClient::WsClient( const Config& config, GMainLoop* loop, const CreateSession& createSession, const Disconnected& disconnected) noexcept: _p(std::make_unique<Private>(this, config, loop, createSession, disconnected)) { } WsClient::~WsClient() { } bool WsClient::init() noexcept { return _p->init(); } void WsClient::connect() noexcept { _p->connect(); } }
11,832
C++
.cpp
348
25.801724
94
0.602875
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,230
ClientSession.cpp
WebRTSP_WebRTSP/RtspSession/ClientSession.cpp
#include "ClientSession.h" #include <cassert> #include "RtspParser/RtspParser.h" namespace rtsp { bool ClientSession::isSupported(Method method) { return _supportedMethods.find(method) != _supportedMethods.end(); } CSeq ClientSession::requestOptions(const std::string& uri) noexcept { assert(!uri.empty()); if(uri.empty()) return 0; Request& request = *createRequest(Method::OPTIONS, uri); sendRequest(request); return request.cseq; } CSeq ClientSession::requestDescribe(const std::string& uri) noexcept { Request& request = *createRequest(Method::DESCRIBE, uri); sendRequest(request); return request.cseq; } CSeq ClientSession::requestRecord( const std::string& uri, const std::string& sdp, const std::optional<std::string>& token) noexcept { Request& request = *createRequest(Method::RECORD, uri); SetContentType(&request, rtsp::SdpContentType); if(token) SetBearerAuthorization(&request, token.value()); request.body.assign(sdp); sendRequest(request); return request.cseq; } CSeq ClientSession::requestPlay( const std::string& uri, const MediaSessionId& session, const std::string& sdp) noexcept { Request* request = createRequest(Method::PLAY, uri, session); rtsp::SetContentType(request, SdpContentType); request->body = sdp; sendRequest(*request); return request->cseq; } CSeq ClientSession::requestTeardown( const std::string& uri, const MediaSessionId& session) noexcept { Request& request = *createRequest(Method::TEARDOWN, uri, session); sendRequest(request); return request.cseq; } bool ClientSession::onOptionsResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; _supportedMethods = rtsp::ParseOptions(response); if(playSupportRequired(request.uri) && (!isSupported(Method::DESCRIBE) || !isSupported(Method::SETUP) || !isSupported(Method::PLAY) || !isSupported(Method::TEARDOWN))) { return false; } if(recordSupportRequired(request.uri) && (!isSupported(Method::RECORD) || !isSupported(Method::SETUP) || !isSupported(Method::TEARDOWN))) { return false; } return true; } }
2,402
C++
.cpp
84
23.714286
69
0.694056
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,231
Log.cpp
WebRTSP_WebRTSP/RtspSession/Log.cpp
#include "Log.h" #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_sinks.h> static std::shared_ptr<spdlog::logger> RtspSessionLogger; void InitRtspSessionLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); RtspSessionLogger = std::make_shared<spdlog::logger>("rtsp::Session", sink); RtspSessionLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& RtspSessionLog() { if(!RtspSessionLogger) #ifndef NDEBUG InitRtspSessionLogger(spdlog::level::debug); #else InitRtspSessionLogger(spdlog::level::info); #endif return RtspSessionLogger; }
665
C++
.cpp
20
30
80
0.75
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,232
Session.cpp
WebRTSP_WebRTSP/RtspSession/Session.cpp
#include "Session.h" #include <cassert> #include <glib.h> #include "Log.h" namespace { const auto Log = RtspSessionLog; std::string GenerateSessionLogId() { g_autoptr(GRand) rand = g_rand_new(); return std::to_string(g_rand_int(rand)); } } namespace rtsp { Session::Session( const WebRTCConfigPtr& webRTCConfig, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : sessionLogId(GenerateSessionLogId()), _webRTCConfig(webRTCConfig), _sendRequest(sendRequest), _sendResponse(sendResponse) { } Session::~Session() { Log()->info("[{}] Session destroyed", sessionLogId); } Request* Session::createRequest( Method method, const std::string& uri) noexcept { for(;;) { const auto& pair = _sentRequests.emplace( _nextCSeq, Request { .method = method, .uri = {}, .protocol = Protocol::WEBRTSP_0_2, .cseq = _nextCSeq }); ++_nextCSeq; if(pair.second) { Request& request = pair.first->second; request.uri = uri; return &request; } } } Request* Session::createRequest( Method method, const std::string& uri, const MediaSessionId& session) noexcept { Request* request = createRequest(method, uri); SetRequestSession(request, session); return request; } Request* Session::attachRequest( const std::unique_ptr<rtsp::Request>& requestPtr) noexcept { for(;;) { const CSeq cseq = _nextCSeq++; const auto& pair = _sentRequests.emplace( cseq, *requestPtr); if(pair.second) { Request& request = pair.first->second; request.cseq = cseq; return &request; } } } Response* Session::prepareResponse( StatusCode statusCode, const std::string::value_type* reasonPhrase, CSeq cseq, const MediaSessionId& session, Response* out) { out->protocol = Protocol::WEBRTSP_0_2; out->cseq = cseq; out->statusCode = statusCode; out->reasonPhrase = reasonPhrase; if(!session.empty()) SetResponseSession(out, session); return out; } Response* Session::prepareOkResponse( CSeq cseq, Response* out) { return prepareResponse(OK, "OK", cseq, std::string(), out); } Response* Session::prepareOkResponse( CSeq cseq, const MediaSessionId& session, Response* out) { return prepareResponse(OK, "OK", cseq, session, out); } void Session::sendOkResponse(CSeq cseq) { Response response; sendResponse(*prepareOkResponse(cseq, &response)); } void Session::sendOkResponse( CSeq cseq, const MediaSessionId& session) { Response response; sendResponse(*prepareOkResponse(cseq, session, &response)); } void Session::sendOkResponse( CSeq cseq, const std::string& contentType, const std::string& body) { Response response; prepareOkResponse(cseq, &response); SetContentType(&response, contentType); response.body = body; sendResponse(response); } void Session::sendOkResponse( CSeq cseq, const MediaSessionId& session, const std::string& contentType, const std::string& body) { Response response; prepareOkResponse(cseq, session, &response); SetContentType(&response, contentType); response.body = body; sendResponse(response); } void Session::sendUnauthorizedResponse(CSeq cseq) { Response response; prepareResponse(UNAUTHORIZED, "Unauthorized", cseq, std::string(), &response); sendResponse(response); } void Session::sendForbiddenResponse(CSeq cseq) { Response response; prepareResponse(FORBIDDEN, "Forbidden", cseq, std::string(), &response); sendResponse(response); } void Session::sendBadRequestResponse(CSeq cseq) { Response response; prepareResponse(BAD_REQUEST, "Bad Request", cseq, std::string(), &response); sendResponse(response); } void Session::sendRequest(const Request& request) noexcept { _sendRequest(&request); } CSeq Session::requestList(const std::string& uri) noexcept { Request& request = *createRequest(Method::LIST, uri); sendRequest(request); return request.cseq; } CSeq Session::sendList( const std::string& uri, const std::string& list, const std::optional<std::string>& token) noexcept { Request& request = *createRequest(Method::LIST, uri); SetContentType(&request, TextParametersContentType); if(token) SetBearerAuthorization(&request, token.value()); request.body = list; sendRequest(request); return request.cseq; } CSeq Session::requestSetup( const std::string& uri, const std::string& contentType, const MediaSessionId& session, const std::string& body) noexcept { assert(!uri.empty()); assert(!session.empty()); Request& request = *createRequest(Method::SETUP, uri); SetRequestSession(&request, session); SetContentType(&request, contentType); request.body = body; sendRequest(request); return request.cseq; } CSeq Session::requestGetParameter( const std::string& uri, const std::string& contentType, const std::string& body, const std::optional<std::string>& token) noexcept { Request& request = *createRequest(Method::GET_PARAMETER, uri); SetContentType(&request, contentType); request.body = body; if(token) SetBearerAuthorization(&request, token.value()); sendRequest(request); return request.cseq; } CSeq Session::requestSetParameter( const std::string& uri, const std::string& contentType, const std::string& body, const std::optional<std::string>& token) noexcept { Request& request = *createRequest(Method::SET_PARAMETER, uri); SetContentType(&request, contentType); request.body = body; if(token) SetBearerAuthorization(&request, token.value()); sendRequest(request); return request.cseq; } void Session::sendResponse(const Response& response) noexcept { _sendResponse(&response); } void Session::disconnect() noexcept { _sendRequest(nullptr); } bool Session::handleResponse(std::unique_ptr<Response>& responsePtr) noexcept { auto it = _sentRequests.find(responsePtr->cseq); if(it == _sentRequests.end()) { Log()->error( "[{}] Failed to find sent request corresponding to response with CSeq = {}", sessionLogId, responsePtr->cseq); return false; } const Request& request = it->second; const bool success = handleResponse(request, responsePtr); _sentRequests.erase(it); return success; } bool Session::handleRequest(std::unique_ptr<Request>& requestPtr) noexcept { switch(requestPtr->method) { case Method::NONE: break; case Method::OPTIONS: return onOptionsRequest(requestPtr); case Method::LIST: return onListRequest(requestPtr); case Method::DESCRIBE: return onDescribeRequest(requestPtr); case Method::SETUP: return onSetupRequest(requestPtr); case Method::PLAY: return onPlayRequest(requestPtr); case Method::SUBSCRIBE: return onSubscribeRequest(requestPtr); case Method::RECORD: return onRecordRequest(requestPtr); case Method::TEARDOWN: return onTeardownRequest(requestPtr); case Method::GET_PARAMETER: return onGetParameterRequest(requestPtr); case Method::SET_PARAMETER: return onSetParameterRequest(requestPtr); } return false; } bool Session::handleResponse( const Request& request, std::unique_ptr<Response>& responsePtr) noexcept { switch(request.method) { case Method::NONE: break; case Method::OPTIONS: return onOptionsResponse(request, *responsePtr); case Method::LIST: return onListResponse(request, *responsePtr); case Method::DESCRIBE: return onDescribeResponse(request, *responsePtr); case Method::SETUP: return onSetupResponse(request, *responsePtr); case Method::PLAY: return onPlayResponse(request, *responsePtr); case Method::SUBSCRIBE: return onSubscribeResponse(request, *responsePtr); case Method::RECORD: return onRecordResponse(request, *responsePtr); case Method::TEARDOWN: return onTeardownResponse(request, *responsePtr); case Method::GET_PARAMETER: return onGetParameterResponse(request, *responsePtr); case Method::SET_PARAMETER: return onSetParameterResponse(request, *responsePtr); } return false; } void Session::onEos() noexcept { disconnect(); } }
8,819
C++
.cpp
312
23.00641
88
0.683511
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,233
main.cpp
WebRTSP_WebRTSP/Apps/BasicServer/main.cpp
#include <memory> #include <CxxPtr/GlibPtr.h> #include <CxxPtr/libwebsocketsPtr.h> #include "Helpers/LwsLog.h" #include "Http/Log.h" #include "Http/HttpServer.h" #include "Signalling/Log.h" #include "Signalling/WsServer.h" #include "Signalling/ServerSession.h" #include "RtStreaming/GstRtStreaming/LibGst.h" #include "RtStreaming/GstRtStreaming/GstTestStreamer2.h" GstTestStreamer2 streamer; static std::unique_ptr<WebRTCPeer> CreatePeer(const std::string&) { return streamer.createPeer(); } static std::unique_ptr<rtsp::ServerSession> CreateSession ( const std::function<void (const rtsp::Request*)>& sendRequest, const std::function<void (const rtsp::Response*)>& sendResponse) noexcept { return std::make_unique<ServerSession>(CreatePeer, sendRequest, sendResponse); } int main(int argc, char *argv[]) { LibGst libGst; http::Config httpConfig {}; signalling::Config config {}; InitWsServerLogger(spdlog::level::trace); InitServerSessionLogger(spdlog::level::trace); GMainLoopPtr loopPtr(g_main_loop_new(nullptr, FALSE)); GMainLoop* loop = loopPtr.get(); lws_context_creation_info lwsInfo {}; lwsInfo.gid = -1; lwsInfo.uid = -1; lwsInfo.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS; #if defined(LWS_WITH_GLIB) lwsInfo.options |= LWS_SERVER_OPTION_GLIB; lwsInfo.foreign_loops = reinterpret_cast<void**>(&loop); #endif LwsContextPtr contextPtr(lws_create_context(&lwsInfo)); lws_context* context = contextPtr.get(); std::string configJs = fmt::format("const WebRTSPPort = {};\r\n", config.port); http::Server httpServer(httpConfig, configJs, loop); signalling::WsServer server(config, loop, CreateSession); if(httpServer.init(context) && server.init(context)) g_main_loop_run(loop); else return -1; return 0; }
1,849
C++
.cpp
51
32.529412
82
0.733034
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,234
RecordTest.cpp
WebRTSP_WebRTSP/Apps/RecordTest/RecordTest.cpp
#include <thread> #include <memory> #include <CxxPtr/GlibPtr.h> #include "RtStreaming/GstRtStreaming/LibGst.h" #define ENABLE_SERVER 1 #define USE_RECORD_STREAMER 1 #define ENABLE_CLIENT 1 #define USE_RESTREAMER 0 #define RECORD_TOKEN "token" #if ENABLE_SERVER #include "RtspParser/RtspParser.h" #include "Signalling/Log.h" #include "Signalling/WsServer.h" #include "Signalling/ServerSession.h" #include "RtStreaming/GstRtStreaming/GstReStreamer.h" #include "RtStreaming/GstRtStreaming/GstRecordStreamer.h" #endif #if ENABLE_CLIENT #include "RtStreaming/GstRtStreaming/GstClient.h" #include "Client/Log.h" #include "Client/WsClient.h" #include "Client/ClientRecordSession.h" #endif #include "RtStreaming/GstRtStreaming/GstTestStreamer.h" #if ENABLE_SERVER #define SERVER_HOST "localhost" #else #define SERVER_HOST "ipcam.stream" #endif enum { SERVER_PORT = 5554, RECONNECT_TIMEOUT = 10, }; #if ENABLE_SERVER #if USE_RECORD_STREAMER GstRecordStreamer recordStreamer; #endif static std::unique_ptr<WebRTCPeer> CreateServerPeer(const std::string&) { #if USE_RECORD_STREAMER return recordStreamer.createPeer(); #else return std::make_unique<GstTestStreamer>(); #endif } static std::unique_ptr<WebRTCPeer> CreateServerRecordPeer(const std::string&) { #if USE_RECORD_STREAMER return recordStreamer.createRecordPeer(); #else return std::make_unique<GstClient>(); #endif } struct TestServerRecordSession : public ServerSession { public: using ServerSession::ServerSession; protected: bool recordEnabled(const std::string&) noexcept override { return true; } bool authorize(const std::unique_ptr<rtsp::Request>&) noexcept override; }; bool TestServerRecordSession::authorize(const std::unique_ptr<rtsp::Request>& requestPtr) noexcept { if(requestPtr->method != rtsp::Method::RECORD) return ServerSession::authorize(requestPtr); const std::pair<rtsp::Authentication, std::string> authPair = rtsp::ParseAuthentication(*requestPtr); if(authPair.first != rtsp::Authentication::Bearer) return false; return authPair.second == RECORD_TOKEN; } static std::unique_ptr<ServerSession> CreateServerSession ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse) noexcept { return std::make_unique<TestServerRecordSession>( std::make_shared<WebRTCConfig>(), CreateServerPeer, CreateServerRecordPeer, sendRequest, sendResponse); } #endif #if ENABLE_CLIENT struct TestRecordSession : public ClientRecordSession { using ClientRecordSession::ClientRecordSession; bool onOptionsResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; }; bool TestRecordSession::onOptionsResponse( const rtsp::Request& request, const rtsp::Response& response) noexcept { if(!ClientRecordSession::onOptionsResponse(request, response)) return false; if(!isSupported(rtsp::Method::RECORD)) return false; startRecord(RECORD_TOKEN); return true; } static std::unique_ptr<WebRTCPeer> CreateClientPeer(const std::string& uri) { #if USE_RESTREAMER return std::make_unique<GstReStreamer>(uri); #else return std::make_unique<GstTestStreamer>(); #endif } static std::unique_ptr<rtsp::ClientSession> CreateClientSession ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse) noexcept { const std::string uri = #if USE_RESTREAMER "rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream"; #else "Record"; #endif return std::make_unique<TestRecordSession>( uri, RECORD_TOKEN, std::make_shared<WebRTCConfig>(), CreateClientPeer, sendRequest, sendResponse); } static void ClientDisconnected(client::WsClient* client) noexcept { GSourcePtr timeoutSourcePtr(g_timeout_source_new_seconds(RECONNECT_TIMEOUT)); GSource* timeoutSource = timeoutSourcePtr.get(); g_source_set_callback(timeoutSource, [] (gpointer userData) -> gboolean { static_cast<client::WsClient*>(userData)->connect(); return false; }, client, nullptr); g_source_attach(timeoutSource, g_main_context_get_thread_default()); } #endif int main(int argc, char *argv[]) { LibGst libGst; #if ENABLE_SERVER std::thread signallingThread( [] () { InitWsServerLogger(spdlog::level::trace); InitServerSessionLogger(spdlog::level::trace); signalling::Config config {}; config.port = SERVER_PORT; GMainContextPtr serverContextPtr(g_main_context_new()); GMainContext* serverContext = serverContextPtr.get(); g_main_context_push_thread_default(serverContext); GMainLoopPtr loopPtr(g_main_loop_new(serverContext, FALSE)); GMainLoop* loop = loopPtr.get(); signalling::WsServer server(config, loop, CreateServerSession); if(server.init()) g_main_loop_run(loop); }); #endif #if ENABLE_CLIENT std::thread clientThread( [] () { InitWsClientLogger(spdlog::level::info); InitClientSessionLogger(spdlog::level::info); client::Config config { .server = SERVER_HOST, .serverPort = SERVER_PORT, .useTls = false }; GMainContextPtr clientContextPtr(g_main_context_new()); GMainContext* clientContext = clientContextPtr.get(); g_main_context_push_thread_default(clientContext); GMainLoopPtr loopPtr(g_main_loop_new(clientContext, FALSE)); GMainLoop* loop = loopPtr.get(); client::WsClient client( config, loop, CreateClientSession, std::bind(ClientDisconnected, &client)); if(client.init()) { client.connect(); g_main_loop_run(loop); } }); #endif #if ENABLE_SERVER if(signallingThread.joinable()) signallingThread.join(); #endif #if ENABLE_CLIENT if(clientThread.joinable()) clientThread.join(); #endif return 0; }
6,403
C++
.cpp
199
26.085427
98
0.685621
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,235
Test.cpp
WebRTSP_WebRTSP/Apps/Test/Test.cpp
#include <thread> #include <memory> #include <CxxPtr/GlibPtr.h> #include "RtStreaming/GstRtStreaming/LibGst.h" #include "TestParse.h" #include "TestSerialize.h" #include "Helpers/LwsLog.h" #define ENABLE_SERVER 1 #define ENABLE_CLIENT 1 #define USE_RESTREAMER 1 #if ENABLE_SERVER #include "Signalling/Log.h" #include "Signalling/WsServer.h" #include "Signalling/ServerSession.h" #include "RtStreaming/GstRtStreaming/GstTestStreamer.h" #include "RtStreaming/GstRtStreaming/GstReStreamer.h" #endif #if ENABLE_CLIENT #include "RtStreaming/GstRtStreaming/GstClient.h" #include "Client/Log.h" #include "Client/WsClient.h" #include "Client/ClientSession.h" #endif #if ENABLE_SERVER #define SERVER_HOST "localhost" #else #define SERVER_HOST "ipcam.stream" #endif enum { SERVER_PORT = 5554, RECONNECT_TIMEOUT = 5, }; #if ENABLE_SERVER static std::unique_ptr<WebRTCPeer> CreateServerPeer(const std::string& uri) { #if USE_RESTREAMER return std::make_unique<GstReStreamer>(uri, std::string()); #else return std::make_unique<GstTestStreamer>(); #endif } static std::unique_ptr<ServerSession> CreateServerSession ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse) noexcept { return std::make_unique<ServerSession>( std::make_shared<WebRTCConfig>(), CreateServerPeer, sendRequest, sendResponse); } #endif #if ENABLE_CLIENT static std::unique_ptr<WebRTCPeer> CreateClientPeer() { return std::make_unique<GstClient>(); } static std::unique_ptr<rtsp::ClientSession> CreateClientSession ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse) noexcept { const std::string url = #if USE_RESTREAMER "rtsp://stream.strba.sk:1935/strba/VYHLAD_JAZERO.stream"; #elif ENABLE_SERVER "*"; #else "Bars"; #endif return std::make_unique<ClientSession>( url, std::make_shared<WebRTCConfig>(), CreateClientPeer, sendRequest, sendResponse); } static void ClientDisconnected(client::WsClient* client) noexcept { GSourcePtr timeoutSourcePtr(g_timeout_source_new_seconds(RECONNECT_TIMEOUT)); GSource* timeoutSource = timeoutSourcePtr.get(); g_source_set_callback(timeoutSource, [] (gpointer userData) -> gboolean { static_cast<client::WsClient*>(userData)->connect(); return false; }, client, nullptr); g_source_attach(timeoutSource, g_main_context_get_thread_default()); } #endif int main(int argc, char *argv[]) { LibGst libGst; TestParse(); TestSerialize(); InitLwsLogger(spdlog::level::warn); #if ENABLE_SERVER std::thread signallingThread( [] () { InitWsServerLogger(spdlog::level::trace); signalling::Config config {}; config.port = SERVER_PORT; GMainContextPtr serverContextPtr(g_main_context_new()); GMainContext* serverContext = serverContextPtr.get(); g_main_context_push_thread_default(serverContext); GMainLoopPtr loopPtr(g_main_loop_new(serverContext, FALSE)); GMainLoop* loop = loopPtr.get(); signalling::WsServer server(config, loop, CreateServerSession); if(server.init()) g_main_loop_run(loop); }); #endif #if ENABLE_CLIENT std::thread clientThread( [] () { InitWsClientLogger(spdlog::level::trace); client::Config config { .server = SERVER_HOST, .serverPort = SERVER_PORT, .useTls = false, }; GMainContextPtr clientContextPtr(g_main_context_new()); GMainContext* clientContext = clientContextPtr.get(); g_main_context_push_thread_default(clientContext); GMainLoopPtr loopPtr(g_main_loop_new(clientContext, FALSE)); GMainLoop* loop = loopPtr.get(); client::WsClient client( config, loop, CreateClientSession, std::bind(ClientDisconnected, &client)); if(client.init()) { client.connect(); g_main_loop_run(loop); } }); #endif #if ENABLE_SERVER if(signallingThread.joinable()) signallingThread.join(); #endif #if ENABLE_CLIENT if(clientThread.joinable()) clientThread.join(); #endif return 0; }
4,564
C++
.cpp
146
24.773973
81
0.660205
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,236
TestParse.cpp
WebRTSP_WebRTSP/Apps/Test/TestParse.cpp
#include "TestParse.h" #include <cassert> #include "RtspParser/RtspParser.h" void TestParse() { { const char OPTIONSRequest[] = " OPTIONS * WEBRTSP/0.2"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2 "; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS*WEBRTSP/0.2"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTION * WEBRTSP/0.2"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS RTS/1.0"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * RTS/1.0"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * RTSP/.0"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2\r\n"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2\r\n" "CSeq: 1"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(!success); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2\r\n" "CSeq: 1\r\n"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(success); assert(request.method == rtsp::Method::OPTIONS); assert(request.uri == "*"); assert(request.protocol == rtsp::Protocol::WEBRTSP_0_2); assert(request.cseq == 1); assert(request.headerFields.empty()); } { const char OPTIONSRequest[] = "OPTIONS * WEBRTSP/0.2\r\n" "CSeq: 1\r\n"; rtsp::Request request; const bool success = rtsp::ParseRequest(OPTIONSRequest, sizeof(OPTIONSRequest) - 1, &request); assert(success); assert(request.method == rtsp::Method::OPTIONS); assert(request.uri == "*"); assert(request.protocol == rtsp::Protocol::WEBRTSP_0_2); assert(request.cseq == 1); assert(request.headerFields.empty()); } { const char SETUPRequest[] = "SETUP rtsp://example.com/meida.ogg/streamid=0 WEBRTSP/0.2\r\n" "CSeq: 3\r\n" "Transport: RTP/AVP;unicast;client_port=8000-8001\r\n"; rtsp::Request request; const bool success = rtsp::ParseRequest(SETUPRequest, sizeof(SETUPRequest) - 1, &request); assert(success); assert(request.method == rtsp::Method::SETUP); assert(request.uri == "rtsp://example.com/meida.ogg/streamid=0"); assert(request.protocol == rtsp::Protocol::WEBRTSP_0_2); assert(request.cseq == 3); assert(request.headerFields.size() == 1); if(request.headerFields.size() == 1) { auto it = request.headerFields.begin(); assert( it->first == "Transport" && it->second == "RTP/AVP;unicast;client_port=8000-8001"); } } { const char GET_PARAMETERRequest[] = "GET_PARAMETER rtsp://example.com/media.mp4 WEBRTSP/0.2\r\n" "CSeq: 9\r\n" "Content-Type: text/parameters\r\n" "Session: 12345678\r\n" "Content-Length: 15\r\n" "\r\n" "packets_received\r\n" "jitter\r\n"; rtsp::Request request; const bool success = rtsp::ParseRequest(GET_PARAMETERRequest, sizeof(GET_PARAMETERRequest) - 1, &request); assert(success); assert(request.method == rtsp::Method::GET_PARAMETER); assert(request.cseq == 9); assert(request.headerFields.size() == 3); assert(!request.body.empty()); } { const char GET_PARAMETERResponse[] = "WEBRTSP/0.2 200 OK\r\n" "CSeq: 9\r\n" "Content-Length: 46\r\n" "Content-Type: text/parameters\r\n" "\r\n" "packets_received: 10\r\n" "jitter: 0.3838\r\n"; rtsp::Response response; const bool success = rtsp::ParseResponse(GET_PARAMETERResponse, sizeof(GET_PARAMETERResponse) - 1, &response); assert(success); assert(response.protocol == rtsp::Protocol::WEBRTSP_0_2); assert(response.statusCode == 200); assert(response.reasonPhrase == "OK"); assert(response.cseq == 9); assert(response.headerFields.size() == 2); assert(!response.body.empty()); } }
6,185
C++
.cpp
175
25.971429
101
0.570666
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,237
TestSerialize.cpp
WebRTSP_WebRTSP/Apps/Test/TestSerialize.cpp
#include "TestSerialize.h" #include <cassert> #include "RtspParser/RtspSerialize.h" void TestSerialize() noexcept { rtsp::Request request; request.method = rtsp::Method::OPTIONS; request.uri = "*"; request.protocol = rtsp::Protocol::WEBRTSP_0_2; request.cseq = 1; const std::string requestMessage = rtsp::Serialize(request); assert(requestMessage == "OPTIONS * WEBRTSP/0.2\r\n" "CSeq: 1\r\n"); rtsp::Response response; response.protocol = rtsp::Protocol::WEBRTSP_0_2; response.cseq = 1; response.headerFields.emplace("Public", "DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); response.statusCode = 200; response.reasonPhrase = "OK"; const std::string responseMessage = rtsp::Serialize(response); assert(responseMessage == "WEBRTSP/0.2 200 OK\r\n" "CSeq: 1\r\n" "Public: DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE\r\n"); }
922
C++
.cpp
26
30.230769
86
0.674944
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,238
Request.cpp
WebRTSP_WebRTSP/RtspParser/Request.cpp
#include "Request.h" namespace rtsp { MediaSessionId RequestSession(const Request& request) { auto it = request.headerFields.find("session"); if(request.headerFields.end() == it) return MediaSessionId(); return it->second; } void SetRequestSession(Request* request, const MediaSessionId& session) { request->headerFields["session"] = session; } std::string RequestContentType(const Request& request) { auto it = request.headerFields.find("content-type"); if(request.headerFields.end() == it) return std::string(); return it->second; } void SetContentType(Request* request, const std::string& contentType) { request->headerFields.emplace(ContentTypeFieldName, contentType); } void SetBearerAuthorization(Request* request, const std::string& token) { request->headerFields.emplace("Authorization", "Bearer " + token); } }
882
C++
.cpp
29
27.275862
71
0.746145
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,239
RtspSerialize.cpp
WebRTSP_WebRTSP/RtspParser/RtspSerialize.cpp
#include "RtspSerialize.h" #include <cassert> namespace rtsp { namespace { void SerializeStatusCode(unsigned statusCode, std::string* out) { out->reserve(out->size() + 3); if(statusCode > 999) { *out += "999"; } else if(statusCode < 100) { *out += "100"; } else { out->resize(out->size() + 3); for(unsigned i = 0; i < 3; ++i) { (*out)[out->size() - i - 1] = '0' + statusCode % 10; statusCode /= 10; } } } } void Serialize(const Parameters& parameters, std::string* out) noexcept { out->clear(); for(const std::pair<std::string, std::string>& parameter: parameters) { *out += parameter.first; *out += ": "; *out += parameter.second; *out += "\r\n"; } } void Serialize(const Request& request, std::string* out) noexcept { try { *out = MethodName(request.method); *out += " "; *out += request.uri; *out += " "; *out += ProtocolName(request.protocol); *out += "\r\n"; *out += "CSeq: "; *out += std::to_string(request.cseq); *out += "\r\n"; for(const std::pair<std::string, std::string>& hf: request.headerFields) { *out += hf.first; *out += ": "; *out += hf.second; *out += "\r\n"; } if(!request.body.empty()) { *out +="\r\n"; *out += request.body; } } catch(...) { out->clear(); } } std::string Serialize(const Request& request) noexcept { assert(!request.uri.empty()); std::string out; Serialize(request, &out); return out; } void Serialize(const Response& response, std::string* out) noexcept { try { *out = ProtocolName(response.protocol); *out += " "; SerializeStatusCode(response.statusCode, out); *out += " "; *out += response.reasonPhrase; *out += "\r\n"; *out += "CSeq: "; *out += std::to_string(response.cseq); *out += "\r\n"; for(const std::pair<std::string, std::string>& hf: response.headerFields) { *out += hf.first; *out += ": "; *out += hf.second; *out += "\r\n"; } if(!response.body.empty()) { *out +="\r\n"; *out += response.body; } } catch(...) { out->clear(); } } std::string Serialize(const Response& response) noexcept { std::string out; Serialize(response, &out); return out; } }
2,568
C++
.cpp
96
19.822917
83
0.507548
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,240
Methods.cpp
WebRTSP_WebRTSP/RtspParser/Methods.cpp
#include "Methods.h" #include <cstring> #include "Token.h" namespace rtsp { namespace { static const Method Methods[] = { Method::OPTIONS, Method::LIST, Method::DESCRIBE, Method::SETUP, Method::PLAY, Method::RECORD, Method::SUBSCRIBE, //Method::PAUSE, Method::TEARDOWN, Method::GET_PARAMETER, Method::SET_PARAMETER, //Method::REDIRECT, }; static const unsigned MethodsCount = sizeof(Methods) / sizeof(Methods[0]); } const char* MethodName(Method method) noexcept { switch(method) { case Method::NONE: return nullptr; case Method::OPTIONS: return "OPTIONS"; case Method::LIST: return "LIST"; case Method::DESCRIBE: return "DESCRIBE"; case Method::SETUP: return "SETUP"; case Method::PLAY: return "PLAY"; case Method::RECORD: return "RECORD"; case Method::SUBSCRIBE: return "SUBSCRIBE"; // case Method::PAUSE: // return "PAUSE"; case Method::TEARDOWN: return "TEARDOWN"; case Method::GET_PARAMETER: return "GET_PARAMETER"; case Method::SET_PARAMETER: return "SET_PARAMETER"; // case Method::REDIRECT: // return "REDIRECT"; } return nullptr; } Method ParseMethod(const Token& token) noexcept { if(IsEmptyToken(token)) return Method::NONE; for(const Method m: Methods) { const char* methodName = MethodName(m); if(0 == strncmp(methodName, token.token, token.size) && strlen(methodName) == token.size) return m; } return Method::NONE; } }
1,616
C++
.cpp
65
19.646154
97
0.636955
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,241
Authentication.cpp
WebRTSP_WebRTSP/RtspParser/Authentication.cpp
#include "Authentication.h" #include <cstring> namespace rtsp { namespace { static const Authentication Authentications[] = { Authentication::Bearer, }; static const unsigned AuthenticationsCount = sizeof(Authentications) / sizeof(Authentications[0]); } const char* AuthenticationName(Authentication authentication) noexcept { switch(authentication) { case Authentication::None: return nullptr; case Authentication::Unknown: return nullptr; case Authentication::Bearer: return "Bearer"; } return nullptr; } Authentication ParseAuthentication(const Token& token) noexcept { if(IsEmptyToken(token)) return Authentication::Unknown; for(const Authentication a: Authentications) { const char* authName = AuthenticationName(a); if(0 == strncmp(authName, token.token, token.size) && strlen(authName) == token.size) return a; } return Authentication::Unknown; } }
977
C++
.cpp
34
24.176471
93
0.725806
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,242
Token.cpp
WebRTSP_WebRTSP/RtspParser/Token.cpp
#include "Token.h" #include <cassert> namespace rtsp { bool IsEmptyToken(const Token& token) noexcept { assert( (token.token == nullptr && token.size == 0) || (token.token != nullptr && token.size > 0)); return token.token == nullptr || token.size == 0; } }
288
C++
.cpp
11
22.454545
54
0.634686
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,243
RtspParser.cpp
WebRTSP_WebRTSP/RtspParser/RtspParser.cpp
#include "RtspParser.h" #include <cstddef> #include <cassert> #include <cstring> #include <algorithm> #include <functional> #include "Methods.h" #include "Protocols.h" #include "Token.h" namespace rtsp { static inline bool IsEOS(size_t pos, size_t size) { return pos == size; } static inline bool IsWSP(char c) { return c == ' ' || c == '\t'; } static inline bool IsCtl(char c) { return (c >= 0 && c <= 31) || c == 127; } static inline bool IsDigit(char c) { switch(c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return true; } return false; } static inline unsigned ParseDigit(char c) { switch(c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return c - '0'; default: return 0; } } static inline bool IsTspecials(char c) { switch(c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '\\': case '\"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': return true; } return false; } static bool IsChar(const char* buf, size_t pos, size_t size, char c) { return !IsEOS(pos, size) && buf[pos] == c; } static bool SkipWSP(const char* buf, size_t* pos, size_t size) { const size_t savePos = *pos; for(; *pos < size && IsWSP(buf[*pos]); ++(*pos)); return savePos != *pos; } static bool IsEOL(const char* buf, size_t pos, size_t size) { return IsChar(buf, pos, size, '\r') && IsChar(buf, pos + 1, size, '\n'); } static bool SkipEOL(const char* buf, size_t* pos, size_t size) { if(!IsEOL(buf, *pos, size)) return false; *pos += 2; return true; } static bool SkipFolding(const char* buf, size_t* pos, size_t size) { size_t tmpPos = *pos; if(!SkipEOL(buf, &tmpPos, size)) return false; if(!SkipWSP(buf, &tmpPos, size)) return false; *pos = tmpPos; return true; } static bool SkipLWS(const char* buf, size_t* pos, size_t size) { size_t tmpPos = *pos; SkipEOL(buf, &tmpPos, size); if(!SkipWSP(buf, &tmpPos, size)) return false; *pos = tmpPos; return true; } static bool Skip(const char* buf, size_t* pos, size_t size, char c) { if(IsChar(buf, *pos, size, c)) { ++(*pos); return true; } return false; } static bool SkipNot(const char* buf, size_t* pos, size_t size, char c) { while(!IsEOS(*pos, size)) { if(IsChar(buf, *pos, size, c)) return true; ++(*pos); } return false; } static Token GetToken(const char* buf, size_t* pos, size_t size) { const size_t tokenPos = *pos; for(; *pos < size; ++(*pos)) { if(IsCtl(buf[*pos]) || IsTspecials(buf[*pos])) break; } Token token; if((*pos - tokenPos) > 0) { token.token = buf + tokenPos; token.size = *pos - tokenPos; } assert( (token.token == nullptr && token.size == 0) || (token.token != nullptr && token.size > 0)); return token; } static Token GetProtocol(const char* buf, size_t* pos, size_t size) { Token token; const char protocolName[] = "WEBRTSP"; const unsigned protocolNameLength = sizeof(protocolName) - 1; if(size - *pos < protocolNameLength + 4) return token; if(0 != strncmp(buf + *pos, protocolName, protocolNameLength)) return token; if(buf[*pos + protocolNameLength] != '/') return token; if(!IsDigit(buf[*pos + protocolNameLength + 1])) return token; if(buf[*pos + protocolNameLength + 2] != '.') return token; if(!IsDigit(buf[*pos + protocolNameLength + 3])) return token; token.token = buf + *pos; token.size = protocolNameLength + 4; *pos += token.size; return token; } static Token GetURI(const char* buf, size_t* pos, size_t size) { // FIXME! fix according to rfc const size_t tokenPos = *pos; for(; *pos < size; ++(*pos)) { if(IsCtl(buf[*pos]) || buf[*pos] == ' ') break; } Token token; if((*pos - tokenPos) > 0) { token.token = buf + tokenPos; token.size = *pos - tokenPos; } assert( (token.token == nullptr && token.size == 0) || (token.token != nullptr && token.size > 0)); return token; } static bool ParseMethodLine(const char* request, size_t* pos, size_t size, Request* out) { const Token methodToken = GetToken(request, pos, size); if(IsEmptyToken(methodToken)) return false; out->method = ParseMethod(methodToken); if(out->method == Method::NONE) return false; if(!SkipWSP(request, pos, size)) return false; const Token uri = GetURI(request, pos, size); if(IsEmptyToken(uri)) return false; out->uri.assign(uri.token, uri.size); if(!SkipWSP(request, pos, size)) return false; const Token protocolToken = GetProtocol(request, pos, size); if(IsEmptyToken(protocolToken)) return false; out->protocol = ParseProtocol(protocolToken); if(out->protocol == Protocol::NONE) return false; if(!SkipEOL(request, pos, size)) return false; return true; } bool ParseHeaderField( const char* buf, size_t* pos, size_t size, std::map<std::string, std::string, LessNoCase>* headerFields) { const Token name = GetToken(buf, pos, size); if(IsEmptyToken(name)) return false; if(!Skip(buf, pos, size, ':')) return false; SkipLWS(buf, pos, size); size_t valuePos = *pos; while(*pos < size) { size_t tmpPos = *pos; if(SkipFolding(buf, pos, size)) continue; else if(SkipEOL(buf, pos, size)) { const Token value { buf + valuePos, tmpPos - valuePos }; headerFields->emplace( std::string(name.token, name.size), std::string(value.token, value.size)); return true; } else if(!IsCtl(buf[*pos])) ++(*pos); else return false; } return false; } bool ParseCSeq(const std::string& token, CSeq* out) noexcept { CSeq tmpOut = 0; for(const std::string::value_type& c: token) { if(!IsDigit(c)) return false; unsigned digit = ParseDigit(c); if(tmpOut > (tmpOut * 10 + digit)) { // overflow return false; } tmpOut = tmpOut * 10 + digit; } if(!tmpOut) return false; if(out) *out = tmpOut; return true; } bool ParseRequest(const char* request, size_t size, Request* out) noexcept { size_t position = 0; if(!ParseMethodLine(request, &position, size, out)) return false; while(!IsEOS(position, size)) { if(!ParseHeaderField(request, &position, size, &(out->headerFields))) return false; if(IsEOS(position, size)) break; if(SkipEOL(request, &position, size)) break; } if(!IsEOS(position, size)) out->body.assign(request + position, size - position); auto cseqIt = out->headerFields.find("cseq"); if(out->headerFields.end() == cseqIt || cseqIt->second.empty()) return false; if(!ParseCSeq(cseqIt->second, &out->cseq)) return false; out->headerFields.erase(cseqIt); return true; } static Token GetStatusCode(const char* buf, size_t* pos, size_t size) { Token token; if(size - *pos < 3) return token; const size_t statusCodePos = *pos; for(unsigned i = 0; i < 3 && *pos < size; ++i, ++(*pos)) if(!IsDigit(buf[*pos])) return token; token.token = buf + statusCodePos; token.size = 3; return token; } unsigned ParseStatusCode(const Token& token) { if(IsEmptyToken(token) || token.size < 3) return 0; return ParseDigit(token.token[0]) * 100 + ParseDigit(token.token[1]) * 10 + ParseDigit(token.token[2]) * 1; } static Token GetReasonPhrase(const char* response, size_t* pos, size_t size) { const size_t reasonPhrasePos = *pos; for(; *pos < size; ++(*pos)) { if(IsCtl(response[*pos])) break; } return Token{ response + reasonPhrasePos, *pos - reasonPhrasePos }; } static bool ParseStatusLine(const char* response, size_t* pos, size_t size, Response* out) { const Token protocolToken = GetProtocol(response, pos, size); if(IsEmptyToken(protocolToken)) return false; out->protocol = ParseProtocol(protocolToken); if(out->protocol == Protocol::NONE) return false; if(!SkipWSP(response, pos, size)) return false; const Token statusCodeToken = GetStatusCode(response, pos, size); if(IsEmptyToken(statusCodeToken)) return false; out->statusCode = ParseStatusCode(statusCodeToken); if(!SkipWSP(response, pos, size)) return false; const Token reasonPhrase = GetReasonPhrase(response, pos, size); if(IsEmptyToken(reasonPhrase)) return false; out->reasonPhrase.assign(reasonPhrase.token, reasonPhrase.size); if(!SkipEOL(response, pos, size)) return false; return true; } bool ParseResponse(const char* response, size_t size, Response* out) noexcept { size_t position = 0; if(!ParseStatusLine(response, &position, size, out)) return false; while(!IsEOS(position, size)) { if(!ParseHeaderField(response, &position, size, &(out->headerFields))) return false; if(SkipEOL(response, &position, size)) break; } if(!IsEOS(position, size)) out->body.assign(response + position, size - position); auto cseqIt = out->headerFields.find("cseq"); if(out->headerFields.end() == cseqIt || cseqIt->second.empty()) return false; if(!ParseCSeq(cseqIt->second, &out->cseq)) return false; out->headerFields.erase(cseqIt); return true; } bool IsRequest(const char* request, size_t size) noexcept { size_t position = 0; const Token methodToken = GetToken(request, &position, size); if(IsEmptyToken(methodToken)) return false; if(ParseMethod(methodToken) == Method::NONE) return false; return true; } static bool ParseParameter( const char* buf, size_t* pos, size_t size, Parameters* parameters) { Token name { buf + *pos }; if(!SkipNot(buf, pos, size, ':')) return false; name.size = buf + *pos - name.token; if(!name.size) return false; if(!Skip(buf, pos, size, ':')) return false; SkipWSP(buf, pos, size); size_t valuePos = *pos; while(!IsEOS(*pos, size)) { size_t tmpPos = *pos; if(SkipEOL(buf, pos, size)) { const Token value { buf + valuePos, tmpPos - valuePos }; parameters->emplace( std::string(name.token, name.size), std::string(value.token, value.size)); return true; } else if(!IsCtl(buf[*pos])) ++(*pos); else return false; } return false; } bool ParseParameters( const std::string& body, Parameters* parameters) noexcept { const char* buf = body.data(); size_t size = body.size(); size_t position = 0; while(!IsEOS(position, size)) { if(!ParseParameter(buf, &position, size, parameters)) return false; } return true; } bool ParseParametersNames( const std::string& body, ParametersNames* names) noexcept { const char* buf = body.data(); size_t size = body.size(); size_t pos = 0; while(!IsEOS(pos, size)) { const Token name = GetToken(buf, &pos, size); if(IsEmptyToken(name)) return false; names->emplace(name.token, name.size); if(!SkipEOL(buf, &pos, size)) return false; } return true; } std::set<rtsp::Method> ParseOptions(const Response& response) { std::set<rtsp::Method> returnOptions; auto it = response.headerFields.find("public"); if(response.headerFields.end() == it) return returnOptions; std::set<rtsp::Method> parsedOptions; const std::string& optionsString = it->second; const char* buf = optionsString.data(); size_t size = optionsString.size(); size_t pos = 0; while(!IsEOS(pos, size)) { SkipWSP(buf, &pos, size); const Token token = GetToken(buf, &pos, size); Method method = ParseMethod(token); if(Method::NONE == method) return returnOptions; SkipWSP(buf, &pos, size); if(!IsEOS(pos, size) && !Skip(buf, &pos, size, ',')) return returnOptions; parsedOptions.insert(method); } returnOptions.swap(parsedOptions); return returnOptions; } std::pair<Authentication, std::string> ParseAuthentication(const Request& request) { auto it = request.headerFields.find("authorization"); if(it == request.headerFields.end()) return std::make_pair(Authentication::None, std::string()); const char* buf = it->second.data(); size_t size = it->second.size(); size_t pos = 0; const Token token = GetToken(buf, &pos, size); Authentication authentication = ParseAuthentication(token); if(Authentication::Unknown == authentication) return std::make_pair(Authentication::Unknown, std::string()); SkipWSP(buf, &pos, size); if(IsEOS(pos, size)) return std::make_pair(authentication, std::string()); return std::make_pair(authentication, std::string(buf + pos, size - pos)); } std::pair<std::string, std::string> SplitUri(const std::string& uri) { const std::string::size_type separatorPos = uri.find_first_of(rtsp::UriSeparator); std::string streamerName = uri.substr(0, separatorPos); std::string substreamName = separatorPos == std::string::npos ? std::string() : uri.substr(separatorPos + 1); return std::make_pair(streamerName, substreamName); } }
14,323
C++
.cpp
491
23.291242
90
0.607624
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,244
Protocols.cpp
WebRTSP_WebRTSP/RtspParser/Protocols.cpp
#include "Protocols.h" #include <cstring> namespace rtsp { namespace { static const Protocol Protocols[] = { Protocol::WEBRTSP_0_2, }; static const unsigned ProtocolsCount = sizeof(Protocols) / sizeof(Protocols[0]); } const char* ProtocolName(Protocol protocol) noexcept { switch(protocol) { case Protocol::NONE: return nullptr; case Protocol::WEBRTSP_0_2: return "WEBRTSP/0.2"; } return nullptr; } Protocol ParseProtocol(const Token& token) noexcept { if(IsEmptyToken(token)) return Protocol::NONE; for(const Protocol p: Protocols) { const char* protocolName = ProtocolName(p); if(0 == strncmp(protocolName, token.token, token.size) && strlen(protocolName) == token.size) return p; } return Protocol::NONE; } }
817
C++
.cpp
31
21.967742
101
0.689521
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,245
Response.cpp
WebRTSP_WebRTSP/RtspParser/Response.cpp
#include "Response.h" namespace rtsp { MediaSessionId ResponseSession(const Response& response) { auto it = response.headerFields.find("session"); if(response.headerFields.end() == it) return MediaSessionId(); return it->second; } void SetResponseSession(Response* response, const MediaSessionId& session) { response->headerFields["session"] = session; } std::string ResponseContentType(const Response& response) { auto it = response.headerFields.find("content-type"); if(response.headerFields.end() == it) return std::string(); return it->second; } void SetContentType(Response* response, const std::string& contentType) { response->headerFields.emplace(ContentTypeFieldName, contentType); } }
752
C++
.cpp
25
26.8
74
0.749304
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,246
Log.cpp
WebRTSP_WebRTSP/Signalling/Log.cpp
#include "Log.h" #include <spdlog/spdlog.h> #include <spdlog/sinks/stdout_sinks.h> static std::shared_ptr<spdlog::logger> WsServerLogger; static std::shared_ptr<spdlog::logger> ServerSessionLogger; void InitWsServerLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); WsServerLogger = std::make_shared<spdlog::logger>("WsServer", sink); WsServerLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& WsServerLog() { if(!WsServerLogger) #ifndef NDEBUG InitWsServerLogger(spdlog::level::debug); #else InitWsServerLogger(spdlog::level::info); #endif return WsServerLogger; } void InitServerSessionLogger(spdlog::level::level_enum level) { spdlog::sink_ptr sink = std::make_shared<spdlog::sinks::stdout_sink_st>(); ServerSessionLogger = std::make_shared<spdlog::logger>("ServerSession", sink); ServerSessionLogger->set_level(level); } const std::shared_ptr<spdlog::logger>& ServerSessionLog() { if(!ServerSessionLogger) #ifndef NDEBUG InitServerSessionLogger(spdlog::level::debug); #else InitServerSessionLogger(spdlog::level::info); #endif return ServerSessionLogger; }
1,229
C++
.cpp
37
29.891892
82
0.749576
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,247
ServerSession.cpp
WebRTSP_WebRTSP/Signalling/ServerSession.cpp
#include "ServerSession.h" #include <list> #include <map> #include "RtspSession/StatusCode.h" #include "RtspSession/IceCandidate.h" #include "Log.h" namespace { struct MediaSession { enum class Type { Describe, Record, Subscribe, }; MediaSession(MediaSession::Type type, const std::string& uri, rtsp::CSeq initialRequestCSeq) : type(type), uri(uri), initialRequestCSeq(initialRequestCSeq) {} const Type type; const std::string uri; const rtsp::CSeq initialRequestCSeq; std::unique_ptr<WebRTCPeer> localPeer; std::deque<rtsp::IceCandidate> iceCandidates; bool prepared = false; }; typedef std::map<rtsp::MediaSessionId, std::unique_ptr<MediaSession>> MediaSessions; const auto Log = ServerSessionLog; } struct ServerSession::Private { struct AutoEraseRequest; struct AutoEraseRecordRequest; Private( ServerSession* owner, const CreatePeer& createPeer); Private( ServerSession* owner, const CreatePeer& createPeer, const CreatePeer& createRecordPeer); ServerSession *const owner; CreatePeer createPeer; CreatePeer createRecordPeer; std::optional<std::string> authCookie; MediaSessions mediaSessions; bool recordEnabled() { return createRecordPeer ? true : false; } std::string nextSessionId() { return std::to_string(_nextSessionId++); } void sendIceCandidates(const rtsp::MediaSessionId&, MediaSession* mediaSession); void streamerPrepared(const rtsp::MediaSessionId&); void recorderPrepared(const rtsp::MediaSessionId&); void recordToClientStreamerPrepared(const rtsp::MediaSessionId&); void iceCandidate( const rtsp::MediaSessionId&, unsigned, const std::string&); void eos(const rtsp::MediaSessionId& session); private: unsigned _nextSessionId = 1; }; ServerSession::Private::Private( ServerSession* owner, const CreatePeer& createPeer) : owner(owner), createPeer(createPeer) { } ServerSession::Private::Private( ServerSession* owner, const CreatePeer& createPeer, const CreatePeer& createRecordPeer) : owner(owner), createPeer(createPeer), createRecordPeer(createRecordPeer) { } void ServerSession::Private::sendIceCandidates( const rtsp::MediaSessionId& session, MediaSession* mediaSession) { if(!mediaSession->iceCandidates.empty()) { std::string iceCandidates; for(const rtsp::IceCandidate& c : mediaSession->iceCandidates) { iceCandidates += std::to_string(c.mlineIndex) + "/" + c.candidate + "\r\n"; } if(!mediaSession->iceCandidates.empty()) { owner->requestSetup( mediaSession->uri, rtsp::IceCandidateContentType, session, iceCandidates); } mediaSession->iceCandidates.clear(); } } void ServerSession::Private::streamerPrepared(const rtsp::MediaSessionId& session) { auto it = mediaSessions.find(session); if(mediaSessions.end() == it || it->second->type != MediaSession::Type::Describe) { owner->disconnect(); return; } MediaSession& mediaSession = *(it->second); WebRTCPeer& localPeer = *mediaSession.localPeer; const rtsp::CSeq describeRequestCSeq = mediaSession.initialRequestCSeq; mediaSession.prepared = true; if(localPeer.sdp().empty()) owner->disconnect(); else { rtsp::Response response; prepareOkResponse(describeRequestCSeq, session, &response); SetContentType(&response, rtsp::SdpContentType); response.body = localPeer.sdp(); owner->sendResponse(response); sendIceCandidates(session, &mediaSession); } } void ServerSession::Private::recorderPrepared(const rtsp::MediaSessionId& session) { auto it = mediaSessions.find(session); if(mediaSessions.end() == it || it->second->type != MediaSession::Type::Record) { owner->disconnect(); return; } MediaSession& mediaSession = *(it->second); WebRTCPeer& recorder = *mediaSession.localPeer; const rtsp::CSeq recordRequestCSeq = mediaSession.initialRequestCSeq; mediaSession.prepared = true; if(recorder.sdp().empty()) owner->disconnect(); else { rtsp::Response response; prepareOkResponse(recordRequestCSeq, session, &response); SetContentType(&response, rtsp::SdpContentType); response.body = recorder.sdp(); owner->sendResponse(response); sendIceCandidates(session, &mediaSession); } } void ServerSession::Private::recordToClientStreamerPrepared(const rtsp::MediaSessionId& mediaSessionId) { auto it = mediaSessions.find(mediaSessionId); assert(mediaSessions.end() != it); if(mediaSessions.end() == it) { return; } MediaSession& mediaSession = *(it->second); if(mediaSession.type != MediaSession::Type::Subscribe) { assert(false); return; } WebRTCPeer& localPeer = *mediaSession.localPeer; mediaSession.prepared = true; if(localPeer.sdp().empty()) { assert(false); owner->disconnect(); } else { rtsp::Request& request = *owner->createRequest(rtsp::Method::RECORD, mediaSession.uri); SetRequestSession(&request, mediaSessionId); SetContentType(&request, rtsp::SdpContentType); request.body = localPeer.sdp(); owner->sendRequest(request); sendIceCandidates(mediaSessionId, &mediaSession); } } void ServerSession::Private::iceCandidate( const rtsp::MediaSessionId& session, unsigned mlineIndex, const std::string& candidate) { auto it = mediaSessions.find(session); if(mediaSessions.end() == it) { owner->disconnect(); return; } MediaSession& mediaSession = *(it->second); if(mediaSession.prepared) { owner->requestSetup( mediaSession.uri, rtsp::IceCandidateContentType, session, std::to_string(mlineIndex) + "/" + candidate + "\r\n"); } else { mediaSession.iceCandidates.emplace_back(rtsp::IceCandidate { mlineIndex, candidate }); } } void ServerSession::Private::eos(const rtsp::MediaSessionId& session) { Log()->trace("[{}] Eos. Session: {}", owner->sessionLogId, session); auto it = mediaSessions.find(session); if(mediaSessions.end() == it) { owner->disconnect(); return; } MediaSession& mediaSession = *(it->second); mediaSession.localPeer->stop(); const rtsp::CSeq describeRequestCSeq = mediaSession.initialRequestCSeq; if(mediaSession.prepared) { rtsp::Request& request = *owner->createRequest(rtsp::Method::TEARDOWN, mediaSession.uri, session); owner->sendRequest(request); } else { rtsp::Response response; prepareResponse( rtsp::StatusCode::BAD_GATEWAY, "Bad Gateway", describeRequestCSeq, session, &response); owner->sendResponse(response); } mediaSessions.erase(it); } ServerSession::ServerSession( const WebRTCConfigPtr& webRTCConfig, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : rtsp::Session(webRTCConfig, sendRequest, sendResponse), _p(new Private(this, createPeer)) { } ServerSession::ServerSession( const WebRTCConfigPtr& webRTCConfig, const CreatePeer& createPeer, const CreatePeer& createRecordPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept : rtsp::Session(webRTCConfig, sendRequest, sendResponse), _p(new Private(this, createPeer, createRecordPeer)) { } ServerSession::~ServerSession() { } bool ServerSession::onConnected(const std::optional<std::string>& authCookie) noexcept { _p->authCookie = authCookie; return rtsp::Session::onConnected(); } const std::optional<std::string>& ServerSession::authCookie() const noexcept { return _p->authCookie; } std::string ServerSession::nextSessionId() { return _p->nextSessionId(); } bool ServerSession::handleRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { if(requestPtr->method != rtsp::Method::RECORD && !authorize(requestPtr)) { Log()->error("[{}] {} authorize failed for \"{}\"", sessionLogId, rtsp::MethodName(requestPtr->method), requestPtr->uri); sendUnauthorizedResponse(requestPtr->cseq); return true; } if(isProxyRequest(*requestPtr)) { switch(requestPtr->method) { case rtsp::Method::DESCRIBE: case rtsp::Method::SETUP: case rtsp::Method::PLAY: case rtsp::Method::TEARDOWN: return handleProxyRequest(requestPtr); default: break; } } return Session::handleRequest(requestPtr); } bool ServerSession::onGetParameterRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const std::string& contentType = rtsp::RequestContentType(*requestPtr); if(contentType.empty() && requestPtr->body.empty()) { // PING/PONG case sendOkResponse(requestPtr->cseq); } else { sendBadRequestResponse(requestPtr->cseq); } return true; } bool ServerSession::onOptionsRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { rtsp::Response response; prepareOkResponse(requestPtr->cseq, rtsp::MediaSessionId(), &response); std::string options; if(listEnabled(requestPtr->uri)) options = "LIST"; const bool playEnabled = this->playEnabled(requestPtr->uri); if(playEnabled) { if(!options.empty()) options += ", "; options += "DESCRIBE, PLAY"; } const bool recordEnabled = this->recordEnabled(requestPtr->uri) && _p->recordEnabled(); if(recordEnabled) { if(!options.empty()) options += ", "; options += "RECORD"; } const bool subscribeEnabled = this->subscribeEnabled(requestPtr->uri); if(subscribeEnabled) { if(!options.empty()) options += ", "; options += "SUBSCRIBE"; } if(playEnabled || recordEnabled || subscribeEnabled) { options += ", SETUP, TEARDOWN"; } response.headerFields.emplace("Public", options); sendResponse(response); return true; } bool ServerSession::playEnabled(const std::string&) noexcept { return true; } bool ServerSession::onDescribeRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const rtsp::Request& request = *requestPtr.get(); if(!playEnabled(request.uri)) { Log()->error("[{}] Playback is not supported for \"{}\"", sessionLogId, requestPtr->uri); return false; } std::unique_ptr<WebRTCPeer> peerPtr = _p->createPeer(requestPtr->uri); if(!peerPtr) { Log()->error("[{}] Failed to create peer for \"{}\"", sessionLogId, requestPtr->uri); return false; } const rtsp::MediaSessionId session = nextSessionId(); auto emplacePair = _p->mediaSessions.emplace( session, std::make_unique<MediaSession>(MediaSession::Type::Describe, request.uri, request.cseq)); if(!emplacePair.second) return false; MediaSession& mediaSession = *(emplacePair.first->second); mediaSession.localPeer = std::move(peerPtr); mediaSession.localPeer->prepare( webRTCConfig(), std::bind( &ServerSession::Private::streamerPrepared, _p.get(), session), std::bind( &ServerSession::Private::iceCandidate, _p.get(), session, std::placeholders::_1, std::placeholders::_2), std::bind( &ServerSession::Private::eos, _p.get(), session)); return true; } bool ServerSession::recordEnabled(const std::string&) noexcept { return false; } bool ServerSession::subscribeEnabled(const std::string&) noexcept { return false; } bool ServerSession::authorize(const std::unique_ptr<rtsp::Request>& requestPtr) noexcept { return requestPtr->method != rtsp::Method::RECORD; } bool ServerSession::onRecordRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const rtsp::Request& request = *requestPtr.get(); if(!recordEnabled(requestPtr->uri) || !_p->recordEnabled()) return false; if(!authorize(requestPtr)) { Log()->error("[{}] RECORD authorize failed for \"{}\"", sessionLogId, requestPtr->uri); return false; } const std::string& sdp = request.body; if(sdp.empty()) return false; std::unique_ptr<WebRTCPeer> peerPtr = _p->createRecordPeer(requestPtr->uri); if(!peerPtr) return false; const std::string contentType = RequestContentType(*requestPtr); if(contentType != rtsp::SdpContentType) return false; const rtsp::MediaSessionId session = nextSessionId(); auto emplacePair = _p->mediaSessions.emplace( session, std::make_unique<MediaSession>(MediaSession::Type::Record, request.uri, request.cseq)); if(!emplacePair.second) return false; MediaSession& mediaSession = *(emplacePair.first->second); mediaSession.localPeer = std::move(peerPtr); WebRTCPeer& localPeer = *(mediaSession.localPeer); localPeer.prepare( webRTCConfig(), std::bind( &ServerSession::Private::recorderPrepared, _p.get(), session), std::bind( &ServerSession::Private::iceCandidate, _p.get(), session, std::placeholders::_1, std::placeholders::_2), std::bind( &ServerSession::Private::eos, _p.get(), session)); localPeer.setRemoteSdp(sdp); localPeer.play(); return true; } bool ServerSession::onSetupRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const rtsp::MediaSessionId session = RequestSession(*requestPtr); auto it = _p->mediaSessions.find(session); if(it == _p->mediaSessions.end()) return false; WebRTCPeer& localPeer = *it->second->localPeer; if(RequestContentType(*requestPtr) != rtsp::IceCandidateContentType) return false; const std::string& ice = requestPtr->body; std::string::size_type pos = 0; while(pos < ice.size()) { const std::string::size_type lineEndPos = ice.find("\r\n", pos); if(lineEndPos == std::string::npos) return false; const std::string line = ice.substr(pos, lineEndPos - pos); const std::string::size_type delimiterPos = line.find("/"); if(delimiterPos == std::string::npos || 0 == delimiterPos) return false; try{ const int idx = std::stoi(line.substr(0, delimiterPos)); if(idx < 0) return false; const std::string candidate = line.substr(delimiterPos + 1); if(candidate.empty()) return false; Log()->trace("[{}] Adding ice candidate \"{}\"", sessionLogId, candidate); localPeer.addIceCandidate(idx, candidate); } catch(...) { return false; } pos = lineEndPos + 2; } sendOkResponse(requestPtr->cseq, session); return true; } bool ServerSession::onPlayRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const rtsp::MediaSessionId session = RequestSession(*requestPtr); if(session.empty()) return false; auto it = _p->mediaSessions.find(session); if(it == _p->mediaSessions.end()) return false; MediaSession& mediaSession = *it->second; if(mediaSession.type != MediaSession::Type::Describe) return false; if(RequestContentType(*requestPtr) != rtsp::SdpContentType) return false; WebRTCPeer& localPeer = *(mediaSession.localPeer); localPeer.setRemoteSdp(requestPtr->body); localPeer.play(); sendOkResponse(requestPtr->cseq, session); return true; } bool ServerSession::onTeardownRequest( std::unique_ptr<rtsp::Request>& requestPtr) noexcept { const rtsp::MediaSessionId session = RequestSession(*requestPtr); auto it = _p->mediaSessions.find(session); if(it == _p->mediaSessions.end()) return false; WebRTCPeer& localPeer = *(it->second->localPeer); localPeer.stop(); sendOkResponse(requestPtr->cseq, session); _p->mediaSessions.erase(it); return true; } void ServerSession::startRecordToClient( const std::string& uri, const rtsp::MediaSessionId& mediaSessionId) noexcept { std::unique_ptr<WebRTCPeer> peerPtr = _p->createPeer(uri); if(!peerPtr) { onEos(); // FIXME! send TEARDOWN instead and remove Media Session return; } auto emplacePair = _p->mediaSessions.emplace( mediaSessionId, std::make_unique<MediaSession>(MediaSession::Type::Subscribe, uri, rtsp::CSeq())); if(!emplacePair.second) { onEos(); // FIXME! send TEARDOWN instead and remove Media Session return; } MediaSession& mediaSession = *(emplacePair.first->second); mediaSession.localPeer = std::move(peerPtr); mediaSession.localPeer->prepare( webRTCConfig(), std::bind( &ServerSession::Private::recordToClientStreamerPrepared, _p.get(), mediaSessionId), std::bind( &ServerSession::Private::iceCandidate, _p.get(), mediaSessionId, std::placeholders::_1, std::placeholders::_2), std::bind( &ServerSession::Private::eos, _p.get(), mediaSessionId)); } bool ServerSession::onRecordResponse(const rtsp::Request& request, const rtsp::Response& response) noexcept { if(rtsp::StatusCode::OK != response.statusCode) return false; const rtsp::MediaSessionId mediaSessionId = RequestSession(request); if(mediaSessionId.empty() || mediaSessionId != ResponseSession(response)) return false; auto it = _p->mediaSessions.find(mediaSessionId); if(it == _p->mediaSessions.end()) return false; MediaSession& mediaSession = *it->second; if(mediaSession.type != MediaSession::Type::Subscribe) return false; if(ResponseContentType(response) != rtsp::SdpContentType) return false; WebRTCPeer& localPeer = *(mediaSession.localPeer); localPeer.setRemoteSdp(response.body); localPeer.play(); return true; } void ServerSession::teardownMediaSession(const rtsp::MediaSessionId& mediaSession) noexcept { assert(!mediaSession.empty()); if(mediaSession.empty()) return; const bool erased = _p->mediaSessions.erase(mediaSession) != 0; assert(erased); }
19,065
C++
.cpp
552
27.911232
129
0.661019
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,248
WsServer.cpp
WebRTSP_WebRTSP/Signalling/WsServer.cpp
#include "WsServer.h" #include <deque> #include <algorithm> #include <optional> #include <CxxPtr/libwebsocketsPtr.h> #include "Helpers/MessageBuffer.h" #include "RtspParser/RtspParser.h" #include "RtspParser/RtspSerialize.h" #include "Log.h" namespace signalling { namespace { enum { RX_BUFFER_SIZE = 512, PING_INTERVAL = 2 * 60, INCOMING_MESSAGE_WAIT_INTERVAL = PING_INTERVAL + 30, }; enum { HTTP_PROTOCOL_ID, PROTOCOL_ID, }; const char* AuthCookieName = "WebRTSP-Auth"; struct SessionData { bool terminateSession = false; MessageBuffer incomingMessage; std::deque<MessageBuffer> sendMessages; std::unique_ptr<ServerSession> rtspSession; }; // Should contain only POD types, // since created inside libwebsockets on session create. struct SessionContextData { lws* wsi; SessionData* data; }; const auto Log = WsServerLog; void LogClientIp(lws* wsi, const std::string& sessionLogId) { char clientIp[INET6_ADDRSTRLEN]; lws_get_peer_simple(wsi, clientIp, sizeof(clientIp)); char xRealIp[INET6_ADDRSTRLEN]; const bool xRealIpPresent = lws_hdr_copy(wsi, xRealIp, sizeof(xRealIp), WSI_TOKEN_HTTP_X_REAL_IP) > 0; const int xForwardedForlength = lws_hdr_total_length(wsi, WSI_TOKEN_X_FORWARDED_FOR); if(xForwardedForlength > 0) { char xForwardedFor[xForwardedForlength + 1]; lws_hdr_copy(wsi, xForwardedFor, sizeof(xForwardedFor), WSI_TOKEN_X_FORWARDED_FOR); if(xRealIpPresent) { Log()->info( "[{}] New client connected. IP: {}, X-Real-IP: {}, X-Forwarded-For: {}", sessionLogId, clientIp, xRealIp, &xForwardedFor[0]); } else { Log()->info( "[{}] New client connected. IP: {}, X-Forwarded-For: {}", sessionLogId, clientIp, &xForwardedFor[0]); } } else if(xRealIpPresent) { Log()->info( "[{}] New client connected. IP: {}, X-Real-IP: {}", sessionLogId, clientIp, xRealIp); } else { Log()->info( "[{}] New client connected. IP: {}", sessionLogId, clientIp); } } } struct WsServer::Private { Private(WsServer*, const Config&, GMainLoop*, const WsServer::CreateSession&); bool init(lws_context* context); int httpCallback(lws*, lws_callback_reasons, void* user, void* in, size_t len); int wsCallback(lws*, lws_callback_reasons, void* user, void* in, size_t len); bool onMessage(SessionContextData*, const MessageBuffer&); void send(SessionContextData*, MessageBuffer*); void sendRequest(SessionContextData*, const rtsp::Request*); void sendResponse(SessionContextData*, const rtsp::Response*); WsServer *const owner; Config config; GMainLoop* loop; CreateSession createSession; LwsContextPtr contextPtr; }; WsServer::Private::Private( WsServer* owner, const Config& config, GMainLoop* loop, const WsServer::CreateSession& createSession) : owner(owner), config(config), loop(loop), createSession(createSession) { } int WsServer::Private::httpCallback( lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) { switch(reason) { default: return lws_callback_http_dummy(wsi, reason, user, in, len); } return 0; } int WsServer::Private::wsCallback( lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) { SessionContextData* scd = static_cast<SessionContextData*>(user); switch (reason) { case LWS_CALLBACK_PROTOCOL_INIT: break; case LWS_CALLBACK_ESTABLISHED: { std::unique_ptr<ServerSession> session = createSession( std::bind(&Private::sendRequest, this, scd, std::placeholders::_1), std::bind(&Private::sendResponse, this, scd, std::placeholders::_1)); if(!session) return -1; LogClientIp(wsi, session->sessionLogId); scd->data = new SessionData { .terminateSession = false, .incomingMessage ={}, .sendMessages = {}, .rtspSession = std::move(session)}; scd->wsi = wsi; std::optional<std::string> authCookie; char cookieBuf[256]; size_t cookieSize = sizeof(cookieBuf); if(0 == lws_http_cookie_get(wsi, AuthCookieName, cookieBuf, &cookieSize)) { authCookie = std::string(cookieBuf, cookieSize); } if(!scd->data->rtspSession->onConnected(authCookie)) return -1; break; } case LWS_CALLBACK_RECEIVE_PONG: Log()->trace("PONG"); break; case LWS_CALLBACK_RECEIVE: { if(scd->data->incomingMessage.onReceive(wsi, in, len)) { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(scd->data->incomingMessage.size()); std::remove_copy( scd->data->incomingMessage.data(), scd->data->incomingMessage.data() + scd->data->incomingMessage.size(), std::back_inserter(logMessage), '\r'); Log()->trace( "[{}] -> WsServer: {}", scd->data->rtspSession->sessionLogId, logMessage); } if(!onMessage(scd, scd->data->incomingMessage)) return -1; scd->data->incomingMessage.clear(); } break; } case LWS_CALLBACK_SERVER_WRITEABLE: { if(scd->data->terminateSession) return -1; if(!scd->data->sendMessages.empty()) { MessageBuffer& buffer = scd->data->sendMessages.front(); if(!buffer.writeAsText(wsi)) { Log()->error( "[{}] write failed.", scd->data->rtspSession->sessionLogId); return -1; } scd->data->sendMessages.pop_front(); if(!scd->data->sendMessages.empty()) lws_callback_on_writable(wsi); } break; } case LWS_CALLBACK_CLOSED: { delete scd->data; scd->data = nullptr; scd->wsi = nullptr; break; } default: break; } return 0; } bool WsServer::Private::init(lws_context* context) { auto HttpCallback = [] (lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) -> int { lws_vhost* vhost = lws_get_vhost(wsi); Private* p = static_cast<Private*>(lws_get_vhost_user(vhost)); return p->httpCallback(wsi, reason, user, in, len); }; auto WsCallback = [] (lws* wsi, lws_callback_reasons reason, void* user, void* in, size_t len) -> int { lws_vhost* vhost = lws_get_vhost(wsi); Private* p = static_cast<Private*>(lws_get_vhost_user(vhost)); return p->wsCallback(wsi, reason, user, in, len); }; const lws_protocols protocols[] = { { "http", HttpCallback, 0, 0, HTTP_PROTOCOL_ID }, { "webrtsp", WsCallback, sizeof(SessionContextData), RX_BUFFER_SIZE, PROTOCOL_ID, nullptr }, { nullptr, nullptr, 0, 0 } }; if(!context) { lws_context_creation_info wsInfo {}; wsInfo.gid = -1; wsInfo.uid = -1; #if LWS_LIBRARY_VERSION_NUMBER < 4000000 wsInfo.ws_ping_pong_interval = PING_INTERVAL; #else lws_retry_bo_t retryPolicy {}; retryPolicy.secs_since_valid_ping = PING_INTERVAL; retryPolicy.secs_since_valid_hangup = INCOMING_MESSAGE_WAIT_INTERVAL; wsInfo.retry_and_idle_policy = &retryPolicy; #endif wsInfo.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS; wsInfo.options |= LWS_SERVER_OPTION_GLIB; wsInfo.foreign_loops = reinterpret_cast<void**>(&loop); contextPtr.reset(lws_create_context(&wsInfo)); context = contextPtr.get(); } if(!context) return false; if(config.port != 0) { Log()->info("Starting WS server on port {}", config.port); lws_context_creation_info vhostInfo {}; vhostInfo.port = config.port; vhostInfo.protocols = protocols; vhostInfo.user = this; if(config.bindToLoopbackOnly) vhostInfo.iface = "lo"; lws_vhost* vhost = lws_create_vhost(context, &vhostInfo); if(!vhost) return false; } return true; } bool WsServer::Private::onMessage( SessionContextData* scd, const MessageBuffer& message) { if(rtsp::IsRequest(message.data(), message.size())) { std::unique_ptr<rtsp::Request> requestPtr = std::make_unique<rtsp::Request>(); if(!rtsp::ParseRequest(message.data(), message.size(), requestPtr.get())) { Log()->error( "[{}] Fail parse request:\n{}\nForcing session disconnect...", scd->data->rtspSession->sessionLogId, std::string(message.data(), message.size())); return false; } switch(requestPtr->method) { case rtsp::Method::NONE: case rtsp::Method::OPTIONS: case rtsp::Method::LIST: case rtsp::Method::SETUP: case rtsp::Method::GET_PARAMETER: case rtsp::Method::SET_PARAMETER: break; case rtsp::Method::DESCRIBE: case rtsp::Method::PLAY: case rtsp::Method::RECORD: case rtsp::Method::SUBSCRIBE: case rtsp::Method::TEARDOWN: Log()->info( "[{}] Got {} request for \"{}\"", scd->data->rtspSession->sessionLogId, rtsp::MethodName(requestPtr->method), requestPtr->uri); break; } if(!scd->data->rtspSession->handleRequest(requestPtr)) { Log()->debug( "[{}] Fail handle request:\n{}\nForcing session disconnect...", scd->data->rtspSession->sessionLogId, std::string(message.data(), message.size())); return false; } } else { std::unique_ptr<rtsp::Response> responsePtr = std::make_unique<rtsp::Response>(); if(!rtsp::ParseResponse(message.data(), message.size(), responsePtr.get())) { Log()->error( "[{}] Fail parse response:\n{}\nForcing session disconnect...", scd->data->rtspSession->sessionLogId, std::string(message.data(), message.size())); return false; } if(!scd->data->rtspSession->handleResponse(responsePtr)) { Log()->error( "[{}] Fail handle response:\n{}\nForcing session disconnect...", scd->data->rtspSession->sessionLogId, std::string(message.data(), message.size())); return false; } } return true; } void WsServer::Private::send(SessionContextData* scd, MessageBuffer* message) { scd->data->sendMessages.emplace_back(std::move(*message)); lws_callback_on_writable(scd->wsi); } void WsServer::Private::sendRequest( SessionContextData* scd, const rtsp::Request* request) { if(!request) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); return; } const std::string serializedRequest = rtsp::Serialize(*request); if(serializedRequest.empty()) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); } else { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(serializedRequest.size()); std::remove_copy( serializedRequest.begin(), serializedRequest.end(), std::back_inserter(logMessage), '\r'); Log()->trace( "[{}] WsServer -> : {}", scd->data->rtspSession->sessionLogId, logMessage); } MessageBuffer requestMessage; requestMessage.assign(serializedRequest); send(scd, &requestMessage); } } void WsServer::Private::sendResponse( SessionContextData* scd, const rtsp::Response* response) { if(!response) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); return; } const std::string serializedResponse = rtsp::Serialize(*response); if(serializedResponse.empty()) { scd->data->terminateSession = true; lws_callback_on_writable(scd->wsi); } else { if(Log()->level() <= spdlog::level::trace) { std::string logMessage; logMessage.reserve(serializedResponse.size()); std::remove_copy( serializedResponse.begin(), serializedResponse.end(), std::back_inserter(logMessage), '\r'); Log()->trace( "[{}] WsServer -> : {}", scd->data->rtspSession->sessionLogId, logMessage); } MessageBuffer responseMessage; responseMessage.assign(serializedResponse); send(scd, &responseMessage); } } WsServer::WsServer( const Config& config, GMainLoop* loop, const CreateSession& createSession) noexcept : _p(std::make_unique<Private>(this, config, loop, createSession)) { } WsServer::~WsServer() { } bool WsServer::init(lws_context* context /*= nullptr*/) noexcept { return _p->init(context); } }
14,124
C++
.cpp
397
26.010076
94
0.571439
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,249
Config.h
WebRTSP_WebRTSP/Http/Config.h
#pragma once #include <string> #include <map> namespace http { enum { DEFAULT_HTTP_PORT = 5080, DEFAULT_HTTPS_PORT = 5443, }; struct Config { bool bindToLoopbackOnly = true; unsigned short port = DEFAULT_HTTP_PORT; std::string wwwRoot = "./www"; std::map<std::string, std::string> passwd; std::string realm = "WebRTSP"; std::string opaque = "WebRTSP"; std::map<std::string, bool> indexPaths; // path -> if auth required for path }; }
479
C++
.h
19
21.842105
80
0.676275
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,250
HttpMicroServer.h
WebRTSP_WebRTSP/Http/HttpMicroServer.h
#pragma once #include <string> #include <memory> #include <functional> #include <chrono> #include <glib.h> #include "Config.h" namespace http { class MicroServer { public: struct AuthCookieData { std::chrono::steady_clock::time_point expiresAt; // FIXME! add allowed IP }; typedef std::function<void (const std::string& token, std::chrono::steady_clock::time_point expiresAt)> OnNewAuthToken; MicroServer( const Config&, const std::string& configJs, const OnNewAuthToken&, GMainContext* context) noexcept; bool init() noexcept; ~MicroServer(); private: struct Private; std::unique_ptr<Private> _p; }; }
692
C++
.h
28
20.535714
123
0.690076
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,251
Log.h
WebRTSP_WebRTSP/Http/Log.h
#pragma once #include <memory> #include <spdlog/spdlog.h> void InitHttpServerLogger(spdlog::level::level_enum level); const std::shared_ptr<spdlog::logger>& HttpServerLog();
178
C++
.h
5
33.8
59
0.792899
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,252
ClientSession.h
WebRTSP_WebRTSP/Client/ClientSession.h
#pragma once #include "RtStreaming/WebRTCPeer.h" #include "RtspSession/ClientSession.h" class ClientSession : public rtsp::ClientSession { public: typedef std::function<std::unique_ptr<WebRTCPeer> ()> CreatePeer; ClientSession( const std::string& uri, const WebRTCConfigPtr&, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; ClientSession( const WebRTCConfigPtr&, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; ~ClientSession(); bool onConnected() noexcept override; protected: void setUri(const std::string&); rtsp::CSeq requestDescribe() noexcept; bool onOptionsResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onDescribeResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onSetupResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onPlayResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onTeardownResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onSetupRequest(std::unique_ptr<rtsp::Request>&) noexcept override; private: struct Private; std::unique_ptr<Private> _p; };
1,413
C++
.h
38
31.421053
75
0.718155
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,253
Config.h
WebRTSP_WebRTSP/Client/Config.h
#pragma once #include <string> namespace client { struct Config { std::string server; unsigned short serverPort; bool useTls = true; }; }
155
C++
.h
10
12.8
30
0.728571
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,254
Log.h
WebRTSP_WebRTSP/Client/Log.h
#pragma once #include <memory> #include <spdlog/spdlog.h> void InitWsClientLogger(spdlog::level::level_enum level); const std::shared_ptr<spdlog::logger>& WsClientLog(); void InitClientSessionLogger(spdlog::level::level_enum level); const std::shared_ptr<spdlog::logger>& ClientSessionLog();
297
C++
.h
7
40.714286
62
0.796491
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,255
ClientRecordSession.h
WebRTSP_WebRTSP/Client/ClientRecordSession.h
#pragma once #include "RtStreaming/WebRTCPeer.h" #include "RtspSession/ClientSession.h" class ClientRecordSession : public rtsp::ClientSession { public: typedef std::function<std::unique_ptr<WebRTCPeer> (const std::string& uri)> CreatePeer; ClientRecordSession( const std::string& targetUri, const std::string& recordToken, const WebRTCConfigPtr&, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; ~ClientRecordSession(); bool onConnected() noexcept override; bool isStreaming() const noexcept; void startRecord(const std::string& sourceUri) noexcept; void stopRecord() noexcept; protected: bool onSetupResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onRecordResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onTeardownResponse( const rtsp::Request&, const rtsp::Response&) noexcept override; bool onSetupRequest(std::unique_ptr<rtsp::Request>&) noexcept override; private: struct Private; std::unique_ptr<Private> _p; };
1,171
C++
.h
31
32.483871
91
0.731211
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,256
WsClient.h
WebRTSP_WebRTSP/Client/WsClient.h
#pragma once #include <string> #include <memory> #include <functional> #include <glib.h> #include "RtspSession/Session.h" #include "Config.h" namespace client { class WsClient { public: typedef std::function< std::unique_ptr<rtsp::Session> ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse)> CreateSession; typedef std::function<void (WsClient&)> Disconnected; WsClient( const Config&, GMainLoop*, const CreateSession&, const Disconnected&) noexcept; bool init() noexcept; ~WsClient(); void connect() noexcept; private: struct Private; std::unique_ptr<Private> _p; }; }
725
C++
.h
29
20.275862
76
0.682749
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,257
StatusCode.h
WebRTSP_WebRTSP/RtspSession/StatusCode.h
#pragma once namespace rtsp { enum StatusCode { OK = 200, BAD_REQUEST = 400, UNAUTHORIZED = 401, FORBIDDEN = 403, BAD_GATEWAY = 502, }; }
162
C++
.h
10
12.8
23
0.641892
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,258
Session.h
WebRTSP_WebRTSP/RtspSession/Session.h
#pragma once #include <memory> #include <functional> #include <map> #include <deque> #include "RtspParser/Request.h" #include "RtspParser/Response.h" #include "StatusCode.h" #include "RtStreaming/WebRTCConfig.h" namespace rtsp { struct Session { typedef std::deque<std::string> IceServers; typedef std::function<void (const Request*)> SendRequest; typedef std::function<void (const Response*)> SendResponse; virtual ~Session(); virtual const WebRTCConfigPtr& webRTCConfig() const { return _webRTCConfig; } virtual bool onConnected() noexcept { return true; } virtual bool handleRequest(std::unique_ptr<Request>&) noexcept; bool handleResponse(std::unique_ptr<Response>& responsePtr) noexcept; const std::string sessionLogId; protected: Session( const WebRTCConfigPtr&, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; Request* createRequest( Method, const std::string& uri) noexcept; Request* createRequest( Method, const std::string& uri, const std::string& session) noexcept; Request* attachRequest( const std::unique_ptr<rtsp::Request>& requestPtr) noexcept; static Response* prepareResponse( StatusCode statusCode, const std::string::value_type* reasonPhrase, CSeq cseq, const MediaSessionId& session, Response* out); static Response* prepareOkResponse( CSeq cseq, const MediaSessionId& session, Response* out); static Response* prepareOkResponse( CSeq cseq, Response* out); void sendOkResponse(CSeq); void sendOkResponse(CSeq, const MediaSessionId&); void sendOkResponse( CSeq, const std::string& contentType, const std::string& body); void sendOkResponse( CSeq, const MediaSessionId&, const std::string& contentType, const std::string& body); void sendUnauthorizedResponse(CSeq); void sendForbiddenResponse(CSeq); void sendBadRequestResponse(CSeq); void sendRequest(const Request&) noexcept; void sendResponse(const Response&) noexcept; void disconnect() noexcept; CSeq requestList(const std::string& uri = "*") noexcept; CSeq sendList( const std::string& uri, const std::string& list, const std::optional<std::string>& token = {}) noexcept; CSeq requestSetup( const std::string& uri, const std::string& contentType, const MediaSessionId& session, const std::string& body) noexcept; CSeq requestGetParameter( const std::string& uri, const std::string& contentType, const std::string& body, const std::optional<std::string>& token = {}) noexcept; CSeq requestSetParameter( const std::string& uri, const std::string& contentType, const std::string& body, const std::optional<std::string>& token = {}) noexcept; virtual bool onOptionsRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onListRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onDescribeRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onSetupRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onPlayRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onSubscribeRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onRecordRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onTeardownRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onGetParameterRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool onSetParameterRequest(std::unique_ptr<Request>&) noexcept { return false; } virtual bool handleResponse( const Request&, std::unique_ptr<Response>&) noexcept; virtual bool onOptionsResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onListResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onDescribeResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onSetupResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onPlayResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onSubscribeResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onRecordResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onTeardownResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onGetParameterResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual bool onSetParameterResponse(const Request& request, const Response& response) noexcept { return StatusCode::OK == response.statusCode; } virtual void onEos() noexcept; private: const WebRTCConfigPtr _webRTCConfig; const SendRequest _sendRequest; const SendResponse _sendResponse; CSeq _nextCSeq = 1; std::map<CSeq, Request> _sentRequests; }; }
5,844
C++
.h
137
36.094891
98
0.701989
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,259
ClientSession.h
WebRTSP_WebRTSP/RtspSession/ClientSession.h
#pragma once #include <functional> #include <set> #include "RtspParser/Request.h" #include "RtspParser/Response.h" #include "Session.h" namespace rtsp { struct ClientSession : public Session { bool isSupported(Method); protected: using Session::Session; virtual bool playSupportRequired(const std::string& /*uri*/) noexcept { return true; } virtual bool recordSupportRequired(const std::string& /*uri*/) noexcept { return false; } CSeq requestOptions(const std::string& uri) noexcept; CSeq requestDescribe(const std::string& uri) noexcept; CSeq requestRecord( const std::string& uri, const std::string& sdp, const std::optional<std::string>& token = {}) noexcept; CSeq requestPlay( const std::string& uri, const MediaSessionId& session, const std::string& sdp) noexcept; CSeq requestTeardown(const std::string& uri, const MediaSessionId&) noexcept; virtual bool onOptionsResponse( const Request&, const Response&) noexcept; private: std::set<Method> _supportedMethods; }; }
1,086
C++
.h
31
30.419355
93
0.717162
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,260
IceCandidate.h
WebRTSP_WebRTSP/RtspSession/IceCandidate.h
#pragma once #include <string> namespace rtsp { struct IceCandidate { unsigned mlineIndex; std::string candidate; }; }
132
C++
.h
8
13.875
26
0.756303
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,261
RtspSerialize.h
WebRTSP_WebRTSP/RtspParser/RtspSerialize.h
#pragma once #include "Request.h" #include "Response.h" namespace rtsp { void Serialize(const Parameters&, std::string* out) noexcept; void Serialize(const Request&, std::string* out) noexcept; std::string Serialize(const Request&) noexcept; void Serialize(const Response&, std::string* out) noexcept; std::string Serialize(const Response&) noexcept; }
360
C++
.h
10
34.3
61
0.787172
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,262
Methods.h
WebRTSP_WebRTSP/RtspParser/Methods.h
#pragma once #include <cstddef> #include "Token.h" namespace rtsp { enum class Method { NONE, OPTIONS, LIST, DESCRIBE, SETUP, PLAY, SUBSCRIBE, RECORD, // PAUSE, TEARDOWN, GET_PARAMETER, SET_PARAMETER, // REDIRECT, }; const char* MethodName(Method) noexcept; Method ParseMethod(const Token&) noexcept; }
362
C++
.h
22
12.954545
42
0.675676
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,263
Protocols.h
WebRTSP_WebRTSP/RtspParser/Protocols.h
#pragma once #include <cstddef> #include "Token.h" namespace rtsp { enum class Protocol { NONE, WEBRTSP_0_2, }; const char* ProtocolName(Protocol) noexcept; Protocol ParseProtocol(const Token& token) noexcept; }
227
C++
.h
11
18.272727
52
0.770335
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,264
Response.h
WebRTSP_WebRTSP/RtspParser/Response.h
#pragma once #include <string> #include <map> #include "Common.h" #include "Methods.h" #include "Protocols.h" #include "LessNoCase.h" namespace rtsp { struct Response { Protocol protocol; unsigned statusCode; std::string reasonPhrase; CSeq cseq; std::map<std::string, std::string, LessNoCase> headerFields; std::string body; }; MediaSessionId ResponseSession(const Response&); void SetResponseSession(Response*, const MediaSessionId&); std::string ResponseContentType(const Response&); void SetContentType(Response*, const std::string&); }
572
C++
.h
21
24.714286
64
0.769797
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,265
Request.h
WebRTSP_WebRTSP/RtspParser/Request.h
#pragma once #include <string> #include <map> #include "Common.h" #include "Methods.h" #include "Protocols.h" #include "LessNoCase.h" namespace rtsp { struct Request { Method method; std::string uri; Protocol protocol = Protocol::WEBRTSP_0_2; CSeq cseq; std::map<std::string, std::string, LessNoCase> headerFields; std::string body; }; MediaSessionId RequestSession(const Request& request); void SetRequestSession(Request*, const MediaSessionId&); std::string RequestContentType(const Request& request); void SetContentType(Request*, const std::string&); void SetBearerAuthorization(Request*, const std::string& token); }
654
C++
.h
22
27.272727
64
0.766026
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,266
Common.h
WebRTSP_WebRTSP/RtspParser/Common.h
#pragma once #include <string> #include <set> #include <map> namespace rtsp { typedef unsigned CSeq; typedef std::string MediaSessionId; typedef std::map<std::string, std::string> Parameters; typedef std::set<std::string> ParametersNames; const char UriSeparator = '/'; const char *const WildcardUri = "*"; const char *const ContentTypeFieldName = "Content-Type"; const char *const TextListContentType = "text/list"; const char *const TextParametersContentType = "text/parameters"; const char *const SdpContentType = "application/sdp"; const char *const IceCandidateContentType = "application/x-ice-candidate"; }
621
C++
.h
17
35.058824
74
0.790268
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,267
Authentication.h
WebRTSP_WebRTSP/RtspParser/Authentication.h
#pragma once #include "Token.h" namespace rtsp { enum class Authentication { None, Unknown, Bearer }; const char* AuthenticationName(Authentication) noexcept; Authentication ParseAuthentication(const Token&) noexcept; }
237
C++
.h
12
17.333333
58
0.8
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,268
Token.h
WebRTSP_WebRTSP/RtspParser/Token.h
#pragma once #include <cstddef> namespace rtsp { struct Token { const char* token = nullptr; size_t size = 0; }; bool IsEmptyToken(const Token& token) noexcept; }
178
C++
.h
10
15.3
47
0.732919
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,269
RtspParser.h
WebRTSP_WebRTSP/RtspParser/RtspParser.h
#pragma once #include "Common.h" #include "Request.h" #include "Response.h" #include "Authentication.h" namespace rtsp { bool ParseCSeq(const std::string&, CSeq* out) noexcept; bool ParseRequest(const char*, size_t, Request*) noexcept; bool ParseResponse(const char*, size_t, Response*) noexcept; bool IsRequest(const char*, size_t) noexcept; bool ParseParameters( const std::string& body, Parameters*) noexcept; bool ParseParametersNames( const std::string& body, ParametersNames*) noexcept; std::set<rtsp::Method> ParseOptions(const Response&); std::pair<Authentication, std::string> ParseAuthentication(const Request&); std::pair<std::string, std::string> SplitUri(const std::string& uri); }
723
C++
.h
20
33.75
75
0.768452
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,270
LessNoCase.h
WebRTSP_WebRTSP/RtspParser/LessNoCase.h
#pragma once #include <string> #include <algorithm> namespace rtsp { struct LessNoCase { bool operator()(const std::string& l, const std::string& r) const { return std::lexicographical_compare( l.begin(), l.end(), r.begin(), r.end(), [] (std::string::value_type l, std::string::value_type r) { return std::tolower(l) < std::tolower(r); }); } }; }
464
C++
.h
17
19.411765
75
0.524887
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,271
WsServer.h
WebRTSP_WebRTSP/Signalling/WsServer.h
#pragma once #include <string> #include <memory> #include <functional> #include <glib.h> #include "Config.h" #include "ServerSession.h" struct lws_context; namespace signalling { class WsServer { public: typedef std::function< std::unique_ptr<ServerSession> ( const rtsp::Session::SendRequest& sendRequest, const rtsp::Session::SendResponse& sendResponse)> CreateSession; WsServer(const Config&, GMainLoop*, const CreateSession&) noexcept; bool init(lws_context* = nullptr) noexcept; ~WsServer(); private: struct Private; std::unique_ptr<Private> _p; }; }
622
C++
.h
24
22.166667
76
0.719388
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,272
Config.h
WebRTSP_WebRTSP/Signalling/Config.h
#pragma once #include <string> namespace signalling { enum { DEFAULT_WS_PORT = 5554, DEFAULT_WSS_PORT = 5555, }; struct Config { bool bindToLoopbackOnly = true; unsigned short port = DEFAULT_WS_PORT; }; }
227
C++
.h
13
14.769231
42
0.716346
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,273
ServerSession.h
WebRTSP_WebRTSP/Signalling/ServerSession.h
#pragma once #include <optional> #include "RtStreaming/WebRTCPeer.h" #include "RtspSession/Session.h" class ServerSession: public rtsp::Session { public: typedef std::function<std::unique_ptr<WebRTCPeer> (const std::string& uri)> CreatePeer; ServerSession( const WebRTCConfigPtr&, const CreatePeer& createPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; ServerSession( const WebRTCConfigPtr&, const CreatePeer& createPeer, const CreatePeer& createRecordPeer, const SendRequest& sendRequest, const SendResponse& sendResponse) noexcept; ~ServerSession(); virtual bool onConnected(const std::optional<std::string>& authCookie) noexcept; bool handleRequest(std::unique_ptr<rtsp::Request>&) noexcept override; void startRecordToClient(const std::string& uri, const rtsp::MediaSessionId&) noexcept; protected: const std::optional<std::string>& authCookie() const noexcept; std::string nextSessionId(); virtual bool listEnabled(const std::string& /*uri*/) noexcept { return false; } virtual bool playEnabled(const std::string& uri) noexcept; virtual bool recordEnabled(const std::string& uri) noexcept; virtual bool subscribeEnabled(const std::string& uri) noexcept; virtual bool authorize(const std::unique_ptr<rtsp::Request>&) noexcept; bool onGetParameterRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onOptionsRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onDescribeRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onSetupRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onPlayRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onRecordRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onTeardownRequest(std::unique_ptr<rtsp::Request>&) noexcept override; bool onRecordResponse(const rtsp::Request& request, const rtsp::Response& response) noexcept override; virtual bool isProxyRequest(const rtsp::Request&) noexcept { return false; } virtual bool handleProxyRequest(std::unique_ptr<rtsp::Request>&) noexcept { return false; } virtual void teardownMediaSession(const rtsp::MediaSessionId&) noexcept; private: struct Private; std::unique_ptr<Private> _p; };
2,381
C++
.h
46
46.521739
106
0.75
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,274
Log.h
WebRTSP_WebRTSP/Signalling/Log.h
#pragma once #include <memory> #include <spdlog/spdlog.h> void InitWsServerLogger(spdlog::level::level_enum level); const std::shared_ptr<spdlog::logger>& WsServerLog(); void InitServerSessionLogger(spdlog::level::level_enum level); const std::shared_ptr<spdlog::logger>& ServerSessionLog();
297
C++
.h
7
40.714286
62
0.796491
WebRTSP/WebRTSP
35
6
0
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,277
Arduino_LSM9DS1.h
arduino-libraries_Arduino_LSM9DS1/src/Arduino_LSM9DS1.h
/* This file is part of the Arduino_LSM9DS1 library. Copyright (c) 2019 Arduino SA. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _LSM9DS1_H_ #define _LSM9DS1_H_ #include "LSM9DS1.h" #endif
910
C++
.h
19
45.210526
80
0.779661
arduino-libraries/Arduino_LSM9DS1
34
51
5
LGPL-2.1
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,278
MouseController.cpp
Hypercall_MouseController/MouseController/MouseController.cpp
#include "MouseController.hpp" namespace MouseController { BYTE NtUserSendInput_Bytes[30]; BYTE NtUserGetAsyncKeyState_Bytes[30]; // Call this once in DllMain or main BOOLEAN WINAPI Init() { // windows 8.1 / windows 10 LPVOID NtUserSendInput_Addr = GetProcAddress(GetModuleHandle("win32u"), "NtUserSendInput"); if (!NtUserSendInput_Addr) { NtUserSendInput_Addr = GetProcAddress(GetModuleHandle("user32"), "NtUserSendInput"); if (!NtUserSendInput_Addr) { // Windows 7 or lower detected NtUserSendInput_Addr = GetProcAddress(GetModuleHandle("user32"), "SendInput"); if (!NtUserSendInput_Addr) return FALSE; } } // windows 8.1 / windows 10 LPVOID NtUserGetAsyncKeyState_Addr = GetProcAddress(GetModuleHandle("win32u"), "NtUserGetAsyncKeyState"); if (!NtUserGetAsyncKeyState_Addr) { NtUserGetAsyncKeyState_Addr = GetProcAddress(GetModuleHandle("user32"), "NtUserGetAsyncKeyState"); if (!NtUserGetAsyncKeyState_Addr) { // Windows 7 or lower detected NtUserGetAsyncKeyState_Addr = GetProcAddress(GetModuleHandle("user32"), "GetAsyncKeyState"); if (!NtUserGetAsyncKeyState_Addr) return FALSE; } } memcpy(NtUserSendInput_Bytes, NtUserSendInput_Addr, 30); memcpy(NtUserGetAsyncKeyState_Bytes, NtUserGetAsyncKeyState_Addr, 30); return TRUE; } // Call this when you leave application or don't need it anymore BOOLEAN WINAPI Uninit() { ZeroMemory(NtUserSendInput_Bytes, 30); ZeroMemory(NtUserGetAsyncKeyState_Spoof, 30); return TRUE; } /* This function spoofs the function. It prevents BattlEye from scanning it! */ BOOLEAN WINAPI NtUserSendInput(UINT cInputs, LPINPUT pInputs, int cbSize) { LPVOID NtUserSendInput_Spoof = VirtualAlloc(0, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // allocate space for syscall if (!NtUserSendInput_Spoof) return FALSE; memcpy(NtUserSendInput_Spoof, NtUserSendInput_Bytes, 30); // copy syscall NTSTATUS Result = reinterpret_cast<NTSTATUS(NTAPI*)(UINT, LPINPUT, int)>(NtUserSendInput_Spoof)(cInputs, pInputs, cbSize); // calling spoofed function ZeroMemory(NtUserSendInput_Spoof, 0x1000); // clean address VirtualFree(NtUserSendInput_Spoof, 0, MEM_RELEASE); // free it return (Result > 0); // return the status } /* This function spoofs the function. It prevents BattlEye from scanning it! */ UINT WINAPI NtUserGetAsyncKeyState(UINT Key) { LPVOID NtUserGetAsyncKeyState_Spoof = VirtualAlloc(0, 0x1000, MEM_COMMIT, PAGE_EXECUTE_READWRITE); // allocate space for syscall if (!NtUserGetAsyncKeyState_Spoof) return FALSE; memcpy(NtUserGetAsyncKeyState_Spoof, NtUserGetAsyncKeyState_Bytes, 30); // copy syscall NTSTATUS Result = reinterpret_cast<NTSTATUS(NTAPI*)(UINT)>(NtUserGetAsyncKeyState_Spoof)(Key); // calling spoofed function ZeroMemory(NtUserGetAsyncKeyState_Spoof, 0x1000); // clean address VirtualFree(NtUserGetAsyncKeyState_Spoof, 0, MEM_RELEASE); // free it return Result; // return the status } /* This function moves the mouse using the syscall */ BOOLEAN WINAPI Move_Mouse(int X, int Y) { INPUT input; input.type = INPUT_MOUSE; input.mi.mouseData = 0; input.mi.time = 0; input.mi.dx = X * (65536 / GetSystemMetrics(SM_CXSCREEN)); input.mi.dy = Y * (65536 / GetSystemMetrics(SM_CYSCREEN)); input.mi.dwFlags = MOUSEEVENTF_MOVE | MOUSEEVENTF_VIRTUALDESK | MOUSEEVENTF_ABSOLUTE; return NtUserSendInput(1, &input, sizeof(input)); } /* This function gets key state using the syscall*/ UINT WINAPI GetAsyncKeyState(UINT Key) { return NtUserGetAsyncKeyState(Key); } }
3,665
C++
.cpp
87
38.011494
153
0.745087
Hypercall/MouseController
34
10
0
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,279
Main.cpp
Hypercall_MouseController/MouseController/Main.cpp
#include "MouseController.h" #include <iostream> int main() { if(MouseController::Init()) std::cout << "MouseController is ready! Press F12 to test the Move_Mouse function" << std::endl; else std::cout << "MouseController failed to start!" << std::endl; while (true) { if (MouseController::GetAsyncKeyState(VK_F12)) { std::cout << "Key pressed" << std::endl; if (MouseController::Move_Mouse(500, 500)) std::cout << "Mouse moved to X : 500, Y : 500" << std::endl; } } MouseController::Uninit(); std::cin.get(); return 1; }
573
C++
.cpp
21
23.857143
99
0.647273
Hypercall/MouseController
34
10
0
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,280
MouseController.h
Hypercall_MouseController/MouseController/MouseController.h
#pragma once #include <windows.h> namespace MouseController { BOOLEAN WINAPI Init(); BOOLEAN WINAPI Uninit(); BOOLEAN WINAPI NtUserSendInput(UINT cInputs, LPINPUT pInputs, int cbSize); UINT WINAPI NtUserGetAsyncKeyState(UINT Key); BOOLEAN WINAPI Move_Mouse(int X, int Y); UINT WINAPI GetAsyncKeyState(UINT Key); }
341
C++
.h
11
27.545455
76
0.778125
Hypercall/MouseController
34
10
0
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,284
canorus.cpp
canorusmusic_canorus/src/canorus.cpp
/*! Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ // Python.h needs to be loaded first! #include "scripting/swigpython.h" #include <QCoreApplication> #include <QDebug> #include <QDir> #include <QFileInfo> #include <QFontDatabase> #include <QLocale> #include <QMetaMethod> #include <QTextCodec> #include <QTranslator> #include "canorus.h" #include "control/helpctl.h" #include "core/settings.h" #include "core/undo.h" #include "interface/rtmididevice.h" #include "score/sheet.h" #include "scripting/swigruby.h" #include "ui/settingsdialog.h" // define private static members QList<CAMainWin*> CACanorus::_mainWinList; CASettings* CACanorus::_settings; CAAutoRecovery* CACanorus::_autoRecovery; CAMidiDevice* CACanorus::_midiDevice; CAUndo* CACanorus::_undo; CAHelpCtl* CACanorus::_help; QList<QString> CACanorus::_recentDocumentList; QHash<QString, int> CACanorus::_fetaMap; std::unique_ptr<QTranslator> CACanorus::_translator; /*! Add all search paths. The search order is the following: - TODO passed path as an argument to exe - TODO path in user's config file - current dir - exe dir - DEFAULT_DATA_DIR set by compiler */ void CACanorus::initSearchPaths() { QStringList categories, paths; categories << "images" << "fonts" << "plugins" << "scripts" << "doc" << "lang" << "base"; for (QString cat: categories) { // The "base" prefix is used by CASwigPython and CASwigRuby to find files which are not in a subdir. QString dirname = (cat == "base") ? "" : cat; // When debugging, current directory may be used for resources. if (QDir(QDir::currentPath() + "/" + dirname).exists()) { QDir::addSearchPath(cat, QDir::currentPath() + "/" + dirname); } // Expected paths when running from canorus source. if (cat == "images" && QDir(qApp->applicationDirPath() + "/../../src/ui/images/").exists()) { QDir::addSearchPath(cat, qApp->applicationDirPath() + "/../../src/ui/images/"); } if (cat == "fonts" && QDir(qApp->applicationDirPath() + "/../../src/fonts/").exists()) { QDir::addSearchPath(cat, qApp->applicationDirPath() + "/../../src/fonts/"); } if (cat == "scripts" && QDir(qApp->applicationDirPath() + "/../../src/scripts/").exists()) { QDir::addSearchPath(cat, qApp->applicationDirPath() + "/../../src/scripts/"); } if (cat == "doc" && QDir(qApp->applicationDirPath()).exists("/../../doc/")) { QDir::addSearchPath(cat, qApp->applicationDirPath() + "/../../doc"); } // Expected paths when running from installation directory. if (QDir(qApp->applicationDirPath() + "/" + dirname).exists()) { QDir::addSearchPath(cat, qApp->applicationDirPath() + "/" + dirname); } #ifdef DEFAULT_DATA_DIR if (QDir(DEFAULT_DATA_DIR + ("/" + dirname)).exists()) { QDir::addSearchPath(cat, DEFAULT_DATA_DIR + ("/" + dirname)); } #endif } } /*! Initializes application properties like application name, home page etc. */ void CACanorus::initMain(int, char* []) { _autoRecovery = nullptr; // Init main application properties QCoreApplication::setOrganizationName("Canorus"); QCoreApplication::setOrganizationDomain("canorus.org"); QCoreApplication::setApplicationName("Canorus"); } /*! Initializes language specific settings like the translation file for the GUI, text flow (left-to-right or right-to-left), default string encoding etc. */ void CACanorus::initTranslations() { QString translationFile = "lang:" + QLocale::system().name() + ".qm"; // load language_COUNTRY.qm if (!QFileInfo(translationFile).exists()) translationFile = "lang:" + QLocale::system().name().left(2) + ".qm"; // if not found, load language.qm if (QFileInfo(translationFile).exists()) { CACanorus::_translator = std::unique_ptr<QTranslator>(new QTranslator); CACanorus::_translator->load(QFileInfo(translationFile).absoluteFilePath()); static_cast<QApplication*>(QApplication::instance())->installTranslator(CACanorus::_translator.get()); } if (QLocale::system().language() == QLocale::Hebrew) { /// \todo add Arabic, etc. static_cast<QApplication*>(QApplication::instance())->setLayoutDirection(Qt::RightToLeft); } } void CACanorus::initCommonGUI(std::unique_ptr<QFileDialog>& uiSaveDialog, std::unique_ptr<QFileDialog>& uiOpenDialog, std::unique_ptr<QFileDialog>& uiExportDialog, std::unique_ptr<QFileDialog>& uiImportDialog) { // Initialize main window's load/save/import/export dialogs qInfo() << "Entered initCommonGUI"; uiSaveDialog = std::make_unique<QFileDialog>(nullptr, QObject::tr("Choose a file to save"), settings()->documentsDirectory().absolutePath()); uiSaveDialog->setFileMode(QFileDialog::AnyFile); uiSaveDialog->setAcceptMode(QFileDialog::AcceptSave); uiSaveDialog->setNameFilters(QStringList() << CAFileFormats::CANORUSML_FILTER); uiSaveDialog->setNameFilters(uiSaveDialog->nameFilters() << CAFileFormats::CAN_FILTER); uiSaveDialog->selectNameFilter(CAFileFormats::getFilter(settings()->defaultSaveFormat())); uiOpenDialog = std::make_unique<QFileDialog>(nullptr, QObject::tr("Choose a file to open"), settings()->documentsDirectory().absolutePath()); uiOpenDialog->setFileMode(QFileDialog::ExistingFile); uiOpenDialog->setAcceptMode(QFileDialog::AcceptOpen); uiOpenDialog->setNameFilters(QStringList() << CAFileFormats::CANORUSML_FILTER); // clear the * filter uiOpenDialog->setNameFilters(uiOpenDialog->nameFilters() << CAFileFormats::CAN_FILTER); QString allFilters; // generate list of all files for (int i = 0; i < uiOpenDialog->nameFilters().size(); i++) { QString curFilter = uiOpenDialog->nameFilters()[i]; int left = curFilter.indexOf('(') + 1; allFilters += curFilter.mid(left, curFilter.size() - left - 1) + " "; } allFilters.chop(1); uiOpenDialog->setNameFilters(QStringList() << QString(QObject::tr("All supported formats (%1)").arg(allFilters)) << uiOpenDialog->nameFilters()); uiExportDialog = std::make_unique<QFileDialog>(nullptr, QObject::tr("Choose a file to export"), settings()->documentsDirectory().absolutePath()); uiExportDialog->setFileMode(QFileDialog::AnyFile); uiExportDialog->setAcceptMode(QFileDialog::AcceptSave); uiExportDialog->setNameFilters(QStringList() << CAFileFormats::LILYPOND_FILTER); uiExportDialog->setNameFilters(uiExportDialog->nameFilters() << CAFileFormats::MUSICXML_FILTER); uiExportDialog->setNameFilters(uiExportDialog->nameFilters() << CAFileFormats::MIDI_FILTER); uiExportDialog->setNameFilters(uiExportDialog->nameFilters() << CAFileFormats::PDF_FILTER); uiExportDialog->setNameFilters(uiExportDialog->nameFilters() << CAFileFormats::SVG_FILTER); uiImportDialog = std::make_unique<QFileDialog>(nullptr, QObject::tr("Choose a file to import"), settings()->documentsDirectory().absolutePath()); uiImportDialog->setFileMode(QFileDialog::ExistingFile); uiImportDialog->setAcceptMode(QFileDialog::AcceptOpen); uiImportDialog->setNameFilters(QStringList() << CAFileFormats::MUSICXML_FILTER); uiImportDialog->setNameFilters(uiImportDialog->nameFilters() << CAFileFormats::MXL_FILTER); uiImportDialog->setNameFilters(uiImportDialog->nameFilters() << CAFileFormats::MIDI_FILTER); // uiImportDialog->setNameFilters( uiImportDialog->nameFilters() << CAFileFormats::LILYPOND_FILTER ); // activate when usable } /*! Initializes playback devices. */ void CACanorus::initPlayback() { qRegisterMetaType<QVector<unsigned char>>("QVector< unsigned char >"); setMidiDevice(new CARtMidiDevice()); } /*! Opens Canorus config file and loads the settings. Config file is always INI file in user's home directory. No native formats are used (Windows registry etc.) - this is provided for easier transition of settings between the platforms. \sa settings() */ CASettingsDialog::CASettingsPage CACanorus::initSettings() { _settings = new CASettings(); switch (_settings->readSettings()) { case -1: return CASettingsDialog::PlaybackSettings; default: return CASettingsDialog::UndefinedSettings; } } /*! Initializes scripting and plugins subsystem. */ void CACanorus::initScripting() { #ifdef USE_RUBY CASwigRuby::init(); #endif #ifdef USE_PYTHON CASwigPython::init(); #endif } /*! Initializes recovery saving. */ void CACanorus::initAutoRecovery() { _autoRecovery = new CAAutoRecovery(); } void CACanorus::initUndo() { _undo = new CAUndo(); } void CACanorus::initFonts() { // addApplicationFont doesn't understand prefix: paths. QFontDatabase::addApplicationFont(QFileInfo("fonts:CenturySchL-Roma.ttf").absoluteFilePath()); QFontDatabase::addApplicationFont(QFileInfo("fonts:CenturySchL-Ital.ttf").absoluteFilePath()); QFontDatabase::addApplicationFont(QFileInfo("fonts:CenturySchL-Bold.ttf").absoluteFilePath()); QFontDatabase::addApplicationFont(QFileInfo("fonts:CenturySchL-BoldItal.ttf").absoluteFilePath()); QFontDatabase::addApplicationFont(QFileInfo("fonts:FreeSans.ttf").absoluteFilePath()); QFontDatabase::addApplicationFont(QFileInfo("fonts:Emmentaler-14.ttf").absoluteFilePath()); // populate glyph->codepoint map using generated list #include "fonts/fetaList.cxx" } /*! Returns codepoint for an Feta (Emmentaler) glyph by its name. */ int CACanorus::fetaCodepoint(const QString& name) { return _fetaMap[name]; } void CACanorus::initHelp() { _help = new CAHelpCtl(); } void CACanorus::insertRecentDocument(QString filename) { if (recentDocumentList().contains(filename)) removeRecentDocument(filename); recentDocumentList().prepend(filename); if (recentDocumentList().size() > settings()->maxRecentDocuments()) recentDocumentList().removeLast(); settings()->writeSettings(); } void CACanorus::addRecentDocument(QString filename) { recentDocumentList() << filename; } void CACanorus::removeRecentDocument(QString filename) { recentDocumentList().removeAll(filename); } /*! Free resources before quitting */ void CACanorus::cleanUp() { delete _settings; delete _midiDevice; autoRecovery()->cleanupRecovery(); delete _autoRecovery; delete _undo; } /*! Parses the switches and settings command line arguments to application. This function sets any settings passed in command line. Returns True, if application should resume with loading or False, if such a switch was passed. \sa parseOpenFileArguments() */ bool CACanorus::parseSettingsArguments(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { if (QString(argv[i]) == "--version") { std::cout << "Canorus - The next generation music score editor" << std::endl << "Version " << CANORUS_VERSION << std::endl; return false; } } return true; } /*! This function parses any arguments which doesn't look like switch or a setting. It creates a new main window and opens a file if a file is passed in the command line. */ void CACanorus::parseOpenFileArguments(int argc, char* argv[]) { for (int i = 1; i < argc; i++) { if (argv[i][0] != '-') { // automatically treat any argument which doesn't start with '-' to be a file name - \todo // passed is not the switch but a file name QFileInfo file(argv[i]); if (!file.exists()) continue; std::unique_ptr<CAMainWin> mainWin = std::make_unique<CAMainWin>(); mainWin->openDocument(file.absoluteFilePath()); mainWin->show(); } } } /*! \fn int CACanorus::mainWinCount() Returns the number of all main windows. */ /*! Returns number of main windows which have the given document opened. */ int CACanorus::mainWinCount(CADocument* doc) { int count = 0; for (int i = 0; i < _mainWinList.size(); i++) if (_mainWinList[i]->document() == doc) count++; return count; } /*! Rebuilds main windows with the given \a document and its views showing the given \a sheet. \sa rebuildUI(CADocument*), CAMainWin::rebuildUI() */ void CACanorus::rebuildUI(CADocument* document, CASheet* sheet) { for (int i = 0; i < mainWinList().size(); i++) if (mainWinList()[i]->document() == document) mainWinList()[i]->rebuildUI(sheet); } /*! Rebuilds main windows with the given \a document. Rebuilds all main windows, if \a document is not given or null. \sa rebuildUI(CADocument*, CASheet*), CAMainWin::rebuildUI() */ void CACanorus::rebuildUI(CADocument* document) { for (int i = 0; i < mainWinList().size(); i++) { if (document && mainWinList()[i]->document() == document) { mainWinList()[i]->rebuildUI(); } else if (!document) mainWinList()[i]->rebuildUI(); } } /*! Repaints all main window. This is useful for example if only selection was changed by external event (eg. plugin) and the GUI should be repainted, but not rebuilt. */ void CACanorus::repaintUI() { for (int i = 0; i < mainWinList().size(); i++) { mainWinList()[i]->repaint(); } } /*! Finds and returns a list of main windows containing the given document. */ QList<CAMainWin*> CACanorus::findMainWin(CADocument* document) { QList<CAMainWin*> mainWinList; for (int i = 0; i < CACanorus::mainWinList().size(); i++) if (CACanorus::mainWinList()[i]->document() == document) mainWinList << CACanorus::mainWinList()[i]; return mainWinList; } /*! \function void CACanorus::addMainWin( CAMainWin *w ) Adds an already created main window to the global main window list. \sa removeMainWin(), mainWinAt() */ /*! Searches recursively for all child objects of the given object, and connects matching signals from them to slots of object that follow the following form: void on_<widget name>_<signal name>(<signal parameters>); Let's assume our object has a child object of type QPushButton with the object name button1. The slot to catch the button's clicked() signal would be: void on_button1_clicked(); This enhanced function allows to precisely define in which object the signal (pOS) is defined and in which object the slot (poR) is defined. \sa QObject::setObjectName() \sa QMetaObject::connectSlotsByName(QObject *o) */ void CACanorus::connectSlotsByName(QObject* pOS, const QObject* pOR) { if (!pOS || !pOR) return; const QMetaObject* mo = pOR->metaObject(); Q_ASSERT(mo); const QObjectList list = pOS->findChildren<QObject*>(QString()); for (int i = 0; i < mo->methodCount(); ++i) { const char* slot = mo->method(i).methodSignature().data(); Q_ASSERT(slot); if (slot[0] != 'o' || slot[1] != 'n' || slot[2] != '_') continue; bool foundIt = false, foundObj = false; if (list.isEmpty()) qWarning("CACanorus::connectSlotsByName: Object list empty!"); for (int j = 0; j < list.count(); ++j) { const QObject* co = list.at(j); QByteArray objName = co->objectName().toLatin1(); unsigned int len = static_cast<unsigned int>(objName.length()); if (!len || qstrncmp(slot + 3, objName.data(), len) || slot[len + 3] != '_') continue; foundObj = true; const QMetaObject* smo = co->metaObject(); int sigIndex = smo->indexOfMethod(slot + len + 4); if (sigIndex < 0) { // search for compatible signals unsigned int slotlen = qstrlen(slot + len + 4) - 1; for (int k = 0; k < co->metaObject()->methodCount(); ++k) { if (smo->method(k).methodType() != QMetaMethod::Signal) continue; if (!qstrncmp(smo->method(k).methodSignature().data(), slot + len + 4, slotlen)) { sigIndex = k; break; } } } if (sigIndex < 0) continue; if (QMetaObject::connect(co, sigIndex, pOR, i)) { foundIt = true; break; } } if (foundIt) { // we found our slot, now skip all overloads while (mo->method(i + 1).attributes() & QMetaMethod::Cloned) ++i; } else if (!(mo->method(i).attributes() & QMetaMethod::Cloned)) { if (foundObj) qWarning("CACanorus::connectSlotsByName: No matching signal for %s", slot); else qWarning("CACanorus::connectSlotsByName: No matching object for %s", slot); } } }
17,073
C++
.cpp
419
35.386635
155
0.675526
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,285
main.cpp
canorusmusic_canorus/src/main.cpp
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include <QApplication> #include <QFile> #include <QFont> #include <QSplashScreen> // Python.h needs to be loaded first! #include "canorus.h" #include "core/settings.h" #include "interface/pluginmanager.h" #include "ui/mainwin.h" #include "ui/settingsdialog.h" #include <iostream> #ifndef Q_OS_WIN #include <signal.h> //Duma leads to a crash on libfontconfig with Ubuntu (10.04/12.04) //#include "duma.h" void catch_sig(int) { qApp->quit(); } #endif #ifdef Q_OS_WIN #include "Windows.h" #endif /*! Main function. This is the first function called when Canorus is run. It initializes CACanorus class and creates the main window. */ int main(int argc, char* argv[]) { QApplication mainApp(argc, argv); #ifdef Q_WS_X11 signal(SIGINT, catch_sig); signal(SIGQUIT, catch_sig); #endif #ifdef Q_OS_WIN // Enable console output on Windows if (AttachConsole(ATTACH_PARENT_PROCESS)) { freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); } #endif CACanorus::initSearchPaths(); QPixmap splashPixmap(400, 300); splashPixmap = QPixmap("images:splash.png"); QSplashScreen splash(splashPixmap); QFont font("Century Schoolbook L"); font.setPixelSize(17); splash.setFont(font); mainApp.processEvents(); // Set main application properties CACanorus::initMain(); // Parse switch and settings command line arguments if (!CACanorus::parseSettingsArguments(argc, argv)) return 0; splash.show(); // Load system translation if found CACanorus::initTranslations(); // Init MIDI devices CACanorus::initPlayback(); // Load config file bool firstTime = !QFile::exists(CASettings::defaultSettingsPath() + "/canorus.ini"); CASettingsDialog::CASettingsPage showSettingsPage = CACanorus::initSettings(); // Enable scripting and plugins subsystem splash.showMessage(QObject::tr("Initializing Scripting engine", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::initScripting(); // Finds all the plugins splash.showMessage(QObject::tr("Reading Plugins", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CAPluginManager::readPlugins(); // Initialize autosave splash.showMessage(QObject::tr("Initializing Automatic recovery", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::initAutoRecovery(); // Initialize help splash.showMessage(QObject::tr("Initializing Help", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::initHelp(); // Initialize undo/redo stacks splash.showMessage(QObject::tr("Initializing Undo/Redo framework", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::initUndo(); // Load bundled fonts splash.showMessage(QObject::tr("Loading fonts", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::initFonts(); // Check for any crashed Canorus sessions and open the recovery files splash.showMessage(QObject::tr("Searching for recovery documents", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::autoRecovery()->openRecovery(); // Creates a main window of a document to open if passed in command line splash.showMessage(QObject::tr("Initializing Main window", "splashScreen"), Qt::AlignBottom | Qt::AlignLeft, Qt::white); mainApp.processEvents(); CACanorus::parseOpenFileArguments(argc, argv); // If no file to open is passed in command line, create a new default main window. It's shown automatically by CACanorus::addMainWin(). if (!CACanorus::mainWinList().size()) { CAMainWin* mainWin = new CAMainWin(); // Init dialogs etc. CACanorus::initCommonGUI(mainWin->uiSaveDialog, mainWin->uiOpenDialog, mainWin->uiExportDialog, mainWin->uiImportDialog); mainWin->newDocument(); mainWin->show(); // Init dialogs etc. CACanorus::initCommonGUI(mainWin->uiSaveDialog, mainWin->uiOpenDialog, mainWin->uiExportDialog, mainWin->uiImportDialog); if (firstTime) { mainWin->on_uiUsersGuide_triggered(); } } splash.close(); // Show settings dialog, if needed (eg. MIDI setup when running Canorus for the first time) if (showSettingsPage != CASettingsDialog::UndefinedSettings) { CASettingsDialog(showSettingsPage, CACanorus::mainWinList()[0]); } return mainApp.exec(); }
4,997
C++
.cpp
125
35.016
139
0.708351
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,286
keysignaturectl.cpp
canorusmusic_canorus/src/scorectl/keysignaturectl.cpp
/*! Copyright (c) 2006-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ // Includes #include <QMessageBox> #include "canorus.h" #include "core/muselementfactory.h" #include "core/undo.h" #include "layout/drawablekeysignature.h" #include "score/keysignature.h" #include "score/sheet.h" #include "scorectl/keysignaturectl.h" #include "ui/mainwin.h" /*! \class CAKeySignatureCtl \brief Keysignature ctl for user interface actions Instances of this class can be used for user interactions of placing key signatures into the score */ /*! Default Construktor Besides standard initialization it creates a dummy object. Though not implemented we assume that the dummy object has at least one signal called dummyToggle. We connect this signal manually to our slot myToggle. */ CAKeySignatureCtl::CAKeySignatureCtl(CAMainWin* poMainWin, const QString& oHash) : _oHash(oHash) { setObjectName("oDummyCtl"); _poMainWin = poMainWin; if (poMainWin == nullptr) qCritical("DummyCtl: No mainwindow instance available!"); } void CAKeySignatureCtl::setupActions() { CACanorus::connectSlotsByName(_poMainWin, this); //connect( _poDummy, SIGNAL( dummyToggle( int ) ), this, SLOT( myToggle( int ) ) ); } // Destructor CAKeySignatureCtl::~CAKeySignatureCtl() { } /*! Changes the number of accidentals. */ void CAKeySignatureCtl::on_uiKeySig_activated(int row) { CADiatonicKey key(static_cast<QComboBox*>(sender())->itemData(row).toString()); if (_poMainWin->mode() == CAMainWin::InsertMode) { _poMainWin->musElementFactory()->setDiatonicKeyNumberOfAccs(key.numberOfAccs()); _poMainWin->musElementFactory()->setDiatonicKeyGender(key.gender()); } else if (_poMainWin->mode() == CAMainWin::EditMode && _poMainWin->currentScoreView() && _poMainWin->currentScoreView()->selection().size()) { QList<CADrawableMusElement*> list = _poMainWin->currentScoreView()->selection(); CACanorus::undo()->createUndoCommand(_poMainWin->document(), tr("change key signature", "undo")); for (int i = 0; i < list.size(); i++) { CAKeySignature* keySig = dynamic_cast<CAKeySignature*>(list[i]->musElement()); CAFunctionMark* fm = dynamic_cast<CAFunctionMark*>(list[i]->musElement()); if (keySig) { keySig->setDiatonicKey(key); } if (fm) { fm->setKey(CADiatonicKey::diatonicKeyToString(key)); } } CACanorus::undo()->pushUndoCommand(); CACanorus::rebuildUI(_poMainWin->document(), _poMainWin->currentSheet()); } } // Changes the toolbar entries for key signature input void CAKeySignatureCtl::on_uiInsertKeySig_toggled(bool checked) { if (checked) { _poMainWin->musElementFactory()->setMusElementType(CAMusElement::KeySignature); _poMainWin->setMode(CAMainWin::InsertMode, _oHash); } }
3,086
C++
.cpp
79
34.367089
147
0.708793
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,287
dummyctl.cpp
canorusmusic_canorus/src/scorectl/dummyctl.cpp
/*! Copyright (c) 2006-2010, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ // Includes #include <QMessageBox> #include "canorus.h" #include "control/dummyctl.h" #include "dummy/dummy.h" // Does not exist, this is only a dummy example! #include "ui/mainwin.h" /*! \class CADummyCtl \brief Dummy example ctl for user interface actions Use this dummy class for creating your own interface action classes. This Ctl was based on CAPreviewCtl originally one of the two first control classes in Canorus. */ /*! Default Construktor Besides standard initialization it creates a dummy object. Though not implemented we assume that the dummy object has at least one signal called dummyToggle. We connect this signal manually to our slot myToggle. */ CADummyCtl::CADummyCtl(CAMainWin* poMainWin) { setObjectName("oDummyCtl"); _poMainWin = poMainWin; _poDummy = new Dummy(); if (poMainWin == 0) qCritical("DummyCtl: No mainwindow instance available!"); else CACanorus::connectSlotsByName(_poMainWin, this); connect(_poDummy, SIGNAL(dummyToggle(int)), this, SLOT(myToggle(int))); } // Destructor CADummyCtl::~CADummyCtl() { if (_poDummy) { delete _poDummy; } _poDummy = 0; } void CADummyCtl::on_uiDummy_triggered() { // Do something } void CADummyCtl::myToggle(int iOn) { // Do something else }
1,549
C++
.cpp
52
26.615385
93
0.736382
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,288
canimport.cpp
canorusmusic_canorus/src/import/canimport.cpp
/*! Copyright (c) 2007-2020, Matevž Jekovec, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "import/canimport.h" #include "core/archive.h" #include "import/canorusmlimport.h" #include "score/resource.h" #include "score/document.h" #include <QDebug> #include <QDir> #include <QTemporaryFile> #include <QTextStream> CACanImport::CACanImport(QTextStream* stream) : CAImport(stream) { } CACanImport::~CACanImport() { } CADocument* CACanImport::importDocumentImpl() { CAArchive* arc = new CAArchive(*stream()->device()); if (!arc->error()) { // Read the score CAIOPtr filePtr = arc->file("content.xml"); CACanorusMLImport* content = new CACanorusMLImport(new QTextStream(&*filePtr)); content->importDocument(); content->wait(); CADocument* doc = content->importedDocument(); delete content; if (!doc) { setStatus(-1); return nullptr; } // extract each resource and correct resource path for (int i = 0; i < doc->resourceList().size(); i++) { std::shared_ptr<CAResource> r = doc->resourceList()[i]; if (!r->isLinked()) { // attached file - copy to /tmp CAIOPtr rPtr = arc->file(r->url().toLocalFile()); // chop the two leading slashes if (!dynamic_cast<QFile*>(&*rPtr)) { qCritical() << "CACanImport: Resource \"" << r->url().toLocalFile() << "\" not found in the file."; continue; } QTemporaryFile* f = new QTemporaryFile(QDir::tempPath() + "/" + r->name()); f->open(); QString targetFile = QFileInfo(*f).absoluteFilePath(); f->close(); delete f; static_cast<QFile*>(&*rPtr)->copy(targetFile); r->setUrl(QUrl::fromLocalFile(targetFile)); } else if (r->url().scheme() == "file" && file()) { // linked local file - convert the relative path to absolute QString outDir(QFileInfo(*file()).absolutePath()); r->setUrl(QUrl::fromLocalFile(QFileInfo(outDir + "/" + r->url().toLocalFile()).absolutePath())); } } // Replace the newly created archive with the current one delete doc->archive(); doc->setArchive(arc); if (!_fileName.isEmpty()) { doc->setFileName(_fileName); } setStatus(0); // done return doc; } else { setStatus(-1); return nullptr; } }
2,738
C++
.cpp
72
29.291667
119
0.579027
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,289
musicxmlimport.cpp
canorusmusic_canorus/src/import/musicxmlimport.cpp
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "import/musicxmlimport.h" #include <QDebug> #include <QXmlStreamAttributes> #include <iostream> // debug #include "import/canorusmlimport.h" #include "score/barline.h" #include "score/clef.h" #include "score/context.h" #include "score/document.h" #include "score/keysignature.h" #include "score/muselement.h" #include "score/note.h" #include "score/playable.h" #include "score/rest.h" #include "score/sheet.h" #include "score/staff.h" #include "score/timesignature.h" #include "score/voice.h" #include "score/articulation.h" #include "score/bookmark.h" #include "score/crescendo.h" #include "score/dynamic.h" #include "score/fermata.h" #include "score/fingering.h" #include "score/instrumentchange.h" #include "score/mark.h" #include "score/repeatmark.h" #include "score/ritardando.h" #include "score/tempo.h" #include "score/text.h" #include "score/lyricscontext.h" #include "score/syllable.h" #include "score/functionmark.h" #include "score/functionmarkcontext.h" CAMusicXmlImport::CAMusicXmlImport(QTextStream* stream) : CAImport(stream) , QXmlStreamReader() { initMusicXmlImport(); } CAMusicXmlImport::CAMusicXmlImport(const QString stream) : CAImport(stream) , QXmlStreamReader() { initMusicXmlImport(); } CAMusicXmlImport::~CAMusicXmlImport() { } void CAMusicXmlImport::initMusicXmlImport() { _document = nullptr; _tempoBpm = -1; } /*! Opens a MusicXML source \a in and creates a document out of it. CAMusicXmlImport uses QXmlStreamReader and SAX model for reading. */ CADocument* CAMusicXmlImport::importDocumentImpl() { QXmlStreamReader::setDevice(stream()->device()); while (!atEnd()) { readNext(); if (error()) { setStatus(-2); break; } switch (tokenType()) { case StartDocument: case DTD: { readHeader(); break; } case StartElement: { if (name() == "score-partwise") { _musicXmlVersion = attributes().value("version").toString(); readScorePartwise(); } else if (name() == "score-timewise") { _musicXmlVersion = attributes().value("version").toString(); readScoreTimewise(); } break; } case ProcessingInstruction: case EntityReference: case Comment: case Characters: case EndElement: case EndDocument: case Invalid: case NoToken: break; } } return _document; } const QString CAMusicXmlImport::readableStatus() { if (status() == -2) { return errorString(); } else { return CAImport::readableStatus(); } } void CAMusicXmlImport::readHeader() { if (tokenType() == DTD) { if (dtdName() != "score-partwise" && dtdName() != "score-timewise") { raiseError(tr("File is not a correct MusicXML file.")); } } } void CAMusicXmlImport::readScorePartwise() { if (name() != "score-partwise") return; _document = new CADocument(); while (!atEnd() && !(tokenType() == EndElement && name() == "score-partwise")) { readNext(); if (tokenType() == StartElement) { if (name() == "work") { readWork(); } else if (name() == "movement-title") { _document->setTitle(readElementText()); } else if (name() == "identification") { readIdentification(); } else if (name() == "defaults") { readDefaults(); } else if (name() == "part-list") { readPartList(); } else if (name() == "part") { readPart(); } } } for (int i = 0; i < _partMapStaff.keys().size(); i++) { // go through all partIds for (int j = 0; j < _partMapStaff[_partMapStaff.keys()[i]].size(); j++) { // go through all staffs with this partId CAStaff* s = _partMapStaff[_partMapStaff.keys()[i]][j]; for (int k = 0; k < s->voiceList().size(); k++) { // go through all voices in this staff // Note Reinhard: Not sure if program and channel cannot exceed 256, "int" is used everywhere s->voiceList()[k]->setMidiProgram(_midiProgram[_partMapStaff.keys()[i]] - 1); s->voiceList()[k]->setMidiChannel(_midiChannel[_partMapStaff.keys()[i]] - 1); } } } } void CAMusicXmlImport::readScoreTimewise() { if (name() != "score-timewise") return; _document = new CADocument(); // TODO: No support for score-timewise yet } void CAMusicXmlImport::readWork() { if (name() != "work") return; while (!atEnd() && !(tokenType() == EndElement && name() == "work")) { readNext(); if (tokenType() == StartElement) { if (name() == "work-title") { _document->setTitle(readElementText()); } } } } void CAMusicXmlImport::readDefaults() { if (name() != "defaults") return; // TODO: Currently this just ignores the defaults while (!atEnd() && !(tokenType() == EndElement && name() == "defaults")) { readNext(); } } void CAMusicXmlImport::readIdentification() { if (name() != "identification") return; while (!atEnd() && !(tokenType() == EndElement && name() == "identification")) { readNext(); if (tokenType() == StartElement) { if (name() == "creator" && attributes().value("type") == "composer") { _document->setComposer(readElementText()); } else if (name() == "creator" && attributes().value("type") == "lyricist") { _document->setPoet(readElementText()); } if (name() == "rights") { _document->setCopyright(readElementText()); } } } } void CAMusicXmlImport::readPartList() { if (name() != "part-list") return; _document->addSheet(); while (!atEnd() && !(tokenType() == EndElement && name() == "part-list")) { readNext(); if (tokenType() == StartElement) { QString partId; if (name() == "score-part") { partId = attributes().value("id").toString(); while (!atEnd() && !(tokenType() == EndElement && name() == "score-part")) { readNext(); if (tokenType() == StartElement && name() == "part-name") { _partName[partId] = readElementText(); } else if (tokenType() == StartElement && name() == "midi-channel") { _midiChannel[partId] = readElementText().toInt(); } else if (tokenType() == StartElement && name() == "midi-program") { _midiProgram[partId] = readElementText().toInt(); } } } } } } void CAMusicXmlImport::readPart() { if (name() != "part") return; QString partId = attributes().value("id").toString(); _partMapStaff[partId] = QList<CAStaff*>(); addStavesIfNeeded(partId, 1); _partMapClef[partId] = QHash<int, CAClef*>(); _partMapKeySig[partId] = QHash<int, CAKeySignature*>(); _partMapTimeSig[partId] = QHash<int, CATimeSignature*>(); while (!atEnd() && !(tokenType() == EndElement && name() == "part")) { readNext(); if (tokenType() == StartElement) { if (name() == "measure") { readMeasure(partId); } } } } void CAMusicXmlImport::readMeasure(QString partId) { if (name() != "measure") return; while (!atEnd() && !(tokenType() == EndElement && name() == "measure")) { readNext(); if (tokenType() == StartElement) { if (name() == "attributes") { readAttributes(partId); } else if (name() == "note") { readNote(partId, _divisions[partId]); } else if (name() == "forward") { readForward(partId, _divisions[partId]); } else if (name() == "direction") { } else if (name() == "sound") { readSound(partId); } } } // Finish the measure (add barlines to all staffs) for (int staffIdx = 0; staffIdx < _partMapStaff[partId].size(); staffIdx++) { CAStaff* staff = _partMapStaff[partId][staffIdx]; int lastVoice = -1; for (int i = 0; i < staff->voiceList().size(); i++) { if (lastVoice == -1 || staff->voiceList()[lastVoice]->lastTimeEnd() < staff->voiceList()[i]->lastTimeEnd()) { lastVoice = i; } } if (lastVoice != -1) { staff->voiceList()[lastVoice]->append(new CABarline(CABarline::Single, staff, 0)); staff->synchronizeVoices(); } } } void CAMusicXmlImport::readAttributes(QString partId) { if (name() != "attributes") return; int staves = 1; while (!atEnd() && !(tokenType() == EndElement && name() == "attributes")) { readNext(); if (tokenType() == StartElement) { if (name() == "divisions") { _divisions[partId] = readElementText().toInt(); } else if (name() == "staves") { staves = readElementText().toInt(); } else if (name() == "key") { int accs = 0; int number = (attributes().value("number").toString().isEmpty() ? 1 : attributes().value("number").toString().toInt()); CADiatonicKey::CAGender gender = CADiatonicKey::Major; while (!atEnd() && !(tokenType() == EndElement && name() == "key")) { readNext(); if (tokenType() == StartElement) { if (name() == "fifths") { accs = readElementText().toInt(); } if (name() == "mode") { gender = CADiatonicKey::genderFromString(readElementText()); } } } if (_partMapStaff[partId].size() >= number) { _partMapKeySig[partId][number] = new CAKeySignature(CADiatonicKey(accs, gender), _partMapStaff[partId][number - 1], 0); } else { _partMapKeySig[partId][number] = new CAKeySignature(CADiatonicKey(accs, gender), nullptr, 0); } } else if (name() == "time") { int beats = 1; int beat = 1; int number = (attributes().value("number").toString().isEmpty() ? 1 : attributes().value("number").toString().toInt()); while (!atEnd() && !(tokenType() == EndElement && name() == "time")) { readNext(); if (tokenType() == StartElement) { if (name() == "beats") { beats = readElementText().toInt(); } if (name() == "beat-type") { beat = readElementText().toInt(); } } } if (_partMapStaff[partId].size() >= number) { _partMapTimeSig[partId][number] = new CATimeSignature(beats, beat, _partMapStaff[partId][number - 1], 0); } else { _partMapTimeSig[partId][number] = new CATimeSignature(beats, beat, nullptr, 0); } } else if (name() == "clef") { QString sign; int number = (attributes().value("number").toString().isEmpty() ? 1 : attributes().value("number").toString().toInt()); while (!atEnd() && !(tokenType() == EndElement && name() == "clef")) { readNext(); if (tokenType() == StartElement) { if (name() == "sign") { sign = readElementText(); } } } CAClef::CAPredefinedClefType t; if (sign == "G") t = CAClef::Treble; // only treble and bass clefs are supported for now else if (sign == "F") t = CAClef::Bass; else t = CAClef::Undefined; if (_partMapStaff[partId].size() >= number) { _partMapClef[partId][number] = new CAClef(t, _partMapStaff[partId][number - 1], 0); } else { _partMapClef[partId][number] = new CAClef(t, nullptr, 0); } } } } addStavesIfNeeded(partId, staves); } void CAMusicXmlImport::readNote(QString partId, int divisions) { if (name() != "note") return; bool isRest = false; bool isPartOfChord = false; bool tieStop = false; int voice = 1; int staff = 1; CAPlayableLength length; CADiatonicPitch pitch; //CANote::CAStemDirection stem = CANote::StemPreferred; int lyricsNumber = -1; bool hyphen = false; bool melisma = false; QString lyricsText; if (!divisions) { std::cerr << "CAMusicXmlImport::readNote()- Error: divisions is 0, setting to 8" << std::endl; divisions = 8; } while (!atEnd() && !(tokenType() == EndElement && name() == "note")) { readNext(); if (tokenType() == StartElement) { if (name() == "rest") { isRest = true; } else if (name() == "chord") { isPartOfChord = true; } else if (name() == "duration") { int duration = readElementText().toInt(); float fDivisions = divisions; length = CAPlayableLength::timeLengthToPlayableLengthList(static_cast<int>((duration / fDivisions) * 256)).first(); } else if (name() == "stem") { QString s = readElementText(); //if (s=="up") stem = CANote::StemUp; //else if (s=="down") stem = CANote::StemDown; } else if (name() == "pitch") { int alter = 0; QString step; int octave = -1; while (!atEnd() && !(tokenType() == EndElement && name() == "pitch")) { readNext(); if (tokenType() == StartElement) { if (name() == "step") { step = readElementText(); } else if (name() == "octave") { octave = readElementText().toInt(); } else if (name() == "alter") { alter = readElementText().toInt(); } } } pitch = CADiatonicPitch::diatonicPitchFromString(step); pitch.setNoteName(pitch.noteName() + (octave * 7)); pitch.setAccs(static_cast<char>(alter)); } else if (name() == "voice") { voice = readElementText().toInt(); } else if (name() == "staff") { staff = readElementText().toInt(); } else if (name() == "lyric") { lyricsNumber = 1; if (!attributes().value("number").isEmpty()) { lyricsNumber = attributes().value("number").toString().toInt(); } while (!atEnd() && !(tokenType() == EndElement && name() == "lyric")) { readNext(); if (tokenType() == StartElement) { if (name() == "text") { lyricsText = readElementText(); } else if (name() == "syllabic") { hyphen = (readElementText() == "begin" || readElementText() == "middle"); } else if (name() == "extend") { melisma = true; } } } } else if (name() == "tie") { if (attributes().value("type") == "stop") { tieStop = true; } } } } CAVoice* v = addVoiceIfNeeded(partId, staff, voice); // grace notes are not supported yet if (length.musicLength() == CAPlayableLength::Undefined) { // grace notes don't have musicLength set return; } CAPlayable* p = nullptr; if (!isRest) { p = new CANote(pitch, length, v, 0); if (_tempoBpm != -1) { p->addMark(new CATempo(CAPlayableLength::Quarter, static_cast<uchar>(_tempoBpm), p)); _tempoBpm = -1; } } else { p = new CARest(CARest::Normal, length, v, 0); } v->append(p, isPartOfChord); // create ties if (tieStop) { CANote* noteEnd = static_cast<CANote*>(p); CANote* noteStart = nullptr; CANote* prevNote = v->previousNote(p->timeStart()); if (prevNote) { QList<CANote*> prevChord = prevNote->getChord(); for (int i = 0; i < prevChord.size(); i++) { if (static_cast<CANote*>(prevChord[i])->diatonicPitch() == noteEnd->diatonicPitch()) { noteStart = static_cast<CANote*>(prevChord[i]); break; } } } if (noteStart) { CASlur* tie = new CASlur(CASlur::TieType, CASlur::SlurPreferred, v->staff(), noteStart, noteEnd); noteStart->setTieStart(tie); noteEnd->setTieEnd(tie); } } // create lyrics if (lyricsNumber != -1) { while (lyricsNumber > v->lyricsContextList().size()) { v->addLyricsContext(new CALyricsContext(v->name() + tr("Lyrics"), v->lyricsContextList().size() + 1, v)); int idx = 0; if (v->lyricsContextList().size() == 1) { // Add the first lyrics right below the staff idx = _document->sheetList()[0]->contextList().indexOf(v->staff()) + 1; } else { // Add next lyrics below the last lyrics line idx = _document->sheetList()[0]->contextList().indexOf(v->lyricsContextList().last()) + 1; } _document->sheetList()[0]->insertContext(idx, v->lyricsContextList().last()); } v->lyricsContextList()[lyricsNumber - 1]->addSyllable(new CASyllable(lyricsText, hyphen, melisma, v->lyricsContextList()[lyricsNumber - 1], p->timeStart(), p->timeLength())); } } void CAMusicXmlImport::readSound(QString partId) { (void)partId; if (name() != "sound") return; if (!attributes().value("tempo").isEmpty()) { _tempoBpm = attributes().value("tempo").toString().toInt(); } } /*! Assures that the given \a partId contains at least \a staves number of staves. Adds new staves, if needed and assings any clefs, key signatures or time signatures in the buffer to the new staff, if their number is the number of the new staff. */ void CAMusicXmlImport::addStavesIfNeeded(QString partId, int staves) { for (int i = _partMapStaff[partId].size() + 1; i <= staves && staves > _partMapStaff[partId].size(); i++) { CAStaff* s = new CAStaff(tr("Staff%1").arg(_document->sheetList()[0]->staffList().size()), _document->sheetList()[0]); _document->sheetList()[0]->addContext(s); _partMapStaff[partId].append(s); if (_partMapKeySig[partId].contains(i)) { _partMapKeySig[partId][i]->setContext(s); } if (_partMapTimeSig[partId].contains(i)) { _partMapTimeSig[partId][i]->setContext(s); } if (_partMapClef[partId].contains(i)) { _partMapClef[partId][i]->setContext(s); } } } /*! Assures that the given \a partId and \a staff contains at least \a voice number of voices. Adds new voices, if needed and adds any clefs, key signatures or time signatures in the buffer to the new voice. */ CAVoice* CAMusicXmlImport::addVoiceIfNeeded(QString partId, int staff, int voice) { CAVoice* v = nullptr; CAStaff* s = nullptr; if (!_partMapVoice[partId].contains(voice)) { s = _partMapStaff[partId][staff - 1]; v = new CAVoice(tr("Voice%1").arg(s->voiceList().size()), s); if (!s->voiceList().size()) { if (_partMapClef[partId].contains(staff)) { v->append(_partMapClef[partId][staff]); } else if (_partMapClef[partId].contains(1)) { // add the default clef v->append(_partMapClef[partId][1]->clone(s)); } if (_partMapKeySig[partId].contains(staff)) { v->append(_partMapKeySig[partId][staff]); } else if (_partMapKeySig[partId].contains(1)) { // add the default keysig v->append(_partMapKeySig[partId][1]->clone(s)); } if (_partMapTimeSig[partId].contains(staff)) { v->append(_partMapTimeSig[partId][staff]); } else if (_partMapTimeSig[partId].contains(1)) { // add the default timesig v->append(_partMapTimeSig[partId][1]->clone(s)); } } s->addVoice(v); s->synchronizeVoices(); _partMapVoice[partId][voice] = v; } else { v = _partMapVoice[partId][voice]; s = v->staff(); } return v; } void CAMusicXmlImport::readForward(QString partId, int divisions) { if (name() != "forward") return; int voice = -1; int length = -1; int staff = 1; while (!atEnd() && !(tokenType() == EndElement && name() == "forward")) { readNext(); if (tokenType() == StartElement) { if (name() == "duration") { float fDivisions = divisions; length = static_cast<int>((readElementText().toInt() / fDivisions) * 256); } else if (name() == "voice") { voice = readElementText().toInt(); } else if (name() == "staff") { staff = readElementText().toInt(); } } } if (voice != -1 && length != -1) { CAVoice* v = addVoiceIfNeeded(partId, staff, voice); QList<CARest*> hiddenRests = CARest::composeRests(length, v->lastTimeEnd(), v); for (int i = 0; i < hiddenRests.size(); i++) { v->append(hiddenRests[i]); } } }
22,920
C++
.cpp
592
28.314189
182
0.524414
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,290
midiimport.cpp
canorusmusic_canorus/src/import/midiimport.cpp
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QTextStream> //#include <QRegExp> #include <QFileInfo> #include <iomanip> #include <iostream> // DEBUG #include "import/midiimport.h" #include "interface/mididevice.h" #include "score/clef.h" #include "score/document.h" #include "score/keysignature.h" #include "score/midinote.h" #include "score/note.h" #include "score/playable.h" #include "score/playablelength.h" #include "score/sheet.h" #include "score/slur.h" #include "score/tempo.h" #include "score/timesignature.h" #include "import/pmidi/wrapper.h" // Note Reinhard Padding Size with 3 bytes to alignment boundary due to "bool" member class CAMidiImportEvent { public: CAMidiImportEvent(bool on, int channel, int pitch, int velocity, int time, int length, int tempo, int program); ~CAMidiImportEvent(); QList<int> _pitchList; // to build chords when neccessary int _channel; int _velocity; int _time; int _length; int _nextTime; int _tempo; // beats per minute int _top; int _bottom; int _program; bool _on; }; CAMidiImportEvent::CAMidiImportEvent(bool on, int channel, int pitch, int velocity, int time, int length = 0, int tempo = 120, int program = 0) { _on = on; _channel = channel; _pitchList.clear(); _pitchList << pitch; _velocity = velocity; _time = time; _length = length; _nextTime = time + length; _tempo = tempo; _program = program; } CAMidiImportEvent::~CAMidiImportEvent() { } CAMidiImport::CAMidiImport(CADocument* document, QTextStream* in) : CAImport(in) { _document = document; initMidiImport(); for (int i = 0; i < 16; i++) { _allChannelsEvents << new QList<QList<CAMidiImportEvent*>*>; _allChannelsEvents[i]->append(new QList<CAMidiImportEvent*>); _allChannelsMediumPitch << 0; } // fill the midi program list with zeros for (int i = 0; i < 16; i++) { _midiProgramList << -1; } } CAMidiImport::~CAMidiImport() { } void CAMidiImport::initMidiImport() { _curLine = _curChar = 0; _curSlur = nullptr; _curPhrasingSlur = nullptr; } void CAMidiImport::addError(QString description, int curLine, int curChar) { _errors << QString(QObject::tr("<i>Fatal error, line %1, char %2:</i><br>")) .arg(curLine ? curLine : _curLine) .arg(curChar ? curChar : _curChar) + description + "<br>"; } CADocument* CAMidiImport::importDocumentImpl() { _document = new CADocument(); CASheet* s = importSheetImpl(); _document->addSheet(s); return _document; } CASheet* CAMidiImport::importSheetImpl() { CASheet* sheet = new CASheet(tr("Midi imported sheet"), _document); sheet = importSheetImplPmidiParser(sheet); // Show filename as sheet name. The tr() string above should only be changed after a release. QFileInfo fi(fileName()); sheet->setName(fi.baseName()); return sheet; } /*! Imports the given MIDI file and returns a list of CAMidiNote objects sorted by timeStart per channel. This function is usually called when raw MIDI operations are done and the actual notes etc. aren't needed. \warning This function returns notes only (without rests). \warning Only abstract note times are preserved. Real MIDI note times (in miliseconds) are lost. */ QList<QList<CAMidiNote*>> CAMidiImport::importMidiNotes() { importMidiEvents(); QList<QList<CAMidiNote*>> midiNotes; for (int i = 0; i < _allChannelsEvents.size(); i++) { midiNotes << QList<CAMidiNote*>(); for (int voiceIdx = 0; voiceIdx < _allChannelsEvents[i]->size(); voiceIdx++) { for (int j = 0; j < _allChannelsEvents[i]->at(voiceIdx)->size(); j++) { CAMidiImportEvent* event = _allChannelsEvents[i]->at(voiceIdx)->at(j); for (int pitchIdx = 0; pitchIdx < event->_pitchList.size(); pitchIdx++) { // temporary solutionsort midi events by time int timeStart = event->_time; int timeLength = event->_length; int k; for (k = 0; k < midiNotes.last().size() && midiNotes.last()[k]->timeStart() < timeStart; k++) ; midiNotes.last().insert(k, new CAMidiNote(event->_pitchList[pitchIdx], timeStart, timeLength, nullptr)); } } } } return midiNotes; } /*! The midi file is opened by calling the pmidi wrapper function \a pmidi_open_midi_file(), then, in a polling loop, the wrapper function pmidi_parse_midi_file() brings out the relevant midi events which are stored in the array _allChannelsEvents[]. All time signatures are stored in the array _allChannelsTimeSignatures[]. The work of pmidi and the wrapper is done then. All time values are scaled here to canorus' own music time scale. Further processing is referred to function \a writeMidiFileEventsToScore_New(). */ void CAMidiImport::importMidiEvents() { QByteArray s; s.append(fileName()); pmidi_open_midi_file(s.constData()); int voiceIndex; int res = PMIDI_STATUS_DUMMY; const int quarterLength = CAPlayableLength::playableLengthToTimeLength(CAPlayableLength::Quarter); int programCache[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; CADiatonicKey dk; bool leftOverNote; bool chordNote; bool timeSigAlreadyThere; setStatus(2); for (; res != PMIDI_STATUS_END;) { res = pmidi_parse_midi_file(); // Scale music time properly pmidi_out.time = (pmidi_out.time * quarterLength) / pmidi_out.time_base; pmidi_out.length = (pmidi_out.length * quarterLength) / pmidi_out.time_base; // // Quantization on hundredtwentyeighths of time starts and lengths by zeroing the msbits, quant being always a power of two // const int quant = CAPlayableLength::playableLengthToTimeLength(CAPlayableLength::HundredTwentyEighth /* CAPlayableLength::SixtyFourth */); int lengthEnd = pmidi_out.time + pmidi_out.length; pmidi_out.time += quant / 2; // rounding pmidi_out.time &= ~(quant - 1); // quant is power of two lengthEnd += quant / 2; lengthEnd &= ~(quant - 1); pmidi_out.length = lengthEnd - pmidi_out.time; switch (res) { case PMIDI_STATUS_END: case PMIDI_STATUS_VERSION: break; case PMIDI_STATUS_TEXT: // std::cout<<" at "<<pmidi_out.time<<" type "<<pmidi_out.type<<" ("<<pmidi_out.name<<") "<< pmidi_out.text<<std::endl; break; case PMIDI_STATUS_TIMESIG: // std::cout<<" Timesig "<<pmidi_out.top // <<"/"<<pmidi_out.bottom // <<" at "<<pmidi_out.time // <<std::endl; // We build the list of time signatures. We assume they are ordered in time. // We don't allow doublets to sneak in. timeSigAlreadyThere = false; for (int i = 0; i < _allChannelsTimeSignatures.size(); i++) { if (_allChannelsTimeSignatures[i]->_time == pmidi_out.time && _allChannelsTimeSignatures[i]->_top == pmidi_out.top && _allChannelsTimeSignatures[i]->_bottom == pmidi_out.bottom) timeSigAlreadyThere = true; } if (timeSigAlreadyThere) break; // If at the same last time another signature comes in the latter one wins. if (!_allChannelsTimeSignatures.size() || _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_time != pmidi_out.time) { // Normal detection of time signature, store it. _allChannelsTimeSignatures << new CAMidiImportEvent(true, 0, 0, 0, pmidi_out.time, 0, 0); _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_top = pmidi_out.top; _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_bottom = pmidi_out.bottom; } else { // overwrite the last one with new values _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_top = pmidi_out.top; _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_bottom = pmidi_out.bottom; } break; case PMIDI_STATUS_TEMPO: // std::cout<<" Tempo "<<pmidi_out.micro_tempo // <<" at "<<pmidi_out.time // <<std::endl; break; case PMIDI_STATUS_NOTE: /* std::cout<<" at "<<pmidi_out.time <<" chan "<<pmidi_out.chan <<" note "<<pmidi_out.note <<" vel "<<pmidi_out.vel <<" len "<<pmidi_out.length<<std::endl; */ // Deal with unfinished notes. This is a note that get's keyed when the old same pitch note is not yet expired. // Pmidi does a printf message with those. We adjust the length and next time of the original note according // the new event, and we don't create a new note in our list. leftOverNote = false; for (voiceIndex = 0; !leftOverNote && voiceIndex < _allChannelsEvents[pmidi_out.chan]->size(); voiceIndex++) { if (_allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->size()) { if (pmidi_out.time < _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_nextTime && _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_pitchList.indexOf(pmidi_out.note) >= 0) { _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_length = pmidi_out.time - _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_time + pmidi_out.length; _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_nextTime = _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_time + _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->back()->_length; leftOverNote = true; } } } // Check for building a chord chordNote = false; for (voiceIndex = 0; !leftOverNote && !chordNote && voiceIndex < _allChannelsEvents[pmidi_out.chan]->size(); voiceIndex++) { for (int i = _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->size() - 1; i >= 0; i--) { // finish chord search when start is too early if (_allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->at(i)->_time < pmidi_out.time) break; if (_allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->at(i)->_time == pmidi_out.time && _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->at(i)->_length == pmidi_out.length) { _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->at(i)->_pitchList << pmidi_out.note; chordNote = true; } } } // Get note to the right voice for (voiceIndex = 0; !leftOverNote && !chordNote && voiceIndex < 30; voiceIndex++) { // we can't imagine that so many voices ar needed in any case so let's put a limit // if another voice is needed and not yet there we create it if (voiceIndex >= _allChannelsEvents[pmidi_out.chan]->size()) { _allChannelsEvents[pmidi_out.chan]->append(new QList<CAMidiImportEvent*>); } if (_allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->size() == 0 || _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->last()->_nextTime <= pmidi_out.time) { // the note can be added _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->append(new CAMidiImportEvent(true, pmidi_out.chan, pmidi_out.note, pmidi_out.vel, pmidi_out.time, pmidi_out.length, 60000000 / pmidi_out.micro_tempo)); // attach the right program to the event _allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->at(_allChannelsEvents[pmidi_out.chan]->at(voiceIndex)->size() - 1)->_program = programCache[pmidi_out.chan]; break; } } break; case PMIDI_STATUS_DUMMY: case PMIDI_STATUS_ROOT: // std::cout<<" Midi-Format: "<<pmidi_out.format // <<" Tracks: "<<pmidi_out.tracks // <<" Time Base: "<<pmidi_out.time_base<<std::endl; break; case PMIDI_STATUS_CONTROL: break; case PMIDI_STATUS_PROGRAM: // std::cout<<" Program: "<<pmidi_out.program // <<" Channel: "<<pmidi_out.chan // <<std::endl; programCache[pmidi_out.chan] = pmidi_out.program; // store the first instrument in the channel to _midiProgramList variable if (_midiProgramList[pmidi_out.chan] == -1) { _midiProgramList[pmidi_out.chan] = pmidi_out.program; } break; case PMIDI_STATUS_PITCH: case PMIDI_STATUS_PRESSURE: case PMIDI_STATUS_KEYTOUCH: case PMIDI_STATUS_SYSEX: break; case PMIDI_STATUS_KEYSIG: // std::cout<<" Keys: "<<pmidi_out.key // <<" Minor: "<<pmidi_out.minor<<std::endl; dk = CADiatonicKey(pmidi_out.key, pmidi_out.minor ? CADiatonicKey::Minor : CADiatonicKey::Major); // After the first key signature only changes are imported if (!_allChannelsKeySignatures.size() || _allChannelsKeySignatures.last()->diatonicKey() != dk) _allChannelsKeySignatures << new CAKeySignature(dk, nullptr, pmidi_out.time); break; case PMIDI_STATUS_SMPTEOFFS: /* std::cout<<" Stunden "<<pmidi_out.hours <<" Minuten "<<pmidi_out.minutes <<" Sekunden "<<pmidi_out.seconds <<" Frames "<<pmidi_out.frames <<" Subframes "<<pmidi_out.subframes<<std::endl; */ break; } } } CASheet* CAMidiImport::importSheetImplPmidiParser(CASheet* sheet) { importMidiEvents(); writeMidiFileEventsToScore_New(sheet); fixAccidentals(sheet); setStatus(5); return sheet; } /*! */ void CAMidiImport::writeMidiFileEventsToScore_New(CASheet* sheet) { int numberOfStaffs = sheet->staffList().size(); int staffIndex = 0; int voiceIndex; CAStaff* staff; CAVoice* voice; setStatus(3); // for debugging only: for (int i = 0; i < _allChannelsTimeSignatures.size(); i++) { // std::cout<<"Time signature " // <<_allChannelsTimeSignatures[i]->_top // <<"/" // <<_allChannelsTimeSignatures[i]->_bottom // <<" at " // <<_allChannelsTimeSignatures[i]->_time // <<std::endl; } // Calculate the medium pitch for every staff for the key selection later _numberOfAllVoices = 2; // plus one for preprocessing, thats calling pmidi, and one for postprocessing for (int chanIndex = 0; chanIndex < 16; chanIndex++) { int n = 0; for (voiceIndex = 0; voiceIndex < _allChannelsEvents[chanIndex]->size(); voiceIndex++) { for (int i = 0; i < _allChannelsEvents[chanIndex]->at(voiceIndex)->size(); i++) { n++; for (int k = 0; k < _allChannelsEvents[chanIndex]->at(voiceIndex)->at(i)->_pitchList.size(); k++) { _allChannelsMediumPitch[chanIndex] += _allChannelsEvents[chanIndex]->at(voiceIndex)->at(i)->_pitchList[k]; } } } if (n > 0) { _allChannelsMediumPitch[chanIndex] = _allChannelsMediumPitch[chanIndex] / n; // std::cout<<"Channel "<<chanIndex<<" has "<<_allChannelsEvents[chanIndex]->size()<<" Voices, Medium-Pitch " // <<_allChannelsMediumPitch[chanIndex]<<std::endl; _numberOfAllVoices += _allChannelsEvents[chanIndex]->size(); } } // Remove coincidenting key signatures. For this we have to make a decrementing loop, because we want to keep the later one. for (int i = _allChannelsKeySignatures.size() - 2; i >= 0; i--) { if (_allChannelsKeySignatures[i]->timeStart() == _allChannelsKeySignatures[i + 1]->timeStart()) _allChannelsKeySignatures.remove(i); } // Zero _tempo when no tempo change, only in the first voice, so later we will set tempo at the remaining points. // By the algorithm used tempo changes on a note will be placed already on the rest before it eventually. for (int ch = 0; ch < 16; ch++) { if (_allChannelsEvents[ch]->size() > 0 && _allChannelsEvents[ch]->at(0)->size() > 1) { int te = _allChannelsEvents[ch]->at(0)->at(0)->_tempo; for (int i = 1; i < _allChannelsEvents[ch]->at(0)->size(); i++) { if (_allChannelsEvents[ch]->at(0)->at(i)->_tempo == te) { _allChannelsEvents[ch]->at(0)->at(i)->_tempo = 0; } else { te = _allChannelsEvents[ch]->at(0)->at(i)->_tempo; } } } } // Midi files support support only time signatures for the all staffs, so, if one staff has a change, all change the same. // Result: For time signatures we keep only one list for all staffs. // Canorus has separate time signature elements for each staff, but shared vor all voices. Each voice gets a reference copy of the // the associated time signature. // Add a default time signature if there is none supplied by the imported file. // // Still missing: A check of time signature consistency // if (!_allChannelsTimeSignatures.size()) { _allChannelsTimeSignatures << new CAMidiImportEvent(true, 0, 0, 0, 0, 0, 0); _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_top = 4; _allChannelsTimeSignatures[_allChannelsTimeSignatures.size() - 1]->_bottom = 4; } int nImportedVoices = 1; // one because preprocessing, ie calling pmidi, is already done setProgress(_numberOfAllVoices ? nImportedVoices * 100 / _numberOfAllVoices : 50); for (unsigned char ch = 0; ch < 16; ch++) { if (!_allChannelsEvents[ch]->size() || !_allChannelsEvents[ch]->first()->size()) /* staff or first voice empty */ continue; if (staffIndex < numberOfStaffs) { staff = sheet->staffList().at(staffIndex); voice = staff->voiceList().first(); } else { // create a new staff with 5 lines staff = new CAStaff(QString("Ch%1").arg(staffIndex), sheet, 5); // Todo: string to build with QObject::tr() sheet->addContext(staff); } CAMusElement* musElemClef = nullptr; for (int voiceIndex = 0; voiceIndex < _allChannelsEvents[ch]->size(); voiceIndex++) { // voiceName = QObject::tr("Voice%1").arg( voiceNumber ); voice = new CAVoice(QString("Ch%1V%2").arg(staffIndex).arg(voiceIndex), staff, CANote::StemNeutral); // Todo: string to build with QObject::tr() staff->addVoice(voice); setCurVoice(voice); voice->setMidiChannel(ch); if (voiceIndex == 0) { if (_allChannelsMediumPitch[ch] < 50) { musElemClef = new CAClef(CAClef::Bass, staff, 0, 0); } else if (_allChannelsMediumPitch[ch] < 65) { musElemClef = new CAClef(CAClef::Treble, staff, 0, -8); } else { musElemClef = new CAClef(CAClef::Treble, staff, 0, 0); } } voice->append(musElemClef, false); writeMidiChannelEventsToVoice_New(ch, voiceIndex, staff, voice); setProgress(_numberOfAllVoices ? nImportedVoices * 100 / _numberOfAllVoices : 50); ++nImportedVoices; staff->synchronizeVoices(); } staffIndex++; } } CAMusElement* CAMidiImport::getOrCreateClef(int, int, CAStaff*, CAVoice*) { return nullptr; } /*! This function looks in the keySignatureReferences */ int CAMidiImport::getNextKeySignatureTime() { if (_actualKeySignatureIndex + 1 < _allChannelsKeySignatures.size()) // there are signatures ahead return _allChannelsKeySignatures[_actualKeySignatureIndex + 1]->timeStart(); return -1; } /*! This function looks in the keySignatureReferences */ CAMusElement* CAMidiImport::getOrCreateKeySignature(int time, int, CAStaff* staff, CAVoice*) { if (_actualKeySignatureIndex + 1 < _allChannelsKeySignatures.size() && // there are signatures ahead, and time is exactly matched time == _allChannelsKeySignatures[_actualKeySignatureIndex + 1]->timeStart()) { _actualKeySignatureIndex++; if (staff->keySignatureRefs().size() < _actualKeySignatureIndex + 1) { staff->keySignatureRefs() << new CAKeySignature(_allChannelsKeySignatures[_actualKeySignatureIndex]->diatonicKey(), staff, time); } return staff->keySignatureRefs()[_actualKeySignatureIndex]; } return nullptr; } /*! Docu neeeded, definitively! rud */ CAMusElement* CAMidiImport::getOrCreateTimeSignature(int time, int, CAStaff* staff, CAVoice*) { if (!staff->timeSignatureRefs().size()) { _actualTimeSignatureIndex = 0; int top = _allChannelsTimeSignatures[_actualTimeSignatureIndex]->_top; int bottom = _allChannelsTimeSignatures[_actualTimeSignatureIndex]->_bottom; staff->timeSignatureRefs() << new CATimeSignature(top, bottom, staff, 0); // std::cout<<" neue Timesig at "<<time<<", there are " // <<_allChannelsTimeSignatures.size() // <<std::endl; // werden ersetzt: return staff->timeSignatureRefs()[_actualTimeSignatureIndex]; } // check if more than one time signature at all if (_actualTimeSignatureIndex < 0 || _allChannelsTimeSignatures.size() > _actualTimeSignatureIndex + 1) { // is a new time signature already looming there? if (time >= _allChannelsTimeSignatures[_actualTimeSignatureIndex + 1]->_time) { _actualTimeSignatureIndex++; // for each voice we run down the list of time signatures of the sheet, all staffs. if (staff->timeSignatureRefs().size() >= _actualTimeSignatureIndex + 1) { return staff->timeSignatureRefs()[_actualTimeSignatureIndex]; } else { int top = _allChannelsTimeSignatures[_actualTimeSignatureIndex]->_top; int bottom = _allChannelsTimeSignatures[_actualTimeSignatureIndex]->_bottom; staff->timeSignatureRefs() << new CATimeSignature(top, bottom, staff, 0); // std::cout<<" new Timesig at "<<time<<", there are " // <<_allChannelsTimeSignatures.size() // <<std::endl; return staff->timeSignatureRefs()[_actualTimeSignatureIndex]; } } } return nullptr; } /*! Docu neeeded Apropo program support at midi import: Now the last effective program assignement per voice will make it through. A separation in voices regarding the midi program is note yet implemented. */ void CAMidiImport::writeMidiChannelEventsToVoice_New(int channel, int voiceIndex, CAStaff* staff, CAVoice* voice) { QList<CAMidiImportEvent*>* events = _allChannelsEvents[channel]->at(voiceIndex); QList<CANote*> noteList; CARest* rest; QList<CANote*> previousNotes; // for sluring QList<CAPlayableLength> lenList; // work list when splitting notes and rests at barlines CATimeSignature* ts = nullptr; CABarline* b = nullptr; int time = 0; // current time in the loop, only increasing, for tracking notes and rests int length; int program; _actualClefIndex = -1; // for each voice we run down the list of time signatures of the sheet, all staffs. _actualKeySignatureIndex = -1; // for each voice we run down the list of time signatures of the sheet, all staffs. _actualTimeSignatureIndex = -1; // for each voice we run down the list of time signatures of the sheet, all staffs. // std::cout<< "Channel "<<channel<<" VoiceIndex "<<voiceIndex<<" "<<std::setw(5)<<events->size()<<" elements"<<std::endl; for (int i = 0; i < events->size(); i++) { if (time == 0) { CAMusElement* ksElem = getOrCreateKeySignature(time, voiceIndex, staff, voice); if (ksElem) { // std::cout<<" KeySig-MusElement "<<ksElem<<" at "<<ksElem->timeStart()<<" "<< // qPrintable( CADiatonicKey::diatonicKeyToString( (static_cast<CAKeySignature*>(ksElem))->diatonicKey() ))<<std::endl; voice->append(ksElem, false); } } // we place a tempo mark only for the first voice, and if we don't place we set tempo null int tempo = voiceIndex == 0 ? events->at(i)->_tempo : 0; b = static_cast<CABarline*>(voice->previousByType(CAMusElement::Barline, voice->lastMusElement())); CAMusElement* tsElem = getOrCreateTimeSignature(time, voiceIndex, staff, voice); if (tsElem) { voice->append(tsElem, false); ts = static_cast<CATimeSignature*>(tsElem); if (channel == 9 && voiceIndex > 1) { //std::cout<< " in advance new time sig at "<<time<<" in "<<ts->beats()<<"/"<<ts->beat()<<std::endl; } } // check if we need to add rests length = events->at(i)->_time - time; while (length > 0) { // This definitively needs clean up!!! CAMusElement* fB = voice->getOnePreviousByType(CAMusElement::Barline, time); if (fB) { b = static_cast<CABarline*>(fB); } else { b = nullptr; } // Hier wird eine vergangene Taktlinie zugewiesen: b = static_cast<CABarline*>( voice->previousByType( CAMusElement::Barline, voice->lastMusElement())); b = static_cast<CABarline*>(voice->previousByType(CAMusElement::Barline, voice->lastMusElement())); lenList.clear(); lenList << CAPlayableLength::matchToBars(length, voice->lastTimeEnd(), b, ts, 4, getNextKeySignatureTime()); for (int j = 0; j < lenList.size(); j++) { rest = new CARest(CARest::Normal, lenList[j], voice, 0, -1); voice->append(rest, false); int len = CAPlayableLength::playableLengthToTimeLength(lenList[j]); //std::cout<< " Rest Length "<<len<<" at "<<time<<std::endl; time += len; length -= len; if (tempo) { // Note Reinhard: Not sure if tempo cannot exceed 256, "int" is used everywhere CAMark* _curMark = new CATempo(CAPlayableLength::Quarter, tempo, rest); rest->addMark(_curMark); tempo = 0; } tsElem = getOrCreateTimeSignature(time, voiceIndex, staff, voice); if (tsElem) { voice->append(tsElem, false); ts = static_cast<CATimeSignature*>(tsElem); // std::cout<< " for a rest new time sig at "<<time<<" in "<<ts->beats()<<"/"<<ts->beat()<<std::endl; } // Time signatures are eventuelly placed before barlines CAMusElement* ksElem = getOrCreateKeySignature(rest->timeEnd(), voiceIndex, staff, voice); if (ksElem) { // std::cout<<" KeySig-MusElement "<<ksElem<<" at "<<ksElem->timeStart()<<" "<< // qPrintable( CADiatonicKey::diatonicKeyToString( (static_cast<CAKeySignature*>(ksElem))->diatonicKey() ))<<std::endl; voice->append(ksElem, false); } // Barlines are shared among voices, see we append an existing one, otherwise a new one //QList<CAMusElement*> foundBarlines = staff->getEltByType( CAMusElement::Barline, rest->timeEnd() ); CAMusElement* bl = staff->getOneEltByType(CAMusElement::Barline, rest->timeEnd()); if (bl) { voice->append(bl, false); b = static_cast<CABarline*>(bl); } else { staff->placeAutoBar(rest); } if (tsElem) { break; } } } // notes to be added length = events->at(i)->_length; program = events->at(i)->_program; previousNotes.clear(); while (length > 0 && events->at(i)->_velocity > 0) { // this needs clean up, definitevely CAMusElement* fB = voice->getOnePreviousByType(CAMusElement::Barline, time); if (fB) { b = static_cast<CABarline*>(fB); } else { b = nullptr; } b = static_cast<CABarline*>(voice->previousByType(CAMusElement::Barline, voice->lastMusElement())); lenList.clear(); lenList << CAPlayableLength::matchToBars(length, voice->lastTimeEnd(), b, ts, 4, getNextKeySignatureTime()); for (int j = 0; j < lenList.size(); j++) { noteList.clear(); for (int k = 0; k < events->at(i)->_pitchList.size(); k++) { CADiatonicPitch diaPitch = matchPitchToKey(voice, events->at(i)->_pitchList[k]); noteList << new CANote(diaPitch, lenList[j], voice, -1); voice->append(noteList[k], k ? true : false); noteList[k]->setStemDirection(CANote::StemPreferred); } // Note Reinhard: Not sure if program cannot exceed 256, "int" is used everywhere voice->setMidiProgram(program); int len = CAPlayableLength::playableLengthToTimeLength(lenList[j]); time += len; length -= len; if (tempo) { // Note Reinhard: Not sure if tempo cannot exceed 256, "int" is used everywhere CAMark* _curMark = new CATempo(CAPlayableLength::Quarter, tempo, noteList.first()); noteList.first()->addMark(_curMark); tempo = 0; } tsElem = getOrCreateTimeSignature(noteList.first()->timeEnd(), voiceIndex, staff, voice); if (tsElem) { voice->append(tsElem, false); ts = static_cast<CATimeSignature*>(tsElem); //std::cout<< " for a note new time sig at "<<time<<" in "<<ts->beats()<<"/"<<ts->beat()<<std::endl; } // Time signatures are eventuelly placed before barlines CAMusElement* ksElem = getOrCreateKeySignature(noteList.first()->timeEnd(), voiceIndex, staff, voice); if (ksElem) { // std::cout<<" KeySig-MusElement "<<ksElem<<" at "<<ksElem->timeStart()<<" "<< // qPrintable( CADiatonicKey::diatonicKeyToString( (static_cast<CAKeySignature*>(ksElem))->diatonicKey() ))<<std::endl; voice->append(ksElem, false); } // Barlines are shared among voices, see we append an existing one, otherwise a new one CAMusElement* bl = staff->getOneEltByType(CAMusElement::Barline, noteList.back()->timeEnd()); if (bl) { voice->append(bl, false); b = static_cast<CABarline*>(bl); } else { staff->placeAutoBar(noteList.back()); } for (int k = 0; k < previousNotes.size(); k++) { CASlur* slur = new CASlur(CASlur::TieType, CASlur::SlurPreferred, staff, previousNotes[k], noteList[k]); previousNotes[k]->setTieStart(slur); noteList[k]->setTieEnd(slur); } previousNotes.clear(); previousNotes << noteList; if (tsElem) { break; } } } } } void CAMidiImport::closeFile() { file()->close(); } /*! Displays a string left of the progress bar */ const QString CAMidiImport::readableStatus() { switch (status()) { case 0: return tr("Ready"); case 1: return tr("Importing..."); case -1: return tr("Error while importing!\nLine %1:%2.").arg(curLine()).arg(curChar()); case 2: return tr("Importing Midi events..."); case 3: return tr("Merging Midi events with the score..."); case 4: return tr("Reinterpreting accidentals..."); case 5: return tr("Drawing score..."); } return ""; } /*! This function is a duplicat in CAKeybdInput! Should be moved to CADiatonicPitch an be reused. This function looks up the current key signiture. Then it computes the proper accidentials for the note. This function should be somewhere else, maybe in \a CADiatonicPitch ? */ CADiatonicPitch CAMidiImport::matchPitchToKey(CAVoice* voice, int midiPitch) { // Default actual Key Signature is C _actualKeySignature = CADiatonicPitch(CADiatonicPitch::C); int i; for (i = 0; i < 7; i++) _actualKeySignatureAccs[i] = 0; _actualKeyAccidentalsSum = 0; // Trace which Key Signature might be in effect. // We make a local copy for later optimisation by only updating at a non // linear input QList<CAMusElement*> keyList = voice->getPreviousByType( CAMusElement::KeySignature, voice->lastTimeEnd()); if (keyList.size()) { // set the note name and its accidental and the accidentals of the scale CAKeySignature* effSig = static_cast<CAKeySignature*>(keyList.last()); return CADiatonicPitch::diatonicPitchFromMidiPitchKey(midiPitch, effSig->diatonicKey()); } else { return CADiatonicPitch::diatonicPitchFromMidiPitch(midiPitch); } } /*! Tries to assume the correct accidental for the alien notes in the key signature. Currently this function searches for disalterations (eg. cis -> c, where c is the note in the scale). The algorithm solves the toggling notes (eg. e es e -> e dis e) and transition notes (eg. e dis d -> e es d). */ void CAMidiImport::fixAccidentals(CASheet* s) { setStatus(4); QList<CAVoice*> voices = s->voiceList(); for (int i = 0; i < voices.size(); i++) { QList<CANote*> noteList = voices[i]->getNoteList(); for (int j = 0; j < noteList.size() - 2; j++) { CAInterval i1(noteList[j]->diatonicPitch(), noteList[j + 1]->diatonicPitch(), false); CAInterval i2(noteList[j]->diatonicPitch(), noteList[j + 2]->diatonicPitch(), false); // toggling notes if (i1 == CAInterval(2, -1) && i2 == CAInterval(0, 1)) { noteList[j + 1]->setDiatonicPitch(noteList[j + 1]->diatonicPitch() + CAInterval(-2, -2)); } else if (i1 == CAInterval(2, 1) && i2 == CAInterval(0, 1)) { noteList[j + 1]->setDiatonicPitch(noteList[j + 1]->diatonicPitch() + CAInterval(-2, 2)); } else // transition notes if (i1 == CAInterval(2, 1) && i2 != CAInterval(1, 2)) { noteList[j]->setDiatonicPitch(noteList[j]->diatonicPitch() + CAInterval(-2, -2)); } else if (i1 == CAInterval(2, -1) && i2 != CAInterval(1, -2)) { noteList[j]->setDiatonicPitch(noteList[j]->diatonicPitch() + CAInterval(-2, 2)); } } } }
36,145
C++
.cpp
737
39.294437
232
0.600204
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,291
canorusmlimport.cpp
canorusmusic_canorus/src/import/canorusmlimport.cpp
/*! Copyright (c) 2006-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QDebug> #include <QFileInfo> #include <QIODevice> #include <QVariant> #include <QVersionNumber> #include "import/canorusmlimport.h" #include "control/resourcectl.h" #include "score/barline.h" #include "score/clef.h" #include "score/context.h" #include "score/document.h" #include "score/keysignature.h" #include "score/muselement.h" #include "score/note.h" #include "score/resource.h" #include "score/rest.h" #include "score/sheet.h" #include "score/staff.h" #include "score/timesignature.h" #include "score/voice.h" #include "score/articulation.h" #include "score/bookmark.h" #include "score/crescendo.h" #include "score/dynamic.h" #include "score/fermata.h" #include "score/fingering.h" #include "score/instrumentchange.h" #include "score/mark.h" #include "score/repeatmark.h" #include "score/ritardando.h" #include "score/tempo.h" #include "score/text.h" #include "score/lyricscontext.h" #include "score/syllable.h" #include "score/figuredbasscontext.h" #include "score/figuredbassmark.h" #include "score/functionmark.h" #include "score/functionmarkcontext.h" #include "score/chordname.h" #include "score/chordnamecontext.h" /*! \class CACanorusMLImport \brief Class for opening the Canorus documents CACanorusMLImport class opens the XML based Canorus documents. It uses SAX parser for reading. \sa CAImport, CACanorusMLExport */ CACanorusMLImport::CACanorusMLImport(QTextStream* stream) : CAImport(stream) , QXmlDefaultHandler() { initCanorusMLImport(); } CACanorusMLImport::CACanorusMLImport(const QString stream) : CAImport(stream) , QXmlDefaultHandler() { initCanorusMLImport(); } CACanorusMLImport::~CACanorusMLImport() { } void CACanorusMLImport::initCanorusMLImport() { _document = nullptr; _curSheet = nullptr; _curContext = nullptr; _curVoice = nullptr; _curMusElt = nullptr; _prevMusElt = nullptr; _curMark = nullptr; _curClef = nullptr; _curTimeSig = nullptr; _curKeySig = nullptr; _curBarline = nullptr; _curNote = nullptr; _curRest = nullptr; _curTie = nullptr; _curSlur = nullptr; _curPhrasingSlur = nullptr; _curTuplet = nullptr; } CADocument* CACanorusMLImport::importDocumentImpl() { QIODevice* device = stream()->device(); QXmlInputSource* src; if (device) src = new QXmlInputSource(device); else { src = new QXmlInputSource(); src->setData(*stream()->string()); } QXmlSimpleReader* reader = new QXmlSimpleReader(); reader->setContentHandler(this); reader->setErrorHandler(this); reader->parse(src); if (document() && !_fileName.isEmpty()) { document()->setFileName(_fileName); } delete reader; delete src; return document(); } /*! This method should be called when a critical error occurs while parsing the XML source. \sa startElement(), endElement() */ bool CACanorusMLImport::fatalError(const QXmlParseException& exception) { qWarning() << "Fatal error on line " << exception.lineNumber() << ", column " << exception.columnNumber() << ": " << exception.message() << "\n\nParser message:\n" << _errorMsg; return false; } /*! This function is called automatically by Qt SAX parser while reading the CanorusML source. This function is called when a new node is opened. It already reads node attributes. The function returns true, if the node was successfully recognized and parsed; otherwise false. \sa endElement() */ bool CACanorusMLImport::startElement(const QString&, const QString&, const QString& qName, const QXmlAttributes& attributes) { if (attributes.value("color") != "") { _color = QVariant(attributes.value("color")).value<QColor>(); if (_version <= QVersionNumber(0, 7, 3)) { // before Canorus 0.7.4, color was incorrectly saved (always #000000) _color = QColor(); } } else { _color = QColor(); } if (qName == "document") { // CADocument _document = new CADocument(); _document->setTitle(attributes.value("title")); _document->setSubtitle(attributes.value("subtitle")); _document->setComposer(attributes.value("composer")); _document->setArranger(attributes.value("arranger")); _document->setPoet(attributes.value("poet")); _document->setTextTranslator(attributes.value("text-translator")); _document->setCopyright(attributes.value("copyright")); _document->setDedication(attributes.value("dedication")); _document->setComments(attributes.value("comments")); _document->setDateCreated(QDateTime::fromString(attributes.value("date-created"), Qt::ISODate)); _document->setDateLastModified(QDateTime::fromString(attributes.value("date-last-modified"), Qt::ISODate)); _document->setTimeEdited(attributes.value("time-edited").toUInt()); } else if (qName == "sheet") { // CASheet QString sheetName = attributes.value("name"); if (sheetName.isEmpty()) sheetName = QObject::tr("Sheet%1").arg(_document->sheetList().size() + 1); _curSheet = new CASheet(sheetName, _document); _document->addSheet(_curSheet); } else if (qName == "staff") { // CAStaff QString staffName = attributes.value("name"); if (!_curSheet) { _errorMsg = "The sheet where to add the staff doesn't exist yet!"; return false; } if (staffName.isEmpty()) staffName = QObject::tr("Staff%1").arg(_curSheet->staffList().size() + 1); _curContext = new CAStaff(staffName, _curSheet, attributes.value("number-of-lines").toInt()); _curSheet->addContext(_curContext); } else if (qName == "lyrics-context") { // CALyricsContext QString lcName = attributes.value("name"); if (!_curSheet) { _errorMsg = "The sheet where to add the lyrics context doesn't exist yet!"; return false; } if (lcName.isEmpty()) lcName = QObject::tr("LyricsContext%1").arg(_curSheet->contextList().size() + 1); _curContext = new CALyricsContext(lcName, attributes.value("stanza-number").toInt(), _curSheet); // voices are not neccesseraly completely read - store indices of the voices internally and then assign them at the end if (!attributes.value("associated-voice-idx").isEmpty()) _lcMap[static_cast<CALyricsContext*>(_curContext)] = attributes.value("associated-voice-idx").toInt(); _curSheet->addContext(_curContext); } else if (qName == "figured-bass-context") { // CAFiguredBassContext QString fbcName = attributes.value("name"); if (!_curSheet) { _errorMsg = "The sheet where to add the figured bass context doesn't exist yet!"; return false; } if (fbcName.isEmpty()) fbcName = QObject::tr("FiguredBassContext%1").arg(_curSheet->contextList().size() + 1); _curContext = new CAFiguredBassContext(fbcName, _curSheet); _curSheet->addContext(_curContext); } else if (qName == "function-mark-context" || qName == "function-marking-context") { // CAFunctionMarkContext QString fmcName = attributes.value("name"); if (!_curSheet) { _errorMsg = "The sheet where to add the function mark context doesn't exist yet!"; return false; } if (fmcName.isEmpty()) fmcName = QObject::tr("FunctionMarkContext%1").arg(_curSheet->contextList().size() + 1); _curContext = new CAFunctionMarkContext(fmcName, _curSheet); _curSheet->addContext(_curContext); } else if (qName == "chord-name-context") { // CAChordNameContext QString cncName = attributes.value("name"); if (!_curSheet) { _errorMsg = "The sheet where to add the chord name context doesn't exist yet!"; return false; } if (cncName.isEmpty()) cncName = QObject::tr("ChordNameContext%1").arg(_curSheet->contextList().size() + 1); _curContext = new CAChordNameContext(cncName, _curSheet); _curSheet->addContext(_curContext); } else if (qName == "voice") { // CAVoice QString voiceName = attributes.value("name"); if (!_curContext) { _errorMsg = "The context where the voice " + voiceName + " should be added doesn't exist yet!"; return false; } else if (_curContext->contextType() != CAContext::Staff) { _errorMsg = "The context type which contains voice " + voiceName + " isn't staff!"; return false; } CAStaff* staff = static_cast<CAStaff*>(_curContext); int voiceNumber = staff->voiceList().size() + 1; if (voiceName.isEmpty()) voiceName = QObject::tr("Voice%1").arg(voiceNumber); CANote::CAStemDirection stemDir = CANote::StemNeutral; if (!attributes.value("stem-direction").isEmpty()) stemDir = CANote::stemDirectionFromString(attributes.value("stem-direction")); _curVoice = new CAVoice(voiceName, staff, stemDir); if (!attributes.value("midi-channel").isEmpty()) { _curVoice->setMidiChannel(static_cast<unsigned char>(attributes.value("midi-channel").toUInt())); } if (!attributes.value("midi-program").isEmpty()) { _curVoice->setMidiProgram(static_cast<unsigned char>(attributes.value("midi-program").toUInt())); } if (!attributes.value("midi-pitch-offset").isEmpty()) { _curVoice->setMidiPitchOffset(static_cast<char>(attributes.value("midi-pitch-offset").toInt())); } staff->addVoice(_curVoice); } else if (qName == "clef") { // CAClef _curClef = new CAClef(CAClef::clefTypeFromString(attributes.value("clef-type")), attributes.value("c1").toInt(), _curVoice->staff(), attributes.value("time-start").toInt(), attributes.value("offset").toInt()); _curMusElt = _curClef; _curMusElt->setColor(_color); } else if (qName == "time-signature") { // CATimeSignature _curTimeSig = new CATimeSignature(attributes.value("beats").toInt(), attributes.value("beat").toInt(), _curVoice->staff(), attributes.value("time-start").toInt(), CATimeSignature::timeSignatureTypeFromString(attributes.value("time-signature-type"))); _curMusElt = _curTimeSig; _curMusElt->setColor(_color); } else if (qName == "key-signature") { // CAKeySignature CAKeySignature::CAKeySignatureType type = CAKeySignature::keySignatureTypeFromString(attributes.value("key-signature-type")); switch (type) { case CAKeySignature::MajorMinor: { _curKeySig = new CAKeySignature(CADiatonicKey(), _curVoice->staff(), attributes.value("time-start").toInt()); break; } case CAKeySignature::Modus: { _curKeySig = new CAKeySignature(CAKeySignature::modusFromString(attributes.value("modus")), _curVoice->staff(), attributes.value("time-start").toInt()); break; } case CAKeySignature::Custom: break; } _curMusElt = _curKeySig; _curMusElt->setColor(_color); } else if (qName == "barline") { // CABarline _curBarline = new CABarline(CABarline::barlineTypeFromString(attributes.value("barline-type")), _curVoice->staff(), attributes.value("time-start").toInt()); _curMusElt = _curBarline; } else if (qName == "note") { // CANote if (QVersionNumber(0, 5).isPrefixOf(_version)) { _curNote = new CANote(CADiatonicPitch(attributes.value("pitch").toInt(), attributes.value("accs").toInt()), CAPlayableLength(CAPlayableLength::musicLengthFromString(attributes.value("playable-length")), attributes.value("dotted").toInt()), _curVoice, attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); } else { _curNote = new CANote(CADiatonicPitch(), CAPlayableLength(), _curVoice, attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); } if (!attributes.value("stem-direction").isEmpty()) { _curNote->setStemDirection(CANote::stemDirectionFromString(attributes.value("stem-direction"))); } if (_curTuplet) { _curNote->setTuplet(_curTuplet); _curTuplet->addNote(_curNote); } _curMusElt = _curNote; _curMusElt->setColor(_color); } else if (qName == "tie") { _curTie = new CASlur(CASlur::TieType, CASlur::SlurPreferred, _curNote->staff(), _curNote, nullptr); _curNote->setTieStart(_curTie); if (!attributes.value("slur-style").isEmpty()) _curTie->setSlurStyle(CASlur::slurStyleFromString(attributes.value("slur-style"))); if (!attributes.value("slur-direction").isEmpty()) _curTie->setSlurDirection(CASlur::slurDirectionFromString(attributes.value("slur-direction"))); _prevMusElt = _curMusElt; _curMusElt = _curTie; _curMusElt->setColor(_color); } else if (qName == "slur-start") { _curSlur = new CASlur(CASlur::SlurType, CASlur::SlurPreferred, _curNote->staff(), _curNote, nullptr); _curNote->setSlurStart(_curSlur); if (!attributes.value("slur-style").isEmpty()) _curSlur->setSlurStyle(CASlur::slurStyleFromString(attributes.value("slur-style"))); if (!attributes.value("slur-direction").isEmpty()) _curSlur->setSlurDirection(CASlur::slurDirectionFromString(attributes.value("slur-direction"))); _prevMusElt = _curMusElt; _curMusElt = _curSlur; _curMusElt->setColor(_color); } else if (qName == "slur-end") { if (_curSlur) { _curNote->setSlurEnd(_curSlur); _curSlur->setNoteEnd(_curNote); _curSlur->setTimeLength(_curNote->timeStart() - _curSlur->noteStart()->timeStart()); _curSlur = nullptr; } } else if (qName == "phrasing-slur-start") { _curPhrasingSlur = new CASlur(CASlur::PhrasingSlurType, CASlur::SlurPreferred, _curNote->staff(), _curNote, nullptr); _curNote->setPhrasingSlurStart(_curPhrasingSlur); if (!attributes.value("slur-style").isEmpty()) _curPhrasingSlur->setSlurStyle(CASlur::slurStyleFromString(attributes.value("slur-style"))); if (!attributes.value("slur-direction").isEmpty()) _curPhrasingSlur->setSlurDirection(CASlur::slurDirectionFromString(attributes.value("slur-direction"))); _prevMusElt = _curMusElt; _curMusElt = _curPhrasingSlur; _curMusElt->setColor(_color); } else if (qName == "phrasing-slur-end") { if (_curPhrasingSlur) { _curNote->setPhrasingSlurEnd(_curPhrasingSlur); _curPhrasingSlur->setNoteEnd(_curNote); _curPhrasingSlur->setTimeLength(_curNote->timeStart() - _curPhrasingSlur->noteStart()->timeStart()); _curPhrasingSlur = nullptr; } } else if (qName == "tuplet") { _curTuplet = new CATuplet(attributes.value("number").toInt(), attributes.value("actual-number").toInt()); _curTuplet->setColor(_color); } else if (qName == "rest") { // CARest if (QVersionNumber(0, 5).isPrefixOf(_version)) { _curRest = new CARest(CARest::restTypeFromString(attributes.value("rest-type")), CAPlayableLength(CAPlayableLength::musicLengthFromString(attributes.value("playable-length")), attributes.value("dotted").toInt()), _curVoice, attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); } else { _curRest = new CARest(CARest::restTypeFromString(attributes.value("rest-type")), CAPlayableLength(), _curVoice, attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); } if (_curTuplet) { _curRest->setTuplet(_curTuplet); _curTuplet->addNote(_curRest); } _curMusElt = _curRest; _curMusElt->setColor(_color); } else if (qName == "syllable") { // CASyllable CASyllable* s = new CASyllable( attributes.value("text"), attributes.value("hyphen") == "1", attributes.value("melisma") == "1", static_cast<CALyricsContext*>(_curContext), attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); // Note: associatedVoice property is set when finishing parsing the sheet static_cast<CALyricsContext*>(_curContext)->addSyllable(s); if (!attributes.value("associated-voice-idx").isEmpty()) _syllableMap[s] = attributes.value("associated-voice-idx").toInt(); _curMusElt = s; _curMusElt->setColor(_color); } else if (qName == "figured-bass-mark") { // CAFiguredBassMark CAFiguredBassMark* f = new CAFiguredBassMark( static_cast<CAFiguredBassContext*>(_curContext), attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); static_cast<CAFiguredBassContext*>(_curContext)->addFiguredBassMark(f); _curMusElt = f; _curMusElt->setColor(_color); } else if (qName == "figured-bass-number") { // CAFiguredBassMark CAFiguredBassMark* f = static_cast<CAFiguredBassMark*>(_curMusElt); if (attributes.value("accs").isEmpty()) { f->addNumber(attributes.value("number").toInt()); } else { f->addNumber(attributes.value("number").toInt(), attributes.value("accs").toInt()); } } else if (qName == "function-mark" || (QVersionNumber(0, 5).isPrefixOf(_version) && qName == "function-marking")) { // CAFunctionMark CAFunctionMark* f = new CAFunctionMark( CAFunctionMark::functionTypeFromString(attributes.value("function")), (attributes.value("minor") == "1" ? true : false), (QVersionNumber(0, 5).isPrefixOf(_version) ? (attributes.value("key").isEmpty() ? "C" : attributes.value("key")) : CADiatonicKey()), static_cast<CAFunctionMarkContext*>(_curContext), attributes.value("time-start").toInt(), attributes.value("time-length").toInt(), CAFunctionMark::functionTypeFromString(attributes.value("chord-area")), (attributes.value("chord-area-minor") == "1" ? true : false), CAFunctionMark::functionTypeFromString(attributes.value("tonic-degree")), (attributes.value("tonic-degree-minor") == "1" ? true : false), "", (attributes.value("ellipse") == "1" ? true : false)); static_cast<CAFunctionMarkContext*>(_curContext)->addFunctionMark(f); _curMusElt = f; _curMusElt->setColor(_color); } else if (qName == "chord-name") { // CAChordName CAChordName* cn = new CAChordName( CADiatonicPitch(), attributes.value("quality-modifier"), static_cast<CAChordNameContext*>(_curContext), attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); _curMusElt = cn; _curMusElt->setColor(_color); } else if (qName == "mark") { // CAMark and subvariants importMark(attributes); _curMark->setColor(_color); } else if (qName == "playable-length") { CAPlayableLength pl = CAPlayableLength(CAPlayableLength::musicLengthFromString(attributes.value("music-length")), attributes.value("dotted").toInt()); if (_depth.top() == "mark") { _curTempoPlayableLength = pl; } else { _curPlayableLength = pl; } } else if (qName == "diatonic-pitch") { _curDiatonicPitch = CADiatonicPitch(attributes.value("note-name").toInt(), attributes.value("accs").toInt()); } else if (qName == "diatonic-key") { _curDiatonicKey = CADiatonicKey(CADiatonicPitch(), CADiatonicKey::genderFromString(attributes.value("gender"))); } else if (qName == "resource") { importResource(attributes); } _depth.push(qName); return true; } /*! This function is called automatically by Qt SAX parser while reading the CanorusML source. This function is called when a node has been closed (\</nodeName\>). Attributes for closed notes are usually not set in CanorusML format. That's why we need to store local node attributes (set when the node is opened) each time. The function returns true, if the node was successfully recognized and parsed; otherwise false. \sa startElement() */ bool CACanorusMLImport::endElement(const QString&, const QString&, const QString& qName) { if (qName == "canorus-version") { // version of Canorus which saved the document _version = QVersionNumber::fromString(_cha); } else if (qName == "document") { //fix voice errors like shared voice elements not being present in both voices etc. for (int i = 0; _document && i < _document->sheetList().size(); i++) { for (int j = 0; j < _document->sheetList()[i]->staffList().size(); j++) { _document->sheetList()[i]->staffList()[j]->synchronizeVoices(); } } } else if (qName == "sheet") { // CASheet QList<CAVoice*> voices = _curSheet->voiceList(); QList<CALyricsContext*> lcs = _lcMap.keys(); for (int i = 0; i < lcs.size(); i++) // assign voices from voice indices lcs.at(i)->setAssociatedVoice(voices.at(_lcMap[lcs[i]])); QList<CASyllable*> syllables = _syllableMap.keys(); for (int i = 0; i < syllables.size(); i++) { // assign voices from voice indices if (_syllableMap[syllables[i]] >= 0 && _syllableMap[syllables[i]] < voices.count()) { syllables.at(i)->setAssociatedVoice(voices.at(_syllableMap[syllables[i]])); } } _lcMap.clear(); _syllableMap.clear(); _curSheet = nullptr; } else if (qName == "staff") { // CAStaff _curContext = nullptr; } else if (qName == "voice") { // CAVoice _curVoice = nullptr; } // Every voice *must* contain signs on their own (eg. a clef is placed in all voices, not just the first one). // The following code finds a sign with the same properties at the same time in other voices. If such a sign exists, only place a pointer to this sign in the current voice. Otherwise, add a sign to all the voices read so far. else if (qName == "clef") { // CAClef if (!_curContext || !_curVoice || _curContext->contextType() != CAContext::Staff) { return false; } // lookup an element with the same type at the same time QList<CAMusElement*> foundElts = static_cast<CAStaff*>(_curContext)->getEltByType(CAMusElement::Clef, _curClef->timeStart()); CAMusElement* sign = nullptr; for (int i = 0; i < foundElts.size(); i++) { if (!foundElts[i]->compare(_curClef)) // element has exactly the same properties if (!_curVoice->musElementList().contains(foundElts[i])) { // if such an element already exists, it means there are two different with the same timestart sign = foundElts[i]; break; } } if (!sign) { // the element doesn't exist yet - add it to all the voices _curVoice->append(_curClef); } else { //the element was found, insert only a reference to the current voice _curVoice->append(sign); delete _curClef; _curClef = nullptr; } } else if (qName == "key-signature") { // CAKeySignature if (!_curContext || !_curVoice || _curContext->contextType() != CAContext::Staff) { return false; } switch (_curKeySig->keySignatureType()) { case CAKeySignature::MajorMinor: _curKeySig->setDiatonicKey(_curDiatonicKey); break; case CAKeySignature::Modus: case CAKeySignature::Custom: break; } // lookup an element with the same type at the same time QList<CAMusElement*> foundElts = static_cast<CAStaff*>(_curContext)->getEltByType(CAMusElement::KeySignature, _curKeySig->timeStart()); CAMusElement* sign = nullptr; for (int i = 0; i < foundElts.size(); i++) { if (!foundElts[i]->compare(_curKeySig)) // element has exactly the same properties if (!_curVoice->musElementList().contains(foundElts[i])) { // if such an element already exists, it means there are two different with the same timestart sign = foundElts[i]; break; } } if (!sign) { // the element doesn't exist yet - add it to all the voices _curVoice->append(_curKeySig); } else { // the element was found, insert only a reference to the current voice _curVoice->append(sign); delete _curKeySig; _curKeySig = nullptr; } } else if (qName == "time-signature") { // CATimeSignature if (!_curContext || !_curVoice || _curContext->contextType() != CAContext::Staff) { return false; } // lookup an element with the same type at the same time QList<CAMusElement*> foundElts = static_cast<CAStaff*>(_curContext)->getEltByType(CAMusElement::TimeSignature, _curTimeSig->timeStart()); CAMusElement* sign = nullptr; for (int i = 0; i < foundElts.size(); i++) { if (!foundElts[i]->compare(_curTimeSig)) // element has exactly the same properties if (!_curVoice->musElementList().contains(foundElts[i])) { // if such an element already exists, it means there are two different with the same timestart sign = foundElts[i]; break; } } if (!sign) { // the element doesn't exist yet - add it to all the voices _curVoice->append(_curTimeSig); } else { // the element was found, insert only a reference to the current voice _curVoice->append(sign); delete _curTimeSig; _curTimeSig = nullptr; } } else if (qName == "barline") { // CABarline if (!_curContext || !_curVoice || _curContext->contextType() != CAContext::Staff) { return false; } // lookup an element with the same type at the same time QList<CAMusElement*> foundElts = static_cast<CAStaff*>(_curContext)->getEltByType(CAMusElement::Barline, _curBarline->timeStart()); CAMusElement* sign = nullptr; for (int i = 0; i < foundElts.size(); i++) { if (!foundElts[i]->compare(_curBarline)) // element has exactly the same properties if (!_curVoice->musElementList().contains(foundElts[i])) { // if such an element already exists, it means there are two different with the same timestart sign = foundElts[i]; break; } } if (!sign) { // the element doesn't exist yet - add it to all the voices _curVoice->append(_curBarline); } else { // the element was found, insert only a reference to the current voice _curVoice->append(sign); delete _curBarline; _curBarline = nullptr; } } else if (qName == "note") { // CANote if (QVersionNumber(0, 5).isPrefixOf(_version)) { } else { _curNote->setPlayableLength(_curPlayableLength); if (!_curNote->tuplet()) { _curNote->calculateTimeLength(); } _curNote->setDiatonicPitch(_curDiatonicPitch); } if (_curVoice->lastNote() && _curVoice->lastNote()->timeStart() == _curNote->timeStart()) _curVoice->append(_curNote, true); else _curVoice->append(_curNote, false); _curNote->updateTies(); _curNote = nullptr; } else if (qName == "tie") { // CASlur - tie } else if (qName == "tuplet") { _curTuplet->assignTimes(); _curTuplet = nullptr; } else if (qName == "rest") { // CARest if (QVersionNumber(0, 5).isPrefixOf(_version)) { } else { _curRest->setPlayableLength(_curPlayableLength); if (!_curRest->tuplet()) { _curRest->calculateTimeLength(); } } _curVoice->append(_curRest); _curRest = nullptr; } else if (qName == "mark") { if (!QVersionNumber(0, 5).isPrefixOf(_version) && _curMark->markType() == CAMark::Tempo) { static_cast<CATempo*>(_curMark)->setBeat(_curTempoPlayableLength); } } else if (qName == "function-mark") { if (!QVersionNumber(0, 5).isPrefixOf(_version) && _curMusElt->musElementType() == CAMusElement::FunctionMark) { static_cast<CAFunctionMark*>(_curMusElt)->setKey(_curDiatonicKey); } } else if (qName == "diatonic-key") { _curDiatonicKey.setDiatonicPitch(_curDiatonicPitch); } else if (qName == "chord-name") { CAChordName* cn = static_cast<CAChordName*>(_curMusElt); cn->setDiatonicPitch(_curDiatonicPitch); static_cast<CAChordNameContext*>(_curContext)->addChordName(cn); } _cha = ""; _depth.pop(); if (_prevMusElt) { _curMusElt = _prevMusElt; _prevMusElt = nullptr; } return true; } /*! Stores the characters between the greater-lesser signs while parsing the XML file. This is usually needed for getting the property values stored not as node attributes, but between greater-lesser signs. eg. \code <length>127</length> \endcode Would set _cha value to "127". \sa startElement(), endElement() */ bool CACanorusMLImport::characters(const QString& ch) { _cha = ch; return true; } void CACanorusMLImport::importMark(const QXmlAttributes& attributes) { CAMark::CAMarkType type = CAMark::markTypeFromString(attributes.value("mark-type")); _curMark = nullptr; switch (type) { case CAMark::Text: { _curMark = new CAText( attributes.value("text"), static_cast<CAPlayable*>(_curMusElt)); break; } case CAMark::Tempo: { if (QVersionNumber(0, 5).isPrefixOf(_version)) { _curMark = new CATempo( CAPlayableLength(CAPlayableLength::musicLengthFromString(attributes.value("beat")), attributes.value("beat-dotted").toInt()), static_cast<unsigned char>(attributes.value("bpm").toUInt()), _curMusElt); } else { _curMark = new CATempo( CAPlayableLength(), static_cast<unsigned char>(attributes.value("bpm").toUInt()), _curMusElt); } break; } case CAMark::Ritardando: { _curMark = new CARitardando( attributes.value("final-tempo").toInt(), static_cast<CAPlayable*>(_curMusElt), attributes.value("time-length").toInt(), CARitardando::ritardandoTypeFromString(attributes.value("ritardando-type"))); break; } case CAMark::Dynamic: { _curMark = new CADynamic( attributes.value("text"), attributes.value("volume").toInt(), static_cast<CANote*>(_curMusElt)); break; } case CAMark::Crescendo: { _curMark = new CACrescendo( attributes.value("final-volume").toInt(), static_cast<CANote*>(_curMusElt), CACrescendo::crescendoTypeFromString(attributes.value("crescendo-type")), attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); break; } case CAMark::Pedal: { _curMark = new CAMark( CAMark::Pedal, _curMusElt, attributes.value("time-start").toInt(), attributes.value("time-length").toInt()); break; } case CAMark::InstrumentChange: { _curMark = new CAInstrumentChange( attributes.value("instrument").toInt(), static_cast<CANote*>(_curMusElt)); break; } case CAMark::BookMark: { _curMark = new CABookMark( attributes.value("text"), _curMusElt); break; } case CAMark::RehersalMark: { _curMark = new CAMark( CAMark::RehersalMark, _curMusElt); break; } case CAMark::Fermata: { if (_curMusElt->isPlayable()) { _curMark = new CAFermata( static_cast<CAPlayable*>(_curMusElt), CAFermata::fermataTypeFromString(attributes.value("fermata-type"))); } else if (_curMusElt->musElementType() == CAMusElement::Barline) { _curMark = new CAFermata( static_cast<CABarline*>(_curMusElt), CAFermata::fermataTypeFromString(attributes.value("fermata-type"))); } break; } case CAMark::RepeatMark: { _curMark = new CARepeatMark( static_cast<CABarline*>(_curMusElt), CARepeatMark::repeatMarkTypeFromString(attributes.value("repeat-mark-type")), attributes.value("volta-number").toInt()); break; } case CAMark::Articulation: { _curMark = new CAArticulation( CAArticulation::articulationTypeFromString(attributes.value("articulation-type")), static_cast<CANote*>(_curMusElt)); break; } case CAMark::Fingering: { QList<CAFingering::CAFingerNumber> fingers; for (int i = 0; !attributes.value(QString("finger%1").arg(i)).isEmpty(); i++) fingers << CAFingering::fingerNumberFromString(attributes.value(QString("finger%1").arg(i))); _curMark = new CAFingering( fingers, static_cast<CANote*>(_curMusElt), attributes.value("original").toInt()); break; } case CAMark::Undefined: break; } if (_curMark) { _curMusElt->addMark(_curMark); } } /*! Imports the current resource. */ void CACanorusMLImport::importResource(const QXmlAttributes& attributes) { bool isLinked = attributes.value("linked").toInt(); std::shared_ptr<CAResource> r; QUrl url = attributes.value("url"); QString name = attributes.value("name"); QString description = attributes.value("description"); CAResource::CAResourceType type = CAResource::resourceTypeFromString(attributes.value("resource-type")); QString rUrl = url.toString(); if (!isLinked && file()) { rUrl = QFileInfo(file()->fileName()).absolutePath() + "/" + url.toLocalFile(); } r = CAResourceCtl::importResource(name, rUrl, isLinked, _document, type); r->setDescription(description); } /*! \fn CACanorusMLImport::document() Returns the newly created document when reading the XML file. */ /*! \var CACanorusMLImport::_cha Current characters being read using characters() method between the greater/lesser separators in XML file. \sa characters() */ /*! \var CACanorusMLImport::_depth Stack which represents the current depth of the document while SAX parsing. It contains the tag names as the values. \sa startElement(), endElement() */ /*! \var CACanorusMLImport::_errorMsg The error message content stored as QString, if the error happens. \sa fatalError() */ /*! \var CACanorusMLImport::_version Document program version - which Canorus saved the file? \sa startElement(), endElement() */ /*! \var CACanorusMLImport::_document Pointer to the document being read. \sa CADocument */
36,765
C++
.cpp
851
34.715629
229
0.620775
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,292
mxlimport.cpp
canorusmusic_canorus/src/import/mxlimport.cpp
/*! Copyright (c) 2018, Matevž Jekovec, Reinhard Katzmann, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "import/mxlimport.h" #include <QDebug> #include <QDir> #include <iostream> // debug CAMXLImport::CAMXLImport(QTextStream* stream) : CAMusicXmlImport(stream) { } CAMXLImport::CAMXLImport(const QString stream) : CAMusicXmlImport(stream) { } CAMXLImport::~CAMXLImport() { } CADocument* CAMXLImport::importDocumentImpl() { int arg = 2; _zipArchivePath = fileName(); // Extract whole archive to temp folder zip_extract(fileName().toLatin1().constData(), QDir::tempPath().toLatin1().constData(), [](const char* filename, void* arg) { static int i = 0; int n = *static_cast<int*>(arg); qDebug().noquote() << "Extracted: " << filename << "(" << ++i << " of " << n << ")\n"; return 0; }, &arg); QFileInfo containerInfo(QDir::tempPath() + QString("/META-INF/container.xml")); QString musicXMLFileName; bool eocRes = openContainer(containerInfo); if (eocRes) { eocRes = readContainerInfo(musicXMLFileName); QFileInfo musicXMLFileInfo(QDir::tempPath() + "/" + musicXMLFileName); if (musicXMLFileInfo.exists()) { setStreamFromFile(musicXMLFileInfo.filePath()); return CAMusicXmlImport::importDocumentImpl(); } qDebug() << "Failed to find musicxml file " << musicXMLFileInfo.filePath() << " in archive"; } return nullptr; } bool CAMXLImport::openContainer(const QFileInfo& containerInfo) { if (containerInfo.exists()) { setStreamFromFile(containerInfo.filePath()); } else { qDebug() << "Failed to find container file " << containerInfo.filePath() << " in archive"; return false; } return true; } bool CAMXLImport::readContainerInfo(QString& musicXMLFileName) { QString containerLine, rootFileLine, mediaTypeLine, fullPathLine; do { containerLine = stream()->readLine(); if (containerLine.contains("<rootfiles")) { do { // No check for <rootfile> to make logic easier (strictly it's required) rootFileLine = stream()->readLine(); if (rootFileLine.contains("full-path")) { fullPathLine = rootFileLine; if (mediaTypeLine.contains("application/vnd.recordare.musicxml+xml")) { break; } } if (rootFileLine.contains("<rootfile")) { if (rootFileLine.contains("media-type")) { mediaTypeLine = rootFileLine; if (!mediaTypeLine.contains("application/vnd.recordare.musicxml+xml")) { fullPathLine.clear(); continue; } if (!fullPathLine.isNull()) break; } } } while (!rootFileLine.isNull()); } } while (!containerLine.isNull()); if (!mediaTypeLine.contains("application/vnd.recordare.musicxml+xml") || fullPathLine.isNull()) { qDebug() << "No musicxml media " << mediaTypeLine << " found in container " << fullPathLine; return false; } QString fullPathStr = "full-path"; int pos = fullPathLine.lastIndexOf(fullPathStr) + fullPathStr.length(); int lastPos = fullPathLine.indexOf("\"", pos + 2); int num = lastPos - pos - 2; musicXMLFileName = fullPathLine.mid(pos + 2, num); //qDebug() << "pos " << pos << " num " << num << " last " << lastPos << " fileName " << musicXMLFileName; return true; }
3,810
C++
.cpp
96
31.34375
129
0.606641
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,293
import.cpp
canorusmusic_canorus/src/import/import.cpp
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "import/import.h" #include <QTextStream> /*! \class CAImport \brief Base class for import filters This class inherits CAFile and is the base class for any specific import filter (eg. LilyPond, CanorusML, MusicXML etc.). If a developer wants to write a new import filter, he should: 1) Create a new class with the base class CAImport 2) Implement CAImport constructors and at least importDocumentImpl() function which returns the new CADocument. 3) Register the filter (put a new fileformat to CAFileFormats and add the filter to open/save dialogs in CACanorus) Optionally: Developer should change the current status and progress while operations are in progress. He should also rewrite the readableStatus() function. The following example illustrates the usage of import class: \code CAMyImportFilter import(); import.setStreamFromFile("jingle bells.xml"); import.importDocument(); import.wait(); setDocument( import.importedDocument() ); CACanorus::rebuildUI(); \endcode In Python the example is even more direct using the string as an input method: \code lilyString = '\\relative c { \\clef "treble" \\time 4/4 c4 d e f | f e d c | c1 \\bar "|." }' myImport = CALilyPondImport( lilyString ) myImport.importVoice() myImport.wait() voice = myImport.importedVoice() \endcode \note Both stream and string can be used both in Canorus and scripting. The example is only for illustration. */ CAImport::CAImport(QTextStream* stream) : CAFile() { setStream(stream); setImportPart(Undefined); setImportedDocument(nullptr); setImportedSheet(nullptr); setImportedStaff(nullptr); setImportedVoice(nullptr); setImportedLyricsContext(nullptr); setImportedFunctionMarkContext(nullptr); _fileName.clear(); } CAImport::CAImport(const QString stream) : CAFile() { setStream(new QTextStream(new QString(stream))); setImportPart(Undefined); setImportedDocument(nullptr); setImportedSheet(nullptr); setImportedStaff(nullptr); setImportedVoice(nullptr); setImportedLyricsContext(nullptr); setImportedFunctionMarkContext(nullptr); } CAImport::~CAImport() { if (stream() && stream()->string()) { delete stream()->string(); } } /*! Extends CAFile::setStreamFromFile by storing the filename in a public variable for use in the pmidi midi file parser. */ void CAImport::setStreamFromFile(const QString filename) { _fileName = filename; CAFile::setStreamFromFile(filename); } QString CAImport::fileName() { return _fileName; } /*! Executed when a new thread is dispatched. It looks which part of the document should be imported and starts the procedure. It emits the appropriate signal when the procedure is finished. */ void CAImport::run() { if (!stream()) { setStatus(-1); } else { switch (importPart()) { case Document: { CADocument* doc = importDocumentImpl(); setImportedDocument(doc); emit documentImported(doc); break; } case Sheet: { CASheet* sheet = importSheetImpl(); setImportedSheet(sheet); emit sheetImported(sheet); break; } case Staff: { CAStaff* staff = importStaffImpl(); setImportedStaff(staff); emit staffImported(staff); break; } case Voice: { CAVoice* voice = importVoiceImpl(); setImportedVoice(voice); emit voiceImported(voice); break; } case LyricsContext: { CALyricsContext* lc = importLyricsContextImpl(); setImportedLyricsContext(lc); emit lyricsContextImported(lc); break; } case FunctionMarkContext: { CAFunctionMarkContext* fmc = importFunctionMarkContextImpl(); setImportedFunctionMarkContext(fmc); emit functionMarkContextImported(fmc); break; } case Undefined: break; } if (status() > 0) { // error - bad implemented filter // job is finished but status is still marked as working, set to Ready to prevent infinite loops setStatus(0); } } emit importDone(status()); } void CAImport::importDocument() { setImportPart(Document); setStatus(1); // process started start(); } void CAImport::importSheet() { setImportPart(Sheet); setStatus(1); // process started start(); } void CAImport::importStaff() { setImportPart(Staff); setStatus(1); // process started start(); } void CAImport::importVoice() { setImportPart(Voice); setStatus(1); // process started start(); } void CAImport::importLyricsContext() { setImportPart(LyricsContext); setStatus(1); // process started start(); } void CAImport::importFunctionMarkContext() { setImportPart(FunctionMarkContext); setStatus(1); // process started start(); } const QString CAImport::readableStatus() { switch (status()) { case 1: return tr("Importing"); case 0: return tr("Ready"); case -1: return tr("Unable to open file for reading"); } return "Ready"; }
5,543
C++
.cpp
189
23.994709
110
0.682665
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,294
lilypondimport.cpp
canorusmusic_canorus/src/import/lilypondimport.cpp
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QFileInfo> #include <QRegExp> #include <QTextStream> #include <iostream> // DEBUG #include "import/lilypondimport.h" #include "score/note.h" #include "score/playable.h" #include "score/sheet.h" #include "score/slur.h" /*! Delimiters which separate various music elements in LilyPond syntax. These are new lines, tabs, blanks etc. \sa nextElement(), parseNextElement() */ const QRegExp CALilyPondImport::WHITESPACE_DELIMITERS = QRegExp("[\\s]"); /*! Delimiters which separate various music elements in LilyPond syntax, but are specific for LilyPond syntax. They are reported as its own element when parsing the next element. \sa nextElement(), parseNextElement() */ const QRegExp CALilyPondImport::SYNTAX_DELIMITERS = QRegExp("[<>{}]"); /*! Combined WHITESPACE_DELIMITERS and SYNTAX_DELIMITERS. */ const QRegExp CALilyPondImport::DELIMITERS = QRegExp( CALilyPondImport::WHITESPACE_DELIMITERS.pattern().left(CALilyPondImport::WHITESPACE_DELIMITERS.pattern().size() - 1) + CALilyPondImport::SYNTAX_DELIMITERS.pattern().mid(1)); CALilyPondImport::CALilyPondImport(const QString in) : CAImport(in) { initLilyPondImport(); } CALilyPondImport::CALilyPondImport(QTextStream* in) : CAImport(in) { initLilyPondImport(); } CALilyPondImport::CALilyPondImport(CADocument* document, QTextStream* in) : CAImport(in) { _document = document; initLilyPondImport(); } CALilyPondImport::~CALilyPondImport() { } void CALilyPondImport::initLilyPondImport() { _curLine = _curChar = 0; _curSlur = nullptr; _curPhrasingSlur = nullptr; _templateVoice = nullptr; } void CALilyPondImport::addError(QString description, int curLine, int curChar) { _errors << QString(QObject::tr("<i>Fatal error, line %1, char %2:</i><br>")) .arg(curLine ? curLine : _curLine) .arg(curChar ? curChar : _curChar) + description + "<br>"; } CASheet* CALilyPondImport::importSheetImpl() { CASheet* sheet = new CASheet(tr("Lilypond imported sheet"), _document); QFileInfo fi(fileName()); sheet->setName(fi.baseName()); (*stream()).setCodec("UTF-8"); QString text(*stream()->string()); // To activate this import code uncomment in src/canorus.cpp this line: //CAMainWin::uiImportDialog->setFilters( CAMainWin::uiImportDialog->filters() << CAFileFormats::LILYPOND_FILTER ); // FIXME this is work in progress. Why we get here a crash? // std::cout << qPrintable( text ); // Note Reinhard: broken code, merge issue ? //return sheet; bool changed = false; for (QString curElt = parseNextElement(); (!in().isEmpty()); curElt = ((curElt.size() && changed) ? curElt : parseNextElement())) { // go to next element, if current one is empty or not changed if (curElt.startsWith("\\header")) { std::cout << "lilyimport header" << std::endl; } if (curElt.startsWith("\\relative")) { std::cout << "lilyimport relative" << std::endl; } changed = true; } return sheet; } CAVoice* CALilyPondImport::importVoiceImpl() { CAVoice* voice = new CAVoice("", nullptr); if (templateVoice()) voice->cloneVoiceProperties(templateVoice()); setCurVoice(voice); CADiatonicPitch prevPitch(21, 0); CAPlayableLength prevLength(CAPlayableLength::Quarter, 0); bool chordCreated = false; bool changed = false; for (QString curElt = parseNextElement(); (!in().isEmpty()); curElt = ((curElt.size() && changed) ? curElt : parseNextElement())) { // go to next element, if current one is empty or not changed changed = true; // changed is default to true and false, if none of if clauses were found if (curElt.startsWith("\\relative")) { // initial \relative notePitch QString notePitch = parseNextElement(); if (!isNote(notePitch)) { addError("\\relative doesn't include pitch."); continue; } prevPitch = relativePitchFromLilyPond(notePitch, 21); curElt.remove(0, 9); } else if (curElt.startsWith("{")) { // start of the voice pushDepth(Voice); curElt.remove(0, 1); } else if (curElt.startsWith("}")) { // end of the voice popDepth(); curElt.remove(0, 1); } else if (curElt.startsWith("<")) { // start of the chord pushDepth(Chord); curElt.remove(0, 1); } else if (curElt.startsWith(">")) { // end of the chord popDepth(); chordCreated = false; if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { prevPitch = static_cast<CANote*>(curVoice()->lastMusElement())->getChord().at(0)->diatonicPitch(); } else { addError(QString("Chord should be finished with a note.")); } curElt.remove(0, 1); } else if (curElt.startsWith("~")) { if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { CANote* note = static_cast<CANote*>(curVoice()->lastMusElement()); note->setTieStart( new CASlur(CASlur::TieType, CASlur::SlurPreferred, note->staff(), note, nullptr)); } else { addError(QString("Tie symbol must be right after the note and not %1. Tie ignored.").arg(CAMusElement::musElementTypeToString(curVoice()->lastMusElement()->musElementType()))); } curElt.remove(0, 1); } else if (curElt.startsWith("(")) { if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { CANote* note = static_cast<CANote*>(curVoice()->lastMusElement())->getChord().at(0); _curSlur = new CASlur(CASlur::SlurType, CASlur::SlurPreferred, note->staff(), note, nullptr); note->setSlurStart(_curSlur); } else { addError(QString("Slur symbol must be right after the note and not %1. Slur ignored.").arg(CAMusElement::musElementTypeToString(curVoice()->lastMusElement()->musElementType()))); } curElt.remove(0, 1); } else if (curElt.startsWith(")") && _curSlur) { if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { CANote* note = static_cast<CANote*>(curVoice()->lastMusElement())->getChord().at(0); note->setSlurEnd(_curSlur); _curSlur->setNoteEnd(note); _curSlur = nullptr; } else { addError(QString("Slur symbol must be right after the note and not %1. Slur ignored.").arg(CAMusElement::musElementTypeToString(curVoice()->lastMusElement()->musElementType()))); } curElt.remove(0, 1); } else if (curElt.startsWith("\\(")) { if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { CANote* note = static_cast<CANote*>(curVoice()->lastMusElement())->getChord().at(0); _curPhrasingSlur = new CASlur(CASlur::PhrasingSlurType, CASlur::SlurPreferred, note->staff(), note, nullptr); note->setPhrasingSlurStart(_curPhrasingSlur); } else { addError(QString("Phrasing slur symbol must be right after the note and not %1. Phrasing slur ignored.").arg(CAMusElement::musElementTypeToString(curVoice()->lastMusElement()->musElementType()))); } curElt.remove(0, 2); } else if (curElt.startsWith("\\)") && _curPhrasingSlur) { if (curVoice()->lastMusElement()->musElementType() == CAMusElement::Note) { CANote* note = static_cast<CANote*>(curVoice()->lastMusElement())->getChord().at(0); note->setPhrasingSlurEnd(_curPhrasingSlur); _curPhrasingSlur->setNoteEnd(note); _curPhrasingSlur = nullptr; } else { addError(QString("Phrasing slur symbol must be right after the note and not %1. Phrasing slur ignored.").arg(CAMusElement::musElementTypeToString(curVoice()->lastMusElement()->musElementType()))); } curElt.remove(0, 2); } else if (isNote(curElt)) { // CANote prevPitch = relativePitchFromLilyPond(curElt, prevPitch, true); CAPlayableLength length = playableLengthFromLilyPond(curElt, true); if (length.musicLength() != CAPlayableLength::Undefined) // length may not be set prevLength = length; CANote* note; if (curDepth() != Chord || !chordCreated) { // the note is not part of the chord or is the first note in the chord note = new CANote(prevPitch, prevLength, curVoice(), curVoice()->lastTimeEnd()); if (curDepth() == Chord) chordCreated = true; curVoice()->append(note, false); } else { // the note is part of the already built chord note = new CANote(prevPitch, prevLength, curVoice(), curVoice()->lastTimeStart()); curVoice()->append(note, true); } note->updateTies(); // close any opened ties if present } else if (isRest(curElt)) { // CARest CARest::CARestType type = restTypeFromLilyPond(curElt, true); CAPlayableLength length = playableLengthFromLilyPond(curElt, true); if (length.musicLength() != CAPlayableLength::Undefined) // length may not be set prevLength = length; curVoice()->append(new CARest(type, prevLength, curVoice(), curVoice()->lastTimeEnd())); } else if (curElt.startsWith("|")) { // CABarline::Single // lookup an element with the same type at the same time CABarline* bar = new CABarline(CABarline::Single, curVoice()->staff(), curVoice()->lastTimeEnd()); CABarline* sharedBar = static_cast<CABarline*>(findSharedElement(bar)); if (!sharedBar) { curVoice()->append(bar); } else { curVoice()->append(sharedBar); delete bar; } curElt.remove(0, 1); } else if (curElt.startsWith("\\bar")) { // CABarline QString typeString = peekNextElement(); CABarline::CABarlineType type = barlineTypeFromLilyPond(peekNextElement()); if (type == CABarline::Undefined) { addError(QString("Error while parsing barline type. Barline type %1 unknown.").arg(typeString)); } // remove clef type from the input parseNextElement(); // lookup an element with the same type at the same time CABarline* bar = new CABarline(type, curVoice()->staff(), curVoice()->lastTimeEnd()); CABarline* sharedBar = static_cast<CABarline*>(findSharedElement(bar)); if (!sharedBar) { curVoice()->append(bar); } else { curVoice()->append(sharedBar); delete bar; } curElt.remove(0, 4); } else if (curElt.startsWith("\\clef")) { // CAClef QString typeString = peekNextElement(); CAClef::CAPredefinedClefType type = predefinedClefTypeFromLilyPond(peekNextElement()); int offset = clefOffsetFromLilyPond(peekNextElement()); if (type == CAClef::Undefined) { addError(QString("Error while parsing clef type. Clef type %1 unknown.").arg(typeString)); } // remove clef type from the input parseNextElement(); CAClef* clef = new CAClef(type, curVoice()->staff(), curVoice()->lastTimeEnd(), offset); CAClef* sharedClef = static_cast<CAClef*>(findSharedElement(clef)); if (!sharedClef) { curVoice()->append(clef); } else { curVoice()->append(sharedClef); delete clef; } curElt.remove(0, 5); } else if (curElt == "\\key") { // CAKeySignature // pitch QString keyString = peekNextElement(); if (!isNote(keyString)) { addError(QString("Error while parsing key signature. Key pitch %1 unknown.").arg(keyString)); continue; } parseNextElement(); // remove pitch // gender QString genderString = peekNextElement(); CADiatonicKey::CAGender gender = diatonicKeyGenderFromLilyPond(genderString); parseNextElement(); CAKeySignature* keySig = new CAKeySignature(CADiatonicKey(relativePitchFromLilyPond(keyString, CADiatonicPitch(3)), gender), curVoice()->staff(), curVoice()->lastTimeEnd()); CAKeySignature* sharedKeySig = static_cast<CAKeySignature*>(findSharedElement(keySig)); if (!sharedKeySig) { curVoice()->append(keySig); } else { curVoice()->append(sharedKeySig); delete keySig; } curElt.remove(0, 4); } else if (curElt.startsWith("\\time")) { // CATimeSignature QString timeString = peekNextElement(); // time signature should have beats/beat format if (timeString.indexOf(QRegExp("\\d+/\\d+")) == -1) { addError(QString("Invalid time signature beats format %1. Beat and number of beats should be written <beats>/<beat>.").arg(timeString)); continue; } CATime time = timeSigFromLilyPond(timeString); parseNextElement(); CATimeSignature* timeSig = new CATimeSignature(time.beats, time.beat, curVoice()->staff(), curVoice()->lastTimeEnd()); CATimeSignature* sharedTimeSig = static_cast<CATimeSignature*>(findSharedElement(timeSig)); if (!sharedTimeSig) { curVoice()->append(timeSig); } else { curVoice()->append(sharedTimeSig); delete timeSig; } curElt.remove(0, 5); } else changed = false; } return voice; } CALyricsContext* CALilyPondImport::importLyricsContextImpl() { CALyricsContext* lc = new CALyricsContext("", 1, static_cast<CASheet*>(nullptr)); CASyllable* lastSyllable = nullptr; int timeSDummy = 0; // dummy timestart to keep the order of inserted syllables. Real timeStarts are sets when repositSyllables() is called for (QString curElt = parseNextElement(); (!in().isEmpty() || !curElt.isEmpty()); curElt = parseNextElement(), timeSDummy++) { QString text = curElt; if (curElt == "_") text = ""; if (lastSyllable && text == "--") { lastSyllable->setHyphenStart(true); } else if (lastSyllable && text == "__") { lastSyllable->setMelismaStart(true); } else { if (text.length() > 0 && text[0] == '"') { while (!text.endsWith('"') && peekNextElement() != "") { text += QString(" ") + parseNextElement(); } text.remove(0, 1); if (text.endsWith('"')) { text.chop(1); } text.replace("\\\"", "\""); text.replace(" ", "_"); } lc->addSyllable(lastSyllable = new CASyllable(text, false, false, lc, timeSDummy, 0)); } } lc->repositionElements(); // sets syllables timeStarts and timeLengths return lc; } /*! Returns the first element in input stream ended with one of the delimiters and shorten input stream for the element. \todo Only one-character syntax delimiters are supported so far. \sa peekNextElement() */ const QString CALilyPondImport::parseNextElement() { // find the first non-whitespace character int start = in().indexOf(QRegExp("\\S")); if (start == -1) { start = 0; } else if (in().mid(start, 1) == "%") { // handle comments start = in().indexOf(QRegExp("[\n\r]"), start); if (start == -1) { start = in().size(); } else { start = in().indexOf(QRegExp("\\S"), start); if (start == -1) { start = in().size(); } } } int i = in().indexOf(DELIMITERS, start); if (i == -1) { i = in().size(); } QString ret; if (i == start) { // syntax delimiter only ret = in().mid(start, 1); /// \todo Support for syntax delimiters longer than 1 character in().remove(0, start + 1); } else { // ordinary whitespace/syntax delimiter ret = in().mid(start, i - start); in().remove(0, i); } return ret; } /*! Returns the first element in input stream ended with one of the delimiters but don't shorten the stream. \sa parseNextElement() */ const QString CALilyPondImport::peekNextElement() { // find the first non-whitespace character int start = in().indexOf(QRegExp("\\S")); if (start == -1) { start = 0; } else if (in().mid(start, 1) == "%") { // handle comments start = in().indexOf(QRegExp("[\n\r]"), start); if (start == -1) { start = in().size(); } else { start = in().indexOf(QRegExp("\\S"), start); if (start == -1) { start = in().size(); } } } int i = in().indexOf(DELIMITERS, start); if (i == -1) i = in().size(); QString ret; if (i == start) { // syntax delimiter only ret = in().left(1); /// \todo } else { // ordinary whitespace/syntax delimiter ret = in().mid(start, i - start); } return ret; } /*! Gathers a list of music elements with the given element's start time and returns the first music element in the gathered list with the same attributes. This method is usually called when voices have "shared" music elements (barlines, clefs etc.). However, in LilyPond syntax the music element can/should be present in all the voices. This function finds this shared music element, if it already exists. If the music element with the same properties exists, user should delete its own instance and add an already existing instance of the returned shared music element to the voice. \sa CAMusElement::compare() */ CAMusElement* CALilyPondImport::findSharedElement(CAMusElement* elt) { if (!curVoice() || !curVoice()->staff()) return nullptr; // gather a list of all the music elements of that type in the staff at that time QList<CAMusElement*> foundElts = curVoice()->staff()->getEltByType(elt->musElementType(), elt->timeStart()); // compare gathered music elements properties for (int i = 0; i < foundElts.size(); i++) if (!foundElts[i]->compare(elt)) // element has exactly the same properties if (!curVoice()->musElementList().contains(foundElts[i])) // element isn't present in the voice yet return foundElts[i]; return nullptr; } /*! Returns true, if the given LilyPond element is a note. \sa isRest() */ bool CALilyPondImport::isNote(const QString elt) { return QString(elt[0]).contains(QRegExp("[a-g]")); } /*! Returns true, if the given LilyPond element is a rest. \sa isNote() */ bool CALilyPondImport::isRest(const QString elt) { return (elt[0] == 'r' || elt[0] == 's' || elt[0] == 'R'); } /*! Generates the note pitch and number of accidentals from the note written in LilyPond syntax. \param parse If true, constNName will be trimmed for the first element - the relative pitch \sa playableLengthFromLilyPond() */ CADiatonicPitch CALilyPondImport::relativePitchFromLilyPond(QString& constNName, CADiatonicPitch prevPitch, bool parse) { QString noteName = constNName; // determine pitch int curPitch = noteName[0].toLatin1() - 'a' + 5 // determine the 0-6 pitch from note name - (prevPitch.noteName() % 7); while (curPitch < -3) //normalize pitch - the max +/- interval is fourth curPitch += 7; while (curPitch > 3) curPitch -= 7; curPitch += prevPitch.noteName(); // determine accidentals signed char curAccs = 0; while (noteName.indexOf("is") != -1) { curAccs++; noteName.remove(0, noteName.indexOf("is") + 2); if (parse) constNName.remove(0, constNName.indexOf("is") + 2); } while ((noteName.indexOf("es") != -1) || (noteName.indexOf("as") != -1)) { curAccs--; noteName.remove(0, ((noteName.indexOf("es") == -1) ? (noteName.indexOf("as") + 2) : (noteName.indexOf("es") + 2))); if (parse) constNName.remove(0, ((constNName.indexOf("es") == -1) ? (constNName.indexOf("as") + 2) : (constNName.indexOf("es") + 2))); } if (!curAccs && parse) constNName.remove(0, 1); // add octave up/down for (int i = 0; i < noteName.size(); i++) { if (noteName[i] == '\'') { curPitch += 7; if (parse) constNName.remove(0, 1); } else if (noteName[i] == ',') { curPitch -= 7; if (parse) constNName.remove(0, 1); } } return CADiatonicPitch(curPitch, curAccs); } /*! Generates playable lentgth and number of dots from the note/rest string in LilyPond syntax. If the playable element doesn't include length, { CAPlayable::CAPlayableLength::Undefined, 0 } is returned. This function also shortens the given string for the playable length, if \a parse is True. \sa relativePitchFromString() */ CAPlayableLength CALilyPondImport::playableLengthFromLilyPond(QString& elt, bool parse) { CAPlayableLength ret; // index of the first number int start = elt.indexOf(QRegExp("[\\d]")); if (start == -1) // no length written return ret; else { // length written // count dots //int d=0; int dStart; for (int i = dStart = elt.indexOf(".", start); i != -1 && i < elt.size() && elt[i] == '.'; i++, ret.setDotted(ret.dotted() + 1)) ; if (dStart == -1) dStart = elt.indexOf(QRegExp("[\\D]"), start); if (dStart == -1) dStart = elt.size(); ret.setMusicLength(static_cast<CAPlayableLength::CAMusicLength>(elt.mid(start, dStart - start).toInt())); if (parse) elt.remove(start, dStart - start + ret.dotted()); } return ret; } /*! Genarates rest type from the LilyPond syntax for the given rest. This function also shortens the given string for the rest type, if \a parse is True. */ CARest::CARestType CALilyPondImport::restTypeFromLilyPond(QString& elt, bool parse) { CARest::CARestType t = CARest::Normal; if (elt[0] == 'r' || elt[0] == 'R') t = CARest::Normal; else t = CARest::Hidden; if (parse) elt.remove(0, 1); return t; } /*! Genarates clef type from the LilyPond syntax for the given clef from format "clefType". */ CAClef::CAPredefinedClefType CALilyPondImport::predefinedClefTypeFromLilyPond(const QString constClef) { // remove any quotes/double quotes QString clef(constClef); clef.remove(QRegExp("[\"']")); if (clef.contains("treble") || clef.contains("violin") || clef.contains("G")) return CAClef::Treble; if (clef.contains("french")) return CAClef::French; if (clef.contains("bass") || clef.contains("F")) return CAClef::Bass; if (clef.contains("varbaritone")) return CAClef::Varbaritone; if (clef.contains("subbass")) return CAClef::Subbass; if (clef.contains("mezzosoprano")) return CAClef::Mezzosoprano; if (clef.contains("soprano")) return CAClef::Soprano; if (clef.contains("alto")) return CAClef::Alto; if (clef.contains("tenor")) return CAClef::Tenor; if (clef.contains("baritone")) return CAClef::Baritone; if (clef == "percussion") return CAClef::Percussion; if (clef == "tab") return CAClef::Tablature; return CAClef::Treble; } /*! Returns the Canorus octava or whichever interval above or below the clef. */ int CALilyPondImport::clefOffsetFromLilyPond(const QString constClef) { // remove any quotes/double quotes QString clef(constClef); clef.remove(QRegExp("[\"']")); if (!clef.contains("_") && !clef.contains("^")) return 0; int m; int idx = clef.indexOf("^"); if (idx == -1) { idx = clef.indexOf("_"); m = -1; } else m = 1; return clef.right(clef.size() - (idx + 1)).toInt() * m; } /*! Returns the key signature gender from format \\genderType. */ CADiatonicKey::CAGender CALilyPondImport::diatonicKeyGenderFromLilyPond(QString gender) { if (gender == "\\major") return CADiatonicKey::Major; else return CADiatonicKey::Minor; } /*! Returns the time signature beat and beats in beats/beat format. */ CALilyPondImport::CATime CALilyPondImport::timeSigFromLilyPond(QString timeSig) { int beats = 0, beat = 0; beats = timeSig.mid(0, timeSig.indexOf("/")).toInt(); beat = timeSig.mid(timeSig.indexOf("/") + 1).toInt(); CATime time = { beats, beat }; return time; } /*! Genarates barline type from the LilyPond syntax for the given barline from format "barlineType". */ CABarline::CABarlineType CALilyPondImport::barlineTypeFromLilyPond(QString constBarline) { // remove any quotes/double quotes QString barline(constBarline); barline.remove(QRegExp("[\"']")); if (barline == "|") return CABarline::Single; else if (barline == "||") return CABarline::Double; else if (barline == "|.") return CABarline::End; else if (barline == "|:") return CABarline::RepeatOpen; else if (barline == ":|") return CABarline::RepeatClose; else if (barline == ":|:") return CABarline::RepeatCloseOpen; else if (barline == ":") return CABarline::Dotted; else return CABarline::Undefined; } const QString CALilyPondImport::readableStatus() { switch (status()) { case 0: return tr("Ready"); case 1: return tr("Importing..."); case -1: return tr("Error while importing!\nLine %1:%2.").arg(curLine()).arg(curChar()); } return "Ready"; }
26,973
C++
.cpp
651
33.205837
212
0.607223
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,295
undocommand.cpp
canorusmusic_canorus/src/core/undocommand.cpp
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "core/undocommand.h" #include "canorus.h" #include "core/undo.h" #include "score/document.h" #include "score/lyricscontext.h" #include "score/resource.h" #include "score/sheet.h" #include "score/voice.h" #include "widgets/scoreview.h" #include "widgets/sourceview.h" /*! \class CAUndoCommand \brief Internal Undo/Redo command This class implements undo and redo action. It inherits QUndoCommand and is usually stored inside QUndoStack or a list. Create this object by passing it a pointer to a document which the state should be saved for the future use. When called undo() or redo() (usually called by CAUndo class) all the documents and sheets currently opened are updated pointing to the previous (undone) or next (redone) states of the structures. \warning You should never directly access this class. Use CAUndo instead. \sa CAUndo */ /*! Creates a new undo command. Internally, it clones the given document and sets it as an undo document. The redo document is directly the passed document. When having multiple undo commands, you should take care of relinking the previous undo commmand's redo document to next command's undo document. This is usually done when pushing the command onto the stack. */ CAUndoCommand::CAUndoCommand(CADocument* document, QString text) : QUndoCommand(text) { setUndoDocument(document->clone()); setRedoDocument(document); } CAUndoCommand::~CAUndoCommand() { if (getUndoDocument() && (!CACanorus::mainWinCount(getUndoDocument()))) delete getUndoDocument(); // delete also redoDocument, if the last on the stack if (getRedoDocument() && !CACanorus::mainWinCount(getRedoDocument()) && CACanorus::undo()->undoStack(getRedoDocument()) && CACanorus::undo()->undoStack(getRedoDocument())->indexOf(this) == CACanorus::undo()->undoStack(getRedoDocument())->count() - 1) delete getRedoDocument(); } void CAUndoCommand::undo() { getUndoDocument()->setTimeEdited(getRedoDocument()->timeEdited()); // time edited might get lost when saving the document and undoing right after getUndoDocument()->setFileName(getRedoDocument()->fileName()); CAUndoCommand::undoDocument(getRedoDocument(), getUndoDocument()); } void CAUndoCommand::redo() { getRedoDocument()->setTimeEdited(getUndoDocument()->timeEdited()); // time edited might get lost when saving the document and redoing right after getRedoDocument()->setFileName(getUndoDocument()->fileName()); CAUndoCommand::undoDocument(getUndoDocument(), getRedoDocument()); } /*! Creates the actual undo (switches the pointers of the document) and updates the GUI. The updating GUI part is quite complicated as it has to update all views showing the right structure and sub-structure (eg. voice with the same index in the new document). */ void CAUndoCommand::undoDocument(CADocument* current, CADocument* newDocument) { QHash<CASheet*, CASheet*> sheetMap; // map old->new sheets QHash<CAContext*, CAContext*> contextMap; // map old->new contexts QHash<CAVoice*, CAVoice*> voiceMap; // map old->new voices bool rebuildNeeded = false; for (int i = 0; i < newDocument->sheetList().size() && i < current->sheetList().size(); i++) { sheetMap[current->sheetList()[i]] = newDocument->sheetList()[i]; for (int j = 0; j < newDocument->sheetList()[i]->contextList().size() && j < current->sheetList()[i]->contextList().size(); j++) { contextMap[current->sheetList()[i]->contextList()[j]] = newDocument->sheetList()[i]->contextList()[j]; } for (int j = 0; j < newDocument->sheetList()[i]->voiceList().size() && j < current->sheetList()[i]->voiceList().size(); j++) { voiceMap[current->sheetList()[i]->voiceList()[j]] = newDocument->sheetList()[i]->voiceList()[j]; } } QList<CAMainWin*> mainWinList = CACanorus::findMainWin(current); if (newDocument->sheetList().size() != current->sheetList().size()) { for (int i = 0; i < mainWinList.size(); i++) { mainWinList[i]->setDocument(newDocument); if (mainWinList[i]->currentScoreView()) { mainWinList[i]->currentScoreView()->setCurrentContext(nullptr); } } rebuildNeeded = true; } else { // rebuild UI and replace sheets with new sheets // TODO: This should be moved to the UI module! for (int i = 0; i < mainWinList.size(); i++) { QList<CAView*> viewList = mainWinList[i]->viewList(); for (int j = 0; j < viewList.size(); j++) { switch (viewList[j]->viewType()) { case CAView::ScoreView: { CAScoreView* sv = static_cast<CAScoreView*>(viewList[j]); sv->setSheet(sheetMap[sv->sheet()]); if (sv->currentContext() && contextMap.contains(sv->currentContext()->context())) { sv->selectContext(contextMap[sv->currentContext()->context()]); } else { sv->selectContext(nullptr); } if (sv->selectedVoice() && voiceMap.contains(sv->selectedVoice())) { sv->setSelectedVoice(voiceMap[sv->selectedVoice()]); } else { sv->setSelectedVoice(nullptr); } break; } case CAView::SourceView: { CASourceView* sv = static_cast<CASourceView*>(viewList[j]); if (sv->voice()) { if (voiceMap.contains(sv->voice())) // set the new voice sv->setVoice(voiceMap[sv->voice()]); else // or close the view if not available delete sv; } if (sv->lyricsContext()) { if (contextMap.contains(sv->lyricsContext()) && contextMap[sv->lyricsContext()]->contextType() == CAContext::LyricsContext) // set the new lyrics context sv->setLyricsContext(static_cast<CALyricsContext*>(contextMap[sv->lyricsContext()])); else // or close the view if not available delete sv; } if (sv->document()) { // set the new document sv->setDocument(newDocument); } break; } } } mainWinList[i]->setDocument(newDocument); } } // update resources for (int i = 0; i < current->resourceList().size(); i++) { current->resourceList()[i]->setDocument(newDocument); } if (rebuildNeeded) CACanorus::rebuildUI(newDocument); }
7,168
C++
.cpp
147
38.938776
254
0.616341
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,296
fileformats.cpp
canorusmusic_canorus/src/core/fileformats.cpp
/*! Copyright (c) 2006-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "core/fileformats.h" #include <QObject> /*! \class CAFileFormats \brief File formats supported by Canorus This class contains the filters shown in file dialogs (eg. when opening/saving a document) and its internal enumeration values used when storing settings for default or last used filter. */ const QString CAFileFormats::CANORUSML_FILTER = QObject::tr("Canorus document (*.xml)"); const QString CAFileFormats::CAN_FILTER = QObject::tr("Canorus archive (*.can)"); const QString CAFileFormats::LILYPOND_FILTER = QObject::tr("LilyPond document (*.ly)"); const QString CAFileFormats::MUSICXML_FILTER = QObject::tr("MusicXML document (*.musicxml)"); const QString CAFileFormats::MXL_FILTER = QObject::tr("Compressed MusicXML document (*.mxl)"); const QString CAFileFormats::NOTEEDIT_FILTER = QObject::tr("NoteEdit document (*.not)"); const QString CAFileFormats::ABCMUSIC_FILTER = QObject::tr("ABC music document (*.abc)"); const QString CAFileFormats::FINALE_FILTER = QObject::tr("Finale document (*.mus)"); const QString CAFileFormats::SIBELIUS_FILTER = QObject::tr("Sibelius document (*.sib)"); const QString CAFileFormats::CAPELLA_FILTER = QObject::tr("Capella document (*.cap)"); const QString CAFileFormats::MIDI_FILTER = QObject::tr("Midi file (*.mid *.midi)"); const QString CAFileFormats::PDF_FILTER = QObject::tr("PDF file (*.pdf)"); const QString CAFileFormats::SVG_FILTER = QObject::tr("SVG file (*.svg)"); /*! Converts the file format enumeration to filter as string. */ const QString CAFileFormats::getFilter(const CAFileFormats::CAFileFormatType t) { switch (t) { case CanorusML: return CANORUSML_FILTER; case Can: return CAN_FILTER; case LilyPond: return LILYPOND_FILTER; case MusicXML: return MUSICXML_FILTER; case MXL: return MXL_FILTER; case PDF: return PDF_FILTER; case SVG: return SVG_FILTER; default: return CANORUSML_FILTER; } } /*! Converts the file format filter string to enumeration appropriate for storing in config file. */ CAFileFormats::CAFileFormatType CAFileFormats::getType(const QString t) { if (t == CANORUSML_FILTER) return CanorusML; else if (t == CAN_FILTER) return Can; if (t == LILYPOND_FILTER) return LilyPond; else if (t == MUSICXML_FILTER) return MusicXML; else if (t == MXL_FILTER) return MXL; else if (t == PDF_FILTER) return PDF; else if (t == SVG_FILTER) return SVG; else return CanorusML; }
2,799
C++
.cpp
72
34.861111
108
0.718015
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,297
midirecorder.cpp
canorusmusic_canorus/src/core/midirecorder.cpp
/*! Copyright (c) 2008-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "core/midirecorder.h" #include "export/midiexport.h" #include "interface/mididevice.h" #include "score/resource.h" /*! \class CAMidiRecorder \brief Class for live recording of the Midi events This class is used when a composer has a musical idea in his fingers and wants to record it. 1) Create a new output resource (eg. midi file in tmp directory) 2) Create this class and pass this resource 2) Call record(). Class will run in a separated thread and start recording all the midi events into the given resource file. 3) Call stop() when recording is done. Class will write the midi data and close the stream. */ CAMidiRecorder::CAMidiRecorder(std::shared_ptr<CAResource> r, CAMidiDevice* d) : QObject() , _resource(r) , _midiExport(nullptr) , _curTime(0) { _paused = false; connect(d, SIGNAL(midiInEvent(QVector<unsigned char>)), this, SLOT(onMidiInEvent(QVector<unsigned char>))); } CAMidiRecorder::~CAMidiRecorder() { disconnect(); } void CAMidiRecorder::timerTimeout() { if (!_paused) { _curTime += 10; } } void CAMidiRecorder::startRecording(int) { if (!_paused) { _midiExport = new CAMidiExport(); _midiExport->setStreamToFile(_resource->url().toLocalFile()); _curTime = 0; _timer = new QTimer(); _timer->setInterval(10); connect(_timer, SIGNAL(timeout()), this, SLOT(timerTimeout())); _timer->start(); // the default time signature is a 4 quarters measure _midiExport->sendMetaEvent(0, CAMidiDevice::Meta_Timesig, 4, 4, 0); _midiExport->sendMetaEvent(0, CAMidiDevice::Meta_Tempo, 120, 0, 0); } else { _paused = false; } } void CAMidiRecorder::stopRecording() { _midiExport->writeFile(); delete _midiExport; _midiExport = nullptr; _timer->stop(); _timer->disconnect(); } void CAMidiRecorder::pauseRecording() { _paused = true; } void CAMidiRecorder::onMidiInEvent(QVector<unsigned char> messages) { if (_midiExport && !_paused) { _midiExport->send(messages, _curTime / 2); // needs division somewhere else ... } }
2,364
C++
.cpp
75
27.6
111
0.695251
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,298
typesetter.cpp
canorusmusic_canorus/src/core/typesetter.cpp
/*! Copyright (c) 2008, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "core/typesetter.h" CATypesetter::CATypesetter() { } CATypesetter::~CATypesetter() { }
309
C++
.cpp
12
24.166667
72
0.784983
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,299
transpose.cpp
canorusmusic_canorus/src/core/transpose.cpp
/*! Copyright (c) 2008-2022, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "core/transpose.h" #include "score/chordname.h" #include "score/chordnamecontext.h" #include "score/diatonicpitch.h" #include "score/functionmark.h" #include "score/functionmarkcontext.h" #include "score/keysignature.h" #include "score/muselement.h" #include "score/note.h" #include "score/sheet.h" #include "score/staff.h" #include "score/voice.h" /*! \class CATranspose \brief Class used for transposing a set of notes for the given interval This is a control class used for making a transposition of a set of music elements, contexts or even the whole score sheet. Use: 1) Create a CATranspose class 2) Pass the music elements you want to transpose in the constructor or by calling addMusElement() or addContext(). 3) Transpose the elements by calling transposeByKeySig(), transposeByInterval(), transposeBySemitones() or reinterpretAccidentals(). \sa CAInterval::fromSemitones() */ CATranspose::CATranspose() { } CATranspose::CATranspose(CASheet* sheet) { for (int i = 0; i < sheet->contextList().size(); i++) { addContext(sheet->contextList()[i]); } } CATranspose::CATranspose(QList<CAContext*> contexts) { for (int i = 0; i < contexts.size(); i++) { addContext(contexts[i]); } } CATranspose::CATranspose(QList<CAMusElement*> selection) { _elements = QSet<CAMusElement*>::fromList(selection); } CATranspose::~CATranspose() { } void CATranspose::addSheet(CASheet* s) { for (int i = 0; i < s->contextList().size(); i++) { addContext(s->contextList()[i]); } } void CATranspose::addContext(CAContext* context) { switch (context->contextType()) { case CAContext::Staff: { CAStaff* staff = static_cast<CAStaff*>(context); for (int j = 0; j < staff->voiceList().size(); j++) { _elements.unite(QSet<CAMusElement*>::fromList(staff->voiceList()[j]->musElementList())); } break; } case CAContext::FunctionMarkContext: { QList<CAFunctionMark*> markList = static_cast<CAFunctionMarkContext*>(context)->functionMarkList(); for (int i = 0; i < markList.size(); i++) { addMusElement(markList[i]); } break; } case CAContext::ChordNameContext: { QList<CAChordName*> cnList = static_cast<CAChordNameContext*>(context)->chordNameList(); for (int i = 0; i < cnList.size(); i++) { addMusElement(cnList[i]); } break; } default: break; } } /*! Transposes the music elements by the given number of semitones. Number can be negative for the direction down. */ void CATranspose::transposeBySemitones(int semitones) { transposeByInterval(CAInterval::fromSemitones(semitones)); } /*! Transposes the music elements from the given key signature \a from to the key signature \a to in the given \a direction. Direction can be 1 for up or -1 for down. */ void CATranspose::transposeByKeySig(CADiatonicKey from, CADiatonicKey to, int direction) { CAInterval interval(from.diatonicPitch(), to.diatonicPitch()); if (((direction < 0) && (to.diatonicPitch().noteName() - from.diatonicPitch().noteName() > 0)) || ((direction > 0) && (to.diatonicPitch().noteName() - from.diatonicPitch().noteName() < 0))) { interval = ~interval; } if (direction < 0) { interval.setQuantity(interval.quantity() * (-1)); } transposeByInterval(interval); /// \todo Notes should be transposed differently when transposing from major -> minor for example } /*! Transposes the music elements by the given interval. If the interval quantity is negative, elements are transposed down. */ void CATranspose::transposeByInterval(CAInterval interval) { for (CAMusElement* elt : _elements) { switch (elt->musElementType()) { case CAMusElement::Note: static_cast<CANote*>(elt)->setDiatonicPitch(static_cast<CANote*>(elt)->diatonicPitch() + interval); break; case CAMusElement::KeySignature: static_cast<CAKeySignature*>(elt)->setDiatonicKey(static_cast<CAKeySignature*>(elt)->diatonicKey() + interval); break; case CAMusElement::ChordName: *static_cast<CAChordName*>(elt)+=(interval); break; case CAMusElement::FunctionMark: static_cast<CAFunctionMark*>(elt)->setKey(static_cast<CAFunctionMark*>(elt)->key() + interval); break; case CAMusElement::MidiNote: // ToDo break; default: break; } } } /*! Changes note accidentals dependent on \a type: 1) If type==1, sharps -> flats 2) If type==-1, flats -> sharps 3) if type==0, invert This function also changes Key signatures dependent on \a type, if their number of accidentals is greater or equal than 5 or lesser or equal than -5. */ void CATranspose::reinterpretAccidentals(int type) { for (CAMusElement* elt : _elements) { switch (elt->musElementType()) { case CAMusElement::Note: case CAMusElement::ChordName: { CADiatonicPitch newPitch; if (elt->musElementType() == CAMusElement::Note) { newPitch = static_cast<CANote*>(elt)->diatonicPitch(); } else if (elt->musElementType() == CAMusElement::ChordName) { newPitch = static_cast<CAChordName*>(elt)->diatonicPitch(); } if (type >= 0 && newPitch.accs() > 0) { newPitch = newPitch + CAInterval(-2, 2); } else if (type <= 0 && newPitch.accs() < 0) { newPitch = newPitch - CAInterval(-2, 2); } if (elt->musElementType() == CAMusElement::Note) { static_cast<CANote*>(elt)->setDiatonicPitch(newPitch); } else if (elt->musElementType() == CAMusElement::ChordName) { static_cast<CAChordName*>(elt)->setDiatonicPitch(newPitch); } break; } case CAMusElement::KeySignature: { CAKeySignature* keySig = static_cast<CAKeySignature*>(elt); CADiatonicKey newDiatonicKey = keySig->diatonicKey(); if (type >= 0 && keySig->diatonicKey().numberOfAccs() >= 5) { newDiatonicKey = CADiatonicKey(keySig->diatonicKey().diatonicPitch() + CAInterval(-2, 2), keySig->diatonicKey().gender()); } else if (type <= 0 && keySig->diatonicKey().numberOfAccs() <= -5) { newDiatonicKey = CADiatonicKey(keySig->diatonicKey().diatonicPitch() - CAInterval(-2, 2), keySig->diatonicKey().gender()); } keySig->setDiatonicKey(newDiatonicKey); break; } default: break; } } }
6,938
C++
.cpp
184
31.532609
195
0.652303
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,300
undo.cpp
canorusmusic_canorus/src/core/undo.cpp
/*! Copyright (c) 2007-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "core/undo.h" #include "core/undocommand.h" #include "score/document.h" // needed for setting the modified flag #include <iostream> /*! \class CAUndo \brief Undo/Redo support This class implements undo and redo Canorus functionality. This singleton object is created upon Canorus startup and is accessed via CACanorus::undo() getter. In essence there is one undo stack for each opened file. When changes to the document are made, the undo action is created and the current document is cloned. This copy is then used to replace the active document in case of undo. A mapping of any document copy out there to the undo stack it belongs to is stored in _undoStack. Each main window has one undo stack or a shared undo stack, if multiple windows represent the same document. Undo stack contains one or more undo commands called upon undo/redo events (each undo command then makes one change to the document). _undoIndex stores the current index of the undo command for each undo stack (i.e. the command which gets called next time the user presses the Undo button). Usage of undo/redo: 1) Create undo stack when creating/opening a new document by calling CAUndo::createUndoStack() 2) Before each action (insertion, removal, editing of elements), call CAUndo::createUndoCommand() and pass the current document to be saved for that action. 3) If the action was successful, commit the command by calling CAUndo::pushUndoCommand(). If not, do nothing - non-pushed commands will get deleted when createUndoCommand() will be issued the next time. 4) For undo/redo, simply call CAUndo::undoStack()->undo(). 5) When destroying the document, also destroy the undo stack (which also destroys all its commands) by calling CAUndo::deleteUndoStack(). This is not done automatically because CADocument is part of the data model and CAUndo part of the controller. If the user already created its own instance of the new document without calling CAUndo::createUndoCommand() (e.g. when parsing the source-view of the whole document), he should use CAUndo::replaceDocument(). \sa CAUndoCommand */ CAUndo::CAUndo() { _undoCommand = nullptr; } CAUndo::~CAUndo() { } /*! Creates a new undoStack for the given document. This should be called at the beginning when the first main window for the given document is created. */ void CAUndo::createUndoStack(CADocument* doc) { _undoStack[doc] = new QList<CAUndoCommand*>; undoIndex(doc) = -1; } /*! Undoes the last change made to document. This method already calls CAUndoCommand::undo(). */ void CAUndo::undo(CADocument* doc) { if (_undoStack[doc] && canUndo(doc)) { _undoStack[doc]->at(undoIndex(doc))->undo(); undoIndex(doc)--; } } /*! Redoes the last change made to document. This method already calls CAUndoCommand::redo(). */ void CAUndo::redo(CADocument* doc) { if (_undoStack[doc] && canRedo(doc)) { _undoStack[doc]->at(undoIndex(doc) + 1)->redo(); undoIndex(doc)++; } } /*! Deletes the undoStack object for the given document. This should be called at the end where no main windows are pointing to the given document anymore. */ void CAUndo::deleteUndoStack(CADocument* doc) { clearUndoCommand(); QList<CAUndoCommand*>* stack = undoStack(doc); while (!stack->isEmpty()) { delete stack->first(); stack->takeFirst(); } delete stack; QList<CADocument*> keys = _undoStack.keys(stack); for (int i = 0; i < keys.size(); i++) removeUndoStack(keys[i]); } /*! Call this to add an undo command (created by createUndoCommand()) to the stack. Undo commands *after* the currently active command will be deleted. undoIndex is updated to the size of the stack - 1. \warning This function is not thread-safe. createUndoCommand() and pushUndoCommand() should be called from the same thread and main window. */ void CAUndo::pushUndoCommand() { if (!_undoCommand || !_undoCommand->getRedoDocument() || !_undoCommand->getUndoDocument()) return; CADocument* d = _undoCommand->getRedoDocument(); _undoCommand->getUndoDocument()->setModified(true); _undoCommand->getRedoDocument()->setModified(true); QList<CAUndoCommand*>* s = _undoStack[d]; CAUndoCommand* prevUndoCommand = (undoIndex(d) < s->size() && undoIndex(d) >= 0 ? s->at(undoIndex(d)) : nullptr); // delete undo commands after the new one, if any (eg. 3x changes, 2x undo, 1x change => removes last 2 undos when making a change) for (int i = undoIndex(d) + 1; i < s->size();) { _undoStack.remove(s->at(i)->getRedoDocument()); delete s->at(i); s->removeAt(i); } if (prevUndoCommand) { if (_undoCommand->getRedoDocument() && prevUndoCommand->getRedoDocument()) prevUndoCommand->setRedoDocument(_undoCommand->getUndoDocument()); } s->append(_undoCommand); // push the command on stack _undoStack[_undoCommand->getUndoDocument()] = s; undoIndex(d) = _undoStack[d]->size() - 1; _undoCommand = nullptr; } /*! Returns True, if changes to the current document have been made and undo is possible. False otherwise. \sa canRedo() */ bool CAUndo::canUndo(CADocument* d) { if (_undoStack[d] && _undoStack[d]->size() && undoIndex(d) != -1) return true; else return false; } /*! Returns True, if changes to the current document have been undone at least once and redo is possible. False otherwise. \sa canUndo() */ bool CAUndo::canRedo(CADocument* d) { if (_undoStack[d] && _undoStack[d]->size() && undoIndex(d) != (_undoStack[d]->size() - 1)) return true; else return false; } /*! Destroys the undo command if decided not to be put on the stack. Does nothing if undo command is null. */ void CAUndo::clearUndoCommand() { if (_undoCommand) { delete _undoCommand; _undoCommand = nullptr; } } /*! Creates an undo command which is later put on the stack. This function is usually called when making changes to the document in the score - all changes ranging from creation/removal of sheets and editing document properties. \warning This function is not thread-safe. createUndoCommand() and pushUndoCommand() should be called from the same thread. */ void CAUndo::createUndoCommand(CADocument* d, QString text) { clearUndoCommand(); _undoCommand = new CAUndoCommand(d, text); } /*! Replace the document pointer to an undo stack. This function is called when the document is rebuilt, e.g. when a CanorusML view commits changes and the old document should be forgotten. */ void CAUndo::replaceDocument(CADocument* oldDoc, CADocument* newDoc) { clearUndoCommand(); QList<CAUndoCommand*>* stack = _undoStack[oldDoc]; CAUndoCommand* prevUndoCommand = (undoIndex(oldDoc) < stack->size() && undoIndex(oldDoc) >= 0 ? stack->at(undoIndex(oldDoc)) : nullptr); if (prevUndoCommand) { if (prevUndoCommand->getRedoDocument() == oldDoc) prevUndoCommand->setRedoDocument(newDoc); } _undoStack.remove(oldDoc); _undoStack[newDoc] = stack; } /*! Gathers a list of all redo and undo instances of the given document \a d. This function is usually called when adding/removing a resource to/from a document. Because resources are not undoable, they should be the same for all the documents. */ QList<CADocument*> CAUndo::getAllDocuments(CADocument* d) { QList<CADocument*> documents; QList<CAUndoCommand*>* undoCommands = _undoStack[d]; if (undoCommands && undoCommands->size()) { for (int i = 0; i < undoCommands->size(); i++) { documents << undoCommands->at(i)->getUndoDocument(); } if (undoCommands->size() > 0) { documents << undoCommands->at(undoCommands->size() - 1)->getRedoDocument(); } } else { documents << d; } return documents; }
8,185
C++
.cpp
207
35.652174
140
0.713404
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,301
settings.cpp
canorusmusic_canorus/src/core/settings.cpp
/*! Copyright (c) 2007-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include <QDebug> #include "core/settings.h" #ifndef SWIGCPP #include "canorus.h" #endif #include "interface/rtmididevice.h" //#define COPY_ACTIONLIST_ELEMS_MANUALLY 1 // Define default settings const bool CASettings::DEFAULT_FINALE_LYRICS_BEHAVIOUR = false; const bool CASettings::DEFAULT_SHADOW_NOTES_IN_OTHER_STAFFS = false; const bool CASettings::DEFAULT_PLAY_INSERTED_NOTES = true; const bool CASettings::DEFAULT_AUTO_BAR = true; const bool CASettings::DEFAULT_USE_NOTE_CHECKER = true; const QDir CASettings::DEFAULT_DOCUMENTS_DIRECTORY = QDir::home(); const QDir CASettings::DEFAULT_SHORTCUTS_DIRECTORY = QDir(QDir::homePath() + "/.config/Canorus"); const CAFileFormats::CAFileFormatType CASettings::DEFAULT_SAVE_FORMAT = CAFileFormats::Can; const int CASettings::DEFAULT_AUTO_RECOVERY_INTERVAL = 1; const int CASettings::DEFAULT_MAX_RECENT_DOCUMENTS = 15; #ifndef SWIGCPP const bool CASettings::DEFAULT_LOCK_SCROLL_PLAYBACK = true; // scroll while playing const bool CASettings::DEFAULT_ANIMATED_SCROLL = true; const bool CASettings::DEFAULT_ANTIALIASING = true; const bool CASettings::DEFAULT_SHOW_RULER = true; const QColor CASettings::DEFAULT_BACKGROUND_COLOR = QColor(255, 255, 240); const QColor CASettings::DEFAULT_FOREGROUND_COLOR = Qt::black; const QColor CASettings::DEFAULT_SELECTION_COLOR = Qt::red; const QColor CASettings::DEFAULT_SELECTION_AREA_COLOR = QColor(255, 0, 80, 70); const QColor CASettings::DEFAULT_SELECTED_CONTEXT_COLOR = Qt::blue; const QColor CASettings::DEFAULT_HIDDEN_ELEMENTS_COLOR = Qt::green; const QColor CASettings::DEFAULT_DISABLED_ELEMENTS_COLOR = Qt::gray; #endif const int CASettings::DEFAULT_MIDI_IN_PORT = -1; const int CASettings::DEFAULT_MIDI_OUT_PORT = -1; const int CASettings::DEFAULT_MIDI_IN_NUM_DEVICES = 0; const int CASettings::DEFAULT_MIDI_OUT_NUM_DEVICES = 0; const CATypesetter::CATypesetterType CASettings::DEFAULT_TYPESETTER = CATypesetter::LilyPond; #ifdef Q_OS_WIN const QString CASettings::DEFAULT_TYPESETTER_LOCATION = "LilyPond/usr/bin/lilypond.exe"; #elif defined(Q_OS_MAC) const QString CASettings::DEFAULT_TYPESETTER_LOCATION = "/Applications/LilyPond.app/Contents/Resources/bin/lilypond"; #else const QString CASettings::DEFAULT_TYPESETTER_LOCATION = "lilypond"; #endif const bool CASettings::DEFAULT_USE_SYSTEM_TYPESETTER = true; const QString CASettings::DEFAULT_PDF_VIEWER_LOCATION = ""; const bool CASettings::DEFAULT_USE_SYSTEM_PDF_VIEWER = true; /*! \class CASettings \brief Class for storing the Canorus settings This class is a model class used for reading and writing the settings in/out of the config file. The default location of config files are usually $HOME$/.config/Canorus for POSIX systems and %HOME%\Application data\Canorus on M$ systems. See \fn defaultSettingsPath(). To use this class simply create it and (optionally) pass a config file name. Use readSettings() to read the actual values then. Use getter/setter methods for getting the properties and call writeSettings() to store new settings. To add a new property: 1) add a private property (eg. _textColor) 2) add public getter, setter methods and initial value (eg. getTextColor(), setTextColor(), DEFAULT_TEXT_COLOR) 3) define the initial value itself in .cpp file 4) add setValue() sentence in writeSettings() method and setTextColor() in readSettings() 5) (optionally) create GUI in CASettingsDialog or CAMainWin menu for your new property \sa CASettingsDialog */ /*! Create a new settings instance using the config file \a fileName. */ CASettings::CASettings(const QString& fileName, QObject* parent) : QSettings(fileName, QSettings::IniFormat, parent) { initSettings(); } /*! Create a new settings instance using the default config file for a local user. */ CASettings::CASettings(QObject* parent) : QSettings(defaultSettingsPath() + "/canorus.ini", QSettings::IniFormat, parent) { initSettings(); } void CASettings::initSettings() { #ifndef SWIGCPP _poEmptyEntry = new CASingleAction(this); #endif } CASettings::~CASettings() { writeSettings(); if (_poEmptyEntry) delete _poEmptyEntry; _poEmptyEntry = nullptr; #ifndef SWIGCPP if (false == _oActionList.isEmpty()) { CASingleAction* poActionEntry; foreach (poActionEntry, _oActionList) { delete poActionEntry; poActionEntry = nullptr; } _oActionList.clear(); } #endif } /*! Writes the stored settings to a config file. */ void CASettings::writeSettings() { setValue("editor/finalelyricsbehaviour", finaleLyricsBehaviour()); setValue("editor/shadownotesinotherstaffs", shadowNotesInOtherStaffs()); setValue("editor/playinsertednotes", playInsertedNotes()); setValue("editor/autobar", autoBar()); setValue("editor/usenotechecker", useNoteChecker()); setValue("appearance/showruler", showRuler()); setValue("files/documentsdirectory", documentsDirectory().absolutePath()); setValue("files/defaultsaveformat", defaultSaveFormat()); setValue("files/autorecoveryinterval", autoRecoveryInterval()); setValue("files/maxrecentdocuments", maxRecentDocuments()); #ifndef SWIGCPP writeRecentDocuments(); setValue("appearance/lockscrollplayback", lockScrollPlayback()); setValue("appearance/animatedscroll", animatedScroll()); setValue("appearance/antialiasing", antiAliasing()); setValue("appearance/backgroundcolor", backgroundColor()); setValue("appearance/foregroundcolor", foregroundColor()); setValue("appearance/selectioncolor", selectionColor()); setValue("appearance/selectionareacolor", selectionAreaColor()); setValue("appearance/selectedcontextcolor", selectedContextColor()); setValue("appearance/hiddenelementscolor", hiddenElementsColor()); setValue("appearance/disabledelementscolor", disabledElementsColor()); #endif setValue("rtmidi/midioutport", midiOutPort()); setValue("rtmidi/midiinport", midiInPort()); setValue("rtmidi/midioutnumdevices", midiOutNumDevices()); setValue("rtmidi/midiinnumdevices", midiInNumDevices()); setValue("printing/typesetter", typesetter()); setValue("printing/typesetterlocation", typesetterLocation()); setValue("printing/usesystemdefaulttypesetter", useSystemDefaultTypesetter()); setValue("printing/pdfviewerlocation", pdfViewerLocation()); setValue("printing/usesystemdefaultpdfviewer", useSystemDefaultPdfViewer()); sync(); } /*! Opens the settings stored in a config file and sets the local values. This function is usually called on application startup to read and validate various settings and show the settings window, if needed (eg. setup the MIDI devices the first time). \return 0, if settings validated fine; -1 for playback settings errors. */ int CASettings::readSettings() { int settingsPage = 0; // Editor settings if (contains("editor/finalelyricsbehaviour")) setFinaleLyricsBehaviour(value("editor/finalelyricsbehaviour").toBool()); else setFinaleLyricsBehaviour(DEFAULT_FINALE_LYRICS_BEHAVIOUR); if (contains("editor/shadownotesinotherstaffs")) setShadowNotesInOtherStaffs(value("editor/shadownotesinotherstaffs").toBool()); else setShadowNotesInOtherStaffs(DEFAULT_SHADOW_NOTES_IN_OTHER_STAFFS); if (contains("editor/playinsertednotes")) setPlayInsertedNotes(value("editor/playinsertednotes").toBool()); else setPlayInsertedNotes(DEFAULT_PLAY_INSERTED_NOTES); if (contains("editor/autobar")) setAutoBar(value("editor/autobar").toBool()); else setAutoBar(DEFAULT_AUTO_BAR); if (contains("editor/usenotechecker")) setUseNoteChecker(value("editor/usenotechecker").toBool()); else setUseNoteChecker(DEFAULT_USE_NOTE_CHECKER); // Saving/Loading settings if (contains("files/documentsdirectory")) setDocumentsDirectory(value("files/documentsdirectory").toString()); else setDocumentsDirectory(DEFAULT_DOCUMENTS_DIRECTORY); if (contains("files/defaultsaveformat")) setDefaultSaveFormat(static_cast<CAFileFormats::CAFileFormatType>(value("files/defaultsaveformat").toInt())); else setDefaultSaveFormat(DEFAULT_SAVE_FORMAT); if (contains("files/autorecoveryinterval")) setAutoRecoveryInterval(value("files/autorecoveryinterval").toInt()); else setAutoRecoveryInterval(DEFAULT_AUTO_RECOVERY_INTERVAL); // Recently opened files if (contains("files/maxrecentdocuments")) setMaxRecentDocuments(value("files/maxrecentdocuments").toInt()); else setMaxRecentDocuments(DEFAULT_MAX_RECENT_DOCUMENTS); #ifndef SWIGCPP readRecentDocuments(); // Appearance settings if (contains("appearance/lockscrollplayback")) setLockScrollPlayback(value("appearance/lockscrollplayback").toBool()); else setLockScrollPlayback(DEFAULT_LOCK_SCROLL_PLAYBACK); if (contains("appearance/animatedscroll")) setAnimatedScroll(value("appearance/animatedscroll").toBool()); else setAnimatedScroll(DEFAULT_ANIMATED_SCROLL); if (contains("appearance/antialiasing")) setAntiAliasing(value("appearance/antialiasing").toBool()); else setAntiAliasing(DEFAULT_ANTIALIASING); if (contains("appearance/backgroundcolor")) setBackgroundColor(value("appearance/backgroundcolor").value<QColor>()); else setBackgroundColor(DEFAULT_BACKGROUND_COLOR); if (contains("appearance/foregroundcolor")) setForegroundColor(value("appearance/foregroundcolor").value<QColor>()); else setForegroundColor(DEFAULT_FOREGROUND_COLOR); if (contains("appearance/selectioncolor")) setSelectionColor(value("appearance/selectioncolor").value<QColor>()); else setSelectionColor(DEFAULT_SELECTION_COLOR); if (contains("appearance/selectionareacolor")) setSelectionAreaColor(value("appearance/selectionareacolor").value<QColor>()); else setSelectionAreaColor(DEFAULT_SELECTION_AREA_COLOR); if (contains("appearance/selectedcontextcolor")) setSelectedContextColor(value("appearance/selectedcontextcolor").value<QColor>()); else setSelectedContextColor(DEFAULT_SELECTED_CONTEXT_COLOR); if (contains("appearance/hiddenelementscolor")) setHiddenElementsColor(value("appearance/hiddenelementscolor").value<QColor>()); else setHiddenElementsColor(DEFAULT_HIDDEN_ELEMENTS_COLOR); if (contains("appearance/disabledelementscolor")) setDisabledElementsColor(value("appearance/disabledelementscolor").value<QColor>()); else setDisabledElementsColor(DEFAULT_DISABLED_ELEMENTS_COLOR); if (contains("appearance/showruler")) setShowRuler(value("appearance/showruler").toBool()); else setShowRuler(DEFAULT_SHOW_RULER); #endif // Playback settings if (contains("rtmidi/midiinport") #ifndef SWIGCPP && value("rtmidi/midiinport").toInt() < CACanorus::midiDevice()->getInputPorts().count() #endif ) { setMidiInPort(value("rtmidi/midiinport").toInt()); } else { setMidiInPort(DEFAULT_MIDI_IN_PORT); settingsPage = -1; } if (contains("rtmidi/midiinnumdevices")) { #ifndef SWIGCPP if (value("rtmidi/midiinnumdevices").toInt() != CACanorus::midiDevice()->getInputPorts().count()) settingsPage = -1; setMidiInNumDevices(CACanorus::midiDevice()->getInputPorts().count()); #endif } else { setMidiInNumDevices(DEFAULT_MIDI_IN_NUM_DEVICES); settingsPage = -1; } if (contains("rtmidi/midioutport") #ifndef SWIGCPP && value("rtmidi/midioutport").toInt() < CACanorus::midiDevice()->getOutputPorts().count() #endif ) { setMidiOutPort(value("rtmidi/midioutport").toInt()); } else { setMidiOutPort(DEFAULT_MIDI_OUT_PORT); settingsPage = -1; } if (contains("rtmidi/midioutnumdevices")) { #ifndef SWIGCPP if (value("rtmidi/midioutnumdevices").toInt() != CACanorus::midiDevice()->getOutputPorts().count()) settingsPage = -1; setMidiOutNumDevices(CACanorus::midiDevice()->getOutputPorts().count()); #endif } else { setMidiOutNumDevices(DEFAULT_MIDI_OUT_NUM_DEVICES); settingsPage = -1; } // Printing settings if (contains("printing/typesetter")) setTypesetter(static_cast<CATypesetter::CATypesetterType>(value("printing/typesetter").toInt())); else setTypesetter(DEFAULT_TYPESETTER); if (contains("printing/typesetterlocation")) setTypesetterLocation(value("printing/typesetterlocation").toString()); else setTypesetterLocation(DEFAULT_TYPESETTER_LOCATION); if (contains("printing/usesystemdefaulttypesetter")) setUseSystemDefaultTypesetter(value("printing/usesystemdefaulttypesetter").toBool()); else setUseSystemDefaultTypesetter(DEFAULT_USE_SYSTEM_TYPESETTER); if (contains("printing/pdfviewerlocation")) setPdfViewerLocation(value("printing/pdfviewerlocation").toString()); else setPdfViewerLocation(DEFAULT_PDF_VIEWER_LOCATION); if (contains("printing/usesystemdefaultpdfviewer")) setUseSystemDefaultPdfViewer(value("printing/usesystemdefaultpdfviewer").toBool()); else setUseSystemDefaultPdfViewer(DEFAULT_USE_SYSTEM_PDF_VIEWER); // Action / Command settings if (contains("action/shortcutsdirectory")) setLatestShortcutsDirectory(value("action/shortcutsdirectory").toString()); else setLatestShortcutsDirectory(DEFAULT_SHORTCUTS_DIRECTORY); return settingsPage; } void CASettings::setMidiInPort(int in) { _midiInPort = in; #ifndef SWIGCPP if (CACanorus::midiDevice()) { CACanorus::midiDevice()->closeInputPort(); CACanorus::midiDevice()->openInputPort(midiInPort()); } #endif } #ifndef SWIGCPP /*! Search one single action in the list of actions (-1: entry not found) Returns an empty action element when the command was not found */ int CASettings::getSingleAction(const QString& oCommandName, QAction*& poResAction) { CASingleAction* poEntryAction; for (int i = 0; i < _oActionList.count(); i++) { poEntryAction = _oActionList[i]; if (poEntryAction->getCommandName() == oCommandName) { poResAction = poEntryAction->getAction(); return i; } } poResAction = _poEmptyEntry->getAction(); return -1; } int CASettings::getSingleAction(const QString& oCommandName, CASingleAction*& poResAction) { CASingleAction* poEntryAction; for (int i = 0; i < _oActionList.count(); i++) { poEntryAction = _oActionList[i]; if (poEntryAction->getCommandName() == oCommandName) { poResAction = poEntryAction; return i; } } poResAction = _poEmptyEntry; return -1; } /*! Updates an action in the action list Return 'true' if the update was successfull Warning: 1) The action will not be copied 2) Only shortcut and no midi information is updated 3) Description cannot be updated */ bool CASettings::setSingleAction(QAction oSingleAction, int iPos) { bool bRet = false; if (iPos >= 0 && iPos < _oActionList.count()) { _oActionList[iPos]->setCommandName(oSingleAction.objectName()); _oActionList[iPos]->setShortCutAsString(oSingleAction.shortcut().toString()); bRet = true; } return bRet; } /*! Takes a complete action list as it's own Manually: Removes all elements and copies every single in the own list Else: According to Qt doc "assigns the other list to this list" Warning: The actions themselves cannot be copied! */ void CASettings::setActionList(QList<CASingleAction*>& oActionList) { #ifdef COPY_ACTIONLIST_ELEMS_MANUALLY _oActionList.clear(); CASingleAction* pActionEntry; for (int i = 0; i < oActionList.count(); i++) { pActionEntry = &getSingleAction(i, oActionList); addSingleAction(*pActionEntry); } #else _oActionList = oActionList; #endif } /*! Adds a single action to the action list Warning: The action will be referenced! */ void CASettings::addSingleAction(CASingleAction& oSingleAction) { qWarning() << "CASettings::addSingleAction" << endl; #ifdef COPY_ACTIONLIST_ELEMS_MANUALLY CASingleAction* pActionEntry = new CASingleAction(0); // parent ? pActionEntry->setCommandName(oSingleAction.getCommandName()); pActionEntry->setDescription(oSingleAction.getDescription()); pActionEntry->setShortCutAsString(oSingleAction.getShortCutAsString()); pActionEntry->setMidiKeySequence(oSingleAction.getMidiKeySequence()); pActionEntry->newAction(oSingleAction.getAction()->parent()); pActionEntry->getAction()->setObjectName(oSingleAction.getAction()->objectName()); pActionEntry->getAction()->setActionGroup(oSingleAction.getAction()->actionGroup()); pActionEntry->getAction()->setAutoRepeat(oSingleAction.getAction()->autoRepeat()); pActionEntry->getAction()->setCheckable(oSingleAction.getAction()->isCheckable()); pActionEntry->getAction()->setChecked(oSingleAction.getAction()->isChecked()); pActionEntry->getAction()->setData(oSingleAction.getAction()->data()); pActionEntry->setAction(oSingleAction.getAction()); _oActionList.append(pActionEntry); #else _oActionList.append(&oSingleAction); #endif qWarning() << "New size is " << _oActionList.size() << endl; } /*! Removes a single action from the action list Return 'true' when succesfull Warning: The action itself is not deleted! */ bool CASettings::deleteSingleAction(QString oCommand, CASingleAction*& poResAction) { bool bRet = false; int iPos = getSingleAction(oCommand, poResAction); if (iPos >= 0) // Double entries should not be in the list { _oActionList.removeOne(poResAction); bRet = true; } #ifdef COPY_ACTIONLIST_ELEMS_MANUALLY delete poResAction; poResAction = 0; #endif return bRet; } void CASettings::readRecentDocuments() { for (int i = 0; contains(QString("files/recentdocument") + QString::number(i)); i++) CACanorus::addRecentDocument(value(QString("files/recentdocument") + QString::number(i)).toString()); } void CASettings::writeRecentDocuments() { for (int i = 0; contains(QString("files/recentdocument") + QString::number(i)); i++) remove(QString("files/recentdocument") + QString::number(i)); for (int i = 0; i < CACanorus::recentDocumentList().size(); i++) setValue(QString("files/recentdocument") + QString::number(i), CACanorus::recentDocumentList()[i]); } #endif // SWIGCPP /*! Returns the default settings path. This function is static and is used when no config filename is specified or when a plugin wants a settings directory to store its own settings in. */ const QString CASettings::defaultSettingsPath() { #ifdef Q_WS_WIN // M$ is of course an exception return QDir::homePath() + "/Application Data/Canorus"; #else // POSIX systems use the same config file path return QDir::homePath() + "/.config/Canorus"; #endif }
19,398
C++
.cpp
463
37.349892
117
0.740391
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,302
notechecker.cpp
canorusmusic_canorus/src/core/notechecker.cpp
/*! Copyright (c) 2015-2019, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QObject> #include "core/notechecker.h" #include "score/notecheckererror.h" #include "score/chordnamecontext.h" #include "score/sheet.h" #include "score/staff.h" #include "score/barline.h" #include "score/chordname.h" #include "score/playablelength.h" #include "score/timesignature.h" /*! \class CANoteChecker \brief Class checking the user errors in the score (e.g. too long bars etc.) This class is spell checker that provides tools for checking potential "typing" errors made by the user such as too little notes not filling the bar and similar. */ CANoteChecker::CANoteChecker() { } CANoteChecker::~CANoteChecker() { } /*! Parse/decompress an existing archive */ void CANoteChecker::checkSheet(CASheet* sheet) { sheet->clearNoteCheckerErrors(); // check for incomplete bars QList<CAContext*> contexts = sheet->contextList(); for (int i = 0; i < contexts.size(); i++) { switch (contexts[i]->contextType()) { case CAContext::Staff: { CAStaff* staff = static_cast<CAStaff*>(contexts[i]); QList<CAMusElement*> timeSigs = staff->timeSignatureRefs(); QList<CAMusElement*> barlines = staff->barlineRefs(); if (!timeSigs.size()) { continue; } int lastTimeSigIdx = 0; int lastTimeSigRequiredDuration = static_cast<CATimeSignature*>(timeSigs[lastTimeSigIdx])->barDuration(); int lastBarlineTime = -1; for (int j = 0; j < barlines.size(); j++) { if (static_cast<CABarline*>(barlines[j])->barlineType() == CABarline::Dotted) { continue; } if (((lastTimeSigIdx + 1) < timeSigs.size()) && barlines[j]->timeStart() > timeSigs[lastTimeSigIdx]->timeStart()) { // go to next time sig lastTimeSigIdx++; lastTimeSigRequiredDuration = static_cast<CATimeSignature*>(timeSigs[lastTimeSigIdx])->barDuration(); } // check the bar duration. // If first bar is partial, the length should be shorter or equal to time sig. if ((lastBarlineTime == -1 && barlines[j]->timeStart() > lastTimeSigRequiredDuration) || (lastBarlineTime != -1 && barlines[j]->timeStart() != lastBarlineTime + lastTimeSigRequiredDuration)) { CANoteCheckerError* nce = new CANoteCheckerError(barlines[j], QObject::tr("Bar duration incorrect.")); sheet->addNoteCheckerError(nce); } lastBarlineTime = barlines[j]->timeStart(); } break; } case CAContext::ChordNameContext: { CAChordNameContext* cnc = static_cast<CAChordNameContext*>(contexts[i]); for (int j = 0; j < cnc->chordNameList().size(); j++) { CAChordName* cn = cnc->chordNameList()[j]; if (cn->diatonicPitch().noteName() == CADiatonicPitch::Undefined && !cn->qualityModifier().isEmpty()) { CANoteCheckerError* nce = new CANoteCheckerError(cn, QObject::tr("Invalid chord name syntax. Please use chord pitch and optionally ':' and quality modifier. e.g. cis:m")); sheet->addNoteCheckerError(nce); } } break; } case CAContext::LyricsContext: case CAContext::FunctionMarkContext: case CAContext::FiguredBassContext: break; } } }
3,735
C++
.cpp
85
34.941176
208
0.623623
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,303
actiondelegate.cpp
canorusmusic_canorus/src/core/actiondelegate.cpp
/*! Copyright (c) 2015-2019, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include <QDebug> #include "actiondelegate.h" #include "canorus.h" #include "settings.h" #include "ui/mainwin.h" #include "ui/singleaction.h" CAActionDelegate::CAActionDelegate(CAMainWin* mainWin) { _mainWin = mainWin; } // Add a single action to the list of actions from Settings (copy action parameters) void CAActionDelegate::addSingleAction(const QString& oCommandName, const QString& oDescription, const QAction& oAction) { CASingleAction* pMainAction = new CASingleAction(_mainWin); if (pMainAction) { //pMainAction->setAction( &oAction ); pMainAction->newAction(); pMainAction->fromQAction(oAction, *pMainAction); pMainAction->setCommandName(oCommandName); pMainAction->setDescription(oDescription); pMainAction->setShortCutAsString(oAction.shortcut().toString()); //pMainAction->setMidiKeySequence( oMidiKeySequence ); // ToDo CACanorus::settings()->addSingleAction(*pMainAction); } } // Update an action with the settings parameters of a single action (copy single action parameters) void CAActionDelegate::updateSingleAction(CASingleAction& oSource, QAction& oAction) { oAction.setText(oSource.getCommandName()); oAction.setStatusTip(oSource.getDescription()); oAction.setShortcut(oSource.getAction()->shortcut()); //oAction->setMidiKeySequence( oSource.getMidiKeySequence ); // ToDo oAction.setObjectName(oSource.getAction()->objectName()); oAction.setActionGroup(oSource.getAction()->actionGroup()); oAction.setAutoRepeat(oSource.getAction()->autoRepeat()); oAction.setCheckable(oSource.getAction()->isCheckable()); oAction.setChecked(oSource.getAction()->isChecked()); oAction.setData(oSource.getAction()->data()); } // Add Actions from CAMainWin to the list of actions of the settings (initialization) void CAActionDelegate::addWinActions(QWidget& widget) { // Hard coded description could be changed to Status Tip Text (if available) //addSingleAction(_mainWin->uiQuit->text(),_mainWin->tr("Exit program"),*_mainWin->uiQuit); QList<QAction*> actionList = widget.actions(); qWarning() << "Delegate: Adding " << actionList.size() << " actions "; QAction* actionEntry; foreach (actionEntry, actionList) { qWarning("Adding new action %s to shortcut list of size %d", actionEntry->text().toLatin1().constData(), widget.actions().size()); addSingleAction(actionEntry->text(), actionEntry->toolTip(), *actionEntry); } } // Remove all CAMainWin actions from the list of (single) actions in settings (exit program) void CAActionDelegate::removeMainWinActions() { CASingleAction* poAction; while (0 != CACanorus::settings()->getActionList().isEmpty()) { poAction = CACanorus::settings()->getActionList().back(); if (poAction) { CACanorus::settings()->deleteSingleAction(poAction->getCommandName(), poAction); delete poAction; poAction = nullptr; } } } // Update all CAMainWin actions using the shortcuts (etc.) read from the settings void CAActionDelegate::updateMainWinActions() { CASingleAction* poResAction; CACanorus::settings()->getSingleAction(_mainWin->uiQuit->text(), poResAction); updateSingleAction(*poResAction, *_mainWin->uiQuit); }
3,540
C++
.cpp
77
41.597403
138
0.73509
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,304
archive.cpp
canorusmusic_canorus/src/core/archive.cpp
/*! Copyright (c) 2007-2020, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QByteArray> #include <QRegExp> #include <QString> #include <QTemporaryFile> #include <zlib.h> #ifdef Q_OS_WIN #include <QSysInfo> #endif #include "core/archive.h" #include "core/tar.h" /*! \class CAArchive \brief Class for the manipulation of a gzipped tar archive (tar.gz) This class allows read/write operations on tar.gz archives. \warning This is not a CATar subclass as it does not represent a tar file, but a gzipped file. The uncompressed content is a tar file. See RFC 1952 for the GZIP specification. */ const int CAArchive::CHUNK = 16384; const QString CAArchive::COMMENT = "Canorus Archive v" + QString(CANORUS_VERSION).remove(QRegExp("[a-z]*$")); /*! Creates and empty archive */ CAArchive::CAArchive() : _err(false) { _tar = new CATar(); } /*! Read an existing archive. */ CAArchive::CAArchive(QIODevice& arch) : _err(false) { parse(arch); } /*! Destory the archive */ CAArchive::~CAArchive() { delete _tar; } /*! Parse/decompress an existing archive */ void CAArchive::parse(QIODevice& arch) { bool close = false; int ret; z_stream strm; QTemporaryFile tar; QBuffer in, out; gz_header header = gz_header(); in.buffer().resize(CHUNK); out.buffer().resize(CHUNK); tar.open(); if (!arch.isOpen()) { if (!arch.open(QIODevice::ReadOnly)) { _err = true; // _tar is invalid. return; } close = true; } header.os = getOS(); header.comment = new unsigned char[21]; header.comm_max = 21; // decompress arch.reset(); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; strm.avail_in = 0; strm.next_in = Z_NULL; ret = inflateInit2(&strm, 31); ret = (ret == Z_OK) ? inflateGetHeader(&strm, &header) : ret; if (ret != Z_OK) //clean up, set error and return { delete[] header.comment; inflateEnd(&strm); if (close) arch.close(); return; } // decompress until deflate stream ends or EOF do { strm.avail_in = arch.read(in.buffer().data(), CHUNK); if (strm.avail_in == 0) break; // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else strm.next_in = reinterpret_cast<Bytef*>(in.buffer().data()); do { strm.avail_out = CHUNK; // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else strm.next_out = reinterpret_cast<Bytef*>(out.buffer().data()); ret = inflate(&strm, Z_NO_FLUSH); if ((ret != Z_OK && ret != Z_STREAM_END && ret != Z_BUF_ERROR) || // buffer error is not fatal tar.write(out.buffer().data(), CHUNK - strm.avail_out) != CHUNK - strm.avail_out) { _err = true; break; } } while (strm.avail_out == 0); } while (ret != Z_STREAM_END && !_err); inflateEnd(&strm); if (ret != Z_STREAM_END) _err = true; if (!_err) { QRegExp re("Canorus Archive v(\\d+\\.\\d+)"); // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else if (re.indexIn(reinterpret_cast<char*>(header.comment)) != -1) _version = re.cap(1); else { _err = true; } tar.reset(); _tar = new CATar(tar); } delete[] header.comment; if (close) arch.close(); } /*! Write the tar.gz archive into the given device. Returns the number of byte written, or -1 on error. */ qint64 CAArchive::write(QIODevice& dest) { bool close = false; int ret, flush; qint64 total = 0, read; z_stream strm; gz_header header = gz_header(); QBuffer in, out; if (!dest.isOpen()) { if (!dest.open(QIODevice::WriteOnly)) return -1; close = true; } if (!dest.isWritable() || error()) { if (close) dest.close(); return -1; } header.os = getOS(); header.comment = new unsigned char[COMMENT.size() + 1]; // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else strcpy(reinterpret_cast<char*>(header.comment), COMMENT.toLatin1().data()); in.open(QIODevice::ReadWrite); out.open(QIODevice::ReadWrite); in.buffer().resize(CHUNK); out.buffer().resize(CHUNK); strm.zalloc = Z_NULL; strm.zfree = Z_NULL; strm.opaque = Z_NULL; ret = deflateInit2(&strm, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY); ret = (ret == Z_OK) ? deflateSetHeader(&strm, &header) : ret; if (ret != Z_OK) { deflateEnd(&strm); delete[] header.comment; if (close) dest.close(); in.close(); out.close(); return -1; } //compress until EOF _tar->open(in); do { in.reset(); ret = _tar->write(in, CHUNK); if (ret == -1) { _err = true; break; } flush = _tar->eof(in) ? Z_FINISH : Z_NO_FLUSH; strm.avail_in = ret; // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else strm.next_in = reinterpret_cast<unsigned char*>(in.buffer().data()); do { strm.avail_out = CHUNK; // The code purposely could cut contents of the array. // For strings it would only work with ASCII code nothing else strm.next_out = reinterpret_cast<unsigned char*>(out.buffer().data()); ret = deflate(&strm, flush); if (ret == Z_STREAM_ERROR) _err = true; read = (!_err) ? dest.write(out.buffer().data(), CHUNK - strm.avail_out) : 0; if (_err || (read != CHUNK - strm.avail_out)) { _err = true; break; } total += read; } while (strm.avail_out == 0); if (strm.avail_in != 0) _err = true; } while (flush != Z_FINISH && !_err); deflateEnd(&strm); if (ret != Z_STREAM_END) _err = true; delete[] header.comment; if (close) dest.close(); _tar->close(in); in.close(); out.close(); return (_err) ? -1 : total; } /*! Return an operating system ID for use in a GZip header. See RFC 1952. */ int CAArchive::getOS() { #ifdef Q_OS_WIN if (QSysInfo::WindowsVersion & QSysInfo::WV_NT_based) return 11; // rfc 1952: "NTFS filesystem (NT)" else return 0; // rfc 1952: "FAT filesystem (MS-DOS, OS/2, NT/Win32" #else // Mac or Linux/Unix/FreeBSD/... return 3; // rfc 1952: "Unix". That what gzip does on Darwin (though there's 7 for "Macintosh"). #endif }
7,166
C++
.cpp
231
24.735931
136
0.589855
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,305
tar.cpp
canorusmusic_canorus/src/core/tar.cpp
/*! Copyright (c) 2007-2020, Itay Perl, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include <QBuffer> #include <QDateTime> #include <QDir> #include <QString> #include <QTemporaryFile> #include <QDebug> #include <cmath> // pow() #include "core/tar.h" /*! \class CATar \brief Class for the manipulation of tar files This class can create and read tar archives, which allow concatenation of multiple files (with directory structure) into a single file. The archive must be opened using \a open() before writing, and closed with close() when writing is done. Don't forget to close() the archive when you're done! For more info on the Tar format see <http://en.wikipedia.org/wiki/Tar_(file_format)>. */ const int CATar::CHUNK = 16384; /*! Creates an empty tar file */ CATar::CATar() : _ok(true) { /* An empty file is a valid tar */ } /*! Destroys a tar archive */ CATar::~CATar() { for (CATarFile* t : _files) { delete t->data; // deletes temp file from disk delete t; } } /*! Parse the given tar file and allow reading from it. */ CATar::CATar(QIODevice& data) : _ok(true) { parse(data); } /*! Parses an existing tar file and initializes this object to represent it. Parsing stops when a parsing errors occurs. The files that were parsed until the error will be available. error() can tell whether an error ocurred. */ void CATar::parse(QIODevice& tar) { bool wasOpen = true; int pad; if (!tar.isOpen()) { tar.open(QIODevice::ReadOnly); wasOpen = false; } while (!tar.atEnd()) { QByteArray hdrba = tar.read(512); CATarFile* file; QTemporaryFile* tempfile; int chksum, chkchksum = 0; if (hdrba.size() < 512) { _ok = false; break; } // Check magic first QByteArray magic = hdrba.mid(257, 6); QByteArray version = hdrba.mid(263, 2); if (magic != QString::fromLatin1("ustar") || version[0] != '0' || version[1] != '0') { _ok = false; continue; } QBuffer header(&hdrba); header.open(QIODevice::ReadOnly); file = new CATarFile; bufncpy(file->hdr.name, header.read(100).data(), 100); file->hdr.mode = header.read(8).toUInt(&_ok, 8); if (!_ok) return; file->hdr.uid = header.read(8).toUInt(&_ok, 8); if (!_ok) return; file->hdr.gid = header.read(8).toUInt(&_ok, 8); if (!_ok) return; file->hdr.size = header.read(12).toULongLong(&_ok, 8); if (!_ok) return; file->hdr.mtime = header.read(12).toUInt(&_ok, 8); if (!_ok) return; chksum = header.read(8).toInt(&_ok, 8); // recorded checksum if (!_ok) return; file->hdr.typeflag = header.read(1)[0]; bufncpy(file->hdr.linkname, header.read(100).data(), 100); header.read(6 + 2); //magic+header bufncpy(file->hdr.uname, header.read(32).data(), 32); bufncpy(file->hdr.gname, header.read(32).data(), 32); header.read(16); // nulls (devmajor, devminor) bufncpy(file->hdr.prefix, header.read(155).data(), 155); // get real checksum for (int i = 0; i < 148; i++) chkchksum += hdrba[i]; chkchksum += int(' ') * 8; for (int i = 156; i < 512; i++) chkchksum += hdrba[i]; if (chkchksum != chksum) { delete file; continue; } tempfile = new QTemporaryFile; tempfile->open(); file->data = tempfile; for (unsigned int i = 0; i < file->hdr.size / CHUNK; i++) file->data->write(tar.read(CHUNK)); file->data->write(tar.read(file->hdr.size % CHUNK)); file->data->flush(); pad = file->hdr.size % 512; if (pad > 0) tar.read(512 - pad); _files << file; } if (!wasOpen) tar.close(); } /** Returns true if the tar contains a file with the given filename. Otherwise false filename may be a relative path. */ bool CATar::contains(const QString& filename) { for (CATarFile* t : _files) { if (filename == t->hdr.name) return true; } return false; } /*! Adds a file to the tar archive. \param filename The full name of the file (including directory path). \param data A reader for the file. \param replace Whether to replace the file, if it's already in the archive. Default is true. \return True if the file has been added, false otherwise (e.g., file with the same name exists). */ bool CATar::addFile(const QString& filename, QIODevice& data, bool replace /* = true */) { if (contains(filename)) { if (!replace) return false; else removeFile(filename); } CATarFile* file = new CATarFile; // Basename only for use with prefix if ever required (see below). /// \todo slash in windows? win32 tar? //QString basename = filename.right(filename.lastIndexOf("/")); //bufncpy(file->hdr.name, basename.toUtf8(), basename.toUtf8().size(), 100); bufncpy(file->hdr.name, filename.toUtf8(), static_cast<size_t>(filename.toUtf8().size()), 100); file->hdr.mode = 0644; // file permissions. set read/write for user, read only for everyone else. file->hdr.size = static_cast<size_t>(data.size()); file->hdr.mtime = QDateTime::currentDateTime().toTime_t(); //FIXME file->hdr.chksum = 0; // later file->hdr.typeflag = '0'; // normal file bufncpy(file->hdr.linkname, nullptr, 0, 100); // Leave user/group info out. Not required AFAICT. file->hdr.uid = file->hdr.gid = 0; bufncpy(file->hdr.uname, "", 0, 32); bufncpy(file->hdr.gname, "", 0, 32); /* if there's need for larger file names with many nested directories, put the directory path (or part of it?) in prefix */ bufncpy(file->hdr.prefix, nullptr, 0, 155); QTemporaryFile* tempfile = new QTemporaryFile; tempfile->open(); file->data = tempfile; bool wasOpen = true; if (!data.isOpen()) { data.open(QIODevice::ReadOnly); wasOpen = false; } data.reset(); //seek to the beginning. // Save the uncompressed data in a temporary file. while (!data.atEnd()) file->data->write(data.read(CHUNK)); file->data->flush(); if (!wasOpen) data.close(); _files << file; return true; } /* A convenience method to add a file from a byte array. */ bool CATar::addFile(const QString& filename, QByteArray data, bool replace) { QBuffer buf(&data, nullptr); return addFile(filename, buf, replace); } /*! Remove a file from the archive */ void CATar::removeFile(const QString& filename) { for (CATarFile* t : _files) { if (filename == t->hdr.name) { delete t; _files.removeAll(t); } } } /*! Returns a reader for a file in the tar. If the file is not found, an empty buffer is returned. The function returns a smart (auto) pointer to a QIODevice. \param filename The file name (including its path if needed). */ CAIOPtr CATar::file(const QString& filename) { if (_files.isEmpty()) return CAIOPtr(new QBuffer()); for (CATarFile* t : _files) { if (filename == t->hdr.name) { QFile* f = new QFile(t->data->fileName()); f->open(QIODevice::ReadWrite); return CAIOPtr(f); } } return CAIOPtr(new QBuffer()); } /*! Converts the file header to ASCII octal format. */ void CATar::writeHeader(QIODevice& dest, int file) { CATarFile* f = _files[file]; char header[513]; char* p = header; quint64 chksum = 0; bufncpyi(p, f->hdr.name, 100); // Filename numToOcti(p, f->hdr.mode, 8); // File permissions numToOcti(p, f->hdr.uid, 8); // User ID numToOcti(p, f->hdr.gid, 8); // Group ID (*Nix/Mac(?) only) numToOcti(p, f->hdr.size, 12); // File size in bytes numToOcti(p, f->hdr.mtime, 12); // Modification time bufncpyi(p, " ", 8); // Checksum, the sum of bytes in the header, with the checksum block filled with spaces (ASCII: 32), computed later *(p++) = f->hdr.typeflag; bufncpyi(p, f->hdr.linkname, 100); bufncpyi(p, "ustar\0", 6); // Magic bufncpyi(p, "00", 2); // Version bufncpyi(p, f->hdr.uname, 32); // User name bufncpyi(p, f->hdr.gname, 32); // Group name bufncpyi(p, nullptr, 0, 16); // devminor/devmajor (what are these anyway?) bufncpyi(p, f->hdr.prefix, 155); // Prefix bufncpyi(p, nullptr, 0, 12); // Padding to 512 bytes. for (int i = 0; i < 500; i++) chksum += static_cast<quint64>(header[i]); // See above. numToOct(header + 148, chksum, 8); // Insert real checksum. dest.write(header, 512); } /*! Write the tar file into the given device in one call. Returns the number of chars written or -1 if an error ocurred. */ qint64 CATar::write(QIODevice& dest) { qint64 total = 0, i; while (!eof(dest)) { i = write(dest, CHUNK); if (i == -1) return -1; total += i; } return total; } /*! Writes the tar file into the given device in chunks. Returns the number of chars written, or -1 if an error occurred. \warning You must use the same QIODevice to get the next chunk. \param dest The destination device. \param chunk max size to write (call again for more). Must be >= 512. */ qint64 CATar::write(QIODevice& dest, qint64 chunk) { //bool close = false; qint64 ret, pad; qint64 total = 0; // Bytes written. //qint64 first_pos; if (chunk < 512) return -1; if (_files.isEmpty()) return 0; if (!_pos.contains(&dest)) return -2; // dest was not open()'d. CATarBufInfo& pos = _pos[&dest]; //first_pos = pos.pos; if (!dest.isOpen()) { if (!dest.open(QIODevice::WriteOnly)) return -1; pos.close = true; } if (!dest.isWritable()) { if (pos.close) dest.close(); return -1; } CATarFile* f; while (chunk >= 512) { f = _files[pos.file]; f->data->reset(); if (pos.pos == 0) { writeHeader(dest, pos.file); pos.pos += 512; total += 512; chunk -= 512; } f->data->seek(pos.pos - 512); ret = dest.write(f->data->read(chunk)); pos.pos += ret; total += ret; chunk -= ret; if (chunk == 0) break; pad = f->data->size() % 512; if (pad > 0) { // QByteArray is limited to max. signed integer value int minSize = static_cast<int>(pow(2, 31) - 1); // 2 GB-1 is a max size of a chunk. if (chunk > minSize) { qCritical() << "QByteArray size exceeded! " << qMin(chunk, qint64(512 - pad)) / pow(1024, 2) << " kb. Limited to 2GB."; } else { minSize = static_cast<int>(qMin(chunk, qint64(512 - pad))); } ret = dest.write(QByteArray(minSize, 0)); // Fill up the 512-block with nulls. pos.pos += ret; total += ret; chunk -= ret; } //proceed to next file. if (pos.file == _files.size() - 1) { pos.eof = true; break; } else { pos.pos = 0; ++pos.file; } } if (pos.close && pos.eof) // close on last chunk, if needed. dest.close(); return total; } /* Tells whether the whole tar has been written to \a dest. */ bool CATar::eof(QIODevice& dest) { //qint64 bufsize = _files.last()->data->size(); if (!_pos.contains(&dest)) return false; CATarBufInfo& pos = _pos[&dest]; if (_files.isEmpty()) return true; return pos.eof; } /*! Write the first \a len bytes in \a src to \a dest and fill \a dest with ASCII NULs up to \a bufsize. Similar strncpy but without enforcing null termination. If bufsize is -1 (the default), no NULs are added. */ char* CATar::bufncpy(char* dest, const char* src, size_t len, size_t bufsize) { if (bufsize == 0) bufsize = len; if (static_cast<int>(len) < 0) return dest; while (bufsize-- > len) dest[bufsize] = 0; while (len--) dest[len] = src[len]; return dest; } char* CATar::bufncpyi(char*& dest, const char* src, size_t len, size_t bufsize) { bufncpy(dest, src, len, bufsize); return (dest += ((bufsize == 0) ? len : bufsize)); } /*! Write \a num to \a buf in octal, with length \a width. Similar to snprintf but wihtout enforcing null termination. Null is inserted if it fits. */ char* CATar::numToOct(char* buf, quint64 num, size_t width) { if (num >= pow(8, width) || buf == nullptr) { return nullptr; // Crash somewhere else. } if (num < pow(8, (width - 1))) // null fits { char len[10]; /// \todo This code looks broken. width is put to the string instead of num sprintf(len, "%%0%ldo", static_cast<unsigned long>(width - 1)); /// \todo This code looks broken. num cannot be added to the string snprintf(buf, width, len, num); // adds null // Correct code could be // sprintf(len, "%%0%do", num-1); // snprintf(buf, static_cast<size_t>(width), "%s", len); // adds null } else { while (num) { char digit = num % 8; buf[--width] = '0' + digit; num = num / 8; } } return buf; } char* CATar::numToOcti(char*& buf, quint64 num, size_t width) { numToOct(buf, num, width); return (buf += width); }
13,864
C++
.cpp
421
26.866983
159
0.594558
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,306
file.cpp
canorusmusic_canorus/src/core/file.cpp
/*! Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "core/file.h" #include <QBuffer> #include <QFile> #include <QTextStream> /*! \class CAFile \brief File import/export base class This class brings tools for manipulating with files and streams (most notably import and export). Classes CAImport and CAExport inherit this class and implement specific methods for import and export. All file operations are done in a separate thread. While the file operations are in progress user can poll the status by calling status(), progress() and readableStatus() for human-readable status defined by the filter. Waiting for the thread to be finished can be implemented by calling QThread::wait() or by catching the signals emitted by children import and export classes. \sa CAImport, CAExport */ CAFile::CAFile() : QThread() { setProgress(0); setStatus(0); setStream(nullptr); setFile(nullptr); _deleteStream = false; } /*! Destructor. Also destroys the created stream and file, if set. */ CAFile::~CAFile() { if (stream() && _deleteStream) delete stream(); if (file()) delete file(); } /*! Creates and sets the stream from the file named \a filename. Stream is Read-only. This method is usually called from the main window when opening a document. This method is also very important for python developers as they cannot directly access QTextStream class, so they call this wrapper instead with a simple string as parameter. */ void CAFile::setStreamFromFile(const QString filename) { setFile(new QFile(filename)); if (file()->open(QIODevice::ReadOnly)) { if (stream() && _deleteStream) { delete stream(); } setStream(new QTextStream(file())); _deleteStream = true; } } #include <iostream> /*! Creates and sets the stream from the file named \a filename. Stream is Read-Write. This method is usually called from the main window when saving the document. This method is also very important for python developers as they cannot directly access QTextStream class, so they call this wrapper instead with a simple string as parameter. */ void CAFile::setStreamToFile(const QString filename) { if (stream() && _deleteStream) { delete stream(); setStream(nullptr); } setFile(new QFile(filename)); if (file()->open(QIODevice::WriteOnly)) { setStream(new QTextStream(file())); _deleteStream = true; } } /*! Creates and sets the stream from the given device. Read-write if the given device is not already open. */ void CAFile::setStreamToDevice(QIODevice* device) { if (stream() && _deleteStream) { delete stream(); setStream(nullptr); } if (!device->isOpen()) { device->open(QIODevice::ReadWrite); } if (device->isOpen()) { setStream(new QTextStream(device)); _deleteStream = true; } } /*! Creates and sets a new virtual IO device usually used for exporting document to a string when QTextStream/QIODevice API is not available (eg. when writing external Python plugins). \sa getStreamAsString() */ void CAFile::setStreamToString() { QBuffer* score = new QBuffer(); setStreamToDevice(score); } /*! This function is provided for convenience when QTextStream/QIODevice API is not available (eg. when writing external Python plugins). It returns the exported value as UTF-8 encoded string. To use this function first initialize the export filter using setStreamToString(). \sa setStreamToString() */ QString CAFile::getStreamAsString() { if (!stream()) { return ""; } else { return QString::fromUtf8(static_cast<QBuffer*>(stream()->device())->data()); } } /*! Creates and sets the stream from the given device. Read-only if the device is not already open. */ void CAFile::setStreamFromDevice(QIODevice* device) { if (stream() && _deleteStream) { delete stream(); setStream(nullptr); } if (!device->isOpen()) { device->open(QIODevice::ReadOnly); } if (device->isOpen()) { CAFile::setStream(new QTextStream(device)); _deleteStream = true; } } /*! \function int CAFile::status() The number describes the current status of the operations. Possible values are: 0 - filter is ready (not started yet or successfully done) greater than 0 - filter is busy, custom filter status -1 - file not found or cannot be opened lesser than -1 - custom filter errors */ /*! \function const QString CAFile::readableStatus() Human readable status eg. the one shown in the status bar. The current status should be reimplemented in children classes. */
4,907
C++
.cpp
154
28.233766
107
0.715435
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,307
mimedata.cpp
canorusmusic_canorus/src/core/mimedata.cpp
/*! Copyright (c) 2007, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See LICENSE.GPL for details. */ #include "core/mimedata.h" #include "score/context.h" /*! Subclass of QMimeData which incorporates list of Music elements for copy/paste functionality. MIME types for Canorus contexts are "application/canorus-contexts". */ const QString CAMimeData::CANORUS_MIME_TYPE = "application/canorus-contexts"; CAMimeData::CAMimeData() : QMimeData() { } CAMimeData::CAMimeData(QList<CAContext*> list) : QMimeData() { setContexts(list); } CAMimeData::~CAMimeData() { for (int i = 0; i < contexts().size(); i++) delete contexts().at(i); } QStringList CAMimeData::formats() const { QStringList curFormats = QMimeData::formats(); if (hasContexts()) curFormats << CANORUS_MIME_TYPE; return curFormats; } bool CAMimeData::hasFormat(const QString format) const { return formats().contains(format); }
1,057
C++
.cpp
38
25.131579
77
0.742319
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,308
autorecovery.cpp
canorusmusic_canorus/src/core/autorecovery.cpp
/*! Copyright (c) 2007-2020, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "core/autorecovery.h" #include "canorus.h" #include "core/settings.h" #include "export/canorusmlexport.h" #include "import/canorusmlimport.h" #include <QFile> #include <QMessageBox> #include <QSet> #include <QTimer> /*! \class CAAutoRecovery \brief Class for making recovery files for application crashes Canorus creates recovery files in Canorus writeable settings directory for each currently opened document every number of minutes defined in CASettings. If the application is closed nicely, recovery files must be cleaned by calling cleanupRecovery() method. Otherwise Canorus looks for recovery files then next time it's executed and opens them automatically by calling openRecovery(). After recovering the files documents are marked as modified (so user needs to resave them, if closing the document by accident) and a special short-interval singleshot timer (see _saveAfterRecoveryInterval) is started to resave recovery files. This is usually needed when a user finds a bug, immediately repeats it and the autosave interval usually set to few minutes is not triggered yet. Recovery documents are not resaved immediately because Canorus might crash when recovering them (or soon after eg. mouse move) and is in unusable state until recovery files are manually deleted. Call saveRecovery() to save the currently opened documents to recovery files. The autosave timer's signal is connected to this slot. Settings class should already be initialized when creating instance of this class. */ /*! Initializes autosave. Reads the autosave timer settings from the CASettings class. */ CAAutoRecovery::CAAutoRecovery() : _saveAfterRecoveryTimer(nullptr) { _autoRecoveryTimer = new QTimer(this); _autoRecoveryTimer->setSingleShot(false); connect(_autoRecoveryTimer, SIGNAL(timeout()), this, SLOT(saveRecovery())); updateTimer(); // reads interval from settings and starts the timer } CAAutoRecovery::~CAAutoRecovery() { delete _autoRecoveryTimer; } /*! Sets auto recovery interval to \a msec miliseconds. */ void CAAutoRecovery::updateTimer() { _autoRecoveryTimer->stop(); _autoRecoveryTimer->setInterval(CACanorus::settings()->autoRecoveryInterval() * 60000); if (CACanorus::settings()->autoRecoveryInterval()) _autoRecoveryTimer->start(); } /*! Saves the currently opened documents into settings folder named recovery0, recovery1 etc. */ void CAAutoRecovery::saveRecovery() { cleanupRecovery(); QSet<CADocument*> documents; for (int i = 0; i < CACanorus::mainWinList().size(); i++) documents << CACanorus::mainWinList()[i]->document(); int c = 0; for (QSet<CADocument*>::const_iterator i = documents.constBegin(); i != documents.constEnd(); i++, c++) { CACanorusMLExport save; save.setStreamToFile(CASettings::defaultSettingsPath() + "/recovery" + QString::number(c)); save.exportDocument(*i); save.wait(); } } /*! Deletes recovery files. This method is usually called when successfully quiting Canorus. */ void CAAutoRecovery::cleanupRecovery() { for (int i = 0; QFile::exists(CASettings::defaultSettingsPath() + "/recovery" + QString::number(i)); i++) { QString fileName = CASettings::defaultSettingsPath() + "/recovery" + QString::number(i); QFile::remove(fileName); if (QDir(fileName + " files").exists()) { foreach (QString entry, QDir(fileName + " files").entryList(QDir::Files)) { QFile::remove(fileName + " files/" + entry); } QDir().rmdir(fileName + " files"); } } } /*! Searches for any not-cleaned up recovery files and opens them. Also shows the recovery message. */ void CAAutoRecovery::openRecovery() { QString documents; for (int i = 0; QFile::exists(CASettings::defaultSettingsPath() + "/recovery" + QString::number(i)); i++) { CACanorusMLImport open; open.setStreamFromFile(CASettings::defaultSettingsPath() + "/recovery" + QString::number(i)); open.importDocument(); open.wait(_recoveryTimeout); if (open.importedDocument()) { open.importedDocument()->setModified(true); // warn that the file is unsaved, if closing open.importedDocument()->setFileName(""); // ToDo: Only one place of mainwin creation / initialization CAMainWin* mainWin = new CAMainWin(); // Init dialogs etc. CACanorus::initCommonGUI(mainWin->uiSaveDialog, mainWin->uiOpenDialog, mainWin->uiExportDialog, mainWin->uiImportDialog); documents.append(tr("- Document %1 last modified on %2.").arg(open.importedDocument()->title()).arg(open.importedDocument()->dateLastModified().toString()) + "\n"); mainWin->openDocument(open.importedDocument()); mainWin->show(); } } cleanupRecovery(); if (!documents.isEmpty()) { if (_saveAfterRecoveryTimer) delete _saveAfterRecoveryTimer; _saveAfterRecoveryTimer = new QTimer(); _saveAfterRecoveryTimer->setInterval(4000); _saveAfterRecoveryTimer->setSingleShot(true); connect(_saveAfterRecoveryTimer, SIGNAL(timeout()), this, SLOT(saveRecovery())); _saveAfterRecoveryTimer->start(); QMessageBox::information( CACanorus::mainWinList()[CACanorus::mainWinList().size() - 1], tr("Document recovery"), tr("Previous session of Canorus was unexpectedly closed.\n\n\ The following documents were successfully recovered:\n%1") .arg(documents)); } }
5,881
C++
.cpp
137
37.554745
176
0.707918
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false
1,532,309
muselementfactory.cpp
canorusmusic_canorus/src/core/muselementfactory.cpp
/*! Copyright (c) 2006-2020, Reinhard Katzmann, Matevž Jekovec, Canorus development team All Rights Reserved. See AUTHORS for a complete list of authors. Licensed under the GNU GENERAL PUBLIC LICENSE. See COPYING for details. */ #include "core/muselementfactory.h" #include "score/articulation.h" #include "score/bookmark.h" #include "score/chordnamecontext.h" #include "score/dynamic.h" #include "score/figuredbasscontext.h" #include "score/functionmarkcontext.h" #include "score/instrumentchange.h" #include "score/playable.h" #include "score/sheet.h" #include "score/text.h" #include "score/tuplet.h" #include "canorus.h" // needed for CASettings #include "core/settings.h" /*! \class CAMusElementFactory \brief creation, removal, configuration of music elements This class is used when creating a new music element, settings its values, but not having it placed inside the score (eg. music element still in the GUI, but user didn't clicked on the score to place it yet). The factory contains the methods to set properties of all the available music elements ranging from playable elements to slurs and lyrics. The actual music element is created and added to the scene when one of the configure functions are called. These functions return True, if the element was successfully created or False otherwise. This class should be typically used in the following order: 1) User selects a music element to place. CAMusElementFactory::setMusElementType() is called. 2) GUI for music element properties is updated according to the current factory values. 3) User sets music element properties he wants (eg. number of accidentals in key signature). CAMusElementFactory::setSomeMusicElementProperty( music element property value ) is called (eg. CAMusElementFactory::setKeySigNumberOfAccs(3) for A-Major/fis-minor). 4) User places the music element. CAMusElementFactory::configureSomeMusicElement() (eg. CAMusElementFactory::configureKeySignature(currentStaff, prevElement)). 5) If the configure function returns True, the GUI is refreshed and the note is drawn. Changing the properties of already placed elements (eg. in edit mode) is done without using the factory. \sa CAMainWin, CAMusElement */ /*! Creates an empty, defeault music elements factory. */ CAMusElementFactory::CAMusElementFactory() { _playableLength = CAPlayableLength(CAPlayableLength::Quarter); _eNoteStemDirection = CANote::StemPreferred; _iPlayableDotted = 0; _eRestType = CARest::Normal; _iTimeSigBeats = 4; _iTimeSigBeat = 4; _diatonicKeyNumberOfAccs = 0; _diatonicKeyGender = CADiatonicKey::Major; _eClef = CAClef::Treble; _iClefOffset = 0; _iNoteAccs = 0; _iNoteExtraAccs = 0; _eBarlineType = CABarline::Single; _eSlurType = CASlur::TieType; _slurStyle = CASlur::SlurSolid; _fbmNumber = 6; _fbmAccs = 0; _fbmAccsVisible = false; _fmFunction = CAFunctionMark::T; // Name of the function _fmChordArea = CAFunctionMark::Undefined; // Chord area of the function _fmTonicDegree = CAFunctionMark::T; // Tonic degree of the function _fmFunctionMinor = false; _fmChordAreaMinor = false; _fmTonicDegreeMinor = false; _fmEllipse = false; _musElementType = CAMusElement::Undefined; mpoEmpty = new CANote(CADiatonicPitch(), CAPlayableLength(), nullptr, 0); // dummy element mpoMusElement = mpoEmpty; _dynamicText = "mf"; _dynamicVolume = 80; _instrument = 0; _fermataType = CAFermata::NormalFermata; _tempoBeat = CAPlayableLength(CAPlayableLength::Half); _tempoBpm = 72; _crescendoFinalVolume = 50; _crescendoType = CACrescendo::Crescendo; _repeatMarkType = CARepeatMark::Volta; _repeatMarkVoltaNumber = 1; _fingeringFinger = CAFingering::First; _fingeringOriginal = false; } /*! Destroys the music elements factory. */ CAMusElementFactory::~CAMusElementFactory() { removeMusElem(true); delete mpoEmpty; } /*! Removes the current music element. Destroys the music element, if \a bReallyRemove is true (default is false). */ void CAMusElementFactory::removeMusElem(bool bReallyRemove /* = false */) { if (mpoMusElement && mpoMusElement != mpoEmpty && bReallyRemove) delete mpoMusElement; mpoMusElement = mpoEmpty; } void CAMusElementFactory::addPlayableDotted(int add, CAPlayableLength l) { _playableLength.setDotted((_playableLength.dotted() + add) % 4); // FIXME: magic number 4 is max. number of flags. // If 128th will be visible in the gui, _playableLength.dotted() could be one higher. // // the more flags a to be inserted note has, the less dots are allowed: // switch (l.musicLength()) { case CAPlayableLength::Eighth: if (_playableLength.dotted() > 3) _playableLength.setDotted(0); break; case CAPlayableLength::Sixteenth: if (_playableLength.dotted() > 2) _playableLength.setDotted(0); break; case CAPlayableLength::ThirtySecond: if (_playableLength.dotted() > 1) _playableLength.setDotted(0); break; case CAPlayableLength::SixtyFourth: if (_playableLength.dotted() > 0) _playableLength.setDotted(0); break; default: break; ; } }; /*! Configures a new clef music element in \a context and right before the \a right element. */ bool CAMusElementFactory::configureClef(CAStaff* staff, CAMusElement* right) { bool success = false; if (staff && staff->voiceList().size()) { mpoMusElement = new CAClef(_eClef, staff, 0, _iClefOffset); success = staff->voiceList()[0]->insert(right, mpoMusElement); if (!success) removeMusElem(true); } return success; } /*! Configures a new key signature music element with \a iKeySignature accidentals, \a context and right before the \a right element. */ bool CAMusElementFactory::configureKeySignature(CAStaff* staff, CAMusElement* right) { bool success = false; if (staff && staff->voiceList().size()) { mpoMusElement = new CAKeySignature(CADiatonicKey(_diatonicKeyNumberOfAccs, _diatonicKeyGender), staff, 0); success = staff->voiceList()[0]->insert(right, mpoMusElement); if (!success) removeMusElem(true); } return success; } /*! Configures a new time signature music element with \a context and right before the \a right element. */ bool CAMusElementFactory::configureTimeSignature(CAStaff* staff, CAMusElement* right) { bool success = false; if (staff && staff->voiceList().size()) { mpoMusElement = new CATimeSignature(_iTimeSigBeats, _iTimeSigBeat, staff, 0); success = staff->voiceList()[0]->insert(right, mpoMusElement); if (!success) removeMusElem(true); } return success; } /*! Configures a new barline with \a context and right before the \a right element. */ bool CAMusElementFactory::configureBarline(CAStaff* staff, CAMusElement* right) { bool success = false; if (staff && staff->voiceList().size()) { mpoMusElement = new CABarline(_eBarlineType, staff, 0); success = staff->voiceList()[0]->insert(right, mpoMusElement); if (!success) removeMusElem(true); } return success; } /*! Configures new note music element in the \a voice before element \a right. If \a addToChord is true and right is note, the element is added to the note instead of inserted. */ bool CAMusElementFactory::configureNote(int pitch, CAVoice* voice, CAMusElement* right, bool addToChord) { bool bSuccess = false; removeMusElem(); if (right && addToChord) { mpoMusElement = new CANote(CADiatonicPitch(pitch, _iNoteAccs), static_cast<CANote*>(right)->playableLength(), voice, 0, // timeStart is set when inserting to voice static_cast<CANote*>(right)->timeLength()); bSuccess = voice->insert(right, mpoMusElement, true); if (static_cast<CANote*>(right)->tuplet()) { static_cast<CANote*>(right)->tuplet()->addNote(static_cast<CAPlayable*>(mpoMusElement)); static_cast<CANote*>(mpoMusElement)->setTuplet(static_cast<CANote*>(right)->tuplet()); } } else { mpoMusElement = new CANote(CADiatonicPitch(pitch, _iNoteAccs), _playableLength, voice, 0); // add an empty syllable or reposit syllables static_cast<CANote*>(mpoMusElement)->setStemDirection(_eNoteStemDirection); bSuccess = voice->insert(right, mpoMusElement, false); if (voice->lastNote() == mpoMusElement) { // note was appended, reposition elements in dependent contexts accordingly for (CALyricsContext* lc : voice->lyricsContextList()) { lc->repositionElements(); } for (CAContext* context : voice->staff()->sheet()->contextList()) { switch (context->contextType()) { case CAContext::FunctionMarkContext: static_cast<CAFunctionMarkContext*>(context)->repositionElements(); break; case CAContext::FiguredBassContext: static_cast<CAFiguredBassContext*>(context)->repositionElements(); break; case CAContext::ChordNameContext: static_cast<CAChordNameContext*>(context)->repositionElements(); break; default: break; } } } else { // note was inserted somewhere inbetween, insert empty element in dependent contexts accordingly for (CALyricsContext* lc : voice->lyricsContextList()) { lc->insertEmptyElement(mpoMusElement->timeStart()); lc->repositionElements(); } for (CAContext* context : voice->staff()->sheet()->contextList()) { switch (context->contextType()) { case CAContext::FunctionMarkContext: case CAContext::FiguredBassContext: case CAContext::ChordNameContext: context->insertEmptyElement(mpoMusElement->timeStart()); context->repositionElements(); break; default: break; } } } } if (bSuccess) { static_cast<CANote*>(mpoMusElement)->updateTies(); } else removeMusElem(true); return bSuccess; } /*! Configures the new tie, slur or phrasing slur for the notes \a noteStart and \a noteEnd. */ bool CAMusElementFactory::configureSlur(CAStaff* staff, CANote* noteStart, CANote* noteEnd) { bool success = false; removeMusElem(); CASlur* slur = new CASlur(slurType(), CASlur::SlurPreferred, staff, noteStart, noteEnd); mpoMusElement = slur; slur->setSlurStyle(slurStyle()); switch (slurType()) { case CASlur::TieType: noteStart->setTieStart(slur); if (noteEnd) noteEnd->setTieEnd(slur); success = true; break; case CASlur::SlurType: noteStart->setSlurStart(slur); if (noteEnd) noteEnd->setSlurEnd(slur); success = true; break; case CASlur::PhrasingSlurType: noteStart->setPhrasingSlurStart(slur); if (noteEnd) noteEnd->setPhrasingSlurEnd(slur); success = true; break; } if (!success) removeMusElem(true); return success; } /*! Configures the new mark and adds it to the \a elt. */ bool CAMusElementFactory::configureMark(CAMusElement* elt) { bool success = false; if (elt->musElementType() == CAMusElement::Mark) return false; switch (markType()) { case CAMark::Dynamic: { if (elt->musElementType() == CAMusElement::Note) { mpoMusElement = new CADynamic(dynamicText(), dynamicVolume(), static_cast<CANote*>(elt)); success = true; } break; } case CAMark::Crescendo: { if (elt->musElementType() == CAMusElement::Note) { mpoMusElement = new CACrescendo(crescendoFinalVolume(), static_cast<CANote*>(elt), crescendoType()); success = true; } break; } case CAMark::Text: { if (elt->isPlayable()) { mpoMusElement = new CAText("", static_cast<CAPlayable*>(elt)); success = true; } break; } case CAMark::BookMark: { mpoMusElement = new CABookMark("", elt); success = true; break; } case CAMark::InstrumentChange: { if (elt->musElementType() == CAMusElement::Note) { mpoMusElement = new CAInstrumentChange(instrument(), static_cast<CANote*>(elt)); success = true; } break; } case CAMark::Tempo: { mpoMusElement = new CATempo(tempoBeat(), tempoBpm(), elt); success = true; break; } case CAMark::Ritardando: { if (elt->isPlayable()) { mpoMusElement = new CARitardando(50, static_cast<CAPlayable*>(elt), elt->timeLength() * 2, ritardandoType()); success = true; } break; } case CAMark::Pedal: { mpoMusElement = new CAMark(CAMark::Pedal, elt); success = true; break; } case CAMark::Fermata: { if (elt->isPlayable()) { mpoMusElement = new CAFermata(static_cast<CAPlayable*>(elt), fermataType()); success = true; } else if (elt->musElementType() == CAMusElement::Barline) { mpoMusElement = new CAFermata(static_cast<CABarline*>(elt), fermataType()); success = true; } break; } case CAMark::RepeatMark: { if (elt->musElementType() == CAMusElement::Barline) { mpoMusElement = new CARepeatMark(static_cast<CABarline*>(elt), repeatMarkType(), (repeatMarkType() == CARepeatMark::Volta ? repeatMarkVoltaNumber() : 0)); success = true; } break; } case CAMark::RehersalMark: { if (elt->musElementType() == CAMusElement::Barline) { mpoMusElement = new CAMark(CAMark::RehersalMark, elt); success = true; } break; } case CAMark::Fingering: { if (elt->musElementType() == CAMusElement::Note) { mpoMusElement = new CAFingering(fingeringFinger(), static_cast<CANote*>(elt), isFingeringOriginal()); success = true; } break; } case CAMark::Articulation: { if (elt->musElementType() == CAMusElement::Note) { mpoMusElement = new CAArticulation(articulationType(), static_cast<CANote*>(elt)); success = true; } break; } case CAMark::Undefined: { fprintf(stderr, "Warning: CAMusElementFactory::configureMark - Undefined Mark"); break; } } if (success) { elt->addMark(static_cast<CAMark*>(mpoMusElement)); return true; } return false; } /*! Configures a new rest music element in voice \a voice before element \a right. */ bool CAMusElementFactory::configureRest(CAVoice* voice, CAMusElement* right) { bool success = false; if (voice) { mpoMusElement = new CARest(restType(), _playableLength, voice, 0); success = voice->insert(right, mpoMusElement); if (!success) removeMusElem(true); else { for (CALyricsContext* lc : voice->lyricsContextList()) { lc->repositionElements(); } for (CAContext* context : voice->staff()->sheet()->contextList()) { switch (context->contextType()) { case CAContext::FunctionMarkContext: case CAContext::FiguredBassContext: case CAContext::ChordNameContext: static_cast<CAChordNameContext*>(context)->repositionElements(); break; default: break; } } } } return success; } /*! Configures a new figured bass mark with \a timeStart and \a timeLength in context \a fbc. */ bool CAMusElementFactory::configureFiguredBassNumber(CAFiguredBassMark* fbm) { if ((_fbmNumber == 0 && (!_fbmAccsVisible)) || (!fbm)) { return false; } if (_fbmAccsVisible) { fbm->addNumber(_fbmNumber, _fbmAccs); } else { fbm->addNumber(_fbmNumber); } mpoMusElement = fbm; return true; } /*! Configures a new function mark with \a timeStart and \a timeLength in context \a fmc. */ bool CAMusElementFactory::configureFunctionMark(CAFunctionMarkContext* fmc, int timeStart, int timeLength) { CAFunctionMark* fm = new CAFunctionMark( fmFunction(), isFMFunctionMinor(), CADiatonicKey::diatonicKeyToString(CADiatonicKey(_diatonicKeyNumberOfAccs, _diatonicKeyGender)), fmc, timeStart, timeLength, fmChordArea(), isFMChordAreaMinor(), fmTonicDegree(), isFMTonicDegreeMinor(), "", /// \todo Function mark altered/added degrees isFMEllipse()); fmc->addFunctionMark(fm); mpoMusElement = fm; return true; } /*! Configures a new tuplet containing the given \a noteList. */ bool CAMusElementFactory::configureTuplet(QList<CAPlayable*>) { return false; } /*! \fn CAMusElementFactory::musElement() Reads the current music element and returns its pointer. */ /*! \fn CAMusElementFactory::musElementType() Returns the current music element type. */ /*! \fn CAMusElementFactory::setMusElementType(CAMusElement::CAMusElementType eMEType) Sets the new current music element type \a eMEType, does not create a new element of this type! */ /*! \var CAMusElementFactory::mpoMusElement Newly created music element itself. \sa musElement() */ /*! \var CAMusElementFactory::_ePlayableLength Length of note/rest to be added. */ /*! \var CAMusElementFactory::_iPlayableDotted Number of dots to be inserted for the note/rest. */ /*! \var CAMusElementFactory::_iNoteExtraAccs Extra note accidentals for new notes which user adds/removes with +/- keys. */ /*! \var CAMusElementFactory::_iNoteAccs Note accidentals at specific coordinates updated regularily when in insert mode. */ /*! \var CAMusElementFactory::_iTimeSigBeats Time signature number of beats to be inserted. */ /*! \var CAMusElementFactory::_iTimeSigBeat Time signature beat to be inserted. */ /*! \var CAMusElementFactory::_eClef Type of the clef to be inserted. */
18,864
C++
.cpp
538
28.384758
166
0.654931
canorusmusic/canorus
34
14
92
GPL-3.0
9/20/2024, 10:43:45 PM (Europe/Amsterdam)
false
false
false
false
false
false
false
false