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