fix crash when copy'ing latent plugins
[ardour.git] / libs / ardour / export_profile_manager.cc
1 /*
2     Copyright (C) 2008 Paul Davis
3     Author: Sakari Bergen
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License
16     along with this program; if not, write to the Free Software
17     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 */
20
21 #include <cassert>
22 #include <stdexcept>
23 #include <cerrno>
24
25 #include <glib.h>
26 #include "pbd/gstdio_compat.h"
27
28 #include <glibmm/fileutils.h>
29 #include <glibmm/miscutils.h>
30
31 #include "pbd/enumwriter.h"
32 #include "pbd/xml++.h"
33 #include "pbd/convert.h"
34
35 #include "ardour/export_profile_manager.h"
36 #include "ardour/export_format_specification.h"
37 #include "ardour/search_paths.h"
38 #include "ardour/export_timespan.h"
39 #include "ardour/export_channel_configuration.h"
40 #include "ardour/export_filename.h"
41 #include "ardour/export_preset.h"
42 #include "ardour/export_handler.h"
43 #include "ardour/export_failed.h"
44 #include "ardour/directory_names.h"
45 #include "ardour/filename_extensions.h"
46 #include "ardour/profile.h"
47 #include "ardour/route.h"
48 #include "ardour/session.h"
49 #include "ardour/broadcast_info.h"
50
51 #include "pbd/i18n.h"
52
53 using namespace std;
54 using namespace Glib;
55 using namespace PBD;
56
57 namespace ARDOUR
58 {
59
60 ExportProfileManager::ExportProfileManager (Session & s, ExportType type)
61   : _type(type)
62   , handler (s.get_export_handler())
63   , session (s)
64
65   , ranges (new LocationList ())
66   , single_range_mode (false)
67
68   , format_list (new FormatList ())
69 {
70         switch(type) {
71         case RegularExport:
72                 xml_node_name = X_("ExportProfile");
73                 break;
74         case RangeExport:
75                 xml_node_name = X_("RangeExportProfile");
76                 break;
77         case SelectionExport:
78                 xml_node_name = X_("SelectionExportProfile");
79                 break;
80         case RegionExport:
81                 xml_node_name = X_("RegionExportProfile");
82                 break;
83         case StemExport:
84                 xml_node_name = X_("StemExportProfile");
85                 break;
86         }
87
88         /* Initialize path variables */
89
90         export_config_dir = Glib::build_filename (user_config_directory(), export_dir_name);
91
92         search_path += export_formats_search_path();
93
94         info << string_compose (_("Searching for export formats in %1"), search_path.to_string()) << endmsg;
95
96         /* create export config directory if necessary */
97
98         if (!Glib::file_test (export_config_dir, Glib::FILE_TEST_EXISTS)) {
99                 if (g_mkdir_with_parents (export_config_dir.c_str(), 0755) != 0) {
100                         error << string_compose (_("Unable to create export format directory %1: %2"), export_config_dir, g_strerror(errno)) << endmsg;
101                 }
102         }
103
104         load_presets ();
105         load_formats ();
106
107         /* Initialize all lists with an empty config */
108
109         XMLNodeList dummy;
110         init_timespans (dummy);
111         init_channel_configs (dummy);
112         init_formats (dummy);
113         init_filenames (dummy);
114 }
115
116 ExportProfileManager::~ExportProfileManager ()
117 {
118         XMLNode * extra_xml (new XMLNode (xml_node_name));
119         serialize_profile (*extra_xml);
120         session.add_extra_xml (*extra_xml);
121 }
122
123 void
124 ExportProfileManager::load_profile ()
125 {
126         XMLNode * extra_node = session.extra_xml (xml_node_name);
127         /* Legacy sessions used Session instant.xml for this */
128         if (!extra_node) {
129                 extra_node = session.instant_xml (xml_node_name);
130         }
131
132         if (extra_node) {
133                 set_state (*extra_node);
134         } else {
135                 XMLNode empty_node (xml_node_name);
136                 set_state (empty_node);
137         }
138 }
139
140 void
141 ExportProfileManager::prepare_for_export ()
142 {
143         TimespanListPtr ts_list = timespans.front()->timespans;
144
145         FormatStateList::const_iterator format_it;
146         FilenameStateList::const_iterator filename_it;
147
148         // For each timespan
149         for (TimespanList::iterator ts_it = ts_list->begin(); ts_it != ts_list->end(); ++ts_it) {
150                 // ..., each format-filename pair
151                 for (format_it = formats.begin(), filename_it = filenames.begin();
152                      format_it != formats.end() && filename_it != filenames.end();
153                      ++format_it, ++filename_it) {
154
155                         ExportFilenamePtr filename = (*filename_it)->filename;
156 //                      filename->include_timespan = (ts_list->size() > 1); Disabled for now...
157
158                         boost::shared_ptr<BroadcastInfo> b;
159                         if ((*format_it)->format->has_broadcast_info()) {
160                                 b.reset (new BroadcastInfo);
161                                 b->set_from_session (session, (*ts_it)->get_start());
162                         }
163
164                         // ...and each channel config
165                         filename->include_channel_config = (_type == StemExport) ||
166                                                            (channel_configs.size() > 1);
167                         for(ChannelConfigStateList::iterator cc_it = channel_configs.begin(); cc_it != channel_configs.end(); ++cc_it) {
168                                 handler->add_export_config (*ts_it, (*cc_it)->config, (*format_it)->format, filename, b);
169                         }
170                 }
171         }
172 }
173
174 bool
175 ExportProfileManager::load_preset (ExportPresetPtr preset)
176 {
177         bool ok = true;
178
179         current_preset = preset;
180         if (!preset) { return false; }
181
182         XMLNode const * state;
183         /* local state is saved in instant.xml and contains timespan
184          * and channel config for per session.
185          * It may not be present for a given preset/session combination
186          * and is never preset for system-wide presets, but that's OK.
187          */
188         if ((state = preset->get_local_state())) {
189                 set_local_state (*state);
190         }
191
192         if ((state = preset->get_global_state())) {
193                 if (!set_global_state (*state)) {
194                         ok = false;
195                 }
196         } else { ok = false; }
197
198         return ok;
199 }
200
201 void
202 ExportProfileManager::load_presets ()
203 {
204         vector<std::string> found = find_file (string_compose (X_("*%1"),export_preset_suffix));
205
206         for (vector<std::string>::iterator it = found.begin(); it != found.end(); ++it) {
207                 load_preset_from_disk (*it);
208         }
209 }
210
211 std::string
212 ExportProfileManager::preset_filename (std::string const & preset_name)
213 {
214         string safe_name = legalize_for_path (preset_name);
215         return Glib::build_filename (export_config_dir, safe_name + export_preset_suffix);
216 }
217
218 ExportPresetPtr
219 ExportProfileManager::new_preset (string const & name)
220 {
221         // Generate new ID and do regular save
222         string filename = preset_filename (name);
223         current_preset.reset (new ExportPreset (filename, session));
224         preset_list.push_back (current_preset);
225         return save_preset (name);
226 }
227
228 ExportPresetPtr
229 ExportProfileManager::save_preset (string const & name)
230 {
231         string filename = preset_filename (name);
232
233         if (!current_preset) {
234                 current_preset.reset (new ExportPreset (filename, session));
235                 preset_list.push_back (current_preset);
236         }
237
238         XMLNode * global_preset = new XMLNode ("ExportPreset");
239         XMLNode * local_preset = new XMLNode ("ExportPreset");
240
241         serialize_global_profile (*global_preset);
242         serialize_local_profile (*local_preset);
243
244         current_preset->set_name (name);
245         current_preset->set_global_state (*global_preset);
246         current_preset->set_local_state (*local_preset);
247
248         current_preset->save (filename);
249
250         return current_preset;
251 }
252
253 void
254 ExportProfileManager::remove_preset ()
255 {
256         if (!current_preset) { return; }
257
258         for (PresetList::iterator it = preset_list.begin(); it != preset_list.end(); ++it) {
259                 if (*it == current_preset) {
260                         preset_list.erase (it);
261                         break;
262                 }
263         }
264
265         FileMap::iterator it = preset_file_map.find (current_preset->id());
266         if (it != preset_file_map.end()) {
267                 if (g_remove (it->second.c_str()) != 0) {
268                         error << string_compose (_("Unable to remove export preset %1: %2"), it->second, g_strerror(errno)) << endmsg;
269                 }
270                 preset_file_map.erase (it);
271         }
272
273         current_preset->remove_local();
274         current_preset.reset();
275 }
276
277 void
278 ExportProfileManager::load_preset_from_disk (std::string const & path)
279 {
280         ExportPresetPtr preset (new ExportPreset (path, session));
281
282         /* Handle id to filename mapping and don't add duplicates to list */
283
284         FilePair pair (preset->id(), path);
285         if (preset_file_map.insert (pair).second) {
286                 preset_list.push_back (preset);
287         }
288 }
289
290 bool
291 ExportProfileManager::set_state (XMLNode const & root)
292 {
293         return set_global_state (root) & set_local_state (root);
294 }
295
296 bool
297 ExportProfileManager::set_global_state (XMLNode const & root)
298 {
299         return init_filenames (root.children ("ExportFilename")) &
300                init_formats (root.children ("ExportFormat"));
301 }
302
303 bool
304 ExportProfileManager::set_local_state (XMLNode const & root)
305 {
306         return init_timespans (root.children ("ExportTimespan")) &
307                init_channel_configs (root.children ("ExportChannelConfiguration"));
308 }
309
310 void
311 ExportProfileManager::serialize_profile (XMLNode & root)
312 {
313         serialize_local_profile (root);
314         serialize_global_profile (root);
315 }
316
317 void
318 ExportProfileManager::serialize_global_profile (XMLNode & root)
319 {
320         for (FormatStateList::iterator it = formats.begin(); it != formats.end(); ++it) {
321                 root.add_child_nocopy (serialize_format (*it));
322         }
323
324         for (FilenameStateList::iterator it = filenames.begin(); it != filenames.end(); ++it) {
325                 root.add_child_nocopy ((*it)->filename->get_state());
326         }
327 }
328
329 void
330 ExportProfileManager::serialize_local_profile (XMLNode & root)
331 {
332         for (TimespanStateList::iterator it = timespans.begin(); it != timespans.end(); ++it) {
333                 root.add_child_nocopy (serialize_timespan (*it));
334         }
335
336         for (ChannelConfigStateList::iterator it = channel_configs.begin(); it != channel_configs.end(); ++it) {
337                 root.add_child_nocopy ((*it)->config->get_state());
338         }
339 }
340
341 std::vector<std::string>
342 ExportProfileManager::find_file (std::string const & pattern)
343 {
344         vector<std::string> found;
345
346         find_files_matching_pattern (found, search_path, pattern);
347
348         return found;
349 }
350
351 void
352 ExportProfileManager::set_selection_range (framepos_t start, framepos_t end)
353 {
354
355         if (start || end) {
356                 selection_range.reset (new Location (session));
357                 selection_range->set_name (_("Selection"));
358                 selection_range->set (start, end);
359         } else {
360                 selection_range.reset();
361         }
362
363         for (TimespanStateList::iterator it = timespans.begin(); it != timespans.end(); ++it) {
364                 (*it)->selection_range = selection_range;
365         }
366 }
367
368 std::string
369 ExportProfileManager::set_single_range (framepos_t start, framepos_t end, string name)
370 {
371         single_range_mode = true;
372
373         single_range.reset (new Location (session));
374         single_range->set_name (name);
375         single_range->set (start, end);
376
377         update_ranges ();
378
379         return single_range->id().to_s();
380 }
381
382 bool
383 ExportProfileManager::init_timespans (XMLNodeList nodes)
384 {
385         timespans.clear ();
386         update_ranges ();
387
388         bool ok = true;
389         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
390                 TimespanStatePtr span = deserialize_timespan (**it);
391                 if (span) {
392                         timespans.push_back (span);
393                 } else { ok = false; }
394         }
395
396         if (timespans.empty()) {
397                 TimespanStatePtr state (new TimespanState (selection_range, ranges));
398                 timespans.push_back (state);
399
400                 // Add session as default selection
401                 Location * session_range;
402
403                 if (Profile->get_trx()) {
404                         session_range = (session.get_play_loop () ? session.locations()->auto_loop_location () : session.locations()->session_range_location());
405                 } else {
406                         session_range = session.locations()->session_range_location();
407                 }
408
409                 if (!session_range) { return false; }
410
411                 ExportTimespanPtr timespan = handler->add_timespan();
412                 timespan->set_name (session_range->name());
413                 timespan->set_range_id (session_range->id().to_s());
414                 timespan->set_range (session_range->start(), session_range->end());
415                 state->timespans->push_back (timespan);
416                 return false;
417         }
418
419         return ok;
420 }
421
422 ExportProfileManager::TimespanStatePtr
423 ExportProfileManager::deserialize_timespan (XMLNode & root)
424 {
425         TimespanStatePtr state (new TimespanState (selection_range, ranges));
426         XMLProperty const * prop;
427
428         XMLNodeList spans = root.children ("Range");
429         for (XMLNodeList::iterator node_it = spans.begin(); node_it != spans.end(); ++node_it) {
430
431                 prop = (*node_it)->property ("id");
432                 if (!prop) { continue; }
433                 string id = prop->value();
434
435                 Location * location = 0;
436                 for (LocationList::iterator it = ranges->begin(); it != ranges->end(); ++it) {
437                         if ((id == "selection" && *it == selection_range.get()) ||
438                             (id == (*it)->id().to_s())) {
439                                 location = *it;
440                                 break;
441                         }
442                 }
443
444                 if (!location) { continue; }
445
446                 ExportTimespanPtr timespan = handler->add_timespan();
447                 timespan->set_name (location->name());
448                 timespan->set_range_id (location->id().to_s());
449                 timespan->set_range (location->start(), location->end());
450                 state->timespans->push_back (timespan);
451         }
452
453         if ((prop = root.property ("format"))) {
454                 state->time_format = (TimeFormat) string_2_enum (prop->value(), TimeFormat);
455         }
456
457         if (state->timespans->empty()) {
458                 return TimespanStatePtr();
459         }
460
461         return state;
462 }
463
464 XMLNode &
465 ExportProfileManager::serialize_timespan (TimespanStatePtr state)
466 {
467         XMLNode & root = *(new XMLNode ("ExportTimespan"));
468         XMLNode * span;
469
470         update_ranges ();
471         for (TimespanList::iterator it = state->timespans->begin(); it != state->timespans->end(); ++it) {
472                 if ((span = root.add_child ("Range"))) {
473                         span->add_property ("id", (*it)->range_id());
474                 }
475         }
476
477         root.add_property ("format", enum_2_string (state->time_format));
478
479         return root;
480 }
481
482 void
483 ExportProfileManager::update_ranges () {
484         ranges->clear();
485
486         if (single_range_mode) {
487                 ranges->push_back (single_range.get());
488                 return;
489         }
490
491
492         /* Loop */
493         if (session.locations()->auto_loop_location ()) {
494                 ranges->push_back (session.locations()->auto_loop_location ());
495         }
496
497         /* Session */
498         if (session.locations()->session_range_location()) {
499                 ranges->push_back (session.locations()->session_range_location());
500         }
501
502         /* Selection */
503
504         if (selection_range) {
505                 ranges->push_back (selection_range.get());
506         }
507
508         /* ranges */
509
510         LocationList const & list (session.locations()->list());
511         for (LocationList::const_iterator it = list.begin(); it != list.end(); ++it) {
512                 if ((*it)->is_range_marker()) {
513                         ranges->push_back (*it);
514                 }
515         }
516 }
517
518 ExportProfileManager::ChannelConfigStatePtr
519 ExportProfileManager::add_channel_config ()
520 {
521         ChannelConfigStatePtr ptr(new ChannelConfigState(handler->add_channel_config()));
522         channel_configs.push_back(ptr);
523         return ptr;
524 }
525
526 bool
527 ExportProfileManager::init_channel_configs (XMLNodeList nodes)
528 {
529         channel_configs.clear();
530
531         if (nodes.empty()) {
532                 ChannelConfigStatePtr config (new ChannelConfigState (handler->add_channel_config()));
533                 channel_configs.push_back (config);
534
535                 // Add master outs as default
536                 if (!session.master_out()) { return false; }
537
538                 IO* master_out = session.master_out()->output().get();
539                 if (!master_out) { return false; }
540
541                 for (uint32_t n = 0; n < master_out->n_ports().n_audio(); ++n) {
542                         PortExportChannel * channel = new PortExportChannel ();
543                         channel->add_port (master_out->audio (n));
544
545                         ExportChannelPtr chan_ptr (channel);
546                         config->config->register_channel (chan_ptr);
547                 }
548                 return false;
549         }
550
551         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
552                 ChannelConfigStatePtr config (new ChannelConfigState (handler->add_channel_config()));
553                 config->config->set_state (**it);
554                 channel_configs.push_back (config);
555         }
556
557         return true;
558 }
559
560 ExportProfileManager::FormatStatePtr
561 ExportProfileManager::duplicate_format_state (FormatStatePtr state)
562 {
563         /* Note: The pointer in the new FormatState should point to the same format spec
564                  as the original state's pointer. The spec itself should not be copied!   */
565
566         FormatStatePtr format (new FormatState (format_list, state->format));
567         formats.push_back (format);
568         return format;
569 }
570
571 void
572 ExportProfileManager::remove_format_state (FormatStatePtr state)
573 {
574         for (FormatStateList::iterator it = formats.begin(); it != formats.end(); ++it) {
575                 if (*it == state) {
576                         formats.erase (it);
577                         return;
578                 }
579         }
580 }
581
582 std::string
583 ExportProfileManager::save_format_to_disk (ExportFormatSpecPtr format)
584 {
585         // TODO filename character stripping
586
587         /* Get filename for file */
588
589         string new_name = format->name();
590         new_name += export_format_suffix;
591
592         /* make sure its legal for the filesystem */
593
594         new_name = legalize_for_path (new_name);
595
596         std::string new_path = Glib::build_filename (export_config_dir, new_name);
597
598         /* Check if format is on disk already */
599         FileMap::iterator it;
600         if ((it = format_file_map.find (format->id())) != format_file_map.end()) {
601
602                 /* Check if config is not in user config dir */
603                 if (Glib::path_get_dirname (it->second) != export_config_dir) {
604
605                         /* Write new file */
606
607                         XMLTree tree (new_path);
608                         tree.set_root (&format->get_state());
609                         tree.write();
610
611                 } else {
612
613                         /* Update file and rename if necessary */
614
615                         XMLTree tree (it->second);
616                         tree.set_root (&format->get_state());
617                         tree.write();
618
619                         if (new_name != Glib::path_get_basename (it->second)) {
620                                 if (g_rename (it->second.c_str(), new_path.c_str()) != 0) {
621                                         error << string_compose (_("Unable to rename export format %1 to %2: %3"), it->second, new_path, g_strerror(errno)) << endmsg;
622                                 };
623                         }
624                 }
625
626                 it->second = new_path;
627
628         } else {
629                 /* Write new file */
630
631                 XMLTree tree (new_path);
632                 tree.set_root (&format->get_state());
633                 tree.write();
634         }
635
636         FormatListChanged ();
637         return new_path;
638 }
639
640 void
641 ExportProfileManager::remove_format_profile (ExportFormatSpecPtr format)
642 {
643         for (FormatList::iterator it = format_list->begin(); it != format_list->end(); ++it) {
644                 if (*it == format) {
645                         format_list->erase (it);
646                         break;
647                 }
648         }
649
650         FileMap::iterator it = format_file_map.find (format->id());
651         if (it != format_file_map.end()) {
652                 if (g_remove (it->second.c_str()) != 0) {
653                         error << string_compose (_("Unable to remove export profile %1: %2"), it->second, g_strerror(errno)) << endmsg;
654                         return;
655                 }
656                 format_file_map.erase (it);
657         }
658
659         FormatListChanged ();
660 }
661
662 ExportFormatSpecPtr
663 ExportProfileManager::get_new_format (ExportFormatSpecPtr original)
664 {
665         ExportFormatSpecPtr format;
666         if (original) {
667                 format.reset (new ExportFormatSpecification (*original));
668                 std::cerr << "After new format created from original, format has id [" << format->id().to_s() << ']' << std::endl;
669         } else {
670                 format = handler->add_format();
671                 format->set_name (_("empty format"));
672         }
673
674         std::string path = save_format_to_disk (format);
675         FilePair pair (format->id(), path);
676         format_file_map.insert (pair);
677
678         format_list->push_back (format);
679         FormatListChanged ();
680
681         return format;
682 }
683
684 bool
685 ExportProfileManager::init_formats (XMLNodeList nodes)
686 {
687         formats.clear();
688
689         bool ok = true;
690         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
691                 FormatStatePtr format = deserialize_format (**it);
692                 if (format) {
693                         formats.push_back (format);
694                 } else { ok = false; }
695         }
696
697         if (formats.empty ()) {
698                 FormatStatePtr format (new FormatState (format_list, ExportFormatSpecPtr ()));
699                 formats.push_back (format);
700                 return false;
701         }
702
703         return ok;
704 }
705
706 ExportProfileManager::FormatStatePtr
707 ExportProfileManager::deserialize_format (XMLNode & root)
708 {
709         XMLProperty const * prop;
710         PBD::UUID id;
711
712         if ((prop = root.property ("id"))) {
713                 id = prop->value();
714         }
715
716         for (FormatList::iterator it = format_list->begin(); it != format_list->end(); ++it) {
717                 if ((*it)->id() == id) {
718                         return FormatStatePtr (new FormatState (format_list, *it));
719                 }
720         }
721
722         return FormatStatePtr ();
723 }
724
725 XMLNode &
726 ExportProfileManager::serialize_format (FormatStatePtr state)
727 {
728         XMLNode * root = new XMLNode ("ExportFormat");
729
730         string id = state->format ? state->format->id().to_s() : "";
731         root->add_property ("id", id);
732
733         return *root;
734 }
735
736 void
737 ExportProfileManager::load_formats ()
738 {
739         vector<std::string> found = find_file (string_compose ("*%1", export_format_suffix));
740
741         for (vector<std::string>::iterator it = found.begin(); it != found.end(); ++it) {
742                 load_format_from_disk (*it);
743         }
744 }
745
746 void
747 ExportProfileManager::load_format_from_disk (std::string const & path)
748 {
749         XMLTree tree;
750
751         if (!tree.read (path)) {
752                 error << string_compose (_("Cannot load export format from %1"), path) << endmsg;
753                 return;
754         }
755
756         XMLNode* root = tree.root();
757         if (!root) {
758                 error << string_compose (_("Cannot export format read from %1"), path) << endmsg;
759                 return;
760         }
761
762         ExportFormatSpecPtr format = handler->add_format (*root);
763
764         /* Handle id to filename mapping and don't add duplicates to list */
765
766         FilePair pair (format->id(), path);
767         if (format_file_map.insert (pair).second) {
768                 format_list->push_back (format);
769         }
770
771         FormatListChanged ();
772 }
773
774 ExportProfileManager::FilenameStatePtr
775 ExportProfileManager::duplicate_filename_state (FilenameStatePtr state)
776 {
777         FilenameStatePtr filename (new FilenameState (handler->add_filename_copy (state->filename)));
778         filenames.push_back (filename);
779         return filename;
780 }
781
782 void
783 ExportProfileManager::remove_filename_state (FilenameStatePtr state)
784 {
785         for (FilenameStateList::iterator it = filenames.begin(); it != filenames.end(); ++it) {
786                 if (*it == state) {
787                         filenames.erase (it);
788                         return;
789                 }
790         }
791 }
792
793 std::string
794 ExportProfileManager::get_sample_filename_for_format (ExportFilenamePtr filename, ExportFormatSpecPtr format)
795 {
796         assert (format);
797
798         if (channel_configs.empty()) { return ""; }
799
800         std::list<string> filenames;
801         build_filenames (filenames, filename, timespans.front()->timespans,
802                          channel_configs.front()->config, format);
803
804         if (filenames.empty()) { return ""; }
805         return filenames.front();
806 }
807
808 bool
809 ExportProfileManager::init_filenames (XMLNodeList nodes)
810 {
811         filenames.clear ();
812
813         for (XMLNodeList::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
814                 ExportFilenamePtr filename = handler->add_filename();
815                 filename->set_state (**it);
816                 filenames.push_back (FilenameStatePtr (new FilenameState (filename)));
817         }
818
819         if (filenames.empty()) {
820                 FilenameStatePtr filename (new FilenameState (handler->add_filename()));
821                 filenames.push_back (filename);
822                 return false;
823         }
824
825         return true;
826 }
827
828 boost::shared_ptr<ExportProfileManager::Warnings>
829 ExportProfileManager::get_warnings ()
830 {
831         boost::shared_ptr<Warnings> warnings (new Warnings ());
832
833         ChannelConfigStatePtr channel_config_state;
834         if (!channel_configs.empty ()) {
835                 channel_config_state = channel_configs.front();
836         }
837
838         TimespanStatePtr timespan_state = timespans.front();
839
840         /*** Check "global" config ***/
841
842         TimespanListPtr timespans = timespan_state->timespans;
843
844         ExportChannelConfigPtr channel_config;
845         if (channel_config_state) {
846                 channel_config = channel_config_state->config;
847         }
848
849         /* Check Timespans are not empty */
850
851         if (timespans->empty()) {
852                 warnings->errors.push_back (_("No timespan has been selected!"));
853         }
854
855         if (channel_config_state == 0) {
856                 warnings->errors.push_back (_("No channels have been selected!"));
857         } else {
858                 /* Check channel config ports */
859                 if (!channel_config->all_channels_have_ports ()) {
860                         warnings->warnings.push_back (_("Some channels are empty"));
861                 }
862         }
863
864         /*** Check files ***/
865
866         if (channel_config_state) {
867                 FormatStateList::const_iterator format_it;
868                 FilenameStateList::const_iterator filename_it;
869                 for (format_it = formats.begin(), filename_it = filenames.begin();
870                      format_it != formats.end() && filename_it != filenames.end();
871                      ++format_it, ++filename_it) {
872                         check_config (warnings, timespan_state, channel_config_state, *format_it, *filename_it);
873                 }
874         }
875
876         return warnings;
877 }
878
879 void
880 ExportProfileManager::check_config (boost::shared_ptr<Warnings> warnings,
881                                     TimespanStatePtr timespan_state,
882                                     ChannelConfigStatePtr channel_config_state,
883                                     FormatStatePtr format_state,
884                                     FilenameStatePtr filename_state)
885 {
886         TimespanListPtr timespans = timespan_state->timespans;
887         ExportChannelConfigPtr channel_config = channel_config_state->config;
888         ExportFormatSpecPtr format = format_state->format;
889         ExportFilenamePtr filename = filename_state->filename;
890
891         /* Check format and maximum channel count */
892         if (!format || !format->type()) {
893                 warnings->errors.push_back (_("No format selected!"));
894         } else if (!channel_config->get_n_chans()) {
895                 warnings->errors.push_back (_("All channels are empty!"));
896         } else if (!check_format (format, channel_config->get_n_chans())) {
897                 warnings->errors.push_back (_("One or more of the selected formats is not compatible with this system!"));
898         } else if (format->channel_limit() < channel_config->get_n_chans()) {
899                 warnings->errors.push_back
900                   (string_compose (_("%1 supports only %2 channels, but you have %3 channels in your channel configuration"),
901                                      format->format_name(),
902                                      format->channel_limit(),
903                                      channel_config->get_n_chans()));
904         }
905
906         if (!warnings->errors.empty()) { return; }
907
908         /* Check filenames */
909
910 //      filename->include_timespan = (timespans->size() > 1); Disabled for now...
911
912         std::list<string> paths;
913         build_filenames(paths, filename, timespans, channel_config, format);
914
915         for (std::list<string>::const_iterator path_it = paths.begin(); path_it != paths.end(); ++path_it) {
916
917                 string path = *path_it;
918
919                 if (Glib::file_test (path, Glib::FILE_TEST_EXISTS)) {
920                         warnings->conflicting_filenames.push_back (path);
921                 }
922
923                 if (format->with_toc()) {
924                         string marker_file = handler->get_cd_marker_filename(path, CDMarkerTOC);
925                         if (Glib::file_test (marker_file, Glib::FILE_TEST_EXISTS)) {
926                                 warnings->conflicting_filenames.push_back (marker_file);
927                         }
928                 }
929
930                 if (format->with_cue()) {
931                         string marker_file = handler->get_cd_marker_filename(path, CDMarkerCUE);
932                         if (Glib::file_test (marker_file, Glib::FILE_TEST_EXISTS)) {
933                                 warnings->conflicting_filenames.push_back (marker_file);
934                         }
935                 }
936         }
937 }
938
939 bool
940 ExportProfileManager::check_format (ExportFormatSpecPtr format, uint32_t channels)
941 {
942         switch (format->type()) {
943           case ExportFormatBase::T_Sndfile:
944                 return check_sndfile_format (format, channels);
945
946           default:
947                 throw ExportFailed (X_("Invalid format given for ExportFileFactory::check!"));
948         }
949 }
950
951 bool
952 ExportProfileManager::check_sndfile_format (ExportFormatSpecPtr format, unsigned int channels)
953 {
954         SF_INFO sf_info;
955         sf_info.channels = channels;
956         sf_info.samplerate = format->sample_rate ();
957         sf_info.format = format->format_id () | format->sample_format ();
958
959         return (sf_format_check (&sf_info) == SF_TRUE ? true : false);
960 }
961
962 void
963 ExportProfileManager::build_filenames(std::list<std::string> & result, ExportFilenamePtr filename,
964                                       TimespanListPtr timespans, ExportChannelConfigPtr channel_config,
965                                       ExportFormatSpecPtr format)
966 {
967         for (std::list<ExportTimespanPtr>::iterator timespan_it = timespans->begin();
968              timespan_it != timespans->end(); ++timespan_it) {
969                 filename->set_timespan (*timespan_it);
970
971                 if (channel_config->get_split()) {
972                         filename->include_channel = true;
973
974                         for (uint32_t chan = 1; chan <= channel_config->get_n_chans(); ++chan) {
975                                 filename->set_channel (chan);
976                                 result.push_back(filename->get_path (format));
977                         }
978
979                 } else {
980                         filename->include_channel = false;
981                         result.push_back(filename->get_path (format));
982                 }
983         }
984 }
985
986 }; // namespace ARDOUR