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