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