fb1e101f246feb69213f2a08911c6003e912d519
[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->audio_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         vector<string> track_names;
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                 /* if we're creating a new track, name it after the cleaned-up
699                  * and "merged" region name.
700                  */
701
702                 track_names.push_back (region_name);
703
704         } else if (target_regions == -1 || target_regions > 1) {
705
706                 /* take each source and create a region for each one */
707
708                 SourceList just_one;
709                 SourceList::iterator x;
710                 uint32_t n;
711
712                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
713
714                         just_one.clear ();
715                         just_one.push_back (*x);
716
717                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
718
719                         if (sources.size() > 1 && disposition == ImportDistinctChannels) {
720
721                                 /* generate a per-channel region name so that things work as
722                                  * intended
723                                  */
724                                 
725                                 string path;
726
727                                 if (fs) {
728                                         region_name = basename_nosuffix (fs->path());
729                                 } else {
730                                         region_name = (*x)->name();
731                                 }
732                                 
733                                 if (sources.size() == 2) {
734                                         if (n == 0) {
735                                                 region_name += "-L";
736                                         } else {
737                                                 region_name += "-R";
738                                         }
739                                 } else if (sources.size() > 2) {
740                                         region_name += string_compose ("-%1", n+1);
741                                 }
742                                 
743                                 track_names.push_back (region_name);
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                                 track_names.push_back (PBD::basename_nosuffix (paths[n]));
753                         }
754
755                         PropertyList plist;
756
757                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
758                            for want of a better idea.  It can't be too small, otherwise if this
759                            is a MIDI region the conversion from frames -> beats -> frames will
760                            round it back down to 0 again.
761                         */
762                         framecnt_t len = (*x)->length (pos);
763                         if (len == 0) {
764                                 len = (60.0 / 120.0) * _session->frame_rate ();
765                         }
766
767                         plist.add (ARDOUR::Properties::start, 0);
768                         plist.add (ARDOUR::Properties::length, len);
769                         plist.add (ARDOUR::Properties::name, region_name);
770                         plist.add (ARDOUR::Properties::layer, 0);
771                         plist.add (ARDOUR::Properties::whole_file, true);
772                         plist.add (ARDOUR::Properties::external, true);
773
774                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
775
776                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
777                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
778                         }
779
780                         regions.push_back (r);
781                 }
782         }
783
784         if (target_regions == 1) {
785                 input_chan = regions.front()->n_channels();
786         } else {
787                 if (target_tracks == 1) {
788                         input_chan = regions.size();
789                 } else {
790                         input_chan = 1;
791                 }
792         }
793
794         if (Config->get_output_auto_connect() & AutoConnectMaster) {
795                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
796         } else {
797                 output_chan = input_chan;
798         }
799
800         int n = 0;
801         framepos_t rlen = 0;
802
803         begin_reversible_command (Operations::insert_file);
804
805         /* we only use tracks names when importing to new tracks, but we
806          * require that one is defined for every region, just to keep
807          * the API simpler.
808          */
809         assert (regions.size() == track_names.size());
810         
811         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
812                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
813
814                 if (use_timestamp) {
815                         if (ar) {
816
817                                 /* get timestamp for this region */
818
819                                 const boost::shared_ptr<Source> s (ar->sources().front());
820                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
821
822                                 assert (as);
823
824                                 if (as->natural_position() != 0) {
825                                         pos = as->natural_position();
826                                 } else if (target_tracks == 1) {
827                                         /* hmm, no timestamp available, put it after the previous region
828                                          */
829                                         if (n == 0) {
830                                                 pos = get_preferred_edit_position ();
831                                         } else {
832                                                 pos += rlen;
833                                         }
834                                 } else {
835                                         pos = get_preferred_edit_position ();
836                                 }
837                         } else {
838                                 /* should really get first position in MIDI file, but for now, use edit position*/
839                                 pos = get_preferred_edit_position ();
840                         }
841                 }
842                 
843                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track, track_names[n]);
844
845                 rlen = (*r)->length();
846
847                 if (target_tracks != 1) {
848                         track.reset ();
849                 } else {
850                         if (!use_timestamp || !ar) {
851                                 /* line each one up right after the other */
852                                 pos += (*r)->length();
853                         }
854                 }
855         }
856
857         commit_reversible_command ();
858         
859         /* setup peak file building in another thread */
860
861         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
862                 SourceFactory::setup_peakfile (*x, true);
863         }
864
865         return 0;
866 }
867
868 int
869 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, framepos_t& pos,
870                                      ImportMode mode, boost::shared_ptr<Track>& existing_track, const string& new_track_name)
871 {
872         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
873         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
874
875         switch (mode) {
876         case ImportAsRegion:
877                 /* relax, its been done */
878                 break;
879
880         case ImportToTrack:
881         {
882                 if (!existing_track) {
883
884                         if (ar) {
885                                 existing_track = get_nth_selected_audio_track (0);
886                         } else if (mr) {
887                                 existing_track = get_nth_selected_midi_track (0);
888                         }
889
890                         if (!existing_track) {
891                                 return -1;
892                         }
893                 }
894
895                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
896                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
897                 playlist->clear_changes ();
898                 playlist->add_region (copy, pos);
899                 _session->add_command (new StatefulDiffCommand (playlist));
900                 break;
901         }
902
903         case ImportAsTrack:
904         {
905                 if (!existing_track) {
906                         if (ar) {
907                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
908
909                                 if (at.empty()) {
910                                         return -1;
911                                 }
912
913                                 existing_track = at.front();
914                         } else if (mr) {
915                                 list<boost::shared_ptr<MidiTrack> > mt (_session->new_midi_track (ChanCount (DataType::MIDI, 1),
916                                                                                                   ChanCount (DataType::MIDI, 1),
917                                                                                                   boost::shared_ptr<PluginInfo>(), 
918                                                                                                   Normal, 0, 1));
919
920                                 if (mt.empty()) {
921                                         return -1;
922                                 }
923
924                                 existing_track = mt.front();
925                         }
926
927                         if (!new_track_name.empty()) {
928                                 existing_track->set_name (new_track_name);
929                         } else {
930                                 existing_track->set_name (region->name());
931                         }
932                 }
933
934                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
935                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
936                 playlist->clear_changes ();
937                 playlist->add_region (copy, pos);
938                 _session->add_command (new StatefulDiffCommand (playlist));
939                 break;
940         }
941
942         case ImportAsTapeTrack:
943         {
944                 if (!ar) {
945                         return -1;
946                 }
947
948                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, Destructive));
949                 if (!at.empty()) {
950                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
951                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
952                         playlist->clear_changes ();
953                         playlist->add_region (copy, pos);
954                         _session->add_command (new StatefulDiffCommand (playlist));
955                 }
956                 break;
957         }
958         }
959
960         return 0;
961 }
962
963 void *
964 Editor::_import_thread (void *arg)
965 {
966         SessionEvent::create_per_thread_pool ("import events", 64);
967
968         Editor *ed = (Editor *) arg;
969         return ed->import_thread ();
970 }
971
972 void *
973 Editor::import_thread ()
974 {
975         _session->import_files (import_status);
976         return 0;
977 }