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