initial attempt at importing SMF tempo maps during MIDI import.
[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)
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         bool have_meter = false;
280
281         for (size_t n = 0; n < num_tempos; ++n) {
282
283                 Evoral::SMF::Tempo* t = smf.nth_tempo (n);
284                 assert (t);
285
286                 Tempo tempo (60 * (1000000 / t->microseconds_per_quarter_note), 4.0);
287                 new_map.add_tempo (tempo, (t->time_pulses/smf.ppqn()) / 4.0, 0, TempoSection::Constant, MusicTime);
288
289                 Meter meter (t->numerator, t->denominator);
290                 Timecode::BBT_Time bbt; /* 1|1|0 which is correct for the no-meter case */
291                 if (have_meter) {
292                         bbt  = new_map.bbt_at_beat ((t->time_pulses/smf.ppqn()));
293                 }
294                 new_map.add_meter (meter, t->time_pulses, bbt, MusicTime);
295
296                 cerr << "@ " << t->time_pulses/smf.ppqn() << " ("
297                      << t->time_seconds << ") Add T " << tempo << " M " << meter << endl;
298         }
299
300         cerr << "NEW MAP:\n";
301         new_map.dump (cerr);
302
303         _session->tempo_map() = new_map;
304 }
305
306 void
307 Editor::do_import (vector<string>        paths,
308                    ImportDisposition     disposition,
309                    ImportMode            mode,
310                    SrcQuality            quality,
311                    MidiTrackNameSource   midi_track_name_source,
312                    MidiTempoMapDisposition smf_tempo_disposition,
313                    framepos_t&           pos,
314                    ARDOUR::PluginInfoPtr instrument)
315 {
316         boost::shared_ptr<Track> track;
317         vector<string> to_import;
318         int nth = 0;
319         bool use_timestamp = (pos == -1);
320
321         if (smf_tempo_disposition == SMFTempoUse) {
322                 /* Find the first MIDI file with a tempo map, and import it
323                    before we do anything else.
324                 */
325
326                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
327                         Evoral::SMF smf;
328                         if (smf.open (*a)) {
329                                 continue;
330                         }
331                         if (smf.num_tempos() > 0) {
332                                 import_smf_tempo_map (smf);
333                                 smf.close ();
334                                 break;
335                         }
336                         smf.close ();
337                 }
338         }
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         import_status.midi_track_name_source = midi_track_name_source;
345
346         ImportProgressWindow ipw (&import_status, _("Import"), _("Cancel Import"));
347
348         bool ok = true;
349
350         if (disposition == Editing::ImportMergeFiles) {
351
352                 /* create 1 region from all paths, add to 1 track,
353                    ignore "track"
354                 */
355
356                 bool cancel = false;
357                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
358                         int check = check_whether_and_how_to_import(*a, false);
359                         if (check == 2) {
360                                 cancel = true;
361                                 break;
362                         }
363                 }
364
365                 if (cancel) {
366                         ok = false;
367                 } else {
368                         ipw.show ();
369                         ok = (import_sndfiles (paths, disposition, mode, quality, pos, 1, 1, track, false, instrument) == 0);
370                         import_status.sources.clear();
371                 }
372
373         } else {
374
375                 bool replace = false;
376
377                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
378
379                         const int check = check_whether_and_how_to_import (*a, true);
380
381                         switch (check) {
382                         case 2:
383                                 // user said skip
384                                 continue;
385                         case 0:
386                                 fatal << "Updating existing sources should be disabled!" << endmsg;
387                                 abort(); /* NOTREACHED*/
388                                 break;
389                         case 1:
390                                 replace = false;
391                                 break;
392                         default:
393                                 fatal << "Illegal return " << check <<  " from check_whether_and_how_to_import()!" << endmsg;
394                                 abort(); /* NOTREACHED*/
395                         }
396
397                         /* have to reset this for every file we handle */
398
399                         if (use_timestamp) {
400                                 pos = -1;
401                         }
402
403                         ipw.show ();
404
405                         switch (disposition) {
406                         case Editing::ImportDistinctFiles:
407
408                                 to_import.clear ();
409                                 to_import.push_back (*a);
410
411                                 if (mode == Editing::ImportToTrack) {
412                                         track = get_nth_selected_audio_track (nth++);
413                                 }
414
415                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, 1, -1, track, replace, instrument) == 0);
416                                 import_status.sources.clear();
417                                 break;
418
419                         case Editing::ImportDistinctChannels:
420
421                                 to_import.clear ();
422                                 to_import.push_back (*a);
423
424                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, -1, -1, track, replace, instrument) == 0);
425                                 import_status.sources.clear();
426                                 break;
427
428                         case Editing::ImportSerializeFiles:
429
430                                 to_import.clear ();
431                                 to_import.push_back (*a);
432
433                                 ok = (import_sndfiles (to_import, disposition, mode, quality, pos, 1, 1, track, replace, instrument) == 0);
434                                 import_status.sources.clear();
435                                 break;
436
437                         case Editing::ImportMergeFiles:
438                                 // Not entered, handled in earlier if() branch
439                                 break;
440                         }
441                 }
442         }
443
444         if (ok) {
445                 _session->save_state ("");
446         }
447
448         import_status.all_done = true;
449 }
450
451 void
452 Editor::do_embed (vector<string> paths, ImportDisposition import_as, ImportMode mode, framepos_t& pos, ARDOUR::PluginInfoPtr instrument)
453 {
454         boost::shared_ptr<Track> track;
455         bool check_sample_rate = true;
456         bool ok = false;
457         vector<string> to_embed;
458         bool multi = paths.size() > 1;
459         int nth = 0;
460         bool use_timestamp = (pos == -1);
461
462         switch (import_as) {
463         case Editing::ImportDistinctFiles:
464                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
465
466                         /* have to reset this for every file we handle */
467                         if (use_timestamp) {
468                                 pos = -1;
469                         }
470
471                         to_embed.clear ();
472                         to_embed.push_back (*a);
473
474                         if (mode == Editing::ImportToTrack) {
475                                 track = get_nth_selected_audio_track (nth++);
476                         }
477
478                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, mode, pos, 1, -1, track, instrument) < -1) {
479                                 goto out;
480                         }
481                 }
482                 break;
483
484         case Editing::ImportDistinctChannels:
485                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
486
487                         /* have to reset this for every file we handle */
488                         if (use_timestamp) {
489                                 pos = -1;
490                         }
491
492                         to_embed.clear ();
493                         to_embed.push_back (*a);
494
495                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, mode, pos, -1, -1, track, instrument) < -1) {
496                                 goto out;
497                         }
498                 }
499                 break;
500
501         case Editing::ImportMergeFiles:
502                 if (embed_sndfiles (paths, multi, check_sample_rate, import_as, mode, pos, 1, 1, track, instrument) < -1) {
503                         goto out;
504                 }
505                 break;
506
507         case Editing::ImportSerializeFiles:
508                 for (vector<string>::iterator a = paths.begin(); a != paths.end(); ++a) {
509
510                         /* have to reset this for every file we handle */
511                         if (use_timestamp) {
512                                 pos = -1;
513                         }
514
515                         to_embed.clear ();
516                         to_embed.push_back (*a);
517
518                         if (embed_sndfiles (to_embed, multi, check_sample_rate, import_as, mode, pos, 1, 1, track, instrument) < -1) {
519                                 goto out;
520                         }
521                 }
522                 break;
523         }
524
525         ok = true;
526
527   out:
528         if (ok) {
529                 _session->save_state ("");
530         }
531 }
532
533 int
534 Editor::import_sndfiles (vector<string>            paths,
535                          ImportDisposition         disposition,
536                          ImportMode                mode,
537                          SrcQuality                quality,
538                          framepos_t&               pos,
539                          int                       target_regions,
540                          int                       target_tracks,
541                          boost::shared_ptr<Track>& track,
542                          bool                      replace,
543                          ARDOUR::PluginInfoPtr     instrument)
544 {
545         import_status.paths = paths;
546         import_status.done = false;
547         import_status.cancel = false;
548         import_status.freeze = false;
549         import_status.quality = quality;
550         import_status.replace_existing_source = replace;
551         import_status.split_midi_channels = (disposition == Editing::ImportDistinctChannels);
552
553         import_status.mode = mode;
554         import_status.pos = pos;
555         import_status.target_tracks = target_tracks;
556         import_status.target_regions = target_regions;
557         import_status.track = track;
558         import_status.replace = replace;
559
560         CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
561         gdk_flush ();
562
563         /* start import thread for this spec. this will ultimately call Session::import_files()
564            which, if successful, will add the files as regions to the region list. its up to us
565            (the GUI) to direct additional steps after that.
566         */
567
568         pthread_create_and_store ("import", &import_status.thread, _import_thread, this);
569         pthread_detach (import_status.thread);
570
571         while (!import_status.done && !import_status.cancel) {
572                 gtk_main_iteration ();
573         }
574
575         // wait for thread to terminate
576         while (!import_status.done) {
577                 gtk_main_iteration ();
578         }
579
580         int result = -1;
581
582         if (!import_status.cancel && !import_status.sources.empty()) {
583                 result = add_sources (
584                         import_status.paths,
585                         import_status.sources,
586                         import_status.pos,
587                         disposition,
588                         import_status.mode,
589                         import_status.target_regions,
590                         import_status.target_tracks,
591                         track, false, instrument
592                         );
593
594                 /* update position from results */
595
596                 pos = import_status.pos;
597         }
598
599         return result;
600 }
601
602 int
603 Editor::embed_sndfiles (vector<string>            paths,
604                         bool                      multifile,
605                         bool&                     check_sample_rate,
606                         ImportDisposition         disposition,
607                         ImportMode                mode,
608                         framepos_t&               pos,
609                         int                       target_regions,
610                         int                       target_tracks,
611                         boost::shared_ptr<Track>& track,
612                         ARDOUR::PluginInfoPtr     instrument)
613 {
614         boost::shared_ptr<AudioFileSource> source;
615         SourceList sources;
616         string linked_path;
617         SoundFileInfo finfo;
618
619         CursorContext::Handle cursor_ctx = CursorContext::create(*this, _cursors->wait);
620         gdk_flush ();
621
622         for (vector<string>::iterator p = paths.begin(); p != paths.end(); ++p) {
623
624                 string path = *p;
625                 string error_msg;
626
627                 /* note that we temporarily truncated _id at the colon */
628
629                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
630                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
631                         return -3;
632                 }
633
634                 if (check_sample_rate  && (finfo.samplerate != (int) _session->frame_rate())) {
635                         vector<string> choices;
636
637                         if (multifile) {
638                                 choices.push_back (_("Cancel entire import"));
639                                 choices.push_back (_("Don't embed it"));
640                                 choices.push_back (_("Embed all without questions"));
641
642                                 Gtkmm2ext::Choice rate_choice (
643                                         _("Sample rate"),
644                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
645                                                         short_path (path, 40)),
646                                         choices, false
647                                         );
648
649                                 int resx = rate_choice.run ();
650
651                                 switch (resx) {
652                                 case 0: /* stop a multi-file import */
653                                         return -2;
654                                 case 1: /* don't embed this one */
655                                         return -1;
656                                 case 2: /* do it, and the rest without asking */
657                                         check_sample_rate = false;
658                                         break;
659                                 case 3: /* do it */
660                                         break;
661                                 default:
662                                         return -2;
663                                 }
664                         } else {
665                                 choices.push_back (_("Cancel"));
666                                 choices.push_back (_("Embed it anyway"));
667
668                                 Gtkmm2ext::Choice rate_choice (
669                                         _("Sample rate"),
670                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
671                                         choices, false
672                                         );
673
674                                 int resx = rate_choice.run ();
675
676                                 switch (resx) {
677                                 case 0: /* don't import */
678                                         return -1;
679                                 case 1: /* do it */
680                                         break;
681                                 default:
682                                         return -2;
683                                 }
684                         }
685                 }
686
687                 for (int n = 0; n < finfo.channels; ++n) {
688
689                         try {
690
691                                 /* check if we have this thing embedded already */
692
693                                 boost::shared_ptr<Source> s;
694
695                                 if ((s = _session->audio_source_by_path_and_channel (path, n)) == 0) {
696
697                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
698                                                 SourceFactory::createExternal (DataType::AUDIO, *_session,
699                                                                                path, n,
700                                                                                (mode == ImportAsTapeTrack
701                                                                                 ? Source::Destructive
702                                                                                 : Source::Flag (0)),
703                                                                         true, true));
704                                 } else {
705                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
706                                 }
707
708                                 sources.push_back(source);
709                         }
710
711                         catch (failed_constructor& err) {
712                                 error << string_compose(_("could not open %1"), path) << endmsg;
713                                 return -3;
714                         }
715
716                         gtk_main_iteration();
717                 }
718         }
719
720         if (!sources.empty()) {
721                 return add_sources (paths, sources, pos, disposition, mode, target_regions, target_tracks, track, true, instrument);
722         }
723
724         return 0;
725 }
726
727 int
728 Editor::add_sources (vector<string>            paths,
729                      SourceList&               sources,
730                      framepos_t&               pos,
731                      ImportDisposition         disposition,
732                      ImportMode                mode,
733                      int                       target_regions,
734                      int                       target_tracks,
735                      boost::shared_ptr<Track>& track,
736                      bool                      /*add_channel_suffix*/,
737                      ARDOUR::PluginInfoPtr     instrument)
738 {
739         vector<boost::shared_ptr<Region> > regions;
740         string region_name;
741         uint32_t input_chan = 0;
742         uint32_t output_chan = 0;
743         bool use_timestamp;
744         vector<string> track_names;
745
746         use_timestamp = (pos == -1);
747
748         // kludge (for MIDI we're abusing "channel" for "track" here)
749         if (SMFSource::safe_midi_file_extension (paths.front())) {
750                 target_regions = -1;
751         }
752
753         if (target_regions == 1) {
754
755                 /* take all the sources we have and package them up as a region */
756
757                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
758
759                 /* we checked in import_sndfiles() that there were not too many */
760
761                 while (RegionFactory::region_by_name (region_name)) {
762                         region_name = bump_name_once (region_name, '.');
763                 }
764
765                 PropertyList plist;
766
767                 plist.add (ARDOUR::Properties::start, 0);
768                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
769                 plist.add (ARDOUR::Properties::name, region_name);
770                 plist.add (ARDOUR::Properties::layer, 0);
771                 plist.add (ARDOUR::Properties::whole_file, true);
772                 plist.add (ARDOUR::Properties::external, true);
773
774                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
775
776                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
777                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
778                 }
779
780                 regions.push_back (r);
781
782                 /* if we're creating a new track, name it after the cleaned-up
783                  * and "merged" region name.
784                  */
785
786                 track_names.push_back (region_name);
787
788         } else if (target_regions == -1 || target_regions > 1) {
789
790                 /* take each source and create a region for each one */
791
792                 SourceList just_one;
793                 SourceList::iterator x;
794                 uint32_t n;
795
796                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
797
798                         just_one.clear ();
799                         just_one.push_back (*x);
800
801                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
802
803                         if (sources.size() > 1 && disposition == ImportDistinctChannels) {
804
805                                 /* generate a per-channel region name so that things work as
806                                  * intended
807                                  */
808
809                                 string path;
810
811                                 if (fs) {
812                                         region_name = basename_nosuffix (fs->path());
813                                 } else {
814                                         region_name = (*x)->name();
815                                 }
816
817                                 if (sources.size() == 2) {
818                                         if (n == 0) {
819                                                 region_name += "-L";
820                                         } else {
821                                                 region_name += "-R";
822                                         }
823                                 } else if (sources.size() > 2) {
824                                         region_name += string_compose ("-%1", n+1);
825                                 }
826
827                                 track_names.push_back (region_name);
828
829                         } else {
830                                 if (fs) {
831                                         region_name = region_name_from_path (fs->path(), false, false, sources.size(), n);
832                                 } else {
833                                         region_name = (*x)->name();
834                                 }
835
836                                 if (SMFSource::safe_midi_file_extension (paths.front())) {
837                                         string track_name = string_compose ("%1-t%2", PBD::basename_nosuffix (fs->path()), (n + 1));
838                                         track_names.push_back (track_name);
839                                 } else {
840                                         track_names.push_back (PBD::basename_nosuffix (paths[n]));
841                                 }
842                         }
843
844                         PropertyList plist;
845
846                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
847                            for want of a better idea.  It can't be too small, otherwise if this
848                            is a MIDI region the conversion from frames -> beats -> frames will
849                            round it back down to 0 again.
850                         */
851                         framecnt_t len = (*x)->length (pos);
852                         if (len == 0) {
853                                 len = (60.0 / 120.0) * _session->frame_rate ();
854                         }
855
856                         plist.add (ARDOUR::Properties::start, 0);
857                         plist.add (ARDOUR::Properties::length, len);
858                         plist.add (ARDOUR::Properties::name, region_name);
859                         plist.add (ARDOUR::Properties::layer, 0);
860                         plist.add (ARDOUR::Properties::whole_file, true);
861                         plist.add (ARDOUR::Properties::external, true);
862
863                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
864
865                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
866                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
867                         }
868
869                         regions.push_back (r);
870                 }
871         }
872
873         if (target_regions == 1) {
874                 input_chan = regions.front()->n_channels();
875         } else {
876                 if (target_tracks == 1) {
877                         input_chan = regions.size();
878                 } else {
879                         input_chan = 1;
880                 }
881         }
882
883         if (Config->get_output_auto_connect() & AutoConnectMaster) {
884                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
885         } else {
886                 output_chan = input_chan;
887         }
888
889         int n = 0;
890         framepos_t rlen = 0;
891
892         begin_reversible_command (Operations::insert_file);
893
894         /* we only use tracks names when importing to new tracks, but we
895          * require that one is defined for every region, just to keep
896          * the API simpler.
897          */
898         assert (regions.size() == track_names.size());
899
900         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
901                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
902
903                 if (use_timestamp) {
904                         if (ar) {
905
906                                 /* get timestamp for this region */
907
908                                 const boost::shared_ptr<Source> s (ar->sources().front());
909                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
910
911                                 assert (as);
912
913                                 if (as->natural_position() != 0) {
914                                         pos = as->natural_position();
915                                 } else if (target_tracks == 1) {
916                                         /* hmm, no timestamp available, put it after the previous region
917                                          */
918                                         if (n == 0) {
919                                                 pos = get_preferred_edit_position ();
920                                         } else {
921                                                 pos += rlen;
922                                         }
923                                 } else {
924                                         pos = get_preferred_edit_position ();
925                                 }
926                         } else {
927                                 /* should really get first position in MIDI file, but for now, use edit position*/
928                                 pos = get_preferred_edit_position ();
929                         }
930                 }
931
932                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track, track_names[n], instrument);
933
934                 rlen = (*r)->length();
935
936                 if (target_tracks != 1) {
937                         track.reset ();
938                 } else {
939                         if (!use_timestamp || !ar) {
940                                 /* line each one up right after the other */
941                                 pos += (*r)->length();
942                         }
943                 }
944         }
945
946         commit_reversible_command ();
947
948         /* setup peak file building in another thread */
949
950         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
951                 SourceFactory::setup_peakfile (*x, true);
952         }
953
954         return 0;
955 }
956
957 int
958 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region,
959                                      uint32_t                  in_chans,
960                                      uint32_t                  out_chans,
961                                      framepos_t&               pos,
962                                      ImportMode                mode,
963                                      boost::shared_ptr<Track>& existing_track,
964                                      const string&             new_track_name,
965                                      ARDOUR::PluginInfoPtr     instrument)
966 {
967         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
968         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
969
970         switch (mode) {
971         case ImportAsRegion:
972                 /* relax, its been done */
973                 break;
974
975         case ImportToTrack:
976         {
977                 if (!existing_track) {
978
979                         if (ar) {
980                                 existing_track = get_nth_selected_audio_track (0);
981                         } else if (mr) {
982                                 existing_track = get_nth_selected_midi_track (0);
983                         }
984
985                         if (!existing_track) {
986                                 return -1;
987                         }
988                 }
989
990                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
991                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
992                 playlist->clear_changes ();
993                 playlist->add_region (copy, pos);
994                 if (Config->get_edit_mode() == Ripple)
995                         playlist->ripple (pos, copy->length(), copy);
996
997                 _session->add_command (new StatefulDiffCommand (playlist));
998                 break;
999         }
1000
1001         case ImportAsTrack:
1002         {
1003                 if (!existing_track) {
1004                         if (ar) {
1005                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, 0, 1, string(), PresentationInfo::max_order, Normal));
1006
1007                                 if (at.empty()) {
1008                                         return -1;
1009                                 }
1010                                 if (Config->get_strict_io ()) {
1011                                         for (list<boost::shared_ptr<AudioTrack> >::iterator i = at.begin(); i != at.end(); ++i) {
1012                                                 (*i)->set_strict_io (true);
1013                                         }
1014                                 }
1015
1016                                 existing_track = at.front();
1017                         } else if (mr) {
1018                                 list<boost::shared_ptr<MidiTrack> > mt (
1019                                         _session->new_midi_track (ChanCount (DataType::MIDI, 1),
1020                                                                   ChanCount (DataType::MIDI, 1),
1021                                                                   instrument, (Plugin::PresetRecord*) 0,
1022                                                                   (RouteGroup*) 0,
1023                                                                   1,
1024                                                                   string(),
1025                                                                   PresentationInfo::max_order));
1026
1027                                 if (mt.empty()) {
1028                                         return -1;
1029                                 }
1030                                 if (Config->get_strict_io ()) {
1031                                         for (list<boost::shared_ptr<MidiTrack> >::iterator i = mt.begin(); i != mt.end(); ++i) {
1032                                                 (*i)->set_strict_io (true);
1033                                         }
1034                                 }
1035
1036                                 // TODO set strict_io from preferences
1037                                 existing_track = mt.front();
1038                         }
1039
1040                         if (!new_track_name.empty()) {
1041                                 existing_track->set_name (new_track_name);
1042                         } else {
1043                                 existing_track->set_name (region->name());
1044                         }
1045                 }
1046
1047                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
1048                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
1049                 playlist->clear_changes ();
1050                 playlist->add_region (copy, pos);
1051                 _session->add_command (new StatefulDiffCommand (playlist));
1052                 break;
1053         }
1054
1055         case ImportAsTapeTrack:
1056         {
1057                 if (!ar) {
1058                         return -1;
1059                 }
1060
1061                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, 0, 1, string(), PresentationInfo::max_order, Destructive));
1062                 if (!at.empty()) {
1063                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
1064                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
1065                         playlist->clear_changes ();
1066                         playlist->add_region (copy, pos);
1067                         _session->add_command (new StatefulDiffCommand (playlist));
1068                 }
1069                 if (Config->get_strict_io ()) {
1070                         for (list<boost::shared_ptr<AudioTrack> >::iterator i = at.begin(); i != at.end(); ++i) {
1071                                 (*i)->set_strict_io (true);
1072                         }
1073                 }
1074                 break;
1075         }
1076         }
1077
1078         return 0;
1079 }
1080
1081 void *
1082 Editor::_import_thread (void *arg)
1083 {
1084         SessionEvent::create_per_thread_pool ("import events", 64);
1085
1086         Editor *ed = (Editor *) arg;
1087         return ed->import_thread ();
1088 }
1089
1090 void *
1091 Editor::import_thread ()
1092 {
1093         _session->import_files (import_status);
1094         return 0;
1095 }