fix merge conflicts from master
[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/audio_track.h"
37 #include "ardour/audiofilesource.h"
38 #include "ardour/audioregion.h"
39 #include "ardour/midi_region.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/operations.h"
42 #include "ardour/region_factory.h"
43 #include "ardour/smf_source.h"
44 #include "ardour/source_factory.h"
45 #include "ardour/utils.h"
46 #include "pbd/memento_command.h"
47
48 #include "ardour_ui.h"
49 #include "editor.h"
50 #include "sfdb_ui.h"
51 #include "editing.h"
52 #include "audio_time_axis.h"
53 #include "midi_time_axis.h"
54 #include "session_import_dialog.h"
55 #include "utils.h"
56 #include "gui_thread.h"
57 #include "interthread_progress_window.h"
58 #include "mouse_cursors.h"
59 #include "editor_cursors.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 std::string;
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 (_("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<string> paths;
95         uint32_t audio_track_cnt;
96         uint32_t midi_track_cnt;
97
98         if (_session == 0) {
99                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
100                 msg.run ();
101                 return;
102         }
103
104         audio_track_cnt = 0;
105         midi_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                         if (atv->is_audio_track()) {
112                                 audio_track_cnt++;
113                         } 
114
115                 } else {
116                         MidiTimeAxisView* mtv = dynamic_cast<MidiTimeAxisView*>(*x);
117
118                         if (mtv) {
119                                 if (mtv->is_midi_track()) {
120                                         midi_track_cnt++;
121                                 }
122                         }
123                 }
124         }
125
126         if (sfbrowser == 0) {
127                 sfbrowser = new SoundFileOmega (_("Add Existing Media"), _session, audio_track_cnt, midi_track_cnt, true);
128         } else {
129                 sfbrowser->reset (audio_track_cnt, midi_track_cnt);
130         }
131
132         sfbrowser->show_all ();
133 }
134
135 void
136 Editor::session_import_dialog ()
137 {
138         SessionImportDialog dialog (_session);
139         ensure_float (dialog);
140         dialog.run ();
141 }
142
143 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
144
145 /**
146  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_files()
147  *
148  * all_or_nothing:
149  *   true  = show "Update", "Import" and "Skip"
150  *   false = show "Import", and "Cancel"
151  *
152  * Returns:
153  *     0  To update an existing source of the same name
154  *     1  To import/embed the file normally (make sure the new name will be unique)
155  *     2  If the user wants to skip this file
156  **/
157 int
158 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
159 {
160         string wave_name (Glib::path_get_basename(path));
161
162         SourceMap all_sources = _session->get_sources();
163         bool already_exists = false;
164         uint32_t existing;
165
166         if ((existing = _session->count_sources_by_origin (path)) > 0) {
167                 already_exists = true;
168         }
169
170         int function = 1;
171
172         if (already_exists) {
173                 string message;
174                 if (all_or_nothing) {
175                         // updating is still disabled
176                         //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);
177                         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);
178                 } else {
179                         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);
180
181                 }
182                 MessageDialog dialog(message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
183
184                 if (all_or_nothing) {
185                         // disabled
186                         //dialog.add_button("Update", 0);
187                         dialog.add_button("Import", 1);
188                         dialog.add_button("Skip",   2);
189                 } else {
190                         dialog.add_button("Import", 1);
191                         dialog.add_button("Cancel", 2);
192                 }
193
194                 //dialog.add_button("Skip all", 4); // All or rest?
195
196                 dialog.show();
197
198                 function = dialog.run ();
199
200                 dialog.hide();
201         }
202
203         return function;
204 }
205
206 boost::shared_ptr<AudioTrack>
207 Editor::get_nth_selected_audio_track (int nth) const
208 {
209         AudioTimeAxisView* atv;
210         TrackSelection::iterator x;
211
212         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
213
214                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
215
216                 if (!atv) {
217                         continue;
218                 } else if (atv->is_audio_track()) {
219                         --nth;
220                 }
221         }
222
223         if (x == selection->tracks.end()) {
224                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
225         } else {
226                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
227         }
228
229         if (!atv || !atv->is_audio_track()) {
230                 return boost::shared_ptr<AudioTrack>();
231         }
232
233         return atv->audio_track();
234 }
235
236 boost::shared_ptr<MidiTrack>
237 Editor::get_nth_selected_midi_track (int nth) const
238 {
239         MidiTimeAxisView* mtv;
240         TrackSelection::iterator x;
241
242         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
243
244                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
245
246                 if (!mtv) {
247                         continue;
248                 } else if (mtv->is_midi_track()) {
249                         --nth;
250                 }
251         }
252
253         if (x == selection->tracks.end()) {
254                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
255         } else {
256                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
257         }
258
259         if (!mtv || !mtv->is_midi_track()) {
260                 return boost::shared_ptr<MidiTrack>();
261         }
262
263         return mtv->midi_track();
264 }
265
266 void
267 Editor::do_import (vector<string> paths, ImportDisposition disposition, ImportMode mode, SrcQuality quality, framepos_t& pos)
268 {
269         boost::shared_ptr<Track> track;
270         vector<string> to_import;
271         int nth = 0;
272         bool use_timestamp = (pos == -1);
273
274         current_interthread_info = &import_status;
275         import_status.current = 1;
276         import_status.total = paths.size ();
277         import_status.all_done = false;
278
279         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
280
281         bool ok = true;
282
283         if (disposition == Editing::ImportMergeFiles) {
284
285                 /* create 1 region from all paths, add to 1 track,
286                    ignore "track"
287                 */
288
289                 bool cancel = false;
290                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
291                         int check = check_whether_and_how_to_import(*a, false);
292                         if (check == 2) {
293                                 cancel = true;
294                                 break;
295                         }
296                 }
297
298                 if (cancel) {
299                         ok = false;
300                 } else {
301                         ipw.show ();
302                         ok = (import_sndfiles (paths, disposition, mode, quality, pos, 1, 1, track, false) == 0);
303                 }
304
305         } else {
306
307                 bool replace = false;
308
309                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
310
311                         const int check = check_whether_and_how_to_import (*a, true);
312
313                         switch (check) {
314                         case 2:
315                                 // user said skip
316                                 continue;
317                         case 0:
318                                 fatal << "Updating existing sources should be disabled!" << endmsg;
319                                 /* NOTREACHED*/
320                                 break;
321                         case 1:
322                                 replace = false;
323                                 break;
324                         default:
325                                 fatal << "Illegal return " << check <<  " from check_whether_and_how_to_import()!" << endmsg;
326                                 /* NOTREACHED*/
327                         }
328
329                         /* have to reset this for every file we handle */
330
331                         if (use_timestamp) {
332                                 pos = -1;
333                         }
334
335                         ipw.show ();
336
337                         switch (disposition) {
338                         case Editing::ImportDistinctFiles:
339
340                                 to_import.clear ();
341                                 to_import.push_back (*a);
342
343                                 if (mode == Editing::ImportToTrack) {
344                                         track = get_nth_selected_audio_track (nth++);
345                                 }
346
347                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, 1, -1, track, replace) == 0);
348                                 break;
349
350                         case Editing::ImportDistinctChannels:
351
352                                 to_import.clear ();
353                                 to_import.push_back (*a);
354
355                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, -1, -1, track, replace) == 0);
356                                 break;
357
358                         case Editing::ImportSerializeFiles:
359
360                                 to_import.clear ();
361                                 to_import.push_back (*a);
362
363                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, 1, 1, track, replace) == 0);
364                                 break;
365
366                         case Editing::ImportMergeFiles:
367                                 // Not entered, handled in earlier if() branch
368                                 break;
369                         }
370                 }
371         }
372
373         if (ok) {
374                 _session->save_state ("");
375         }
376
377         import_status.all_done = true;
378 }
379
380 void
381 Editor::do_embed (vector<string> paths, ImportDisposition import_as, ImportMode mode, framepos_t& pos)
382 {
383         boost::shared_ptr<Track> track;
384         bool check_sample_rate = true;
385         bool ok = false;
386         vector<string> to_embed;
387         bool multi = paths.size() > 1;
388         int nth = 0;
389         bool use_timestamp = (pos == -1);
390
391         switch (import_as) {
392         case Editing::ImportDistinctFiles:
393                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
394
395                         /* have to reset this for every file we handle */
396                         if (use_timestamp) {
397                                 pos = -1;
398                         }
399
400                         to_embed.clear ();
401                         to_embed.push_back (*a);
402
403                         if (mode == Editing::ImportToTrack) {
404                                 track = get_nth_selected_audio_track (nth++);
405                         }
406
407                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, mode, pos, 1, -1, track) < -1) {
408                                 goto out;
409                         }
410                 }
411                 break;
412
413         case Editing::ImportDistinctChannels:
414                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
415
416                         /* have to reset this for every file we handle */
417                         if (use_timestamp) {
418                                 pos = -1;
419                         }
420
421                         to_embed.clear ();
422                         to_embed.push_back (*a);
423
424                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, 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, import_as, mode, pos, 1, 1, track) < -1) {
432                         goto out;
433                 }
434                 break;
435
436         case Editing::ImportSerializeFiles:
437                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
438
439                         /* have to reset this for every file we handle */
440                         if (use_timestamp) {
441                                 pos = -1;
442                         }
443
444                         to_embed.clear ();
445                         to_embed.push_back (*a);
446
447                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, mode, pos, 1, 1, track) < -1) {
448                                 goto out;
449                         }
450                 }
451                 break;
452         }
453
454         ok = true;
455
456   out:
457         if (ok) {
458                 _session->save_state ("");
459         }
460 }
461
462 int
463 Editor::import_sndfiles (vector<string> paths, ImportDisposition disposition, ImportMode mode, SrcQuality quality, framepos_t& pos,
464                          int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool replace)
465 {
466         import_status.paths = paths;
467         import_status.done = false;
468         import_status.cancel = false;
469         import_status.freeze = false;
470         import_status.quality = quality;
471         import_status.replace_existing_source = replace;
472
473         import_status.mode = mode;
474         import_status.pos = pos;
475         import_status.target_tracks = target_tracks;
476         import_status.target_regions = target_regions;
477         import_status.track = track;
478         import_status.replace = replace;
479
480         set_canvas_cursor (_cursors->wait);
481         gdk_flush ();
482
483         /* start import thread for this spec. this will ultimately call Session::import_files()
484            which, if successful, will add the files as regions to the region list. its up to us
485            (the GUI) to direct additional steps after that.
486         */
487
488         pthread_create_and_store ("import", &import_status.thread, _import_thread, this);
489         pthread_detach (import_status.thread);
490
491         while (!import_status.done && !import_status.cancel) {
492                 gtk_main_iteration ();
493         }
494
495         import_status.done = true;
496
497         int result = -1;
498
499         if (!import_status.cancel && !import_status.sources.empty()) {
500                 result = add_sources (
501                         import_status.paths,
502                         import_status.sources,
503                         import_status.pos,
504                         disposition,
505                         import_status.mode,
506                         import_status.target_regions,
507                         import_status.target_tracks,
508                         track, false
509                         );
510
511                 /* update position from results */
512
513                 pos = import_status.pos;
514         }
515
516         set_canvas_cursor (current_canvas_cursor);
517         return result;
518 }
519
520 int
521 Editor::embed_sndfiles (vector<string> paths, bool multifile,
522                         bool& check_sample_rate, ImportDisposition disposition, ImportMode mode, 
523                         framepos_t& pos, int target_regions, int target_tracks,
524                         boost::shared_ptr<Track>& track)
525 {
526         boost::shared_ptr<AudioFileSource> source;
527         SourceList sources;
528         string linked_path;
529         SoundFileInfo finfo;
530         int ret = 0;
531
532         set_canvas_cursor (_cursors->wait);
533         gdk_flush ();
534
535         for (vector<string>::iterator p = paths.begin(); p != paths.end(); ++p) {
536
537                 string path = *p;
538                 string error_msg;
539
540                 /* note that we temporarily truncated _id at the colon */
541
542                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
543                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
544                         goto out;
545                 }
546
547                 if (check_sample_rate  && (finfo.samplerate != (int) _session->frame_rate())) {
548                         vector<string> choices;
549
550                         if (multifile) {
551                                 choices.push_back (_("Cancel entire import"));
552                                 choices.push_back (_("Don't embed it"));
553                                 choices.push_back (_("Embed all without questions"));
554
555                                 Gtkmm2ext::Choice rate_choice (
556                                         _("Sample rate"),
557                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
558                                                         short_path (path, 40)),
559                                         choices, false
560                                         );
561
562                                 int resx = rate_choice.run ();
563
564                                 switch (resx) {
565                                 case 0: /* stop a multi-file import */
566                                         ret = -2;
567                                         goto out;
568                                 case 1: /* don't embed this one */
569                                         ret = -1;
570                                         goto out;
571                                 case 2: /* do it, and the rest without asking */
572                                         check_sample_rate = false;
573                                         break;
574                                 case 3: /* do it */
575                                         break;
576                                 default:
577                                         ret = -2;
578                                         goto out;
579                                 }
580                         } else {
581                                 choices.push_back (_("Cancel"));
582                                 choices.push_back (_("Embed it anyway"));
583
584                                 Gtkmm2ext::Choice rate_choice (
585                                         _("Sample rate"),
586                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
587                                         choices, false
588                                         );
589
590                                 int resx = rate_choice.run ();
591
592                                 switch (resx) {
593                                 case 0: /* don't import */
594                                         ret = -1;
595                                         goto out;
596                                 case 1: /* do it */
597                                         break;
598                                 default:
599                                         ret = -2;
600                                         goto out;
601                                 }
602                         }
603                 }
604
605                 set_canvas_cursor (_cursors->wait);
606
607                 for (int n = 0; n < finfo.channels; ++n) {
608
609                         try {
610
611                                 /* check if we have this thing embedded already */
612
613                                 boost::shared_ptr<Source> s;
614
615                                 if ((s = _session->source_by_path_and_channel (path, n)) == 0) {
616
617                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
618                                                 SourceFactory::createExternal (DataType::AUDIO, *_session,
619                                                                                path, n, 
620                                                                                (mode == ImportAsTapeTrack
621                                                                                 ? Source::Destructive
622                                                                                 : Source::Flag (0)),
623                                                                         true, true));
624                                 } else {
625                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
626                                 }
627
628                                 sources.push_back(source);
629                         }
630
631                         catch (failed_constructor& err) {
632                                 error << string_compose(_("could not open %1"), path) << endmsg;
633                                 goto out;
634                         }
635
636                         ARDOUR_UI::instance()->flush_pending ();
637                 }
638         }
639
640         if (sources.empty()) {
641                 goto out;
642         }
643
644
645         ret = add_sources (paths, sources, pos, disposition, mode, target_regions, target_tracks, track, true);
646
647   out:
648         set_canvas_cursor (current_canvas_cursor);
649         return ret;
650 }
651
652 int
653 Editor::add_sources (vector<string> paths, SourceList& sources, framepos_t& pos, ImportDisposition disposition, ImportMode mode,
654                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool /*add_channel_suffix*/)
655 {
656         vector<boost::shared_ptr<Region> > regions;
657         string region_name;
658         uint32_t input_chan = 0;
659         uint32_t output_chan = 0;
660         bool use_timestamp;
661         
662         use_timestamp = (pos == -1);
663
664         // kludge (for MIDI we're abusing "channel" for "track" here)
665         if (SMFSource::safe_midi_file_extension (paths.front())) {
666                 target_regions = -1;
667         }
668
669         if (target_regions == 1) {
670
671                 /* take all the sources we have and package them up as a region */
672
673                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
674
675                 /* we checked in import_sndfiles() that there were not too many */
676
677                 while (RegionFactory::region_by_name (region_name)) {
678                         region_name = bump_name_once (region_name, '.');
679                 }
680
681                 PropertyList plist;
682
683                 plist.add (ARDOUR::Properties::start, 0);
684                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
685                 plist.add (ARDOUR::Properties::name, region_name);
686                 plist.add (ARDOUR::Properties::layer, 0);
687                 plist.add (ARDOUR::Properties::whole_file, true);
688                 plist.add (ARDOUR::Properties::external, true);
689
690                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
691
692                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
693                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
694                 }
695
696                 regions.push_back (r);
697
698
699         } else if (target_regions == -1 || target_regions > 1) {
700
701                 /* take each source and create a region for each one */
702
703                 SourceList just_one;
704                 SourceList::iterator x;
705                 uint32_t n;
706
707                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
708
709                         just_one.clear ();
710                         just_one.push_back (*x);
711
712                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
713
714                         if (sources.size() > 1 && disposition == ImportDistinctChannels) {
715
716                                 /* generate a per-channel region name so that things work as
717                                  * intended
718                                  */
719                                 
720                                 string path;
721
722                                 if (fs) {
723                                         region_name = basename_nosuffix (fs->path());
724                                 } else {
725                                         region_name = (*x)->name();
726                                 }
727                                 
728                                 switch (sources.size()) {
729                                         /* zero and one channel handled
730                                            by previous if() condition
731                                         */
732                                 case 2:
733                                         if (n == 0) {
734                                                 region_name += "-L";
735                                         } else {
736                                                 region_name += "-R";
737                                         }
738                                         break;
739                                 default:
740                                         region_name += (char) '-';
741                                         region_name += (char) ('1' + n);
742                                         break;
743                                 }
744                                 
745                         } else {
746                                 if (fs) {
747                                         region_name = region_name_from_path (fs->path(), false, false, sources.size(), n);
748                                 } else{
749                                         region_name = (*x)->name();
750                                 }
751                         }
752
753                         PropertyList plist;
754
755                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
756                            for want of a better idea.  It can't be too small, otherwise if this
757                            is a MIDI region the conversion from frames -> beats -> frames will
758                            round it back down to 0 again.
759                         */
760                         framecnt_t len = (*x)->length (pos);
761                         if (len == 0) {
762                                 len = (60.0 / 120.0) * _session->frame_rate ();
763                         }
764
765                         plist.add (ARDOUR::Properties::start, 0);
766                         plist.add (ARDOUR::Properties::length, len);
767                         plist.add (ARDOUR::Properties::name, region_name);
768                         plist.add (ARDOUR::Properties::layer, 0);
769                         plist.add (ARDOUR::Properties::whole_file, true);
770                         plist.add (ARDOUR::Properties::external, true);
771
772                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
773
774                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
775                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
776                         }
777
778                         regions.push_back (r);
779                 }
780         }
781
782         if (target_regions == 1) {
783                 input_chan = regions.front()->n_channels();
784         } else {
785                 if (target_tracks == 1) {
786                         input_chan = regions.size();
787                 } else {
788                         input_chan = 1;
789                 }
790         }
791
792         if (Config->get_output_auto_connect() & AutoConnectMaster) {
793                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
794         } else {
795                 output_chan = input_chan;
796         }
797
798         int n = 0;
799         framepos_t rlen = 0;
800
801         begin_reversible_command (Operations::insert_file);
802         
803         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
804                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
805
806                 if (use_timestamp) {
807                         if (ar) {
808
809                                 /* get timestamp for this region */
810
811                                 const boost::shared_ptr<Source> s (ar->sources().front());
812                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
813
814                                 assert (as);
815
816                                 if (as->natural_position() != 0) {
817                                         pos = as->natural_position();
818                                 } else if (target_tracks == 1) {
819                                         /* hmm, no timestamp available, put it after the previous region
820                                          */
821                                         if (n == 0) {
822                                                 pos = get_preferred_edit_position ();
823                                         } else {
824                                                 pos += rlen;
825                                         }
826                                 } else {
827                                         pos = get_preferred_edit_position ();
828                                 }
829                         } else {
830                                 /* should really get first position in MIDI file, but for now, use edit position*/
831                                 pos = get_preferred_edit_position ();
832                         }
833                 }
834
835
836                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
837
838                 rlen = (*r)->length();
839
840                 if (target_tracks != 1) {
841                         track.reset ();
842                 } else {
843                         if (!use_timestamp || !ar) {
844                                 /* line each one up right after the other */
845                                 pos += (*r)->length();
846                         }
847                 }
848         }
849
850         commit_reversible_command ();
851         
852         /* setup peak file building in another thread */
853
854         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
855                 SourceFactory::setup_peakfile (*x, true);
856         }
857
858         return 0;
859 }
860
861 int
862 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, framepos_t& pos,
863                                      ImportMode mode, boost::shared_ptr<Track>& existing_track)
864 {
865         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
866         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
867
868         switch (mode) {
869         case ImportAsRegion:
870                 /* relax, its been done */
871                 break;
872
873         case ImportToTrack:
874         {
875                 if (!existing_track) {
876
877                         if (ar) {
878                                 existing_track = get_nth_selected_audio_track (0);
879                         } else if (mr) {
880                                 existing_track = get_nth_selected_midi_track (0);
881                         }
882
883                         if (!existing_track) {
884                                 return -1;
885                         }
886                 }
887
888                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
889                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
890                 playlist->clear_changes ();
891                 playlist->add_region (copy, pos);
892                 _session->add_command (new StatefulDiffCommand (playlist));
893                 break;
894         }
895
896         case ImportAsTrack:
897         {
898                 if (!existing_track) {
899                         if (ar) {
900                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
901
902                                 if (at.empty()) {
903                                         return -1;
904                                 }
905
906                                 existing_track = at.front();
907                         } else if (mr) {
908                                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (ChanCount (DataType::MIDI, 1),
909                                                                                                   ChanCount (DataType::MIDI, 1),
910                                                                                                   boost::shared_ptr<PluginInfo>(), 
911                                                                                                   Normal, 0, 1));
912
913                                 if (mt.empty()) {
914                                         return -1;
915                                 }
916
917                                 existing_track = mt.front();
918                         }
919
920                         existing_track->set_name (region->name());
921                 }
922
923                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
924                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
925                 playlist->clear_changes ();
926                 playlist->add_region (copy, pos);
927                 _session->add_command (new StatefulDiffCommand (playlist));
928                 break;
929         }
930
931         case ImportAsTapeTrack:
932         {
933                 if (!ar) {
934                         return -1;
935                 }
936
937                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Destructive));
938                 if (!at.empty()) {
939                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
940                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
941                         playlist->clear_changes ();
942                         playlist->add_region (copy, pos);
943                         _session->add_command (new StatefulDiffCommand (playlist));
944                 }
945                 break;
946         }
947         }
948
949         return 0;
950 }
951
952 void *
953 Editor::_import_thread (void *arg)
954 {
955         SessionEvent::create_per_thread_pool ("import events", 64);
956
957         Editor *ed = (Editor *) arg;
958         return ed->import_thread ();
959 }
960
961 void *
962 Editor::import_thread ()
963 {
964         _session->import_files (import_status);
965         return 0;
966 }