Apply LV2 changes from 2.0.
[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 <sys/time.h>
23 #include <errno.h>
24 #include <unistd.h>
25 #include <algorithm>
26
27 #include <sndfile.h>
28
29 #include <pbd/pthread_utils.h>
30 #include <pbd/basename.h>
31 #include <pbd/shortpath.h>
32
33 #include <gtkmm2ext/choice.h>
34 #include <gtkmm2ext/window_title.h>
35
36 #include <ardour/session.h>
37 #include <ardour/session_directory.h>
38 #include <ardour/audioplaylist.h>
39 #include <ardour/audioregion.h>
40 #include <ardour/audio_diskstream.h>
41 #include <ardour/midi_track.h>
42 #include <ardour/midi_region.h>
43 #include <ardour/utils.h>
44 #include <ardour/audio_track.h>
45 #include <ardour/audioplaylist.h>
46 #include <ardour/audiofilesource.h>
47 #include <ardour/region_factory.h>
48 #include <ardour/source_factory.h>
49 #include <ardour/session.h>
50 #include <pbd/memento_command.h>
51
52 #include "ardour_ui.h"
53 #include "editor.h"
54 #include "sfdb_ui.h"
55 #include "editing.h"
56 #include "audio_time_axis.h"
57 #include "midi_time_axis.h"
58 #include "session_import_dialog.h"
59 #include "utils.h"
60
61 #include "i18n.h"
62
63 using namespace std;
64 using namespace ARDOUR;
65 using namespace PBD;
66 using namespace sigc;
67 using namespace Gtk;
68 using namespace Gtkmm2ext;
69 using namespace Editing;
70 using Glib::ustring;
71
72 /* Functions supporting the incorporation of external (non-captured) audio material into ardour */
73
74 void
75 Editor::add_external_audio_action (ImportMode mode_hint)
76 {
77         if (session == 0) {
78                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
79                 msg.run ();
80                 return;
81         }
82         
83         if (sfbrowser == 0) {
84                 sfbrowser = new SoundFileOmega (*this, _("Add existing media"), session, 0, true, mode_hint);
85         } else {
86                 sfbrowser->set_mode (mode_hint);
87         }
88
89         external_audio_dialog ();
90 }
91
92 void
93 Editor::external_audio_dialog ()
94 {
95         vector<Glib::ustring> paths;
96         uint32_t track_cnt;
97
98         if (session == 0) {
99                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
100                 msg.run ();
101                 return;
102         }
103         
104         track_cnt = 0;
105
106         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
107                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*x);
108                 
109                 if (!atv) {
110                         continue;
111                 } else if (atv->is_audio_track()) {
112                         track_cnt++;
113                 }
114         }
115
116         if (sfbrowser == 0) {
117                 sfbrowser = new SoundFileOmega (*this, _("Add existing media"), session, track_cnt, true);
118         } else {
119                 sfbrowser->reset (track_cnt);
120         }
121
122         sfbrowser->show_all ();
123
124
125         bool keepRunning;
126
127         do {
128                 keepRunning = false;
129
130                 int response = sfbrowser->run ();
131
132                 switch (response) {
133                         case RESPONSE_APPLY:
134                                 // leave the dialog open
135                                 break;
136
137                         case RESPONSE_OK:
138                                 sfbrowser->hide ();
139                                 break;
140
141                         default:
142                                 // cancel from the browser - we are done
143                                 sfbrowser->hide ();
144                                 return;
145                 }
146
147                 /* lets do it */
148
149                 paths = sfbrowser->get_paths ();
150
151                 ImportPosition pos = sfbrowser->get_position ();
152                 ImportMode mode = sfbrowser->get_mode ();
153                 ImportDisposition chns = sfbrowser->get_channel_disposition ();
154                 nframes64_t where;
155
156                 switch (pos) {
157                         case ImportAtEditPoint:
158                                 where = get_preferred_edit_position ();
159                                 break;
160                         case ImportAtTimestamp:
161                                 where = -1;
162                                 break;
163                         case ImportAtPlayhead:
164                                 where = playhead_cursor->current_frame;
165                                 break;
166                         case ImportAtStart:
167                                 where = session->current_start_frame();
168                                 break;
169                 }
170
171                 SrcQuality quality = sfbrowser->get_src_quality();
172
173
174                 if (sfbrowser->copy_files_btn.get_active()) {
175                         do_import (paths, chns, mode, quality, where);
176                 } else {
177                         do_embed (paths, chns, mode, where);
178                 }
179
180                 if (response == RESPONSE_APPLY) {
181                         sfbrowser->clear_selection ();
182                         keepRunning = true;
183                 }
184
185         } while (keepRunning);
186 }
187
188 void
189 Editor::session_import_dialog ()
190 {
191         SessionImportDialog dialog (*session);
192         ensure_float (dialog);
193         dialog.run ();
194 }
195
196 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
197
198 /**
199  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_audiofiles()
200  *
201  * all_or_nothing:
202  *   true  = show "Update", "Import" and "Skip"
203  *   false = show "Import", and "Cancel"
204  *
205  * Returns:
206  *     0  To update an existing source of the same name
207  *     1  To import/embed the file normally (make sure the new name will be unique)
208  *     2  If the user wants to skip this file
209  **/
210 int
211 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
212 {
213         string wave_name (Glib::path_get_basename(path));
214
215         SourceMap all_sources = session->get_sources();
216         bool wave_name_exists = false;
217
218         for (SourceMap::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
219                 string tmp (Glib::path_get_basename (i->second->path()));
220
221                 if (tmp == wave_name) {
222                         wave_name_exists = true;
223                         break;
224                 }
225         }
226
227         int function = 1;
228
229
230         if (wave_name_exists) {
231                 string message;
232                 if (all_or_nothing) {
233                         // updating is still disabled
234                         //message = string_compose(_("The session already contains a source file named %1. Do you want to update that file (and thus all regions using the file) or import this file as a new file?"),wave_name);
235                         message = string_compose(_("The session already contains a source file named %1. This file will be imported as a new file, please confirm."),wave_name);
236                 } else {
237                         message = string_compose(_("A source file %1 already exists. This operation will not update that source but import the file %2 as a new source, please confirm."), wave_name, wave_name);
238
239                 }
240                 MessageDialog dialog(message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
241
242                 if (all_or_nothing) {
243                         // disabled
244                         //dialog.add_button("Update", 0);
245                         dialog.add_button("Import", 1);
246                         dialog.add_button("Skip",   2);
247                 } else {
248                         dialog.add_button("Import", 1);
249                         dialog.add_button("Cancel", 2);
250                 }
251                 
252                 
253                 //dialog.add_button("Skip all", 4); // All or rest?
254
255                 dialog.show();
256
257                 function = dialog.run ();
258
259                 dialog.hide();
260         }
261
262         return function;
263 }
264
265 boost::shared_ptr<AudioTrack>
266 Editor::get_nth_selected_audio_track (int nth) const
267 {
268         AudioTimeAxisView* atv;
269         TrackSelection::iterator x;
270         
271         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
272
273                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
274                 
275                 if (!atv) {
276                         continue;
277                 } else if (atv->is_audio_track()) {
278                         --nth;
279                 }
280         }
281         
282         if (x == selection->tracks.end()) {
283                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
284         } else {
285                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
286         }
287         
288         if (!atv || !atv->is_audio_track()) {
289                 return boost::shared_ptr<AudioTrack>();
290         }
291         
292         return atv->audio_track();
293 }       
294
295 boost::shared_ptr<MidiTrack>
296 Editor::get_nth_selected_midi_track (int nth) const
297 {
298         MidiTimeAxisView* mtv;
299         TrackSelection::iterator x;
300         
301         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
302
303                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
304                 
305                 if (!mtv) {
306                         continue;
307                 } else if (mtv->is_midi_track()) {
308                         --nth;
309                 }
310         }
311         
312         if (x == selection->tracks.end()) {
313                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
314         } else {
315                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
316         }
317         
318         if (!mtv || !mtv->is_midi_track()) {
319                 return boost::shared_ptr<MidiTrack>();
320         }
321         
322         return mtv->midi_track();
323 }       
324
325 bool
326 Editor::idle_do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
327 {
328         _do_import (paths, chns, mode, quality, pos);
329         return false;
330 }
331
332 void
333 Editor::do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
334 {
335 #ifdef GTKOSX
336         Glib::signal_idle().connect (bind (mem_fun (*this, &Editor::idle_do_import), paths, chns, mode, quality, pos));
337 #else
338         _do_import (paths, chns, mode, quality, pos);
339 #endif
340 }
341
342 void
343 Editor::_do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
344 {
345         boost::shared_ptr<Track> track;
346         vector<ustring> to_import;
347         bool ok = true;
348         int nth = 0;
349
350         if (interthread_progress_window == 0) {
351                 build_interthread_progress_window ();
352         }
353
354         if (chns == Editing::ImportMergeFiles) {
355                 /* create 1 region from all paths, add to 1 track,
356                    ignore "track"
357                 */
358                 bool cancel = false;
359                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
360                         int check = check_whether_and_how_to_import(*a, false);
361                         if (check == 2) {
362                                 cancel = true;
363                                 break;
364                         }
365                 }
366
367                 if (!cancel) {
368                         if (import_sndfiles (paths, mode, quality, pos, 1, 1, track, false)) {
369                                 ok = false;
370                         }
371                 }
372
373         } else {
374                 bool replace = false;
375
376                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
377
378                         int check = check_whether_and_how_to_import(*a, true);
379
380                         if (check == 2 ) { 
381                                 // skip
382                                 continue;
383                         }
384
385                         if (check == 0) {
386                                 fatal << "Updating existing sources should be disabled!" << endl;
387                                 replace = true;
388                         } else if (check == 1) {
389                                 replace = false;
390                         }
391                         
392
393                         switch (chns) {
394                                 case Editing::ImportDistinctFiles:
395
396                                         to_import.clear ();
397                                         to_import.push_back (*a);
398
399                                         if (mode == Editing::ImportToTrack) {
400                                                 track = get_nth_selected_audio_track (nth++);
401                                         }
402
403                                         if (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, replace)) {
404                                                 ok = false;
405                                         }
406
407                                         break;
408
409                                 case Editing::ImportDistinctChannels:
410
411                                         to_import.clear ();
412                                         to_import.push_back (*a);
413
414                                         if (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, replace)) {
415                                                 ok = false;
416                                         }
417
418                                         break;
419
420                                 case Editing::ImportSerializeFiles:
421
422                                         to_import.clear ();
423                                         to_import.push_back (*a);
424
425                                         /* create 1 region from this path, add to 1 track,
426                                            reuse "track" across paths
427                                            */
428
429                                         if (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, replace)) {
430                                                 ok = false;
431                                         }
432
433                                         break;
434
435                                 case Editing::ImportMergeFiles:
436                                         // Not entered
437                                         break;
438                         }
439                 }
440
441                 if (ok) {
442                         session->save_state ("");
443                 }
444
445                 interthread_progress_window->hide_all ();
446         }
447 }
448
449 bool
450 Editor::idle_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
451 {
452         _do_embed (paths, chns, mode, pos);
453         return false;
454 }
455
456 void
457 Editor::do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
458 {
459 #ifdef GTKOSX
460         Glib::signal_idle().connect (bind (mem_fun (*this, &Editor::idle_do_embed), paths, chns, mode, pos));
461 #else
462         _do_embed (paths, chns, mode, pos);
463 #endif
464 }
465
466 void
467 Editor::_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
468 {
469         boost::shared_ptr<Track> track;
470         bool check_sample_rate = true;
471         bool ok = false;
472         vector<ustring> to_embed;
473         bool multi = paths.size() > 1;
474         int nth = 0;
475
476         switch (chns) {
477         case Editing::ImportDistinctFiles:
478                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
479
480                         to_embed.clear ();
481                         to_embed.push_back (*a);
482
483                         if (mode == Editing::ImportToTrack) {
484                                 track = get_nth_selected_audio_track (nth++);
485                         }
486
487                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
488                                 goto out;
489                         }
490                 }
491                 break;
492                 
493         case Editing::ImportDistinctChannels:
494                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
495
496                         to_embed.clear ();
497                         to_embed.push_back (*a);
498
499                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
500                                 goto out;
501                         }
502                 }
503                 break;
504
505         case Editing::ImportMergeFiles:
506                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
507                         goto out;
508                 }
509         break;
510
511         case Editing::ImportSerializeFiles:
512                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
513
514                         to_embed.clear ();
515                         to_embed.push_back (*a);
516
517                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
518                                 goto out;
519                         }
520                 }
521                 break;
522         }
523
524         ok = true;
525         
526   out:  
527         if (ok) {
528                 session->save_state ("");
529         }
530 }
531
532 int
533 Editor::import_sndfiles (vector<ustring> paths, ImportMode mode, SrcQuality quality, nframes64_t& pos, 
534                          int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool replace)
535 {
536         WindowTitle title = string_compose (_("importing %1"), paths.front());
537
538         interthread_progress_window->set_title (title.get_string());
539         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
540         interthread_progress_bar.set_fraction (0.0f);
541         interthread_cancel_label.set_text (_("Cancel Import"));
542         current_interthread_info = &import_status;
543
544         import_status.paths = paths;
545         import_status.done = false;
546         import_status.cancel = false;
547         import_status.freeze = false;
548         import_status.done = 0.0;
549         import_status.quality = quality;
550         import_status.replace_existing_source = replace;
551
552         interthread_progress_connection = Glib::signal_timeout().connect 
553                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 500);
554         
555         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
556         ARDOUR_UI::instance()->flush_pending ();
557
558         /* start import thread for this spec. this will ultimately call Session::import_audiofiles()
559            and if successful will add the file(s) as a region to the session region list.
560         */
561         
562         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
563         pthread_detach (import_status.thread);
564         
565         while (!(import_status.done || import_status.cancel)) {
566                 gtk_main_iteration ();
567         }
568
569         interthread_progress_window->hide ();
570         
571         import_status.done = true;
572         interthread_progress_connection.disconnect ();
573         
574         /* import thread finished - see if we should build a new track */
575
576         boost::shared_ptr<AudioRegion> r;
577         
578         if (import_status.cancel || import_status.sources.empty()) {
579                 goto out;
580         }
581
582         if (add_sources (paths, import_status.sources, pos, mode, target_regions, target_tracks, track, false) == 0) {
583                 session->save_state ("");
584         }
585
586   out:
587         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
588         return 0;
589 }
590
591 int
592 Editor::embed_sndfiles (vector<Glib::ustring> paths, bool multifile,
593                         bool& check_sample_rate, ImportMode mode, nframes64_t& pos, int target_regions, int target_tracks,
594                         boost::shared_ptr<Track>& track)
595 {
596         boost::shared_ptr<AudioFileSource> source;
597         SourceList sources;
598         string linked_path;
599         SoundFileInfo finfo;
600         int ret = 0;
601
602         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
603         ARDOUR_UI::instance()->flush_pending ();
604
605         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
606
607                 ustring path = *p;
608
609                 /* lets see if we can link it into the session */
610                 
611                 sys::path tmp = session->session_directory().sound_path() / Glib::path_get_basename(path);
612                 linked_path = tmp.to_string();
613                 
614                 if (link (path.c_str(), linked_path.c_str()) == 0) {
615
616                         /* there are many reasons why link(2) might have failed.
617                            but if it succeeds, we now have a link in the
618                            session sound dir that will protect against
619                            unlinking of the original path. nice.
620                         */
621                         
622                         path = linked_path;
623
624                 } else {
625
626                         /* one possible reason is that its already linked */
627
628                         if (errno == EEXIST) {
629                                 struct stat sb;
630
631                                 if (stat (linked_path.c_str(), &sb) == 0) {
632                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
633                                                 path = linked_path;
634                                         }
635                                 }
636                         }
637                 }
638                 
639                 /* note that we temporarily truncated _id at the colon */
640                 
641                 string error_msg;
642
643                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
644                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
645                         goto out;
646                 }
647                 
648                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
649                         vector<string> choices;
650                         
651                         if (multifile) {
652                                 choices.push_back (_("Cancel entire import"));
653                                 choices.push_back (_("Don't embed it"));
654                                 choices.push_back (_("Embed all without questions"));
655                         
656                                 Gtkmm2ext::Choice rate_choice (
657                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
658                                                         short_path (path, 40)),
659                                         choices, false);
660                                 
661                                 int resx = rate_choice.run ();
662                                 
663                                 switch (resx) {
664                                 case 0: /* stop a multi-file import */
665                                         ret = -2;
666                                         goto out;
667                                 case 1: /* don't embed this one */
668                                         ret = -1;
669                                         goto out;
670                                 case 2: /* do it, and the rest without asking */
671                                         check_sample_rate = false;
672                                         break;
673                                 case 3: /* do it */
674                                         break;
675                                 default:
676                                         ret = -2;
677                                         goto out;
678                                 }
679                         } else {
680                                 choices.push_back (_("Cancel"));
681                                 choices.push_back (_("Embed it anyway"));
682                         
683                                 Gtkmm2ext::Choice rate_choice (
684                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
685                                         choices, false);
686                                 
687                                 int resx = rate_choice.run ();
688                                 
689                                 switch (resx) {
690                                 case 0: /* don't import */
691                                         ret = -1;
692                                         goto out;
693                                 case 1: /* do it */
694                                         break;
695                                 default:
696                                         ret = -2;
697                                         goto out;
698                                 }
699                         }
700                 }
701                 
702                 track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
703
704                 for (int n = 0; n < finfo.channels; ++n) {
705                         try {
706
707                                 /* check if we have this thing embedded already */
708
709                                 boost::shared_ptr<Source> s;
710
711                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
712
713                                         cerr << "add embed/import source with defer_peaks = true\n";
714
715                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
716                                                                                                (DataType::AUDIO, *session, path,  n,
717                                                                                                 (mode == ImportAsTapeTrack ? 
718                                                                                                  AudioFileSource::Destructive : 
719                                                                                                  AudioFileSource::Flag (0)),
720                                                                                                 true, true));
721                                 } else {
722                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
723                                 }
724
725                                 sources.push_back(source);
726                         } 
727                         
728                         catch (failed_constructor& err) {
729                                 error << string_compose(_("could not open %1"), path) << endmsg;
730                                 goto out;
731                         }
732                         
733                         ARDOUR_UI::instance()->flush_pending ();
734                 }
735         }
736
737         if (sources.empty()) {
738                 goto out;
739         }
740
741         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
742
743   out:
744         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
745         return ret;
746 }
747
748 int
749 Editor::add_sources (vector<Glib::ustring> paths, SourceList& sources, nframes64_t& pos, ImportMode mode, 
750                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool add_channel_suffix)
751 {
752         vector<boost::shared_ptr<Region> > regions;
753         ustring region_name;
754         uint32_t input_chan = 0;
755         uint32_t output_chan = 0;
756
757         if (pos == -1) { // "use timestamp"
758                 if (sources[0]->natural_position() != 0) {
759                         pos = sources[0]->natural_position();
760                 } else {
761                         pos = get_preferred_edit_position ();
762                 }
763         }
764
765         // kludge (for MIDI we're abusing "channel" for "track" here)
766         if (paths.front().rfind(".mid") != Glib::ustring::npos)
767                 target_regions = -1;
768
769         if (target_regions == 1) {
770
771                 /* take all the sources we have and package them up as a region */
772
773                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
774                 
775                 regions.push_back (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
776                                                            Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
777                 
778         } else if (target_regions == -1) {
779
780                 /* take each source and create a region for each one */
781
782                 SourceList just_one;
783                 SourceList::iterator x;
784                 uint32_t n;
785
786                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
787
788                         just_one.clear ();
789                         just_one.push_back (*x);
790                         
791                         region_name = region_name_from_path ((*x)->path(), false, false, sources.size(), n);
792
793                         regions.push_back (RegionFactory::create (just_one, 0, (*x)->length(), region_name, 0,
794                                                                    Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External)));
795
796                 }
797         }
798
799         if (target_regions == 1) {
800                 input_chan = regions.front()->n_channels();
801         } else {
802                 if (target_tracks == 1) {
803                         input_chan = regions.size();
804                 } else {
805                         input_chan = 1;
806                 }
807         }
808
809         if (Config->get_output_auto_connect() & AutoConnectMaster) {
810                 output_chan = (session->master_out() ? session->master_out()->n_inputs().n_audio() : input_chan);
811         } else {
812                 output_chan = input_chan;
813         }
814
815         int n = 0;
816
817         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
818
819                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
820
821                 if (target_tracks != 1) {
822                         track.reset ();
823                 } else {
824                         pos += (*r)->length();
825                 } 
826         }
827
828         /* setup peak file building in another thread */
829
830         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
831                 SourceFactory::setup_peakfile (*x, true);
832         }
833
834         return 0;
835 }
836         
837 int
838 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, nframes64_t& pos, 
839                                   ImportMode mode, boost::shared_ptr<Track>& existing_track)
840 {
841         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
842         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
843
844         switch (mode) {
845         case ImportAsRegion:
846                 /* relax, its been done */
847                 break;
848                 
849         case ImportToTrack:
850         {
851                 if (!existing_track) {
852
853                         if (ar) {
854                                 existing_track = get_nth_selected_audio_track (0);
855                         } else if (mr) {
856                                 existing_track = get_nth_selected_midi_track (0);
857                         }
858
859                         if (!existing_track) {
860                                 return -1;
861                         }
862                 }
863
864                 boost::shared_ptr<Playlist> playlist = existing_track->diskstream()->playlist();
865                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
866                 begin_reversible_command (_("insert file"));
867                 XMLNode &before = playlist->get_state();
868                 playlist->add_region (copy, pos);
869                 session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
870                 commit_reversible_command ();
871                 break;
872         }
873
874         case ImportAsTrack:
875         { 
876                 if (!existing_track) {
877                         if (ar) {
878                                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
879
880                                 if (at.empty()) {
881                                         return -1;
882                                 }
883
884                                 existing_track = at.front();
885                         } else if (mr) {
886                                 list<boost::shared_ptr<MidiTrack> > mt (session->new_midi_track (Normal, 1));
887
888                                 if (mt.empty()) {
889                                         return -1;
890                                 }
891
892                                 existing_track = mt.front();
893                         }
894
895                         existing_track->set_name (region->name());
896                 }
897
898                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
899                 existing_track->diskstream()->playlist()->add_region (copy, pos);
900                 break;
901         }
902
903
904         case ImportAsTapeTrack:
905         {
906                 if (!ar)
907                         return -1;
908
909                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
910                 if (!at.empty()) {
911                         boost::shared_ptr<Region> copy (RegionFactory::create (region));
912                         at.front()->set_name (basename_nosuffix (copy->name()));
913                         at.front()->diskstream()->playlist()->add_region (copy, pos);
914                 }
915                 break;
916         }
917         }
918
919         return 0;
920 }
921
922 void *
923 Editor::_import_thread (void *arg)
924 {
925         PBD::ThreadCreated (pthread_self(), X_("Import"));
926
927         Editor *ed = (Editor *) arg;
928         return ed->import_thread ();
929 }
930
931 void *
932 Editor::import_thread ()
933 {
934         session->import_audiofiles (import_status);
935         pthread_exit_pbd (0);
936         /*NOTREACHED*/
937         return 0;
938 }
939
940 gint
941 Editor::import_progress_timeout (void *arg)
942 {
943         bool reset = false;
944
945         if (!interthread_progress_window->is_visible()) {
946                 interthread_progress_window->show_all ();
947                 reset = true;
948         }
949
950         interthread_progress_label.set_text (import_status.doing_what);
951
952         if (import_status.freeze) {
953                 interthread_cancel_button.set_sensitive(false);
954         } else {
955                 interthread_cancel_button.set_sensitive(true);
956         }
957
958         if (import_status.doing_what == "building peak files") {
959                 interthread_progress_bar.pulse ();
960                 return FALSE;
961         } else {
962                 float val = import_status.progress;
963                 interthread_progress_bar.set_fraction (min (max (0.0f, val), 1.0f));
964         }
965
966         if (reset) {
967
968                 /* the window is now visible, speed up the updates */
969                 
970                 interthread_progress_connection.disconnect ();
971                 interthread_progress_connection = Glib::signal_timeout().connect 
972                         (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
973                 return false;
974         } else {
975                 return !(import_status.done || import_status.cancel);
976         }
977 }
978