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