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