summaryrefslogtreecommitdiffstats
path: root/src/gui/seqmanager
diff options
context:
space:
mode:
authortpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-03-01 18:37:05 +0000
committertpearson <tpearson@283d02a7-25f6-0310-bc7c-ecb5cbfe19da>2010-03-01 18:37:05 +0000
commit145364a8af6a1fec06556221e66d4b724a62fc9a (patch)
tree53bd71a544008c518034f208d64c932dc2883f50 /src/gui/seqmanager
downloadrosegarden-145364a8af6a1fec06556221e66d4b724a62fc9a.tar.gz
rosegarden-145364a8af6a1fec06556221e66d4b724a62fc9a.zip
Added old abandoned KDE3 version of the RoseGarden MIDI tool
git-svn-id: svn://anonsvn.kde.org/home/kde/branches/trinity/applications/rosegarden@1097595 283d02a7-25f6-0310-bc7c-ecb5cbfe19da
Diffstat (limited to 'src/gui/seqmanager')
-rw-r--r--src/gui/seqmanager/AudioSegmentMmapper.cpp133
-rw-r--r--src/gui/seqmanager/AudioSegmentMmapper.h61
-rw-r--r--src/gui/seqmanager/CompositionMmapper.cpp174
-rw-r--r--src/gui/seqmanager/CompositionMmapper.h75
-rw-r--r--src/gui/seqmanager/ControlBlockMmapper.cpp226
-rw-r--r--src/gui/seqmanager/ControlBlockMmapper.h83
-rw-r--r--src/gui/seqmanager/MetronomeMmapper.cpp268
-rw-r--r--src/gui/seqmanager/MetronomeMmapper.h87
-rw-r--r--src/gui/seqmanager/MidiFilterDialog.cpp229
-rw-r--r--src/gui/seqmanager/MidiFilterDialog.h71
-rw-r--r--src/gui/seqmanager/SegmentMmapper.cpp562
-rw-r--r--src/gui/seqmanager/SegmentMmapper.h112
-rw-r--r--src/gui/seqmanager/SegmentMmapperFactory.cpp96
-rw-r--r--src/gui/seqmanager/SegmentMmapperFactory.h63
-rw-r--r--src/gui/seqmanager/SequenceManager.cpp2141
-rw-r--r--src/gui/seqmanager/SequenceManager.h322
-rw-r--r--src/gui/seqmanager/SequencerMapper.cpp105
-rw-r--r--src/gui/seqmanager/SequencerMapper.h113
-rw-r--r--src/gui/seqmanager/SpecialSegmentMmapper.cpp56
-rw-r--r--src/gui/seqmanager/SpecialSegmentMmapper.h59
-rw-r--r--src/gui/seqmanager/TempoSegmentMmapper.cpp77
-rw-r--r--src/gui/seqmanager/TempoSegmentMmapper.h60
-rw-r--r--src/gui/seqmanager/TimeSigSegmentMmapper.cpp72
-rw-r--r--src/gui/seqmanager/TimeSigSegmentMmapper.h62
24 files changed, 5307 insertions, 0 deletions
diff --git a/src/gui/seqmanager/AudioSegmentMmapper.cpp b/src/gui/seqmanager/AudioSegmentMmapper.cpp
new file mode 100644
index 0000000..8933b39
--- /dev/null
+++ b/src/gui/seqmanager/AudioSegmentMmapper.cpp
@@ -0,0 +1,133 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "AudioSegmentMmapper.h"
+
+#include "base/Event.h"
+#include "base/Composition.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "SegmentMmapper.h"
+#include "sound/MappedEvent.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+AudioSegmentMmapper::AudioSegmentMmapper(RosegardenGUIDoc* doc, Segment* s,
+ const QString& fileName)
+ : SegmentMmapper(doc, s, fileName)
+{}
+
+void AudioSegmentMmapper::dump()
+{
+ Composition &comp = m_doc->getComposition();
+
+ RealTime eventTime;
+ Track* track = comp.getTrackById(m_segment->getTrack());
+
+ // Can't write out if no track
+ if (!track) {
+ std::cerr << "AudioSegmentMmapper::dump: ERROR: No track for segment!"
+ << std::endl;
+ return ;
+ }
+
+ timeT segmentStartTime = m_segment->getStartTime();
+ timeT segmentEndTime = m_segment->getEndMarkerTime();
+ timeT segmentDuration = segmentEndTime - segmentStartTime;
+ timeT repeatEndTime = segmentEndTime;
+
+ //!!! The repeat count is actually not quite right for audio
+ // segments -- it returns one too many for repeating segments,
+ // because in midi segments you want that (to deal with partial
+ // repeats). Here we really need to find a better way to deal
+ // with partial repeats...
+
+ int repeatCount = getSegmentRepeatCount();
+ if (repeatCount > 0)
+ repeatEndTime = m_segment->getRepeatEndTime();
+
+ MappedEvent* bufPos = m_mmappedEventBuffer;
+
+ for (int repeatNo = 0; repeatNo <= repeatCount; ++repeatNo) {
+
+ timeT playTime =
+ segmentStartTime + repeatNo * segmentDuration;
+ if (playTime >= repeatEndTime)
+ break;
+
+ playTime = playTime + m_segment->getDelay();
+ eventTime = comp.getElapsedRealTime(playTime);
+ eventTime = eventTime + m_segment->getRealTimeDelay();
+
+ RealTime audioStart = m_segment->getAudioStartTime();
+ RealTime audioDuration = m_segment->getAudioEndTime() - audioStart;
+ MappedEvent *mE =
+ new (bufPos) MappedEvent(track->getInstrument(), // send instrument for audio
+ m_segment->getAudioFileId(),
+ eventTime,
+ audioDuration,
+ audioStart);
+ mE->setTrackId(track->getId());
+ mE->setRuntimeSegmentId(m_segment->getRuntimeId());
+
+ // Send the autofade if required
+ //
+ if (m_segment->isAutoFading()) {
+ mE->setAutoFade(true);
+ mE->setFadeInTime(m_segment->getFadeInTime());
+ mE->setFadeOutTime(m_segment->getFadeOutTime());
+ std::cout << "AudioSegmentMmapper::dump - "
+ << "SETTING AUTOFADE "
+ << "in = " << m_segment->getFadeInTime()
+ << ", out = " << m_segment->getFadeOutTime()
+ << std::endl;
+ } else {
+ // std::cout << "AudioSegmentMmapper::dump - "
+ // << "NO AUTOFADE SET ON SEGMENT" << std::endl;
+ }
+
+ ++bufPos;
+ }
+
+ *(size_t *)m_mmappedRegion = repeatCount + 1;
+}
+
+size_t AudioSegmentMmapper::computeMmappedSize()
+{
+ if (!m_segment) return 0;
+
+ int repeatCount = getSegmentRepeatCount();
+
+ return (repeatCount + 1) * 1 * sizeof(MappedEvent);
+ // audio segments don't have events, we just need room for 1 MappedEvent
+}
+
+}
+
diff --git a/src/gui/seqmanager/AudioSegmentMmapper.h b/src/gui/seqmanager/AudioSegmentMmapper.h
new file mode 100644
index 0000000..bc4d798
--- /dev/null
+++ b/src/gui/seqmanager/AudioSegmentMmapper.h
@@ -0,0 +1,61 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_AUDIOSEGMENTMMAPPER_H_
+#define _RG_AUDIOSEGMENTMMAPPER_H_
+
+#include "SegmentMmapper.h"
+
+
+class QString;
+
+
+namespace Rosegarden
+{
+
+class Segment;
+class RosegardenGUIDoc;
+
+
+class AudioSegmentMmapper : public SegmentMmapper
+{
+ friend class SegmentMmapperFactory;
+
+protected:
+ AudioSegmentMmapper(RosegardenGUIDoc*, Segment*,
+ const QString& fileName);
+
+ virtual size_t computeMmappedSize();
+
+ /// dump all segment data in the file
+ virtual void dump();
+};
+
+//----------------------------------------
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/CompositionMmapper.cpp b/src/gui/seqmanager/CompositionMmapper.cpp
new file mode 100644
index 0000000..094f562
--- /dev/null
+++ b/src/gui/seqmanager/CompositionMmapper.cpp
@@ -0,0 +1,174 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "CompositionMmapper.h"
+#include "misc/Debug.h"
+
+#include <kstddirs.h>
+#include "base/Composition.h"
+#include "base/Segment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "gui/application/RosegardenApplication.h"
+#include "SegmentMmapperFactory.h"
+#include "SegmentMmapper.h"
+#include <kglobal.h>
+#include <qdir.h>
+#include <qfile.h>
+#include <qstring.h>
+#include <qstringlist.h>
+#include <stdint.h>
+
+
+namespace Rosegarden
+{
+
+CompositionMmapper::CompositionMmapper(RosegardenGUIDoc *doc)
+ : m_doc(doc)
+{
+ cleanup();
+
+ SEQMAN_DEBUG << "CompositionMmapper() - doc = " << doc << endl;
+ Composition &comp = m_doc->getComposition();
+
+ for (Composition::iterator it = comp.begin(); it != comp.end(); it++) {
+
+ Track* track = comp.getTrackById((*it)->getTrack());
+
+ // check to see if track actually exists
+ //
+ if (track == 0)
+ continue;
+
+ mmapSegment(*it);
+ }
+}
+
+CompositionMmapper::~CompositionMmapper()
+{
+ SEQMAN_DEBUG << "~CompositionMmapper()\n";
+
+ //
+ // Clean up possible left-overs
+ //
+ cleanup();
+
+ for (segmentmmapers::iterator i = m_segmentMmappers.begin();
+ i != m_segmentMmappers.end(); ++i)
+ delete i->second;
+}
+
+void CompositionMmapper::cleanup()
+{
+ // In case the sequencer is still running, mapping some segments
+ //
+ rgapp->sequencerSend("closeAllSegments()");
+
+ // Erase all 'segment_*' files
+ //
+ QString tmpPath = KGlobal::dirs()->resourceDirs("tmp").last();
+
+ QDir segmentsDir(tmpPath, "segment_*");
+ for (unsigned int i = 0; i < segmentsDir.count(); ++i) {
+ QString segmentName = tmpPath + '/' + segmentsDir[i];
+ SEQMAN_DEBUG << "CompositionMmapper : cleaning up " << segmentName << endl;
+ QFile::remove
+ (segmentName);
+ }
+
+}
+
+bool CompositionMmapper::segmentModified(Segment* segment)
+{
+ SegmentMmapper* mmapper = m_segmentMmappers[segment];
+
+ if (!mmapper)
+ return false; // this can happen with the SegmentSplitCommand, where the new segment's transpose is set
+ // even though it's not mapped yet
+
+ SEQMAN_DEBUG << "CompositionMmapper::segmentModified(" << segment << ") - mmapper = "
+ << mmapper << endl;
+
+ return mmapper->refresh();
+}
+
+void CompositionMmapper::segmentAdded(Segment* segment)
+{
+ SEQMAN_DEBUG << "CompositionMmapper::segmentAdded(" << segment << ")\n";
+
+ mmapSegment(segment);
+}
+
+void CompositionMmapper::segmentDeleted(Segment* segment)
+{
+ SEQMAN_DEBUG << "CompositionMmapper::segmentDeleted(" << segment << ")\n";
+ SegmentMmapper* mmapper = m_segmentMmappers[segment];
+ m_segmentMmappers.erase(segment);
+ SEQMAN_DEBUG << "CompositionMmapper::segmentDeleted() : deleting SegmentMmapper " << mmapper << endl;
+
+ delete mmapper;
+}
+
+void CompositionMmapper::mmapSegment(Segment* segment)
+{
+ SEQMAN_DEBUG << "CompositionMmapper::mmapSegment(" << segment << ")\n";
+
+ SegmentMmapper* mmapper = SegmentMmapperFactory::makeMmapperForSegment(m_doc,
+ segment,
+ makeFileName(segment));
+
+ if (mmapper)
+ m_segmentMmappers[segment] = mmapper;
+}
+
+QString CompositionMmapper::makeFileName(Segment* segment)
+{
+ QStringList tmpDirs = KGlobal::dirs()->resourceDirs("tmp");
+
+ return QString("%1/segment_%2")
+ .arg(tmpDirs.last())
+ .arg((uintptr_t)segment, 0, 16);
+}
+
+QString CompositionMmapper::getSegmentFileName(Segment* s)
+{
+ SegmentMmapper* mmapper = m_segmentMmappers[s];
+
+ if (mmapper)
+ return mmapper->getFileName();
+ else
+ return QString::null;
+}
+
+size_t CompositionMmapper::getSegmentFileSize(Segment* s)
+{
+ SegmentMmapper* mmapper = m_segmentMmappers[s];
+
+ if (mmapper)
+ return mmapper->getFileSize();
+ else
+ return 0;
+}
+
+}
diff --git a/src/gui/seqmanager/CompositionMmapper.h b/src/gui/seqmanager/CompositionMmapper.h
new file mode 100644
index 0000000..8bf997d
--- /dev/null
+++ b/src/gui/seqmanager/CompositionMmapper.h
@@ -0,0 +1,75 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_COMPOSITIONMMAPPER_H_
+#define _RG_COMPOSITIONMMAPPER_H_
+
+#include <map>
+#include <qstring.h>
+
+
+
+
+namespace Rosegarden
+{
+
+class SegmentMmapper;
+class Segment;
+class RosegardenGUIDoc;
+
+
+class CompositionMmapper
+{
+ friend class SequenceManager;
+
+public:
+ CompositionMmapper(RosegardenGUIDoc *doc);
+ ~CompositionMmapper();
+
+ QString getSegmentFileName(Segment*);
+ size_t getSegmentFileSize(Segment*);
+
+ void cleanup();
+
+protected:
+ bool segmentModified(Segment*);
+ void segmentAdded(Segment*);
+ void segmentDeleted(Segment*);
+
+ void mmapSegment(Segment*);
+ QString makeFileName(Segment*);
+
+ //--------------- Data members ---------------------------------
+
+ RosegardenGUIDoc* m_doc;
+ typedef std::map<Segment*, SegmentMmapper*> segmentmmapers;
+
+ segmentmmapers m_segmentMmappers;
+};
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/ControlBlockMmapper.cpp b/src/gui/seqmanager/ControlBlockMmapper.cpp
new file mode 100644
index 0000000..90ab6c2
--- /dev/null
+++ b/src/gui/seqmanager/ControlBlockMmapper.cpp
@@ -0,0 +1,226 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "ControlBlockMmapper.h"
+#include "misc/Debug.h"
+
+#include <kstddirs.h>
+#include "misc/Strings.h"
+#include "base/Composition.h"
+#include "base/Exception.h"
+#include "base/MidiProgram.h"
+#include "base/Track.h"
+#include "document/RosegardenGUIDoc.h"
+#include "sound/ControlBlock.h"
+#include <kglobal.h>
+#include <qfile.h>
+#include <qstring.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <errno.h>
+
+namespace Rosegarden
+{
+
+ControlBlockMmapper::ControlBlockMmapper(RosegardenGUIDoc* doc)
+ : m_doc(doc),
+ m_fileName(createFileName()),
+ m_fd( -1),
+ m_mmappedBuffer(0),
+ m_mmappedSize(sizeof(ControlBlock)),
+ m_controlBlock(0)
+{
+ // just in case
+ QFile::remove
+ (m_fileName);
+
+ m_fd = ::open(m_fileName.latin1(), O_RDWR | O_CREAT | O_TRUNC,
+ S_IRUSR | S_IWUSR);
+ if (m_fd < 0) {
+ SEQMAN_DEBUG << "ControlBlockMmapper : Couldn't open " << m_fileName
+ << endl;
+ throw Exception("Couldn't open " + qstrtostr(m_fileName));
+ }
+
+ setFileSize(m_mmappedSize);
+
+ //
+ // mmap() file for writing
+ //
+ m_mmappedBuffer = ::mmap(0, m_mmappedSize,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED, m_fd, 0);
+
+ if (m_mmappedBuffer == (void*) - 1) {
+ SEQMAN_DEBUG << QString("mmap failed : (%1) %2\n").arg(errno).arg(strerror(errno));
+ throw Exception("mmap failed");
+ }
+
+ SEQMAN_DEBUG << "ControlBlockMmapper : mmap size : " << m_mmappedSize
+ << " at " << (void*)m_mmappedBuffer << endl;
+
+ // Create new control block on file
+ initControlBlock();
+}
+
+ControlBlockMmapper::~ControlBlockMmapper()
+{
+ ::munmap(m_mmappedBuffer, m_mmappedSize);
+ ::close(m_fd);
+ QFile::remove
+ (m_fileName);
+}
+
+QString ControlBlockMmapper::createFileName()
+{
+ return KGlobal::dirs()->resourceDirs("tmp").last() + "/rosegarden_control_block";
+}
+
+void ControlBlockMmapper::updateTrackData(Track *t)
+{
+ m_controlBlock->updateTrackData(t);
+}
+
+void ControlBlockMmapper::setTrackDeleted(TrackId t)
+{
+ m_controlBlock->setTrackDeleted(t, true);
+}
+
+void ControlBlockMmapper::updateMidiFilters(MidiFilter thruFilter,
+ MidiFilter recordFilter)
+{
+ m_controlBlock->setThruFilter(thruFilter);
+ m_controlBlock->setRecordFilter(recordFilter);
+}
+
+void ControlBlockMmapper::updateMetronomeData(InstrumentId instId)
+{
+ m_controlBlock->setInstrumentForMetronome(instId);
+}
+
+void ControlBlockMmapper::updateMetronomeForPlayback()
+{
+ bool muted = !m_doc->getComposition().usePlayMetronome();
+ SEQMAN_DEBUG << "ControlBlockMmapper::updateMetronomeForPlayback: muted=" << muted << endl;
+ if (m_controlBlock->isMetronomeMuted() == muted)
+ return ;
+ m_controlBlock->setMetronomeMuted(muted);
+}
+
+void ControlBlockMmapper::updateMetronomeForRecord()
+{
+ bool muted = !m_doc->getComposition().useRecordMetronome();
+ SEQMAN_DEBUG << "ControlBlockMmapper::updateMetronomeForRecord: muted=" << muted << endl;
+ if (m_controlBlock->isMetronomeMuted() == muted)
+ return ;
+ m_controlBlock->setMetronomeMuted(muted);
+}
+
+bool ControlBlockMmapper::updateSoloData(bool solo,
+ TrackId selectedTrack)
+{
+ bool changed = false;
+
+ if (solo != m_controlBlock->isSolo()) {
+
+ changed = true;
+
+ } else if (solo &&
+ (selectedTrack != m_controlBlock->getSelectedTrack())) {
+
+ changed = true;
+ }
+
+ m_controlBlock->setSolo(solo);
+ m_controlBlock->setSelectedTrack(selectedTrack);
+
+ return changed;
+}
+
+void ControlBlockMmapper::setDocument(RosegardenGUIDoc* doc)
+{
+ SEQMAN_DEBUG << "ControlBlockMmapper::setDocument()\n";
+ m_doc = doc;
+ initControlBlock();
+}
+
+void ControlBlockMmapper::initControlBlock()
+{
+ SEQMAN_DEBUG << "ControlBlockMmapper::initControlBlock()\n";
+
+ m_controlBlock = new (m_mmappedBuffer) ControlBlock(m_doc->getComposition().getMaxTrackId());
+
+ Composition& comp = m_doc->getComposition();
+
+ for (Composition::trackiterator i = comp.getTracks().begin(); i != comp.getTracks().end(); ++i) {
+ Track* track = i->second;
+ if (track == 0)
+ continue;
+
+ m_controlBlock->updateTrackData(track);
+ }
+
+ m_controlBlock->setMetronomeMuted(!comp.usePlayMetronome());
+
+ m_controlBlock->setThruFilter(m_doc->getStudio().getMIDIThruFilter());
+ m_controlBlock->setRecordFilter(m_doc->getStudio().getMIDIRecordFilter());
+
+ ::msync(m_mmappedBuffer, m_mmappedSize, MS_ASYNC);
+}
+
+void ControlBlockMmapper::setFileSize(size_t size)
+{
+ SEQMAN_DEBUG << "ControlBlockMmapper : setting size of "
+ << m_fileName << " to " << size << endl;
+ // rewind
+ ::lseek(m_fd, 0, SEEK_SET);
+
+ //
+ // enlarge the file
+ // (seek() to wanted size, then write a byte)
+ //
+ if (::lseek(m_fd, size - 1, SEEK_SET) == -1) {
+ std::cerr << "WARNING: ControlBlockMmapper : Couldn't lseek in " << m_fileName
+ << " to " << size << std::endl;
+ throw Exception("lseek failed");
+ }
+
+ if (::write(m_fd, "\0", 1) != 1) {
+ std::cerr << "WARNING: ControlBlockMmapper : Couldn't write byte in "
+ << m_fileName << std::endl;
+ throw Exception("write failed");
+ }
+
+}
+
+void
+ControlBlockMmapper::enableMIDIThruRouting(bool state)
+{
+ m_controlBlock->setMidiRoutingEnabled(state);
+}
+
+}
diff --git a/src/gui/seqmanager/ControlBlockMmapper.h b/src/gui/seqmanager/ControlBlockMmapper.h
new file mode 100644
index 0000000..a96e742
--- /dev/null
+++ b/src/gui/seqmanager/ControlBlockMmapper.h
@@ -0,0 +1,83 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_CONTROLBLOCKMMAPPER_H_
+#define _RG_CONTROLBLOCKMMAPPER_H_
+
+#include "base/MidiProgram.h"
+#include "base/Track.h"
+#include <qstring.h>
+
+
+
+
+namespace Rosegarden
+{
+
+class Track;
+class RosegardenGUIDoc;
+class ControlBlock;
+
+
+class ControlBlockMmapper
+{
+public:
+ ControlBlockMmapper(RosegardenGUIDoc*);
+ ~ControlBlockMmapper();
+
+ QString getFileName() { return m_fileName; }
+ void updateTrackData(Track*);
+ void setTrackDeleted(TrackId);
+ void updateMetronomeData(InstrumentId instId);
+ void updateMetronomeForPlayback();
+ void updateMetronomeForRecord();
+ bool updateSoloData(bool solo, TrackId selectedTrack);
+ void updateMidiFilters(MidiFilter thruFilter,
+ MidiFilter recordFilter);
+ void setDocument(RosegardenGUIDoc*);
+ void enableMIDIThruRouting(bool state);
+
+protected:
+ void initControlBlock();
+ void setFileSize(size_t);
+ QString createFileName();
+
+ //--------------- Data members ---------------------------------
+ RosegardenGUIDoc* m_doc;
+ QString m_fileName;
+ int m_fd;
+ void* m_mmappedBuffer;
+ size_t m_mmappedSize;
+ ControlBlock* m_controlBlock;
+};
+
+
+//----------------------------------------
+
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/MetronomeMmapper.cpp b/src/gui/seqmanager/MetronomeMmapper.cpp
new file mode 100644
index 0000000..9ca9af7
--- /dev/null
+++ b/src/gui/seqmanager/MetronomeMmapper.cpp
@@ -0,0 +1,268 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "MetronomeMmapper.h"
+#include "misc/Debug.h"
+#include <kapplication.h>
+
+#include "sound/Midi.h"
+#include <kstddirs.h>
+#include "document/ConfigGroups.h"
+#include "base/Event.h"
+#include "base/MidiProgram.h"
+#include "base/NotationTypes.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/Studio.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "SegmentMmapper.h"
+#include "sound/MappedEvent.h"
+#include <kconfig.h>
+#include <kglobal.h>
+#include <qstring.h>
+#include <algorithm>
+
+
+namespace Rosegarden
+{
+
+MetronomeMmapper::MetronomeMmapper(RosegardenGUIDoc* doc)
+ : SegmentMmapper(doc, 0, createFileName()),
+ m_metronome(0), // no metronome to begin with
+ m_tickDuration(0, 100000000)
+{
+ SEQMAN_DEBUG << "MetronomeMmapper ctor : " << this << endl;
+
+ // get metronome device
+ Studio &studio = m_doc->getStudio();
+ int device = studio.getMetronomeDevice();
+
+ const MidiMetronome *metronome =
+ m_doc->getStudio().getMetronomeFromDevice(device);
+
+ if (metronome) {
+
+ SEQMAN_DEBUG << "MetronomeMmapper: have metronome, it's on instrument " << metronome->getInstrument() << endl;
+
+ m_metronome = new MidiMetronome(*metronome);
+ } else {
+ m_metronome = new MidiMetronome
+ (SystemInstrumentBase);
+ SEQMAN_DEBUG << "MetronomeMmapper: no metronome for device " << device << endl;
+ }
+
+ Composition& c = m_doc->getComposition();
+ timeT t = c.getBarStart( -20); // somewhat arbitrary
+ int depth = m_metronome->getDepth();
+
+ if (depth > 0) {
+ while (t < c.getEndMarker()) {
+
+ TimeSignature sig = c.getTimeSignatureAt(t);
+ timeT barDuration = sig.getBarDuration();
+ std::vector<int> divisions;
+ if (depth > 0)
+ sig.getDivisions(depth - 1, divisions);
+ int ticks = 1;
+
+ for (int i = -1; i < (int)divisions.size(); ++i) {
+ if (i >= 0)
+ ticks *= divisions[i];
+
+ for (int tick = 0; tick < ticks; ++tick) {
+ if (i >= 0 && (tick % divisions[i] == 0))
+ continue;
+ timeT tickTime = t + (tick * barDuration) / ticks;
+ m_ticks.push_back(Tick(tickTime, i + 1));
+ }
+ }
+
+ t = c.getBarEndForTime(t);
+ }
+ }
+
+ KConfig *config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+ int midiClock = config->readNumEntry("midiclock", 0);
+ int mtcMode = config->readNumEntry("mtcmode", 0);
+
+ if (midiClock == 1) {
+ timeT quarterNote = Note(Note::Crotchet).getDuration();
+
+ // Insert 24 clocks per quarter note
+ //
+ for (timeT insertTime = c.getStartMarker();
+ insertTime < c.getEndMarker();
+ insertTime += quarterNote / 24) {
+ m_ticks.push_back(Tick(insertTime, 3));
+ }
+ }
+
+
+ if (mtcMode > 0) {
+ // do something
+ }
+
+ sortTicks();
+
+ if (m_ticks.size() == 0) {
+ SEQMAN_DEBUG << "MetronomeMmapper : WARNING no ticks generated\n";
+ }
+
+ // Done by init()
+
+ // m_mmappedSize = computeMmappedSize();
+ // if (m_mmappedSize > 0) {
+ // setFileSize(m_mmappedSize);
+ // doMmap();
+ // dump();
+ // }
+}
+
+MetronomeMmapper::~MetronomeMmapper()
+{
+ SEQMAN_DEBUG << "~MetronomeMmapper " << this << endl;
+ delete m_metronome;
+}
+
+InstrumentId MetronomeMmapper::getMetronomeInstrument()
+{
+ return m_metronome->getInstrument();
+}
+
+QString MetronomeMmapper::createFileName()
+{
+ return KGlobal::dirs()->resourceDirs("tmp").last() + "/rosegarden_metronome";
+}
+
+void MetronomeMmapper::dump()
+{
+ RealTime eventTime;
+ Composition& comp = m_doc->getComposition();
+
+ SEQMAN_DEBUG << "MetronomeMmapper::dump: instrument is " << m_metronome->getInstrument() << endl;
+
+ MappedEvent* bufPos = m_mmappedEventBuffer, *mE;
+
+ for (TickContainer::iterator i = m_ticks.begin(); i != m_ticks.end(); ++i) {
+
+ /*
+ SEQMAN_DEBUG << "MetronomeMmapper::dump: velocity = "
+ << int(velocity) << endl;
+ */
+
+ eventTime = comp.getElapsedRealTime(i->first);
+
+ if (i->second == 3) // MIDI Clock
+ {
+ mE = new (bufPos) MappedEvent(0, MappedEvent::MidiSystemMessage);
+ mE->setData1(MIDI_TIMING_CLOCK);
+ mE->setEventTime(eventTime);
+ } else {
+ MidiByte velocity;
+ MidiByte pitch;
+ switch (i->second) {
+ case 0:
+ velocity = m_metronome->getBarVelocity();
+ pitch = m_metronome->getBarPitch();
+ break;
+ case 1:
+ velocity = m_metronome->getBeatVelocity();
+ pitch = m_metronome->getBeatPitch();
+ break;
+ default:
+ velocity = m_metronome->getSubBeatVelocity();
+ pitch = m_metronome->getSubBeatPitch();
+ break;
+ }
+
+ new (bufPos) MappedEvent(m_metronome->getInstrument(),
+ MappedEvent::MidiNoteOneShot,
+ pitch,
+ velocity,
+ eventTime,
+ m_tickDuration,
+ RealTime::zeroTime);
+ }
+
+ ++bufPos;
+ }
+
+ // Store the number of events at the start of the shared memory region
+ *(size_t *)m_mmappedRegion = (bufPos - m_mmappedEventBuffer);
+
+ SEQMAN_DEBUG << "MetronomeMmapper::dump: - "
+ << "Total events written = " << *(size_t *)m_mmappedRegion
+ << endl;
+}
+
+void MetronomeMmapper::sortTicks()
+{
+ sort(m_ticks.begin(), m_ticks.end());
+}
+
+size_t MetronomeMmapper::computeMmappedSize()
+{
+ KConfig *config = kapp->config();
+ config->setGroup(Rosegarden::SequencerOptionsConfigGroup);
+ int midiClock = config->readNumEntry("midiclock", 0);
+ int mtcMode = config->readNumEntry("mtcmode", 0);
+
+ // base size for Metronome ticks
+ size_t size = m_ticks.size() * sizeof(MappedEvent);
+ Composition& comp = m_doc->getComposition();
+
+ if (midiClock == 1)
+ {
+ using Rosegarden::Note;
+
+ // Allow room for MIDI clocks
+ int clocks = ( 24 * ( comp.getEndMarker() - comp.getStartMarker() ) ) /
+ Note(Note::Crotchet).getDuration();
+
+ /*
+ SEQMAN_DEBUG << "MetronomeMmapper::computeMmappedSize - "
+ << "Number of clock events catered for = " << clocks
+ << endl;
+ */
+
+ size += clocks * sizeof(MappedEvent);
+ }
+
+ if (mtcMode > 0)
+ {
+ // Allow room for MTC timing messages (how?)
+ }
+
+ return size;
+}
+
+unsigned int MetronomeMmapper::getSegmentRepeatCount()
+{
+ return 1;
+}
+
+}
diff --git a/src/gui/seqmanager/MetronomeMmapper.h b/src/gui/seqmanager/MetronomeMmapper.h
new file mode 100644
index 0000000..1e18171
--- /dev/null
+++ b/src/gui/seqmanager/MetronomeMmapper.h
@@ -0,0 +1,87 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_METRONOMEMMAPPER_H_
+#define _RG_METRONOMEMMAPPER_H_
+
+#include "base/MidiProgram.h"
+#include "base/RealTime.h"
+#include "SegmentMmapper.h"
+#include <qstring.h>
+#include <utility>
+#include <vector>
+#include "base/Event.h"
+
+
+
+
+namespace Rosegarden
+{
+
+class RosegardenGUIDoc;
+class MidiMetronome;
+
+
+class MetronomeMmapper : public SegmentMmapper
+{
+ friend class SegmentMmapperFactory;
+
+public:
+
+ virtual ~MetronomeMmapper();
+
+ InstrumentId getMetronomeInstrument();
+
+ // overrides from SegmentMmapper
+ virtual unsigned int getSegmentRepeatCount();
+
+protected:
+ MetronomeMmapper(RosegardenGUIDoc* doc);
+
+ virtual size_t computeMmappedSize();
+
+ void sortTicks();
+ QString createFileName();
+
+ // override from SegmentMmapper
+ virtual void dump();
+
+ //--------------- Data members ---------------------------------
+ typedef std::pair<timeT, int> Tick;
+ typedef std::vector<Tick> TickContainer;
+ friend bool operator<(Tick, Tick);
+
+ TickContainer m_ticks;
+ bool m_deleteMetronome;
+ const MidiMetronome* m_metronome;
+ RealTime m_tickDuration;
+};
+
+//----------------------------------------
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/MidiFilterDialog.cpp b/src/gui/seqmanager/MidiFilterDialog.cpp
new file mode 100644
index 0000000..69d687a
--- /dev/null
+++ b/src/gui/seqmanager/MidiFilterDialog.cpp
@@ -0,0 +1,229 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "MidiFilterDialog.h"
+
+#include <klocale.h>
+#include "base/MidiProgram.h"
+#include "base/NotationTypes.h"
+#include "document/RosegardenGUIDoc.h"
+#include "gui/seqmanager/SequenceManager.h"
+#include "sound/MappedEvent.h"
+#include <kdialogbase.h>
+#include <qbuttongroup.h>
+#include <qcheckbox.h>
+#include <qhbox.h>
+#include <qwidget.h>
+
+
+namespace Rosegarden
+{
+
+MidiFilterDialog::MidiFilterDialog(QWidget *parent,
+ RosegardenGUIDoc *doc):
+ KDialogBase(parent, 0, true, i18n("Modify MIDI filters..."),
+ Ok | Apply | Close | Help),
+ m_doc(doc),
+ m_modified(true)
+{
+ setHelp("studio-midi-filters");
+
+ QHBox *hBox = makeHBoxMainWidget();
+
+ m_thruBox =
+ new QButtonGroup(1,
+ Qt::Horizontal,
+ i18n("THRU events to ignore"), hBox);
+
+ QCheckBox *noteThru = new QCheckBox(i18n("Note"), m_thruBox);
+ QCheckBox *progThru = new QCheckBox(i18n("Program Change"), m_thruBox);
+ QCheckBox *keyThru = new QCheckBox(i18n("Key Pressure"), m_thruBox);
+ QCheckBox *chanThru = new QCheckBox(i18n("Channel Pressure"), m_thruBox);
+ QCheckBox *pitchThru = new QCheckBox(i18n("Pitch Bend"), m_thruBox);
+ QCheckBox *contThru = new QCheckBox(i18n("Controller"), m_thruBox);
+ QCheckBox *sysThru = new QCheckBox(i18n("System Exclusive"), m_thruBox);
+
+ MidiFilter thruFilter = m_doc->getStudio().getMIDIThruFilter();
+
+ if (thruFilter & MappedEvent::MidiNote)
+ noteThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiProgramChange)
+ progThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiKeyPressure)
+ keyThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiChannelPressure)
+ chanThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiPitchBend)
+ pitchThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiController)
+ contThru->setChecked(true);
+
+ if (thruFilter & MappedEvent::MidiSystemMessage)
+ sysThru->setChecked(true);
+
+ m_recordBox =
+ new QButtonGroup(1,
+ Qt::Horizontal,
+ i18n("RECORD events to ignore"), hBox);
+
+ QCheckBox *noteRecord = new QCheckBox(i18n("Note"), m_recordBox);
+ QCheckBox *progRecord = new QCheckBox(i18n("Program Change"), m_recordBox);
+ QCheckBox *keyRecord = new QCheckBox(i18n("Key Pressure"), m_recordBox);
+ QCheckBox *chanRecord = new QCheckBox(i18n("Channel Pressure"), m_recordBox);
+ QCheckBox *pitchRecord = new QCheckBox(i18n("Pitch Bend"), m_recordBox);
+ QCheckBox *contRecord = new QCheckBox(i18n("Controller"), m_recordBox);
+ QCheckBox *sysRecord = new QCheckBox(i18n("System Exclusive"), m_recordBox);
+
+ MidiFilter recordFilter =
+ m_doc->getStudio().getMIDIRecordFilter();
+
+ if (recordFilter & MappedEvent::MidiNote)
+ noteRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiProgramChange)
+ progRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiKeyPressure)
+ keyRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiChannelPressure)
+ chanRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiPitchBend)
+ pitchRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiController)
+ contRecord->setChecked(true);
+
+ if (recordFilter & MappedEvent::MidiSystemMessage)
+ sysRecord->setChecked(true);
+
+
+ connect(m_thruBox, SIGNAL(released(int)),
+ this, SLOT(slotSetModified()));
+
+ connect(m_recordBox, SIGNAL(released(int)),
+ this, SLOT(slotSetModified()));
+
+ setModified(false);
+}
+
+void
+MidiFilterDialog::slotApply()
+{
+ MidiFilter thruFilter = 0,
+ recordFilter = 0;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(0))->isChecked())
+ thruFilter |= MappedEvent::MidiNote;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(1))->isChecked())
+ thruFilter |= MappedEvent::MidiProgramChange;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(2))->isChecked())
+ thruFilter |= MappedEvent::MidiKeyPressure;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(3))->isChecked())
+ thruFilter |= MappedEvent::MidiChannelPressure;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(4))->isChecked())
+ thruFilter |= MappedEvent::MidiPitchBend;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(5))->isChecked())
+ thruFilter |= MappedEvent::MidiController;
+
+ if (dynamic_cast<QCheckBox*>(m_thruBox->find(6))->isChecked())
+ thruFilter |= MappedEvent::MidiSystemMessage;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(0))->isChecked())
+ recordFilter |= MappedEvent::MidiNote;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(1))->isChecked())
+ recordFilter |= MappedEvent::MidiProgramChange;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(2))->isChecked())
+ recordFilter |= MappedEvent::MidiKeyPressure;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(3))->isChecked())
+ recordFilter |= MappedEvent::MidiChannelPressure;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(4))->isChecked())
+ recordFilter |= MappedEvent::MidiPitchBend;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(5))->isChecked())
+ recordFilter |= MappedEvent::MidiController;
+
+ if (dynamic_cast<QCheckBox*>(m_recordBox->find(6))->isChecked())
+ recordFilter |= MappedEvent::MidiSystemMessage;
+
+
+ //if (m_thruBox->
+
+ m_doc->getStudio().setMIDIThruFilter(thruFilter);
+ m_doc->getStudio().setMIDIRecordFilter(recordFilter);
+
+ if (m_doc->getSequenceManager()) {
+ m_doc->getSequenceManager()->filtersChanged(thruFilter, recordFilter);
+ }
+
+ setModified(false);
+}
+
+void
+MidiFilterDialog::slotOk()
+{
+ slotApply();
+ accept();
+}
+
+void
+MidiFilterDialog::slotSetModified()
+{
+ setModified(true);
+}
+
+void
+MidiFilterDialog::setModified(bool value)
+{
+ if (m_modified == value)
+ return ;
+
+ if (value) {
+ enableButtonApply(true);
+ } else {
+ enableButtonApply(false);
+ }
+
+ m_modified = value;
+
+}
+
+}
+#include "MidiFilterDialog.moc"
diff --git a/src/gui/seqmanager/MidiFilterDialog.h b/src/gui/seqmanager/MidiFilterDialog.h
new file mode 100644
index 0000000..06099ac
--- /dev/null
+++ b/src/gui/seqmanager/MidiFilterDialog.h
@@ -0,0 +1,71 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_MIDIFILTERDIALOG_H_
+#define _RG_MIDIFILTERDIALOG_H_
+
+#include <kdialogbase.h>
+
+
+class QWidget;
+class QButtonGroup;
+
+
+namespace Rosegarden
+{
+
+class RosegardenGUIDoc;
+
+
+class MidiFilterDialog : public KDialogBase
+{
+ Q_OBJECT
+public:
+ MidiFilterDialog(QWidget *parent,
+ RosegardenGUIDoc *doc);
+
+ void setModified(bool value);
+
+public slots:
+
+ void slotOk();
+ void slotApply();
+ void slotSetModified();
+
+protected:
+
+ RosegardenGUIDoc *m_doc;
+
+ QButtonGroup *m_thruBox;
+ QButtonGroup *m_recordBox;
+
+ bool m_modified;
+
+};
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/SegmentMmapper.cpp b/src/gui/seqmanager/SegmentMmapper.cpp
new file mode 100644
index 0000000..5cf117d
--- /dev/null
+++ b/src/gui/seqmanager/SegmentMmapper.cpp
@@ -0,0 +1,562 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "SegmentMmapper.h"
+#include "misc/Debug.h"
+
+#include "misc/Strings.h"
+#include "base/BaseProperties.h"
+#include "base/Composition.h"
+#include "base/Event.h"
+#include "base/Exception.h"
+#include "base/NotationTypes.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/SegmentPerformanceHelper.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "sound/MappedEvent.h"
+#include <qfile.h>
+#include <qstring.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <errno.h>
+
+
+namespace Rosegarden
+{
+
+SegmentMmapper::SegmentMmapper(RosegardenGUIDoc* doc,
+ Segment* segment, const QString& fileName)
+ : m_doc(doc),
+ m_segment(segment),
+ m_fileName(fileName),
+ m_fd( -1),
+ m_mmappedSize(0),
+ m_mmappedRegion(0),
+ m_mmappedEventBuffer((MappedEvent*)0)
+{
+ SEQMAN_DEBUG << "SegmentMmapper : " << this
+ << " trying to mmap " << m_fileName
+ << endl;
+
+ m_fd = ::open(m_fileName.latin1(), O_RDWR | O_CREAT | O_TRUNC,
+ S_IRUSR | S_IWUSR);
+ if (m_fd < 0) {
+ perror("SegmentMmapper::SegmentMmapper: Failed to open mmap file for writing");
+ SEQMAN_DEBUG << "SegmentMmapper : Couldn't open " << m_fileName
+ << endl;
+ throw Exception("Couldn't open " + qstrtostr(m_fileName));
+ }
+
+ // SEQMAN_DEBUG << "SegmentMmapper : mmap size = " << m_mmappedSize
+ // << endl;
+}
+
+void SegmentMmapper::init()
+{
+ m_mmappedSize = computeMmappedSize() + sizeof(size_t);
+
+ if (m_mmappedSize > 0) {
+ setFileSize(m_mmappedSize);
+ doMmap();
+ dump();
+ if (m_segment != 0) {
+ SEQMAN_DEBUG << "SegmentMmapper::init : mmap size = " << m_mmappedSize
+ << " for segment " << m_segment->getLabel() << endl;
+ }
+
+ } else {
+ SEQMAN_DEBUG << "SegmentMmapper::init : mmap size = 0 - skipping mmapping for now\n";
+ }
+}
+
+SegmentMmapper::~SegmentMmapper()
+{
+ SEQMAN_DEBUG << "~SegmentMmapper : " << this
+ << " unmapping " << (void*)m_mmappedRegion
+ << " of size " << m_mmappedSize
+ << endl;
+
+ if (m_mmappedRegion && m_mmappedSize)
+ ::munmap(m_mmappedRegion, m_mmappedSize);
+
+ ::close(m_fd);
+ SEQMAN_DEBUG << "~SegmentMmapper : removing " << m_fileName << endl;
+
+ QFile::remove
+ (m_fileName);
+}
+
+bool SegmentMmapper::refresh()
+{
+ bool res = false;
+
+ size_t newMmappedSize = computeMmappedSize() + sizeof(size_t);
+
+ SEQMAN_DEBUG << "SegmentMmapper::refresh() - " << getFileName()
+ << " - m_mmappedRegion = " << (void*)m_mmappedRegion
+ << " - m_mmappedEventBuffer = " << (void*)m_mmappedEventBuffer
+ << " - new size = " << newMmappedSize
+ << " - old size = " << m_mmappedSize
+ << endl;
+
+ // We can't zero out the buffer here because if the mmapped
+ // segment is being read from by the sequencer in the interval of
+ // time between the memset() and the dump(), the sequencer will go
+ // over all the zeros up to the end of the segment and reach its
+ // end, and therefore will stop playing it.
+ //
+
+ if (newMmappedSize != m_mmappedSize) {
+
+ res = true;
+
+ if (newMmappedSize == 0) {
+
+ // nothing to do, just msync and go
+ ::msync(m_mmappedRegion, m_mmappedSize, MS_ASYNC);
+ m_mmappedSize = 0;
+ return true;
+
+ } else {
+
+ setFileSize(newMmappedSize);
+ remap(newMmappedSize);
+ }
+ }
+
+ dump();
+
+ return res;
+}
+
+void SegmentMmapper::setFileSize(size_t size)
+{
+ SEQMAN_DEBUG << "SegmentMmapper::setFileSize() : setting size of "
+ << m_fileName << " to " << size
+ << " - current size = " << m_mmappedSize << endl;
+
+ if (size < m_mmappedSize) {
+
+ // Don't truncate the file here: that will cause trouble for
+ // the sequencer
+ // ftruncate(m_fd, size);
+
+ } else {
+
+ // On linux, ftruncate can enlarge a file, but this isn't specified by POSIX
+ // so go the safe way
+
+ if (size == 0) {
+ SEQMAN_DEBUG << "SegmentMmapper : size == 0 : no resize to do\n";
+ return ;
+ }
+
+ // rewind
+ ::lseek(m_fd, 0, SEEK_SET);
+
+ //
+ // enlarge the file
+ // (seek() to wanted size, then write a byte)
+ //
+ if (::lseek(m_fd, size - 1, SEEK_SET) == -1) {
+ std::cerr << "WARNING: SegmentMmapper : Couldn't lseek in "
+ << m_fileName << " to " << size << std::endl;
+ throw Exception("lseek failed");
+ }
+
+ if (::write(m_fd, "\0", 1) != 1) {
+ std::cerr << "WARNING: SegmentMmapper : Couldn't write byte in "
+ << m_fileName << std::endl;
+ throw Exception("write failed");
+ }
+
+ }
+
+
+}
+
+void SegmentMmapper::remap(size_t newsize)
+{
+ SEQMAN_DEBUG << "SegmentMmapper : remapping " << m_fileName
+ << " from size " << m_mmappedSize
+ << " to size " << newsize << endl;
+
+ if (!m_mmappedRegion) { // nothing to mremap, just mmap
+
+ SEQMAN_DEBUG << "SegmentMmapper : nothing to remap - mmap instead\n";
+ m_mmappedSize = newsize;
+ doMmap();
+
+ } else {
+
+#ifdef linux
+ void *oldBuffer = m_mmappedRegion;
+ m_mmappedRegion = (MappedEvent*)::mremap(m_mmappedRegion, m_mmappedSize,
+ newsize, MREMAP_MAYMOVE);
+ m_mmappedEventBuffer = (MappedEvent *)((size_t *)m_mmappedRegion + 1);
+
+ if (m_mmappedRegion != oldBuffer) {
+ SEQMAN_DEBUG << "NOTE: buffer moved from " << oldBuffer <<
+ " to " << (void *)m_mmappedRegion << endl;
+ }
+#else
+ ::munmap(m_mmappedRegion, m_mmappedSize);
+ m_mmappedRegion = ::mmap(0, newsize,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED, m_fd, 0);
+ m_mmappedEventBuffer = (MappedEvent *)((size_t *)m_mmappedRegion + 1);
+#endif
+
+ if (m_mmappedRegion == (void*) - 1) {
+ SEQMAN_DEBUG << QString("mremap failed : (%1) %2\n").arg(errno).arg(strerror(errno));
+ throw Exception("mremap failed");
+ }
+
+ m_mmappedSize = newsize;
+ }
+}
+
+void SegmentMmapper::doMmap()
+{
+ //
+ // mmap() file for writing
+ //
+ m_mmappedRegion = ::mmap(0, m_mmappedSize,
+ PROT_READ | PROT_WRITE,
+ MAP_SHARED, m_fd, 0);
+ m_mmappedEventBuffer = (MappedEvent *)((size_t *)m_mmappedRegion + 1);
+
+ if (m_mmappedRegion == (void*) - 1) {
+ SEQMAN_DEBUG << QString("mmap failed : (%1) %2\n").arg(errno).arg(strerror(errno));
+ throw Exception("mmap failed");
+ }
+
+ SEQMAN_DEBUG << "SegmentMmapper::doMmap() - mmap size : " << m_mmappedSize
+ << " at " << (void*)m_mmappedRegion << endl;
+
+}
+
+void SegmentMmapper::dump()
+{
+ Composition &comp = m_doc->getComposition();
+
+ RealTime eventTime;
+ RealTime duration;
+ Track* track = comp.getTrackById(m_segment->getTrack());
+
+ timeT segmentStartTime = m_segment->getStartTime();
+ timeT segmentEndTime = m_segment->getEndMarkerTime();
+ timeT segmentDuration = segmentEndTime - segmentStartTime;
+ timeT repeatEndTime = segmentEndTime;
+
+ int repeatCount = getSegmentRepeatCount();
+
+ if (repeatCount > 0)
+ repeatEndTime = m_segment->getRepeatEndTime();
+
+ MappedEvent* bufPos = m_mmappedEventBuffer;
+
+ for (int repeatNo = 0; repeatNo <= repeatCount; ++repeatNo) {
+
+ Segment *triggered = 0;
+ Segment::iterator *i = 0;
+
+ for (Segment::iterator j = m_segment->begin();
+ m_segment->isBeforeEndMarker(j) || (i && *i != triggered->end()); ) {
+
+ bool usingi = false;
+ Segment::iterator *k = &j;
+
+ if (i && *i != triggered->end() &&
+ (!m_segment->isBeforeEndMarker(j) ||
+ (**i)->getAbsoluteTime() < (*j)->getAbsoluteTime())) {
+ k = i;
+ usingi = true;
+ }
+
+ if (!usingi) { // don't permit nested triggered segments
+
+ long triggerId = -1;
+ (**k)->get
+ <Int>(BaseProperties::TRIGGER_SEGMENT_ID, triggerId);
+
+ if (triggerId >= 0) {
+
+ TriggerSegmentRec *rec =
+ comp.getTriggerSegmentRec(triggerId);
+
+ if (rec && rec->getSegment()) {
+ timeT performanceDuration =
+ SegmentPerformanceHelper(*m_segment).
+ getSoundingDuration(j);
+ if (performanceDuration > 0) {
+ mergeTriggerSegment(&triggered, *j,
+ performanceDuration, rec);
+ size_t sz = addMmappedSize(rec->getSegment());
+ size_t offset = bufPos - m_mmappedEventBuffer;
+ setFileSize(sz);
+ remap(sz);
+ bufPos = m_mmappedEventBuffer + offset;
+ }
+ }
+
+ if (triggered) {
+ if (i)
+ delete i;
+ i = new Segment::iterator
+ (triggered->findTime((*j)->getAbsoluteTime()));
+ }
+
+ // Use the next triggered event (presumably the
+ // first of the current triggered segment) instead
+ // of the one that triggered it
+
+ ++j; // whatever happens, we don't want to write this one
+
+ if (i && *i != triggered->end() &&
+ (!m_segment->isBeforeEndMarker(j) ||
+ ((**i)->getAbsoluteTime() < (*j)->getAbsoluteTime()))) {
+ k = i;
+ usingi = true;
+ } else {
+ // no joy at all
+ continue;
+ }
+ }
+ }
+
+ // Ignore rests
+ //
+ if (!(**k)->isa(Note::EventRestType)) {
+
+ SegmentPerformanceHelper helper
+ (usingi ? *triggered : *m_segment);
+
+ timeT playTime =
+ helper.getSoundingAbsoluteTime(*k) + repeatNo * segmentDuration;
+ if (playTime >= repeatEndTime)
+ break;
+
+ timeT playDuration = helper.getSoundingDuration(*k);
+
+ // Ignore notes without duration -- they're probably in a tied
+ // series but not as first note
+ //
+ if (playDuration > 0 || !(**k)->isa(Note::EventType)) {
+
+ if (playTime + playDuration > repeatEndTime)
+ playDuration = repeatEndTime - playTime;
+
+ playTime = playTime + m_segment->getDelay();
+ eventTime = comp.getElapsedRealTime(playTime);
+
+ // slightly quicker than calling helper.getRealSoundingDuration()
+ duration =
+ comp.getElapsedRealTime(playTime + playDuration) - eventTime;
+
+ eventTime = eventTime + m_segment->getRealTimeDelay();
+
+ try {
+ // Create mapped event in mmapped buffer. The
+ // instrument will be extracted from the ControlBlock
+ // by the sequencer, so we set it to zero here.
+ MappedEvent *mE = new (bufPos)
+ MappedEvent(0,
+ ***k, // three stars! what an accolade
+ eventTime,
+ duration);
+ mE->setTrackId(track->getId());
+
+ if (m_segment->getTranspose() != 0 &&
+ (**k)->isa(Note::EventType)) {
+ mE->setPitch(mE->getPitch() + m_segment->getTranspose());
+ }
+
+ ++bufPos;
+
+ } catch (...) {
+ SEQMAN_DEBUG << "SegmentMmapper::dump - caught exception while trying to create MappedEvent\n";
+ }
+ }
+ }
+
+ ++*k; // increment either i or j, whichever one we just used
+ }
+
+ delete i;
+ delete triggered;
+ }
+
+ // Store the number of events at the start of the shared memory region
+ *(size_t *)m_mmappedRegion = (bufPos - m_mmappedEventBuffer);
+
+ size_t coveredArea = (bufPos - m_mmappedEventBuffer) * sizeof(MappedEvent);
+ memset(bufPos, 0, m_mmappedSize - coveredArea - sizeof(size_t));
+
+ ::msync(m_mmappedRegion, m_mmappedSize, MS_ASYNC);
+}
+
+void
+SegmentMmapper::mergeTriggerSegment(Segment **target,
+ Event *trigger,
+ timeT evDuration,
+ TriggerSegmentRec *rec)
+{
+ if (!rec || !rec->getSegment() || rec->getSegment()->empty())
+ return ;
+ if (!*target)
+ *target = new Segment;
+
+ timeT evTime = trigger->getAbsoluteTime();
+ timeT trStart = rec->getSegment()->getStartTime();
+ timeT trEnd = rec->getSegment()->getEndMarkerTime();
+ timeT trDuration = trEnd - trStart;
+ if (trDuration == 0)
+ return ;
+
+ bool retune = false;
+ std::string timeAdjust = BaseProperties::TRIGGER_SEGMENT_ADJUST_NONE;
+
+ trigger->get
+ <Bool>
+ (BaseProperties::TRIGGER_SEGMENT_RETUNE, retune);
+
+ trigger->get
+ <String>
+ (BaseProperties::TRIGGER_SEGMENT_ADJUST_TIMES, timeAdjust);
+
+ long evPitch = rec->getBasePitch();
+ (void)trigger->get
+ <Int>(BaseProperties::PITCH, evPitch);
+ int pitchDiff = evPitch - rec->getBasePitch();
+
+ long evVelocity = rec->getBaseVelocity();
+ (void)trigger->get
+ <Int>(BaseProperties::VELOCITY, evVelocity);
+ int velocityDiff = evVelocity - rec->getBaseVelocity();
+
+ timeT offset = 0;
+ if (timeAdjust == BaseProperties::TRIGGER_SEGMENT_ADJUST_SYNC_END) {
+ offset = evDuration - trDuration;
+ }
+
+ for (Segment::iterator i = rec->getSegment()->begin();
+ rec->getSegment()->isBeforeEndMarker(i); ++i) {
+
+ timeT t = (*i)->getAbsoluteTime() - trStart;
+ timeT d = (*i)->getDuration();
+
+ if (evDuration != trDuration &&
+ timeAdjust == BaseProperties::TRIGGER_SEGMENT_ADJUST_SQUISH) {
+ t = timeT(double(t * evDuration) / double(trDuration));
+ d = timeT(double(d * evDuration) / double(trDuration));
+ }
+
+ t += evTime + offset;
+
+ if (t < evTime) {
+ if (t + d <= evTime)
+ continue;
+ else {
+ d -= (evTime - t);
+ t = evTime;
+ }
+ }
+
+ if (timeAdjust == BaseProperties::TRIGGER_SEGMENT_ADJUST_SYNC_START) {
+ if (t + d > evTime + evDuration) {
+ if (t >= evTime + evDuration)
+ continue;
+ else {
+ d = evTime + evDuration - t;
+ }
+ }
+ }
+
+ Event *newEvent = new Event(**i, t, d);
+
+ if (retune && newEvent->has(BaseProperties::PITCH)) {
+ int pitch = newEvent->get
+ <Int>(BaseProperties::PITCH) + pitchDiff;
+ if (pitch > 127)
+ pitch = 127;
+ if (pitch < 0)
+ pitch = 0;
+ newEvent->set
+ <Int>(BaseProperties::PITCH, pitch);
+ }
+
+ if (newEvent->has(BaseProperties::VELOCITY)) {
+ int velocity = newEvent->get
+ <Int>(BaseProperties::VELOCITY) + velocityDiff;
+ if (velocity > 127)
+ velocity = 127;
+ if (velocity < 0)
+ velocity = 0;
+ newEvent->set
+ <Int>(BaseProperties::VELOCITY, velocity);
+ }
+
+ (*target)->insert(newEvent);
+ }
+}
+
+unsigned int SegmentMmapper::getSegmentRepeatCount()
+{
+ int repeatCount = 0;
+
+ timeT segmentStartTime = m_segment->getStartTime();
+ timeT segmentEndTime = m_segment->getEndMarkerTime();
+ timeT segmentDuration = segmentEndTime - segmentStartTime;
+ timeT repeatEndTime = segmentEndTime;
+
+ if (m_segment->isRepeating() && segmentDuration > 0) {
+ repeatEndTime = m_segment->getRepeatEndTime();
+ repeatCount = 1 + (repeatEndTime - segmentEndTime) / segmentDuration;
+ }
+
+ return repeatCount;
+}
+
+size_t SegmentMmapper::addMmappedSize(Segment *s)
+{
+ int repeatCount = getSegmentRepeatCount();
+ return m_mmappedSize + (repeatCount + 1) * s->size() * sizeof(MappedEvent);
+}
+
+size_t SegmentMmapper::computeMmappedSize()
+{
+ if (!m_segment) return 0;
+
+ int repeatCount = getSegmentRepeatCount();
+
+ return (repeatCount + 1) * m_segment->size() * sizeof(MappedEvent);
+}
+
+}
diff --git a/src/gui/seqmanager/SegmentMmapper.h b/src/gui/seqmanager/SegmentMmapper.h
new file mode 100644
index 0000000..ab25aab
--- /dev/null
+++ b/src/gui/seqmanager/SegmentMmapper.h
@@ -0,0 +1,112 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_SEGMENTMMAPPER_H_
+#define _RG_SEGMENTMMAPPER_H_
+
+#include <qstring.h>
+#include "base/Event.h"
+
+
+
+
+namespace Rosegarden
+{
+
+class TriggerSegmentRec;
+class Segment;
+class RosegardenGUIDoc;
+class MappedEvent;
+class Event;
+
+
+class SegmentMmapper
+{
+ friend class SegmentMmapperFactory;
+public:
+ virtual ~SegmentMmapper();
+
+ /**
+ * refresh the object after the segment has been modified
+ * returns true if size changed (and thus the sequencer
+ * needs to be told about it
+ */
+ bool refresh();
+
+ QString getFileName() { return m_fileName; }
+ size_t getFileSize() const { return m_mmappedSize; }
+
+ virtual unsigned int getSegmentRepeatCount();
+
+protected:
+ SegmentMmapper(RosegardenGUIDoc*, Segment*,
+ const QString& fileName);
+
+ virtual size_t computeMmappedSize();
+
+ virtual size_t addMmappedSize(Segment *);
+
+ /// actual setup, must be called after ctor, calls virtual methods
+ virtual void init();
+
+ /// set the size of the mmapped file
+ void setFileSize(size_t);
+
+ /// perform the mmap() of the file
+ void doMmap();
+
+ /// mremap() the file after a size change
+ void remap(size_t newsize);
+
+ /// dump all segment data in the file
+ virtual void dump();
+
+ void mergeTriggerSegment(Segment **target,
+ Event *trigger,
+ timeT performanceDuration,
+ TriggerSegmentRec *rec);
+
+ //--------------- Data members ---------------------------------
+ RosegardenGUIDoc* m_doc;
+ Segment* m_segment;
+ QString m_fileName;
+
+ int m_fd;
+ size_t m_mmappedSize;
+
+ // The shared memory region starts with a size_t value
+ // representing the number of MappedEvents that follow.
+ void *m_mmappedRegion;
+
+ // And this points to the next byte in the shared memory region.
+ MappedEvent* m_mmappedEventBuffer;
+};
+
+//----------------------------------------
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/SegmentMmapperFactory.cpp b/src/gui/seqmanager/SegmentMmapperFactory.cpp
new file mode 100644
index 0000000..085d842
--- /dev/null
+++ b/src/gui/seqmanager/SegmentMmapperFactory.cpp
@@ -0,0 +1,96 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "SegmentMmapperFactory.h"
+
+#include "base/Segment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "misc/Debug.h"
+#include "MetronomeMmapper.h"
+#include "SegmentMmapper.h"
+#include "AudioSegmentMmapper.h"
+#include "TempoSegmentMmapper.h"
+#include "TimeSigSegmentMmapper.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+SegmentMmapper* SegmentMmapperFactory::makeMmapperForSegment(RosegardenGUIDoc* doc,
+ Rosegarden::Segment* segment,
+ const QString& fileName)
+{
+ SegmentMmapper* mmapper = 0;
+
+ if (segment == 0) {
+ SEQMAN_DEBUG << "SegmentMmapperFactory::makeMmapperForSegment() segment == 0\n";
+ return 0;
+ }
+
+ switch (segment->getType()) {
+ case Segment::Internal :
+ mmapper = new SegmentMmapper(doc, segment, fileName);
+ break;
+ case Segment::Audio :
+ mmapper = new AudioSegmentMmapper(doc, segment, fileName);
+ break;
+ default:
+ SEQMAN_DEBUG << "SegmentMmapperFactory::makeMmapperForSegment(" << segment
+ << ") : can't map, unknown segment type " << segment->getType() << endl;
+ mmapper = 0;
+ }
+
+ if (mmapper)
+ mmapper->init();
+
+ return mmapper;
+}
+
+MetronomeMmapper* SegmentMmapperFactory::makeMetronome(RosegardenGUIDoc* doc)
+{
+ MetronomeMmapper* mmapper = new MetronomeMmapper(doc);
+ mmapper->init();
+
+ return mmapper;
+}
+
+TimeSigSegmentMmapper* SegmentMmapperFactory::makeTimeSig(RosegardenGUIDoc* doc)
+{
+ TimeSigSegmentMmapper* mmapper = new TimeSigSegmentMmapper(doc, "rosegarden_timesig");
+
+ mmapper->init();
+ return mmapper;
+}
+
+TempoSegmentMmapper* SegmentMmapperFactory::makeTempo(RosegardenGUIDoc* doc)
+{
+ TempoSegmentMmapper* mmapper = new TempoSegmentMmapper(doc, "rosegarden_tempo");
+
+ mmapper->init();
+ return mmapper;
+}
+
+}
diff --git a/src/gui/seqmanager/SegmentMmapperFactory.h b/src/gui/seqmanager/SegmentMmapperFactory.h
new file mode 100644
index 0000000..2970024
--- /dev/null
+++ b/src/gui/seqmanager/SegmentMmapperFactory.h
@@ -0,0 +1,63 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_SEGMENTMMAPPERFACTORY_H_
+#define _RG_SEGMENTMMAPPERFACTORY_H_
+
+
+
+class QString;
+
+
+namespace Rosegarden
+{
+
+class TimeSigSegmentMmapper;
+class TempoSegmentMmapper;
+class SegmentMmapper;
+class Segment;
+class RosegardenGUIDoc;
+class MetronomeMmapper;
+
+
+class SegmentMmapperFactory
+{
+public:
+
+ static SegmentMmapper* makeMmapperForSegment(RosegardenGUIDoc*, Segment*,
+ const QString& fileName);
+
+ static MetronomeMmapper* makeMetronome(RosegardenGUIDoc*);
+ static TimeSigSegmentMmapper* makeTimeSig(RosegardenGUIDoc*);
+ static TempoSegmentMmapper* makeTempo(RosegardenGUIDoc*);
+};
+
+//----------------------------------------
+
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/SequenceManager.cpp b/src/gui/seqmanager/SequenceManager.cpp
new file mode 100644
index 0000000..12334f6
--- /dev/null
+++ b/src/gui/seqmanager/SequenceManager.cpp
@@ -0,0 +1,2141 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "SequenceManager.h"
+
+#include "sound/Midi.h"
+#include "misc/Debug.h"
+#include "document/ConfigGroups.h"
+#include "base/Composition.h"
+#include "base/Device.h"
+#include "base/Exception.h"
+#include "base/Instrument.h"
+#include "base/MidiProgram.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/Studio.h"
+#include "base/Track.h"
+#include "base/TriggerSegment.h"
+#include "CompositionMmapper.h"
+#include "document/RosegardenGUIDoc.h"
+#include "document/MultiViewCommandHistory.h"
+#include "gui/application/RosegardenApplication.h"
+#include "gui/application/RosegardenGUIApp.h"
+#include "gui/application/RosegardenGUIView.h"
+#include "gui/dialogs/AudioManagerDialog.h"
+#include "gui/dialogs/CountdownDialog.h"
+#include "gui/dialogs/TransportDialog.h"
+#include "gui/kdeext/KStartupLogo.h"
+#include "gui/studio/StudioControl.h"
+#include "gui/widgets/CurrentProgressDialog.h"
+#include "MetronomeMmapper.h"
+#include "SegmentMmapperFactory.h"
+#include "SequencerMapper.h"
+#include "ControlBlockMmapper.h"
+#include "sound/AudioFile.h"
+#include "sound/MappedComposition.h"
+#include "sound/MappedEvent.h"
+#include "sound/MappedInstrument.h"
+#include "sound/SoundDriver.h"
+#include "TempoSegmentMmapper.h"
+#include "TimeSigSegmentMmapper.h"
+#include <klocale.h>
+#include <kstddirs.h>
+#include <kconfig.h>
+#include <kglobal.h>
+#include <kmessagebox.h>
+#include <qapplication.h>
+#include <qcstring.h>
+#include <qcursor.h>
+#include <qdatastream.h>
+#include <qevent.h>
+#include <qobject.h>
+#include <qpushbutton.h>
+#include <qstring.h>
+#include <qstringlist.h>
+#include <qtimer.h>
+#include <algorithm>
+
+
+namespace Rosegarden
+{
+
+SequenceManager::SequenceManager(RosegardenGUIDoc *doc,
+ TransportDialog *transport):
+ m_doc(doc),
+ m_compositionMmapper(new CompositionMmapper(m_doc)),
+ m_controlBlockMmapper(new ControlBlockMmapper(m_doc)),
+ m_metronomeMmapper(SegmentMmapperFactory::makeMetronome(m_doc)),
+ m_tempoSegmentMmapper(SegmentMmapperFactory::makeTempo(m_doc)),
+ m_timeSigSegmentMmapper(SegmentMmapperFactory::makeTimeSig(m_doc)),
+ m_transportStatus(STOPPED),
+ m_soundDriverStatus(NO_DRIVER),
+ m_transport(transport),
+ m_lastRewoundAt(clock()),
+ m_countdownDialog(0),
+ m_countdownTimer(new QTimer(m_doc)),
+ m_shownOverrunWarning(false),
+ m_recordTime(new QTime()),
+ m_compositionRefreshStatusId(m_doc->getComposition().getNewRefreshStatusId()),
+ m_updateRequested(true),
+ m_compositionMmapperResetTimer(new QTimer(m_doc)),
+ m_sequencerMapper(0),
+ m_reportTimer(new QTimer(m_doc)),
+ m_canReport(true),
+ m_lastLowLatencySwitchSent(false),
+ m_lastTransportStartPosition(0),
+ m_sampleRate(0)
+{
+ // Replaced this with a call to cleanup() from composition mmapper ctor:
+ // if done here, this removes the mmapped versions of any segments stored
+ // in the autoload (that have only just been mapped by the ctor!)
+ // m_compositionMmapper->cleanup();
+
+ m_countdownDialog = new CountdownDialog(dynamic_cast<QWidget*>
+ (m_doc->parent())->parentWidget());
+ // Connect these for use later
+ //
+ connect(m_countdownTimer, SIGNAL(timeout()),
+ this, SLOT(slotCountdownTimerTimeout()));
+
+ connect(m_reportTimer, SIGNAL(timeout()),
+ this, SLOT(slotAllowReport()));
+
+ connect(m_compositionMmapperResetTimer, SIGNAL(timeout()),
+ this, SLOT(slotScheduledCompositionMmapperReset()));
+
+
+ connect(doc->getCommandHistory(), SIGNAL(commandExecuted()),
+ this, SLOT(update()));
+
+ m_doc->getComposition().addObserver(this);
+
+ // The owner of this sequence manager will need to call
+ // checkSoundDriverStatus on it to set up its status appropriately
+ // immediately after construction; we used to do it from here but
+ // we're not well placed to handle reporting to the user if it
+ // throws an exception (and we don't want to leave the object half
+ // constructed).
+
+ // Try to map the sequencer file
+ //
+ mapSequencer();
+}
+
+SequenceManager::~SequenceManager()
+{
+ m_doc->getComposition().removeObserver(this);
+
+ SEQMAN_DEBUG << "SequenceManager::~SequenceManager()\n";
+ delete m_compositionMmapper;
+ delete m_controlBlockMmapper;
+ delete m_metronomeMmapper;
+ delete m_tempoSegmentMmapper;
+ delete m_timeSigSegmentMmapper;
+ delete m_sequencerMapper;
+}
+
+void SequenceManager::setDocument(RosegardenGUIDoc* doc)
+{
+ SEQMAN_DEBUG << "SequenceManager::setDocument(" << doc << ")\n";
+
+ DataBlockRepository::clear();
+
+ m_doc->getComposition().removeObserver(this);
+ disconnect(m_doc->getCommandHistory(), SIGNAL(commandExecuted()));
+
+ m_segments.clear();
+ m_triggerSegments.clear();
+
+ m_doc = doc;
+ Composition &comp = m_doc->getComposition();
+
+ // Must recreate and reconnect the countdown timer and dialog
+ // (bug 729039)
+ //
+ delete m_countdownDialog;
+ delete m_countdownTimer;
+ delete m_compositionMmapperResetTimer;
+
+ m_countdownDialog = new CountdownDialog(dynamic_cast<QWidget*>
+ (m_doc->parent())->parentWidget());
+
+ // Bug 933041: no longer connect the CountdownDialog from
+ // SequenceManager; instead let the RosegardenGUIApp connect it to
+ // its own slotStop to ensure the right housekeeping is done
+
+ m_countdownTimer = new QTimer(m_doc);
+
+ // Connect this for use later
+ //
+ connect(m_countdownTimer, SIGNAL(timeout()),
+ this, SLOT(slotCountdownTimerTimeout()));
+
+ m_compositionRefreshStatusId = comp.getNewRefreshStatusId();
+ comp.addObserver(this);
+
+ connect(m_doc->getCommandHistory(), SIGNAL(commandExecuted()),
+ this, SLOT(update()));
+
+ for (Composition::iterator i = comp.begin(); i != comp.end(); ++i) {
+
+ SEQMAN_DEBUG << "Adding segment with rid " << (*i)->getRuntimeId() << endl;
+
+ m_segments.insert(SegmentRefreshMap::value_type
+ (*i, (*i)->getNewRefreshStatusId()));
+ }
+
+ for (Composition::triggersegmentcontaineriterator i =
+ comp.getTriggerSegments().begin();
+ i != comp.getTriggerSegments().end(); ++i) {
+ m_triggerSegments.insert(SegmentRefreshMap::value_type
+ ((*i)->getSegment(),
+ (*i)->getSegment()->getNewRefreshStatusId()));
+ }
+
+
+ m_compositionMmapperResetTimer = new QTimer(m_doc);
+ connect(m_compositionMmapperResetTimer, SIGNAL(timeout()),
+ this, SLOT(slotScheduledCompositionMmapperReset()));
+
+ resetCompositionMmapper();
+
+ // Try to map the sequencer file
+ //
+ mapSequencer();
+}
+
+void
+SequenceManager::setTransportStatus(const TransportStatus &status)
+{
+ m_transportStatus = status;
+}
+
+void
+SequenceManager::mapSequencer()
+{
+ if (m_sequencerMapper)
+ return ;
+
+ try {
+ m_sequencerMapper = new SequencerMapper(
+ KGlobal::dirs()->resourceDirs("tmp").last() + "/rosegarden_sequencer_timing_block");
+ } catch (Exception) {
+ m_sequencerMapper = 0;
+ }
+}
+
+bool
+SequenceManager::play()
+{
+ mapSequencer();
+
+ Composition &comp = m_doc->getComposition();
+
+ // If already playing or recording then stop
+ //
+ if (m_transportStatus == PLAYING ||
+ m_transportStatus == RECORDING ) {
+ stopping();
+ return true;
+ }
+
+ // This check may throw an exception
+ checkSoundDriverStatus(false);
+
+ // Align Instrument lists and send initial program changes
+ //
+ preparePlayback();
+
+ m_lastTransportStartPosition = comp.getPosition();
+
+ // Update play metronome status
+ //
+ m_controlBlockMmapper->updateMetronomeData
+ (m_metronomeMmapper->getMetronomeInstrument());
+ m_controlBlockMmapper->updateMetronomeForPlayback();
+
+ // make sure we toggle the play button
+ //
+ m_transport->PlayButton()->setOn(true);
+
+ //!!! disable the record button, because recording while playing is horribly
+ // broken, and disabling it is less complicated than fixing it
+ // see #1223025 - DMM
+ // SEQMAN_DEBUG << "SequenceManager::play() - disabling record button, as we are playing\n";
+ // m_transport->RecordButton()->setEnabled(false);
+
+ if (comp.getCurrentTempo() == 0) {
+ comp.setCompositionDefaultTempo(comp.getTempoForQpm(120.0));
+
+ SEQMAN_DEBUG << "SequenceManager::play() - setting Tempo to Default value of 120.000\n";
+ } else {
+ SEQMAN_DEBUG << "SequenceManager::play() - starting to play\n";
+ }
+
+ // Send initial tempo
+ //
+ double qnD = 60.0 / comp.getTempoQpm(comp.getCurrentTempo());
+ RealTime qnTime =
+ RealTime(long(qnD),
+ long((qnD - double(long(qnD))) * 1000000000.0));
+ StudioControl::sendQuarterNoteLength(qnTime);
+
+ // set the tempo in the transport
+ m_transport->setTempo(comp.getCurrentTempo());
+
+ // The arguments for the Sequencer
+ RealTime startPos = comp.getElapsedRealTime(comp.getPosition());
+
+ // If we're looping then jump to loop start
+ if (comp.isLooping())
+ startPos = comp.getElapsedRealTime(comp.getLoopStart());
+
+ KConfig* config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+
+ bool lowLat = config->readBoolEntry("audiolowlatencymonitoring", true);
+
+ if (lowLat != m_lastLowLatencySwitchSent) {
+
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+ streamOut << lowLat;
+
+ rgapp->sequencerSend("setLowLatencyMode(bool)", data);
+ m_lastLowLatencySwitchSent = lowLat;
+ }
+
+ QByteArray data;
+ QCString replyType;
+ QByteArray replyData;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ // playback start position
+ streamOut << (long)startPos.sec;
+ streamOut << (long)startPos.nsec;
+
+ // Apart from perhaps the small file size, I think with hindsight
+ // that these options are more easily set to reasonable defaults
+ // here than left to the user. Mostly.
+
+ //!!! need some cleverness somewhere to ensure the read-ahead
+ //is larger than the JACK period size
+
+ if (lowLat) {
+ streamOut << 0L; // read-ahead sec
+ streamOut << 160000000L; // read-ahead nsec
+ streamOut << 0L; // audio mix sec
+ streamOut << 60000000L; // audio mix nsec: ignored in lowlat mode
+ streamOut << 2L; // audio read sec
+ streamOut << 500000000L; // audio read nsec
+ streamOut << 4L; // audio write sec
+ streamOut << 0L; // audio write nsec
+ streamOut << 256L; // cacheable small file size in K
+ } else {
+ streamOut << 0L; // read-ahead sec
+ streamOut << 500000000L; // read-ahead nsec
+ streamOut << 0L; // audio mix sec
+ streamOut << 400000000L; // audio mix nsec
+ streamOut << 2L; // audio read sec
+ streamOut << 500000000L; // audio read nsec
+ streamOut << 4L; // audio write sec
+ streamOut << 0L; // audio write nsec
+ streamOut << 256L; // cacheable small file size in K
+ }
+
+ // Send Play to the Sequencer
+ if (!rgapp->sequencerCall("play(long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int)",
+ replyType, replyData, data)) {
+ m_transportStatus = STOPPED;
+ return false;
+ }
+
+ // ensure the return type is ok
+ QDataStream streamIn(replyData, IO_ReadOnly);
+ int result;
+ streamIn >> result;
+
+ if (result) {
+ // completed successfully
+ m_transportStatus = STARTING_TO_PLAY;
+ } else {
+ m_transportStatus = STOPPED;
+ std::cerr << "ERROR: SequenceManager::play(): Failed to start playback!" << std::endl;
+ }
+
+ return false;
+}
+
+void
+SequenceManager::stopping()
+{
+ if (m_countdownTimer)
+ m_countdownTimer->stop();
+ if (m_countdownDialog)
+ m_countdownDialog->hide();
+
+ // Do this here rather than in stop() to avoid any potential
+ // race condition (we use setPointerPosition() during stop()).
+ //
+ if (m_transportStatus == STOPPED) {
+ /*!!!
+ if (m_doc->getComposition().isLooping())
+ m_doc->slotSetPointerPosition(m_doc->getComposition().getLoopStart());
+ else
+ m_doc->slotSetPointerPosition(m_doc->getComposition().getStartMarker());
+ */
+ m_doc->slotSetPointerPosition(m_lastTransportStartPosition);
+
+ return ;
+ }
+
+ // Disarm recording and drop back to STOPPED
+ //
+ if (m_transportStatus == RECORDING_ARMED) {
+ m_transportStatus = STOPPED;
+ m_transport->RecordButton()->setOn(false);
+ m_transport->MetronomeButton()->
+ setOn(m_doc->getComposition().usePlayMetronome());
+ return ;
+ }
+
+ SEQMAN_DEBUG << "SequenceManager::stopping() - preparing to stop\n";
+
+ // SEQMAN_DEBUG << kdBacktrace() << endl;
+
+ stop();
+
+ m_shownOverrunWarning = false;
+}
+
+void
+SequenceManager::stop()
+{
+ // Toggle off the buttons - first record
+ //
+ if (m_transportStatus == RECORDING) {
+ m_transport->RecordButton()->setOn(false);
+ m_transport->MetronomeButton()->
+ setOn(m_doc->getComposition().usePlayMetronome());
+
+ // Remove the countdown dialog and stop the timer
+ //
+ m_countdownDialog->hide();
+ m_countdownTimer->stop();
+ }
+
+ // Now playback
+ m_transport->PlayButton()->setOn(false);
+
+ // re-enable the record button if it was previously disabled when
+ // going into play mode - DMM
+ // SEQMAN_DEBUG << "SequenceManager::stop() - re-enabling record button\n";
+ // m_transport->RecordButton()->setEnabled(true);
+
+
+ // "call" the sequencer with a stop so we get a synchronous
+ // response - then we can fiddle about with the audio file
+ // without worrying about the sequencer causing problems
+ // with access to the same audio files.
+ //
+
+ // wait cursor
+ //
+ QApplication::setOverrideCursor(QCursor(Qt::waitCursor));
+
+ QCString replyType;
+ QByteArray replyData;
+
+ bool failed = false;
+ if (!rgapp->sequencerCall("stop()", replyType, replyData)) {
+ failed = true;
+ }
+
+ // restore
+ QApplication::restoreOverrideCursor();
+
+ TransportStatus status = m_transportStatus;
+
+ // set new transport status first, so that if we're stopping
+ // recording we don't risk the record segment being restored by a
+ // timer while the document is busy trying to do away with it
+ m_transportStatus = STOPPED;
+
+ // if we're recording MIDI or Audio then tidy up the recording Segment
+ if (status == RECORDING) {
+ m_doc->stopRecordingMidi();
+ m_doc->stopRecordingAudio();
+
+ SEQMAN_DEBUG << "SequenceManager::stop() - stopped recording\n";
+ }
+
+ // always untoggle the play button at this stage
+ //
+ m_transport->PlayButton()->setOn(false);
+ SEQMAN_DEBUG << "SequenceManager::stop() - stopped playing\n";
+
+ // We don't reset controllers at this point - what happens with static
+ // controllers the next time we play otherwise? [rwb]
+ //resetControllers();
+
+ if (failed) {
+ throw(Exception("Failed to contact Rosegarden sequencer with stop command. Please save your composition and restart Rosegarden to continue."));
+ }
+}
+
+void
+SequenceManager::rewind()
+{
+ Composition &composition = m_doc->getComposition();
+
+ timeT position = composition.getPosition();
+ std::pair<timeT, timeT> barRange =
+ composition.getBarRangeForTime(position - 1);
+
+ if (m_transportStatus == PLAYING) {
+
+ // if we're playing and we had a rewind request less than 200ms
+ // ago and we're some way into the bar but less than half way
+ // through it, rewind two barlines instead of one
+
+ clock_t now = clock();
+ int elapsed = (now - m_lastRewoundAt) * 1000 / CLOCKS_PER_SEC;
+
+ SEQMAN_DEBUG << "That was " << m_lastRewoundAt << ", this is " << now << ", elapsed is " << elapsed << endl;
+
+ if (elapsed >= 0 && elapsed <= 200) {
+ if (position > barRange.first &&
+ position < barRange.second &&
+ position <= (barRange.first + (barRange.second -
+ barRange.first) / 2)) {
+ barRange = composition.getBarRangeForTime(barRange.first - 1);
+ }
+ }
+
+ m_lastRewoundAt = now;
+ }
+
+ if (barRange.first < composition.getStartMarker()) {
+ m_doc->slotSetPointerPosition(composition.getStartMarker());
+ } else {
+ m_doc->slotSetPointerPosition(barRange.first);
+ }
+}
+
+void
+SequenceManager::fastforward()
+{
+ Composition &composition = m_doc->getComposition();
+
+ timeT position = composition.getPosition() + 1;
+ timeT newPosition = composition.getBarRangeForTime(position).second;
+
+ // Don't skip past end marker
+ //
+ if (newPosition > composition.getEndMarker())
+ newPosition = composition.getEndMarker();
+
+ m_doc->slotSetPointerPosition(newPosition);
+
+}
+
+void
+SequenceManager::notifySequencerStatus(TransportStatus status)
+{
+ // for the moment we don't do anything fancy
+ m_transportStatus = status;
+
+}
+
+void
+SequenceManager::sendSequencerJump(const RealTime &time)
+{
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+ streamOut << (long)time.sec;
+ streamOut << (long)time.nsec;
+
+ rgapp->sequencerSend("jumpTo(long int, long int)", data);
+}
+
+void
+SequenceManager::record(bool toggled)
+{
+ mapSequencer();
+
+ SEQMAN_DEBUG << "SequenceManager::record(" << toggled << ")" << endl;
+
+ Composition &comp = m_doc->getComposition();
+ Studio &studio = m_doc->getStudio();
+ KConfig* config = kapp->config();
+ config->setGroup(GeneralOptionsConfigGroup);
+
+ bool punchIn = false; // are we punching in?
+
+ // If we have any audio tracks armed, then we need to check for
+ // a valid audio record path and a working audio subsystem before
+ // we go any further
+
+ const Composition::recordtrackcontainer &recordTracks =
+ comp.getRecordTracks();
+
+ for (Composition::recordtrackcontainer::const_iterator i =
+ recordTracks.begin();
+ i != recordTracks.end(); ++i) {
+
+ Track *track = comp.getTrackById(*i);
+ InstrumentId instrId = track->getInstrument();
+ Instrument *instr = studio.getInstrumentById(instrId);
+
+ if (instr && instr->getType() == Instrument::Audio) {
+ if (!m_doc || !(m_soundDriverStatus & AUDIO_OK)) {
+ m_transport->RecordButton()->setOn(false);
+ throw(Exception("Audio subsystem is not available - can't record audio"));
+ }
+ // throws BadAudioPathException if path is not valid:
+ m_doc->getAudioFileManager().testAudioPath();
+ break;
+ }
+ }
+
+ if (toggled) { // preparing record or punch-in record
+
+ if (m_transportStatus == RECORDING_ARMED) {
+ SEQMAN_DEBUG << "SequenceManager::record - unarming record\n";
+ m_transportStatus = STOPPED;
+
+ // Toggle the buttons
+ m_transport->MetronomeButton()->setOn(comp.usePlayMetronome());
+ m_transport->RecordButton()->setOn(false);
+
+ return ;
+ }
+
+ if (m_transportStatus == STOPPED) {
+ SEQMAN_DEBUG << "SequenceManager::record - armed record\n";
+ m_transportStatus = RECORDING_ARMED;
+
+ // Toggle the buttons
+ m_transport->MetronomeButton()->setOn(comp.useRecordMetronome());
+ m_transport->RecordButton()->setOn(true);
+
+ return ;
+ }
+
+ if (m_transportStatus == RECORDING) {
+ SEQMAN_DEBUG << "SequenceManager::record - stop recording and keep playing\n";
+
+ QByteArray data;
+ QCString replyType;
+ QByteArray replyData;
+
+ // Send Record to the Sequencer to signal it to drop out of record mode
+ if (!rgapp->sequencerCall("punchOut()", replyType, replyData, data)) {
+ SEQMAN_DEBUG << "SequenceManager::record - the \"not very plausible\" code executed\n";
+ // #1797873 - set new transport status first, so that
+ // if we're stopping recording we don't risk the
+ // record segment being restored by a timer while the
+ // document is busy trying to do away with it
+ m_transportStatus = STOPPED;
+
+ m_doc->stopRecordingMidi();
+ m_doc->stopRecordingAudio();
+ return ;
+ }
+
+ // #1797873 - as above
+ m_transportStatus = PLAYING;
+
+ m_doc->stopRecordingMidi();
+ m_doc->stopRecordingAudio();
+
+ return ;
+ }
+
+ if (m_transportStatus == PLAYING) {
+ SEQMAN_DEBUG << "SequenceManager::record - punch in recording\n";
+ punchIn = true;
+ goto punchin;
+ }
+
+ } else {
+
+ m_lastTransportStartPosition = comp.getPosition();
+
+punchin:
+
+ // Get the record tracks and check we have a record instrument
+
+ bool haveInstrument = false;
+ bool haveAudioInstrument = false;
+ bool haveMIDIInstrument = false;
+ //TrackId recordMIDITrack = 0;
+
+ for (Composition::recordtrackcontainer::const_iterator i =
+ comp.getRecordTracks().begin();
+ i != comp.getRecordTracks().end(); ++i) {
+
+ InstrumentId iid =
+ comp.getTrackById(*i)->getInstrument();
+
+ Instrument *inst = studio.getInstrumentById(iid);
+ if (inst) {
+ haveInstrument = true;
+ if (inst->getType() == Instrument::Audio) {
+ haveAudioInstrument = true;
+ break;
+ } else { // soft synths count as MIDI for our purposes here
+ haveMIDIInstrument = true;
+ //recordMIDITrack = *i;
+ }
+ }
+ }
+
+ if (!haveInstrument) {
+ m_transport->RecordButton()->setDown(false);
+ throw(Exception("No Record instrument selected"));
+ }
+
+ // may throw an exception
+ checkSoundDriverStatus(false);
+
+ // toggle the Metronome button if it's in use
+ m_transport->MetronomeButton()->setOn(comp.useRecordMetronome());
+
+ // Update record metronome status
+ //
+ m_controlBlockMmapper->updateMetronomeData
+ (m_metronomeMmapper->getMetronomeInstrument());
+ m_controlBlockMmapper->updateMetronomeForRecord();
+
+ // If we are looping then jump to start of loop and start recording,
+ // if we're not take off the number of count-in bars and start
+ // recording.
+ //
+ if (comp.isLooping())
+ m_doc->slotSetPointerPosition(comp.getLoopStart());
+ else {
+ if (m_transportStatus != RECORDING_ARMED && punchIn == false) {
+ int startBar = comp.getBarNumber(comp.getPosition());
+ startBar -= config->readUnsignedNumEntry("countinbars", 0);
+ m_doc->slotSetPointerPosition(comp.getBarRange(startBar).first);
+ }
+ }
+
+ m_doc->setRecordStartTime(m_doc->getComposition().getPosition());
+
+ if (haveAudioInstrument) {
+ // Ask the document to update its record latencies so as to
+ // do latency compensation when we stop
+ m_doc->updateAudioRecordLatency();
+ }
+
+ if (haveMIDIInstrument) {
+ // Create the record MIDI segment now, so that the
+ // composition view has a real segment to display. It
+ // won't actually be added to the composition until the
+ // first recorded event arrives. We don't have to do this
+ // from here for audio, because for audio the sequencer
+ // calls back on createRecordAudioFiles so as to find out
+ // what files it needs to write to.
+ /*m_doc->addRecordMIDISegment(recordMIDITrack);*/
+ for (Composition::recordtrackcontainer::const_iterator i =
+ comp.getRecordTracks().begin(); i != comp.getRecordTracks().end(); ++i) {
+ InstrumentId iid = comp.getTrackById(*i)->getInstrument();
+ Instrument *inst = studio.getInstrumentById(iid);
+ if (inst && (inst->getType() != Instrument::Audio)) {
+ SEQMAN_DEBUG << "SequenceManager: mdoc->addRecordMIDISegment(" << *i << ")" << endl;
+ m_doc->addRecordMIDISegment(*i);
+ }
+ }
+ }
+
+ // set the buttons
+ m_transport->RecordButton()->setOn(true);
+ m_transport->PlayButton()->setOn(true);
+
+ if (comp.getCurrentTempo() == 0) {
+ SEQMAN_DEBUG << "SequenceManager::play() - setting Tempo to Default value of 120.000\n";
+ comp.setCompositionDefaultTempo(comp.getTempoForQpm(120.0));
+ } else {
+ SEQMAN_DEBUG << "SequenceManager::record() - starting to record\n";
+ }
+
+ // set the tempo in the transport
+ //
+ m_transport->setTempo(comp.getCurrentTempo());
+
+ // The arguments for the Sequencer - record is similar to playback,
+ // we must being playing to record.
+ //
+ RealTime startPos =
+ comp.getElapsedRealTime(comp.getPosition());
+
+ bool lowLat = config->readBoolEntry("audiolowlatencymonitoring", true);
+
+ if (lowLat != m_lastLowLatencySwitchSent) {
+
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+ streamOut << lowLat;
+
+ rgapp->sequencerSend("setLowLatencyMode(bool)", data);
+ m_lastLowLatencySwitchSent = lowLat;
+ }
+
+ QByteArray data;
+ QCString replyType;
+ QByteArray replyData;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ // playback start position
+ streamOut << (long)startPos.sec;
+ streamOut << (long)startPos.nsec;
+
+ // Apart from perhaps the small file size, I think with hindsight
+ // that these options are more easily set to reasonable defaults
+ // here than left to the user. Mostly.
+
+ //!!! Duplicates code in play()
+
+ //!!! need some cleverness somewhere to ensure the read-ahead
+ //is larger than the JACK period size
+
+ if (lowLat) {
+ streamOut << 0L; // read-ahead sec
+ streamOut << 160000000L; // read-ahead nsec
+ streamOut << 0L; // audio mix sec
+ streamOut << 60000000L; // audio mix nsec: ignored in lowlat mode
+ streamOut << 2L; // audio read sec
+ streamOut << 500000000L; // audio read nsec
+ streamOut << 4L; // audio write sec
+ streamOut << 0L; // audio write nsec
+ streamOut << 256L; // cacheable small file size in K
+ } else {
+ streamOut << 0L; // read-ahead sec
+ streamOut << 500000000L; // read-ahead nsec
+ streamOut << 0L; // audio mix sec
+ streamOut << 400000000L; // audio mix nsec
+ streamOut << 2L; // audio read sec
+ streamOut << 500000000L; // audio read nsec
+ streamOut << 4L; // audio write sec
+ streamOut << 0L; // audio write nsec
+ streamOut << 256L; // cacheable small file size in K
+ }
+
+ // record type
+ streamOut << (long)STARTING_TO_RECORD;
+
+ // Send Play to the Sequencer
+ if (!rgapp->sequencerCall("record(long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int, long int)",
+ replyType, replyData, data)) {
+ // failed
+ m_transportStatus = STOPPED;
+ return ;
+ }
+
+ // ensure the return type is ok
+ QDataStream streamIn(replyData, IO_ReadOnly);
+ int result;
+ streamIn >> result;
+
+ if (result) {
+
+ // completed successfully
+ m_transportStatus = STARTING_TO_RECORD;
+
+ // Create the countdown timer dialog to show recording time
+ // remaining. (Note (dmm) this has changed, and it now reports
+ // the time remaining during both MIDI and audio recording.)
+ //
+ timeT p = comp.getPosition();
+ timeT d = comp.getEndMarker();
+ // end marker less current position == available duration
+ d -= p;
+
+ // set seconds to total possible time, initially
+ RealTime rtd = comp.getElapsedRealTime(d);
+ int seconds = rtd.sec;
+
+ // re-initialise
+ m_countdownDialog->setTotalTime(seconds);
+
+ // Create the timer
+ //
+ m_recordTime->start();
+
+ // Start an elapse timer for updating the dialog -
+ // it will fire every second.
+ //
+ m_countdownTimer->start(1000);
+
+ // Pop-up the dialog (don't use exec())
+ //
+ // bug #1505805, abolish recording countdown dialog
+ //m_countdownDialog->show();
+
+ } else {
+ // Stop immediately - turn off buttons in parent
+ //
+ m_transportStatus = STOPPED;
+
+ if (haveAudioInstrument) {
+ throw(Exception("Couldn't start recording audio.\nPlease set a valid file path in the Document Properties\n(Composition menu -> Edit Document Properties -> Audio)."));
+ }
+ }
+ }
+}
+
+void
+SequenceManager::processAsynchronousMidi(const MappedComposition &mC,
+ AudioManagerDialog *audioManagerDialog)
+{
+ static bool boolShowingWarning = false;
+ static bool boolShowingALSAWarning = false;
+ static long warningShownAt = 0;
+
+ if (m_doc == 0 || mC.size() == 0)
+ return ;
+
+ MappedComposition::const_iterator i;
+
+ // Thru filtering is done at the sequencer for the actual sound
+ // output, but here we need both filtered (for OUT display) and
+ // unfiltered (for insertable note callbacks) compositions, so
+ // we've received the unfiltered copy and will filter here
+ MappedComposition tempMC =
+ applyFiltering(mC,
+ MappedEvent::MappedEventType(
+ m_doc->getStudio().getMIDIThruFilter()));
+
+ // send to the MIDI labels (which can only hold one event at a time)
+ i = mC.begin();
+ if (i != mC.end()) {
+ m_transport->setMidiInLabel(*i);
+ }
+
+ i = tempMC.begin();
+ while (i != tempMC.end()) {
+ if ((*i)->getRecordedDevice() != Device::CONTROL_DEVICE) {
+ m_transport->setMidiOutLabel(*i);
+ break;
+ }
+ ++i;
+ }
+
+ for (i = mC.begin(); i != mC.end(); ++i ) {
+ if ((*i)->getType() >= MappedEvent::Audio) {
+ if ((*i)->getType() == MappedEvent::AudioStopped) {
+ /*
+ SEQMAN_DEBUG << "AUDIO FILE ID = "
+ << int((*i)->getData1())
+ << " - FILE STOPPED - "
+ << "INSTRUMENT = "
+ << (*i)->getInstrument()
+ << endl;
+ */
+
+ if (audioManagerDialog && (*i)->getInstrument() ==
+ m_doc->getStudio().getAudioPreviewInstrument()) {
+ audioManagerDialog->
+ closePlayingDialog(
+ AudioFileId((*i)->getData1()));
+ }
+ }
+
+ if ((*i)->getType() == MappedEvent::AudioLevel)
+ sendAudioLevel(*i);
+
+ if ((*i)->getType() ==
+ MappedEvent::AudioGeneratePreview) {
+ SEQMAN_DEBUG << "Received AudioGeneratePreview: data1 is " << int((*i)->getData1()) << ", data2 " << int((*i)->getData2()) << ", instrument is " << (*i)->getInstrument() << endl;
+
+ m_doc->finalizeAudioFile((int)(*i)->getData1() +
+ (int)(*i)->getData2() * 256);
+ }
+
+ if ((*i)->getType() ==
+ MappedEvent::SystemUpdateInstruments) {
+ // resync Devices and Instruments
+ //
+ m_doc->syncDevices();
+
+ /*KConfig* config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+ QString recordDeviceStr = config->readEntry("midirecorddevice");
+ sendMIDIRecordingDevice(recordDeviceStr);*/
+ restoreRecordSubscriptions();
+ }
+
+ if (m_transportStatus == PLAYING ||
+ m_transportStatus == RECORDING) {
+ if ((*i)->getType() == MappedEvent::SystemFailure) {
+
+ SEQMAN_DEBUG << "Failure of some sort..." << endl;
+
+ bool handling = true;
+
+ /* These are the ones that we always report or handle. */
+
+ if ((*i)->getData1() == MappedEvent::FailureJackDied) {
+
+ // Something horrible has happened to JACK or we got
+ // bumped out of the graph. Either way stop playback.
+ //
+ stopping();
+
+ } else if ((*i)->getData1() == MappedEvent::FailureJackRestartFailed) {
+
+ KMessageBox::error(
+ dynamic_cast<QWidget*>(m_doc->parent())->parentWidget(),
+ i18n("The JACK Audio subsystem has failed or it has stopped Rosegarden from processing audio.\nPlease restart Rosegarden to continue working with audio.\nQuitting other running applications may improve Rosegarden's performance."));
+
+ } else if ((*i)->getData1() == MappedEvent::FailureJackRestart) {
+
+ KMessageBox::error(
+ dynamic_cast<QWidget*>(m_doc->parent())->parentWidget(),
+ i18n("The JACK Audio subsystem has stopped Rosegarden from processing audio, probably because of a processing overload.\nAn attempt to restart the audio service has been made, but some problems may remain.\nQuitting other running applications may improve Rosegarden's performance."));
+
+ } else if ((*i)->getData1() == MappedEvent::FailureCPUOverload) {
+
+#define REPORT_CPU_OVERLOAD 1
+#ifdef REPORT_CPU_OVERLOAD
+
+ stopping();
+
+ KMessageBox::error(
+ dynamic_cast<QWidget*>(m_doc->parent())->parentWidget(),
+ i18n("Run out of processor power for real-time audio processing. Cannot continue."));
+
+#endif
+
+ } else {
+
+ handling = false;
+ }
+
+ if (handling)
+ continue;
+
+ if (!m_canReport) {
+ SEQMAN_DEBUG << "Not reporting it to user just yet"
+ << endl;
+ continue;
+ }
+
+ if ((*i)->getData1() == MappedEvent::FailureALSACallFailed) {
+
+ struct timeval tv;
+ (void)gettimeofday(&tv, 0);
+
+ if (tv.tv_sec - warningShownAt >= 5 &&
+ !boolShowingALSAWarning) {
+
+ QString message = i18n("A serious error has occurred in the ALSA MIDI subsystem. It may not be possible to continue sequencing. Please check console output for more information.");
+ boolShowingALSAWarning = true;
+
+ KMessageBox::information(0, message);
+ boolShowingALSAWarning = false;
+
+ (void)gettimeofday(&tv, 0);
+ warningShownAt = tv.tv_sec;
+ }
+
+ } else if ((*i)->getData1() == MappedEvent::FailureXRuns) {
+
+ //#define REPORT_XRUNS 1
+#ifdef REPORT_XRUNS
+
+ struct timeval tv;
+ (void)gettimeofday(&tv, 0);
+
+ if (tv.tv_sec - warningShownAt >= 5 &&
+ !boolShowingWarning) {
+
+ QString message = i18n("JACK Audio subsystem is losing sample frames.");
+ boolShowingWarning = true;
+
+ KMessageBox::information(0, message);
+ boolShowingWarning = false;
+
+ (void)gettimeofday(&tv, 0);
+ warningShownAt = tv.tv_sec;
+ }
+#endif
+
+ } else if (!m_shownOverrunWarning) {
+
+ QString message;
+
+ switch ((*i)->getData1()) {
+
+ case MappedEvent::FailureDiscUnderrun:
+ message = i18n("Failed to read audio data from disc in time to service the audio subsystem.");
+ break;
+
+ case MappedEvent::FailureDiscOverrun:
+ message = i18n("Failed to write audio data to disc fast enough to service the audio subsystem.");
+ break;
+
+ case MappedEvent::FailureBussMixUnderrun:
+ message = i18n("The audio mixing subsystem is failing to keep up.");
+ break;
+
+ case MappedEvent::FailureMixUnderrun:
+ message = i18n("The audio subsystem is failing to keep up.");
+ break;
+
+ default:
+ message = i18n("Unknown sequencer failure mode!");
+ break;
+ }
+
+ m_shownOverrunWarning = true;
+
+#ifdef REPORT_XRUNS
+
+ KMessageBox::information(0, message);
+#else
+
+ if ((*i)->getData1() == MappedEvent::FailureDiscOverrun) {
+ // the error you can't hear
+ KMessageBox::information(0, message);
+ } else {
+ std::cerr << message << std::endl;
+ }
+#endif
+
+ }
+
+ // Turn off the report flag and set off a one-shot
+ // timer for 5 seconds.
+ //
+ if (!m_reportTimer->isActive()) {
+ m_canReport = false;
+ m_reportTimer->start(5000, true);
+ }
+ }
+ } else {
+ KStartupLogo::hideIfStillThere();
+
+ if ((*i)->getType() == MappedEvent::SystemFailure) {
+
+ if ((*i)->getData1() == MappedEvent::FailureJackRestartFailed) {
+
+ KMessageBox::error(
+ dynamic_cast<QWidget*>(m_doc->parent()),
+ i18n("The JACK Audio subsystem has failed or it has stopped Rosegarden from processing audio.\nPlease restart Rosegarden to continue working with audio.\nQuitting other running applications may improve Rosegarden's performance."));
+
+ } else if ((*i)->getData1() == MappedEvent::FailureJackRestart) {
+
+ KMessageBox::error(
+ dynamic_cast<QWidget*>(m_doc->parent()),
+ i18n("The JACK Audio subsystem has stopped Rosegarden from processing audio, probably because of a processing overload.\nAn attempt to restart the audio service has been made, but some problems may remain.\nQuitting other running applications may improve Rosegarden's performance."));
+
+ } else if ((*i)->getData1() == MappedEvent::WarningImpreciseTimer &&
+ shouldWarnForImpreciseTimer()) {
+
+ std::cerr << "Rosegarden: WARNING: No accurate sequencer timer available" << std::endl;
+
+ KStartupLogo::hideIfStillThere();
+ CurrentProgressDialog::freeze();
+
+ RosegardenGUIApp::self()->awaitDialogClearance();
+
+ KMessageBox::information(
+ dynamic_cast<QWidget*>(m_doc->parent()),
+ i18n("<h3>System timer resolution is too low</h3><p>Rosegarden was unable to find a high-resolution timing source for MIDI performance.</p><p>This may mean you are using a Linux system with the kernel timer resolution set too low. Please contact your Linux distributor for more information.</p><p>Some Linux distributors already provide low latency kernels, see <a href=\"http://rosegarden.wiki.sourceforge.net/Low+latency+kernels\">http://rosegarden.wiki.sourceforge.net/Low+latency+kernels</a> for instructions.</p>"),
+ NULL, NULL,
+ KMessageBox::Notify + KMessageBox::AllowLink);
+
+ CurrentProgressDialog::thaw();
+
+ } else if ((*i)->getData1() == MappedEvent::WarningImpreciseTimerTryRTC &&
+ shouldWarnForImpreciseTimer()) {
+
+ std::cerr << "Rosegarden: WARNING: No accurate sequencer timer available" << std::endl;
+
+ KStartupLogo::hideIfStillThere();
+ CurrentProgressDialog::freeze();
+
+ RosegardenGUIApp::self()->awaitDialogClearance();
+
+ KMessageBox::information(
+ dynamic_cast<QWidget*>(m_doc->parent()),
+ i18n("<h3>System timer resolution is too low</h3><p>Rosegarden was unable to find a high-resolution timing source for MIDI performance.</p><p>You may be able to solve this problem by loading the RTC timer kernel module. To do this, try running <b>sudo modprobe snd-rtctimer</b> in a terminal window and then restarting Rosegarden.</p><p>Alternatively, check whether your Linux distributor provides a multimedia-optimized kernel. See <a href=\"http://rosegarden.wiki.sourceforge.net/Low+latency+kernels\">http://rosegarden.wiki.sourceforge.net/Low+latency+kernels</a> for notes about this.</p>"),
+ NULL, NULL,
+ KMessageBox::Notify + KMessageBox::AllowLink);
+
+ CurrentProgressDialog::thaw();
+ }
+ }
+ }
+ }
+ }
+
+ // if we aren't playing or recording, consider invoking any
+ // step-by-step clients (using unfiltered composition). send
+ // out any incoming external controller events
+
+ for (i = mC.begin(); i != mC.end(); ++i ) {
+ if (m_transportStatus == STOPPED ||
+ m_transportStatus == RECORDING_ARMED) {
+ if ((*i)->getType() == MappedEvent::MidiNote) {
+ if ((*i)->getVelocity() == 0) {
+ emit insertableNoteOffReceived((*i)->getPitch(), (*i)->getVelocity());
+ } else {
+ emit insertableNoteOnReceived((*i)->getPitch(), (*i)->getVelocity());
+ }
+ }
+ }
+ if ((*i)->getRecordedDevice() == Device::CONTROL_DEVICE) {
+ SEQMAN_DEBUG << "controllerDeviceEventReceived" << endl;
+ emit controllerDeviceEventReceived(*i);
+ }
+ }
+}
+
+void
+SequenceManager::rewindToBeginning()
+{
+ SEQMAN_DEBUG << "SequenceManager::rewindToBeginning()\n";
+ m_doc->slotSetPointerPosition(m_doc->getComposition().getStartMarker());
+}
+
+void
+SequenceManager::fastForwardToEnd()
+{
+ SEQMAN_DEBUG << "SequenceManager::fastForwardToEnd()\n";
+
+ Composition &comp = m_doc->getComposition();
+ m_doc->slotSetPointerPosition(comp.getDuration());
+}
+
+void
+SequenceManager::setLoop(const timeT &lhs, const timeT &rhs)
+{
+ // do not set a loop if JACK transport sync is enabled, because this is
+ // completely broken, and apparently broken due to a limitation of JACK
+ // transport itself. #1240039 - DMM
+ // KConfig* config = kapp->config();
+ // config->setGroup(SequencerOptionsConfigGroup);
+ // if (config->readBoolEntry("jacktransport", false))
+ // {
+ // //!!! message box should go here to inform user of why the loop was
+ // // not set, but I can't add it at the moment due to to the pre-release
+ // // freeze - DMM
+ // return;
+ // }
+
+ // Let the sequencer know about the loop markers
+ //
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ RealTime loopStart =
+ m_doc->getComposition().getElapsedRealTime(lhs);
+ RealTime loopEnd =
+ m_doc->getComposition().getElapsedRealTime(rhs);
+
+ streamOut << (long)loopStart.sec;
+ streamOut << (long)loopStart.nsec;
+ streamOut << (long)loopEnd.sec;
+ streamOut << (long)loopEnd.nsec;
+
+ rgapp->sequencerSend("setLoop(long int, long int, long int, long int)", data);
+}
+
+void
+SequenceManager::checkSoundDriverStatus(bool warnUser)
+{
+ QByteArray data;
+ QCString replyType;
+ QByteArray replyData;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ streamOut << QString(VERSION);
+
+ if (! rgapp->sequencerCall("getSoundDriverStatus(QString)",
+ replyType, replyData, data)) {
+
+ m_soundDriverStatus = NO_DRIVER;
+
+ } else {
+
+ QDataStream streamIn(replyData, IO_ReadOnly);
+ unsigned int result;
+ streamIn >> result;
+ m_soundDriverStatus = result;
+ }
+
+ SEQMAN_DEBUG << "Sound driver status is: " << m_soundDriverStatus << endl;
+
+ if (!warnUser) return;
+
+#ifdef HAVE_LIBJACK
+ if ((m_soundDriverStatus & (AUDIO_OK | MIDI_OK | VERSION_OK)) ==
+ (AUDIO_OK | MIDI_OK | VERSION_OK)) return;
+#else
+ if ((m_soundDriverStatus & (MIDI_OK | VERSION_OK)) ==
+ (MIDI_OK | VERSION_OK)) return;
+#endif
+
+ KStartupLogo::hideIfStillThere();
+ CurrentProgressDialog::freeze();
+
+ QString text = "";
+
+ if (m_soundDriverStatus == NO_DRIVER) {
+ text = i18n("<p>Both MIDI and Audio subsystems have failed to initialize.</p><p>You may continue without the sequencer, but we suggest closing Rosegarden, running \"alsaconf\" as root, and starting Rosegarden again. If you wish to run with no sequencer by design, then use \"rosegarden --nosequencer\" to avoid seeing this error in the future.</p>");
+ } else if (!(m_soundDriverStatus & MIDI_OK)) {
+ text = i18n("<p>The MIDI subsystem has failed to initialize.</p><p>You may continue without the sequencer, but we suggest closing Rosegarden, running \"modprobe snd-seq-midi\" as root, and starting Rosegarden again. If you wish to run with no sequencer by design, then use \"rosegarden --nosequencer\" to avoid seeing this error in the future.</p>");
+ } else if (!(m_soundDriverStatus & VERSION_OK)) {
+ text = i18n("<p>The Rosegarden sequencer module version does not match the GUI module version.</p><p>You have probably mixed up files from two different versions of Rosegarden. Please check your installation.</p>");
+ }
+
+ if (text != "") {
+ RosegardenGUIApp::self()->awaitDialogClearance();
+ KMessageBox::error(RosegardenGUIApp::self(),
+ i18n("<h3>Sequencer startup failed</h3>%1").arg(text));
+ CurrentProgressDialog::thaw();
+ return;
+ }
+
+#ifdef HAVE_LIBJACK
+ if (!(m_soundDriverStatus & AUDIO_OK)) {
+ RosegardenGUIApp::self()->awaitDialogClearance();
+ KMessageBox::information(RosegardenGUIApp::self(), i18n("<h3>Failed to connect to JACK audio server.</h3><p>Rosegarden could not connect to the JACK audio server. This probably means the JACK server is not running.</p><p>If you want to be able to play or record audio files or use plugins, you should exit Rosegarden and start the JACK server before running Rosegarden again.</p>"),
+ i18n("Failed to connect to JACK"),
+ "startup-jack-failed");
+ }
+#endif
+ CurrentProgressDialog::thaw();
+}
+
+void
+SequenceManager::preparePlayback(bool forceProgramChanges)
+{
+ Studio &studio = m_doc->getStudio();
+ InstrumentList list = studio.getAllInstruments();
+ MappedComposition mC;
+ MappedEvent *mE;
+
+ std::set<InstrumentId> activeInstruments;
+
+ Composition &composition = m_doc->getComposition();
+
+ for (Composition::trackcontainer::const_iterator i =
+ composition.getTracks().begin();
+ i != composition.getTracks().end(); ++i) {
+
+ Track *track = i->second;
+ if (track) activeInstruments.insert(track->getInstrument());
+ }
+
+ // Send the MappedInstruments (minimal Instrument information
+ // required for Performance) to the Sequencer
+ //
+ InstrumentList::iterator it = list.begin();
+ for (; it != list.end(); it++) {
+
+ StudioControl::sendMappedInstrument(MappedInstrument(*it));
+
+ // Send program changes for MIDI Instruments
+ //
+ if ((*it)->getType() == Instrument::Midi) {
+
+ if (activeInstruments.find((*it)->getId()) ==
+ activeInstruments.end()) {
+// std::cerr << "SequenceManager::preparePlayback: instrument "
+// << (*it)->getId() << " is not in use" << std::endl;
+ continue;
+ }
+
+ // send bank select always before program change
+ //
+ if ((*it)->sendsBankSelect()) {
+ mE = new MappedEvent((*it)->getId(),
+ MappedEvent::MidiController,
+ MIDI_CONTROLLER_BANK_MSB,
+ (*it)->getMSB());
+ mC.insert(mE);
+
+ mE = new MappedEvent((*it)->getId(),
+ MappedEvent::MidiController,
+ MIDI_CONTROLLER_BANK_LSB,
+ (*it)->getLSB());
+ mC.insert(mE);
+ }
+
+ // send program change
+ //
+ if ((*it)->sendsProgramChange() || forceProgramChanges) {
+ RG_DEBUG << "SequenceManager::preparePlayback() : sending prg change for "
+ << (*it)->getPresentationName().c_str() << endl;
+
+ mE = new MappedEvent((*it)->getId(),
+ MappedEvent::MidiProgramChange,
+ (*it)->getProgramChange());
+ mC.insert(mE);
+ }
+
+ } else if ((*it)->getType() == Instrument::Audio ||
+ (*it)->getType() == Instrument::SoftSynth) {
+ } else {
+ RG_DEBUG << "SequenceManager::preparePlayback - "
+ << "unrecognised instrument type" << endl;
+ }
+
+
+ }
+
+ // Send the MappedComposition if it's got anything in it
+ showVisuals(mC);
+ StudioControl::sendMappedComposition(mC);
+}
+
+void
+SequenceManager::sendAudioLevel(MappedEvent *mE)
+{
+ RosegardenGUIView *v;
+ QList<RosegardenGUIView>& viewList = m_doc->getViewList();
+
+ for (v = viewList.first(); v != 0; v = viewList.next()) {
+ v->showVisuals(mE);
+ }
+
+}
+
+void
+SequenceManager::resetControllers()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetControllers - resetting\n";
+
+ // Should do all Midi Instrument - not just guess like this is doing
+ // currently.
+
+ InstrumentList list = m_doc->getStudio().getPresentationInstruments();
+ InstrumentList::iterator it;
+
+ MappedComposition mC;
+
+ for (it = list.begin(); it != list.end(); it++) {
+ if ((*it)->getType() == Instrument::Midi) {
+ MappedEvent *mE = new MappedEvent((*it)->getId(),
+ MappedEvent::MidiController,
+ MIDI_CONTROLLER_RESET,
+ 0);
+ mC.insert(mE);
+ }
+ }
+
+ StudioControl::sendMappedComposition(mC);
+ //showVisuals(mC);
+}
+
+void
+SequenceManager::resetMidiNetwork()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetMidiNetwork - resetting\n";
+ MappedComposition mC;
+
+ // Should do all Midi Instrument - not just guess like this is doing
+ // currently.
+
+ for (unsigned int i = 0; i < 16; i++) {
+ MappedEvent *mE =
+ new MappedEvent(MidiInstrumentBase + i,
+ MappedEvent::MidiController,
+ MIDI_SYSTEM_RESET,
+ 0);
+
+ mC.insert(mE);
+ }
+ showVisuals(mC);
+ StudioControl::sendMappedComposition(mC);
+}
+
+void
+SequenceManager::sendMIDIRecordingDevice(const QString recordDeviceStr)
+{
+
+ if (recordDeviceStr) {
+ int recordDevice = recordDeviceStr.toInt();
+
+ if (recordDevice >= 0) {
+ MappedEvent mE(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemRecordDevice,
+ MidiByte(recordDevice),
+ MidiByte(true));
+
+ StudioControl::sendMappedEvent(mE);
+ SEQMAN_DEBUG << "set MIDI record device to "
+ << recordDevice << endl;
+ }
+ }
+}
+
+void
+SequenceManager::restoreRecordSubscriptions()
+{
+ KConfig* config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+ //QString recordDeviceStr = config->readEntry("midirecorddevice");
+ QStringList devList = config->readListEntry("midirecorddevice");
+
+ for ( QStringList::ConstIterator it = devList.begin();
+ it != devList.end(); ++it) {
+ sendMIDIRecordingDevice(*it);
+ }
+
+}
+
+void
+SequenceManager::reinitialiseSequencerStudio()
+{
+ KConfig* config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+ //QString recordDeviceStr = config->readEntry("midirecorddevice");
+
+ //sendMIDIRecordingDevice(recordDeviceStr);
+ restoreRecordSubscriptions();
+
+ // Toggle JACK audio ports appropriately
+ //
+ bool submasterOuts = config->readBoolEntry("audiosubmasterouts", false);
+ bool faderOuts = config->readBoolEntry("audiofaderouts", false);
+ unsigned int audioFileFormat = config->readUnsignedNumEntry("audiorecordfileformat", 1);
+
+ MidiByte ports = 0;
+ if (faderOuts) {
+ ports |= MappedEvent::FaderOuts;
+ }
+ if (submasterOuts) {
+ ports |= MappedEvent::SubmasterOuts;
+ }
+ MappedEvent mEports
+ (MidiInstrumentBase,
+ MappedEvent::SystemAudioPorts,
+ ports);
+
+ StudioControl::sendMappedEvent(mEports);
+
+ MappedEvent mEff
+ (MidiInstrumentBase,
+ MappedEvent::SystemAudioFileFormat,
+ audioFileFormat);
+ StudioControl::sendMappedEvent(mEff);
+
+
+ // Set the studio from the current document
+ //
+ m_doc->initialiseStudio();
+}
+
+void
+SequenceManager::panic()
+{
+ SEQMAN_DEBUG << "panic button\n";
+
+ stopping();
+
+ MappedEvent mE(MidiInstrumentBase, MappedEvent::Panic, 0, 0);
+ emit setProgress(40);
+ StudioControl::sendMappedEvent(mE);
+ emit setProgress(100);
+
+ // Studio &studio = m_doc->getStudio();
+ //
+ // InstrumentList list = studio.getPresentationInstruments();
+ // InstrumentList::iterator it;
+ //
+ // int maxDevices = 0, device = 0;
+ // for (it = list.begin(); it != list.end(); it++)
+ // if ((*it)->getType() == Instrument::Midi)
+ // maxDevices++;
+ //
+ // emit setProgress(40);
+ //
+ // for (it = list.begin(); it != list.end(); it++)
+ // {
+ // if ((*it)->getType() == Instrument::Midi)
+ // {
+ // for (unsigned int i = 0; i < 128; i++)
+ // {
+ // MappedEvent
+ // mE((*it)->getId(),
+ // MappedEvent::MidiNote,
+ // i,
+ // 0);
+ //
+ // StudioControl::sendMappedEvent(mE);
+ // }
+ //
+ // device++;
+ // }
+ //
+ // emit setProgress(int(90.0 * (double(device) / double(maxDevices))));
+ // }
+ //
+ // resetControllers();
+}
+
+void
+SequenceManager::showVisuals(const MappedComposition &mC)
+{
+ MappedComposition::const_iterator it = mC.begin();
+ if (it != mC.end())
+ m_transport->setMidiOutLabel(*it);
+}
+
+MappedComposition
+SequenceManager::applyFiltering(const MappedComposition &mC,
+ MappedEvent::MappedEventType filter)
+{
+ MappedComposition retMc;
+ MappedComposition::const_iterator it = mC.begin();
+
+ for (; it != mC.end(); it++) {
+ if (!((*it)->getType() & filter))
+ retMc.insert(new MappedEvent(*it));
+ }
+
+ return retMc;
+}
+
+void SequenceManager::resetCompositionMmapper()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetCompositionMmapper()\n";
+ delete m_compositionMmapper;
+ m_compositionMmapper = new CompositionMmapper(m_doc);
+
+ resetMetronomeMmapper();
+ resetTempoSegmentMmapper();
+ resetTimeSigSegmentMmapper();
+ resetControlBlockMmapper();
+}
+
+void SequenceManager::resetMetronomeMmapper()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetMetronomeMmapper()\n";
+
+ delete m_metronomeMmapper;
+ m_metronomeMmapper = SegmentMmapperFactory::makeMetronome(m_doc);
+}
+
+void SequenceManager::resetTempoSegmentMmapper()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetTempoSegmentMmapper()\n";
+
+ delete m_tempoSegmentMmapper;
+ m_tempoSegmentMmapper = SegmentMmapperFactory::makeTempo(m_doc);
+}
+
+void SequenceManager::resetTimeSigSegmentMmapper()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetTimeSigSegmentMmapper()\n";
+
+ delete m_timeSigSegmentMmapper;
+ m_timeSigSegmentMmapper = SegmentMmapperFactory::makeTimeSig(m_doc);
+}
+
+void SequenceManager::resetControlBlockMmapper()
+{
+ SEQMAN_DEBUG << "SequenceManager::resetControlBlockMmapper()\n";
+
+ m_controlBlockMmapper->setDocument(m_doc);
+}
+
+bool SequenceManager::event(QEvent *e)
+{
+ if (e->type() == QEvent::User) {
+ SEQMAN_DEBUG << "SequenceManager::event() with user event\n";
+ if (m_updateRequested) {
+ SEQMAN_DEBUG << "SequenceManager::event(): update requested\n";
+ checkRefreshStatus();
+ m_updateRequested = false;
+ }
+ return true;
+ } else {
+ return QObject::event(e);
+ }
+}
+
+void SequenceManager::update()
+{
+ SEQMAN_DEBUG << "SequenceManager::update()\n";
+ // schedule a refresh-status check for the next event loop
+ QEvent *e = new QEvent(QEvent::User);
+ m_updateRequested = true;
+ QApplication::postEvent(this, e);
+}
+
+void SequenceManager::checkRefreshStatus()
+{
+ SEQMAN_DEBUG << "SequenceManager::checkRefreshStatus()\n";
+
+ // Look at trigger segments first: if one of those has changed, we'll
+ // need to be aware of it when scanning segments subsequently
+
+ TriggerSegmentRec::SegmentRuntimeIdSet ridset;
+ Composition &comp = m_doc->getComposition();
+ SegmentRefreshMap newTriggerMap;
+
+ for (Composition::triggersegmentcontaineriterator i =
+ comp.getTriggerSegments().begin();
+ i != comp.getTriggerSegments().end(); ++i) {
+
+ Segment *s = (*i)->getSegment();
+
+ if (m_triggerSegments.find(s) == m_triggerSegments.end()) {
+ newTriggerMap[s] = s->getNewRefreshStatusId();
+ } else {
+ newTriggerMap[s] = m_triggerSegments[s];
+ }
+
+ if (s->getRefreshStatus(newTriggerMap[s]).needsRefresh()) {
+ TriggerSegmentRec::SegmentRuntimeIdSet &thisSet = (*i)->getReferences();
+ ridset.insert(thisSet.begin(), thisSet.end());
+ s->getRefreshStatus(newTriggerMap[s]).setNeedsRefresh(false);
+ }
+ }
+
+ m_triggerSegments = newTriggerMap;
+
+ SEQMAN_DEBUG << "SequenceManager::checkRefreshStatus: segments modified by changes to trigger segments are:" << endl;
+ int x = 0;
+ for (TriggerSegmentRec::SegmentRuntimeIdSet::iterator i = ridset.begin();
+ i != ridset.end(); ++i) {
+ SEQMAN_DEBUG << x << ": " << *i << endl;
+ ++x;
+ }
+
+ std::vector<Segment*>::iterator i;
+
+ // Check removed segments first
+ for (i = m_removedSegments.begin(); i != m_removedSegments.end(); ++i) {
+ processRemovedSegment(*i);
+ }
+ m_removedSegments.clear();
+
+ SEQMAN_DEBUG << "SequenceManager::checkRefreshStatus: we have "
+ << m_segments.size() << " segments" << endl;
+
+ // then the ones which are still there
+ for (SegmentRefreshMap::iterator i = m_segments.begin();
+ i != m_segments.end(); ++i) {
+ if (i->first->getRefreshStatus(i->second).needsRefresh() ||
+ ridset.find(i->first->getRuntimeId()) != ridset.end()) {
+ segmentModified(i->first);
+ i->first->getRefreshStatus(i->second).setNeedsRefresh(false);
+ }
+ }
+
+ // then added ones
+ for (i = m_addedSegments.begin(); i != m_addedSegments.end(); ++i) {
+ processAddedSegment(*i);
+ }
+ m_addedSegments.clear();
+}
+
+void SequenceManager::segmentModified(Segment* s)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentModified(" << s << ")\n";
+
+ bool sizeChanged = m_compositionMmapper->segmentModified(s);
+
+ SEQMAN_DEBUG << "SequenceManager::segmentModified() : size changed = "
+ << sizeChanged << endl;
+
+ if ((m_transportStatus == PLAYING) && sizeChanged) {
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ streamOut << (QString)m_compositionMmapper->getSegmentFileName(s);
+ streamOut << (size_t)m_compositionMmapper->getSegmentFileSize(s);
+
+ SEQMAN_DEBUG << "SequenceManager::segmentModified() : DCOP-call sequencer remapSegment"
+ << m_compositionMmapper->getSegmentFileName(s) << endl;
+
+ rgapp->sequencerSend("remapSegment(QString, size_t)", data);
+ }
+}
+
+void SequenceManager::segmentAdded(const Composition*, Segment* s)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentAdded(" << s << ")\n";
+ m_addedSegments.push_back(s);
+}
+
+void SequenceManager::segmentRemoved(const Composition*, Segment* s)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentRemoved(" << s << ")\n";
+ m_removedSegments.push_back(s);
+ std::vector<Segment*>::iterator i = find(m_addedSegments.begin(), m_addedSegments.end(), s);
+ if (i != m_addedSegments.end())
+ m_addedSegments.erase(i);
+}
+
+void SequenceManager::segmentRepeatChanged(const Composition*, Segment* s, bool repeat)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentRepeatChanged(" << s << ", " << repeat << ")\n";
+ segmentModified(s);
+}
+
+void SequenceManager::segmentRepeatEndChanged(const Composition*, Segment* s, timeT newEndTime)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentRepeatEndChanged(" << s << ", " << newEndTime << ")\n";
+ segmentModified(s);
+}
+
+void SequenceManager::segmentEventsTimingChanged(const Composition*, Segment * s, timeT t, RealTime)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentEventsTimingChanged(" << s << ", " << t << ")\n";
+ segmentModified(s);
+ if (s && s->getType() == Segment::Audio && m_transportStatus == PLAYING) {
+ QByteArray data;
+ rgapp->sequencerSend("remapTracks()", data);
+ }
+}
+
+void SequenceManager::segmentTransposeChanged(const Composition*, Segment *s, int transpose)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentTransposeChanged(" << s << ", " << transpose << ")\n";
+ segmentModified(s);
+}
+
+void SequenceManager::segmentTrackChanged(const Composition*, Segment *s, TrackId id)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentTrackChanged(" << s << ", " << id << ")\n";
+ segmentModified(s);
+ if (s && s->getType() == Segment::Audio && m_transportStatus == PLAYING) {
+ QByteArray data;
+ rgapp->sequencerSend("remapTracks()", data);
+ }
+}
+
+void SequenceManager::segmentEndMarkerChanged(const Composition*, Segment *s, bool)
+{
+ SEQMAN_DEBUG << "SequenceManager::segmentEndMarkerChanged(" << s << ")\n";
+ segmentModified(s);
+}
+
+void SequenceManager::processAddedSegment(Segment* s)
+{
+ SEQMAN_DEBUG << "SequenceManager::processAddedSegment(" << s << ")\n";
+
+ m_compositionMmapper->segmentAdded(s);
+
+ if (m_transportStatus == PLAYING) {
+
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ streamOut << m_compositionMmapper->getSegmentFileName(s);
+
+ if (!rgapp->sequencerSend("addSegment(QString)", data)) {
+ m_transportStatus = STOPPED;
+ }
+ }
+
+ // Add to segments map
+ int id = s->getNewRefreshStatusId();
+ m_segments.insert(SegmentRefreshMap::value_type(s, id));
+
+}
+
+void SequenceManager::processRemovedSegment(Segment* s)
+{
+ SEQMAN_DEBUG << "SequenceManager::processRemovedSegment(" << s << ")\n";
+
+ QString filename = m_compositionMmapper->getSegmentFileName(s);
+ m_compositionMmapper->segmentDeleted(s);
+
+ if (m_transportStatus == PLAYING) {
+
+ QByteArray data;
+ QDataStream streamOut(data, IO_WriteOnly);
+
+ streamOut << filename;
+
+ if (!rgapp->sequencerSend("deleteSegment(QString)", data)) {
+ // failed
+ m_transportStatus = STOPPED;
+ }
+ }
+
+ // Remove from segments map
+ m_segments.erase(s);
+}
+
+void SequenceManager::endMarkerTimeChanged(const Composition *, bool /*shorten*/)
+{
+ SEQMAN_DEBUG << "SequenceManager::endMarkerTimeChanged()\n";
+ m_compositionMmapperResetTimer->start(500, true); // schedule a composition mmapper reset in 0.5s
+}
+
+void SequenceManager::timeSignatureChanged(const Composition *)
+{
+ resetMetronomeMmapper();
+}
+
+void SequenceManager::trackChanged(const Composition *, Track* t)
+{
+ SEQMAN_DEBUG << "SequenceManager::trackChanged(" << t << ", " << (t ? t->getPosition() : -1) << ")\n";
+ m_controlBlockMmapper->updateTrackData(t);
+
+ if (m_transportStatus == PLAYING) {
+ QByteArray data;
+ rgapp->sequencerSend("remapTracks()", data);
+ }
+}
+
+void SequenceManager::trackDeleted(const Composition *, TrackId t)
+{
+ m_controlBlockMmapper->setTrackDeleted(t);
+}
+
+void SequenceManager::metronomeChanged(InstrumentId id,
+ bool regenerateTicks)
+{
+ // This method is called when the user has changed the
+ // metronome instrument, pitch etc
+
+ SEQMAN_DEBUG << "SequenceManager::metronomeChanged (simple)"
+ << ", instrument = "
+ << id
+ << endl;
+
+ if (regenerateTicks)
+ resetMetronomeMmapper();
+
+ m_controlBlockMmapper->updateMetronomeData(id);
+ if (m_transportStatus == PLAYING) {
+ m_controlBlockMmapper->updateMetronomeForPlayback();
+ } else {
+ m_controlBlockMmapper->updateMetronomeForRecord();
+ }
+
+ m_metronomeMmapper->refresh();
+ m_timeSigSegmentMmapper->refresh();
+ m_tempoSegmentMmapper->refresh();
+}
+
+void SequenceManager::metronomeChanged(const Composition *)
+{
+ // This method is called when the muting status in the composition
+ // has changed -- the metronome itself has not actually changed
+
+ SEQMAN_DEBUG << "SequenceManager::metronomeChanged "
+ << ", instrument = "
+ << m_metronomeMmapper->getMetronomeInstrument()
+ << endl;
+
+ m_controlBlockMmapper->updateMetronomeData
+ (m_metronomeMmapper->getMetronomeInstrument());
+
+ if (m_transportStatus == PLAYING) {
+ m_controlBlockMmapper->updateMetronomeForPlayback();
+ } else {
+ m_controlBlockMmapper->updateMetronomeForRecord();
+ }
+}
+
+void SequenceManager::filtersChanged(MidiFilter thruFilter,
+ MidiFilter recordFilter)
+{
+ m_controlBlockMmapper->updateMidiFilters(thruFilter, recordFilter);
+}
+
+void SequenceManager::soloChanged(const Composition *, bool solo, TrackId selectedTrack)
+{
+ if (m_controlBlockMmapper->updateSoloData(solo, selectedTrack)) {
+ if (m_transportStatus == PLAYING) {
+ QByteArray data;
+ rgapp->sequencerSend("remapTracks()", data);
+ }
+ }
+}
+
+void SequenceManager::tempoChanged(const Composition *c)
+{
+ SEQMAN_DEBUG << "SequenceManager::tempoChanged()\n";
+
+ // Refresh all segments
+ //
+ for (SegmentRefreshMap::iterator i = m_segments.begin();
+ i != m_segments.end(); ++i) {
+ segmentModified(i->first);
+ }
+
+ // and metronome, time sig and tempo
+ //
+ m_metronomeMmapper->refresh();
+ m_timeSigSegmentMmapper->refresh();
+ m_tempoSegmentMmapper->refresh();
+
+ if (c->isLooping())
+ setLoop(c->getLoopStart(), c->getLoopEnd());
+ else if (m_transportStatus == PLAYING) {
+ // If the tempo changes during playback, reset the pointer
+ // position because the sequencer keeps track of position in
+ // real time and we want to maintain the same position in
+ // musical time. Turn off play tracking while this happens,
+ // so that we don't jump about in the main window while the
+ // user's trying to drag the tempo in it. (That doesn't help
+ // for matrix or notation though, sadly)
+ bool tracking = RosegardenGUIApp::self()->isTrackEditorPlayTracking();
+ if (tracking)
+ RosegardenGUIApp::self()->slotToggleTracking();
+ m_doc->slotSetPointerPosition(c->getPosition());
+ if (tracking)
+ RosegardenGUIApp::self()->slotToggleTracking();
+ }
+}
+
+void
+SequenceManager::sendTransportControlStatuses()
+{
+ KConfig* config = kapp->config();
+ config->setGroup(SequencerOptionsConfigGroup);
+
+ // Get the config values
+ //
+ bool jackTransport = config->readBoolEntry("jacktransport", false);
+ bool jackMaster = config->readBoolEntry("jackmaster", false);
+
+ int mmcMode = config->readNumEntry("mmcmode", 0);
+ int mtcMode = config->readNumEntry("mtcmode", 0);
+
+ int midiClock = config->readNumEntry("midiclock", 0);
+ bool midiSyncAuto = config->readBoolEntry("midisyncautoconnect", false);
+
+ // Send JACK transport
+ //
+ int jackValue = 0;
+ if (jackTransport && jackMaster)
+ jackValue = 2;
+ else {
+ if (jackTransport)
+ jackValue = 1;
+ else
+ jackValue = 0;
+ }
+
+ MappedEvent mEjackValue(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemJackTransport,
+ MidiByte(jackValue));
+ StudioControl::sendMappedEvent(mEjackValue);
+
+
+ // Send MMC transport
+ //
+ MappedEvent mEmmcValue(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemMMCTransport,
+ MidiByte(mmcMode));
+
+ StudioControl::sendMappedEvent(mEmmcValue);
+
+
+ // Send MTC transport
+ //
+ MappedEvent mEmtcValue(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemMTCTransport,
+ MidiByte(mtcMode));
+
+ StudioControl::sendMappedEvent(mEmtcValue);
+
+
+ // Send MIDI Clock
+ //
+ MappedEvent mEmidiClock(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemMIDIClock,
+ MidiByte(midiClock));
+
+ StudioControl::sendMappedEvent(mEmidiClock);
+
+
+ // Send MIDI Sync Auto-Connect
+ //
+ MappedEvent mEmidiSyncAuto(MidiInstrumentBase, // InstrumentId
+ MappedEvent::SystemMIDISyncAuto,
+ MidiByte(midiSyncAuto ? 1 : 0));
+
+ StudioControl::sendMappedEvent(mEmidiSyncAuto);
+
+}
+
+void
+SequenceManager::slotCountdownTimerTimeout()
+{
+ // Set the elapsed time in seconds
+ //
+ m_countdownDialog->setElapsedTime(m_recordTime->elapsed() / 1000);
+}
+
+void
+SequenceManager::slotFoundMountPoint(const QString&,
+ unsigned long kBSize,
+ unsigned long /*kBUsed*/,
+ unsigned long kBAvail)
+{
+ m_gotDiskSpaceResult = true;
+ m_diskSpaceKBAvail = kBAvail;
+}
+
+void
+SequenceManager::enableMIDIThruRouting(bool state)
+{
+ m_controlBlockMmapper->enableMIDIThruRouting(state);
+}
+
+int
+SequenceManager::getSampleRate()
+{
+ if (m_sampleRate != 0) return m_sampleRate;
+
+ QCString replyType;
+ QByteArray replyData;
+ if (rgapp->sequencerCall("getSampleRate()", replyType, replyData)) {
+ QDataStream streamIn(replyData, IO_ReadOnly);
+ unsigned int result;
+ streamIn >> m_sampleRate;
+ }
+
+ return m_sampleRate;
+}
+
+bool
+SequenceManager::shouldWarnForImpreciseTimer()
+{
+ kapp->config()->setGroup(SequencerOptionsConfigGroup);
+ QString timer = kapp->config()->readEntry("timer");
+ if (timer == "(auto)" || timer == "") return true;
+ else return false; // if the user has chosen the timer, leave them alone
+}
+
+}
+#include "SequenceManager.moc"
diff --git a/src/gui/seqmanager/SequenceManager.h b/src/gui/seqmanager/SequenceManager.h
new file mode 100644
index 0000000..792ec01
--- /dev/null
+++ b/src/gui/seqmanager/SequenceManager.h
@@ -0,0 +1,322 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_SEQUENCEMANAGER_H_
+#define _RG_SEQUENCEMANAGER_H_
+
+#include "base/Composition.h"
+#include "base/Event.h"
+#include "base/MidiProgram.h"
+#include "base/RealTime.h"
+#include "base/Track.h"
+#include "gui/application/RosegardenDCOP.h"
+#include "sound/MappedComposition.h"
+#include "sound/MappedEvent.h"
+#include <qobject.h>
+#include <qstring.h>
+#include <vector>
+#include <map>
+
+
+class QTimer;
+class QTime;
+class QEvent;
+
+
+namespace Rosegarden
+{
+
+class TransportDialog;
+class Track;
+class TimeSigSegmentMmapper;
+class TempoSegmentMmapper;
+class SequencerMapper;
+class Segment;
+class RosegardenGUIDoc;
+class MetronomeMmapper;
+class CountdownDialog;
+class ControlBlockMmapper;
+class CompositionMmapper;
+class Composition;
+class AudioManagerDialog;
+
+
+class SequenceManager : public QObject, public CompositionObserver
+{
+ Q_OBJECT
+public:
+ SequenceManager(RosegardenGUIDoc *doc,
+ TransportDialog *transport);
+ ~SequenceManager();
+
+ /**
+ * Replaces the internal document
+ */
+ void setDocument(RosegardenGUIDoc*);
+
+ /**
+ * Return the current internal document
+ */
+ RosegardenGUIDoc* getDocument();
+
+ //
+ // Transport controls
+ //
+
+ /// returns true if the call actually paused playback
+ bool play();
+
+ // We don't call stop() directly - using stopping() and then
+ // call stop().
+ //
+ void stop();
+
+ void stopping();
+ void rewind();
+ void fastforward();
+ void record(bool countIn);
+ void rewindToBeginning();
+ void fastForwardToEnd();
+
+ void setLoop(const timeT &lhs, const timeT &rhs);
+ void notifySequencerStatus(TransportStatus status);
+ void sendSequencerJump(const RealTime &time);
+
+ // Events coming in
+ void processAsynchronousMidi(const MappedComposition &mC,
+ AudioManagerDialog *aMD);
+
+ // Before playing and recording. If warnUser is true, show the
+ // user a warning dialog if there is a problem with the setup.
+ //
+ void checkSoundDriverStatus(bool warnUser);
+
+ /**
+ * Send program changes and align Instrument lists before playback
+ * starts.
+ * Also called at document loading (with arg set to true) to reset all instruments
+ * (fix for bug 820174)
+ *
+ * @arg forceProgramChanges if true, always send program changes even if the instrument is
+ * set not to send any.
+ */
+ void preparePlayback(bool forceProgramChanges = false);
+
+ /// Check and set sequencer status
+ void setTransportStatus(const TransportStatus &status);
+ TransportStatus getTransportStatus() const { return m_transportStatus; }
+
+ /**
+ * Suspend the sequencer to allow for a safe DCOP call() i.e. one
+ * when we don't hang both clients 'cos they're blocking on each
+ * other.
+ */
+ void suspendSequencer(bool value);
+
+ /// Send the audio level to VU meters
+ void sendAudioLevel(MappedEvent *mE);
+
+ /// Find what has been initialised and what hasn't
+ unsigned int getSoundDriverStatus() { return m_soundDriverStatus; }
+
+ /// Reset MIDI controllers
+ void resetControllers();
+
+ /// Reset MIDI network
+ void resetMidiNetwork();
+
+ /// Reinitialise the studio
+ void reinitialiseSequencerStudio();
+
+ /// Send JACK and MMC transport control statuses
+ void sendTransportControlStatuses();
+
+ /// Send all note offs and resets to MIDI devices
+ void panic();
+
+ /// Send an MC to the view
+ void showVisuals(const MappedComposition &mC);
+
+ /// Apply in-situ filtering to a MappedComposition
+ MappedComposition
+ applyFiltering(const MappedComposition &mC,
+ MappedEvent::MappedEventType filter);
+
+ CountdownDialog* getCountdownDialog() { return m_countdownDialog; }
+
+
+ //
+ // CompositionObserver interface
+ //
+ virtual void segmentAdded (const Composition*, Segment*);
+ virtual void segmentRemoved (const Composition*, Segment*);
+ virtual void segmentRepeatChanged (const Composition*, Segment*, bool);
+ virtual void segmentRepeatEndChanged (const Composition*, Segment*, timeT);
+ virtual void segmentEventsTimingChanged(const Composition*, Segment *, timeT delay, RealTime rtDelay);
+ virtual void segmentTransposeChanged (const Composition*, Segment *, int transpose);
+ virtual void segmentTrackChanged (const Composition*, Segment *, TrackId id);
+ virtual void segmentEndMarkerChanged (const Composition*, Segment *, bool);
+ virtual void endMarkerTimeChanged (const Composition*, bool shorten);
+ virtual void trackChanged (const Composition*, Track*);
+ virtual void trackDeleted (const Composition*, TrackId);
+ virtual void timeSignatureChanged (const Composition*);
+ virtual void metronomeChanged (const Composition*);
+ virtual void soloChanged (const Composition*, bool solo, TrackId selectedTrack);
+ virtual void tempoChanged (const Composition*);
+
+ void processAddedSegment(Segment*);
+ void processRemovedSegment(Segment*);
+ void segmentModified(Segment*);
+
+ virtual bool event(QEvent *e);
+
+ /// for the gui to call to indicate that the metronome needs to be remapped
+ void metronomeChanged(InstrumentId id, bool regenerateTicks);
+
+ /// for the gui to call to indicate that a MIDI filter needs to be remapped
+ void filtersChanged(MidiFilter thruFilter,
+ MidiFilter recordFilter);
+
+ /// Return the current sequencer memory mapped file
+ SequencerMapper* getSequencerMapper() { return m_sequencerMapper; }
+
+ /// Ensure that the sequencer file is mapped
+ void mapSequencer();
+
+ void setTransport(TransportDialog* t) { m_transport = t; }
+
+ void enableMIDIThruRouting(bool state);
+
+ int getSampleRate(); // may return 0 if sequencer uncontactable
+
+public slots:
+
+ void update();
+
+signals:
+ void setProgress(int);
+ void incrementProgress(int);
+
+ void insertableNoteOnReceived(int pitch, int velocity);
+ void insertableNoteOffReceived(int pitch, int velocity);
+ void controllerDeviceEventReceived(MappedEvent *ev);
+
+protected slots:
+ void slotCountdownTimerTimeout();
+
+ // Activated by timer to allow a message to be reported to
+ // the user - we use this mechanism so that the user isn't
+ // bombarded with dialogs in the event of lots of failures.
+ //
+ void slotAllowReport() { m_canReport = true; }
+
+ void slotFoundMountPoint(const QString&,
+ unsigned long kBSize,
+ unsigned long kBUsed,
+ unsigned long kBAvail);
+
+ void slotScheduledCompositionMmapperReset() { resetCompositionMmapper(); }
+
+protected:
+
+ void resetCompositionMmapper();
+ void resetControlBlockMmapper();
+ void resetMetronomeMmapper();
+ void resetTempoSegmentMmapper();
+ void resetTimeSigSegmentMmapper();
+ void checkRefreshStatus();
+ void sendMIDIRecordingDevice(const QString recordDeviceStr);
+ void restoreRecordSubscriptions();
+ bool shouldWarnForImpreciseTimer();
+
+ //--------------- Data members ---------------------------------
+
+ MappedComposition m_mC;
+ RosegardenGUIDoc *m_doc;
+ CompositionMmapper *m_compositionMmapper;
+ ControlBlockMmapper *m_controlBlockMmapper;
+ MetronomeMmapper *m_metronomeMmapper;
+ TempoSegmentMmapper *m_tempoSegmentMmapper;
+ TimeSigSegmentMmapper *m_timeSigSegmentMmapper;
+
+ std::vector<Segment*> m_addedSegments;
+ std::vector<Segment*> m_removedSegments;
+ bool m_metronomeNeedsRefresh;
+
+ // statuses
+ TransportStatus m_transportStatus;
+ unsigned int m_soundDriverStatus;
+
+ // pointer to the transport dialog
+ TransportDialog *m_transport;
+
+ clock_t m_lastRewoundAt;
+
+ CountdownDialog *m_countdownDialog;
+ QTimer *m_countdownTimer;
+
+ bool m_shownOverrunWarning;
+
+ // Keep a track of elapsed record time with this object
+ //
+ QTime *m_recordTime;
+
+ typedef std::map<Segment *, int> SegmentRefreshMap;
+ SegmentRefreshMap m_segments; // map to refresh status id
+ SegmentRefreshMap m_triggerSegments;
+ unsigned int m_compositionRefreshStatusId;
+ bool m_updateRequested;
+
+ // used to schedule a composition mmapper reset when the composition end time marker changes
+ // this can be caused by a window resize, and since the reset is potentially expensive we want to collapse
+ // several following requests into one.
+ QTimer *m_compositionMmapperResetTimer;
+
+ // Information that the sequencer is providing to us - for the moment
+ // it's only the position pointer.
+ //
+ SequencerMapper *m_sequencerMapper;
+
+ // Just to make sure we don't bother the user too often
+ //
+ QTimer *m_reportTimer;
+ bool m_canReport;
+
+ bool m_gotDiskSpaceResult;
+ unsigned long m_diskSpaceKBAvail;
+
+ bool m_lastLowLatencySwitchSent;
+
+ timeT m_lastTransportStartPosition;
+
+ int m_sampleRate;
+};
+
+
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/SequencerMapper.cpp b/src/gui/seqmanager/SequencerMapper.cpp
new file mode 100644
index 0000000..5d8acf3
--- /dev/null
+++ b/src/gui/seqmanager/SequencerMapper.cpp
@@ -0,0 +1,105 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "SequencerMapper.h"
+
+#include "misc/Debug.h"
+#include "base/Exception.h"
+#include "base/MidiProgram.h"
+#include "base/RealTime.h"
+#include "base/Track.h"
+#include "sound/MappedComposition.h"
+#include "sound/MappedEvent.h"
+#include "sound/SequencerDataBlock.h"
+#include <qfileinfo.h>
+#include <qstring.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <sys/mman.h>
+#include <errno.h>
+
+
+namespace Rosegarden
+{
+
+SequencerMapper::SequencerMapper(const QString filename)
+ : m_fd( -1),
+ m_mmappedSize(0),
+ m_mmappedBuffer((void *)0),
+ m_filename(filename)
+{
+ RG_DEBUG << "SequencerMapper::SequencerMapper - mmapping " << filename << endl;
+ map();
+}
+
+SequencerMapper::~SequencerMapper()
+{
+ unmap();
+}
+
+void
+SequencerMapper::map()
+{
+ QFileInfo fInfo(m_filename);
+ if (!fInfo.exists()) {
+ RG_DEBUG << "SequencerMapper::map() : file " << m_filename << " doesn't exist\n";
+ throw Exception("file not found");
+ }
+
+ m_fd = ::open(m_filename.latin1(), O_RDWR);
+
+ if (m_fd < 0) {
+ RG_DEBUG << "SequencerMapper::map() : Couldn't open " << m_filename
+ << endl;
+ throw Exception("Couldn't open " + std::string(m_filename.data()));
+ }
+
+ m_mmappedSize = sizeof(SequencerDataBlock);
+ m_mmappedBuffer = (long*)::mmap(0, m_mmappedSize, PROT_READ, MAP_SHARED, m_fd, 0);
+
+ if (m_mmappedBuffer == (void*) - 1) {
+
+ RG_DEBUG << QString("mmap failed : (%1) %2\n").
+ arg(errno).arg(strerror(errno));
+
+ throw Exception("mmap failed");
+ }
+
+ RG_DEBUG << "SequencerMapper::map() : "
+ << (void*)m_mmappedBuffer << "," << m_mmappedSize << endl;
+
+ m_sequencerDataBlock = new (m_mmappedBuffer)
+ SequencerDataBlock(false);
+}
+
+void
+SequencerMapper::unmap()
+{
+ ::munmap(m_mmappedBuffer, m_mmappedSize);
+ ::close(m_fd);
+}
+
+}
diff --git a/src/gui/seqmanager/SequencerMapper.h b/src/gui/seqmanager/SequencerMapper.h
new file mode 100644
index 0000000..59d217f
--- /dev/null
+++ b/src/gui/seqmanager/SequencerMapper.h
@@ -0,0 +1,113 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_SEQUENCERMAPPER_H_
+#define _RG_SEQUENCERMAPPER_H_
+
+#include "base/MidiProgram.h"
+#include "base/RealTime.h"
+#include "base/Track.h"
+#include "sound/SequencerDataBlock.h"
+#include <qstring.h>
+
+
+class LevelInfo;
+
+
+namespace Rosegarden
+{
+
+class MappedEvent;
+class MappedComposition;
+
+
+class SequencerMapper
+{
+public:
+ SequencerMapper(const QString filename);
+ ~SequencerMapper();
+
+ RealTime getPositionPointer() const {
+ return m_sequencerDataBlock->getPositionPointer();
+ }
+
+ bool getVisual(MappedEvent &ev) const {
+ return m_sequencerDataBlock->getVisual(ev);
+ }
+
+ int getRecordedEvents(MappedComposition &mC) const {
+ return m_sequencerDataBlock->getRecordedEvents(mC);
+ }
+
+ bool getTrackLevel(TrackId track,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getTrackLevel(track, info);
+ }
+
+ bool getInstrumentLevel(InstrumentId id,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getInstrumentLevel(id, info);
+ }
+
+ bool getInstrumentLevelForMixer(InstrumentId id,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getInstrumentLevelForMixer(id, info);
+ }
+
+ bool getInstrumentRecordLevel(InstrumentId id,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getInstrumentRecordLevel(id, info);
+ }
+
+ bool getInstrumentRecordLevelForMixer(InstrumentId id,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getInstrumentRecordLevelForMixer(id, info);
+ }
+
+ bool getSubmasterLevel(int submaster,
+ LevelInfo &info) const {
+ return m_sequencerDataBlock->getSubmasterLevel(submaster, info);
+ }
+
+ bool getMasterLevel(LevelInfo &info) const {
+ return m_sequencerDataBlock->getMasterLevel(info);
+ }
+
+protected:
+ void map();
+ void unmap();
+
+ int m_fd;
+ size_t m_mmappedSize;
+ void* m_mmappedBuffer;
+ QString m_filename;
+ SequencerDataBlock *m_sequencerDataBlock;
+};
+
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/SpecialSegmentMmapper.cpp b/src/gui/seqmanager/SpecialSegmentMmapper.cpp
new file mode 100644
index 0000000..5926f11
--- /dev/null
+++ b/src/gui/seqmanager/SpecialSegmentMmapper.cpp
@@ -0,0 +1,56 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "SpecialSegmentMmapper.h"
+
+#include <kstddirs.h>
+#include "base/Event.h"
+#include "base/Segment.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "SegmentMmapper.h"
+#include <kglobal.h>
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+SpecialSegmentMmapper::SpecialSegmentMmapper(RosegardenGUIDoc* doc,
+ QString baseFileName)
+ : SegmentMmapper(doc, 0, createFileName(baseFileName))
+{}
+
+QString SpecialSegmentMmapper::createFileName(QString baseFileName)
+{
+ return KGlobal::dirs()->resourceDirs("tmp").last() + "/" + baseFileName;
+}
+
+unsigned int SpecialSegmentMmapper::getSegmentRepeatCount()
+{
+ return 1;
+}
+
+}
diff --git a/src/gui/seqmanager/SpecialSegmentMmapper.h b/src/gui/seqmanager/SpecialSegmentMmapper.h
new file mode 100644
index 0000000..e16c7b5
--- /dev/null
+++ b/src/gui/seqmanager/SpecialSegmentMmapper.h
@@ -0,0 +1,59 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_SPECIALSEGMENTMMAPPER_H_
+#define _RG_SPECIALSEGMENTMMAPPER_H_
+
+#include "SegmentMmapper.h"
+#include <qstring.h>
+
+
+
+
+namespace Rosegarden
+{
+
+class RosegardenGUIDoc;
+
+
+class SpecialSegmentMmapper : public SegmentMmapper
+{
+public:
+ // overrides from SegmentMmapper
+ virtual unsigned int getSegmentRepeatCount();
+
+protected:
+ SpecialSegmentMmapper(RosegardenGUIDoc* doc,
+ QString baseFileName);
+
+ QString createFileName(QString baseFileName);
+};
+
+//----------------------------------------
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/TempoSegmentMmapper.cpp b/src/gui/seqmanager/TempoSegmentMmapper.cpp
new file mode 100644
index 0000000..1c53922
--- /dev/null
+++ b/src/gui/seqmanager/TempoSegmentMmapper.cpp
@@ -0,0 +1,77 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "TempoSegmentMmapper.h"
+
+#include "base/Event.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "SegmentMmapper.h"
+#include "sound/MappedEvent.h"
+#include "SpecialSegmentMmapper.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+void TempoSegmentMmapper::dump()
+{
+ RealTime eventTime;
+
+ Composition& comp = m_doc->getComposition();
+ MappedEvent* bufPos = m_mmappedEventBuffer;
+
+ for (int i = 0; i < comp.getTempoChangeCount(); ++i) {
+
+ std::pair<timeT, tempoT> tempoChange = comp.getTempoChange(i);
+
+ eventTime = comp.getElapsedRealTime(tempoChange.first);
+ MappedEvent* mappedEvent = new (bufPos) MappedEvent();
+ mappedEvent->setType(MappedEvent::Tempo);
+ mappedEvent->setEventTime(eventTime);
+
+ // Nasty hack -- we use the instrument ID to pass through the
+ // raw tempo value, as it has the appropriate range (unlike
+ // e.g. tempo1 + tempo2). These events are not actually used
+ // on the sequencer side yet, so this may change to something
+ // nicer at some point.
+ mappedEvent->setInstrument(tempoChange.second);
+
+ ++bufPos;
+ }
+
+ // Store the number of events at the start of the shared memory region
+ *(size_t *)m_mmappedRegion = (bufPos - m_mmappedEventBuffer);
+}
+
+size_t TempoSegmentMmapper::computeMmappedSize()
+{
+ return m_doc->getComposition().getTempoChangeCount() * sizeof(MappedEvent);
+}
+
+}
diff --git a/src/gui/seqmanager/TempoSegmentMmapper.h b/src/gui/seqmanager/TempoSegmentMmapper.h
new file mode 100644
index 0000000..08c8ebf
--- /dev/null
+++ b/src/gui/seqmanager/TempoSegmentMmapper.h
@@ -0,0 +1,60 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_TEMPOSEGMENTMMAPPER_H_
+#define _RG_TEMPOSEGMENTMMAPPER_H_
+
+#include "SpecialSegmentMmapper.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+class RosegardenGUIDoc;
+
+
+class TempoSegmentMmapper : public SpecialSegmentMmapper
+{
+ friend class SegmentMmapperFactory;
+
+protected:
+ TempoSegmentMmapper(RosegardenGUIDoc* doc,
+ QString baseFileName)
+ : SpecialSegmentMmapper(doc, baseFileName) {}
+
+ // overrides from SegmentMmapper
+ virtual size_t computeMmappedSize();
+
+ // override from SegmentMmapper
+ virtual void dump();
+};
+
+//----------------------------------------
+
+
+}
+
+#endif
diff --git a/src/gui/seqmanager/TimeSigSegmentMmapper.cpp b/src/gui/seqmanager/TimeSigSegmentMmapper.cpp
new file mode 100644
index 0000000..98beab3
--- /dev/null
+++ b/src/gui/seqmanager/TimeSigSegmentMmapper.cpp
@@ -0,0 +1,72 @@
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+
+#include "TimeSigSegmentMmapper.h"
+
+#include "base/Event.h"
+#include "base/RealTime.h"
+#include "base/Segment.h"
+#include "base/TriggerSegment.h"
+#include "document/RosegardenGUIDoc.h"
+#include "SegmentMmapper.h"
+#include "sound/MappedEvent.h"
+#include "SpecialSegmentMmapper.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+void TimeSigSegmentMmapper::dump()
+{
+ RealTime eventTime;
+
+ Composition& comp = m_doc->getComposition();
+ MappedEvent* bufPos = m_mmappedEventBuffer;
+
+ for (int i = 0; i < comp.getTimeSignatureCount(); ++i) {
+
+ std::pair<timeT, TimeSignature> timeSigChange = comp.getTimeSignatureChange(i);
+
+ eventTime = comp.getElapsedRealTime(timeSigChange.first);
+ MappedEvent* mappedEvent = new (bufPos) MappedEvent();
+ mappedEvent->setType(MappedEvent::TimeSignature);
+ mappedEvent->setEventTime(eventTime);
+ mappedEvent->setData1(timeSigChange.second.getNumerator());
+ mappedEvent->setData2(timeSigChange.second.getDenominator());
+
+ ++bufPos;
+ }
+
+ // Store the number of events at the start of the shared memory region
+ *(size_t *)m_mmappedRegion = (bufPos - m_mmappedEventBuffer);
+}
+
+size_t TimeSigSegmentMmapper::computeMmappedSize()
+{
+ return m_doc->getComposition().getTimeSignatureCount() * sizeof(MappedEvent);
+}
+
+}
diff --git a/src/gui/seqmanager/TimeSigSegmentMmapper.h b/src/gui/seqmanager/TimeSigSegmentMmapper.h
new file mode 100644
index 0000000..20e0474
--- /dev/null
+++ b/src/gui/seqmanager/TimeSigSegmentMmapper.h
@@ -0,0 +1,62 @@
+
+/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
+
+/*
+ Rosegarden
+ A MIDI and audio sequencer and musical notation editor.
+
+ This program is Copyright 2000-2008
+ Guillaume Laurent <glaurent@telegraph-road.org>,
+ Chris Cannam <cannam@all-day-breakfast.com>,
+ Richard Bown <richard.bown@ferventsoftware.com>
+
+ The moral rights of Guillaume Laurent, Chris Cannam, and Richard
+ Bown to claim authorship of this work have been asserted.
+
+ Other copyrights also apply to some parts of this work. Please
+ see the AUTHORS file and individual file headers for details.
+
+ This program is free software; you can redistribute it and/or
+ modify it under the terms of the GNU General Public License as
+ published by the Free Software Foundation; either version 2 of the
+ License, or (at your option) any later version. See the file
+ COPYING included with this distribution for more information.
+*/
+
+#ifndef _RG_TIMESIGSEGMENTMMAPPER_H_
+#define _RG_TIMESIGSEGMENTMMAPPER_H_
+
+#include "SpecialSegmentMmapper.h"
+#include <qstring.h>
+
+
+namespace Rosegarden
+{
+
+class RosegardenGUIDoc;
+
+
+class TimeSigSegmentMmapper : public SpecialSegmentMmapper
+{
+ friend class SegmentMmapperFactory;
+
+public:
+
+protected:
+ TimeSigSegmentMmapper(RosegardenGUIDoc* doc,
+ QString baseFileName)
+ : SpecialSegmentMmapper(doc, baseFileName) {}
+
+ // overrides from SegmentMmapper
+ virtual size_t computeMmappedSize();
+
+ // override from SegmentMmapper
+ virtual void dump();
+};
+
+//----------------------------------------
+
+
+}
+
+#endif