remove cruft
[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         set_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                 set_canvas_cursor (_cursors->wait);
605
606                 for (int n = 0; n < finfo.channels; ++n) {
607
608                         try {
609
610                                 /* check if we have this thing embedded already */
611
612                                 boost::shared_ptr<Source> s;
613
614                                 if ((s = _session->source_by_path_and_channel (path, n)) == 0) {
615
616                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
617                                                 SourceFactory::createExternal (DataType::AUDIO, *_session,
618                                                                                path, n, 
619                                                                                (mode == ImportAsTapeTrack
620                                                                                 ? Source::Destructive
621                                                                                 : Source::Flag (0)),
622                                                                         true, true));
623                                 } else {
624                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
625                                 }
626
627                                 sources.push_back(source);
628                         }
629
630                         catch (failed_constructor& err) {
631                                 error << string_compose(_("could not open %1"), path) << endmsg;
632                                 goto out;
633                         }
634
635                         ARDOUR_UI::instance()->flush_pending ();
636                 }
637         }
638
639         if (sources.empty()) {
640                 goto out;
641         }
642
643
644         ret = add_sources (paths, sources, pos, disposition, mode, target_regions, target_tracks, track, true);
645
646   out:
647         set_canvas_cursor (current_canvas_cursor);
648         return ret;
649 }
650
651 int
652 Editor::add_sources (vector<string> paths, SourceList& sources, framepos_t& pos, ImportDisposition disposition, ImportMode mode,
653                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool /*add_channel_suffix*/)
654 {
655         vector<boost::shared_ptr<Region> > regions;
656         string region_name;
657         uint32_t input_chan = 0;
658         uint32_t output_chan = 0;
659         bool use_timestamp;
660         
661         use_timestamp = (pos == -1);
662
663         // kludge (for MIDI we're abusing "channel" for "track" here)
664         if (SMFSource::safe_midi_file_extension (paths.front())) {
665                 target_regions = -1;
666         }
667
668         if (target_regions == 1) {
669
670                 /* take all the sources we have and package them up as a region */
671
672                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
673
674                 /* we checked in import_sndfiles() that there were not too many */
675
676                 while (RegionFactory::region_by_name (region_name)) {
677                         region_name = bump_name_once (region_name, '.');
678                 }
679
680                 PropertyList plist;
681
682                 plist.add (ARDOUR::Properties::start, 0);
683                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
684                 plist.add (ARDOUR::Properties::name, region_name);
685                 plist.add (ARDOUR::Properties::layer, 0);
686                 plist.add (ARDOUR::Properties::whole_file, true);
687                 plist.add (ARDOUR::Properties::external, true);
688
689                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
690
691                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
692                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
693                 }
694
695                 regions.push_back (r);
696
697
698         } else if (target_regions == -1 || target_regions > 1) {
699
700                 /* take each source and create a region for each one */
701
702                 SourceList just_one;
703                 SourceList::iterator x;
704                 uint32_t n;
705
706                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
707
708                         just_one.clear ();
709                         just_one.push_back (*x);
710
711                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
712
713                         if (sources.size() > 1 && disposition == ImportDistinctChannels) {
714
715                                 /* generate a per-channel region name so that things work as
716                                  * intended
717                                  */
718                                 
719                                 string path;
720
721                                 if (fs) {
722                                         region_name = basename_nosuffix (fs->path());
723                                 } else {
724                                         region_name = (*x)->name();
725                                 }
726                                 
727                                 switch (sources.size()) {
728                                         /* zero and one channel handled
729                                            by previous if() condition
730                                         */
731                                 case 2:
732                                         if (n == 0) {
733                                                 region_name += "-L";
734                                         } else {
735                                                 region_name += "-R";
736                                         }
737                                         break;
738                                 default:
739                                         region_name += (char) '-';
740                                         region_name += (char) ('1' + n);
741                                         break;
742                                 }
743                                 
744                         } else {
745                                 if (fs) {
746                                         region_name = region_name_from_path (fs->path(), false, false, sources.size(), n);
747                                 } else{
748                                         region_name = (*x)->name();
749                                 }
750                         }
751
752                         PropertyList plist;
753
754                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
755                            for want of a better idea.  It can't be too small, otherwise if this
756                            is a MIDI region the conversion from frames -> beats -> frames will
757                            round it back down to 0 again.
758                         */
759                         framecnt_t len = (*x)->length (pos);
760                         if (len == 0) {
761                                 len = (60.0 / 120.0) * _session->frame_rate ();
762                         }
763
764                         plist.add (ARDOUR::Properties::start, 0);
765                         plist.add (ARDOUR::Properties::length, len);
766                         plist.add (ARDOUR::Properties::name, region_name);
767                         plist.add (ARDOUR::Properties::layer, 0);
768                         plist.add (ARDOUR::Properties::whole_file, true);
769                         plist.add (ARDOUR::Properties::external, true);
770
771                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
772
773                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
774                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
775                         }
776
777                         regions.push_back (r);
778                 }
779         }
780
781         if (target_regions == 1) {
782                 input_chan = regions.front()->n_channels();
783         } else {
784                 if (target_tracks == 1) {
785                         input_chan = regions.size();
786                 } else {
787                         input_chan = 1;
788                 }
789         }
790
791         if (Config->get_output_auto_connect() & AutoConnectMaster) {
792                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
793         } else {
794                 output_chan = input_chan;
795         }
796
797         int n = 0;
798         framepos_t rlen = 0;
799
800         begin_reversible_command (Operations::insert_file);
801         
802         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
803                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
804
805                 if (use_timestamp) {
806                         if (ar) {
807
808                                 /* get timestamp for this region */
809
810                                 const boost::shared_ptr<Source> s (ar->sources().front());
811                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
812
813                                 assert (as);
814
815                                 if (as->natural_position() != 0) {
816                                         pos = as->natural_position();
817                                 } else if (target_tracks == 1) {
818                                         /* hmm, no timestamp available, put it after the previous region
819                                          */
820                                         if (n == 0) {
821                                                 pos = get_preferred_edit_position ();
822                                         } else {
823                                                 pos += rlen;
824                                         }
825                                 } else {
826                                         pos = get_preferred_edit_position ();
827                                 }
828                         } else {
829                                 /* should really get first position in MIDI file, but for now, use edit position*/
830                                 pos = get_preferred_edit_position ();
831                         }
832                 }
833
834
835                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
836
837                 rlen = (*r)->length();
838
839                 if (target_tracks != 1) {
840                         track.reset ();
841                 } else {
842                         if (!use_timestamp || !ar) {
843                                 /* line each one up right after the other */
844                                 pos += (*r)->length();
845                         }
846                 }
847         }
848
849         commit_reversible_command ();
850         
851         /* setup peak file building in another thread */
852
853         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
854                 SourceFactory::setup_peakfile (*x, true);
855         }
856
857         return 0;
858 }
859
860 int
861 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, framepos_t& pos,
862                                      ImportMode mode, boost::shared_ptr<Track>& existing_track)
863 {
864         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
865         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
866
867         switch (mode) {
868         case ImportAsRegion:
869                 /* relax, its been done */
870                 break;
871
872         case ImportToTrack:
873         {
874                 if (!existing_track) {
875
876                         if (ar) {
877                                 existing_track = get_nth_selected_audio_track (0);
878                         } else if (mr) {
879                                 existing_track = get_nth_selected_midi_track (0);
880                         }
881
882                         if (!existing_track) {
883                                 return -1;
884                         }
885                 }
886
887                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
888                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
889                 playlist->clear_changes ();
890                 playlist->add_region (copy, pos);
891                 _session->add_command (new StatefulDiffCommand (playlist));
892                 break;
893         }
894
895         case ImportAsTrack:
896         {
897                 if (!existing_track) {
898                         if (ar) {
899                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
900
901                                 if (at.empty()) {
902                                         return -1;
903                                 }
904
905                                 existing_track = at.front();
906                         } else if (mr) {
907                                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (ChanCount (DataType::MIDI, 1),
908                                                                                                   ChanCount (DataType::MIDI, 1),
909                                                                                                   boost::shared_ptr<PluginInfo>(), 
910                                                                                                   Normal, 0, 1));
911
912                                 if (mt.empty()) {
913                                         return -1;
914                                 }
915
916                                 existing_track = mt.front();
917                         }
918
919                         existing_track->set_name (region->name());
920                 }
921
922                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
923                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
924                 playlist->clear_changes ();
925                 playlist->add_region (copy, pos);
926                 _session->add_command (new StatefulDiffCommand (playlist));
927                 break;
928         }
929
930         case ImportAsTapeTrack:
931         {
932                 if (!ar) {
933                         return -1;
934                 }
935
936                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Destructive));
937                 if (!at.empty()) {
938                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
939                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
940                         playlist->clear_changes ();
941                         playlist->add_region (copy, pos);
942                         _session->add_command (new StatefulDiffCommand (playlist));
943                 }
944                 break;
945         }
946         }
947
948         return 0;
949 }
950
951 void *
952 Editor::_import_thread (void *arg)
953 {
954         SessionEvent::create_per_thread_pool ("import events", 64);
955
956         Editor *ed = (Editor *) arg;
957         return ed->import_thread ();
958 }
959
960 void *
961 Editor::import_thread ()
962 {
963         _session->import_files (import_status);
964         return 0;
965 }