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