fd76b2e9e0d7476ed92d580be912d06284ea194e
[ardour.git] / libs / ardour / export_handler.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 <ardour/export_handler.h>
22
23 #include <pbd/convert.h>
24 #include <pbd/filesystem.h>
25
26 #include <ardour/ardour.h>
27 #include <ardour/configuration.h>
28 #include <ardour/export_timespan.h>
29 #include <ardour/export_channel_configuration.h>
30 #include <ardour/export_status.h>
31 #include <ardour/export_format_specification.h>
32 #include <ardour/export_filename.h>
33 #include <ardour/export_processor.h>
34 #include <ardour/export_failed.h>
35
36 using namespace PBD;
37 using std::ofstream;
38
39 namespace ARDOUR
40 {
41
42 /*** ExportElementFactory ***/
43
44 ExportElementFactory::ExportElementFactory (Session & session) :
45   session (session)
46 {
47
48 }
49
50 ExportElementFactory::~ExportElementFactory ()
51 {
52
53 }
54
55 ExportElementFactory::TimespanPtr
56 ExportElementFactory::add_timespan ()
57 {
58         return TimespanPtr (new ExportTimespan (session.export_status, session.frame_rate()));
59 }
60
61 ExportElementFactory::ChannelConfigPtr
62 ExportElementFactory::add_channel_config ()
63 {
64         return ChannelConfigPtr (new ExportChannelConfiguration (session.export_status));
65 }
66
67 ExportElementFactory::FormatPtr
68 ExportElementFactory::add_format ()
69 {
70         return FormatPtr (new ExportFormatSpecification (session));
71 }
72
73 ExportElementFactory::FormatPtr
74 ExportElementFactory::add_format (XMLNode const & state)
75 {
76         return FormatPtr (new ExportFormatSpecification (session, state));
77 }
78
79 ExportElementFactory::FormatPtr
80 ExportElementFactory::add_format_copy (FormatPtr other)
81 {
82         return FormatPtr (new ExportFormatSpecification (*other));
83 }
84
85 ExportElementFactory::FilenamePtr
86 ExportElementFactory::add_filename ()
87 {
88         return FilenamePtr (new ExportFilename (session));
89 }
90
91 ExportElementFactory::FilenamePtr
92 ExportElementFactory::add_filename_copy (FilenamePtr other)
93 {
94         return FilenamePtr (new ExportFilename (*other));
95 }
96
97 /*** ExportHandler ***/
98
99 ExportHandler::ExportHandler (Session & session) :
100   ExportElementFactory (session),
101   session (session),
102   realtime (false)
103 {
104         processor.reset (new ExportProcessor (session));
105
106         files_written_connection = ExportProcessor::WritingFile.connect (sigc::mem_fun (files_written, &std::list<Glib::ustring>::push_back));
107 }
108
109 ExportHandler::~ExportHandler ()
110 {
111         if (session.export_status.aborted()) {
112                 for (std::list<Glib::ustring>::iterator it = files_written.begin(); it != files_written.end(); ++it) {
113                         sys::remove (sys::path (*it));
114                 }
115         }
116         
117         channel_config_connection.disconnect();
118         files_written_connection.disconnect();
119 }
120
121 bool
122 ExportHandler::add_export_config (TimespanPtr timespan, ChannelConfigPtr channel_config, FormatPtr format, FilenamePtr filename)
123 {
124         FileSpec spec (channel_config, format, filename);
125         ConfigPair pair (timespan, spec);
126         config_map.insert (pair);
127         
128         return true;
129 }
130
131 /// Starts exporting the registered configurations
132 /** The following happens, when do_export is called:
133  * 1. Session is prepared in do_export
134  * 2. start_timespan is called, which then registers all necessary channel configs to a timespan
135  * 3. The timespan reads each unique channel into a tempfile and calls Session::stop_export when the end is reached
136  * 4. stop_export emits ExportFinished after stopping the transport, this ends up calling finish_timespan
137  * 5. finish_timespan registers all the relevant formats and filenames to relevant channel configurations
138  * 6. finish_timespan does a manual call to timespan_thread_finished, which gets the next channel configuration
139  *    for the current timespan, calling write_files for it
140  * 7. write_files writes the actual export files, composing them from the individual channels from tempfiles and
141  *    emits FilesWritten when it is done, which ends up calling timespan_thread_finished
142  * 8. Once all channel configs are written, a new timespan is started by calling start_timespan
143  * 9. When all timespans are written the session is taken out of export.
144  */
145
146 void
147 ExportHandler::do_export (bool rt)
148 {
149         /* Count timespans */
150
151         ExportStatus & status = session.export_status;
152         status.init();
153         std::set<TimespanPtr> timespan_set;
154         for (ConfigMap::iterator it = config_map.begin(); it != config_map.end(); ++it) {
155                 timespan_set.insert (it->first);
156         }
157         status.total_timespans = timespan_set.size();
158
159         /* Start export */
160
161         realtime = rt;
162
163         session.ExportFinished.connect (sigc::mem_fun (*this, &ExportHandler::finish_timespan));
164         session.pre_export ();
165         start_timespan ();
166 }
167
168 struct LocationSortByStart {
169     bool operator() (Location *a, Location *b) {
170             return a->start() < b->start();
171     }
172 };
173
174 void
175 ExportHandler::export_cd_marker_file (TimespanPtr timespan, FormatPtr file_format, std::string filename, CDMarkerFormat format)
176 {
177         string filepath;
178         void (ExportHandler::*header_func) (CDMarkerStatus &);
179         void (ExportHandler::*track_func) (CDMarkerStatus &);
180         void (ExportHandler::*index_func) (CDMarkerStatus &);
181
182         switch (format) {
183           case CDMarkerTOC:
184                 filepath = filename + ".toc";
185                 header_func = &ExportHandler::write_toc_header;
186                 track_func = &ExportHandler::write_track_info_toc;
187                 index_func = &ExportHandler::write_index_info_toc;
188                 break;
189           case CDMarkerCUE:
190                 filepath = filename + ".cue";
191                 header_func = &ExportHandler::write_cue_header;
192                 track_func = &ExportHandler::write_track_info_cue;
193                 index_func = &ExportHandler::write_index_info_cue;
194                 break;
195           default:
196                 return;
197         }
198         
199         CDMarkerStatus status (filepath, timespan, file_format, filename);
200
201         if (!status.out) {
202                 error << string_compose(_("Editor: cannot open \"%1\" as export file for CD marker file"), filepath) << endmsg;
203                 return;
204         }
205         
206         (this->*header_func) (status);
207         
208         /* Get locations and sort */
209         
210         Locations::LocationList const & locations (session.locations()->list());
211         Locations::LocationList::const_iterator i;
212         Locations::LocationList temp;
213
214         for (i = locations.begin(); i != locations.end(); ++i) {
215                 if ((*i)->start() >= timespan->get_start() && (*i)->end() <= timespan->get_end() && (*i)->is_cd_marker() && !(*i)->is_end()) {
216                         temp.push_back (*i);
217                 }
218         }
219
220         if (temp.empty()) {
221                 // TODO One index marker for whole thing
222                 return;
223         }
224         
225         LocationSortByStart cmp;
226         temp.sort (cmp);
227         Locations::LocationList::const_iterator nexti;
228
229         /* Start actual marker stuff */
230
231         nframes_t last_end_time = timespan->get_start(), last_start_time = timespan->get_start();
232         status.track_position = last_start_time - timespan->get_start();
233
234         for (i = temp.begin(); i != temp.end(); ++i) {
235
236                 status.marker = *i;
237
238                 if ((*i)->start() < last_end_time) {
239                         if ((*i)->is_mark()) {
240                                 /* Index within track */
241                                 
242                                 status.index_position = (*i)->start() - timespan->get_start();
243                                 (this->*index_func) (status);
244                         }
245                         
246                         continue;
247                 }
248
249                 /* A track, defined by a cd range marker or a cd location marker outside of a cd range */
250                 
251                 status.track_position = last_end_time - timespan->get_start();
252                 status.track_start_frame = (*i)->start() - timespan->get_start();  // everything before this is the pregap
253                 status.track_duration = 0;
254                 
255                 if ((*i)->is_mark()) {
256                         // a mark track location needs to look ahead to the next marker's start to determine length
257                         nexti = i;
258                         ++nexti;
259                         
260                         if (nexti != temp.end()) {
261                                 status.track_duration = (*nexti)->start() - last_end_time;
262                                 
263                                 last_start_time = (*i)->start();
264                                 last_end_time = (*nexti)->start();
265                         } else {
266                                 // this was the last marker, use timespan end
267                                 status.track_duration = timespan->get_end() - last_end_time;
268                                 
269                                 last_start_time = (*i)->start();
270                                 last_end_time = timespan->get_end();
271                         }
272                 } else {
273                         // range
274                         status.track_duration = (*i)->end() - last_end_time;
275                         
276                         last_start_time = (*i)->start();
277                         last_end_time = (*i)->end();
278                 }
279                 
280                 (this->*track_func) (status);
281         }
282 }
283
284 void
285 ExportHandler::write_cue_header (CDMarkerStatus & status)
286 {
287         Glib::ustring title = status.timespan->name().compare ("Session") ? status.timespan->name() : (Glib::ustring) session.name();
288
289         status.out << "REM Cue file generated by Ardour" << endl;
290         status.out << "TITLE \"" << title << "\"" << endl;
291
292         // TODO
293         if (!status.format->format_name().compare ("WAV")) {
294                   status.out << "FILE " << status.filename  << " WAVE" << endl;
295         } else {
296                   status.out << "FILE " << status.filename  << ' ' << status.format->format_name() << endl;
297         }
298 }
299
300 void
301 ExportHandler::write_toc_header (CDMarkerStatus & status)
302 {
303         Glib::ustring title = status.timespan->name().compare ("Session") ? status.timespan->name() : (Glib::ustring) session.name();
304
305         status.out << "CD_DA" << endl;
306         status.out << "CD_TEXT {" << endl << "  LANGUAGE_MAP {" << endl << "    0 : EN" << endl << "  }" << endl;
307         status.out << "  LANGUAGE 0 {" << endl << "    TITLE \"" << title << "\"" << endl << "  }" << endl << "}" << endl;
308 }
309
310 void
311 ExportHandler::write_track_info_cue (CDMarkerStatus & status)
312 {
313         gchar buf[18];
314
315         status.out << endl << "TRACK " << status.track_number << " AUDIO" << endl;
316         status.out << "FLAGS " ;
317         
318         if (status.marker->cd_info.find("scms") != status.marker->cd_info.end())  {
319                 status.out << "SCMS ";
320         } else {
321                 status.out << "DCP ";
322         }
323         
324         if (status.marker->cd_info.find("preemph") != status.marker->cd_info.end())  {
325                 status.out << "PRE";
326         }
327         status.out << endl;
328         
329         if (status.marker->cd_info.find("isrc") != status.marker->cd_info.end())  {
330                 status.out << "ISRC " << status.marker->cd_info["isrc"] << endl;
331                 
332         }
333         if (status.marker->name() != "") {
334                 status.out << "TITLE \"" << status.marker->name() << "\"" << endl;
335         }
336         
337         if (status.marker->cd_info.find("performer") != status.marker->cd_info.end()) {
338                 status.out << "PERFORMER \"" <<  status.marker->cd_info["performer"] << "\"" << endl;
339         }
340         
341         if (status.marker->cd_info.find("string_composer") != status.marker->cd_info.end()) {
342                 status.out << "SONGWRITER \"" << status.marker->cd_info["string_composer"]  << "\"" << endl;
343         }
344
345         frames_to_cd_frames_string (buf, status.track_position);
346         status.out << "INDEX 00" << buf << endl;
347         
348         frames_to_cd_frames_string (buf, status.track_start_frame);
349         status.out << "INDEX 01" << buf << endl;
350         
351         status.index_number = 2;
352         status.track_number++;
353 }
354
355 void
356 ExportHandler::write_track_info_toc (CDMarkerStatus & status)
357 {
358         gchar buf[18];
359
360         status.out << endl << "TRACK AUDIO" << endl;
361                 
362         if (status.marker->cd_info.find("scms") != status.marker->cd_info.end())  {
363                 status.out << "NO ";
364         }
365         status.out << "COPY" << endl;
366         
367         if (status.marker->cd_info.find("preemph") != status.marker->cd_info.end())  {
368                 status.out << "PRE_EMPHASIS" << endl;
369         } else {
370                 status.out << "NO PRE_EMPHASIS" << endl;
371         }
372         
373         if (status.marker->cd_info.find("isrc") != status.marker->cd_info.end())  {
374                 status.out << "ISRC \"" << status.marker->cd_info["isrc"] << "\"" << endl;
375         }
376         
377         status.out << "CD_TEXT {" << endl << "  LANGUAGE 0 {" << endl << "     TITLE \"" << status.marker->name() << "\"" << endl;
378         if (status.marker->cd_info.find("performer") != status.marker->cd_info.end()) {
379                 status.out << "     PERFORMER \"" << status.marker->cd_info["performer"]  << "\"" << endl;
380         }
381         if (status.marker->cd_info.find("string_composer") != status.marker->cd_info.end()) {
382                 status.out  << "     COMPOSER \"" << status.marker->cd_info["string_composer"] << "\"" << endl;
383         }
384         
385         if (status.marker->cd_info.find("isrc") != status.marker->cd_info.end()) {                        
386                 status.out  << "     ISRC \"";
387                 status.out << status.marker->cd_info["isrc"].substr(0,2) << "-";
388                 status.out << status.marker->cd_info["isrc"].substr(2,3) << "-";
389                 status.out << status.marker->cd_info["isrc"].substr(5,2) << "-";
390                 status.out << status.marker->cd_info["isrc"].substr(7,5) << "\"" << endl;
391         }
392         
393         status.out << "  }" << endl << "}" << endl;
394         
395         frames_to_cd_frames_string (buf, status.track_position);
396         status.out << "FILE \"" << status.filename << "\" " << buf;
397         
398         frames_to_cd_frames_string (buf, status.track_duration);
399         status.out << buf << endl;
400         
401         frames_to_cd_frames_string (buf, status.track_start_frame - status.track_position);
402         status.out << "START" << buf << endl;
403 }
404
405 void
406 ExportHandler::write_index_info_cue (CDMarkerStatus & status)
407 {
408         gchar buf[18];
409
410         snprintf (buf, sizeof(buf), "INDEX %02d", cue_indexnum);
411         status.out << buf;
412         frames_to_cd_frames_string (buf, status.index_position);
413         status.out << buf << endl;
414         
415         cue_indexnum++;
416 }
417
418 void
419 ExportHandler::write_index_info_toc (CDMarkerStatus & status)
420 {
421         gchar buf[18];
422
423         frames_to_cd_frames_string (buf, status.index_position - status.track_position);
424         status.out << "INDEX" << buf << endl;
425 }
426
427 void
428 ExportHandler::frames_to_cd_frames_string (char* buf, nframes_t when)
429 {
430         nframes_t remainder;
431         nframes_t fr = session.nominal_frame_rate();
432         int mins, secs, frames;
433
434         mins = when / (60 * fr);
435         remainder = when - (mins * 60 * fr);
436         secs = remainder / fr;
437         remainder -= secs * fr;
438         frames = remainder / (fr / 75);
439         sprintf (buf, " %02d:%02d:%02d", mins, secs, frames);
440 }
441
442 void
443 ExportHandler::start_timespan ()
444 {
445         session.export_status.timespan++;
446
447         if (config_map.empty()) {
448                 session.finalize_audio_export();
449                 return;
450         }
451
452         current_timespan = config_map.begin()->first;
453         
454         /* Register channel configs with timespan */
455         
456         timespan_bounds = config_map.equal_range (current_timespan);
457         
458         for (ConfigMap::iterator it = timespan_bounds.first; it != timespan_bounds.second; ++it) {
459                 it->second.channel_config->register_with_timespan (current_timespan);
460         }
461
462         /* connect stuff and start export */
463
464         current_timespan->process_connection = session.ProcessExport.connect (sigc::mem_fun (*current_timespan, &ExportTimespan::process));
465         session.start_audio_export (current_timespan->get_start(), realtime);
466 }
467
468 void
469 ExportHandler::finish_timespan ()
470 {
471         current_timespan->process_connection.disconnect ();
472         
473         /* Register formats and filenames to relevant channel configs */
474         
475         session.export_status.total_formats = 0;
476         session.export_status.format = 0;
477         
478         for (ConfigMap::iterator it = timespan_bounds.first; it != timespan_bounds.second; ++it) {
479         
480                 session.export_status.total_formats++;
481         
482                 /* Setup filename */
483                 
484                 it->second.filename->set_timespan (current_timespan);
485                 it->second.filename->set_channel_config (it->second.channel_config);
486                 
487                 /* Do actual registration */
488         
489                 ChannelConfigPtr chan_config = it->second.channel_config;
490                 chan_config->register_file_config (it->second.format, it->second.filename);
491         }
492         
493         /* Start writing files by doing a manual call to timespan_thread_finished */
494         
495         current_map_it = timespan_bounds.first;
496         timespan_thread_finished ();
497 }
498
499 void
500 ExportHandler::timespan_thread_finished ()
501 {
502         channel_config_connection.disconnect();
503
504         if (current_map_it != timespan_bounds.second) {
505         
506                 /* Get next configuration as long as no new export process is started */
507                 
508                 ChannelConfigPtr cc = current_map_it->second.channel_config;
509                 while (!cc->write_files(processor)) {
510         
511                         ++current_map_it;
512                         
513                         if (current_map_it == timespan_bounds.second) {
514                         
515                                 /* reached end of bounds, this call will end up in the else block below */
516                         
517                                 timespan_thread_finished ();
518                                 return;
519                         }
520                         
521                         cc = current_map_it->second.channel_config;
522                 }
523         
524                 channel_config_connection = cc->FilesWritten.connect (sigc::mem_fun (*this, &ExportHandler::timespan_thread_finished));
525                 ++current_map_it;
526         
527         } else { /* All files are written from current timespan, reset timespan and start new */
528         
529                 /* Unregister configs and remove configs with this timespan */
530         
531                 for (ConfigMap::iterator it = timespan_bounds.first; it != timespan_bounds.second;) {
532                         it->second.channel_config->unregister_all ();
533                         
534                         ConfigMap::iterator to_erase = it;
535                         ++it;
536                         config_map.erase (to_erase);
537                 }
538                 
539                 /* Start new timespan */
540         
541                 start_timespan ();
542         
543         }
544 }
545
546 } // namespace ARDOUR