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