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