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