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