Add constructor of MonoPictureFrame from a JPEG2000 codestream file.
[libdcp.git] / src / subtitle_content.cc
1 /*
2     Copyright (C) 2012-2014 Carl Hetherington <cth@carlh.net>
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include "raw_convert.h"
21 #include "subtitle_content.h"
22 #include "util.h"
23 #include "xml.h"
24 #include "font.h"
25 #include "text.h"
26 #include "load_font.h"
27 #include "subtitle_string.h"
28 #include "AS_DCP.h"
29 #include "KM_util.h"
30 #include <libxml++/nodes/element.h>
31 #include <boost/algorithm/string.hpp>
32 #include <fstream>
33
34 using std::string;
35 using std::list;
36 using std::ostream;
37 using std::ofstream;
38 using std::stringstream;
39 using std::cout;
40 using boost::shared_ptr;
41 using boost::optional;
42 using namespace dcp;
43
44 SubtitleContent::SubtitleContent (boost::filesystem::path file, bool mxf)
45         : Content (file)
46 {
47         shared_ptr<cxml::Document> xml;
48         
49         if (mxf) {
50                 ASDCP::TimedText::MXFReader reader;
51                 Kumu::Result_t r = reader.OpenRead (file.string().c_str ());
52                 if (ASDCP_FAILURE (r)) {
53                         boost::throw_exception (MXFFileError ("could not open MXF file for reading", file, r));
54                 }
55                 
56                 string s;
57                 reader.ReadTimedTextResource (s, 0, 0);
58                 xml.reset (new cxml::Document ("SubtitleReel"));
59                 stringstream t;
60                 t << s;
61                 xml->read_stream (t);
62
63                 ASDCP::WriterInfo info;
64                 reader.FillWriterInfo (info);
65                 
66                 char buffer[64];
67                 Kumu::bin2UUIDhex (info.AssetUUID, ASDCP::UUIDlen, buffer, sizeof (buffer));
68                 _id = buffer;
69
70         } else {
71                 xml.reset (new cxml::Document ("DCSubtitle"));
72                 xml->read_file (file);
73                 _id = xml->string_child ("SubtitleID");
74         }
75
76         /* XXX: hacks aplenty in here; probably need separate parsers for DCSubtitle and SubtitleReel */
77
78         _movie_title = xml->optional_string_child ("MovieTitle");
79         _reel_number = xml->string_child ("ReelNumber");
80         _language = xml->string_child ("Language");
81
82         xml->ignore_child ("LoadFont");
83
84         list<shared_ptr<dcp::Font> > font_nodes = type_children<dcp::Font> (xml, "Font");
85         _load_font_nodes = type_children<dcp::LoadFont> (xml, "LoadFont");
86
87         /* Now make Subtitle objects to represent the raw XML nodes
88            in a sane way.
89         */
90
91         shared_ptr<cxml::Node> subtitle_list = xml->optional_node_child ("SubtitleList");
92         if (subtitle_list) {
93                 list<shared_ptr<dcp::Font> > font = type_children<dcp::Font> (subtitle_list, "Font");
94                 copy (font.begin(), font.end(), back_inserter (font_nodes));
95         }
96         
97         ParseState parse_state;
98         examine_font_nodes (xml, font_nodes, parse_state);
99 }
100
101 SubtitleContent::SubtitleContent (string movie_title, string language)
102         : _movie_title (movie_title)
103         , _reel_number ("1")
104         , _language (language)
105 {
106
107 }
108
109 void
110 SubtitleContent::examine_font_nodes (
111         shared_ptr<const cxml::Node> xml,
112         list<shared_ptr<dcp::Font> > const & font_nodes,
113         ParseState& parse_state
114         )
115 {
116         for (list<shared_ptr<dcp::Font> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
117
118                 parse_state.font_nodes.push_back (*i);
119                 maybe_add_subtitle ((*i)->text, parse_state);
120
121                 for (list<shared_ptr<dcp::Subtitle> >::iterator j = (*i)->subtitle_nodes.begin(); j != (*i)->subtitle_nodes.end(); ++j) {
122                         parse_state.subtitle_nodes.push_back (*j);
123                         examine_text_nodes (xml, (*j)->text_nodes, parse_state);
124                         examine_font_nodes (xml, (*j)->font_nodes, parse_state);
125                         parse_state.subtitle_nodes.pop_back ();
126                 }
127         
128                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
129                 examine_text_nodes (xml, (*i)->text_nodes, parse_state);
130                 
131                 parse_state.font_nodes.pop_back ();
132         }
133 }
134
135 void
136 SubtitleContent::examine_text_nodes (
137         shared_ptr<const cxml::Node> xml,
138         list<shared_ptr<dcp::Text> > const & text_nodes,
139         ParseState& parse_state
140         )
141 {
142         for (list<shared_ptr<dcp::Text> >::const_iterator i = text_nodes.begin(); i != text_nodes.end(); ++i) {
143                 parse_state.text_nodes.push_back (*i);
144                 maybe_add_subtitle ((*i)->text, parse_state);
145                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
146                 parse_state.text_nodes.pop_back ();
147         }
148 }
149
150 void
151 SubtitleContent::maybe_add_subtitle (string text, ParseState const & parse_state)
152 {
153         if (empty_or_white_space (text)) {
154                 return;
155         }
156         
157         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
158                 return;
159         }
160
161         assert (!parse_state.text_nodes.empty ());
162         assert (!parse_state.subtitle_nodes.empty ());
163         
164         dcp::Font effective_font (parse_state.font_nodes);
165         dcp::Text effective_text (*parse_state.text_nodes.back ());
166         dcp::Subtitle effective_subtitle (*parse_state.subtitle_nodes.back ());
167
168         _subtitles.push_back (
169                 SubtitleString (
170                         font_id_to_name (effective_font.id),
171                         effective_font.italic.get(),
172                         effective_font.color.get(),
173                         effective_font.size,
174                         effective_subtitle.in,
175                         effective_subtitle.out,
176                         effective_text.v_position,
177                         effective_text.v_align,
178                         text,
179                         effective_font.effect ? effective_font.effect.get() : NONE,
180                         effective_font.effect_color.get(),
181                         effective_subtitle.fade_up_time,
182                         effective_subtitle.fade_down_time
183                         )
184                 );
185 }
186
187 list<SubtitleString>
188 SubtitleContent::subtitles_at (Time t) const
189 {
190         list<SubtitleString> s;
191         for (list<SubtitleString>::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
192                 if (i->in() <= t && t <= i->out ()) {
193                         s.push_back (*i);
194                 }
195         }
196
197         return s;
198 }
199
200 std::string
201 SubtitleContent::font_id_to_name (string id) const
202 {
203         list<shared_ptr<dcp::LoadFont> >::const_iterator i = _load_font_nodes.begin();
204         while (i != _load_font_nodes.end() && (*i)->id != id) {
205                 ++i;
206         }
207
208         if (i == _load_font_nodes.end ()) {
209                 return "";
210         }
211
212         if ((*i)->uri && (*i)->uri.get() == "arial.ttf") {
213                 return "Arial";
214         }
215
216         return "";
217 }
218
219 void
220 SubtitleContent::add (SubtitleString s)
221 {
222         _subtitles.push_back (s);
223 }
224
225 struct SubtitleSorter {
226         bool operator() (SubtitleString const & a, SubtitleString const & b) {
227                 if (a.in() != b.in()) {
228                         return a.in() < b.in();
229                 }
230                 return a.v_position() < b.v_position();
231         }
232 };
233
234 void
235 SubtitleContent::write_xml (boost::filesystem::path p) const
236 {
237         FILE* f = fopen_boost (p, "w");
238         if (!f) {
239                 throw FileError ("Could not open file for writing", p, -1);
240         }
241         
242         Glib::ustring const s = xml_as_string ();
243         fwrite (s.c_str(), 1, s.bytes(), f);
244         fclose (f);
245
246         _file = p;
247 }
248
249 Glib::ustring
250 SubtitleContent::xml_as_string () const
251 {
252         xmlpp::Document doc;
253         xmlpp::Element* root = doc.create_root_node ("DCSubtitle");
254         root->set_attribute ("Version", "1.0");
255
256         root->add_child("SubtitleID")->add_child_text (_id);
257         if (_movie_title) {
258                 root->add_child("MovieTitle")->add_child_text (_movie_title.get ());
259         }
260         root->add_child("ReelNumber")->add_child_text (raw_convert<string> (_reel_number));
261         root->add_child("Language")->add_child_text (_language);
262
263         if (_load_font_nodes.size() > 1) {
264                 boost::throw_exception (MiscError ("multiple LoadFont nodes not supported"));
265         }
266
267         if (!_load_font_nodes.empty ()) {
268                 xmlpp::Element* load_font = root->add_child("LoadFont");
269                 load_font->set_attribute ("Id", _load_font_nodes.front()->id);
270                 if (_load_font_nodes.front()->uri) {
271                         load_font->set_attribute ("URI", _load_font_nodes.front()->uri.get ());
272                 }
273         }
274
275         list<SubtitleString> sorted = _subtitles;
276         sorted.sort (SubtitleSorter ());
277
278         /* XXX: multiple fonts not supported */
279         /* XXX: script, underlined, weight not supported */
280
281         bool italic = false;
282         Color color;
283         int size = 0;
284         Effect effect = NONE;
285         Color effect_color;
286         int spot_number = 1;
287         Time last_in;
288         Time last_out;
289         Time last_fade_up_time;
290         Time last_fade_down_time;
291
292         xmlpp::Element* font = 0;
293         xmlpp::Element* subtitle = 0;
294
295         for (list<SubtitleString>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
296
297                 /* We will start a new <Font>...</Font> whenever some font property changes.
298                    I suppose we should really make an optimal hierarchy of <Font> tags, but
299                    that seems hard.
300                 */
301
302                 bool const font_changed =
303                         italic       != i->italic()       ||
304                         color        != i->color()        ||
305                         size         != i->size()         ||
306                         effect       != i->effect()       ||
307                         effect_color != i->effect_color();
308
309                 if (font_changed) {
310                         italic = i->italic ();
311                         color = i->color ();
312                         size = i->size ();
313                         effect = i->effect ();
314                         effect_color = i->effect_color ();
315                 }
316
317                 if (!font || font_changed) {
318                         font = root->add_child ("Font");
319                         string id = "theFontId";
320                         if (!_load_font_nodes.empty()) {
321                                 id = _load_font_nodes.front()->id;
322                         }
323                         font->set_attribute ("Id", id);
324                         font->set_attribute ("Italic", italic ? "yes" : "no");
325                         font->set_attribute ("Color", color.to_argb_string());
326                         font->set_attribute ("Size", raw_convert<string> (size));
327                         font->set_attribute ("Effect", effect_to_string (effect));
328                         font->set_attribute ("EffectColor", effect_color.to_argb_string());
329                         font->set_attribute ("Script", "normal");
330                         font->set_attribute ("Underlined", "no");
331                         font->set_attribute ("Weight", "normal");
332                 }
333
334                 if (!subtitle || font_changed ||
335                     (last_in != i->in() ||
336                      last_out != i->out() ||
337                      last_fade_up_time != i->fade_up_time() ||
338                      last_fade_down_time != i->fade_down_time()
339                             )) {
340
341                         subtitle = font->add_child ("Subtitle");
342                         subtitle->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
343                         subtitle->set_attribute ("TimeIn", i->in().to_string());
344                         subtitle->set_attribute ("TimeOut", i->out().to_string());
345                         subtitle->set_attribute ("FadeUpTime", raw_convert<string> (i->fade_up_time().to_ticks()));
346                         subtitle->set_attribute ("FadeDownTime", raw_convert<string> (i->fade_down_time().to_ticks()));
347
348                         last_in = i->in ();
349                         last_out = i->out ();
350                         last_fade_up_time = i->fade_up_time ();
351                         last_fade_down_time = i->fade_down_time ();
352                 }
353
354                 xmlpp::Element* text = subtitle->add_child ("Text");
355                 text->set_attribute ("VAlign", valign_to_string (i->v_align()));                
356                 text->set_attribute ("VPosition", raw_convert<string> (i->v_position()));
357                 text->add_child_text (i->text());
358         }
359
360         return doc.write_to_string_formatted ("UTF-8");
361 }
362
363 Time
364 SubtitleContent::latest_subtitle_out () const
365 {
366         Time t;
367         for (list<SubtitleString>::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
368                 if (i->out() > t) {
369                         t = i->out ();
370                 }
371         }
372
373         return t;
374 }