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)
51 , capture_start_frame (0)
52 , capture_captured (0)
53 , was_recording (false)
54 , adjust_capture_position (0)
56 , first_recordable_frame (max_framepos)
57 , last_recordable_frame (max_framepos)
58 , last_possibly_recording (0)
59 , _alignment_style (ExistingMaterial)
60 , _alignment_choice (Automatic)
61 , _num_captured_loops (0)
62 , _accumulated_capture_offset (0)
63 , _gui_feed_buffer(AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
65 DiskIOProcessor::init ();
69 DiskWriter::default_chunk_frames ()
75 DiskWriter::set_write_source_name (string const & str)
77 _write_source_name = str;
82 DiskWriter::check_record_status (framepos_t transport_frame, bool can_record)
84 int possibly_recording;
87 const int transport_rolling = 0x4;
88 const int track_rec_enabled = 0x2;
89 const int global_rec_enabled = 0x1;
90 const int fully_rec_enabled = (transport_rolling|track_rec_enabled|global_rec_enabled);
92 /* merge together the 3 factors that affect record status, and compute
96 rolling = _session.transport_speed() != 0.0f;
97 possibly_recording = (rolling << 2) | ((int)record_enabled() << 1) | (int)can_record;
98 change = possibly_recording ^ last_possibly_recording;
100 if (possibly_recording == last_possibly_recording) {
104 const framecnt_t existing_material_offset = _session.worst_playback_latency();
106 if (possibly_recording == fully_rec_enabled) {
108 if (last_possibly_recording == fully_rec_enabled) {
112 capture_start_frame = _session.transport_frame();
113 first_recordable_frame = capture_start_frame + _capture_offset;
114 last_recordable_frame = max_framepos;
116 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: @ %7 (%9) FRF = %2 CSF = %4 CO = %5, EMO = %6 RD = %8 WOL %10 WTL %11\n",
117 name(), first_recordable_frame, last_recordable_frame, capture_start_frame,
119 existing_material_offset,
121 _session.transport_frame(),
122 _session.worst_output_latency(),
123 _session.worst_track_latency()));
126 if (_alignment_style == ExistingMaterial) {
127 first_recordable_frame += existing_material_offset;
128 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("\tshift FRF by EMO %1\n",
129 first_recordable_frame));
132 prepare_record_status (capture_start_frame);
136 if (last_possibly_recording == fully_rec_enabled) {
138 /* we were recording last time */
140 if (change & transport_rolling) {
142 /* transport-change (stopped rolling): last_recordable_frame was set in ::prepare_to_stop(). We
143 * had to set it there because we likely rolled past the stopping point to declick out,
144 * and then backed up.
150 last_recordable_frame = _session.transport_frame() + _capture_offset;
152 if (_alignment_style == ExistingMaterial) {
153 last_recordable_frame += existing_material_offset;
159 last_possibly_recording = possibly_recording;
163 DiskWriter::calculate_record_range (Evoral::OverlapType ot, framepos_t transport_frame, framecnt_t nframes,
164 framecnt_t & rec_nframes, framecnt_t & rec_offset)
167 case Evoral::OverlapNone:
171 case Evoral::OverlapInternal:
172 /* ---------- recrange
175 rec_nframes = nframes;
179 case Evoral::OverlapStart:
180 /* |--------| recrange
183 rec_nframes = transport_frame + nframes - first_recordable_frame;
185 rec_offset = first_recordable_frame - transport_frame;
189 case Evoral::OverlapEnd:
190 /* |--------| recrange
191 * |-------- transrange
193 rec_nframes = last_recordable_frame - transport_frame;
197 case Evoral::OverlapExternal:
198 /* |--------| recrange
199 * -------------- transrange
201 rec_nframes = last_recordable_frame - first_recordable_frame;
202 rec_offset = first_recordable_frame - transport_frame;
206 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 rec? %2 @ %3 (for %4) FRF %5 LRF %6 : rf %7 @ %8\n",
207 _name, enum_2_string (ot), transport_frame, nframes,
208 first_recordable_frame, last_recordable_frame, rec_nframes, rec_offset));
212 DiskWriter::prepare_to_stop (framepos_t transport_frame, framepos_t audible_frame)
214 switch (_alignment_style) {
215 case ExistingMaterial:
216 last_recordable_frame = transport_frame + _capture_offset;
217 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));
221 last_recordable_frame = audible_frame; // note that capture_offset is zero
222 /* we may already have captured audio before the last_recordable_frame (audible frame),
225 if (last_recordable_frame > capture_start_frame) {
226 capture_captured = min (capture_captured, last_recordable_frame - capture_start_frame);
228 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose("%1: prepare to stop sets last recordable frame to audible frame @ %2\n", _name, audible_frame));
235 DiskWriter::engage_record_enable ()
237 g_atomic_int_set (&_record_enabled, 1);
241 DiskWriter::disengage_record_enable ()
243 g_atomic_int_set (&_record_enabled, 0);
247 DiskWriter::engage_record_safe ()
249 g_atomic_int_set (&_record_safe, 1);
253 DiskWriter::disengage_record_safe ()
255 g_atomic_int_set (&_record_safe, 0);
258 /** Get the start position (in session frames) of the nth capture in the current pass */
260 DiskWriter::get_capture_start_frame (uint32_t n) const
262 Glib::Threads::Mutex::Lock lm (capture_info_lock);
264 if (capture_info.size() > n) {
265 /* this is a completed capture */
266 return capture_info[n]->start;
268 /* this is the currently in-progress capture */
269 return capture_start_frame;
274 DiskWriter::get_captured_frames (uint32_t n) const
276 Glib::Threads::Mutex::Lock lm (capture_info_lock);
278 if (capture_info.size() > n) {
279 /* this is a completed capture */
280 return capture_info[n]->frames;
282 /* this is the currently in-progress capture */
283 return capture_captured;
288 DiskWriter::set_input_latency (framecnt_t l)
294 DiskWriter::set_capture_offset ()
296 switch (_alignment_style) {
297 case ExistingMaterial:
298 _capture_offset = _input_latency;
307 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)));
312 DiskWriter::set_align_style (AlignStyle a, bool force)
314 if (record_enabled() && _session.actively_recording()) {
318 if ((a != _alignment_style) || force) {
319 _alignment_style = a;
320 cerr << name() << " using align style " << enum_2_string (_alignment_style) << endl;
321 set_capture_offset ();
322 AlignmentStyleChanged ();
327 DiskWriter::set_align_choice (AlignChoice a, bool force)
329 if (record_enabled() && _session.actively_recording()) {
333 if ((a != _alignment_choice) || force) {
334 _alignment_choice = a;
336 switch (_alignment_choice) {
337 case UseExistingMaterial:
338 set_align_style (ExistingMaterial);
341 set_align_style (CaptureTime);
344 error << string_compose (_("programming error: %1"), "DiskWriter: asked to use illegal alignment style") << endmsg;
351 DiskWriter::state (bool full)
353 XMLNode& node (DiskIOProcessor::state (full));
354 node.set_property (X_("type"), X_("diskwriter"));
355 node.set_property (X_("capture-alignment"), enum_2_string (_alignment_choice));
356 node.set_property (X_("record-safe"), (_record_safe ? X_("yes" : "no")));
361 DiskWriter::set_state (const XMLNode& node, int version)
363 if (DiskIOProcessor::set_state (node, version)) {
369 if (node.get_property (X_("capture-alignment"), ac)) {
370 set_align_choice (ac, true);
372 set_align_choice (Automatic, true);
375 if (!node.get_property (X_("record-safe"), _record_safe)) {
376 _record_safe = false;
379 reset_write_sources (false, true);
385 DiskWriter::non_realtime_locate (framepos_t position)
387 if (_midi_write_source) {
388 _midi_write_source->set_timeline_position (position);
391 DiskIOProcessor::non_realtime_locate (position);
396 DiskWriter::prepare_record_status(framepos_t capture_start_frame)
398 if (recordable() && destructive()) {
399 boost::shared_ptr<ChannelList> c = channels.reader();
400 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
402 RingBufferNPT<CaptureTransition>::rw_vector transitions;
403 (*chan)->capture_transition_buf->get_write_vector (&transitions);
405 if (transitions.len[0] > 0) {
406 transitions.buf[0]->type = CaptureStart;
407 transitions.buf[0]->capture_val = capture_start_frame;
408 (*chan)->capture_transition_buf->increment_write_ptr(1);
411 fatal << X_("programming error: capture_transition_buf is full on rec start! inconceivable!")
419 /** Do some record stuff [not described in this comment!]
422 * - Setup playback_distance with the nframes, or nframes adjusted
423 * for current varispeed, if appropriate.
424 * - Setup current_playback_buffer in each ChannelInfo to point to data
425 * that someone can read playback_distance worth of data from.
428 DiskWriter::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
429 double speed, pframes_t nframes, bool result_required)
432 boost::shared_ptr<ChannelList> c = channels.reader();
433 ChannelList::iterator chan;
434 framecnt_t rec_offset = 0;
435 framecnt_t rec_nframes = 0;
436 bool nominally_recording;
437 bool re = record_enabled ();
438 bool can_record = _session.actively_recording ();
441 if (!_pending_active) {
446 if (_pending_active) {
453 _need_butler = false;
455 check_record_status (start_frame, can_record);
461 nominally_recording = (can_record && re);
463 // Safeguard against situations where process() goes haywire when autopunching
464 // and last_recordable_frame < first_recordable_frame
466 if (last_recordable_frame < first_recordable_frame) {
467 last_recordable_frame = max_framepos;
470 const Location* const loop_loc = loop_location;
471 framepos_t loop_start = 0;
472 framepos_t loop_end = 0;
473 framepos_t loop_length = 0;
476 get_location_times (loop_loc, &loop_start, &loop_end, &loop_length);
479 adjust_capture_position = 0;
481 if (nominally_recording || (re && was_recording && _session.get_record_enabled() && (_session.config.get_punch_in() || _session.preroll_record_punch_enabled()))) {
483 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, start_frame, end_frame);
484 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
485 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
486 calculate_record_range (ot, start_frame, nframes, rec_nframes, rec_offset);
488 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
490 if (rec_nframes && !was_recording) {
491 capture_captured = 0;
494 /* Loop recording, so pretend the capture started at the loop
495 start rgardless of what time it is now, so the source starts
496 at the loop start and can handle time wrapping around.
497 Otherwise, start the source right now as usual.
499 capture_captured = start_frame - loop_start;
500 capture_start_frame = loop_start;
503 if (_midi_write_source) {
504 _midi_write_source->mark_write_starting_now (capture_start_frame, capture_captured, loop_length);
507 g_atomic_int_set(const_cast<gint*> (&_frames_pending_write), 0);
508 g_atomic_int_set(const_cast<gint*> (&_num_captured_loops), 0);
510 was_recording = true;
514 /* For audio: not writing frames to the capture ringbuffer offsets
515 * the recording. For midi: we need to keep track of the record range
516 * and subtract the accumulated difference from the event time.
519 _accumulated_capture_offset += rec_offset;
521 _accumulated_capture_offset += nframes;
526 if (can_record && !_last_capture_sources.empty()) {
527 _last_capture_sources.clear ();
534 const size_t n_buffers = bufs.count().n_audio();
536 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
538 ChannelInfo* chaninfo (*chan);
539 AudioBuffer& buf (bufs.get_audio (n%n_buffers));
541 chaninfo->buf->get_write_vector (&chaninfo->rw_vector);
543 if (rec_nframes <= (framecnt_t) chaninfo->rw_vector.len[0]) {
545 Sample *incoming = buf.data (rec_offset);
546 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * rec_nframes);
550 framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
552 if (rec_nframes > total) {
553 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
554 DEBUG_THREAD_SELF, name(), rec_nframes, total));
559 Sample *incoming = buf.data (rec_offset);
560 framecnt_t first = chaninfo->rw_vector.len[0];
562 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * first);
563 memcpy (chaninfo->rw_vector.buf[1], incoming + first, sizeof (Sample) * (rec_nframes - first));
566 chaninfo->buf->increment_write_ptr (rec_nframes);
572 // Pump entire port buffer into the ring buffer (TODO: split cycles?)
573 MidiBuffer& buf = bufs.get_midi (0);
574 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
575 MidiChannelFilter* filter = mt ? &mt->capture_filter() : 0;
577 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
578 Evoral::Event<MidiBuffer::TimeType> ev(*i, false);
579 if (ev.time() + rec_offset > rec_nframes) {
583 if (DEBUG_ENABLED(DEBUG::MidiIO)) {
584 const uint8_t* __data = ev.buffer();
586 DEBUG_STR_APPEND(a, string_compose ("mididiskstream %1 capture event @ %2 + %3 sz %4 ", this, ev.time(), start_frame, ev.size()));
587 for (size_t i=0; i < ev.size(); ++i) {
588 DEBUG_STR_APPEND(a,hex);
589 DEBUG_STR_APPEND(a,"0x");
590 DEBUG_STR_APPEND(a,(int)__data[i]);
591 DEBUG_STR_APPEND(a,' ');
593 DEBUG_STR_APPEND(a,'\n');
594 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
597 /* Write events to the capture buffer in frames from session start,
598 but ignoring looping so event time progresses monotonically.
599 The source knows the loop length so it knows exactly where the
600 event occurs in the series of recorded loops and can implement
601 any desirable behaviour. We don't want to send event with
602 transport time here since that way the source can not
603 reconstruct their actual time; future clever MIDI looping should
604 probably be implemented in the source instead of here.
606 const framecnt_t loop_offset = _num_captured_loops * loop_length;
607 const framepos_t event_time = start_frame + loop_offset - _accumulated_capture_offset + ev.time();
608 if (event_time < 0 || event_time < first_recordable_frame) {
609 /* Event out of range, skip */
613 if (!filter || !filter->filter(ev.buffer(), ev.size())) {
614 _midi_buf->write (event_time, ev.event_type(), ev.size(), ev.buffer());
617 g_atomic_int_add(const_cast<gint*>(&_frames_pending_write), nframes);
619 if (buf.size() != 0) {
620 Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex, Glib::Threads::TRY_LOCK);
623 /* Copy this data into our GUI feed buffer and tell the GUI
624 that it can read it if it likes.
626 _gui_feed_buffer.clear ();
628 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
629 /* This may fail if buf is larger than _gui_feed_buffer, but it's not really
630 the end of the world if it does.
632 _gui_feed_buffer.push_back ((*i).time() + start_frame, (*i).size(), (*i).buffer());
636 DataRecorded (_midi_write_source); /* EMIT SIGNAL */
639 capture_captured += rec_nframes;
640 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, rec_nframes));
644 /* not recording this time, but perhaps we were before .. */
648 _accumulated_capture_offset = 0;
652 /* AUDIO BUTLER REQUIRED CODE */
654 if (_playlists[DataType::AUDIO] && !c->empty()) {
655 if (((framecnt_t) c->front()->buf->read_space() >= _chunk_frames)) {
660 /* MIDI BUTLER REQUIRED CODE */
662 if (_playlists[DataType::MIDI] && (_midi_buf->read_space() < _midi_buf->bufsize() / 2)) {
666 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 writer run, needs butler = %2\n", name(), _need_butler));
670 DiskWriter::finish_capture (boost::shared_ptr<ChannelList> c)
672 was_recording = false;
673 first_recordable_frame = max_framepos;
674 last_recordable_frame = max_framepos;
676 if (capture_captured == 0) {
680 if (recordable() && destructive()) {
681 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
683 RingBufferNPT<CaptureTransition>::rw_vector transvec;
684 (*chan)->capture_transition_buf->get_write_vector(&transvec);
686 if (transvec.len[0] > 0) {
687 transvec.buf[0]->type = CaptureEnd;
688 transvec.buf[0]->capture_val = capture_captured;
689 (*chan)->capture_transition_buf->increment_write_ptr(1);
693 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record! inconceivable!")) << endmsg;
699 CaptureInfo* ci = new CaptureInfo;
701 ci->start = capture_start_frame;
702 ci->frames = capture_captured;
704 /* XXX theoretical race condition here. Need atomic exchange ?
705 However, the circumstances when this is called right
706 now (either on record-disable or transport_stopped)
707 mean that no actual race exists. I think ...
708 We now have a capture_info_lock, but it is only to be used
709 to synchronize in the transport_stop and the capture info
710 accessors, so that invalidation will not occur (both non-realtime).
713 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
715 capture_info.push_back (ci);
716 capture_captured = 0;
718 /* now we've finished a capture, reset first_recordable_frame for next time */
719 first_recordable_frame = max_framepos;
723 DiskWriter::set_record_enabled (bool yn)
725 if (!recordable() || !_session.record_enabling_legal() || record_safe ()) {
729 /* can't rec-enable in destructive mode if transport is before start */
731 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
735 /* yes, i know that this not proof against race conditions, but its
736 good enough. i think.
739 if (record_enabled() != yn) {
741 engage_record_enable ();
743 disengage_record_enable ();
746 RecordEnableChanged (); /* EMIT SIGNAL */
751 DiskWriter::set_record_safe (bool yn)
753 if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty()) {
757 /* can't rec-safe in destructive mode if transport is before start ????
760 if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
764 /* yes, i know that this not proof against race conditions, but its
765 good enough. i think.
768 if (record_safe () != yn) {
770 engage_record_safe ();
772 disengage_record_safe ();
775 RecordSafeChanged (); /* EMIT SIGNAL */
780 DiskWriter::prep_record_enable ()
782 if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty() || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
786 /* can't rec-enable in destructive mode if transport is before start */
788 if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
792 boost::shared_ptr<ChannelList> c = channels.reader();
794 capturing_sources.clear ();
796 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
797 capturing_sources.push_back ((*chan)->write_source);
798 Source::Lock lock((*chan)->write_source->mutex());
799 (*chan)->write_source->mark_streaming_write_started (lock);
806 DiskWriter::prep_record_disable ()
808 capturing_sources.clear ();
813 DiskWriter::buffer_load () const
815 boost::shared_ptr<ChannelList> c = channels.reader();
821 return (float) ((double) c->front()->buf->write_space()/
822 (double) c->front()->buf->bufsize());
826 DiskWriter::set_note_mode (NoteMode m)
830 boost::shared_ptr<MidiPlaylist> mp = boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
833 mp->set_note_mode (m);
836 if (_midi_write_source && _midi_write_source->model())
837 _midi_write_source->model()->set_note_mode(m);
841 DiskWriter::seek (framepos_t frame, bool complete_refill)
844 ChannelList::iterator chan;
845 boost::shared_ptr<ChannelList> c = channels.reader();
847 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
848 (*chan)->buf->reset ();
852 g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
853 g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
855 /* can't rec-enable in destructive mode if transport is before start */
857 if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
858 disengage_record_enable ();
861 playback_sample = frame;
868 DiskWriter::do_flush (RunContext ctxt, bool force_flush)
872 RingBufferNPT<Sample>::rw_vector vector;
873 RingBufferNPT<CaptureTransition>::rw_vector transvec;
881 boost::shared_ptr<ChannelList> c = channels.reader();
882 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
884 (*chan)->buf->get_read_vector (&vector);
886 total = vector.len[0] + vector.len[1];
888 if (total == 0 || (total < _chunk_frames && !force_flush && was_recording)) {
892 /* if there are 2+ chunks of disk i/o possible for
893 this track, let the caller know so that it can arrange
894 for us to be called again, ASAP.
896 if we are forcing a flush, then if there is* any* extra
897 work, let the caller know.
899 if we are no longer recording and there is any extra work,
900 let the caller know too.
903 if (total >= 2 * _chunk_frames || ((force_flush || !was_recording) && total > _chunk_frames)) {
907 to_write = min (_chunk_frames, (framecnt_t) vector.len[0]);
909 // check the transition buffer when recording destructive
910 // important that we get this after the capture buf
913 (*chan)->capture_transition_buf->get_read_vector(&transvec);
914 size_t transcount = transvec.len[0] + transvec.len[1];
917 for (ti=0; ti < transcount; ++ti) {
918 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
920 if (captrans.type == CaptureStart) {
921 // by definition, the first data we got above represents the given capture pos
923 (*chan)->write_source->mark_capture_start (captrans.capture_val);
924 (*chan)->curr_capture_cnt = 0;
926 } else if (captrans.type == CaptureEnd) {
928 // capture end, the capture_val represents total frames in capture
930 if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
932 // shorten to make the write a perfect fit
933 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
935 if (nto_write < to_write) {
936 ret = 1; // should we?
938 to_write = nto_write;
940 (*chan)->write_source->mark_capture_end ();
942 // increment past this transition, but go no further
947 // actually ends just beyond this chunk, so force more work
955 (*chan)->capture_transition_buf->increment_read_ptr(ti);
959 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
960 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
964 (*chan)->buf->increment_read_ptr (to_write);
965 (*chan)->curr_capture_cnt += to_write;
967 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < _chunk_frames) && !destructive()) {
969 /* we wrote all of vector.len[0] but it wasn't an entire
970 disk_write_chunk_frames of data, so arrange for some part
971 of vector.len[1] to be flushed to disk as well.
974 to_write = min ((framecnt_t)(_chunk_frames - to_write), (framecnt_t) vector.len[1]);
976 DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
978 if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
979 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
983 (*chan)->buf->increment_read_ptr (to_write);
984 (*chan)->curr_capture_cnt += to_write;
996 DiskWriter::reset_write_sources (bool mark_write_complete, bool /*force*/)
998 ChannelList::iterator chan;
999 boost::shared_ptr<ChannelList> c = channels.reader();
1002 if (!_session.writable() || !recordable()) {
1006 capturing_sources.clear ();
1008 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1010 if (!destructive()) {
1012 if ((*chan)->write_source) {
1014 if (mark_write_complete) {
1015 Source::Lock lock((*chan)->write_source->mutex());
1016 (*chan)->write_source->mark_streaming_write_completed (lock);
1017 (*chan)->write_source->done_with_peakfile_writes ();
1020 if ((*chan)->write_source->removable()) {
1021 (*chan)->write_source->mark_for_remove ();
1022 (*chan)->write_source->drop_references ();
1025 (*chan)->write_source.reset ();
1028 use_new_write_source (DataType::AUDIO, n);
1030 if (record_enabled()) {
1031 capturing_sources.push_back ((*chan)->write_source);
1036 if ((*chan)->write_source == 0) {
1037 use_new_write_source (DataType::AUDIO, n);
1042 if (_midi_write_source) {
1043 if (mark_write_complete) {
1044 Source::Lock lm(_midi_write_source->mutex());
1045 _midi_write_source->mark_streaming_write_completed (lm);
1049 if (_playlists[DataType::MIDI]) {
1050 use_new_write_source (DataType::MIDI);
1053 if (destructive() && !c->empty ()) {
1055 /* we now have all our write sources set up, so create the
1056 playlist's single region.
1059 if (_playlists[DataType::MIDI]->empty()) {
1060 setup_destructive_playlist ();
1066 DiskWriter::use_new_write_source (DataType dt, uint32_t n)
1068 if (dt == DataType::MIDI) {
1070 _accumulated_capture_offset = 0;
1071 _midi_write_source.reset();
1074 _midi_write_source = boost::dynamic_pointer_cast<SMFSource>(
1075 _session.create_midi_source_for_session (write_source_name ()));
1077 if (!_midi_write_source) {
1078 throw failed_constructor();
1082 catch (failed_constructor &err) {
1083 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1084 _midi_write_source.reset();
1088 boost::shared_ptr<ChannelList> c = channels.reader();
1090 if (!recordable()) {
1094 if (n >= c->size()) {
1095 error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1099 ChannelInfo* chan = (*c)[n];
1102 if ((chan->write_source = _session.create_audio_source_for_session (
1103 c->size(), write_source_name(), n, destructive())) == 0) {
1104 throw failed_constructor();
1108 catch (failed_constructor &err) {
1109 error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1110 chan->write_source.reset ();
1114 /* do not remove destructive files even if they are empty */
1116 chan->write_source->set_allow_remove_if_empty (!destructive());
1123 DiskWriter::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1125 uint32_t buffer_position;
1126 bool more_work = true;
1128 boost::shared_ptr<AudioRegion> region;
1129 framecnt_t total_capture;
1131 SourceList::iterator src;
1132 ChannelList::iterator chan;
1133 vector<CaptureInfo*>::iterator ci;
1134 boost::shared_ptr<ChannelList> c = channels.reader();
1136 bool mark_write_completed = false;
1140 boost::shared_ptr<AudioPlaylist> pl = boost::dynamic_pointer_cast<AudioPlaylist> (_playlists[DataType::AUDIO]);
1142 /* butler is already stopped, but there may be work to do
1143 to flush remaining data to disk.
1146 while (more_work && !err) {
1147 switch (do_flush (TransportContext, true)) {
1154 error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1159 /* XXX is there anything we can do if err != 0 ? */
1160 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1162 if (capture_info.empty()) {
1166 if (abort_capture) {
1168 if (destructive()) {
1172 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1174 if ((*chan)->write_source) {
1176 (*chan)->write_source->mark_for_remove ();
1177 (*chan)->write_source->drop_references ();
1178 (*chan)->write_source.reset ();
1181 /* new source set up in "out" below */
1187 for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1188 total_capture += (*ci)->frames;
1191 /* figure out the name for this take */
1193 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1195 boost::shared_ptr<AudioFileSource> s = (*chan)->write_source;
1199 s->update_header (capture_info.front()->start, when, twhen);
1200 s->set_captured_for (_name.val());
1201 s->mark_immutable ();
1203 if (Config->get_auto_analyse_audio()) {
1204 Analyser::queue_source_for_analysis (s, true);
1207 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", s->path(), s->length (0)));
1215 /* destructive tracks have a single, never changing region */
1217 if (destructive()) {
1219 /* send a signal that any UI can pick up to do the right thing. there is
1220 a small problem here in that a UI may need the peak data to be ready
1221 for the data that was recorded and this isn't interlocked with that
1222 process. this problem is deferred to the UI.
1225 pl->LayeringChanged(); // XXX this may not get the UI to do the right thing
1229 string whole_file_region_name;
1230 whole_file_region_name = region_name_from_path (c->front()->write_source->name(), true);
1232 /* Register a new region with the Session that
1233 describes the entire source. Do this first
1234 so that any sub-regions will obviously be
1235 children of this one (later!)
1241 plist.add (Properties::start, c->front()->write_source->last_capture_start_frame());
1242 plist.add (Properties::length, total_capture);
1243 plist.add (Properties::name, whole_file_region_name);
1244 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1245 rx->set_automatic (true);
1246 rx->set_whole_file (true);
1248 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1249 region->special_set_position (capture_info.front()->start);
1253 catch (failed_constructor& err) {
1254 error << string_compose(_("%1: could not create region for complete audio file"), _name) << endmsg;
1258 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1260 pl->clear_changes ();
1261 pl->set_capture_insertion_in_progress (true);
1264 const framepos_t preroll_off = _session.preroll_record_trim_len ();
1265 for (buffer_position = c->front()->write_source->last_capture_start_frame(), ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1269 RegionFactory::region_name (region_name, whole_file_region_name, false);
1271 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture bufpos %5 start @ %2 length %3 add new region %4\n",
1272 _name, (*ci)->start, (*ci)->frames, region_name, buffer_position));
1278 plist.add (Properties::start, buffer_position);
1279 plist.add (Properties::length, (*ci)->frames);
1280 plist.add (Properties::name, region_name);
1282 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1283 region = boost::dynamic_pointer_cast<AudioRegion> (rx);
1284 if (preroll_off > 0) {
1285 region->trim_front (buffer_position + preroll_off);
1289 catch (failed_constructor& err) {
1290 error << _("AudioDiskstream: could not create region for captured audio!") << endmsg;
1291 continue; /* XXX is this OK? */
1294 i_am_the_modifier++;
1296 pl->add_region (region, (*ci)->start + preroll_off, 1, non_layered());
1297 pl->set_layer (region, DBL_MAX);
1298 i_am_the_modifier--;
1300 buffer_position += (*ci)->frames;
1304 pl->set_capture_insertion_in_progress (false);
1305 _session.add_command (new StatefulDiffCommand (pl));
1308 mark_write_completed = true;
1311 reset_write_sources (mark_write_completed);
1315 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1319 capture_info.clear ();
1320 capture_start_frame = 0;
1328 DiskWriter::transport_stopped_wallclock (struct tm& /*when*/, time_t /*twhen*/, bool abort_capture)
1330 bool more_work = true;
1332 boost::shared_ptr<MidiRegion> region;
1333 MidiRegion::SourceList srcs;
1334 MidiRegion::SourceList::iterator src;
1335 vector<CaptureInfo*>::iterator ci;
1339 /* butler is already stopped, but there may be work to do
1340 to flush remaining data to disk.
1343 while (more_work && !err) {
1344 switch (do_flush (TransportContext, true)) {
1351 error << string_compose(_("MidiDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1356 /* XXX is there anything we can do if err != 0 ? */
1357 Glib::Threads::Mutex::Lock lm (capture_info_lock);
1359 if (capture_info.empty()) {
1360 goto no_capture_stuff_to_do;
1363 if (abort_capture) {
1365 if (_write_source) {
1366 _write_source->mark_for_remove ();
1367 _write_source->drop_references ();
1368 _write_source.reset();
1371 /* new source set up in "out" below */
1375 framecnt_t total_capture = 0;
1376 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1377 total_capture += (*ci)->frames;
1380 if (_write_source->length (capture_info.front()->start) != 0) {
1382 /* phew, we have data */
1384 Source::Lock source_lock(_write_source->mutex());
1386 /* figure out the name for this take */
1388 srcs.push_back (_write_source);
1390 _write_source->set_timeline_position (capture_info.front()->start);
1391 _write_source->set_captured_for (_name);
1393 /* set length in beats to entire capture length */
1395 BeatsFramesConverter converter (_session.tempo_map(), capture_info.front()->start);
1396 const Evoral::Beats total_capture_beats = converter.from (total_capture);
1397 _write_source->set_length_beats (total_capture_beats);
1399 /* flush to disk: this step differs from the audio path,
1400 where all the data is already on disk.
1403 _write_source->mark_midi_streaming_write_completed (source_lock, Evoral::Sequence<Evoral::Beats>::ResolveStuckNotes, total_capture_beats);
1405 /* we will want to be able to keep (over)writing the source
1406 but we don't want it to be removable. this also differs
1407 from the audio situation, where the source at this point
1408 must be considered immutable. luckily, we can rely on
1409 MidiSource::mark_streaming_write_completed() to have
1410 already done the necessary work for that.
1413 string whole_file_region_name;
1414 whole_file_region_name = region_name_from_path (_write_source->name(), true);
1416 /* Register a new region with the Session that
1417 describes the entire source. Do this first
1418 so that any sub-regions will obviously be
1419 children of this one (later!)
1425 plist.add (Properties::name, whole_file_region_name);
1426 plist.add (Properties::whole_file, true);
1427 plist.add (Properties::automatic, true);
1428 plist.add (Properties::start, 0);
1429 plist.add (Properties::length, total_capture);
1430 plist.add (Properties::layer, 0);
1432 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1434 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1435 region->special_set_position (capture_info.front()->start);
1439 catch (failed_constructor& err) {
1440 error << string_compose(_("%1: could not create region for complete midi file"), _name) << endmsg;
1444 _last_capture_sources.insert (_last_capture_sources.end(), srcs.begin(), srcs.end());
1446 _playlist->clear_changes ();
1447 _playlist->freeze ();
1449 /* Session frame time of the initial capture in this pass, which is where the source starts */
1450 framepos_t initial_capture = 0;
1451 if (!capture_info.empty()) {
1452 initial_capture = capture_info.front()->start;
1455 const framepos_t preroll_off = _session.preroll_record_trim_len ();
1456 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1460 RegionFactory::region_name (region_name, _write_source->name(), false);
1462 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 capture start @ %2 length %3 add new region %4\n",
1463 _name, (*ci)->start, (*ci)->frames, region_name));
1466 // cerr << _name << ": based on ci of " << (*ci)->start << " for " << (*ci)->frames << " add a region\n";
1471 /* start of this region is the offset between the start of its capture and the start of the whole pass */
1472 plist.add (Properties::start, (*ci)->start - initial_capture);
1473 plist.add (Properties::length, (*ci)->frames);
1474 plist.add (Properties::length_beats, converter.from((*ci)->frames).to_double());
1475 plist.add (Properties::name, region_name);
1477 boost::shared_ptr<Region> rx (RegionFactory::create (srcs, plist));
1478 region = boost::dynamic_pointer_cast<MidiRegion> (rx);
1479 if (preroll_off > 0) {
1480 region->trim_front ((*ci)->start - initial_capture + preroll_off);
1484 catch (failed_constructor& err) {
1485 error << _("MidiDiskstream: could not create region for captured midi!") << endmsg;
1486 continue; /* XXX is this OK? */
1489 // cerr << "add new region, buffer position = " << buffer_position << " @ " << (*ci)->start << endl;
1491 i_am_the_modifier++;
1492 _playlist->add_region (region, (*ci)->start + preroll_off);
1493 i_am_the_modifier--;
1497 _session.add_command (new StatefulDiffCommand(_playlist));
1501 /* No data was recorded, so this capture will
1502 effectively be aborted; do the same as we
1503 do for an explicit abort.
1506 if (_write_source) {
1507 _write_source->mark_for_remove ();
1508 _write_source->drop_references ();
1509 _write_source.reset();
1515 reset_write_sources ();
1517 for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1521 capture_info.clear ();
1522 capture_start_frame = 0;
1524 no_capture_stuff_to_do:
1531 DiskWriter::transport_looped (framepos_t transport_frame)
1533 if (was_recording) {
1534 // all we need to do is finish this capture, with modified capture length
1535 boost::shared_ptr<ChannelList> c = channels.reader();
1539 // the next region will start recording via the normal mechanism
1540 // we'll set the start position to the current transport pos
1541 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1542 capture_start_frame = transport_frame;
1543 first_recordable_frame = transport_frame; // mild lie
1544 last_recordable_frame = max_framepos;
1545 was_recording = true;
1547 if (recordable() && destructive()) {
1548 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1550 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1551 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1553 if (transvec.len[0] > 0) {
1554 transvec.buf[0]->type = CaptureStart;
1555 transvec.buf[0]->capture_val = capture_start_frame;
1556 (*chan)->capture_transition_buf->increment_write_ptr(1);
1560 fatal << X_("programming error: capture_transition_buf is full on rec loop! inconceivable!")
1568 /* Here we only keep track of the number of captured loops so monotonic
1569 event times can be delivered to the write source in process(). Trying
1570 to be clever here is a world of trouble, it is better to simply record
1571 the input in a straightforward non-destructive way. In the future when
1572 we want to implement more clever MIDI looping modes it should be done in
1573 the Source and/or entirely after the capture is finished.
1575 if (was_recording) {
1576 g_atomic_int_add(const_cast<gint*> (&_num_captured_loops), 1);
1581 DiskWriter::setup_destructive_playlist ()
1584 boost::shared_ptr<ChannelList> c = channels.reader();
1586 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1587 srcs.push_back ((*chan)->write_source);
1590 /* a single full-sized region */
1592 assert (!srcs.empty ());
1595 plist.add (Properties::name, _name.val());
1596 plist.add (Properties::start, 0);
1597 plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
1599 boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
1600 _playlists[DataType::AUDIO]->add_region (region, srcs.front()->natural_position());
1602 /* apply region properties and update write sources */
1603 use_destructive_playlist();
1607 DiskWriter::use_destructive_playlist ()
1609 /* this is called from the XML-based constructor or ::set_destructive. when called,
1610 we already have a playlist and a region, but we need to
1611 set up our sources for write. we use the sources associated
1612 with the (presumed single, full-extent) region.
1615 boost::shared_ptr<Region> rp;
1617 const RegionList& rl (_playlists[DataType::AUDIO]->region_list_property().rlist());
1618 if (rl.size() > 0) {
1619 /* this can happen when dragging a region onto a tape track */
1620 assert((rl.size() == 1));
1626 reset_write_sources (false, true);
1630 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
1633 throw failed_constructor();
1636 /* be sure to stretch the region out to the maximum length (non-musical)*/
1638 region->set_length (max_framepos - region->position(), 0);
1641 ChannelList::iterator chan;
1642 boost::shared_ptr<ChannelList> c = channels.reader();
1644 for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1645 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
1646 assert((*chan)->write_source);
1647 (*chan)->write_source->set_allow_remove_if_empty (false);
1649 /* this might be false if we switched modes, so force it */
1651 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
1652 (*chan)->write_source->set_destructive (true);
1654 // should be set when creating the source or loading the state
1655 assert ((*chan)->write_source->destructive());
1659 /* the source list will never be reset for a destructive track */
1663 DiskWriter::adjust_buffering ()
1665 boost::shared_ptr<ChannelList> c = channels.reader();
1667 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1668 (*chan)->resize (_session.butler()->audio_diskstream_capture_buffer_size());
1673 DiskWriter::realtime_handle_transport_stopped ()
1675 realtime_speed_change ();
1679 DiskWriter::set_name (string const & str)
1681 string my_name = X_("writer:");
1684 if (_name != my_name) {
1685 SessionObject::set_name (my_name);
1692 DiskWriter::steal_write_source_name ()
1694 if (_playlists[DataType::MIDI]) {
1695 string our_old_name = _midi_write_source->name();
1697 /* this will bump the name of the current write source to the next one
1698 * (e.g. "MIDI 1-1" gets renamed to "MIDI 1-2"), thus leaving the
1699 * current write source name (e.g. "MIDI 1-1" available). See the
1700 * comments in Session::create_midi_source_by_stealing_name() about why
1705 string new_path = _session.new_midi_source_path (name());
1707 if (_midi_write_source->rename (new_path)) {
1714 return our_old_name;
1717 return std::string();
1721 DiskWriter::configure_io (ChanCount in, ChanCount out)
1723 if (!DiskIOProcessor::configure_io (in, out)) {
1727 reset_write_sources (false, true);