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