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