56bdc82ff7a8b93df46e0b6ff076857db8d4fe69
[ardour.git] / gtk2_ardour / editor_audio_import.cc
1 /*
2     Copyright (C) 2000-2006 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     $Id$
19 */
20
21 #include <pbd/pthread_utils.h>
22 #include <pbd/basename.h>
23
24 #include <gtkmm2ext/choice.h>
25
26 #include <ardour/session.h>
27 #include <ardour/audioplaylist.h>
28 #include <ardour/audioregion.h>
29 #include <ardour/audio_diskstream.h>
30 #include <ardour/utils.h>
31 #include <ardour/audio_track.h>
32 #include <ardour/audioplaylist.h>
33 #include <ardour/audiofilesource.h>
34 #include <ardour/region_factory.h>
35 #include <ardour/source_factory.h>
36 #include <pbd/memento_command.h>
37
38 #include "ardour_ui.h"
39 #include "editor.h"
40 #include "sfdb_ui.h"
41 #include "editing.h"
42 #include "audio_time_axis.h"
43
44 #include "i18n.h"
45
46 using namespace std;
47 using namespace ARDOUR;
48 using namespace PBD;
49 using namespace sigc;
50 using namespace Gtk;
51 using namespace Editing;
52
53 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
54
55 void
56 Editor::add_external_audio_action (ImportMode mode)
57 {
58         nframes_t& pos = edit_cursor->current_frame;
59         AudioTrack* track = 0;
60
61         if (!selection->tracks.empty()) {
62                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
63                 if (atv) {
64                         track = atv->audio_track();
65                 }
66         }
67
68         bring_in_external_audio (mode, track, pos, false);
69 }
70
71 void
72 Editor::bring_in_external_audio (ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
73 {
74         if (session == 0) {
75                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
76                 msg.run ();
77                 return;
78         }
79
80         SoundFileOmega sfdb (_("Add existing audio to session"), session);
81         sfdb.set_mode (mode);
82
83         switch (sfdb.run()) {
84         case SoundFileOmega::ResponseImport:
85                 do_import (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
86                 break;
87                 
88         case SoundFileOmega::ResponseEmbed:
89                 do_embed (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
90                 break;
91
92         default:
93                 break;
94         }
95 }
96
97 void
98 Editor::do_import (vector<Glib::ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
99 {
100         /* SFDB sets "multichan" to true to indicate "split channels"
101            so reverse the setting to match the way libardour
102            interprets it.
103         */
104         
105         import_status.multichan = !split;
106
107         if (interthread_progress_window == 0) {
108                 build_interthread_progress_window ();
109         }
110         
111         /* for each path that was selected, import it and then potentially create a new track
112            containing the new region as the sole contents.
113         */
114
115         for (vector<Glib::ustring>::iterator i = paths.begin(); i != paths.end(); ++i ) {
116                 import_sndfile (*i, mode, track, pos);
117         }
118
119         interthread_progress_window->hide_all ();
120 }
121
122 void
123 Editor::do_embed (vector<Glib::ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
124 {
125         bool multiple_files = paths.size() > 1;
126         bool check_sample_rate = true;
127         vector<Glib::ustring>::iterator i;
128         
129         for (i = paths.begin(); i != paths.end(); ++i) {
130                 int ret = embed_sndfile (*i, split, multiple_files, check_sample_rate, mode, track, pos, prompt);
131
132                 if (ret < -1) {
133                         break;
134                 }
135         }
136
137         if (i == paths.end()) {
138                 session->save_state ("");
139         }
140 }
141
142 int
143 Editor::import_sndfile (Glib::ustring path, ImportMode mode, AudioTrack* track, nframes_t& pos)
144 {
145         interthread_progress_window->set_title (string_compose (_("ardour: importing %1"), path));
146         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
147         interthread_progress_window->show_all ();
148         interthread_progress_bar.set_fraction (0.0f);
149         interthread_cancel_label.set_text (_("Cancel Import"));
150         current_interthread_info = &import_status;
151
152         import_status.pathname = path;
153         import_status.done = false;
154         import_status.cancel = false;
155         import_status.freeze = false;
156         import_status.done = 0.0;
157         
158         interthread_progress_connection = Glib::signal_timeout().connect 
159                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
160         
161         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
162         ARDOUR_UI::instance()->flush_pending ();
163
164         /* start import thread for this path. this will ultimately call Session::import_audiofile()
165            and if successful will add the file as a region to the session region list.
166         */
167         
168         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
169         pthread_detach (import_status.thread);
170         
171         while (!(import_status.done || import_status.cancel)) {
172                 gtk_main_iteration ();
173         }
174         
175         import_status.done = true;
176         interthread_progress_connection.disconnect ();
177         
178         /* import thread finished - see if we should build a new track */
179         
180         if (!import_status.new_regions.empty()) {
181                 boost::shared_ptr<AudioRegion> region (import_status.new_regions.front());
182                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), track, pos, mode);
183         }
184
185         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
186         return 0;
187 }
188
189 int
190 Editor::embed_sndfile (Glib::ustring path, bool split, bool multiple_files, bool& check_sample_rate, ImportMode mode, 
191                        AudioTrack* track, nframes_t& pos, bool prompt)
192 {
193         boost::shared_ptr<AudioFileSource> source;
194         SourceList sources;
195         boost::shared_ptr<AudioRegion> region;
196         string idspec;
197         string linked_path;
198         SoundFileInfo finfo;
199         string region_name;
200         uint32_t input_chan;
201         uint32_t output_chan;
202
203         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
204         ARDOUR_UI::instance()->flush_pending ();
205
206         /* lets see if we can link it into the session */
207         
208         linked_path = session->sound_dir();
209         linked_path += Glib::path_get_basename (path);
210
211         if (link (path.c_str(), linked_path.c_str()) == 0) {
212
213                 /* there are many reasons why link(2) might have failed.
214                    but if it succeeds, we now have a link in the
215                    session sound dir that will protect against
216                    unlinking of the original path. nice.
217                 */
218
219                 path = linked_path;
220         }
221
222         /* note that we temporarily truncated _id at the colon */
223
224         string error_msg;
225
226         if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
227                 error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), selection, error_msg ) << endmsg;
228                 return 0;
229         }
230         
231         if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
232                 vector<string> choices;
233                 
234                 if (multiple_files) {
235                         choices.push_back (_("Cancel entire import"));
236                         choices.push_back (_("Don't embed it"));
237                         choices.push_back (_("Embed all without questions"));
238                 } else {
239                         choices.push_back (_("Cancel"));
240                 }
241
242                 choices.push_back (_("Embed it anyway"));
243                 
244                 Gtkmm2ext::Choice rate_choice (
245                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
246                         choices, false);
247                 
248                 switch (rate_choice.run()) {
249                 case 0: /* stop a multi-file import */
250                 case 1: /* don't import this one */
251                         return -1;
252                 case 2: /* do it, and the rest without asking */
253                         check_sample_rate = false;
254                         break;
255                 case 3: /* do it */
256                         break;
257                 default:
258                         return -2;
259                 }
260         }
261         
262         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
263         ARDOUR_UI::instance()->flush_pending ();
264         
265         /* make the proper number of channels in the region */
266
267         for (int n = 0; n < finfo.channels; ++n)
268         {
269                 idspec = path;
270                 idspec += string_compose(":%1", n);
271                 
272                 try {
273                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
274                                                                                (*session, idspec, 
275                                                                                 (mode == ImportAsTapeTrack ? 
276                                                                                  AudioFileSource::Destructive : 
277                                                                                  AudioFileSource::Flag (0))));
278                         sources.push_back(source);
279                 } 
280                 
281                 catch (failed_constructor& err) {
282                         error << string_compose(_("could not open %1"), path) << endmsg;
283                         goto out;
284                 }
285                 
286                 ARDOUR_UI::instance()->flush_pending ();
287         }
288         
289         if (sources.empty()) {
290                 goto out;
291         }
292
293         if (sources[0]->natural_position() != 0) {
294                 pos = sources[0]->natural_position();
295         } 
296
297         region_name = PBD::basename_nosuffix (path);
298         region_name += "-0";
299         
300         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
301                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
302         
303         input_chan = finfo.channels;
304         
305         if (Config->get_output_auto_connect() & AutoConnectMaster) {
306                 output_chan = (session->master_out() ? session->master_out()->n_inputs() : input_chan);
307         } else {
308                 output_chan = input_chan;
309         }
310         
311         finish_bringing_in_audio (region, input_chan, output_chan, track, pos, mode);
312         
313   out:
314         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
315         return 0;
316 }
317
318 int
319 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, AudioTrack* track, nframes_t& pos, ImportMode mode)
320 {
321         switch (mode) {
322         case ImportAsRegion:
323                 /* relax, its been done */
324                 break;
325                 
326         case ImportToTrack:
327                 if (track) {
328                         boost::shared_ptr<Playlist> playlist = track->diskstream()->playlist();
329                         
330                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
331                         begin_reversible_command (_("insert sndfile"));
332                         XMLNode &before = playlist->get_state();
333                         playlist->add_region (copy, pos);
334                         session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
335                         commit_reversible_command ();
336
337                         pos += region->length();
338                 }
339                 break;
340                 
341         case ImportAsTrack:
342         { 
343                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
344                 if (!at.empty()) {
345                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
346                         at.front()->diskstream()->playlist()->add_region (copy, pos);
347                 }
348                 break;
349         }
350
351         case ImportAsTapeTrack:
352         {
353                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
354                 if (!at.empty()) {
355                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
356                         at.front()->diskstream()->playlist()->add_region (copy, pos);
357                 }
358                 break;
359         }
360         }
361
362         return 0;
363 }
364
365 void *
366 Editor::_import_thread (void *arg)
367 {
368         PBD::ThreadCreated (pthread_self(), X_("Import"));
369
370         Editor *ed = (Editor *) arg;
371         return ed->import_thread ();
372 }
373
374 void *
375 Editor::import_thread ()
376 {
377         session->import_audiofile (import_status);
378         pthread_exit_pbd (0);
379         /*NOTREACHED*/
380         return 0;
381 }
382
383 gint
384 Editor::import_progress_timeout (void *arg)
385 {
386         interthread_progress_label.set_text (import_status.doing_what);
387
388         if (import_status.freeze) {
389                 interthread_cancel_button.set_sensitive(false);
390         } else {
391                 interthread_cancel_button.set_sensitive(true);
392         }
393
394         if (import_status.doing_what == "building peak files") {
395                 interthread_progress_bar.pulse ();
396                 return FALSE;
397         } else {
398                 interthread_progress_bar.set_fraction (import_status.progress);
399         }
400
401         return !(import_status.done || import_status.cancel);
402 }
403