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