Basically-working interop subtitle font handling.
[libdcp.git] / src / subtitle_asset.cc
1 /*
2     Copyright (C) 2012-2015 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_asset.h"
22 #include "util.h"
23 #include "xml.h"
24 #include "font_node.h"
25 #include "text_node.h"
26 #include "subtitle_string.h"
27 #include "dcp_assert.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 <boost/shared_array.hpp>
33 #include <fstream>
34
35 using std::string;
36 using std::list;
37 using std::ostream;
38 using std::ofstream;
39 using std::stringstream;
40 using std::cout;
41 using std::cerr;
42 using boost::shared_ptr;
43 using boost::shared_array;
44 using boost::optional;
45 using boost::dynamic_pointer_cast;
46 using namespace dcp;
47
48 SubtitleAsset::SubtitleAsset ()
49 {
50
51 }
52
53 SubtitleAsset::SubtitleAsset (boost::filesystem::path file)
54         : Asset (file)
55 {
56
57 }
58
59 void
60 SubtitleAsset::parse_subtitles (shared_ptr<cxml::Document> xml, list<shared_ptr<dcp::FontNode> > font_nodes)
61 {
62         /* Make Subtitle objects to represent the raw XML nodes in a sane way */
63         ParseState parse_state;
64         examine_font_nodes (xml, font_nodes, parse_state);
65 }
66
67 void
68 SubtitleAsset::examine_font_nodes (
69         shared_ptr<const cxml::Node> xml,
70         list<shared_ptr<dcp::FontNode> > const & font_nodes,
71         ParseState& parse_state
72         )
73 {
74         for (list<shared_ptr<dcp::FontNode> >::const_iterator i = font_nodes.begin(); i != font_nodes.end(); ++i) {
75
76                 parse_state.font_nodes.push_back (*i);
77                 maybe_add_subtitle ((*i)->text, parse_state);
78
79                 for (list<shared_ptr<dcp::SubtitleNode> >::iterator j = (*i)->subtitle_nodes.begin(); j != (*i)->subtitle_nodes.end(); ++j) {
80                         parse_state.subtitle_nodes.push_back (*j);
81                         examine_text_nodes (xml, (*j)->text_nodes, parse_state);
82                         examine_font_nodes (xml, (*j)->font_nodes, parse_state);
83                         parse_state.subtitle_nodes.pop_back ();
84                 }
85         
86                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
87                 examine_text_nodes (xml, (*i)->text_nodes, parse_state);
88                 
89                 parse_state.font_nodes.pop_back ();
90         }
91 }
92
93 void
94 SubtitleAsset::examine_text_nodes (
95         shared_ptr<const cxml::Node> xml,
96         list<shared_ptr<dcp::TextNode> > const & text_nodes,
97         ParseState& parse_state
98         )
99 {
100         for (list<shared_ptr<dcp::TextNode> >::const_iterator i = text_nodes.begin(); i != text_nodes.end(); ++i) {
101                 parse_state.text_nodes.push_back (*i);
102                 maybe_add_subtitle ((*i)->text, parse_state);
103                 examine_font_nodes (xml, (*i)->font_nodes, parse_state);
104                 parse_state.text_nodes.pop_back ();
105         }
106 }
107
108 void
109 SubtitleAsset::maybe_add_subtitle (string text, ParseState const & parse_state)
110 {
111         if (empty_or_white_space (text)) {
112                 return;
113         }
114         
115         if (parse_state.text_nodes.empty() || parse_state.subtitle_nodes.empty ()) {
116                 return;
117         }
118
119         DCP_ASSERT (!parse_state.text_nodes.empty ());
120         DCP_ASSERT (!parse_state.subtitle_nodes.empty ());
121         
122         dcp::FontNode effective_font (parse_state.font_nodes);
123         dcp::TextNode effective_text (*parse_state.text_nodes.back ());
124         dcp::SubtitleNode effective_subtitle (*parse_state.subtitle_nodes.back ());
125
126         _subtitles.push_back (
127                 SubtitleString (
128                         effective_font.id,
129                         effective_font.italic.get_value_or (false),
130                         effective_font.colour.get_value_or (dcp::Colour (255, 255, 255)),
131                         effective_font.size,
132                         effective_font.aspect_adjust.get_value_or (1.0),
133                         effective_subtitle.in,
134                         effective_subtitle.out,
135                         effective_text.h_position,
136                         effective_text.h_align,
137                         effective_text.v_position,
138                         effective_text.v_align,
139                         text,
140                         effective_font.effect.get_value_or (NONE),
141                         effective_font.effect_colour.get_value_or (dcp::Colour (0, 0, 0)),
142                         effective_subtitle.fade_up_time,
143                         effective_subtitle.fade_down_time
144                         )
145                 );
146 }
147
148 list<SubtitleString>
149 SubtitleAsset::subtitles_during (Time from, Time to) const
150 {
151         list<SubtitleString> s;
152         for (list<SubtitleString>::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
153                 if (i->out() >= from && i->in() <= to) {
154                         s.push_back (*i);
155                 }
156         }
157
158         return s;
159 }
160
161 void
162 SubtitleAsset::add (SubtitleString s)
163 {
164         _subtitles.push_back (s);
165 }
166
167 Time
168 SubtitleAsset::latest_subtitle_out () const
169 {
170         Time t;
171         for (list<SubtitleString>::const_iterator i = _subtitles.begin(); i != _subtitles.end(); ++i) {
172                 if (i->out() > t) {
173                         t = i->out ();
174                 }
175         }
176
177         return t;
178 }
179
180 bool
181 SubtitleAsset::equals (shared_ptr<const Asset> other_asset, EqualityOptions options, NoteHandler note) const
182 {
183         if (!Asset::equals (other_asset, options, note)) {
184                 return false;
185         }
186         
187         shared_ptr<const SubtitleAsset> other = dynamic_pointer_cast<const SubtitleAsset> (other_asset);
188         if (!other) {
189                 return false;
190         }
191
192         if (_subtitles != other->_subtitles) {
193                 note (DCP_ERROR, "subtitles differ");
194                 return false;
195         }
196
197         return true;
198 }
199
200 struct SubtitleSorter {
201         bool operator() (SubtitleString const & a, SubtitleString const & b) {
202                 if (a.in() != b.in()) {
203                         return a.in() < b.in();
204                 }
205                 return a.v_position() < b.v_position();
206         }
207 };
208
209 void
210 SubtitleAsset::subtitles_as_xml (xmlpp::Element* root, int time_code_rate, string xmlns) const
211 {
212         list<SubtitleString> sorted = _subtitles;
213         sorted.sort (SubtitleSorter ());
214
215         /* XXX: script, underlined, weight not supported */
216
217         optional<string> font;
218         bool italic = false;
219         Colour colour;
220         int size = 0;
221         float aspect_adjust = 1.0;
222         Effect effect = NONE;
223         Colour effect_colour;
224         int spot_number = 1;
225         Time last_in;
226         Time last_out;
227         Time last_fade_up_time;
228         Time last_fade_down_time;
229
230         xmlpp::Element* font_element = 0;
231         xmlpp::Element* subtitle_element = 0;
232
233         for (list<SubtitleString>::iterator i = sorted.begin(); i != sorted.end(); ++i) {
234
235                 /* We will start a new <Font>...</Font> whenever some font property changes.
236                    I suppose we should really make an optimal hierarchy of <Font> tags, but
237                    that seems hard.
238                 */
239
240                 bool const font_changed =
241                         font          != i->font()          ||
242                         italic        != i->italic()        ||
243                         colour        != i->colour()        ||
244                         size          != i->size()          ||
245                         fabs (aspect_adjust - i->aspect_adjust()) > ASPECT_ADJUST_EPSILON ||
246                         effect        != i->effect()        ||
247                         effect_colour != i->effect_colour();
248
249                 if (font_changed) {
250                         font = i->font ();
251                         italic = i->italic ();
252                         colour = i->colour ();
253                         size = i->size ();
254                         aspect_adjust = i->aspect_adjust ();
255                         effect = i->effect ();
256                         effect_colour = i->effect_colour ();
257                 }
258
259                 if (!font_element || font_changed) {
260                         font_element = root->add_child ("Font", xmlns);
261                         if (font) {
262                                 font_element->set_attribute ("Id", font.get ());
263                         }
264                         font_element->set_attribute ("Italic", italic ? "yes" : "no");
265                         font_element->set_attribute ("Color", colour.to_argb_string());
266                         font_element->set_attribute ("Size", raw_convert<string> (size));
267                         if (fabs (aspect_adjust - 1.0) > ASPECT_ADJUST_EPSILON) {
268                                 font_element->set_attribute ("AspectAdjust", raw_convert<string> (aspect_adjust));
269                         }
270                         font_element->set_attribute ("Effect", effect_to_string (effect));
271                         font_element->set_attribute ("EffectColor", effect_colour.to_argb_string());
272                         font_element->set_attribute ("Script", "normal");
273                         font_element->set_attribute ("Underlined", "no");
274                         font_element->set_attribute ("Weight", "normal");
275                 }
276
277                 if (!subtitle_element || font_changed ||
278                     (last_in != i->in() ||
279                      last_out != i->out() ||
280                      last_fade_up_time != i->fade_up_time() ||
281                      last_fade_down_time != i->fade_down_time()
282                             )) {
283
284                         subtitle_element = font_element->add_child ("Subtitle", xmlns);
285                         subtitle_element->set_attribute ("SpotNumber", raw_convert<string> (spot_number++));
286                         subtitle_element->set_attribute ("TimeIn", i->in().rebase(time_code_rate).as_string());
287                         subtitle_element->set_attribute ("TimeOut", i->out().rebase(time_code_rate).as_string());
288                         subtitle_element->set_attribute ("FadeUpTime", raw_convert<string> (i->fade_up_time().as_editable_units(time_code_rate)));
289                         subtitle_element->set_attribute ("FadeDownTime", raw_convert<string> (i->fade_down_time().as_editable_units(time_code_rate)));
290
291                         last_in = i->in ();
292                         last_out = i->out ();
293                         last_fade_up_time = i->fade_up_time ();
294                         last_fade_down_time = i->fade_down_time ();
295                 }
296
297                 xmlpp::Element* text = subtitle_element->add_child ("Text", xmlns);
298                 if (i->h_align() != HALIGN_CENTER) {
299                         text->set_attribute ("HAlign", halign_to_string (i->h_align ()));
300                 }
301                 if (i->h_position() > ALIGN_EPSILON) {
302                         text->set_attribute ("HPosition", raw_convert<string> (i->h_position() * 100, 6));
303                 }
304                 text->set_attribute ("VAlign", valign_to_string (i->v_align()));                
305                 text->set_attribute ("VPosition", raw_convert<string> (i->v_position() * 100, 6));
306                 text->add_child_text (i->text());
307         }
308 }
309
310 void
311 SubtitleAsset::add_font_data (string id, boost::filesystem::path file)
312 {
313         boost::uintmax_t size = boost::filesystem::file_size (file);
314         FILE* f = fopen_boost (file, "r");
315         if (!f) {
316                 throw FileError ("could not open font file for reading", file, errno);
317         }
318
319         shared_array<uint8_t> data (new uint8_t[size]);
320         size_t const read = fread (data.get(), 1, size, f);
321         fclose (f);
322         
323         if (read != size) {
324                 throw FileError ("could not read font file", file, -1);
325         }
326
327         _fonts[id] = FontData (data, size, file);
328 }