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