debug output
[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
33 #include <gtkmm2ext/choice.h>
34
35 #include "ardour/session.h"
36 #include "ardour/session_directory.h"
37 #include "ardour/audioplaylist.h"
38 #include "ardour/audioregion.h"
39 #include "ardour/audio_diskstream.h"
40 #include "ardour/midi_track.h"
41 #include "ardour/midi_region.h"
42 #include "ardour/utils.h"
43 #include "ardour/audio_track.h"
44 #include "ardour/audioplaylist.h"
45 #include "ardour/audiofilesource.h"
46 #include "ardour/region_factory.h"
47 #include "ardour/source_factory.h"
48 #include "ardour/session.h"
49 #include "pbd/memento_command.h"
50
51 #include "ardour_ui.h"
52 #include "editor.h"
53 #include "sfdb_ui.h"
54 #include "editing.h"
55 #include "audio_time_axis.h"
56 #include "midi_time_axis.h"
57 #include "session_import_dialog.h"
58 #include "utils.h"
59 #include "gui_thread.h"
60
61 #include "i18n.h"
62
63 using namespace std;
64 using namespace ARDOUR;
65 using namespace PBD;
66 using namespace sigc;
67 using namespace Gtk;
68 using namespace Gtkmm2ext;
69 using namespace Editing;
70 using Glib::ustring;
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 (*this, _("Add Existing Media"), session, 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<Glib::ustring> paths;
96         uint32_t track_cnt;
97
98         if (session == 0) {
99                 MessageDialog msg (_("You can't import or embed an audiofile until you have a session loaded."));
100                 msg.run ();
101                 return;
102         }
103
104         track_cnt = 0;
105
106         for (TrackSelection::iterator x = selection->tracks.begin(); x != selection->tracks.end(); ++x) {
107                 AudioTimeAxisView* atv = dynamic_cast<AudioTimeAxisView*>(*x);
108
109                 if (!atv) {
110                         continue;
111                 } else if (atv->is_audio_track()) {
112                         track_cnt++;
113                 }
114         }
115
116         if (sfbrowser == 0) {
117                 sfbrowser = new SoundFileOmega (*this, _("Add Existing Media"), session, track_cnt, true);
118         } else {
119                 sfbrowser->reset (track_cnt);
120         }
121
122         sfbrowser->show_all ();
123
124
125         bool keepRunning;
126
127         do {
128                 keepRunning = false;
129
130                 int response = sfbrowser->run ();
131
132                 switch (response) {
133                         case RESPONSE_APPLY:
134                                 // leave the dialog open
135                                 break;
136
137                         case RESPONSE_OK:
138                                 sfbrowser->hide ();
139                                 break;
140
141                         default:
142                                 // cancel from the browser - we are done
143                                 sfbrowser->hide ();
144                                 return;
145                 }
146
147                 /* lets do it */
148
149                 paths = sfbrowser->get_paths ();
150
151                 ImportPosition pos = sfbrowser->get_position ();
152                 ImportMode mode = sfbrowser->get_mode ();
153                 ImportDisposition chns = sfbrowser->get_channel_disposition ();
154                 nframes64_t where;
155
156                 switch (pos) {
157                         case ImportAtEditPoint:
158                                 where = get_preferred_edit_position ();
159                                 break;
160                         case ImportAtTimestamp:
161                                 where = -1;
162                                 break;
163                         case ImportAtPlayhead:
164                                 where = playhead_cursor->current_frame;
165                                 break;
166                         case ImportAtStart:
167                                 where = session->current_start_frame();
168                                 break;
169                 }
170
171                 SrcQuality quality = sfbrowser->get_src_quality();
172
173
174                 if (sfbrowser->copy_files_btn.get_active()) {
175                         do_import (paths, chns, mode, quality, where);
176                 } else {
177                         do_embed (paths, chns, mode, where);
178                 }
179
180                 if (response == RESPONSE_APPLY) {
181                         sfbrowser->clear_selection ();
182                         keepRunning = true;
183                 }
184
185         } while (keepRunning);
186 }
187
188 void
189 Editor::session_import_dialog ()
190 {
191         SessionImportDialog dialog (*session);
192         ensure_float (dialog);
193         dialog.run ();
194 }
195
196 typedef std::map<PBD::ID,boost::shared_ptr<ARDOUR::Source> > SourceMap;
197
198 /**
199  * Updating is still disabled, see note in libs/ardour/import.cc Session::import_audiofiles()
200  *
201  * all_or_nothing:
202  *   true  = show "Update", "Import" and "Skip"
203  *   false = show "Import", and "Cancel"
204  *
205  * Returns:
206  *     0  To update an existing source of the same name
207  *     1  To import/embed the file normally (make sure the new name will be unique)
208  *     2  If the user wants to skip this file
209  **/
210 int
211 Editor::check_whether_and_how_to_import(string path, bool all_or_nothing)
212 {
213         string wave_name (Glib::path_get_basename(path));
214
215         SourceMap all_sources = session->get_sources();
216         bool wave_name_exists = false;
217
218         for (SourceMap::iterator i = all_sources.begin(); i != all_sources.end(); ++i) {
219                 string tmp (Glib::path_get_basename (i->second->path()));
220                 if (tmp == wave_name) {
221                         wave_name_exists = true;
222                         break;
223                 }
224         }
225
226         int function = 1;
227
228         if (wave_name_exists) {
229                 string message;
230                 if (all_or_nothing) {
231                         // updating is still disabled
232                         //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);
233                         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);
234                 } else {
235                         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);
236
237                 }
238                 MessageDialog dialog(message, false, Gtk::MESSAGE_QUESTION, Gtk::BUTTONS_NONE, true);
239
240                 if (all_or_nothing) {
241                         // disabled
242                         //dialog.add_button("Update", 0);
243                         dialog.add_button("Import", 1);
244                         dialog.add_button("Skip",   2);
245                 } else {
246                         dialog.add_button("Import", 1);
247                         dialog.add_button("Cancel", 2);
248                 }
249
250                 //dialog.add_button("Skip all", 4); // All or rest?
251
252                 dialog.show();
253
254                 function = dialog.run ();
255
256                 dialog.hide();
257         }
258
259         return function;
260 }
261
262 boost::shared_ptr<AudioTrack>
263 Editor::get_nth_selected_audio_track (int nth) const
264 {
265         AudioTimeAxisView* atv;
266         TrackSelection::iterator x;
267
268         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
269
270                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
271
272                 if (!atv) {
273                         continue;
274                 } else if (atv->is_audio_track()) {
275                         --nth;
276                 }
277         }
278
279         if (x == selection->tracks.end()) {
280                 atv = dynamic_cast<AudioTimeAxisView*>(selection->tracks.back());
281         } else {
282                 atv = dynamic_cast<AudioTimeAxisView*>(*x);
283         }
284
285         if (!atv || !atv->is_audio_track()) {
286                 return boost::shared_ptr<AudioTrack>();
287         }
288
289         return atv->audio_track();
290 }
291
292 boost::shared_ptr<MidiTrack>
293 Editor::get_nth_selected_midi_track (int nth) const
294 {
295         MidiTimeAxisView* mtv;
296         TrackSelection::iterator x;
297
298         for (x = selection->tracks.begin(); nth > 0 && x != selection->tracks.end(); ++x) {
299
300                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
301
302                 if (!mtv) {
303                         continue;
304                 } else if (mtv->is_midi_track()) {
305                         --nth;
306                 }
307         }
308
309         if (x == selection->tracks.end()) {
310                 mtv = dynamic_cast<MidiTimeAxisView*>(selection->tracks.back());
311         } else {
312                 mtv = dynamic_cast<MidiTimeAxisView*>(*x);
313         }
314
315         if (!mtv || !mtv->is_midi_track()) {
316                 return boost::shared_ptr<MidiTrack>();
317         }
318
319         return mtv->midi_track();
320 }
321
322 void
323 Editor::do_import (vector<ustring> paths, ImportDisposition chns, ImportMode mode, SrcQuality quality, nframes64_t& pos)
324 {
325         boost::shared_ptr<Track> track;
326         vector<ustring> to_import;
327         int nth = 0;
328
329         if (interthread_progress_window == 0) {
330                 build_interthread_progress_window ();
331         }
332
333         if (chns == Editing::ImportMergeFiles) {
334
335                 /* create 1 region from all paths, add to 1 track,
336                    ignore "track"
337                 */
338
339                 bool cancel = false;
340                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
341                         int check = check_whether_and_how_to_import(*a, false);
342                         if (check == 2) {
343                                 cancel = true;
344                                 break;
345                         }
346                 }
347
348                 if (!cancel) {
349                         import_sndfiles (paths, mode, quality, pos, 1, 1, track, false, paths.size());
350                 }
351
352         } else {
353
354                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
355
356                         int const check = check_whether_and_how_to_import (*a, true);
357
358                         if (check != 2) {
359                                 to_import.push_back (*a);
360                         }
361                 }
362
363                 bool ok = true;
364
365                 switch (chns) {
366                 case Editing::ImportDistinctFiles:
367
368                         if (mode == Editing::ImportToTrack) {
369                                 track = get_nth_selected_audio_track (nth++);
370                         }
371
372                         ok = (import_sndfiles (to_import, mode, quality, pos, 1, -1, track, false, to_import.size()) == 0);
373                         break;
374
375                 case Editing::ImportDistinctChannels:
376                         ok = (import_sndfiles (to_import, mode, quality, pos, -1, -1, track, false, to_import.size()) == 0);
377                         break;
378
379                 case Editing::ImportSerializeFiles:
380                         ok = (import_sndfiles (to_import, mode, quality, pos, 1, 1, track, false, to_import.size()) == 0);
381                         break;
382
383                 case Editing::ImportMergeFiles:
384                         // Not entered, handled in earlier if() branch
385                         break;
386                 }
387         }
388
389         interthread_progress_window->hide_all ();
390 }
391
392 void
393 Editor::do_embed (vector<ustring> paths, ImportDisposition chns, ImportMode mode, nframes64_t& pos)
394 {
395         boost::shared_ptr<Track> track;
396         bool check_sample_rate = true;
397         bool ok = false;
398         vector<ustring> to_embed;
399         bool multi = paths.size() > 1;
400         int nth = 0;
401
402         switch (chns) {
403         case Editing::ImportDistinctFiles:
404                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
405
406                         to_embed.clear ();
407                         to_embed.push_back (*a);
408
409                         if (mode == Editing::ImportToTrack) {
410                                 track = get_nth_selected_audio_track (nth++);
411                         }
412
413                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, -1, track) < -1) {
414                                 goto out;
415                         }
416                 }
417                 break;
418
419         case Editing::ImportDistinctChannels:
420                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
421
422                         to_embed.clear ();
423                         to_embed.push_back (*a);
424
425                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, -1, -1, track) < -1) {
426                                 goto out;
427                         }
428                 }
429                 break;
430
431         case Editing::ImportMergeFiles:
432                 if (embed_sndfiles (paths, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
433                         goto out;
434                 }
435         break;
436
437         case Editing::ImportSerializeFiles:
438                 for (vector<ustring>::iterator a = paths.begin(); a != paths.end(); ++a) {
439
440                         to_embed.clear ();
441                         to_embed.push_back (*a);
442
443                         if (embed_sndfiles (to_embed, multi, check_sample_rate, mode, pos, 1, 1, track) < -1) {
444                                 goto out;
445                         }
446                 }
447                 break;
448         }
449
450         ok = true;
451
452   out:
453         if (ok) {
454                 session->save_state ("");
455         }
456 }
457
458 int
459 Editor::import_sndfiles (vector<ustring> paths, ImportMode mode, SrcQuality quality, nframes64_t& pos,
460                          int target_regions, int target_tracks, boost::shared_ptr<Track> track, bool replace, uint32_t total)
461 {
462         interthread_progress_window->set_title (string_compose (_("Importing %1"), paths.front()));
463         interthread_progress_window->set_position (Gtk::WIN_POS_MOUSE);
464         interthread_progress_bar.set_fraction (0.0f);
465         interthread_cancel_label.set_text (_("Cancel Import"));
466         current_interthread_info = &import_status;
467
468         import_status.paths = paths;
469         import_status.done = false;
470         import_status.cancel = false;
471         import_status.freeze = false;
472         import_status.done = 0.0;
473         import_status.quality = quality;
474         import_status.replace_existing_source = replace;
475         import_status.total = total;
476
477         import_status.mode = mode;
478         import_status.pos = pos;
479         import_status.target_tracks = target_tracks;
480         import_status.target_regions = target_regions;
481         import_status.track = track;
482         import_status.replace = replace;
483         interthread_progress_connection = Glib::signal_timeout().connect
484                 (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 500);
485
486         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
487         gdk_flush ();
488
489         /* start import thread for this spec. this will ultimately call Session::import_audiofiles()
490            which, if successful, will add the files as regions to the region list. its up to us
491            (the GUI) to direct additional steps after that.
492         */
493
494         pthread_create_and_store ("import", &import_status.thread, 0, _import_thread, this);
495         pthread_detach (import_status.thread);
496
497         while (!import_status.done && !import_status.cancel) {
498                 gtk_main_iteration ();
499         }
500
501         interthread_progress_window->hide ();
502         import_status.done = true;
503         interthread_progress_connection.disconnect ();
504
505         if (!import_status.cancel && !import_status.sources.empty()) {
506                 if (add_sources (import_status.paths,
507                                  import_status.sources,
508                                  import_status.pos,
509                                  import_status.mode,
510                                  import_status.target_regions,
511                                  import_status.target_tracks,
512                                  import_status.track, false) == 0) {
513                         session->save_state ("");
514                 }
515
516                 /* update position from results */
517
518                 pos = import_status.pos;
519         }
520
521
522         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
523         return 0;
524 }
525
526 int
527 Editor::embed_sndfiles (vector<Glib::ustring> paths, bool multifile,
528                         bool& check_sample_rate, ImportMode mode, nframes64_t& pos, int target_regions, int target_tracks,
529                         boost::shared_ptr<Track>& track)
530 {
531         boost::shared_ptr<AudioFileSource> source;
532         SourceList sources;
533         string linked_path;
534         SoundFileInfo finfo;
535         int ret = 0;
536         Glib::ustring path_to_use;
537
538         track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
539         gdk_flush ();
540
541         for (vector<Glib::ustring>::iterator p = paths.begin(); p != paths.end(); ++p) {
542
543                 ustring path = *p;
544
545                 /* lets see if we can link it into the session */
546
547                 sys::path tmp = session->session_directory().sound_path() / Glib::path_get_basename(path);
548                 linked_path = tmp.to_string();
549
550                 path_to_use = linked_path;
551
552                 if (link (path.c_str(), linked_path.c_str()) == 0) {
553
554                         /* there are many reasons why link(2) might have failed.
555                            but if it succeeds, we now have a link in the
556                            session sound dir that will protect against
557                            unlinking of the original path. nice.
558                         */
559
560                         path = linked_path;
561                         path_to_use = Glib::path_get_basename (path);
562
563                 } else {
564
565                         /* one possible reason is that its already linked */
566
567                         if (errno == EEXIST) {
568                                 struct stat sb;
569
570                                 if (stat (linked_path.c_str(), &sb) == 0) {
571                                         if (sb.st_nlink > 1) { // its a hard link, assume its the one we want
572                                                 path = linked_path;
573                                                 path_to_use = Glib::path_get_basename (path);
574                                         }
575                                 }
576                         }
577                 }
578
579                 /* note that we temporarily truncated _id at the colon */
580
581                 string error_msg;
582
583                 if (!AudioFileSource::get_soundfile_info (path, finfo, error_msg)) {
584                         error << string_compose(_("Editor: cannot open file \"%1\", (%2)"), path, error_msg ) << endmsg;
585                         goto out;
586                 }
587
588                 if (check_sample_rate  && (finfo.samplerate != (int) session->frame_rate())) {
589                         vector<string> choices;
590
591                         if (multifile) {
592                                 choices.push_back (_("Cancel entire import"));
593                                 choices.push_back (_("Don't embed it"));
594                                 choices.push_back (_("Embed all without questions"));
595
596                                 Gtkmm2ext::Choice rate_choice (
597                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"),
598                                                         short_path (path, 40)),
599                                         choices, false);
600
601                                 int resx = rate_choice.run ();
602
603                                 switch (resx) {
604                                 case 0: /* stop a multi-file import */
605                                         ret = -2;
606                                         goto out;
607                                 case 1: /* don't embed this one */
608                                         ret = -1;
609                                         goto out;
610                                 case 2: /* do it, and the rest without asking */
611                                         check_sample_rate = false;
612                                         break;
613                                 case 3: /* do it */
614                                         break;
615                                 default:
616                                         ret = -2;
617                                         goto out;
618                                 }
619                         } else {
620                                 choices.push_back (_("Cancel"));
621                                 choices.push_back (_("Embed it anyway"));
622
623                                 Gtkmm2ext::Choice rate_choice (
624                                         string_compose (_("%1\nThis audiofile's sample rate doesn't match the session sample rate!"), path),
625                                         choices, false);
626
627                                 int resx = rate_choice.run ();
628
629                                 switch (resx) {
630                                 case 0: /* don't import */
631                                         ret = -1;
632                                         goto out;
633                                 case 1: /* do it */
634                                         break;
635                                 default:
636                                         ret = -2;
637                                         goto out;
638                                 }
639                         }
640                 }
641
642                 track_canvas->get_window()->set_cursor (Gdk::Cursor (Gdk::WATCH));
643
644                 for (int n = 0; n < finfo.channels; ++n) {
645                         try {
646
647                                 /* check if we have this thing embedded already */
648
649                                 boost::shared_ptr<Source> s;
650
651                                 if ((s = session->source_by_path_and_channel (path, n)) == 0) {
652
653                                         source = boost::dynamic_pointer_cast<AudioFileSource> (
654                                                         SourceFactory::createReadable (DataType::AUDIO, *session,
655                                                                         path_to_use, false, n,
656                                                                         (mode == ImportAsTapeTrack
657                                                                                 ? Source::Destructive
658                                                                                 : Source::Flag (0)),
659                                                                         true, true));
660                                 } else {
661                                         source = boost::dynamic_pointer_cast<AudioFileSource> (s);
662                                 }
663
664                                 sources.push_back(source);
665                         }
666
667                         catch (failed_constructor& err) {
668                                 error << string_compose(_("could not open %1"), path) << endmsg;
669                                 goto out;
670                         }
671
672                         ARDOUR_UI::instance()->flush_pending ();
673                 }
674         }
675
676         if (sources.empty()) {
677                 goto out;
678         }
679
680         ret = add_sources (paths, sources, pos, mode, target_regions, target_tracks, track, true);
681
682   out:
683         track_canvas->get_window()->set_cursor (*current_canvas_cursor);
684         return ret;
685 }
686
687 int
688 Editor::add_sources (vector<Glib::ustring> paths, SourceList& sources, nframes64_t& pos, ImportMode mode,
689                      int target_regions, int target_tracks, boost::shared_ptr<Track>& track, bool /*add_channel_suffix*/)
690 {
691         vector<boost::shared_ptr<Region> > regions;
692         ustring region_name;
693         uint32_t input_chan = 0;
694         uint32_t output_chan = 0;
695         bool use_timestamp;
696
697         use_timestamp = (pos == -1);
698
699         if (use_timestamp) {
700                 if (sources[0]->natural_position() != 0) {
701                         pos = sources[0]->natural_position();
702                 } else {
703                         pos = get_preferred_edit_position ();
704                 }
705         }
706
707         // kludge (for MIDI we're abusing "channel" for "track" here)
708         if (paths.front().rfind(".mid") != Glib::ustring::npos)
709                 target_regions = -1;
710
711         if (target_regions == 1) {
712
713                 /* take all the sources we have and package them up as a region */
714
715                 region_name = region_name_from_path (paths.front(), (sources.size() > 1), false);
716
717                 boost::shared_ptr<Region> r = RegionFactory::create (sources, 0, sources[0]->length(pos), region_name, 0,
718                                                                      Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External));
719
720                 if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
721                         boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position(sources[0]->natural_position());
722                 }
723
724                 regions.push_back (r);
725
726
727         } else if (target_regions == -1 || target_regions > 1) {
728
729                 /* take each source and create a region for each one */
730
731                 SourceList just_one;
732                 SourceList::iterator x;
733                 uint32_t n;
734
735                 for (n = 0, x = sources.begin(); x != sources.end(); ++x, ++n) {
736
737                         just_one.clear ();
738                         just_one.push_back (*x);
739
740                         region_name = region_name_from_path ((*x)->path(), false, false, sources.size(), n);
741
742                         boost::shared_ptr<Region> r = RegionFactory::create (just_one, 0, (*x)->length(pos), region_name, 0,
743                                                                              Region::Flag (Region::DefaultFlags|Region::WholeFile|Region::External));
744
745                         if (use_timestamp && boost::dynamic_pointer_cast<AudioRegion>(r)) {
746                                 boost::dynamic_pointer_cast<AudioRegion>(r)->special_set_position((*x)->natural_position());
747                         }
748
749                         regions.push_back (r);
750                 }
751         }
752
753         if (target_regions == 1) {
754                 input_chan = regions.front()->n_channels();
755         } else {
756                 if (target_tracks == 1) {
757                         input_chan = regions.size();
758                 } else {
759                         input_chan = 1;
760                 }
761         }
762
763         if (Config->get_output_auto_connect() & AutoConnectMaster) {
764                 output_chan = (session->master_out() ? session->master_out()->n_inputs().n_audio() : input_chan);
765         } else {
766                 output_chan = input_chan;
767         }
768
769         int n = 0;
770
771         for (vector<boost::shared_ptr<Region> >::iterator r = regions.begin(); r != regions.end(); ++r, ++n) {
772
773                 finish_bringing_in_material (*r, input_chan, output_chan, pos, mode, track);
774
775                 if (target_tracks != 1) {
776                         track.reset ();
777                 } else {
778                         pos += (*r)->length();
779                 }
780         }
781
782         /* setup peak file building in another thread */
783
784         for (SourceList::iterator x = sources.begin(); x != sources.end(); ++x) {
785                 SourceFactory::setup_peakfile (*x, true);
786         }
787
788         return 0;
789 }
790
791 int
792 Editor::finish_bringing_in_material (boost::shared_ptr<Region> region, uint32_t in_chans, uint32_t out_chans, nframes64_t& pos,
793                                   ImportMode mode, boost::shared_ptr<Track>& existing_track)
794 {
795         boost::shared_ptr<AudioRegion> ar = boost::dynamic_pointer_cast<AudioRegion>(region);
796         boost::shared_ptr<MidiRegion> mr = boost::dynamic_pointer_cast<MidiRegion>(region);
797
798         switch (mode) {
799         case ImportAsRegion:
800                 /* relax, its been done */
801                 break;
802
803         case ImportToTrack:
804         {
805                 if (!existing_track) {
806
807                         if (ar) {
808                                 existing_track = get_nth_selected_audio_track (0);
809                         } else if (mr) {
810                                 existing_track = get_nth_selected_midi_track (0);
811                         }
812
813                         if (!existing_track) {
814                                 return -1;
815                         }
816                 }
817
818                 boost::shared_ptr<Playlist> playlist = existing_track->diskstream()->playlist();
819                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
820                 begin_reversible_command (_("insert file"));
821                 XMLNode &before = playlist->get_state();
822                 playlist->add_region (copy, pos);
823                 session->add_command (new MementoCommand<Playlist>(*playlist, &before, &playlist->get_state()));
824                 commit_reversible_command ();
825                 break;
826         }
827
828         case ImportAsTrack:
829         {
830                 if (!existing_track) {
831                         if (ar) {
832                                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Normal, 0, 1));
833
834                                 if (at.empty()) {
835                                         return -1;
836                                 }
837
838                                 existing_track = at.front();
839                         } else if (mr) {
840                                 list<boost::shared_ptr<MidiTrack> > mt (session->new_midi_track (Normal, 0, 1));
841
842                                 if (mt.empty()) {
843                                         return -1;
844                                 }
845
846                                 existing_track = mt.front();
847                         }
848
849                         existing_track->set_name (region->name());
850                 }
851
852                 boost::shared_ptr<Region> copy (RegionFactory::create (region));
853                 existing_track->diskstream()->playlist()->add_region (copy, pos);
854                 break;
855         }
856
857
858         case ImportAsTapeTrack:
859         {
860                 if (!ar)
861                         return -1;
862
863                 list<boost::shared_ptr<AudioTrack> > at (session->new_audio_track (in_chans, out_chans, Destructive));
864                 if (!at.empty()) {
865                         boost::shared_ptr<Region> copy (RegionFactory::create (region));
866                         at.front()->set_name (basename_nosuffix (copy->name()));
867                         at.front()->diskstream()->playlist()->add_region (copy, pos);
868                 }
869                 break;
870         }
871         }
872
873         return 0;
874 }
875
876 void *
877 Editor::_import_thread (void *arg)
878 {
879         PBD::notify_gui_about_thread_creation (pthread_self(), X_("Import"));
880
881         Editor *ed = (Editor *) arg;
882         return ed->import_thread ();
883 }
884
885 void *
886 Editor::import_thread ()
887 {
888         session->import_audiofiles (import_status);
889         pthread_exit_pbd (0);
890         /*NOTREACHED*/
891         return 0;
892 }
893
894 gint
895 Editor::import_progress_timeout (void */*arg*/)
896 {
897         bool reset = false;
898
899         if (!interthread_progress_window->is_visible()) {
900                 interthread_progress_window->show_all ();
901                 reset = true;
902         }
903
904         interthread_progress_label.set_text (import_status.doing_what);
905
906         if (import_status.freeze) {
907                 interthread_cancel_button.set_sensitive(false);
908         } else {
909                 interthread_cancel_button.set_sensitive(true);
910         }
911
912         if (import_status.doing_what == "building peak files") {
913                 interthread_progress_bar.pulse ();
914                 return FALSE;
915         } else {
916                 float val = import_status.progress;
917                 interthread_progress_bar.set_fraction (min (max (0.0f, val), 1.0f));
918         }
919
920         if (reset) {
921
922                 /* the window is now visible, speed up the updates */
923
924                 interthread_progress_connection.disconnect ();
925                 interthread_progress_connection = Glib::signal_timeout().connect
926                         (bind (mem_fun(*this, &Editor::import_progress_timeout), (gpointer) 0), 100);
927                 return false;
928         } else {
929                 return !(import_status.done || import_status.cancel);
930         }
931 }
932