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