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