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