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