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