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