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