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