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