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