2 Copyright (C) 2009-2016 Paul Davis
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version.
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 #include "ardour/analyser.h"
23 #include "ardour/audioengine.h"
24 #include "ardour/audiofilesource.h"
25 #include "ardour/audio_buffer.h"
26 #include "ardour/audioplaylist.h"
27 #include "ardour/audioregion.h"
28 #include "ardour/butler.h"
29 #include "ardour/debug.h"
30 #include "ardour/disk_writer.h"
31 #include "ardour/midi_playlist.h"
32 #include "ardour/midi_source.h"
33 #include "ardour/midi_track.h"
34 #include "ardour/port.h"
35 #include "ardour/region_factory.h"
36 #include "ardour/session.h"
37 #include "ardour/smf_source.h"
39 using namespace ARDOUR;
43 ARDOUR::framecnt_t DiskWriter::_chunk_frames = DiskWriter::default_chunk_frames ();
44 PBD::Signal0<void> DiskWriter::Overrun;
46 DiskWriter::DiskWriter (Session& s, string const & str, DiskIOProcessor::Flag f)
47 : DiskIOProcessor (s, str, f)
48 , capture_start_frame (0)
49 , capture_captured (0)
50 , was_recording (false)
51 , adjust_capture_position (0)
53 , first_recordable_frame (max_framepos)
54 , last_recordable_frame (max_framepos)
55 , last_possibly_recording (0)
56 , _alignment_style (ExistingMaterial)
57 , _alignment_choice (Automatic)
58 , _num_captured_loops (0)
59 , _accumulated_capture_offset (0)
60 , _gui_feed_buffer(AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
62 DiskIOProcessor::init ();
66 DiskWriter::default_chunk_frames ()
72 DiskWriter::set_write_source_name (string const & str)
74 _write_source_name = str;
79 DiskWriter::check_record_status (framepos_t transport_frame, bool can_record)
81 int possibly_recording;
84 const int transport_rolling = 0x4;
85 const int track_rec_enabled = 0x2;
86 const int global_rec_enabled = 0x1;
87 const int fully_rec_enabled = (transport_rolling|track_rec_enabled|global_rec_enabled);
89 /* merge together the 3 factors that affect record status, and compute
93 rolling = _session.transport_speed() != 0.0f;
94 possibly_recording = (rolling << 2) | ((int)record_enabled() << 1) | (int)can_record;
95 change = possibly_recording ^ last_possibly_recording;
97 if (possibly_recording == last_possibly_recording) {
101 const framecnt_t existing_material_offset = _session.worst_playback_latency();
103 if (possibly_recording == fully_rec_enabled) {
105 if (last_possibly_recording == fully_rec_enabled) {
109 capture_start_frame = _session.transport_frame();
110 first_recordable_frame = capture_start_frame + _capture_offset;
111 last_recordable_frame = max_framepos;
113 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: @ %7 (%9) FRF = %2 CSF = %4 CO = %5, EMO = %6 RD = %8 WOL %10 WTL %11\n",
114 name(), first_recordable_frame, last_recordable_frame, capture_start_frame,
116 existing_material_offset,
118 _session.transport_frame(),
119 _session.worst_output_latency(),
120 _session.worst_track_latency()));
123 if (_alignment_style == ExistingMaterial) {
124 first_recordable_frame += existing_material_offset;
125 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("\tshift FRF by EMO %1\n",
126 first_recordable_frame));
129 prepare_record_status (capture_start_frame);
133 if (last_possibly_recording == fully_rec_enabled) {
135 /* we were recording last time */
137 if (change & transport_rolling) {
139 /* transport-change (stopped rolling): last_recordable_frame was set in ::prepare_to_stop(). We
140 * had to set it there because we likely rolled past the stopping point to declick out,
141 * and then backed up.
147 last_recordable_frame = _session.transport_frame() + _capture_offset;
149 if (_alignment_style == ExistingMaterial) {
150 last_recordable_frame += existing_material_offset;
156 last_possibly_recording = possibly_recording;
160 DiskWriter::calculate_record_range (Evoral::OverlapType ot, framepos_t transport_frame, framecnt_t nframes,
161 framecnt_t & rec_nframes, framecnt_t & rec_offset)
164 case Evoral::OverlapNone:
168 case Evoral::OverlapInternal:
169 /* ---------- recrange
172 rec_nframes = nframes;
176 case Evoral::OverlapStart:
177 /* |--------| recrange
180 rec_nframes = transport_frame + nframes - first_recordable_frame;
182 rec_offset = first_recordable_frame - transport_frame;
186 case Evoral::OverlapEnd:
187 /* |--------| recrange
188 * |-------- transrange
190 rec_nframes = last_recordable_frame - transport_frame;
194 case Evoral::OverlapExternal:
195 /* |--------| recrange
196 * -------------- transrange
198 rec_nframes = last_recordable_frame - first_recordable_frame;
199 rec_offset = first_recordable_frame - transport_frame;
203 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 rec? %2 @ %3 (for %4) FRF %5 LRF %6 : rf %7 @ %8\n",
204 _name, enum_2_string (ot), transport_frame, nframes,
205 first_recordable_frame, last_recordable_frame, rec_nframes, rec_offset));
209 DiskWriter::prepare_to_stop (framepos_t transport_frame, framepos_t audible_frame)
211 switch (_alignment_style) {
212 case ExistingMaterial:
213 last_recordable_frame = transport_frame + _capture_offset;
214 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose("%1: prepare to stop sets last recordable frame to %2 + %3 = %4\n", _name, transport_frame, _capture_offset, last_recordable_frame));
218 last_recordable_frame = audible_frame; // note that capture_offset is zero
219 /* we may already have captured audio before the last_recordable_frame (audible frame),
222 if (last_recordable_frame > capture_start_frame) {
223 capture_captured = min (capture_captured, last_recordable_frame - capture_start_frame);
225 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose("%1: prepare to stop sets last recordable frame to audible frame @ %2\n", _name, audible_frame));
232 DiskWriter::engage_record_enable ()
234 g_atomic_int_set (&_record_enabled, 1);
238 DiskWriter::disengage_record_enable ()
240 g_atomic_int_set (&_record_enabled, 0);
244 DiskWriter::engage_record_safe ()
246 g_atomic_int_set (&_record_safe, 1);
250 DiskWriter::disengage_record_safe ()
252 g_atomic_int_set (&_record_safe, 0);
255 /** Get the start position (in session frames) of the nth capture in the current pass */
257 DiskWriter::get_capture_start_frame (uint32_t n) const
259 Glib::Threads::Mutex::Lock lm (capture_info_lock);
261 if (capture_info.size() > n) {
262 /* this is a completed capture */
263 return capture_info[n]->start;
265 /* this is the currently in-progress capture */
266 return capture_start_frame;
271 DiskWriter::get_captured_frames (uint32_t n) const
273 Glib::Threads::Mutex::Lock lm (capture_info_lock);
275 if (capture_info.size() > n) {
276 /* this is a completed capture */
277 return capture_info[n]->frames;
279 /* this is the currently in-progress capture */
280 return capture_captured;
285 DiskWriter::set_input_latency (framecnt_t l)
291 DiskWriter::set_capture_offset ()
293 switch (_alignment_style) {
294 case ExistingMaterial:
295 _capture_offset = _input_latency;
304 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: using IO latency, capture offset set to %2 with style = %3\n", name(), _capture_offset, enum_2_string (_alignment_style)));
309 DiskWriter::set_align_style (AlignStyle a, bool force)
311 if (record_enabled() && _session.actively_recording()) {
315 if ((a != _alignment_style) || force) {
316 _alignment_style = a;
317 set_capture_offset ();
318 AlignmentStyleChanged ();
323 DiskWriter::set_align_style_from_io ()
325 bool have_physical = false;
327 if (_alignment_choice != Automatic) {
335 boost::shared_ptr<IO> input = _route->input ();
339 vector<string> connections;
340 boost::shared_ptr<ChannelList> c = channels.reader();
342 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan, ++n) {
344 if ((input->nth (n).get()) && (input->nth (n)->get_connections (connections) == 0)) {
345 if (AudioEngine::instance()->port_is_physical (connections[0])) {
346 have_physical = true;
351 connections.clear ();
356 // compensate for latency when bouncing from master or mixbus.
357 // we need to use "ExistingMaterial" to pick up the master bus' latency
358 // see also Route::direct_feeds_according_to_reality
361 if (_session.master_out() && ios.fed_by (_session.master_out()->output())) {
362 have_physical = true;
364 for (uint32_t n = 0; n < NUM_MIXBUSES && !have_physical; ++n) {
365 if (_session.get_mixbus (n) && ios.fed_by (_session.get_mixbus(n)->output())) {
366 have_physical = true;
372 set_align_style (ExistingMaterial);
374 set_align_style (CaptureTime);
379 DiskWriter::set_align_choice (AlignChoice a, bool force)
381 if (record_enabled() && _session.actively_recording()) {
385 if ((a != _alignment_choice) || force) {
386 _alignment_choice = a;
388 switch (_alignment_choice) {
390 set_align_style_from_io ();
392 case UseExistingMaterial:
393 set_align_style (ExistingMaterial);
396 set_align_style (CaptureTime);
403 DiskWriter::state (bool full)
405 XMLNode& node (DiskIOProcessor::state (full));
406 node.set_property(X_("type"), X_("diskwriter"));
407 node.set_property (X_("capture-alignment"), enum_2_string (_alignment_choice));
408 node.set_property (X_("record-safe"), (_record_safe ? X_("yes" : "no")));
413 DiskWriter::set_state (const XMLNode& node, int version)
415 XMLProperty const * prop;
417 if (DiskIOProcessor::set_state (node, version)) {
421 if (!node.property (X_("capture-alignment"))) != 0) {
422 set_align_choice (AlignChoice (string_2_enum (prop->value(), _alignment_choice)), true);
424 set_align_choice (Automatic, true);
428 if (!node.get_property (X_("record-safe"), _record_safe)) {
429 _record_safe = false;
432 reset_write_sources (false, true);
438 DiskWriter::non_realtime_locate (framepos_t position)
440 if (_midi_write_source) {
441 _midi_write_source->set_timeline_position (position);
444 DiskIOProcessor::non_realtime_locate (position);
449 DiskWriter::prepare_record_status(framepos_t capture_start_frame)
451 if (recordable() && destructive()) {
452 boost::shared_ptr<ChannelList> c = channels.reader();
453 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
455 RingBufferNPT<CaptureTransition>::rw_vector transitions;
456 (*chan)->capture_transition_buf->get_write_vector (&transitions);
458 if (transitions.len[0] > 0) {
459 transitions.buf[0]->type = CaptureStart;
460 transitions.buf[0]->capture_val = capture_start_frame;
461 (*chan)->capture_transition_buf->increment_write_ptr(1);
464 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
472 /** Do some record stuff [not described in this comment!]
475 * - Setup playback_distance with the nframes, or nframes adjusted
476 * for current varispeed, if appropriate.
477 * - Setup current_playback_buffer in each ChannelInfo to point to data
478 * that someone can read playback_distance worth of data from.
481 DiskWriter::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
482 double speed, pframes_t nframes, bool result_required)
485 boost::shared_ptr<ChannelList> c = channels.reader();
486 ChannelList::iterator chan;
487 framecnt_t rec_offset = 0;
488 framecnt_t rec_nframes = 0;
489 bool nominally_recording;
490 bool re = record_enabled ();
491 bool can_record = _session.actively_recording ();
493 _need_butler = false;
495 check_record_status (start_frame, can_record);
501 nominally_recording = (can_record && re);
503 // Safeguard against situations where process() goes haywire when autopunching
504 // and last_recordable_frame < first_recordable_frame
506 if (last_recordable_frame < first_recordable_frame) {
507 last_recordable_frame = max_framepos;
510 const Location* const loop_loc = loop_location;
511 framepos_t loop_start = 0;
512 framepos_t loop_end = 0;
513 framepos_t loop_length = 0;
516 get_location_times (loop_loc, &loop_start, &loop_end, &loop_length);
519 adjust_capture_position = 0;
521 if (nominally_recording || (re && was_recording && _session.get_record_enabled() && (_session.config.get_punch_in() || _session.preroll_record_punch_enabled()))) {
523 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, start_frame, end_frame);
524 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
525 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
526 calculate_record_range (ot, start_frame, nframes, rec_nframes, rec_offset);
528 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
530 if (rec_nframes && !was_recording) {
531 capture_captured = 0;
534 /* Loop recording, so pretend the capture started at the loop
535 start rgardless of what time it is now, so the source starts
536 at the loop start and can handle time wrapping around.
537 Otherwise, start the source right now as usual.
539 capture_captured = start_frame - loop_start;
540 capture_start_frame = loop_start;
543 if (_midi_write_source) {
544 _midi_write_source->mark_write_starting_now (capture_start_frame, capture_captured, loop_length);
547 g_atomic_int_set(const_cast<gint*> (&_frames_pending_write), 0);
548 g_atomic_int_set(const_cast<gint*> (&_num_captured_loops), 0);
550 was_recording = true;
554 /* For audio: not writing frames to the capture ringbuffer offsets
555 * the recording. For midi: we need to keep track of the record range
556 * and subtract the accumulated difference from the event time.
559 _accumulated_capture_offset += rec_offset;
561 _accumulated_capture_offset += nframes;
566 if (can_record && !_last_capture_sources.empty()) {
567 _last_capture_sources.clear ();
574 const size_t n_buffers = bufs.count().n_audio();
576 for (n = 0; chan != c->end(); ++chan, ++n) {
578 ChannelInfo* chaninfo (*chan);
579 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
581 chaninfo->buf->get_write_vector (&chaninfo->rw_vector);
583 if (rec_nframes <= (framecnt_t) chaninfo->rw_vector.len[0]) {
585 Sample *incoming = buf.data (rec_offset);
586 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * rec_nframes);
590 framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
592 if (rec_nframes > total) {
593 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
594 DEBUG_THREAD_SELF, name(), rec_nframes, total));
599 Sample *incoming = buf.data (rec_offset);
600 framecnt_t first = chaninfo->rw_vector.len[0];
602 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * first);
603 memcpy (chaninfo->rw_vector.buf[1], incoming + first, sizeof (Sample) * (rec_nframes - first));
606 chaninfo->buf->increment_write_ptr (rec_nframes);
612 // Pump entire port buffer into the ring buffer (TODO: split cycles?)
613 MidiBuffer& buf = bufs.get_midi (0);
614 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
615 MidiChannelFilter* filter = mt ? &mt->capture_filter() : 0;
617 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
618 Evoral::Event<MidiBuffer::TimeType> ev(*i, false);
619 if (ev.time() + rec_offset > rec_nframes) {
623 if (DEBUG_ENABLED(DEBUG::MidiIO)) {
624 const uint8_t* __data = ev.buffer();
626 DEBUG_STR_APPEND(a, string_compose ("mididiskstream %1 capture event @ %2 + %3 sz %4 ", this, ev.time(), start_frame, ev.size()));
627 for (size_t i=0; i < ev.size(); ++i) {
628 DEBUG_STR_APPEND(a,hex);
629 DEBUG_STR_APPEND(a,"0x");
630 DEBUG_STR_APPEND(a,(int)__data[i]);
631 DEBUG_STR_APPEND(a,' ');
633 DEBUG_STR_APPEND(a,'\n');
634 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
637 /* Write events to the capture buffer in frames from session start,
638 but ignoring looping so event time progresses monotonically.
639 The source knows the loop length so it knows exactly where the
640 event occurs in the series of recorded loops and can implement
641 any desirable behaviour. We don't want to send event with
642 transport time here since that way the source can not
643 reconstruct their actual time; future clever MIDI looping should
644 probably be implemented in the source instead of here.
646 const framecnt_t loop_offset = _num_captured_loops * loop_length;
647 const framepos_t event_time = start_frame + loop_offset - _accumulated_capture_offset + ev.time();
648 if (event_time < 0 || event_time < first_recordable_frame) {
649 /* Event out of range, skip */
653 if (!filter || !filter->filter(ev.buffer(), ev.size())) {
654 _midi_buf->write (event_time, ev.event_type(), ev.size(), ev.buffer());
657 g_atomic_int_add(const_cast<gint*>(&_frames_pending_write), nframes);
659 if (buf.size() != 0) {
660 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex, Glib::Threads::TRY_LOCK);
663 /* Copy this data into our GUI feed buffer and tell the GUI
664 that it can read it if it likes.
666 _gui_feed_buffer.clear ();
668 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
669 /* This may fail if buf is larger than _gui_feed_buffer, but it's not really
670 the end of the world if it does.
672 _gui_feed_buffer.push_back ((*i).time() + start_frame, (*i).size(), (*i).buffer());
676 DataRecorded (_midi_write_source); /* EMIT SIGNAL */
679 capture_captured += rec_nframes;
680 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, rec_nframes));
684 /* not recording this time, but perhaps we were before .. */
688 _accumulated_capture_offset = 0;
692 /* AUDIO BUTLER REQUIRED CODE */
694 if (_playlists[DataType::AUDIO] && !c->empty()) {
695 if (((framecnt_t) c->front()->buf->read_space() >= _chunk_frames)) {
700 /* MIDI BUTLER REQUIRED CODE */
702 if (_playlists[DataType::MIDI] && (_midi_buf->read_space() < _midi_buf->bufsize() / 2)) {
706 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 writer run, needs butler = %2\n", name(), _need_butler));
710 DiskWriter::finish_capture (boost::shared_ptr<ChannelList> c)
712 was_recording = false;
713 first_recordable_frame = max_framepos;
714 last_recordable_frame = max_framepos;
716 if (capture_captured == 0) {
720 if (recordable() && destructive()) {
721 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
723 RingBufferNPT<CaptureTransition>::rw_vector transvec;
724 (*chan)->capture_transition_buf->get_write_vector(&transvec);
726 if (transvec.len[0] > 0) {
727 transvec.buf[0]->type = CaptureEnd;
728 transvec.buf[0]->capture_val = capture_captured;
729 (*chan)->capture_transition_buf->increment_write_ptr(1);
733 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
739 CaptureInfo* ci = new CaptureInfo;
741 ci->start = capture_start_frame;
742 ci->frames = capture_captured;
744 /* XXX theoretical race condition here. Need atomic exchange ?
745 However, the circumstances when this is called right
746 now (either on record-disable or transport_stopped)
747 mean that no actual race exists. I think ...
748 We now have a capture_info_lock, but it is only to be used
749 to synchronize in the transport_stop and the capture info
750 accessors, so that invalidation will not occur (both non-realtime).
753 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
755 capture_info.push_back (ci);
756 capture_captured = 0;
758 /* now we've finished a capture, reset first_recordable_frame for next time */
759 first_recordable_frame = max_framepos;
763 DiskWriter::set_record_enabled (bool yn)
765 if (!recordable() || !_session.record_enabling_legal() || record_safe ()) {
769 /* can't rec-enable in destructive mode if transport is before start */
771 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
775 /* yes, i know that this not proof against race conditions, but its
776 good enough. i think.
779 if (record_enabled() != yn) {
781 engage_record_enable ();
783 disengage_record_enable ();
786 RecordEnableChanged (); /* EMIT SIGNAL */
791 DiskWriter::set_record_safe (bool yn)
793 if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty()) {
797 /* can't rec-safe in destructive mode if transport is before start ????
800 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
804 /* yes, i know that this not proof against race conditions, but its
805 good enough. i think.
808 if (record_safe () != yn) {
810 engage_record_safe ();
812 disengage_record_safe ();
815 RecordSafeChanged (); /* EMIT SIGNAL */
820 DiskWriter::prep_record_enable ()
822 if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty() || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
826 /* can't rec-enable in destructive mode if transport is before start */
828 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
832 boost::shared_ptr<ChannelList> c = channels.reader();
834 capturing_sources.clear ();
836 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
837 capturing_sources.push_back ((*chan)->write_source);
838 Source::Lock lock((*chan)->write_source->mutex());
839 (*chan)->write_source->mark_streaming_write_started (lock);
846 DiskWriter::prep_record_disable ()
848 capturing_sources.clear ();
853 DiskWriter::buffer_load () const
855 boost::shared_ptr<ChannelList> c = channels.reader();
861 return (float) ((double) c->front()->buf->write_space()/
862 (double) c->front()->buf->bufsize());
866 DiskWriter::set_note_mode (NoteMode m)
870 boost::shared_ptr<MidiPlaylist> mp = boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
873 mp->set_note_mode (m);
876 if (_midi_write_source && _midi_write_source->model())
877 _midi_write_source->model()->set_note_mode(m);
881 DiskWriter::seek (framepos_t frame, bool complete_refill)
884 ChannelList::iterator chan;
885 boost::shared_ptr<ChannelList> c = channels.reader();
887 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
888 (*chan)->buf->reset ();
892 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
893 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
895 /* can't rec-enable in destructive mode if transport is before start */
897 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
898 disengage_record_enable ();
901 playback_sample = frame;
908 DiskWriter::do_flush (RunContext ctxt, bool force_flush)
912 RingBufferNPT<Sample>::rw_vector vector;
913 RingBufferNPT<CaptureTransition>::rw_vector transvec;
921 boost::shared_ptr<ChannelList> c = channels.reader();
922 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
924 (*chan)->buf->get_read_vector (&vector);
926 total = vector.len[0] + vector.len[1];
928 if (total == 0 || (total < _chunk_frames && !force_flush && was_recording)) {
932 /* if there are 2+ chunks of disk i/o possible for
933 this track, let the caller know so that it can arrange
934 for us to be called again, ASAP.
936 if we are forcing a flush, then if there is* any* extra
937 work, let the caller know.
939 if we are no longer recording and there is any extra work,
940 let the caller know too.
943 if (total >= 2 * _chunk_frames || ((force_flush || !was_recording) && total > _chunk_frames)) {
947 to_write = min (_chunk_frames, (framecnt_t) vector.len[0]);
949 // check the transition buffer when recording destructive
950 // important that we get this after the capture buf
953 (*chan)->capture_transition_buf->get_read_vector(&transvec);
954 size_t transcount = transvec.len[0] + transvec.len[1];
957 for (ti=0; ti < transcount; ++ti) {
958 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
960 if (captrans.type == CaptureStart) {
961 // by definition, the first data we got above represents the given capture pos
963 (*chan)->write_source->mark_capture_start (captrans.capture_val);
964 (*chan)->curr_capture_cnt = 0;
966 } else if (captrans.type == CaptureEnd) {
968 // capture end, the capture_val represents total frames in capture
970 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
972 // shorten to make the write a perfect fit
973 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
975 if (nto_write < to_write) {
976 ret = 1; // should we?
978 to_write = nto_write;
980 (*chan)->write_source->mark_capture_end ();
982 // increment past this transition, but go no further
987 // actually ends just beyond this chunk, so force more work
995 (*chan)->capture_transition_buf->increment_read_ptr(ti);
999 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
1000 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1004 (*chan)->buf->increment_read_ptr (to_write);
1005 (*chan)->curr_capture_cnt += to_write;
1007 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < _chunk_frames) && !destructive()) {
1009 /* we wrote all of vector.len[0] but it wasn't an entire
1010 disk_write_chunk_frames of data, so arrange for some part
1011 of vector.len[1] to be flushed to disk as well.
1014 to_write = min ((framecnt_t)(_chunk_frames - to_write), (framecnt_t) vector.len[1]);
1016 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
1018 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
1019 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
1023 (*chan)->buf->increment_read_ptr (to_write);
1024 (*chan)->curr_capture_cnt += to_write;
1036 DiskWriter::reset_write_sources (bool mark_write_complete, bool /*force*/)
1038 ChannelList::iterator chan;
1039 boost::shared_ptr<ChannelList> c = channels.reader();
1042 if (!_session.writable() || !recordable()) {
1046 capturing_sources.clear ();
1048 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1050 if (!destructive()) {
1052 if ((*chan)->write_source) {
1054 if (mark_write_complete) {
1055 Source::Lock lock((*chan)->write_source->mutex());
1056 (*chan)->write_source->mark_streaming_write_completed (lock);
1057 (*chan)->write_source->done_with_peakfile_writes ();
1060 if ((*chan)->write_source->removable()) {
1061 (*chan)->write_source->mark_for_remove ();
1062 (*chan)->write_source->drop_references ();
1065 (*chan)->write_source.reset ();
1068 use_new_write_source (DataType::AUDIO, n);
1070 if (record_enabled()) {
1071 capturing_sources.push_back ((*chan)->write_source);
1076 if ((*chan)->write_source == 0) {
1077 use_new_write_source (DataType::AUDIO, n);
1082 if (_midi_write_source) {
1083 if (mark_write_complete) {
1084 Source::Lock lm(_midi_write_source->mutex());
1085 _midi_write_source->mark_streaming_write_completed (lm);
1088 use_new_write_source (DataType::MIDI);
1090 if (destructive() && !c->empty ()) {
1092 /* we now have all our write sources set up, so create the
1093 playlist's single region.
1096 if (_playlists[DataType::MIDI]->empty()) {
1097 setup_destructive_playlist ();
1104 DiskWriter::use_new_write_source (DataType dt, uint32_t n)
1106 if (dt == DataType::MIDI) {
1108 _accumulated_capture_offset = 0;
1109 _midi_write_source.reset();
1112 _midi_write_source = boost::dynamic_pointer_cast<SMFSource>(
1113 _session.create_midi_source_for_session (write_source_name ()));
1115 if (!_midi_write_source) {
1116 throw failed_constructor();
1120 catch (failed_constructor &err) {
1121 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1122 _midi_write_source.reset();
1126 boost::shared_ptr<ChannelList> c = channels.reader();
1128 if (!recordable()) {
1132 if (n >= c->size()) {
1133 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1137 ChannelInfo* chan = (*c)[n];
1140 if ((chan->write_source = _session.create_audio_source_for_session (
1141 c->size(), write_source_name(), n, destructive())) == 0) {
1142 throw failed_constructor();
1146 catch (failed_constructor &err) {
1147 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1148 chan->write_source.reset ();
1152 /* do not remove destructive files even if they are empty */
1154 chan->write_source->set_allow_remove_if_empty (!destructive());
1161 DiskWriter::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1163 uint32_t buffer_position;
1164 bool more_work = true;
1166 boost::shared_ptr<AudioRegion> region;
1167 framecnt_t total_capture;
1169 SourceList::iterator src;
1170 ChannelList::iterator chan;
1171 vector<CaptureInfo*>::iterator ci;
1172 boost::shared_ptr<ChannelList> c = channels.reader();
1174 bool mark_write_completed = false;
1178 boost::shared_ptr<AudioPlaylist> pl = boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
1180 /* butler is already stopped, but there may be work to do
1181 to flush remaining data to disk.
1184 while (more_work && !err) {
1185 switch (do_flush (TransportContext, true)) {
1192 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1197 /* XXX is there anything we can do if err != 0 ? */
1198 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1200 if (capture_info.empty()) {
1204 if (abort_capture) {
1206 if (destructive()) {
1210 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1212 if ((*chan)->write_source) {
1214 (*chan)->write_source->mark_for_remove ();
1215 (*chan)->write_source->drop_references ();
1216 (*chan)->write_source.reset ();
1219 /* new source set up in "out" below */
1225 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1226 total_capture += (*ci)->frames;
1229 /* figure out the name for this take */
1231 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1233 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1237 s->update_header (capture_info.front()->start, when, twhen);
1238 s->set_captured_for (_name.val());
1239 s->mark_immutable ();
1241 if (Config->get_auto_analyse_audio()) {
1242 Analyser::queue_source_for_analysis (s, true);
1245 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", s->path(), s->length (0)));
1253 /* destructive tracks have a single, never changing region */
1255 if (destructive()) {
1257 /* send a signal that any UI can pick up to do the right thing. there is
1258 a small problem here in that a UI may need the peak data to be ready
1259 for the data that was recorded and this isn't interlocked with that
1260 process. this problem is deferred to the UI.
1263 pl->LayeringChanged(); // XXX this may not get the UI to do the right thing
1267 string whole_file_region_name;
1268 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1270 /* Register a new region with the Session that
1271 describes the entire source. Do this first
1272 so that any sub-regions will obviously be
1273 children of this one (later!)
1279 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1280 plist.add (Properties::length, total_capture);
1281 plist.add (Properties::name, whole_file_region_name);
1282 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1283 rx->set_automatic (true);
1284 rx->set_whole_file (true);
1286 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1287 region->special_set_position (capture_info.front()->start);
1291 catch (failed_constructor& err) {
1292 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1296 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1298 pl->clear_changes ();
1299 pl->set_capture_insertion_in_progress (true);
1302 const framepos_t preroll_off = _session.preroll_record_trim_len ();
1303 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1307 RegionFactory::region_name (region_name, whole_file_region_name, false);
1309 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1310 _name, (*ci)->start, (*ci)->frames, region_name, buffer_position));
1316 plist.add (Properties::start, buffer_position);
1317 plist.add (Properties::length, (*ci)->frames);
1318 plist.add (Properties::name, region_name);
1320 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1321 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1322 if (preroll_off > 0) {
1323 region->trim_front (buffer_position + preroll_off);
1327 catch (failed_constructor& err) {
1328 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1329 continue; /* XXX is this OK? */
1332 i_am_the_modifier++;
1334 pl->add_region (region, (*ci)->start + preroll_off, 1, non_layered());
1335 pl->set_layer (region, DBL_MAX);
1336 i_am_the_modifier--;
1338 buffer_position += (*ci)->frames;
1342 pl->set_capture_insertion_in_progress (false);
1343 _session.add_command (new StatefulDiffCommand (pl));
1346 mark_write_completed = true;
1349 reset_write_sources (mark_write_completed);
1353 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1357 capture_info.clear ();
1358 capture_start_frame = 0;
1366 DiskWriter::transport_stopped_wallclock (struct tm& /*when*/, time_t /*twhen*/, bool abort_capture)
1368 bool more_work = true;
1370 boost::shared_ptr<MidiRegion> region;
1371 MidiRegion::SourceList srcs;
1372 MidiRegion::SourceList::iterator src;
1373 vector<CaptureInfo*>::iterator ci;
1377 /* butler is already stopped, but there may be work to do
1378 to flush remaining data to disk.
1381 while (more_work && !err) {
1382 switch (do_flush (TransportContext, true)) {
1389 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1394 /* XXX is there anything we can do if err != 0 ? */
1395 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1397 if (capture_info.empty()) {
1398 goto no_capture_stuff_to_do;
1401 if (abort_capture) {
1403 if (_write_source) {
1404 _write_source->mark_for_remove ();
1405 _write_source->drop_references ();
1406 _write_source.reset();
1409 /* new source set up in "out" below */
1413 framecnt_t total_capture = 0;
1414 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1415 total_capture += (*ci)->frames;
1418 if (_write_source->length (capture_info.front()->start) != 0) {
1420 /* phew, we have data */
1422 Source::Lock source_lock(_write_source->mutex());
1424 /* figure out the name for this take */
1426 srcs.push_back (_write_source);
1428 _write_source->set_timeline_position (capture_info.front()->start);
1429 _write_source->set_captured_for (_name);
1431 /* set length in beats to entire capture length */
1433 BeatsFramesConverter converter (_session.tempo_map(), capture_info.front()->start);
1434 const Evoral::Beats total_capture_beats = converter.from (total_capture);
1435 _write_source->set_length_beats (total_capture_beats);
1437 /* flush to disk: this step differs from the audio path,
1438 where all the data is already on disk.
1441 _write_source->mark_midi_streaming_write_completed (source_lock, Evoral::Sequence<Evoral::Beats>::ResolveStuckNotes, total_capture_beats);
1443 /* we will want to be able to keep (over)writing the source
1444 but we don't want it to be removable. this also differs
1445 from the audio situation, where the source at this point
1446 must be considered immutable. luckily, we can rely on
1447 MidiSource::mark_streaming_write_completed() to have
1448 already done the necessary work for that.
1451 string whole_file_region_name;
1452 whole_file_region_name = region_name_from_path (_write_source->name(), true);
1454 /* Register a new region with the Session that
1455 describes the entire source. Do this first
1456 so that any sub-regions will obviously be
1457 children of this one (later!)
1463 plist.add (Properties::name, whole_file_region_name);
1464 plist.add (Properties::whole_file, true);
1465 plist.add (Properties::automatic, true);
1466 plist.add (Properties::start, 0);
1467 plist.add (Properties::length, total_capture);
1468 plist.add (Properties::layer, 0);
1470 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1472 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1473 region->special_set_position (capture_info.front()->start);
1477 catch (failed_constructor& err) {
1478 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1482 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1484 _playlist->clear_changes ();
1485 _playlist->freeze ();
1487 /* Session frame time of the initial capture in this pass, which is where the source starts */
1488 framepos_t initial_capture = 0;
1489 if (!capture_info.empty()) {
1490 initial_capture = capture_info.front()->start;
1493 const framepos_t preroll_off = _session.preroll_record_trim_len ();
1494 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1498 RegionFactory::region_name (region_name, _write_source->name(), false);
1500 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1501 _name, (*ci)->start, (*ci)->frames, region_name));
1504 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1509 /* start of this region is the offset between the start of its capture and the start of the whole pass */
1510 plist.add (Properties::start, (*ci)->start - initial_capture);
1511 plist.add (Properties::length, (*ci)->frames);
1512 plist.add (Properties::length_beats, converter.from((*ci)->frames).to_double());
1513 plist.add (Properties::name, region_name);
1515 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1516 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1517 if (preroll_off > 0) {
1518 region->trim_front ((*ci)->start - initial_capture + preroll_off);
1522 catch (failed_constructor& err) {
1523 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1524 continue; /* XXX is this OK? */
1527 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1529 i_am_the_modifier++;
1530 _playlist->add_region (region, (*ci)->start + preroll_off);
1531 i_am_the_modifier--;
1535 _session.add_command (new StatefulDiffCommand(_playlist));
1539 /* No data was recorded, so this capture will
1540 effectively be aborted; do the same as we
1541 do for an explicit abort.
1544 if (_write_source) {
1545 _write_source->mark_for_remove ();
1546 _write_source->drop_references ();
1547 _write_source.reset();
1553 use_new_write_source (0);
1555 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1559 capture_info.clear ();
1560 capture_start_frame = 0;
1562 no_capture_stuff_to_do:
1569 DiskWriter::transport_looped (framepos_t transport_frame)
1571 if (was_recording) {
1572 // all we need to do is finish this capture, with modified capture length
1573 boost::shared_ptr<ChannelList> c = channels.reader();
1577 // the next region will start recording via the normal mechanism
1578 // we'll set the start position to the current transport pos
1579 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1580 capture_start_frame = transport_frame;
1581 first_recordable_frame = transport_frame; // mild lie
1582 last_recordable_frame = max_framepos;
1583 was_recording = true;
1585 if (recordable() && destructive()) {
1586 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1588 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1589 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1591 if (transvec.len[0] > 0) {
1592 transvec.buf[0]->type = CaptureStart;
1593 transvec.buf[0]->capture_val = capture_start_frame;
1594 (*chan)->capture_transition_buf->increment_write_ptr(1);
1598 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1606 /* Here we only keep track of the number of captured loops so monotonic
1607 event times can be delivered to the write source in process(). Trying
1608 to be clever here is a world of trouble, it is better to simply record
1609 the input in a straightforward non-destructive way. In the future when
1610 we want to implement more clever MIDI looping modes it should be done in
1611 the Source and/or entirely after the capture is finished.
1613 if (was_recording) {
1614 g_atomic_int_add(const_cast<gint*> (&_num_captured_loops), 1);
1619 DiskWriter::setup_destructive_playlist ()
1622 boost::shared_ptr<ChannelList> c = channels.reader();
1624 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1625 srcs.push_back ((*chan)->write_source);
1628 /* a single full-sized region */
1630 assert (!srcs.empty ());
1633 plist.add (Properties::name, _name.val());
1634 plist.add (Properties::start, 0);
1635 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
1637 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
1638 _playlists[DataType::AUDIO]->add_region (region, srcs.front()->natural_position());
1640 /* apply region properties and update write sources */
1641 use_destructive_playlist();
1645 DiskWriter::use_destructive_playlist ()
1647 /* this is called from the XML-based constructor or ::set_destructive. when called,
1648 we already have a playlist and a region, but we need to
1649 set up our sources for write. we use the sources associated
1650 with the (presumed single, full-extent) region.
1653 boost::shared_ptr<Region> rp;
1655 const RegionList& rl (_playlists[DataType::AUDIO]->region_list_property().rlist());
1656 if (rl.size() > 0) {
1657 /* this can happen when dragging a region onto a tape track */
1658 assert((rl.size() == 1));
1664 reset_write_sources (false, true);
1668 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
1671 throw failed_constructor();
1674 /* be sure to stretch the region out to the maximum length (non-musical)*/
1676 region->set_length (max_framepos - region->position(), 0);
1679 ChannelList::iterator chan;
1680 boost::shared_ptr<ChannelList> c = channels.reader();
1682 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1683 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
1684 assert((*chan)->write_source);
1685 (*chan)->write_source->set_allow_remove_if_empty (false);
1687 /* this might be false if we switched modes, so force it */
1689 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
1690 (*chan)->write_source->set_destructive (true);
1692 // should be set when creating the source or loading the state
1693 assert ((*chan)->write_source->destructive());
1697 /* the source list will never be reset for a destructive track */
1701 DiskWriter::adjust_buffering ()
1703 boost::shared_ptr<ChannelList> c = channels.reader();
1705 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1706 (*chan)->resize (_session.butler()->audio_diskstream_capture_buffer_size());
1711 DiskWriter::realtime_handle_transport_stopped ()
1713 realtime_speed_change ();