Merged with trunk R1283.
[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 using Glib::ustring;
53
54 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
55
56 void
57 Editor::add_external_audio_action (ImportMode mode)
58 {
59         nframes_t& pos = edit_cursor->current_frame;
60         AudioTrack* track = 0;
61
62         if (!selection->tracks.empty()) {
63                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.front());
64                 if (atv) {
65                         track = atv->audio_track();
66                 }
67         }
68
69         bring_in_external_audio (mode, track, pos, false);
70 }
71
72 void
73 Editor::bring_in_external_audio (ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
74 {
75         if (session == 0) {
76                 MessageDialog msg (0, _("You can't import or embed an audiofile until you have a session loaded."));
77                 msg.run ();
78                 return;
79         }
80
81         SoundFileOmega sfdb (_("Add existing audio to session"), session);
82         sfdb.set_mode (mode);
83
84         switch (sfdb.run()) {
85         case SoundFileOmega::ResponseImport:
86                 do_import (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
87                 break;
88                 
89         case SoundFileOmega::ResponseEmbed:
90                 do_embed (sfdb.get_paths(), sfdb.get_split(), sfdb.get_mode(), track, pos, prompt);
91                 break;
92
93         default:
94                 break;
95         }
96 }
97
98 void
99 Editor::do_import (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
100 {
101         /* SFDB sets "multichan" to true to indicate "split channels"
102            so reverse the setting to match the way libardour
103            interprets it.
104         */
105         
106         import_status.multichan = !split;
107
108         if (interthread_progress_window == 0) {
109                 build_interthread_progress_window ();
110         }
111
112         vector<ustring> to_import;
113
114         for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
115
116                 to_import.clear ();
117                 to_import.push_back (*a);
118
119                 import_sndfile (to_import, mode, track, pos);
120         }
121
122         interthread_progress_window->hide_all ();
123 }
124
125 void
126 Editor::do_embed (vector<ustring> paths, bool split, ImportMode mode, AudioTrack* track, nframes_t& pos, bool prompt)
127 {
128         bool multiple_files = paths.size() > 1;
129         bool check_sample_rate = true;
130         vector<ustring>::iterator a;
131
132         for (a = paths.begin(); a != paths.end(); ) {
133         
134                 Glib::ustring path = *a;
135                 Glib::ustring pair_base;
136                 vector<ustring> to_embed;
137
138                 to_embed.push_back (path);
139                 a = paths.erase (a);
140
141                 if (path_is_paired (path, pair_base)) {
142
143                         ustring::size_type len = pair_base.length();
144
145                         for (vector<Glib::ustring>::iterator b = paths.begin(); b != paths.end(); ) {
146
147                                 if (((*b).substr (0, len) == pair_base) && ((*b).length() == path.length())) {
148
149                                         to_embed.push_back (*b);
150                                                 
151                                         /* don't process this one again */
152
153                                         b = paths.erase (b);
154                                         break;
155
156                                 } else {
157                                         ++b;
158                                 }
159                         }
160                 }
161
162                 if (to_embed.size() > 1) {
163
164                         vector<string> choices;
165
166                         choices.push_back (string_compose (_("Import as a %1 region"),
167                                                            to_embed.size() > 2 ? _("multichannel") : _("stereo")));
168                         choices.push_back (_("Import as multiple regions"));
169                         
170                         Gtkmm2ext::Choice chooser (string_compose (_("Paired files detected (%1, %2 ...).\nDo you want to:"),
171                                                                    to_embed[0],
172                                                                    to_embed[1]),
173                                                    choices);
174                         
175                         if (chooser.run () == 0) {
176                                 
177                                 /* keep them paired */
178
179                                 if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
180                                         break;
181                                 }
182
183                         } else {
184
185                                 /* one thing per file */
186
187                                 vector<ustring> foo;
188
189                                 for (vector<ustring>::iterator x = to_embed.begin(); x != to_embed.end(); ++x) {
190
191                                         foo.clear ();
192                                         foo.push_back (*x);
193
194                                         if (embed_sndfile (foo, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
195                                                 break;
196                                         }
197                                 }
198                         }
199
200                 } else {
201                         
202                         if (embed_sndfile (to_embed, split, multiple_files, check_sample_rate, mode, track, pos, prompt) < -1) {
203                                 break;
204                         }
205                 }
206         }
207         
208         if (a == paths.end()) {
209                 session->save_state ("");
210         }
211 }
212
213 int
214 Editor::import_sndfile (vector<ustring> paths, ImportMode mode, AudioTrack* track, nframes_t& pos)
215 {
216         interthread_progress_window->set_title (string_compose (_("ardour: importing %1"), paths.front()));
217         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
218         interthread_progress_window->show_all ();
219         interthread_progress_bar.set_fraction (0.0f);
220         interthread_cancel_label.set_text (_("Cancel Import"));
221         current_interthread_info = &import_status;
222
223         import_status.paths = paths;
224         import_status.done = false;
225         import_status.cancel = false;
226         import_status.freeze = false;
227         import_status.done = 0.0;
228         
229         interthread_progress_connection = Glib::signal_timeout().connect 
230                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
231         
232         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
233         ARDOUR_UI::instance()->flush_pending ();
234
235         /* start import thread for this spec. this will ultimately call Session::import_audiofile()
236            and if successful will add the file(s) as a region to the session region list.
237         */
238         
239         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
240         pthread_detach (import_status.thread);
241         
242         while (!(import_status.done || import_status.cancel)) {
243                 gtk_main_iteration ();
244         }
245         
246         import_status.done = true;
247         interthread_progress_connection.disconnect ();
248         
249         /* import thread finished - see if we should build a new track */
250         
251         if (!import_status.new_regions.empty()) {
252                 boost::shared_ptr<AudioRegion> region = boost::dynamic_pointer_cast<AudioRegion>(import_status.new_regions.front());
253                 finish_bringing_in_audio (region, region->n_channels(), region->n_channels(), track, pos, mode);
254         }
255
256         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
257         return 0;
258 }
259
260 int
261 Editor::embed_sndfile (vector<Glib::ustring> paths, bool split, bool multiple_files, bool& check_sample_rate, ImportMode mode, 
262                        AudioTrack* track, nframes_t& pos, bool prompt)
263 {
264         boost::shared_ptr<AudioFileSource> source;
265         SourceList sources;
266         boost::shared_ptr<AudioRegion> region;
267         string idspec;
268         string linked_path;
269         SoundFileInfo finfo;
270         ustring region_name;
271         uint32_t input_chan = 0;
272         uint32_t output_chan = 0;
273
274         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
275         ARDOUR_UI::instance()->flush_pending ();
276
277         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
278
279                 ustring path = *p;
280
281                 /* lets see if we can link it into the session */
282                 
283                 linked_path = session->sound_dir();
284                 linked_path += '/';
285                 linked_path += Glib::path_get_basename (path);
286                 
287                 if (link (path.c_str(), linked_path.c_str()) == 0) {
288                         
289                         /* there are many reasons why link(2) might have failed.
290                            but if it succeeds, we now have a link in the
291                            session sound dir that will protect against
292                            unlinking of the original path. nice.
293                         */
294                         
295                         path = linked_path;
296                 }
297                 
298                 /* note that we temporarily truncated _id at the colon */
299                 
300                 string error_msg;
301                 
302                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
303                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), selection, error_msg ) << endmsg;
304                         return 0;
305                 }
306                 
307                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
308                         vector<string> choices;
309                         
310                         if (multiple_files) {
311                                 choices.push_back (_("Cancel entire import"));
312                                 choices.push_back (_("Don't embed it"));
313                                 choices.push_back (_("Embed all without questions"));
314                         } else {
315                                 choices.push_back (_("Cancel"));
316                         }
317                         
318                         choices.push_back (_("Embed it anyway"));
319                         
320                         Gtkmm2ext::Choice rate_choice (
321                                 string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
322                                 choices, false);
323                         
324                         switch (rate_choice.run()) {
325                         case 0: /* stop a multi-file import */
326                         case 1: /* don't import this one */
327                                 return -1;
328                         case 2: /* do it, and the rest without asking */
329                                 check_sample_rate = false;
330                                 break;
331                         case 3: /* do it */
332                                 break;
333                         default:
334                                 return -2;
335                         }
336                 }
337                 
338                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
339                 ARDOUR_UI::instance()->flush_pending ();
340         
341                 /* make the proper number of channels in the region */
342                 
343                 input_chan += finfo.channels;
344         
345                 for (int n = 0; n < finfo.channels; ++n)
346                 {
347                         idspec = path;
348                         idspec += string_compose(":%1", n);
349                         
350                         try {
351                                 source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
352                                                                                        (DataType::AUDIO, *session, idspec, 
353                                                                                         (mode == ImportAsTapeTrack ? 
354                                                                                          AudioFileSource::Destructive : 
355                                                                                          AudioFileSource::Flag (0))));
356                                 sources.push_back(source);
357                         } 
358                         
359                         catch (failed_constructor& err) {
360                                 error << string_compose(_("could not open %1"), path) << endmsg;
361                                 goto out;
362                         }
363                         
364                         ARDOUR_UI::instance()->flush_pending ();
365                 }
366         }
367
368         if (sources.empty()) {
369                 goto out;
370         }
371
372         if (sources[0]->natural_position() != 0) {
373                 pos = sources[0]->natural_position();
374         } 
375
376         region_name = region_name_from_path (paths.front(), (sources.size() > 1));
377         
378         region = boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
379                                                                                   Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
380         
381         if (Config->get_output_auto_connect() & AutoConnectMaster) {
382                 output_chan = (session->master_out() ? session->master_out()->n_inputs().get(DataType::AUDIO) : input_chan);
383         } else {
384                 output_chan = input_chan;
385         }
386
387         finish_bringing_in_audio (region, input_chan, output_chan, track, pos, mode);
388         
389   out:
390         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
391         return 0;
392 }
393
394 int
395 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)
396 {
397         switch (mode) {
398         case ImportAsRegion:
399                 /* relax, its been done */
400                 break;
401                 
402         case ImportToTrack:
403                 if (track) {
404                         boost::shared_ptr<Playlist> playlist = track->diskstream()->playlist();
405                         
406                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
407                         begin_reversible_command (_("insert sndfile"));
408                         XMLNode &before = playlist->get_state();
409                         playlist->add_region (copy, pos);
410                         session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
411                         commit_reversible_command ();
412
413                         pos += region->length();
414                 }
415                 break;
416                 
417         case ImportAsTrack:
418         { 
419                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
420                 if (!at.empty()) {
421                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
422                         at.front()->diskstream()->playlist()->add_region (copy, pos);
423                 }
424                 break;
425         }
426
427         case ImportAsTapeTrack:
428         {
429                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
430                 if (!at.empty()) {
431                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
432                         at.front()->diskstream()->playlist()->add_region (copy, pos);
433                 }
434                 break;
435         }
436         }
437
438         return 0;
439 }
440
441 void *
442 Editor::_import_thread (void *arg)
443 {
444         PBD::ThreadCreated (pthread_self(), X_("Import"));
445
446         Editor *ed = (Editor *) arg;
447         return ed->import_thread ();
448 }
449
450 void *
451 Editor::import_thread ()
452 {
453         session->import_audiofile (import_status);
454         pthread_exit_pbd (0);
455         /*NOTREACHED*/
456         return 0;
457 }
458
459 gint
460 Editor::import_progress_timeout (void *arg)
461 {
462         interthread_progress_label.set_text (import_status.doing_what);
463
464         if (import_status.freeze) {
465                 interthread_cancel_button.set_sensitive(false);
466         } else {
467                 interthread_cancel_button.set_sensitive(true);
468         }
469
470         if (import_status.doing_what == "building peak files") {
471                 interthread_progress_bar.pulse ();
472                 return FALSE;
473         } else {
474                 interthread_progress_bar.set_fraction (import_status.progress);
475         }
476
477         return !(import_status.done || import_status.cancel);
478 }
479