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