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