Use labs() for long instead of abs()
[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 (!finfo.seekable) {
653                         MessageDialog msg ( string_compose ( _("%1\nThis audiofile cannot be embedded. It must be imported!"), short_path (path, 40)), false, Gtk::MESSAGE_ERROR);
654                         msg.set_position (WIN_POS_MOUSE);
655                         msg.run ();
656                         return -2;
657                 }
658
659                 if (check_sample_rate  && (finfo.samplerate != (int) _session->sample_rate())) {
660                         vector<string> choices;
661
662                         if (multifile) {
663                                 choices.push_back (_("Cancel entire import"));
664                                 choices.push_back (_("Don't embed it"));
665                                 choices.push_back (_("Embed all without questions"));
666
667                                 ArdourWidgets::Choice rate_choice (
668                                         _("Sample rate"),
669                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
670                                                         short_path (path, 40)),
671                                         choices, false
672                                         );
673
674                                 int resx = rate_choice.run ();
675
676                                 switch (resx) {
677                                 case 0: /* stop a multi-file import */
678                                         return -2;
679                                 case 1: /* don't embed this one */
680                                         return -1;
681                                 case 2: /* do it, and the rest without asking */
682                                         check_sample_rate = false;
683                                         break;
684                                 case 3: /* do it */
685                                         break;
686                                 default:
687                                         return -2;
688                                 }
689                         } else {
690                                 choices.push_back (_("Cancel"));
691                                 choices.push_back (_("Embed it anyway"));
692
693                                 ArdourWidgets::Choice rate_choice (
694                                         _("Sample rate"),
695                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
696                                         choices, false
697                                         );
698
699                                 int resx = rate_choice.run ();
700
701                                 switch (resx) {
702                                 case 0: /* don't import */
703                                         return -1;
704                                 case 1: /* do it */
705                                         break;
706                                 default:
707                                         return -2;
708                                 }
709                         }
710                 }
711
712                 for (int n = 0; n < finfo.channels; ++n) {
713
714                         try {
715
716                                 /* check if we have this thing embedded already */
717
718                                 boost::shared_ptr<Source> s;
719
720                                 if ((s = _session->audio_source_by_path_and_channel (path, n)) == 0) {
721
722                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
723                                                 SourceFactory::createExternal (DataType::AUDIO, *_session,
724                                                                                path, n,
725                                                                                (mode == ImportAsTapeTrack
726                                                                                 ? Source::Destructive
727                                                                                 : Source::Flag (0)),
728                                                                         true, true));
729                                 } else {
730                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
731                                 }
732
733                                 sources.push_back(source);
734                         }
735
736                         catch (failed_constructor& err) {
737                                 error << string_compose(_("could not open %1"), path) << endmsg;
738                                 return -3;
739                         }
740
741                         gtk_main_iteration();
742                 }
743         }
744
745         if (!sources.empty()) {
746                 return add_sources (paths, sources, pos, disposition, mode, target_regions, target_tracks, track, true, instrument);
747         }
748
749         return 0;
750 }
751
752 int
753 Editor::add_sources (vector<string>            paths,
754                      SourceList&               sources,
755                      samplepos_t&              pos,
756                      ImportDisposition         disposition,
757                      ImportMode                mode,
758                      int                       target_regions,
759                      int                       target_tracks,
760                      boost::shared_ptr<Track>& track,
761                      bool                      /*add_channel_suffix*/,
762                      ARDOUR::PluginInfoPtr     instrument)
763 {
764         vector<boost::shared_ptr<Region> > regions;
765         string region_name;
766         uint32_t input_chan = 0;
767         uint32_t output_chan = 0;
768         bool use_timestamp;
769         vector<string> track_names;
770
771         use_timestamp = (pos == -1);
772
773         // kludge (for MIDI we're abusing "channel" for "track" here)
774         if (SMFSource::safe_midi_file_extension (paths.front())) {
775                 target_regions = -1;
776         }
777
778         if (target_regions == 1) {
779
780                 /* take all the sources we have and package them up as a region */
781
782                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
783
784                 /* we checked in import_sndfiles() that there were not too many */
785
786                 while (RegionFactory::region_by_name (region_name)) {
787                         region_name = bump_name_once (region_name, '.');
788                 }
789
790                 PropertyList plist;
791
792                 plist.add (ARDOUR::Properties::start, 0);
793                 plist.add (ARDOUR::Properties::length, sources[0]->length (pos));
794                 plist.add (ARDOUR::Properties::name, region_name);
795                 plist.add (ARDOUR::Properties::layer, 0);
796                 plist.add (ARDOUR::Properties::whole_file, true);
797                 plist.add (ARDOUR::Properties::external, true);
798
799                 boost::shared_ptr<Region> r = RegionFactory::create (sources, plist);
800
801                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
802                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
803                 }
804
805                 regions.push_back (r);
806
807                 /* if we're creating a new track, name it after the cleaned-up
808                  * and "merged" region name.
809                  */
810
811                 track_names.push_back (region_name);
812
813         } else if (target_regions == -1 || target_regions > 1) {
814
815                 /* take each source and create a region for each one */
816
817                 SourceList just_one;
818                 SourceList::iterator x;
819                 uint32_t n;
820
821                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
822
823                         just_one.clear ();
824                         just_one.push_back (*x);
825
826                         boost::shared_ptr<FileSource> fs = boost::dynamic_pointer_cast<FileSource> (*x);
827
828                         if (sources.size() > 1 && disposition == ImportDistinctChannels) {
829
830                                 /* generate a per-channel region name so that things work as
831                                  * intended
832                                  */
833
834                                 string path;
835
836                                 if (fs) {
837                                         region_name = basename_nosuffix (fs->path());
838                                 } else {
839                                         region_name = (*x)->name();
840                                 }
841
842                                 if (sources.size() == 2) {
843                                         if (n == 0) {
844                                                 region_name += "-L";
845                                         } else {
846                                                 region_name += "-R";
847                                         }
848                                 } else if (sources.size() > 2) {
849                                         region_name += string_compose ("-%1", n+1);
850                                 }
851
852                                 track_names.push_back (region_name);
853
854                         } else {
855                                 if (fs) {
856                                         region_name = region_name_from_path (fs->path(), false, false, sources.size(), n);
857                                 } else {
858                                         region_name = (*x)->name();
859                                 }
860
861                                 if (SMFSource::safe_midi_file_extension (paths.front())) {
862                                         string track_name = string_compose ("%1-t%2", PBD::basename_nosuffix (fs->path()), (n + 1));
863                                         track_names.push_back (track_name);
864                                 } else {
865                                         track_names.push_back (PBD::basename_nosuffix (paths[n]));
866                                 }
867                         }
868
869                         PropertyList plist;
870
871                         /* Fudge region length to ensure it is non-zero; make it 1 beat at 120bpm
872                            for want of a better idea.  It can't be too small, otherwise if this
873                            is a MIDI region the conversion from samples -> beats -> samples will
874                            round it back down to 0 again.
875                         */
876                         samplecnt_t len = (*x)->length (pos);
877                         if (len == 0) {
878                                 len = (60.0 / 120.0) * _session->sample_rate ();
879                         }
880
881                         plist.add (ARDOUR::Properties::start, 0);
882                         plist.add (ARDOUR::Properties::length, len);
883                         plist.add (ARDOUR::Properties::name, region_name);
884                         plist.add (ARDOUR::Properties::layer, 0);
885                         plist.add (ARDOUR::Properties::whole_file, true);
886                         plist.add (ARDOUR::Properties::external, true);
887
888                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, plist);
889
890                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
891                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
892                         }
893
894                         regions.push_back (r);
895                 }
896         }
897
898         if (target_regions == 1) {
899                 input_chan = regions.front()->n_channels();
900         } else {
901                 if (target_tracks == 1) {
902                         input_chan = regions.size();
903                 } else {
904                         input_chan = 1;
905                 }
906         }
907
908         if (Config->get_output_auto_connect() & AutoConnectMaster) {
909                 output_chan = (_session->master_out() ? _session->master_out()->n_inputs().n_audio() : input_chan);
910         } else {
911                 output_chan = input_chan;
912         }
913
914         int n = 0;
915         samplepos_t rlen = 0;
916
917         begin_reversible_command (Operations::insert_file);
918
919         /* we only use tracks names when importing to new tracks, but we
920          * require that one is defined for every region, just to keep
921          * the API simpler.
922          */
923         assert (regions.size() == track_names.size());
924
925         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
926                 boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion> (*r);
927
928                 if (use_timestamp) {
929                         if (ar) {
930
931                                 /* get timestamp for this region */
932
933                                 const boost::shared_ptr<Source> s (ar->sources().front());
934                                 const boost::shared_ptr<AudioSource> as = boost::dynamic_pointer_cast<AudioSource> (s);
935
936                                 assert (as);
937
938                                 if (as->natural_position() != 0) {
939                                         pos = as->natural_position();
940                                 } else if (target_tracks == 1) {
941                                         /* hmm, no timestamp available, put it after the previous region
942                                          */
943                                         if (n == 0) {
944                                                 pos = get_preferred_edit_position ();
945                                         } else {
946                                                 pos += rlen;
947                                         }
948                                 } else {
949                                         pos = get_preferred_edit_position ();
950                                 }
951                         } else {
952                                 /* should really get first position in MIDI file, but for now, use edit position*/
953                                 pos = get_preferred_edit_position ();
954                         }
955                 }
956
957                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track, track_names[n], instrument);
958
959                 rlen = (*r)->length();
960
961                 if (target_tracks != 1) {
962                         track.reset ();
963                 } else {
964                         if (!use_timestamp || !ar) {
965                                 /* line each one up right after the other */
966                                 pos += (*r)->length();
967                         }
968                 }
969         }
970
971         commit_reversible_command ();
972
973         /* setup peak file building in another thread */
974
975         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
976                 SourceFactory::setup_peakfile (*x, true);
977         }
978
979         return 0;
980 }
981
982 int
983 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region,
984                                      uint32_t                  in_chans,
985                                      uint32_t                  out_chans,
986                                      samplepos_t&               pos,
987                                      ImportMode                mode,
988                                      boost::shared_ptr<Track>& existing_track,
989                                      const string&             new_track_name,
990                                      ARDOUR::PluginInfoPtr     instrument)
991 {
992         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
993         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
994
995         switch (mode) {
996         case ImportAsRegion:
997                 /* relax, its been done */
998                 break;
999
1000         case ImportToTrack:
1001         {
1002                 if (!existing_track) {
1003
1004                         if (ar) {
1005                                 existing_track = get_nth_selected_audio_track (0);
1006                         } else if (mr) {
1007                                 existing_track = get_nth_selected_midi_track (0);
1008                         }
1009
1010                         if (!existing_track) {
1011                                 return -1;
1012                         }
1013                 }
1014
1015                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
1016                 boost::shared_ptr<Region> copy (RegionFactory::create (region, region->properties()));
1017                 playlist->clear_changes ();
1018                 playlist->add_region (copy, pos);
1019                 if (Config->get_edit_mode() == Ripple)
1020                         playlist->ripple (pos, copy->length(), copy);
1021
1022                 _session->add_command (new StatefulDiffCommand (playlist));
1023                 break;
1024         }
1025
1026         case ImportAsTrack:
1027         {
1028                 if (!existing_track) {
1029                         if (ar) {
1030                                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, 0, 1, string(), PresentationInfo::max_order, Normal));
1031
1032                                 if (at.empty()) {
1033                                         return -1;
1034                                 }
1035                                 if (Config->get_strict_io ()) {
1036                                         for (list<boost::shared_ptr<AudioTrack> >::iterator i = at.begin(); i != at.end(); ++i) {
1037                                                 (*i)->set_strict_io (true);
1038                                         }
1039                                 }
1040
1041                                 existing_track = at.front();
1042                         } else if (mr) {
1043                                 list<boost::shared_ptr<MidiTrack> > mt (
1044                                         _session->new_midi_track (ChanCount (DataType::MIDI, 1),
1045                                                                   ChanCount (DataType::MIDI, 1),
1046                                                                   Config->get_strict_io () || Profile->get_mixbus (),
1047                                                                   instrument, (Plugin::PresetRecord*) 0,
1048                                                                   (RouteGroup*) 0,
1049                                                                   1,
1050                                                                   string(),
1051                                                                   PresentationInfo::max_order));
1052
1053                                 if (mt.empty()) {
1054                                         return -1;
1055                                 }
1056
1057                                 // TODO set strict_io from preferences
1058                                 existing_track = mt.front();
1059                         }
1060
1061                         if (!new_track_name.empty()) {
1062                                 existing_track->set_name (new_track_name);
1063                         } else {
1064                                 existing_track->set_name (region->name());
1065                         }
1066                 }
1067
1068                 boost::shared_ptr<Playlist> playlist = existing_track->playlist();
1069                 boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
1070                 playlist->clear_changes ();
1071                 playlist->add_region (copy, pos);
1072                 _session->add_command (new StatefulDiffCommand (playlist));
1073                 break;
1074         }
1075
1076         case ImportAsTapeTrack:
1077         {
1078                 if (!ar) {
1079                         return -1;
1080                 }
1081
1082                 list<boost::shared_ptr<AudioTrack> > at (_session->new_audio_track (in_chans, out_chans, 0, 1, string(), PresentationInfo::max_order, Destructive));
1083                 if (!at.empty()) {
1084                         boost::shared_ptr<Playlist> playlist = at.front()->playlist();
1085                         boost::shared_ptr<Region> copy (RegionFactory::create (region, true));
1086                         playlist->clear_changes ();
1087                         playlist->add_region (copy, pos);
1088                         _session->add_command (new StatefulDiffCommand (playlist));
1089                 }
1090                 if (Config->get_strict_io ()) {
1091                         for (list<boost::shared_ptr<AudioTrack> >::iterator i = at.begin(); i != at.end(); ++i) {
1092                                 (*i)->set_strict_io (true);
1093                         }
1094                 }
1095                 break;
1096         }
1097         }
1098
1099         return 0;
1100 }
1101
1102 void *
1103 Editor::_import_thread (void *arg)
1104 {
1105         SessionEvent::create_per_thread_pool ("import events", 64);
1106
1107         Editor *ed = (Editor *) arg;
1108         return ed->import_thread ();
1109 }
1110
1111 void *
1112 Editor::import_thread ()
1113 {
1114         _session->import_files (import_status);
1115         return 0;
1116 }