Optimize automation-event process splitting
[ardour.git] / gtk2_ardour / editor_export_audio.cc
1 /*
2     Copyright (C) 2001 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 /* Note: public Editor methods are documented in public_editor.h */
21
22 #include <inttypes.h>
23 #include <unistd.h>
24 #include <climits>
25
26 #include <gtkmm/messagedialog.h>
27
28 #include "pbd/gstdio_compat.h"
29
30 #include "pbd/pthread_utils.h"
31
32 #include "ardour/audio_track.h"
33 #include "ardour/audiofilesource.h"
34 #include "ardour/audioplaylist.h"
35 #include "ardour/audioregion.h"
36 #include "ardour/chan_count.h"
37 #include "ardour/midi_region.h"
38 #include "ardour/session.h"
39 #include "ardour/session_directory.h"
40 #include "ardour/source_factory.h"
41 #include "ardour/types.h"
42
43 #include "audio_region_view.h"
44 #include "audio_time_axis.h"
45 #include "editor.h"
46 #include "export_dialog.h"
47 #include "midi_export_dialog.h"
48 #include "midi_region_view.h"
49 #include "public_editor.h"
50 #include "selection.h"
51 #include "time_axis_view.h"
52 #include "utils.h"
53
54 #include "pbd/i18n.h"
55
56 using namespace std;
57 using namespace ARDOUR;
58 using namespace PBD;
59 using namespace Gtk;
60
61 void
62 Editor::export_audio ()
63 {
64         ExportDialog dialog (*this, _("Export"), ExportProfileManager::RegularExport);
65         dialog.set_session (_session);
66         dialog.run();
67 }
68
69 void
70 Editor::stem_export ()
71 {
72         StemExportDialog dialog (*this);
73         dialog.set_session (_session);
74         dialog.run();
75 }
76
77 void
78 Editor::export_selection ()
79 {
80         ExportSelectionDialog dialog (*this);
81         dialog.set_session (_session);
82         dialog.run();
83 }
84
85 void
86 Editor::export_range ()
87 {
88         ArdourMarker* marker;
89
90         if ((marker = reinterpret_cast<ArdourMarker *> (marker_menu_item->get_data ("marker"))) == 0) {
91                 fatal << _("programming error: marker canvas item has no marker object pointer!") << endmsg;
92                 abort(); /*NOTREACHED*/
93         }
94
95         Location* l;
96         bool is_start;
97
98         if (((l = find_location_from_marker (marker, is_start)) != 0) && (l->end() > l->start())) {
99                 ExportRangeDialog dialog (*this, l->id().to_s());
100                 dialog.set_session (_session);
101                 dialog.run();
102         }
103 }
104
105 bool
106 Editor::process_midi_export_dialog (MidiExportDialog& dialog, boost::shared_ptr<MidiRegion> midi_region)
107 {
108         string path = dialog.get_path ();
109
110         if (Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
111                 bool overwrite = ARDOUR_UI_UTILS::overwrite_file_dialog (dialog,
112                                                                          _("Confirm MIDI File Overwrite"),
113                                                                          _("A file with the same name already exists. Do you want to overwrite it?"));
114
115                 if (!overwrite) {
116                         return false;
117                 }
118
119                 /* force ::g_unlink because the backend code will
120                    go wrong if it tries to open an existing
121                    file for writing.
122                 */
123                 ::g_unlink (path.c_str());
124         }
125
126         return midi_region->do_export (path);
127 }
128
129 /** Export the first selected region */
130 void
131 Editor::export_region ()
132 {
133         if (selection->regions.empty()) {
134                 return;
135         }
136
137         boost::shared_ptr<Region> r = selection->regions.front()->region();
138         boost::shared_ptr<AudioRegion> audio_region = boost::dynamic_pointer_cast<AudioRegion>(r);
139         boost::shared_ptr<MidiRegion> midi_region = boost::dynamic_pointer_cast<MidiRegion>(r);
140
141         if (audio_region) {
142
143                 RouteTimeAxisView & rtv (dynamic_cast<RouteTimeAxisView &> (selection->regions.front()->get_time_axis_view()));
144                 AudioTrack & track (dynamic_cast<AudioTrack &> (*rtv.route()));
145
146                 ExportRegionDialog dialog (*this, *(audio_region.get()), track);
147                 dialog.set_session (_session);
148                 dialog.run ();
149
150         } else if (midi_region) {
151
152                 MidiExportDialog dialog (*this, midi_region);
153                 dialog.set_session (_session);
154
155                 bool finished = false;
156                 while (!finished) {
157                         switch (dialog.run ()) {
158                         case Gtk::RESPONSE_ACCEPT:
159                                 finished = process_midi_export_dialog (dialog, midi_region);
160                                 break;
161                         default:
162                                 return;
163                         }
164                 }
165         }
166 }
167
168 int
169 Editor::write_region_selection (RegionSelection& regions)
170 {
171         for (RegionSelection::iterator i = regions.begin(); i != regions.end(); ++i) {
172                 AudioRegionView* arv = dynamic_cast<AudioRegionView*>(*i);
173                 if (arv) {
174                         if (write_region ("", arv->audio_region()) == false)
175                                 return -1;
176                 }
177
178                 MidiRegionView* mrv = dynamic_cast<MidiRegionView*>(*i);
179                 if (mrv) {
180                         warning << "MIDI region export not implemented" << endmsg;
181                 }
182         }
183
184         return 0;
185 }
186
187 void
188 Editor::bounce_region_selection (bool with_processing)
189 {
190         /* no need to check for bounceable() because this operation never puts
191          * its results back in the playlist (only in the region list).
192          */
193
194         for (RegionSelection::iterator i = selection->regions.begin(); i != selection->regions.end(); ++i) {
195
196                 boost::shared_ptr<Region> region ((*i)->region());
197                 RouteTimeAxisView* rtv = dynamic_cast<RouteTimeAxisView*>(&(*i)->get_time_axis_view());
198                 boost::shared_ptr<Track> track = boost::dynamic_pointer_cast<Track> (rtv->route());
199
200                 InterThreadInfo itt;
201
202                 boost::shared_ptr<Region> r;
203
204                 if (with_processing) {
205                         r = track->bounce_range (region->position(), region->position() + region->length(), itt, track->main_outs(), false);
206                 } else {
207                         r = track->bounce_range (region->position(), region->position() + region->length(), itt, boost::shared_ptr<Processor>(), false);
208                 }
209         }
210 }
211
212 bool
213 Editor::write_region (string path, boost::shared_ptr<AudioRegion> region)
214 {
215         boost::shared_ptr<AudioFileSource> fs;
216         const samplepos_t chunk_size = 4096;
217         samplepos_t to_read;
218         Sample buf[chunk_size];
219         gain_t gain_buffer[chunk_size];
220         samplepos_t pos;
221         char s[PATH_MAX+1];
222         uint32_t cnt;
223         vector<boost::shared_ptr<AudioFileSource> > sources;
224         uint32_t nchans;
225
226         const string sound_directory = _session->session_directory().sound_path();
227
228         nchans = region->n_channels();
229
230         /* don't do duplicate of the entire source if that's what is going on here */
231
232         if (region->start() == 0 && region->length() == region->source_length(0)) {
233                 /* XXX should link(2) to create a new inode with "path" */
234                 return true;
235         }
236
237         if (path.length() == 0) {
238
239                 for (uint32_t n=0; n < nchans; ++n) {
240
241                         for (cnt = 0; cnt < 999999; ++cnt) {
242                                 if (nchans == 1) {
243                                         snprintf (s, sizeof(s), "%s/%s_%" PRIu32 ".wav", sound_directory.c_str(),
244                                                   legalize_for_path(region->name()).c_str(), cnt);
245                                 }
246                                 else {
247                                         snprintf (s, sizeof(s), "%s/%s_%" PRIu32 "-%" PRId32 ".wav", sound_directory.c_str(),
248                                                   legalize_for_path(region->name()).c_str(), cnt, n);
249                                 }
250
251                                 path = s;
252
253                                 if (!Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
254                                         break;
255                                 }
256                         }
257
258                         if (cnt == 999999) {
259                                 error << "" << endmsg;
260                                 goto error_out;
261                         }
262
263
264
265                         try {
266                                 fs = boost::dynamic_pointer_cast<AudioFileSource> (
267                                         SourceFactory::createWritable (DataType::AUDIO, *_session,
268                                                                        path, true,
269                                                                        false, _session->sample_rate()));
270                         }
271
272                         catch (failed_constructor& err) {
273                                 goto error_out;
274                         }
275
276                         sources.push_back (fs);
277                 }
278         }
279         else {
280                 /* TODO: make filesources based on passed path */
281
282         }
283
284         to_read = region->length();
285         pos = region->position();
286
287         while (to_read) {
288                 samplepos_t this_time;
289
290                 this_time = min (to_read, chunk_size);
291
292                 for (vector<boost::shared_ptr<AudioFileSource> >::iterator src=sources.begin(); src != sources.end(); ++src) {
293
294                         fs = (*src);
295
296                         if (region->read_at (buf, buf, gain_buffer, pos, this_time) != this_time) {
297                                 break;
298                         }
299
300                         if (fs->write (buf, this_time) != this_time) {
301                                 error << "" << endmsg;
302                                 goto error_out;
303                         }
304                 }
305
306                 to_read -= this_time;
307                 pos += this_time;
308         }
309
310         time_t tnow;
311         struct tm* now;
312         time (&tnow);
313         now = localtime (&tnow);
314
315         for (vector<boost::shared_ptr<AudioFileSource> >::iterator src = sources.begin(); src != sources.end(); ++src) {
316                 (*src)->update_header (0, *now, tnow);
317                 (*src)->mark_immutable ();
318         }
319
320         return true;
321
322 error_out:
323
324         for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = sources.begin(); i != sources.end(); ++i) {
325                 (*i)->mark_for_remove ();
326         }
327
328         return 0;
329 }
330
331 int
332 Editor::write_audio_selection (TimeSelection& ts)
333 {
334         int ret = 0;
335
336         if (selection->tracks.empty()) {
337                 return 0;
338         }
339
340         for (TrackSelection::iterator i = selection->tracks.begin(); i != selection->tracks.end(); ++i) {
341
342                 AudioTimeAxisView* atv;
343
344                 if ((atv = dynamic_cast<AudioTimeAxisView*>(*i)) == 0) {
345                         continue;
346                 }
347
348                 if (atv->is_audio_track()) {
349
350                         boost::shared_ptr<AudioPlaylist> playlist = boost::dynamic_pointer_cast<AudioPlaylist>(atv->track()->playlist());
351
352                         if (playlist && write_audio_range (*playlist, atv->track()->n_channels(), ts) == 0) {
353                                 ret = -1;
354                                 break;
355                         }
356                 }
357         }
358
359         return ret;
360 }
361
362 bool
363 Editor::write_audio_range (AudioPlaylist& playlist, const ChanCount& count, list<AudioRange>& range)
364 {
365         boost::shared_ptr<AudioFileSource> fs;
366         const samplepos_t chunk_size = 4096;
367         samplepos_t nframes;
368         Sample buf[chunk_size];
369         gain_t gain_buffer[chunk_size];
370         samplepos_t pos;
371         char s[PATH_MAX+1];
372         uint32_t cnt;
373         string path;
374         vector<boost::shared_ptr<AudioFileSource> > sources;
375
376         const string sound_directory = _session->session_directory().sound_path();
377
378         uint32_t channels = count.n_audio();
379
380         for (uint32_t n=0; n < channels; ++n) {
381
382                 for (cnt = 0; cnt < 999999; ++cnt) {
383                         if (channels == 1) {
384                                 snprintf (s, sizeof(s), "%s/%s_%" PRIu32 ".wav", sound_directory.c_str(),
385                                           legalize_for_path(playlist.name()).c_str(), cnt);
386                         }
387                         else {
388                                 snprintf (s, sizeof(s), "%s/%s_%" PRIu32 "-%" PRId32 ".wav", sound_directory.c_str(),
389                                           legalize_for_path(playlist.name()).c_str(), cnt, n);
390                         }
391
392                         if (!Glib::file_test (s, Glib::FILE_TEST_EXISTS)) {
393                                 break;
394                         }
395                 }
396
397                 if (cnt == 999999) {
398                         error << "" << endmsg;
399                         goto error_out;
400                 }
401
402                 path = s;
403
404                 try {
405                         fs = boost::dynamic_pointer_cast<AudioFileSource> (
406                                 SourceFactory::createWritable (DataType::AUDIO, *_session,
407                                                                path, true,
408                                                                false, _session->sample_rate()));
409                 }
410
411                 catch (failed_constructor& err) {
412                         goto error_out;
413                 }
414
415                 sources.push_back (fs);
416
417         }
418
419
420         for (list<AudioRange>::iterator i = range.begin(); i != range.end();) {
421
422                 nframes = (*i).length();
423                 pos = (*i).start;
424
425                 while (nframes) {
426                         samplepos_t this_time;
427
428                         this_time = min (nframes, chunk_size);
429
430                         for (uint32_t n=0; n < channels; ++n) {
431
432                                 fs = sources[n];
433
434                                 if (playlist.read (buf, buf, gain_buffer, pos, this_time, n) != this_time) {
435                                         break;
436                                 }
437
438                                 if (fs->write (buf, this_time) != this_time) {
439                                         goto error_out;
440                                 }
441                         }
442
443                         nframes -= this_time;
444                         pos += this_time;
445                 }
446
447                 list<AudioRange>::iterator tmp = i;
448                 ++tmp;
449
450                 if (tmp != range.end()) {
451
452                         /* fill gaps with silence */
453
454                         nframes = (*tmp).start - (*i).end;
455
456                         while (nframes) {
457
458                                 samplepos_t this_time = min (nframes, chunk_size);
459                                 memset (buf, 0, sizeof (Sample) * this_time);
460
461                                 for (uint32_t n=0; n < channels; ++n) {
462
463                                         fs = sources[n];
464                                         if (fs->write (buf, this_time) != this_time) {
465                                                 goto error_out;
466                                         }
467                                 }
468
469                                 nframes -= this_time;
470                         }
471                 }
472
473                 i = tmp;
474         }
475
476         time_t tnow;
477         struct tm* now;
478         time (&tnow);
479         now = localtime (&tnow);
480
481         for (vector<boost::shared_ptr<AudioFileSource> >::iterator s = sources.begin(); s != sources.end(); ++s) {
482                 (*s)->update_header (0, *now, tnow);
483                 (*s)->mark_immutable ();
484                 // do we need to ref it again?
485         }
486
487         return true;
488
489 error_out:
490         /* unref created files */
491
492         for (vector<boost::shared_ptr<AudioFileSource> >::iterator i = sources.begin(); i != sources.end(); ++i) {
493                 (*i)->mark_for_remove ();
494         }
495
496         return false;
497 }
498
499 void
500 Editor::write_selection ()
501 {
502         if (!selection->time.empty()) {
503                 write_audio_selection (selection->time);
504         } else if (!selection->regions.empty()) {
505                 write_region_selection (selection->regions);
506         }
507 }