move _file_frame from DiskIOProcessor into DiskReader (only place where it is needed...
[ardour.git] / libs / ardour / disk_writer.cc
1 /*
2     Copyright (C) 2009-2016 Paul Davis
3
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.
8
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.
13
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.
17
18 */
19
20 #include "pbd/i18n.h"
21
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"
38
39 using namespace ARDOUR;
40 using namespace PBD;
41 using namespace std;
42
43 ARDOUR::framecnt_t DiskWriter::_chunk_frames = DiskWriter::default_chunk_frames ();
44 PBD::Signal0<void> DiskWriter::Overrun;
45
46 DiskWriter::DiskWriter (Session& s, string const & str, DiskIOProcessor::Flag f)
47         : DiskIOProcessor (s, str, f)
48         , _record_enabled (0)
49         , _record_safe (0)
50         , capture_start_frame (0)
51         , capture_captured (0)
52         , was_recording (false)
53         , adjust_capture_position (0)
54         , _capture_offset (0)
55         , first_recordable_frame (max_framepos)
56         , last_recordable_frame (max_framepos)
57         , last_possibly_recording (0)
58         , _alignment_style (ExistingMaterial)
59         , _alignment_choice (Automatic)
60         , _num_captured_loops (0)
61         , _accumulated_capture_offset (0)
62         , _gui_feed_buffer(AudioEngine::instance()->raw_buffer_size (DataType::MIDI))
63 {
64         DiskIOProcessor::init ();
65 }
66
67 DiskWriter::~DiskWriter ()
68 {
69         DEBUG_TRACE (DEBUG::Destruction, string_compose ("DiskWriter %1 @ %2 deleted\n", _name, this));
70
71         boost::shared_ptr<ChannelList> c = channels.reader();
72
73         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
74                 (*chan)->write_source.reset ();
75         }
76 }
77
78 framecnt_t
79 DiskWriter::default_chunk_frames ()
80 {
81         return 65536;
82 }
83
84 bool
85 DiskWriter::set_write_source_name (string const & str)
86 {
87         _write_source_name = str;
88         return true;
89 }
90
91 void
92 DiskWriter::check_record_status (framepos_t transport_frame, bool can_record)
93 {
94         int possibly_recording;
95         int rolling;
96         int change;
97         const int transport_rolling = 0x4;
98         const int track_rec_enabled = 0x2;
99         const int global_rec_enabled = 0x1;
100         const int fully_rec_enabled = (transport_rolling|track_rec_enabled|global_rec_enabled);
101
102         /* merge together the 3 factors that affect record status, and compute
103          * what has changed.
104          */
105
106         rolling = _session.transport_speed() != 0.0f;
107         possibly_recording = (rolling << 2) | ((int)record_enabled() << 1) | (int)can_record;
108         change = possibly_recording ^ last_possibly_recording;
109
110         if (possibly_recording == last_possibly_recording) {
111                 return;
112         }
113
114         const framecnt_t existing_material_offset = _session.worst_playback_latency();
115
116         if (possibly_recording == fully_rec_enabled) {
117
118                 if (last_possibly_recording == fully_rec_enabled) {
119                         return;
120                 }
121
122                 capture_start_frame = _session.transport_frame();
123                 first_recordable_frame = capture_start_frame + _capture_offset;
124                 last_recordable_frame = max_framepos;
125
126                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: @ %7 (%9) FRF = %2 CSF = %4 CO = %5, EMO = %6 RD = %8 WOL %10 WTL %11\n",
127                                                                       name(), first_recordable_frame, last_recordable_frame, capture_start_frame,
128                                                                       _capture_offset,
129                                                                       existing_material_offset,
130                                                                       transport_frame,
131                                                                       _session.transport_frame(),
132                                                                       _session.worst_output_latency(),
133                                                                       _session.worst_track_latency()));
134
135
136                 if (_alignment_style == ExistingMaterial) {
137                         first_recordable_frame += existing_material_offset;
138                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("\tshift FRF by EMO %1\n",
139                                                                               first_recordable_frame));
140                 }
141
142                 prepare_record_status (capture_start_frame);
143
144         } else {
145
146                 if (last_possibly_recording == fully_rec_enabled) {
147
148                         /* we were recording last time */
149
150                         if (change & transport_rolling) {
151
152                                 /* transport-change (stopped rolling): last_recordable_frame was set in ::prepare_to_stop(). We
153                                  * had to set it there because we likely rolled past the stopping point to declick out,
154                                  * and then backed up.
155                                  */
156
157                         } else {
158                                 /* punch out */
159
160                                 last_recordable_frame = _session.transport_frame() + _capture_offset;
161
162                                 if (_alignment_style == ExistingMaterial) {
163                                         last_recordable_frame += existing_material_offset;
164                                 }
165                         }
166                 }
167         }
168
169         last_possibly_recording = possibly_recording;
170 }
171
172 void
173 DiskWriter::calculate_record_range (Evoral::OverlapType ot, framepos_t transport_frame, framecnt_t nframes,
174                                     framecnt_t & rec_nframes, framecnt_t & rec_offset)
175 {
176         switch (ot) {
177         case Evoral::OverlapNone:
178                 rec_nframes = 0;
179                 break;
180
181         case Evoral::OverlapInternal:
182                 /*     ----------    recrange
183                  *       |---|       transrange
184                  */
185                 rec_nframes = nframes;
186                 rec_offset = 0;
187                 break;
188
189         case Evoral::OverlapStart:
190                 /*    |--------|    recrange
191                  *  -----|          transrange
192                  */
193                 rec_nframes = transport_frame + nframes - first_recordable_frame;
194                 if (rec_nframes) {
195                         rec_offset = first_recordable_frame - transport_frame;
196                 }
197                 break;
198
199         case Evoral::OverlapEnd:
200                 /*    |--------|    recrange
201                  *       |--------  transrange
202                  */
203                 rec_nframes = last_recordable_frame - transport_frame;
204                 rec_offset = 0;
205                 break;
206
207         case Evoral::OverlapExternal:
208                 /*    |--------|    recrange
209                  *  --------------  transrange
210                  */
211                 rec_nframes = last_recordable_frame - first_recordable_frame;
212                 rec_offset = first_recordable_frame - transport_frame;
213                 break;
214         }
215
216         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 rec? %2 @ %3 (for %4) FRF %5 LRF %6 : rf %7 @ %8\n",
217                                                               _name, enum_2_string (ot), transport_frame, nframes,
218                                                               first_recordable_frame, last_recordable_frame, rec_nframes, rec_offset));
219 }
220
221 void
222 DiskWriter::prepare_to_stop (framepos_t transport_frame, framepos_t audible_frame)
223 {
224         switch (_alignment_style) {
225         case ExistingMaterial:
226                 last_recordable_frame = transport_frame + _capture_offset;
227                 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));
228                 break;
229
230         case CaptureTime:
231                 last_recordable_frame = audible_frame; // note that capture_offset is zero
232                 /* we may already have captured audio before the last_recordable_frame (audible frame),
233                    so deal with this.
234                 */
235                 if (last_recordable_frame > capture_start_frame) {
236                         capture_captured = min (capture_captured, last_recordable_frame - capture_start_frame);
237                 }
238                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose("%1: prepare to stop sets last recordable frame to audible frame @ %2\n", _name, audible_frame));
239                 break;
240         }
241
242 }
243
244 void
245 DiskWriter::engage_record_enable ()
246 {
247         g_atomic_int_set (&_record_enabled, 1);
248 }
249
250 void
251 DiskWriter::disengage_record_enable ()
252 {
253         g_atomic_int_set (&_record_enabled, 0);
254 }
255
256 void
257 DiskWriter::engage_record_safe ()
258 {
259         g_atomic_int_set (&_record_safe, 1);
260 }
261
262 void
263 DiskWriter::disengage_record_safe ()
264 {
265         g_atomic_int_set (&_record_safe, 0);
266 }
267
268 /** Get the start position (in session frames) of the nth capture in the current pass */
269 ARDOUR::framepos_t
270 DiskWriter::get_capture_start_frame (uint32_t n) const
271 {
272         Glib::Threads::Mutex::Lock lm (capture_info_lock);
273
274         if (capture_info.size() > n) {
275                 /* this is a completed capture */
276                 return capture_info[n]->start;
277         } else {
278                 /* this is the currently in-progress capture */
279                 return capture_start_frame;
280         }
281 }
282
283 ARDOUR::framecnt_t
284 DiskWriter::get_captured_frames (uint32_t n) const
285 {
286         Glib::Threads::Mutex::Lock lm (capture_info_lock);
287
288         if (capture_info.size() > n) {
289                 /* this is a completed capture */
290                 return capture_info[n]->frames;
291         } else {
292                 /* this is the currently in-progress capture */
293                 return capture_captured;
294         }
295 }
296
297 void
298 DiskWriter::set_input_latency (framecnt_t l)
299 {
300         Processor::set_input_latency (l);
301         set_capture_offset ();
302 }
303
304 void
305 DiskWriter::set_capture_offset ()
306 {
307         switch (_alignment_style) {
308         case ExistingMaterial:
309                 _capture_offset = _input_latency;
310                 break;
311
312         case CaptureTime:
313         default:
314                 _capture_offset = 0;
315                 break;
316         }
317
318         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: using input latency %4, capture offset set to %2 with style = %3\n", name(), _capture_offset, enum_2_string (_alignment_style), _input_latency));
319 }
320
321
322 void
323 DiskWriter::set_align_style (AlignStyle a, bool force)
324 {
325         if (record_enabled() && _session.actively_recording()) {
326                 return;
327         }
328
329         if ((a != _alignment_style) || force) {
330                 _alignment_style = a;
331                 set_capture_offset ();
332                 AlignmentStyleChanged ();
333         }
334 }
335
336 void
337 DiskWriter::set_align_choice (AlignChoice a, bool force)
338 {
339         if (record_enabled() && _session.actively_recording()) {
340                 return;
341         }
342
343         if ((a != _alignment_choice) || force) {
344                 _alignment_choice = a;
345
346                 switch (_alignment_choice) {
347                 case UseExistingMaterial:
348                         set_align_style (ExistingMaterial);
349                         break;
350                 case UseCaptureTime:
351                         set_align_style (CaptureTime);
352                         break;
353                 default:
354                         error << string_compose (_("programming error: %1"), "DiskWriter: asked to use illegal alignment style") << endmsg;
355                         break;
356                 }
357         }
358 }
359
360 XMLNode&
361 DiskWriter::state (bool full)
362 {
363         XMLNode& node (DiskIOProcessor::state (full));
364         node.set_property (X_("type"), X_("diskwriter"));
365         node.set_property (X_("capture-alignment"), enum_2_string (_alignment_choice));
366         node.set_property (X_("record-safe"), (_record_safe ? X_("yes" : "no")));
367         return node;
368 }
369
370 int
371 DiskWriter::set_state (const XMLNode& node, int version)
372 {
373         if (DiskIOProcessor::set_state (node, version)) {
374                 return -1;
375         }
376
377         AlignChoice ac;
378
379         if (node.get_property (X_("capture-alignment"), ac)) {
380                 set_align_choice (ac, true);
381         } else {
382                 set_align_choice (Automatic, true);
383         }
384
385         if (!node.get_property (X_("record-safe"), _record_safe)) {
386                 _record_safe = false;
387         }
388
389         reset_write_sources (false, true);
390
391         return 0;
392 }
393
394 void
395 DiskWriter::non_realtime_locate (framepos_t position)
396 {
397         if (_midi_write_source) {
398                 _midi_write_source->set_timeline_position (position);
399         }
400
401         DiskIOProcessor::non_realtime_locate (position);
402 }
403
404
405 void
406 DiskWriter::prepare_record_status(framepos_t capture_start_frame)
407 {
408         if (recordable() && destructive()) {
409                 boost::shared_ptr<ChannelList> c = channels.reader();
410                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
411
412                         RingBufferNPT<CaptureTransition>::rw_vector transitions;
413                         (*chan)->capture_transition_buf->get_write_vector (&transitions);
414
415                         if (transitions.len[0] > 0) {
416                                 transitions.buf[0]->type = CaptureStart;
417                                 transitions.buf[0]->capture_val = capture_start_frame;
418                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
419                         } else {
420                                 // bad!
421                                 fatal << X_("programming error: capture_transition_buf is full on rec start!  inconceivable!")
422                                         << endmsg;
423                         }
424                 }
425         }
426 }
427
428
429 /** Do some record stuff [not described in this comment!]
430  *
431  *  Also:
432  *    - Setup playback_distance with the nframes, or nframes adjusted
433  *      for current varispeed, if appropriate.
434  *    - Setup current_playback_buffer in each ChannelInfo to point to data
435  *      that someone can read playback_distance worth of data from.
436  */
437 void
438 DiskWriter::run (BufferSet& bufs, framepos_t start_frame, framepos_t end_frame,
439                  double speed, pframes_t nframes, bool result_required)
440 {
441         uint32_t n;
442         boost::shared_ptr<ChannelList> c = channels.reader();
443         ChannelList::iterator chan;
444         framecnt_t rec_offset = 0;
445         framecnt_t rec_nframes = 0;
446         bool nominally_recording;
447         bool re = record_enabled ();
448         bool can_record = _session.actively_recording ();
449
450         if (_active) {
451                 if (!_pending_active) {
452                         _active = false;
453                         return;
454                 }
455         } else {
456                 if (_pending_active) {
457                         _active = true;
458                 } else {
459                         return;
460                 }
461         }
462
463         _need_butler = false;
464
465         check_record_status (start_frame, can_record);
466
467         if (nframes == 0) {
468                 return;
469         }
470
471         nominally_recording = (can_record && re);
472
473         // Safeguard against situations where process() goes haywire when autopunching
474         // and last_recordable_frame < first_recordable_frame
475
476         if (last_recordable_frame < first_recordable_frame) {
477                 last_recordable_frame = max_framepos;
478         }
479
480         const Location* const loop_loc    = loop_location;
481         framepos_t            loop_start  = 0;
482         framepos_t            loop_end    = 0;
483         framepos_t            loop_length = 0;
484
485         if (loop_loc) {
486                 get_location_times (loop_loc, &loop_start, &loop_end, &loop_length);
487         }
488
489         adjust_capture_position = 0;
490
491         if (nominally_recording || (re && was_recording && _session.get_record_enabled() && (_session.config.get_punch_in() || _session.preroll_record_punch_enabled()))) {
492
493                 Evoral::OverlapType ot = Evoral::coverage (first_recordable_frame, last_recordable_frame, start_frame, end_frame);
494                 // XXX should this be transport_frame + nframes - 1 ? coverage() expects its parameter ranges to include their end points
495                 // XXX also, first_recordable_frame & last_recordable_frame may both be == max_framepos: coverage() will return OverlapNone in that case. Is thak OK?
496                 calculate_record_range (ot, start_frame, nframes, rec_nframes, rec_offset);
497
498                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1: this time record %2 of %3 frames, offset %4\n", _name, rec_nframes, nframes, rec_offset));
499
500                 if (rec_nframes && !was_recording) {
501                         capture_captured = 0;
502
503                         if (loop_loc) {
504                                 /* Loop recording, so pretend the capture started at the loop
505                                    start rgardless of what time it is now, so the source starts
506                                    at the loop start and can handle time wrapping around.
507                                    Otherwise, start the source right now as usual.
508                                 */
509                                 capture_captured    = start_frame - loop_start;
510                                 capture_start_frame = loop_start;
511                         }
512
513                         if (_midi_write_source) {
514                                 _midi_write_source->mark_write_starting_now (capture_start_frame, capture_captured, loop_length);
515                         }
516
517                         g_atomic_int_set(const_cast<gint*> (&_frames_pending_write), 0);
518                         g_atomic_int_set(const_cast<gint*> (&_num_captured_loops), 0);
519
520                         was_recording = true;
521
522                 }
523
524                 /* For audio: not writing frames to the capture ringbuffer offsets
525                  * the recording. For midi: we need to keep track of the record range
526                  * and subtract the accumulated difference from the event time.
527                  */
528                 if (rec_nframes) {
529                         _accumulated_capture_offset += rec_offset;
530                 } else {
531                         _accumulated_capture_offset += nframes;
532                 }
533
534         }
535
536         if (can_record && !_last_capture_sources.empty()) {
537                 _last_capture_sources.clear ();
538         }
539
540         if (rec_nframes) {
541
542                 /* AUDIO */
543
544                 const size_t n_buffers = bufs.count().n_audio();
545
546                 for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
547
548                         ChannelInfo* chaninfo (*chan);
549                         AudioBuffer& buf (bufs.get_audio (n%n_buffers));
550
551                         chaninfo->buf->get_write_vector (&chaninfo->rw_vector);
552
553                         if (rec_nframes <= (framecnt_t) chaninfo->rw_vector.len[0]) {
554
555                                 Sample *incoming = buf.data (rec_offset);
556                                 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * rec_nframes);
557
558                         } else {
559
560                                 framecnt_t total = chaninfo->rw_vector.len[0] + chaninfo->rw_vector.len[1];
561
562                                 if (rec_nframes > total) {
563                                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 overrun in %2, rec_nframes = %3 total space = %4\n",
564                                                                                     DEBUG_THREAD_SELF, name(), rec_nframes, total));
565                                         Overrun ();
566                                         return;
567                                 }
568
569                                 Sample *incoming = buf.data (rec_offset);
570                                 framecnt_t first = chaninfo->rw_vector.len[0];
571
572                                 memcpy (chaninfo->rw_vector.buf[0], incoming, sizeof (Sample) * first);
573                                 memcpy (chaninfo->rw_vector.buf[1], incoming + first, sizeof (Sample) * (rec_nframes - first));
574                         }
575
576                         chaninfo->buf->increment_write_ptr (rec_nframes);
577
578                 }
579
580                 /* MIDI */
581
582                 // Pump entire port buffer into the ring buffer (TODO: split cycles?)
583                 MidiBuffer& buf    = bufs.get_midi (0);
584                 boost::shared_ptr<MidiTrack> mt = boost::dynamic_pointer_cast<MidiTrack>(_route);
585                 MidiChannelFilter* filter = mt ? &mt->capture_filter() : 0;
586
587                 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
588                         Evoral::Event<MidiBuffer::TimeType> ev(*i, false);
589                         if (ev.time() + rec_offset > rec_nframes) {
590                                 break;
591                         }
592 #ifndef NDEBUG
593                         if (DEBUG_ENABLED(DEBUG::MidiIO)) {
594                                 const uint8_t* __data = ev.buffer();
595                                 DEBUG_STR_DECL(a);
596                                 DEBUG_STR_APPEND(a, string_compose ("mididiskstream %1 capture event @ %2 + %3 sz %4 ", this, ev.time(), start_frame, ev.size()));
597                                 for (size_t i=0; i < ev.size(); ++i) {
598                                         DEBUG_STR_APPEND(a,hex);
599                                         DEBUG_STR_APPEND(a,"0x");
600                                         DEBUG_STR_APPEND(a,(int)__data[i]);
601                                         DEBUG_STR_APPEND(a,' ');
602                                 }
603                                 DEBUG_STR_APPEND(a,'\n');
604                                 DEBUG_TRACE (DEBUG::MidiIO, DEBUG_STR(a).str());
605                         }
606 #endif
607                         /* Write events to the capture buffer in frames from session start,
608                            but ignoring looping so event time progresses monotonically.
609                            The source knows the loop length so it knows exactly where the
610                            event occurs in the series of recorded loops and can implement
611                            any desirable behaviour.  We don't want to send event with
612                            transport time here since that way the source can not
613                            reconstruct their actual time; future clever MIDI looping should
614                            probably be implemented in the source instead of here.
615                         */
616                         const framecnt_t loop_offset = _num_captured_loops * loop_length;
617                         const framepos_t event_time = start_frame + loop_offset - _accumulated_capture_offset + ev.time();
618                         if (event_time < 0 || event_time < first_recordable_frame) {
619                                 /* Event out of range, skip */
620                                 continue;
621                         }
622
623                         if (!filter || !filter->filter(ev.buffer(), ev.size())) {
624                                 _midi_buf->write (event_time, ev.event_type(), ev.size(), ev.buffer());
625                         }
626                 }
627                 g_atomic_int_add(const_cast<gint*>(&_frames_pending_write), nframes);
628
629                 if (buf.size() != 0) {
630                         Glib::Threads::Mutex::Lock lm (_gui_feed_buffer_mutex, Glib::Threads::TRY_LOCK);
631
632                         if (lm.locked ()) {
633                                 /* Copy this data into our GUI feed buffer and tell the GUI
634                                    that it can read it if it likes.
635                                 */
636                                 _gui_feed_buffer.clear ();
637
638                                 for (MidiBuffer::iterator i = buf.begin(); i != buf.end(); ++i) {
639                                         /* This may fail if buf is larger than _gui_feed_buffer, but it's not really
640                                            the end of the world if it does.
641                                         */
642                                         _gui_feed_buffer.push_back ((*i).time() + start_frame, (*i).size(), (*i).buffer());
643                                 }
644                         }
645
646                         DataRecorded (_midi_write_source); /* EMIT SIGNAL */
647                 }
648
649                 capture_captured += rec_nframes;
650                 DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("%1 now captured %2 (by %3)\n", name(), capture_captured, rec_nframes));
651
652         } else {
653
654                 /* not recording this time, but perhaps we were before .. */
655
656                 if (was_recording) {
657                         finish_capture (c);
658                         _accumulated_capture_offset = 0;
659                 }
660         }
661
662         /* AUDIO BUTLER REQUIRED CODE */
663
664         if (_playlists[DataType::AUDIO] && !c->empty()) {
665                 if (((framecnt_t) c->front()->buf->read_space() >= _chunk_frames)) {
666                         _need_butler = true;
667                 }
668         }
669
670         /* MIDI BUTLER REQUIRED CODE */
671
672         if (_playlists[DataType::MIDI] && (_midi_buf->read_space() < _midi_buf->bufsize() / 2)) {
673                 _need_butler = true;
674         }
675
676         // DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 writer run, needs butler = %2\n", name(), _need_butler));
677 }
678
679 void
680 DiskWriter::finish_capture (boost::shared_ptr<ChannelList> c)
681 {
682         was_recording = false;
683         first_recordable_frame = max_framepos;
684         last_recordable_frame = max_framepos;
685
686         if (capture_captured == 0) {
687                 return;
688         }
689
690         if (recordable() && destructive()) {
691                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
692
693                         RingBufferNPT<CaptureTransition>::rw_vector transvec;
694                         (*chan)->capture_transition_buf->get_write_vector(&transvec);
695
696                         if (transvec.len[0] > 0) {
697                                 transvec.buf[0]->type = CaptureEnd;
698                                 transvec.buf[0]->capture_val = capture_captured;
699                                 (*chan)->capture_transition_buf->increment_write_ptr(1);
700                         }
701                         else {
702                                 // bad!
703                                 fatal << string_compose (_("programmer error: %1"), X_("capture_transition_buf is full when stopping record!  inconceivable!")) << endmsg;
704                         }
705                 }
706         }
707
708
709         CaptureInfo* ci = new CaptureInfo;
710
711         ci->start =  capture_start_frame;
712         ci->frames = capture_captured;
713
714         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("Finish capture, add new CI, %1 + %2\n", ci->start, ci->frames));
715
716         /* XXX theoretical race condition here. Need atomic exchange ?
717            However, the circumstances when this is called right
718            now (either on record-disable or transport_stopped)
719            mean that no actual race exists. I think ...
720            We now have a capture_info_lock, but it is only to be used
721            to synchronize in the transport_stop and the capture info
722            accessors, so that invalidation will not occur (both non-realtime).
723         */
724
725         capture_info.push_back (ci);
726         capture_captured = 0;
727
728         /* now we've finished a capture, reset first_recordable_frame for next time */
729         first_recordable_frame = max_framepos;
730 }
731
732 void
733 DiskWriter::set_record_enabled (bool yn)
734 {
735         if (!recordable() || !_session.record_enabling_legal() || record_safe ()) {
736                 return;
737         }
738
739         /* can't rec-enable in destructive mode if transport is before start */
740
741         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
742                 return;
743         }
744
745         /* yes, i know that this not proof against race conditions, but its
746            good enough. i think.
747         */
748
749         if (record_enabled() != yn) {
750                 if (yn) {
751                         engage_record_enable ();
752                 } else {
753                         disengage_record_enable ();
754                 }
755
756                 RecordEnableChanged (); /* EMIT SIGNAL */
757         }
758 }
759
760 void
761 DiskWriter::set_record_safe (bool yn)
762 {
763         if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty()) {
764                 return;
765         }
766
767         /* can't rec-safe in destructive mode if transport is before start ????
768          REQUIRES REVIEW */
769
770         if (destructive() && yn && _session.transport_frame() < _session.current_start_frame()) {
771                 return;
772         }
773
774         /* yes, i know that this not proof against race conditions, but its
775          good enough. i think.
776          */
777
778         if (record_safe () != yn) {
779                 if (yn) {
780                         engage_record_safe ();
781                 } else {
782                         disengage_record_safe ();
783                 }
784
785                 RecordSafeChanged (); /* EMIT SIGNAL */
786         }
787 }
788
789 bool
790 DiskWriter::prep_record_enable ()
791 {
792         if (!recordable() || !_session.record_enabling_legal() || channels.reader()->empty() || record_safe ()) { // REQUIRES REVIEW "|| record_safe ()"
793                 return false;
794         }
795
796         /* can't rec-enable in destructive mode if transport is before start */
797
798         if (destructive() && _session.transport_frame() < _session.current_start_frame()) {
799                 return false;
800         }
801
802         boost::shared_ptr<ChannelList> c = channels.reader();
803
804         capturing_sources.clear ();
805
806         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
807                 capturing_sources.push_back ((*chan)->write_source);
808                 Source::Lock lock((*chan)->write_source->mutex());
809                 (*chan)->write_source->mark_streaming_write_started (lock);
810         }
811
812         return true;
813 }
814
815 bool
816 DiskWriter::prep_record_disable ()
817 {
818         capturing_sources.clear ();
819         return true;
820 }
821
822 float
823 DiskWriter::buffer_load () const
824 {
825         boost::shared_ptr<ChannelList> c = channels.reader();
826
827         if (c->empty ()) {
828                 return 1.0;
829         }
830
831         return (float) ((double) c->front()->buf->write_space()/
832                         (double) c->front()->buf->bufsize());
833 }
834
835 void
836 DiskWriter::set_note_mode (NoteMode m)
837 {
838         _note_mode = m;
839
840         boost::shared_ptr<MidiPlaylist> mp = boost::dynamic_pointer_cast<MidiPlaylist> (_playlists[DataType::MIDI]);
841
842         if (mp) {
843                 mp->set_note_mode (m);
844         }
845
846         if (_midi_write_source && _midi_write_source->model())
847                 _midi_write_source->model()->set_note_mode(m);
848 }
849
850 int
851 DiskWriter::seek (framepos_t frame, bool complete_refill)
852 {
853         uint32_t n;
854         ChannelList::iterator chan;
855         boost::shared_ptr<ChannelList> c = channels.reader();
856
857         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
858                 (*chan)->buf->reset ();
859         }
860
861         _midi_buf->reset ();
862         g_atomic_int_set(&_frames_read_from_ringbuffer, 0);
863         g_atomic_int_set(&_frames_written_to_ringbuffer, 0);
864
865         /* can't rec-enable in destructive mode if transport is before start */
866
867         if (destructive() && record_enabled() && frame < _session.current_start_frame()) {
868                 disengage_record_enable ();
869         }
870
871         playback_sample = frame;
872
873         return 0;
874 }
875
876 int
877 DiskWriter::do_flush (RunContext ctxt, bool force_flush)
878 {
879         uint32_t to_write;
880         int32_t ret = 0;
881         RingBufferNPT<Sample>::rw_vector vector;
882         RingBufferNPT<CaptureTransition>::rw_vector transvec;
883         framecnt_t total;
884
885         transvec.buf[0] = 0;
886         transvec.buf[1] = 0;
887         vector.buf[0] = 0;
888         vector.buf[1] = 0;
889
890         boost::shared_ptr<ChannelList> c = channels.reader();
891         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
892
893                 (*chan)->buf->get_read_vector (&vector);
894
895                 total = vector.len[0] + vector.len[1];
896
897                 if (total == 0 || (total < _chunk_frames && !force_flush && was_recording)) {
898                         goto out;
899                 }
900
901                 /* if there are 2+ chunks of disk i/o possible for
902                    this track, let the caller know so that it can arrange
903                    for us to be called again, ASAP.
904
905                    if we are forcing a flush, then if there is* any* extra
906                    work, let the caller know.
907
908                    if we are no longer recording and there is any extra work,
909                    let the caller know too.
910                 */
911
912                 if (total >= 2 * _chunk_frames || ((force_flush || !was_recording) && total > _chunk_frames)) {
913                         ret = 1;
914                 }
915
916                 to_write = min (_chunk_frames, (framecnt_t) vector.len[0]);
917
918                 // check the transition buffer when recording destructive
919                 // important that we get this after the capture buf
920
921                 if (destructive()) {
922                         (*chan)->capture_transition_buf->get_read_vector(&transvec);
923                         size_t transcount = transvec.len[0] + transvec.len[1];
924                         size_t ti;
925
926                         for (ti=0; ti < transcount; ++ti) {
927                                 CaptureTransition & captrans = (ti < transvec.len[0]) ? transvec.buf[0][ti] : transvec.buf[1][ti-transvec.len[0]];
928
929                                 if (captrans.type == CaptureStart) {
930                                         // by definition, the first data we got above represents the given capture pos
931
932                                         (*chan)->write_source->mark_capture_start (captrans.capture_val);
933                                         (*chan)->curr_capture_cnt = 0;
934
935                                 } else if (captrans.type == CaptureEnd) {
936
937                                         // capture end, the capture_val represents total frames in capture
938
939                                         if (captrans.capture_val <= (*chan)->curr_capture_cnt + to_write) {
940
941                                                 // shorten to make the write a perfect fit
942                                                 uint32_t nto_write = (captrans.capture_val - (*chan)->curr_capture_cnt);
943
944                                                 if (nto_write < to_write) {
945                                                         ret = 1; // should we?
946                                                 }
947                                                 to_write = nto_write;
948
949                                                 (*chan)->write_source->mark_capture_end ();
950
951                                                 // increment past this transition, but go no further
952                                                 ++ti;
953                                                 break;
954                                         }
955                                         else {
956                                                 // actually ends just beyond this chunk, so force more work
957                                                 ret = 1;
958                                                 break;
959                                         }
960                                 }
961                         }
962
963                         if (ti > 0) {
964                                 (*chan)->capture_transition_buf->increment_read_ptr(ti);
965                         }
966                 }
967
968                 if ((!(*chan)->write_source) || (*chan)->write_source->write (vector.buf[0], to_write) != to_write) {
969                         error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
970                         return -1;
971                 }
972
973                 (*chan)->buf->increment_read_ptr (to_write);
974                 (*chan)->curr_capture_cnt += to_write;
975
976                 if ((to_write == vector.len[0]) && (total > to_write) && (to_write < _chunk_frames) && !destructive()) {
977
978                         /* we wrote all of vector.len[0] but it wasn't an entire
979                            disk_write_chunk_frames of data, so arrange for some part
980                            of vector.len[1] to be flushed to disk as well.
981                         */
982
983                         to_write = min ((framecnt_t)(_chunk_frames - to_write), (framecnt_t) vector.len[1]);
984
985                         DEBUG_TRACE (DEBUG::Butler, string_compose ("%1 additional write of %2\n", name(), to_write));
986
987                         if ((*chan)->write_source->write (vector.buf[1], to_write) != to_write) {
988                                 error << string_compose(_("AudioDiskstream %1: cannot write to disk"), id()) << endmsg;
989                                 return -1;
990                         }
991
992                         (*chan)->buf->increment_read_ptr (to_write);
993                         (*chan)->curr_capture_cnt += to_write;
994                 }
995         }
996
997         /* MIDI*/
998
999         if (_midi_write_source) {
1000
1001                 const framecnt_t total = g_atomic_int_get(const_cast<gint*> (&_frames_pending_write));
1002
1003                 if (total == 0 ||
1004                     _midi_buf->read_space() == 0 ||
1005                     (!force_flush && (total < _chunk_frames) && was_recording)) {
1006                         goto out;
1007                 }
1008
1009                 /* if there are 2+ chunks of disk i/o possible for
1010                    this track), let the caller know so that it can arrange
1011                    for us to be called again, ASAP.
1012
1013                    if we are forcing a flush, then if there is* any* extra
1014                    work, let the caller know.
1015
1016                    if we are no longer recording and there is any extra work,
1017                    let the caller know too.
1018                 */
1019
1020                 if (total >= 2 * _chunk_frames || ((force_flush || !was_recording) && total > _chunk_frames)) {
1021                         ret = 1;
1022                 }
1023
1024                 if (force_flush) {
1025                         /* push out everything we have, right now */
1026                         to_write = UINT32_MAX;
1027                 } else {
1028                         to_write = _chunk_frames;
1029                 }
1030
1031                 if (record_enabled() && ((total > _chunk_frames) || force_flush)) {
1032                         Source::Lock lm(_midi_write_source->mutex());
1033                         if (_midi_write_source->midi_write (lm, *_midi_buf, get_capture_start_frame (0), to_write) != to_write) {
1034                                 error << string_compose(_("MidiDiskstream %1: cannot write to disk"), id()) << endmsg;
1035                                 return -1;
1036                         }
1037                         g_atomic_int_add(const_cast<gint*> (&_frames_pending_write), -to_write);
1038                 }
1039         }
1040
1041   out:
1042         return ret;
1043
1044 }
1045
1046 void
1047 DiskWriter::reset_write_sources (bool mark_write_complete, bool /*force*/)
1048 {
1049         ChannelList::iterator chan;
1050         boost::shared_ptr<ChannelList> c = channels.reader();
1051         uint32_t n;
1052
1053         if (!_session.writable() || !recordable()) {
1054                 return;
1055         }
1056
1057         capturing_sources.clear ();
1058
1059         for (chan = c->begin(), n = 0; chan != c->end(); ++chan, ++n) {
1060
1061                 if (!destructive()) {
1062
1063                         if ((*chan)->write_source) {
1064
1065                                 if (mark_write_complete) {
1066                                         Source::Lock lock((*chan)->write_source->mutex());
1067                                         (*chan)->write_source->mark_streaming_write_completed (lock);
1068                                         (*chan)->write_source->done_with_peakfile_writes ();
1069                                 }
1070
1071                                 if ((*chan)->write_source->removable()) {
1072                                         (*chan)->write_source->mark_for_remove ();
1073                                         (*chan)->write_source->drop_references ();
1074                                 }
1075
1076                                 (*chan)->write_source.reset ();
1077                         }
1078
1079                         use_new_write_source (DataType::AUDIO, n);
1080
1081                         if (record_enabled()) {
1082                                 capturing_sources.push_back ((*chan)->write_source);
1083                         }
1084
1085                 } else {
1086
1087                         if ((*chan)->write_source == 0) {
1088                                 use_new_write_source (DataType::AUDIO, n);
1089                         }
1090                 }
1091         }
1092
1093         if (_midi_write_source) {
1094                 if (mark_write_complete) {
1095                         Source::Lock lm(_midi_write_source->mutex());
1096                         _midi_write_source->mark_streaming_write_completed (lm);
1097                 }
1098         }
1099
1100         if (_playlists[DataType::MIDI]) {
1101                 use_new_write_source (DataType::MIDI);
1102         }
1103
1104         if (destructive() && !c->empty ()) {
1105
1106                 /* we now have all our write sources set up, so create the
1107                    playlist's single region.
1108                 */
1109
1110                 if (_playlists[DataType::MIDI]->empty()) {
1111                         setup_destructive_playlist ();
1112                 }
1113         }
1114 }
1115
1116 int
1117 DiskWriter::use_new_write_source (DataType dt, uint32_t n)
1118 {
1119         if (dt == DataType::MIDI) {
1120
1121                 _accumulated_capture_offset = 0;
1122                 _midi_write_source.reset();
1123
1124                 try {
1125                         _midi_write_source = boost::dynamic_pointer_cast<SMFSource>(
1126                                 _session.create_midi_source_for_session (write_source_name ()));
1127
1128                         if (!_midi_write_source) {
1129                                 throw failed_constructor();
1130                         }
1131                 }
1132
1133                 catch (failed_constructor &err) {
1134                         error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1135                         _midi_write_source.reset();
1136                         return -1;
1137                 }
1138         } else {
1139                 boost::shared_ptr<ChannelList> c = channels.reader();
1140
1141                 if (!recordable()) {
1142                         return 1;
1143                 }
1144
1145                 if (n >= c->size()) {
1146                         error << string_compose (_("AudioDiskstream: channel %1 out of range"), n) << endmsg;
1147                         return -1;
1148                 }
1149
1150                 ChannelInfo* chan = (*c)[n];
1151
1152                 try {
1153                         if ((chan->write_source = _session.create_audio_source_for_session (
1154                                      c->size(), write_source_name(), n, destructive())) == 0) {
1155                                 throw failed_constructor();
1156                         }
1157                 }
1158
1159                 catch (failed_constructor &err) {
1160                         error << string_compose (_("%1:%2 new capture file not initialized correctly"), _name, n) << endmsg;
1161                         chan->write_source.reset ();
1162                         return -1;
1163                 }
1164
1165                 /* do not remove destructive files even if they are empty */
1166
1167                 chan->write_source->set_allow_remove_if_empty (!destructive());
1168         }
1169
1170         return 0;
1171 }
1172
1173 void
1174 DiskWriter::transport_stopped_wallclock (struct tm& when, time_t twhen, bool abort_capture)
1175 {
1176         bool more_work = true;
1177         int err = 0;
1178         framecnt_t total_capture;
1179         SourceList audio_srcs;
1180         SourceList midi_srcs;
1181         ChannelList::iterator chan;
1182         vector<CaptureInfo*>::iterator ci;
1183         boost::shared_ptr<ChannelList> c = channels.reader();
1184         uint32_t n = 0;
1185         bool mark_write_completed = false;
1186
1187         finish_capture (c);
1188
1189
1190         /* butler is already stopped, but there may be work to do
1191            to flush remaining data to disk.
1192         */
1193
1194         while (more_work && !err) {
1195                 switch (do_flush (TransportContext, true)) {
1196                 case 0:
1197                         more_work = false;
1198                         break;
1199                 case 1:
1200                         break;
1201                 case -1:
1202                         error << string_compose(_("AudioDiskstream \"%1\": cannot flush captured data to disk!"), _name) << endmsg;
1203                         err++;
1204                 }
1205         }
1206
1207         /* XXX is there anything we can do if err != 0 ? */
1208         Glib::Threads::Mutex::Lock lm (capture_info_lock);
1209
1210         if (capture_info.empty()) {
1211                 return;
1212         }
1213
1214         if (abort_capture) {
1215
1216                 if (destructive()) {
1217                         goto outout;
1218                 }
1219
1220                 for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1221
1222                         if ((*chan)->write_source) {
1223
1224                                 (*chan)->write_source->mark_for_remove ();
1225                                 (*chan)->write_source->drop_references ();
1226                                 (*chan)->write_source.reset ();
1227                         }
1228
1229                         /* new source set up in "out" below */
1230                 }
1231
1232                 if (_midi_write_source) {
1233                         _midi_write_source->mark_for_remove ();
1234                         _midi_write_source->drop_references ();
1235                         _midi_write_source.reset();
1236                 }
1237
1238                 goto out;
1239         }
1240
1241         for (total_capture = 0, ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1242                 total_capture += (*ci)->frames;
1243         }
1244
1245         /* figure out the name for this take */
1246
1247         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1248
1249                 boost::shared_ptr<AudioFileSource> as = (*chan)->write_source;
1250
1251                 if (as) {
1252                         audio_srcs.push_back (as);
1253                         as->update_header (capture_info.front()->start, when, twhen);
1254                         as->set_captured_for (_name.val());
1255                         as->mark_immutable ();
1256
1257                         if (Config->get_auto_analyse_audio()) {
1258                                 Analyser::queue_source_for_analysis (as, true);
1259                         }
1260
1261                         DEBUG_TRACE (DEBUG::CaptureAlignment, string_compose ("newly captured source %1 length %2\n", as->path(), as->length (0)));
1262                 }
1263
1264                 if (_midi_write_source) {
1265                         midi_srcs.push_back (_midi_write_source);
1266                 }
1267         }
1268
1269
1270         /* MIDI */
1271
1272         if (_midi_write_source) {
1273
1274                 if (_midi_write_source->length (capture_info.front()->start) == 0) {
1275                         /* No data was recorded, so this capture will
1276                            effectively be aborted; do the same as we
1277                            do for an explicit abort.
1278                         */
1279                         if (_midi_write_source) {
1280                                 _midi_write_source->mark_for_remove ();
1281                                 _midi_write_source->drop_references ();
1282                                 _midi_write_source.reset();
1283                         }
1284
1285                         goto out;
1286                 }
1287
1288                 /* phew, we have data */
1289
1290                 Source::Lock source_lock(_midi_write_source->mutex());
1291
1292                 /* figure out the name for this take */
1293
1294                 midi_srcs.push_back (_midi_write_source);
1295
1296                 _midi_write_source->set_timeline_position (capture_info.front()->start);
1297                 _midi_write_source->set_captured_for (_name);
1298
1299                 /* set length in beats to entire capture length */
1300
1301                 BeatsFramesConverter converter (_session.tempo_map(), capture_info.front()->start);
1302                 const Evoral::Beats total_capture_beats = converter.from (total_capture);
1303                 _midi_write_source->set_length_beats (total_capture_beats);
1304
1305                 /* flush to disk: this step differs from the audio path,
1306                    where all the data is already on disk.
1307                 */
1308
1309                 _midi_write_source->mark_midi_streaming_write_completed (source_lock, Evoral::Sequence<Evoral::Beats>::ResolveStuckNotes, total_capture_beats);
1310         }
1311
1312         _last_capture_sources.insert (_last_capture_sources.end(), audio_srcs.begin(), audio_srcs.end());
1313         _last_capture_sources.insert (_last_capture_sources.end(), midi_srcs.begin(), midi_srcs.end());
1314
1315
1316         if (_route) {
1317                 _route->use_captured_sources (audio_srcs, capture_info);
1318                 _route->use_captured_sources (midi_srcs, capture_info);
1319         }
1320
1321         mark_write_completed = true;
1322
1323   out:
1324         reset_write_sources (mark_write_completed);
1325
1326   outout:
1327
1328         for (ci = capture_info.begin(); ci != capture_info.end(); ++ci) {
1329                 delete *ci;
1330         }
1331
1332         capture_info.clear ();
1333         capture_start_frame = 0;
1334 }
1335
1336 void
1337 DiskWriter::transport_looped (framepos_t transport_frame)
1338 {
1339         if (was_recording) {
1340                 // all we need to do is finish this capture, with modified capture length
1341                 boost::shared_ptr<ChannelList> c = channels.reader();
1342
1343                 finish_capture (c);
1344
1345                 // the next region will start recording via the normal mechanism
1346                 // we'll set the start position to the current transport pos
1347                 // no latency adjustment or capture offset needs to be made, as that already happened the first time
1348                 capture_start_frame = transport_frame;
1349                 first_recordable_frame = transport_frame; // mild lie
1350                 last_recordable_frame = max_framepos;
1351                 was_recording = true;
1352
1353                 if (recordable() && destructive()) {
1354                         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1355
1356                                 RingBufferNPT<CaptureTransition>::rw_vector transvec;
1357                                 (*chan)->capture_transition_buf->get_write_vector(&transvec);
1358
1359                                 if (transvec.len[0] > 0) {
1360                                         transvec.buf[0]->type = CaptureStart;
1361                                         transvec.buf[0]->capture_val = capture_start_frame;
1362                                         (*chan)->capture_transition_buf->increment_write_ptr(1);
1363                                 }
1364                                 else {
1365                                         // bad!
1366                                         fatal << X_("programming error: capture_transition_buf is full on rec loop!  inconceivable!")
1367                                               << endmsg;
1368                                 }
1369                         }
1370                 }
1371
1372         }
1373
1374         /* Here we only keep track of the number of captured loops so monotonic
1375            event times can be delivered to the write source in process().  Trying
1376            to be clever here is a world of trouble, it is better to simply record
1377            the input in a straightforward non-destructive way.  In the future when
1378            we want to implement more clever MIDI looping modes it should be done in
1379            the Source and/or entirely after the capture is finished.
1380         */
1381         if (was_recording) {
1382                 g_atomic_int_add(const_cast<gint*> (&_num_captured_loops), 1);
1383         }
1384 }
1385
1386 void
1387 DiskWriter::setup_destructive_playlist ()
1388 {
1389         SourceList srcs;
1390         boost::shared_ptr<ChannelList> c = channels.reader();
1391
1392         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1393                 srcs.push_back ((*chan)->write_source);
1394         }
1395
1396         /* a single full-sized region */
1397
1398         assert (!srcs.empty ());
1399
1400         PropertyList plist;
1401         plist.add (Properties::name, _name.val());
1402         plist.add (Properties::start, 0);
1403         plist.add (Properties::length, max_framepos - srcs.front()->natural_position());
1404
1405         boost::shared_ptr<Region> region (RegionFactory::create (srcs, plist));
1406         _playlists[DataType::AUDIO]->add_region (region, srcs.front()->natural_position());
1407
1408         /* apply region properties and update write sources */
1409         use_destructive_playlist();
1410 }
1411
1412 void
1413 DiskWriter::use_destructive_playlist ()
1414 {
1415         /* this is called from the XML-based constructor or ::set_destructive. when called,
1416            we already have a playlist and a region, but we need to
1417            set up our sources for write. we use the sources associated
1418            with the (presumed single, full-extent) region.
1419         */
1420
1421         boost::shared_ptr<Region> rp;
1422         {
1423                 const RegionList& rl (_playlists[DataType::AUDIO]->region_list_property().rlist());
1424                 if (rl.size() > 0) {
1425                         /* this can happen when dragging a region onto a tape track */
1426                         assert((rl.size() == 1));
1427                         rp = rl.front();
1428                 }
1429         }
1430
1431         if (!rp) {
1432                 reset_write_sources (false, true);
1433                 return;
1434         }
1435
1436         boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion> (rp);
1437
1438         if (region == 0) {
1439                 throw failed_constructor();
1440         }
1441
1442         /* be sure to stretch the region out to the maximum length (non-musical)*/
1443
1444         region->set_length (max_framepos - region->position(), 0);
1445
1446         uint32_t n;
1447         ChannelList::iterator chan;
1448         boost::shared_ptr<ChannelList> c = channels.reader();
1449
1450         for (n = 0, chan = c->begin(); chan != c->end(); ++chan, ++n) {
1451                 (*chan)->write_source = boost::dynamic_pointer_cast<AudioFileSource>(region->source (n));
1452                 assert((*chan)->write_source);
1453                 (*chan)->write_source->set_allow_remove_if_empty (false);
1454
1455                 /* this might be false if we switched modes, so force it */
1456
1457 #ifdef XXX_OLD_DESTRUCTIVE_API_XXX
1458                 (*chan)->write_source->set_destructive (true);
1459 #else
1460                 // should be set when creating the source or loading the state
1461                 assert ((*chan)->write_source->destructive());
1462 #endif
1463         }
1464
1465         /* the source list will never be reset for a destructive track */
1466 }
1467
1468 void
1469 DiskWriter::adjust_buffering ()
1470 {
1471         boost::shared_ptr<ChannelList> c = channels.reader();
1472
1473         for (ChannelList::iterator chan = c->begin(); chan != c->end(); ++chan) {
1474                 (*chan)->resize (_session.butler()->audio_diskstream_capture_buffer_size());
1475         }
1476 }
1477
1478 void
1479 DiskWriter::realtime_handle_transport_stopped ()
1480 {
1481         realtime_speed_change ();
1482 }
1483
1484 bool
1485 DiskWriter::set_name (string const & str)
1486 {
1487         string my_name = X_("recorder:");
1488         my_name += str;
1489
1490         if (_name != my_name) {
1491                 SessionObject::set_name (my_name);
1492         }
1493
1494         return true;
1495 }
1496
1497 std::string
1498 DiskWriter::steal_write_source_name ()
1499 {
1500         if (_playlists[DataType::MIDI]) {
1501                 string our_old_name = _midi_write_source->name();
1502
1503                 /* this will bump the name of the current write source to the next one
1504                  * (e.g. "MIDI 1-1" gets renamed to "MIDI 1-2"), thus leaving the
1505                  * current write source name (e.g. "MIDI 1-1" available). See the
1506                  * comments in Session::create_midi_source_by_stealing_name() about why
1507                  * we do this.
1508                  */
1509
1510                 try {
1511                         string new_path = _session.new_midi_source_path (name());
1512
1513                         if (_midi_write_source->rename (new_path)) {
1514                                 return string();
1515                         }
1516                 } catch (...) {
1517                         return string ();
1518                 }
1519
1520                 return our_old_name;
1521         }
1522
1523         return std::string();
1524 }
1525
1526 bool
1527 DiskWriter::configure_io (ChanCount in, ChanCount out)
1528 {
1529         if (!DiskIOProcessor::configure_io (in, out)) {
1530                 return false;
1531         }
1532
1533         reset_write_sources (false, true);
1534
1535         return true;
1536 }