b0c8b25b5024afc9d189be884c4bf6a9f98f46d7
[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
26 #include <sndfile.h>
27
28 #include <pbd/pthread_utils.h>
29 #include <pbd/basename.h>
30 #include <pbd/shortpath.h>
31
32 #include <gtkmm2ext/choice.h>
33 #include <gtkmm2ext/window_title.h>
34
35 #include <ardour/session.h>
36 #include <ardour/session_directory.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<ARDOUR::Source> > SourceMap;
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         SourceMap all_sources = session->get_sources();
203         bool wave_name_exists = false;
204
205         for (SourceMap::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 void
285 Editor::do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
286 {
287         boost::shared_ptr<AudioTrack> track;
288         vector<ustring> to_import;
289         bool ok = true;
290         int nth = 0;
291
292         if (interthread_progress_window == 0) {
293                 build_interthread_progress_window ();
294         }
295
296
297         if (chns == Editing::ImportMergeFiles) {
298                 /* create 1 region from all paths, add to 1 track,
299                    ignore "track"
300                 */
301                 bool cancel = false;
302                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
303                         int check = check_whether_and_how_to_import(*a, false);
304                         if (check == 2) {
305                                 cancel = true;
306                                 break;
307                         }
308                 }
309
310                 if (!cancel) {
311                         if (import_sndfiles (paths, mode, quality, pos, 1, 1, track, false)) {
312                                 ok = false;
313                         }
314                 }
315
316         } else {
317                 bool replace = false;
318
319                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end() && ok; ++a) {
320
321                         int check = check_whether_and_how_to_import(*a, true);
322
323                         if (check == 2 ) { 
324                                 // skip
325                                 continue;
326                         }
327
328                         if (check == 0) {
329                                 fatal << "Updating existing sources should be disabled!" << endl;
330                                 replace = true;
331                         } else if (check == 1) {
332                                 replace = false;
333                         }
334                         
335
336                         switch (chns) {
337                                 case Editing::ImportDistinctFiles:
338
339                                         to_import.clear ();
340                                         to_import.push_back (*a);
341
342                                         if (mode == Editing::ImportToTrack) {
343                                                 track = get_nth_selected_audio_track (nth++);
344                                         }
345
346                                         if (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, replace)) {
347                                                 ok = false;
348                                         }
349
350                                         break;
351
352                                 case Editing::ImportDistinctChannels:
353
354                                         to_import.clear ();
355                                         to_import.push_back (*a);
356
357                                         if (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, replace)) {
358                                                 ok = false;
359                                         }
360
361                                         break;
362
363                                 case Editing::ImportSerializeFiles:
364
365                                         to_import.clear ();
366                                         to_import.push_back (*a);
367
368                                         /* create 1 region from this path, add to 1 track,
369                                            reuse "track" across paths
370                                            */
371
372                                         if (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, replace)) {
373                                                 ok = false;
374                                         }
375
376                                         break;
377
378                                 case Editing::ImportMergeFiles:
379                                         // Not entered
380                                         break;
381                         }
382                 }
383
384                 if (ok) {
385                         session->save_state ("");
386                 }
387
388                 interthread_progress_window->hide_all ();
389         }
390 }
391
392 bool
393 Editor::idle_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
394 {
395         _do_embed (paths, chns, mode, pos);
396         return false;
397 }
398
399 void
400 Editor::do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
401 {
402 #ifdef GTKOSX
403         Glib::signal_idle().connect (bind (mem_fun (*this, &Editor::idle_do_embed), paths, chns, mode, pos));
404 #else
405         _do_embed (paths, chns, mode, pos);
406 #endif
407 }
408
409 void
410 Editor::_do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
411 {
412         boost::shared_ptr<AudioTrack> track;
413         bool check_sample_rate = true;
414         bool ok = false;
415         vector<ustring> to_embed;
416         bool multi = paths.size() > 1;
417         int nth = 0;
418
419         switch (chns) {
420         case Editing::ImportDistinctFiles:
421                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
422
423                         to_embed.clear ();
424                         to_embed.push_back (*a);
425
426                         if (mode == Editing::ImportToTrack) {
427                                 track = get_nth_selected_audio_track (nth++);
428                         }
429
430                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
431                                 goto out;
432                         }
433                 }
434                 break;
435                 
436         case Editing::ImportDistinctChannels:
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 (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
443                                 goto out;
444                         }
445                 }
446                 break;
447
448         case Editing::ImportMergeFiles:
449                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
450                         goto out;
451                 }
452         break;
453
454         case Editing::ImportSerializeFiles:
455                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
456
457                         to_embed.clear ();
458                         to_embed.push_back (*a);
459
460                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
461                                 goto out;
462                         }
463                 }
464                 break;
465         }
466
467         ok = true;
468         
469   out:  
470         if (ok) {
471                 session->save_state ("");
472         }
473 }
474
475 int
476 Editor::import_sndfiles (vector<ustring> paths, ImportMode mode, SrcQuality quality, nframes64_t& pos, 
477                          int target_regions, int target_tracks, boost::shared_ptr<AudioTrack>& track, bool replace)
478 {
479         WindowTitle title = string_compose (_("importing %1"), paths.front());
480
481         interthread_progress_window->set_title (title.get_string());
482         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
483         interthread_progress_window->show_all ();
484         interthread_progress_bar.set_fraction (0.0f);
485         interthread_cancel_label.set_text (_("Cancel Import"));
486         current_interthread_info = &import_status;
487
488         import_status.paths = paths;
489         import_status.done = false;
490         import_status.cancel = false;
491         import_status.freeze = false;
492         import_status.done = 0.0;
493         import_status.quality = quality;
494         import_status.replace_existing_source = replace;
495
496         interthread_progress_connection = Glib::signal_timeout().connect 
497                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
498         
499         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
500         ARDOUR_UI::instance()->flush_pending ();
501
502         /* start import thread for this spec. this will ultimately call Session::import_audiofiles()
503            and if successful will add the file(s) as a region to the session region list.
504         */
505         
506         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
507         pthread_detach (import_status.thread);
508         
509         while (!(import_status.done || import_status.cancel)) {
510                 gtk_main_iteration ();
511         }
512
513         interthread_progress_window->hide ();
514         
515         import_status.done = true;
516         interthread_progress_connection.disconnect ();
517         
518         /* import thread finished - see if we should build a new track */
519
520         boost::shared_ptr<AudioRegion> r;
521         
522         if (import_status.cancel || import_status.sources.empty()) {
523                 goto out;
524         }
525
526         if (add_sources (paths, import_status.sources, pos, mode, target_regions, target_tracks, track, false) == 0) {
527                 session->save_state ("");
528         }
529
530   out:
531         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
532         return 0;
533 }
534
535 int
536 Editor::embed_sndfiles (vector<Glib::ustring> paths, bool multifile,
537                         bool& check_sample_rate, ImportMode mode, nframes64_t& pos, int target_regions, int target_tracks,
538                         boost::shared_ptr<AudioTrack>& track)
539 {
540         boost::shared_ptr<AudioFileSource> source;
541         SourceList sources;
542         string linked_path;
543         SoundFileInfo finfo;
544         int ret = 0;
545
546         track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
547         ARDOUR_UI::instance()->flush_pending ();
548
549         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
550
551                 ustring path = *p;
552
553                 /* lets see if we can link it into the session */
554                 
555                 sys::path tmp = session->session_directory().sound_path() / Glib::path_get_basename(path);
556                 linked_path = tmp.to_string();
557                 
558                 if (link (path.c_str(), linked_path.c_str()) == 0) {
559
560                         /* there are many reasons why link(2) might have failed.
561                            but if it succeeds, we now have a link in the
562                            session sound dir that will protect against
563                            unlinking of the original path. nice.
564                         */
565                         
566                         path = linked_path;
567
568                 } else {
569
570                         /* one possible reason is that its already linked */
571
572                         if (errno == EEXIST) {
573                                 struct stat sb;
574
575                                 if (stat (linked_path.c_str(), &sb) == 0) {
576                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
577                                                 path = linked_path;
578                                         }
579                                 }
580                         }
581                 }
582                 
583                 /* note that we temporarily truncated _id at the colon */
584                 
585                 string error_msg;
586
587                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
588                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
589                         goto out;
590                 }
591                 
592                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
593                         vector<string> choices;
594                         
595                         if (multifile) {
596                                 choices.push_back (_("Cancel entire import"));
597                                 choices.push_back (_("Don't embed it"));
598                                 choices.push_back (_("Embed all without questions"));
599                         
600                                 Gtkmm2ext::Choice rate_choice (
601                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), 
602                                                         short_path (path, 40)),
603                                         choices, false);
604                                 
605                                 int resx = rate_choice.run ();
606                                 
607                                 switch (resx) {
608                                 case 0: /* stop a multi-file import */
609                                         ret = -2;
610                                         goto out;
611                                 case 1: /* don't embed this one */
612                                         ret = -1;
613                                         goto out;
614                                 case 2: /* do it, and the rest without asking */
615                                         check_sample_rate = false;
616                                         break;
617                                 case 3: /* do it */
618                                         break;
619                                 default:
620                                         ret = -2;
621                                         goto out;
622                                 }
623                         } else {
624                                 choices.push_back (_("Cancel"));
625                                 choices.push_back (_("Embed it anyway"));
626                         
627                                 Gtkmm2ext::Choice rate_choice (
628                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
629                                         choices, false);
630                                 
631                                 int resx = rate_choice.run ();
632                                 
633                                 switch (resx) {
634                                 case 0: /* don't import */
635                                         ret = -1;
636                                         goto out;
637                                 case 1: /* do it */
638                                         break;
639                                 default:
640                                         ret = -2;
641                                         goto out;
642                                 }
643                         }
644                 }
645                 
646                 track_canvas.get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
647
648                 for (int n = 0; n < finfo.channels; ++n) {
649                         try {
650
651                                 /* check if we have this thing embedded already */
652
653                                 boost::shared_ptr<Source> s;
654
655                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
656                                         source = boost::dynamic_pointer_cast<AudioFileSource> (SourceFactory::createReadable 
657                                                                                                (DataType::AUDIO, *session, path,  n,
658                                                                                                 (mode == ImportAsTapeTrack ? 
659                                                                                                  AudioFileSource::Destructive : 
660                                                                                                  AudioFileSource::Flag (0)),
661                                                                                                 true, true));
662                                 } else {
663                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
664                                 }
665
666                                 sources.push_back(source);
667                         } 
668                         
669                         catch (failed_constructor& err) {
670                                 error << string_compose(_("could not open %1"), path) << endmsg;
671                                 goto out;
672                         }
673                         
674                         ARDOUR_UI::instance()->flush_pending ();
675                 }
676         }
677
678         if (sources.empty()) {
679                 goto out;
680         }
681
682         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
683
684   out:
685         track_canvas.get_window()->set_cursor (*current_canvas_cursor);
686         return ret;
687 }
688
689 int
690 Editor::add_sources (vector<Glib::ustring> paths, SourceList& sources, nframes64_t& pos, ImportMode mode, 
691                      int target_regions, int target_tracks, boost::shared_ptr<AudioTrack>& track, bool add_channel_suffix)
692 {
693         vector<boost::shared_ptr<AudioRegion> > regions;
694         ustring region_name;
695         uint32_t input_chan = 0;
696         uint32_t output_chan = 0;
697
698         if (pos == -1) { // "use timestamp"
699                 if (sources[0]->natural_position() != 0) {
700                         pos = sources[0]->natural_position();
701                 } else {
702                         pos = get_preferred_edit_position ();
703                 }
704         }
705
706         if (target_regions == 1) {
707
708                 /* take all the sources we have and package them up as a region */
709
710                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
711                 
712                 regions.push_back (boost::dynamic_pointer_cast<AudioRegion> 
713                                    (RegionFactory::create (sources, 0, sources[0]->length(), region_name, 0,
714                                                            Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External))));
715                 
716         } else if (target_regions == -1) {
717
718                 /* take each source and create a region for each one */
719
720                 SourceList just_one;
721                 SourceList::iterator x;
722                 uint32_t n;
723
724                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
725
726                         just_one.clear ();
727                         just_one.push_back (*x);
728                         
729                         boost::shared_ptr<AudioFileSource> afs = boost::dynamic_pointer_cast<AudioFileSource> (*x);
730
731                         region_name = region_name_from_path (afs->path(), false, true, sources.size(), n);
732
733                         regions.push_back (boost::dynamic_pointer_cast<AudioRegion> 
734                                            (RegionFactory::create (just_one, 0, (*x)->length(), region_name, 0,
735                                                                    Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External))));
736
737                 }
738         }
739
740         if (target_regions == 1) {
741                 input_chan = regions.front()->n_channels();
742         } else {
743                 if (target_tracks == 1) {
744                         input_chan = regions.size();
745                 } else {
746                         input_chan = 1;
747                 }
748         }
749
750         if (Config->get_output_auto_connect() & AutoConnectMaster) {
751                 output_chan = (session->master_out() ? session->master_out()->n_inputs().n_audio() : input_chan);
752         } else {
753                 output_chan = input_chan;
754         }
755
756         int n = 0;
757
758         for (vector<boost::shared_ptr<AudioRegion> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
759
760                 finish_bringing_in_audio (*r, input_chan, output_chan, pos, mode, track);
761
762                 if (target_tracks != 1) {
763                         track.reset ();
764                 } else {
765                         pos += (*r)->length();
766                 } 
767         }
768
769         /* setup peak file building in another thread */
770
771         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
772                 SourceFactory::setup_peakfile (*x, true);
773         }
774
775         return 0;
776 }
777         
778 int
779 Editor::finish_bringing_in_audio (boost::shared_ptr<AudioRegion> region, uint32_t in_chans, uint32_t out_chans, nframes64_t& pos, 
780                                   ImportMode mode, boost::shared_ptr<AudioTrack>& existing_track)
781 {
782         switch (mode) {
783         case ImportAsRegion:
784                 /* relax, its been done */
785                 break;
786                 
787         case ImportToTrack:
788         {
789                 if (!existing_track) {
790
791                         existing_track = get_nth_selected_audio_track (0);
792
793                         if (!existing_track) {
794                                 return -1;
795                         }
796                 }
797
798                 boost::shared_ptr<Playlist> playlist = existing_track->diskstream()->playlist();
799                 boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
800                 begin_reversible_command (_("insert sndfile"));
801                 XMLNode &before = playlist->get_state();
802                 playlist->add_region (copy, pos);
803                 session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
804                 commit_reversible_command ();
805                 break;
806         }
807
808         case ImportAsTrack:
809         { 
810                 if (!existing_track) {
811                         list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 1));
812
813                         if (at.empty()) {
814                                 return -1;
815                         }
816
817                         existing_track = at.front();
818                         existing_track->set_name (region->name());
819                 }
820
821                 boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
822                 existing_track->diskstream()->playlist()->add_region (copy, pos);
823                 break;
824         }
825
826
827         case ImportAsTapeTrack:
828         {
829                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
830                 if (!at.empty()) {
831                         boost::shared_ptr<AudioRegion> copy (boost::dynamic_pointer_cast<AudioRegion> (RegionFactory::create (region)));
832                         at.front()->set_name (basename_nosuffix (copy->name()));
833                         at.front()->diskstream()->playlist()->add_region (copy, pos);
834                 }
835                 break;
836         }
837         }
838
839         return 0;
840 }
841
842 void *
843 Editor::_import_thread (void *arg)
844 {
845         PBD::ThreadCreated (pthread_self(), X_("Import"));
846
847         Editor *ed = (Editor *) arg;
848         return ed->import_thread ();
849 }
850
851 void *
852 Editor::import_thread ()
853 {
854         session->import_audiofiles (import_status);
855         pthread_exit_pbd (0);
856         /*NOTREACHED*/
857         return 0;
858 }
859
860 gint
861 Editor::import_progress_timeout (void *arg)
862 {
863         interthread_progress_label.set_text (import_status.doing_what);
864
865         if (import_status.freeze) {
866                 interthread_cancel_button.set_sensitive(false);
867         } else {
868                 interthread_cancel_button.set_sensitive(true);
869         }
870
871         if (import_status.doing_what == "building peak files") {
872                 interthread_progress_bar.pulse ();
873                 return FALSE;
874         } else {
875                 interthread_progress_bar.set_fraction (import_status.progress);
876         }
877
878         return !(import_status.done || import_status.cancel);
879 }
880