fd7b734ea22f7e9c573f2d1c465655c299297043
[libdcp.git] / src / cpl.cc
1 /*
2     Copyright (C) 2012 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 <fstream>
21 #include <libxml/parser.h>
22 #include "cpl.h"
23 #include "parse/cpl.h"
24 #include "util.h"
25 #include "picture_asset.h"
26 #include "sound_asset.h"
27 #include "subtitle_asset.h"
28 #include "parse/asset_map.h"
29 #include "reel.h"
30 #include "metadata.h"
31 #include "encryption.h"
32 #include "exceptions.h"
33 #include "compose.hpp"
34
35 using std::string;
36 using std::stringstream;
37 using std::ofstream;
38 using std::ostream;
39 using std::list;
40 using boost::shared_ptr;
41 using boost::lexical_cast;
42 using namespace libdcp;
43
44 CPL::CPL (string directory, string name, ContentKind content_kind, int length, int frames_per_second)
45         : _directory (directory)
46         , _name (name)
47         , _content_kind (content_kind)
48         , _length (length)
49         , _fps (frames_per_second)
50 {
51         _uuid = make_uuid ();
52 }
53
54 /** Construct a CPL object from a XML file.
55  *  @param directory The directory containing this CPL's DCP.
56  *  @param file The CPL XML filename.
57  *  @param asset_map The corresponding asset map.
58  *  @param require_mxfs true to throw an exception if a required MXF file does not exist.
59  */
60 CPL::CPL (string directory, string file, shared_ptr<const libdcp::parse::AssetMap> asset_map, bool require_mxfs)
61         : _directory (directory)
62         , _content_kind (FEATURE)
63         , _length (0)
64         , _fps (0)
65 {
66         /* Read the XML */
67         shared_ptr<parse::CPL> cpl;
68         try {
69                 cpl.reset (new parse::CPL (file));
70         } catch (FileError& e) {
71                 boost::throw_exception (FileError ("could not load CPL file", file));
72         }
73         
74         /* Now cherry-pick the required bits into our own data structure */
75         
76         _name = cpl->annotation_text;
77         _content_kind = cpl->content_kind;
78
79         for (list<shared_ptr<libdcp::parse::Reel> >::iterator i = cpl->reels.begin(); i != cpl->reels.end(); ++i) {
80
81                 shared_ptr<parse::Picture> p;
82
83                 if ((*i)->asset_list->main_picture) {
84                         p = (*i)->asset_list->main_picture;
85                 } else {
86                         p = (*i)->asset_list->main_stereoscopic_picture;
87                 }
88                 
89                 _fps = p->edit_rate.numerator;
90                 _length += p->duration;
91
92                 shared_ptr<PictureAsset> picture;
93                 shared_ptr<SoundAsset> sound;
94                 shared_ptr<SubtitleAsset> subtitle;
95
96                 /* Some rather twisted logic to decide if we are 3D or not;
97                    some DCPs give a MainStereoscopicPicture to indicate 3D, others
98                    just have a FrameRate twice the EditRate and apparently
99                    expect you to divine the fact that they are hence 3D.
100                 */
101
102                 if (!(*i)->asset_list->main_stereoscopic_picture && p->edit_rate == p->frame_rate) {
103
104                         try {
105                                 picture.reset (new MonoPictureAsset (
106                                                        _directory,
107                                                        asset_map->asset_from_id (p->id)->chunks.front()->path
108                                                        )
109                                         );
110
111                                 picture->set_entry_point (p->entry_point);
112                                 picture->set_duration (p->duration);
113                         } catch (MXFFileError) {
114                                 if (require_mxfs) {
115                                         throw;
116                                 }
117                         }
118                         
119                 } else {
120                         try {
121                                 picture.reset (new StereoPictureAsset (
122                                                        _directory,
123                                                        asset_map->asset_from_id (p->id)->chunks.front()->path,
124                                                        _fps,
125                                                        p->duration
126                                                        )
127                                         );
128
129                                 picture->set_entry_point (p->entry_point);
130                                 picture->set_duration (p->duration);
131                                 
132                         } catch (MXFFileError) {
133                                 if (require_mxfs) {
134                                         throw;
135                                 }
136                         }
137                         
138                 }
139                 
140                 if ((*i)->asset_list->main_sound) {
141                         
142                         try {
143                                 sound.reset (new SoundAsset (
144                                                      _directory,
145                                                      asset_map->asset_from_id ((*i)->asset_list->main_sound->id)->chunks.front()->path
146                                                      )
147                                         );
148
149                                 sound->set_entry_point ((*i)->asset_list->main_sound->entry_point);
150                                 sound->set_duration ((*i)->asset_list->main_sound->duration);
151                         } catch (MXFFileError) {
152                                 if (require_mxfs) {
153                                         throw;
154                                 }
155                         }
156                 }
157
158                 if ((*i)->asset_list->main_subtitle) {
159                         
160                         subtitle.reset (new SubtitleAsset (
161                                                 _directory,
162                                                 asset_map->asset_from_id ((*i)->asset_list->main_subtitle->id)->chunks.front()->path
163                                                 )
164                                 );
165
166                         subtitle->set_entry_point ((*i)->asset_list->main_subtitle->entry_point);
167                         subtitle->set_duration ((*i)->asset_list->main_subtitle->duration);
168                 }
169                         
170                 _reels.push_back (shared_ptr<Reel> (new Reel (picture, sound, subtitle)));
171         }
172 }
173
174 void
175 CPL::add_reel (shared_ptr<const Reel> reel)
176 {
177         _reels.push_back (reel);
178 }
179
180 void
181 CPL::write_xml (XMLMetadata const & metadata, shared_ptr<Encryption> crypt) const
182 {
183         boost::filesystem::path p;
184         p /= _directory;
185         stringstream s;
186         s << _uuid << "_cpl.xml";
187         p /= s.str();
188
189         xmlpp::Document doc;
190         xmlpp::Element* root = doc.create_root_node ("CompositionPlaylist", "http://www.smpte-ra.org/schemas/429-7/2006/CPL");
191
192         if (crypt) {
193                 root->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "dsig");
194         }
195         
196         root->add_child("Id")->add_child_text ("urn:uuid:" + _uuid);
197         root->add_child("AnnotationText")->add_child_text (_name);
198         root->add_child("IssueDate")->add_child_text (metadata.issue_date);
199         root->add_child("Creator")->add_child_text (metadata.creator);
200         root->add_child("ContentTitleText")->add_child_text (_name);
201         root->add_child("ContentKind")->add_child_text (content_kind_to_string (_content_kind));
202         {
203                 xmlpp::Node* cv = root->add_child ("ContentVersion");
204                 cv->add_child ("Id")->add_child_text ("urn:uri:" + _uuid + "_" + metadata.issue_date);
205                 cv->add_child ("LabelText")->add_child_text (_uuid + "_" + metadata.issue_date);
206         }
207         root->add_child("RatingList");
208
209         xmlpp::Node* reel_list = root->add_child ("ReelList");
210         
211         for (list<shared_ptr<const Reel> >::const_iterator i = _reels.begin(); i != _reels.end(); ++i) {
212                 (*i)->write_to_cpl (reel_list);
213         }
214
215         if (crypt) {
216                 sign (root, crypt->certificates, crypt->signer_key);
217         }
218
219         doc.write_to_file_formatted (p.string (), "UTF-8");
220
221         _digest = make_digest (p.string ());
222         _length = boost::filesystem::file_size (p.string ());
223 }
224
225 void
226 CPL::write_to_pkl (xmlpp::Node* node) const
227 {
228         xmlpp::Node* asset = node->add_child ("Asset");
229         asset->add_child("Id")->add_child_text ("urn:uuid:" + _uuid);
230         asset->add_child("Hash")->add_child_text (_digest);
231         asset->add_child("Size")->add_child_text (lexical_cast<string> (_length));
232         asset->add_child("Type")->add_child_text ("text/xml");
233 }
234
235 list<shared_ptr<const Asset> >
236 CPL::assets () const
237 {
238         list<shared_ptr<const Asset> > a;
239         for (list<shared_ptr<const Reel> >::const_iterator i = _reels.begin(); i != _reels.end(); ++i) {
240                 if ((*i)->main_picture ()) {
241                         a.push_back ((*i)->main_picture ());
242                 }
243                 if ((*i)->main_sound ()) {
244                         a.push_back ((*i)->main_sound ());
245                 }
246                 if ((*i)->main_subtitle ()) {
247                         a.push_back ((*i)->main_subtitle ());
248                 }
249         }
250
251         return a;
252 }
253
254 void
255 CPL::write_to_assetmap (xmlpp::Node* node) const
256 {
257         xmlpp::Node* asset = node->add_child ("Asset");
258         asset->add_child("Id")->add_child_text ("urn:uuid:" + _uuid);
259         xmlpp::Node* chunk_list = asset->add_child ("ChunkList");
260         xmlpp::Node* chunk = chunk_list->add_child ("Chunk");
261         chunk->add_child("Path")->add_child_text (_uuid + "_cpl.xml");
262         chunk->add_child("VolumeIndex")->add_child_text ("1");
263         chunk->add_child("Offset")->add_child_text("0");
264         chunk->add_child("Length")->add_child_text(lexical_cast<string> (_length));
265 }
266         
267         
268         
269 bool
270 CPL::equals (CPL const & other, EqualityOptions opt, boost::function<void (NoteType, string)> note) const
271 {
272         if (_name != other._name && !opt.cpl_names_can_differ) {
273                 stringstream s;
274                 s << "names differ: " << _name << " vs " << other._name << "\n";
275                 note (ERROR, s.str ());
276                 return false;
277         }
278
279         if (_content_kind != other._content_kind) {
280                 note (ERROR, "content kinds differ");
281                 return false;
282         }
283
284         if (_fps != other._fps) {
285                 note (ERROR, String::compose ("frames per second differ (%1 vs %2)", _fps, other._fps));
286                 return false;
287         }
288
289         if (_length != other._length) {
290                 stringstream s;
291                 s << "lengths differ (" << _length << " cf " << other._length << ")";
292                 note (ERROR, String::compose ("lengths differ (%1 vs %2)", _length, other._length));
293                 return false;
294         }
295
296         if (_reels.size() != other._reels.size()) {
297                 note (ERROR, String::compose ("reel counts differ (%1 vs %2)", _reels.size(), other._reels.size()));
298                 return false;
299         }
300         
301         list<shared_ptr<const Reel> >::const_iterator a = _reels.begin ();
302         list<shared_ptr<const Reel> >::const_iterator b = other._reels.begin ();
303         
304         while (a != _reels.end ()) {
305                 if (!(*a)->equals (*b, opt, note)) {
306                         return false;
307                 }
308                 ++a;
309                 ++b;
310         }
311
312         return true;
313 }
314
315 shared_ptr<xmlpp::Document>
316 CPL::make_kdm (
317         CertificateChain const & certificates,
318         string const & signer_key,
319         shared_ptr<const Certificate> recipient_cert,
320         boost::posix_time::ptime from,
321         boost::posix_time::ptime until,
322         MXFMetadata const & mxf_metadata,
323         XMLMetadata const & xml_metadata
324         ) const
325 {
326         assert (recipient_cert);
327         
328         shared_ptr<xmlpp::Document> doc (new xmlpp::Document);
329         xmlpp::Element* root = doc->create_root_node ("DCinemaSecurityMessage");
330         root->set_namespace_declaration ("http://www.smpte-ra.org/schemas/430-3/2006/ETM", "");
331         root->set_namespace_declaration ("http://www.w3.org/2000/09/xmldsig#", "ds");
332         root->set_namespace_declaration ("http://www.w3.org/2001/04/xmlenc#", "enc");
333
334         {
335                 xmlpp::Element* authenticated_public = root->add_child("AuthenticatedPublic");
336                 authenticated_public->set_attribute("Id", "ID_AuthenticatedPublic");
337                 xmlAddID (0, doc->cobj(), (const xmlChar *) "ID_AuthenticatedPublic", authenticated_public->get_attribute("Id")->cobj());
338                 
339                 authenticated_public->add_child("MessageId")->add_child_text ("urn:uuid:" + make_uuid());
340                 authenticated_public->add_child("MessageType")->add_child_text ("http://www.smpte-ra.org/430-1/2006/KDM#kdm-key-type");
341                 authenticated_public->add_child("AnnotationText")->add_child_text (mxf_metadata.product_name);
342                 authenticated_public->add_child("IssueDate")->add_child_text (xml_metadata.issue_date);
343
344                 {
345                         xmlpp::Element* signer = authenticated_public->add_child("Signer");
346                         signer->add_child("X509IssuerName", "ds")->add_child_text (
347                                 Certificate::name_for_xml (recipient_cert->issuer())
348                                 );
349                         signer->add_child("X509SerialNumber", "ds")->add_child_text (
350                                 recipient_cert->serial()
351                                 );
352                 }
353
354                 {
355                         xmlpp::Element* required_extensions = authenticated_public->add_child("RequiredExtensions");
356
357                         {
358                                 xmlpp::Element* kdm_required_extensions = required_extensions->add_child("KDMRequiredExtensions");
359                                 kdm_required_extensions->set_namespace_declaration ("http://www.smpte-ra.org/schemas/430-1/2006/KDM");
360                                 {
361                                         xmlpp::Element* recipient = kdm_required_extensions->add_child("Recipient");
362                                         {
363                                                 xmlpp::Element* serial_element = recipient->add_child("X509IssuerSerial");
364                                                 serial_element->add_child("X509IssuerName", "ds")->add_child_text (
365                                                         Certificate::name_for_xml (recipient_cert->issuer())
366                                                         );
367                                                 serial_element->add_child("X509SerialNumber", "ds")->add_child_text (
368                                                         recipient_cert->serial()
369                                                         );
370                                         }
371
372                                         recipient->add_child("X509SubjectName")->add_child_text (Certificate::name_for_xml (recipient_cert->subject()));
373                                 }
374
375                                 kdm_required_extensions->add_child("CompositionPlaylistId")->add_child_text("urn:uuid:" + _uuid);
376                                 kdm_required_extensions->add_child("ContentTitleText")->add_child_text(_name);
377                                 kdm_required_extensions->add_child("ContentAuthenticator")->add_child_text(certificates.leaf()->thumbprint());
378                                 kdm_required_extensions->add_child("ContentKeysNotValidBefore")->add_child_text("XXX");
379                                 kdm_required_extensions->add_child("ContentKeysNotValidAfter")->add_child_text("XXX");
380
381                                 {
382                                         xmlpp::Element* authorized_device_info = kdm_required_extensions->add_child("AuthorizedDeviceInfo");
383                                         authorized_device_info->add_child("DeviceListIdentifier")->add_child_text("urn:uuid:" + make_uuid());
384                                         authorized_device_info->add_child("DeviceListDescription")->add_child_text(recipient_cert->subject());
385                                         {
386                                                 xmlpp::Element* device_list = authorized_device_info->add_child("DeviceList");
387                                                 device_list->add_child("CertificateThumbprint")->add_child_text(recipient_cert->thumbprint());
388                                         }
389                                 }
390
391                                 {
392                                         xmlpp::Element* key_id_list = kdm_required_extensions->add_child("KeyIdList");
393                                         list<shared_ptr<const Asset> > a = assets();
394                                         for (list<shared_ptr<const Asset> >::iterator i = a.begin(); i != a.end(); ++i) {
395                                                 /* XXX: non-MXF assets? */
396                                                 shared_ptr<const MXFAsset> mxf = boost::dynamic_pointer_cast<const MXFAsset> (*i);
397                                                 if (mxf) {
398                                                         mxf->add_typed_key_id (key_id_list);
399                                                 }
400                                         }
401                                 }
402
403                                 {
404                                         xmlpp::Element* forensic_mark_flag_list = kdm_required_extensions->add_child("ForensicMarkFlagList");
405                                         forensic_mark_flag_list->add_child("ForensicMarkFlag")->add_child_text ( 
406                                                 "http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-picture-disable"
407                                                 );
408                                         forensic_mark_flag_list->add_child("ForensicMarkFlag")->add_child_text ( 
409                                                 "http://www.smpte-ra.org/430-1/2006/KDM#mrkflg-audio-disable"
410                                                 );
411                                 }
412                         }
413                 }
414                                          
415                 authenticated_public->add_child("NonCriticalExtensions");
416         }
417
418         {
419                 xmlpp::Element* authenticated_private = root->add_child("AuthenticatedPrivate");
420                 authenticated_private->set_attribute ("Id", "ID_AuthenticatedPrivate");
421                 xmlAddID (0, doc->cobj(), (const xmlChar *) "ID_AuthenticatedPrivate", authenticated_private->get_attribute("Id")->cobj());
422                 {
423                         xmlpp::Element* encrypted_key = authenticated_private->add_child ("EncryptedKey", "enc");
424                         {
425                                 xmlpp::Element* encryption_method = encrypted_key->add_child ("EncryptionMethod", "enc");
426                                 encryption_method->set_attribute ("Algorithm", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p");
427                                 encryption_method->add_child("DigestMethod", "ds")->set_attribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
428                         }
429
430                         xmlpp::Element* cipher_data = authenticated_private->add_child ("CipherData", "enc");
431                         cipher_data->add_child("CipherValue", "enc")->add_child_text("XXX");
432                 }
433         }
434         
435         /* XXX: x2 one for each mxf? */
436
437         {
438                 xmlpp::Element* signature = root->add_child("Signature", "ds");
439                 
440                 {
441                         xmlpp::Element* signed_info = signature->add_child("SignedInfo", "ds");
442                         signed_info->add_child("CanonicalizationMethod", "ds")->set_attribute(
443                                 "Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"
444                                 );
445                         signed_info->add_child("SignatureMethod", "ds")->set_attribute(
446                                 "Algorithm", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"
447                                 );
448                         {
449                                 xmlpp::Element* reference = signed_info->add_child("Reference", "ds");
450                                 reference->set_attribute("URI", "#ID_AuthenticatedPublic");
451                                 reference->add_child("DigestMethod", "ds")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
452                                 reference->add_child("DigestValue", "ds");
453                         }
454                         
455                         {                               
456                                 xmlpp::Element* reference = signed_info->add_child("Reference", "ds");
457                                 reference->set_attribute("URI", "#ID_AuthenticatedPrivate");
458                                 reference->add_child("DigestMethod", "ds")->set_attribute("Algorithm", "http://www.w3.org/2001/04/xmlenc#sha256");
459                                 reference->add_child("DigestValue", "ds");
460                         }
461                 }
462                 
463                 add_signature_value (signature, certificates, signer_key, "ds");
464         }
465
466         return doc;
467 }