mp4decrypt 0.6.1

Decrypt CENC protected MP4 content using Bento4
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
//! This crate provides a safe high-level API to decrypt CENC/CENS/CBC1/CBCS protected MP4 content
//! using [Bento4](https://github.com/axiomatic-systems/Bento4).
//!
//! ## Environment Variables
//!
//! The following environment variables can be used to configure the Bento4 library location:
//!
//! | Variable | Description |
//! |----------|-------------|
//! | `BENTO4_DIR` | Directory of a Bento4 installation. Should contain `lib` and `include` subdirectories. |
//! | `BENTO4_VENDOR` | If set, always build and link against the vendored Bento4 version. |
//!
//! These variables can also be prefixed with the upper-cased target architecture
//! (e.g. `X86_64_UNKNOWN_LINUX_GNU_BENTO4_DIR`), which is useful for cross-compilation.
//!
//! ## Quick Start
//!
//! ```no_run
//! use mp4decrypt::Ap4CencDecryptingProcessor;
//! use std::{error::Error, fs, io::Write};
//!
//! fn main() -> Result<(), Box<dyn Error>> {
//!     // Create a processor with decryption keys
//!     let processor = Ap4CencDecryptingProcessor::new()
//!         .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
//!         .build()?;
//!
//!     // Decrypt in memory
//!     let init_data = fs::read("init.mp4")?;
//!     let segment_data = fs::read("segment.m4s")?;
//!     let decrypted = processor.decrypt(&segment_data, Some(&init_data))?;
//!
//!     // Write playable MP4 (init + decrypted segment)
//!     let mut f = fs::File::create("output.mp4")?;
//!     f.write_all(&init_data)?;
//!     f.write_all(&decrypted)?;
//!
//!     Ok(())
//! }
//! ```
//!
//! ## Multithreaded Decryption
//!
//! The processor is thread-safe and can be shared across multiple threads using `Arc`.
//! This is useful for decrypting multiple segments in parallel:
//!
//! ```no_run
//! use mp4decrypt::Ap4CencDecryptingProcessor;
//! use std::{fs, sync::Arc, thread};
//!
//! fn main() -> Result<(), mp4decrypt::Error> {
//!     // Create a shared processor
//!     let processor = Arc::new(
//!         Ap4CencDecryptingProcessor::new()
//!             .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
//!             .build()?
//!     );
//!
//!     let init_data = Arc::new(fs::read("init.mp4").unwrap());
//!
//!     // Spawn multiple threads to decrypt segments in parallel
//!     let handles: Vec<_> = (1..=10)
//!         .map(|i| {
//!             let processor = Arc::clone(&processor);
//!             let init = Arc::clone(&init_data);
//!
//!             thread::spawn(move || {
//!                 let segment = fs::read(format!("segment_{}.m4s", i)).unwrap();
//!                 let decrypted = processor.decrypt(&segment, Some(&*init)).unwrap();
//!
//!                 // Write playable MP4 (init + decrypted segment)
//!                 let mut f = fs::File::create(format!("decrypted_{}.mp4", i)).unwrap();
//!                 use std::io::Write;
//!                 f.write_all(&*init).unwrap();
//!                 f.write_all(&decrypted).unwrap();
//!             })
//!         })
//!         .collect();
//!
//!     // Wait for all threads to complete
//!     for handle in handles {
//!         handle.join().expect("Thread panicked");
//!     }
//!
//!     Ok(())
//! }
//! ```
//!
//! ## File-Based Decryption
//!
//! For large files or when you want to avoid loading everything into memory:
//!
//! ```no_run
//! use mp4decrypt::Ap4CencDecryptingProcessor;
//!
//! fn main() -> Result<(), mp4decrypt::Error> {
//!     let processor = Ap4CencDecryptingProcessor::new()
//!         .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
//!         .build()?;
//!
//!     // Decrypt directly from file to file
//!     processor.decrypt_file(
//!         "encrypted_segment.m4s",
//!         "decrypted_segment.m4s",
//!         Some("init.mp4"),
//!     )?;
//!
//!     Ok(())
//! }
//! ```

mod error;

pub use error::Error;

use core::ffi::{c_char, c_int, c_uchar, c_uint, c_void};
use std::{collections::HashMap, ffi::CString, path::Path, ptr, sync::Mutex};

static AP4_LOCK: Mutex<()> = Mutex::new(());

unsafe extern "C" {
    fn ap4_processor_new(keys: *const c_uchar, size: c_uint) -> *mut c_void;
    fn ap4_processor_free(ctx: *mut c_void);
    fn ap4_free(ptr: *mut c_uchar);
    fn ap4_decrypt_file(
        ctx: *mut c_void,
        input_path: *const c_char,
        output_path: *const c_char,
        init_path: *const c_char,
    ) -> c_int;
    fn ap4_decrypt_memory(
        ctx: *mut c_void,
        input_data: *const c_uchar,
        input_size: c_uint,
        init_data: *const c_uchar,
        init_size: c_uint,
        output_data: *mut *mut c_uchar,
        output_size: *mut c_uint,
    ) -> c_int;
}

/// A CENC (Common Encryption) decrypting processor for MP4 files.
///
/// This struct wraps the Bento4 `AP4_CencDecryptingProcessor` and provides
/// a safe Rust interface for decrypting CENC or CBCS encrypted MP4 content.
///
/// # Thread Safety
///
/// `Ap4CencDecryptingProcessor` implements both `Send` and `Sync`, meaning it can be
/// safely shared across threads using `Arc<Ap4CencDecryptingProcessor>`. Internally,
/// all decryption operations are synchronized using a mutex to ensure thread safety.
///
/// # Example
///
/// ```no_run
/// use mp4decrypt::Ap4CencDecryptingProcessor;
/// use std::{fs, sync::Arc, thread};
///
/// let processor = Arc::new(
///     Ap4CencDecryptingProcessor::new()
///         .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")
///         .unwrap()
///         .build()
///         .unwrap()
/// );
///
/// // Clone Arc for use in another thread
/// let processor_clone = Arc::clone(&processor);
/// let handle = thread::spawn(move || {
///     // Use processor_clone in this thread
/// });
/// ```
pub struct Ap4CencDecryptingProcessor {
    ptr: *mut c_void,
}

// SAFETY: The underlying Bento4 processor is protected by AP4_LOCK mutex,
// making all operations thread-safe.
unsafe impl Send for Ap4CencDecryptingProcessor {}
unsafe impl Sync for Ap4CencDecryptingProcessor {}

impl Ap4CencDecryptingProcessor {
    /// Creates a new builder for configuring the decryption processor.
    ///
    /// Use the builder to add one or more KID/key pairs, then call [`Ap4CencDecryptingProcessorBuilder::build`]
    /// to create the processor.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
    ///     .build()?;
    /// # Ok::<(), mp4decrypt::Error>(())
    /// ```
    #[allow(clippy::new_ret_no_self)]
    pub fn new() -> Ap4CencDecryptingProcessorBuilder {
        Ap4CencDecryptingProcessorBuilder::default()
    }

    /// Decrypts encrypted MP4 data in memory.
    ///
    /// This method takes encrypted segment data and an optional initialization segment,
    /// and returns the decrypted segment data. The init segment is passed separately
    /// to the decryption processor for parsing encryption metadata.
    ///
    /// # Arguments
    ///
    /// * `input_data` - The encrypted MP4 segment data (e.g., `.m4s` fragment)
    /// * `init_data` - Optional initialization segment data (e.g., `init.mp4`). Required
    ///   for fragmented MP4 streams to provide encryption metadata.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Vec<u8>)` containing the decrypted segment data on success, or an error if:
    /// - The input or init data exceeds 4GB ([`Error::DataTooLarge`])
    /// - Decryption fails ([`Error::DecryptionFailed`])
    ///
    /// # Note
    ///
    /// The returned data contains only the decrypted segment, **not** the init segment.
    /// To create a playable MP4 file, you must manually prepend the init segment.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    /// use std::{fs, io::Write};
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
    ///     .build()?;
    ///
    /// // With initialization segment
    /// let init = fs::read("video_init.mp4")?;
    /// let segment = fs::read("video_1.m4s")?;
    /// let decrypted = processor.decrypt(&segment, Some(&init))?;
    ///
    /// // Create playable MP4 by prepending init segment
    /// let mut f = fs::File::create("output.mp4")?;
    /// f.write_all(&init)?;
    /// f.write_all(&decrypted)?;
    ///
    /// // Without initialization segment (raw decrypted segment)
    /// let decrypted_raw = processor.decrypt(&segment, None::<&Vec<u8>>)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads
    /// when the processor is shared via `Arc`.
    pub fn decrypt<T: AsRef<[u8]>>(
        &self,
        input_data: T,
        init_data: Option<T>,
    ) -> Result<Vec<u8>, Error> {
        let input_ref = input_data.as_ref();
        let input_ptr = input_ref.as_ptr();
        let input_size = u32::try_from(input_ref.len()).map_err(|_| Error::DataTooLarge)?;

        let (init_ptr, init_size) = match &init_data {
            Some(init) => {
                let init_ref = init.as_ref();
                let size = u32::try_from(init_ref.len()).map_err(|_| Error::DataTooLarge)?;
                (init_ref.as_ptr(), size)
            }
            None => (ptr::null(), 0),
        };

        let mut output_ptr: *mut c_uchar = ptr::null_mut();
        let mut output_size: c_uint = 0;

        let result = {
            let _lock = AP4_LOCK.lock().unwrap();
            unsafe {
                ap4_decrypt_memory(
                    self.ptr,
                    input_ptr,
                    input_size,
                    init_ptr,
                    init_size,
                    &mut output_ptr,
                    &mut output_size,
                )
            }
        };

        if result == 0 {
            let decrypted = unsafe {
                let slice = std::slice::from_raw_parts(output_ptr, output_size as usize);
                let vec = slice.to_vec();
                ap4_free(output_ptr);
                vec
            };
            Ok(decrypted)
        } else {
            Err(Error::DecryptionFailed(result))
        }
    }

    /// Decrypts an encrypted MP4 file and writes the result to disk.
    ///
    /// This method is more memory-efficient than [`decrypt`](Self::decrypt) for large files
    /// as it streams data directly from disk rather than loading it all into memory.
    ///
    /// # Arguments
    ///
    /// * `input_path` - Path to the encrypted MP4 segment file (e.g., `segment.m4s`)
    /// * `output_path` - Path where the decrypted data will be written
    /// * `init_path` - Optional path to the initialization segment (e.g., `init.mp4`).
    ///   Required for proper decryption of fragmented MP4 files.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` on success, or an error if decryption fails.
    ///
    /// # Note
    ///
    /// Unlike [`decrypt`](Self::decrypt), this method does **not** combine the init and
    /// segment data in the output. If you need a playable MP4 file, you must manually
    /// concatenate the init segment with the decrypted output:
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    /// use std::fs;
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
    ///     .build()?;
    ///
    /// // Decrypt the segment
    /// processor.decrypt_file(
    ///     "encrypted_segment.m4s",
    ///     "decrypted_segment.m4s",
    ///     Some("init.mp4"),
    /// )?;
    ///
    /// // Create playable MP4 by concatenating init + decrypted segment
    /// let init = fs::read("init.mp4")?;
    /// let segment = fs::read("decrypted_segment.m4s")?;
    /// let mut playable = init;
    /// playable.extend(segment);
    /// fs::write("playable.mp4", playable)?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently from multiple threads
    /// when the processor is shared via `Arc`.
    pub fn decrypt_file<T: AsRef<Path>>(
        &self,
        input_path: T,
        output_path: T,
        init_path: Option<T>,
    ) -> Result<(), Error> {
        let input_cstr = CString::new(input_path.as_ref().to_string_lossy().as_bytes()).unwrap();
        let output_cstr = CString::new(output_path.as_ref().to_string_lossy().as_bytes()).unwrap();
        let init_cstr =
            init_path.map(|p| CString::new(p.as_ref().to_string_lossy().as_bytes()).unwrap());

        let init_ptr = init_cstr
            .as_ref()
            .map(|s| s.as_ptr())
            .unwrap_or(ptr::null());

        let result = {
            let _lock = AP4_LOCK.lock().unwrap();
            unsafe {
                ap4_decrypt_file(
                    self.ptr,
                    input_cstr.as_ptr(),
                    output_cstr.as_ptr(),
                    init_ptr,
                )
            }
        };

        if result == 0 {
            Ok(())
        } else {
            Err(Error::DecryptionFailed(result))
        }
    }
}

impl Drop for Ap4CencDecryptingProcessor {
    fn drop(&mut self) {
        let _lock = AP4_LOCK.lock().unwrap();
        unsafe { ap4_processor_free(self.ptr) }
    }
}

/// Builder for creating [`Ap4CencDecryptingProcessor`] instances.
///
/// Use this builder to configure decryption keys before creating the processor.
/// At least one KID/key pair must be provided.
///
/// # Example
///
/// ```no_run
/// use mp4decrypt::Ap4CencDecryptingProcessor;
/// use std::collections::HashMap;
///
/// // Add keys one at a time
/// let processor = Ap4CencDecryptingProcessor::new()
///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
///     .key("63cb5f7184dd4b689a5c5ff11ee6a328", "3bda3329158a4789880816a70e7e436d")?
///     .build()?;
///
/// // Or add multiple keys from a HashMap
/// let mut keys = HashMap::new();
/// keys.insert(
///     "eb676abbcb345e96bbcf616630f1a3da".to_string(),
///     "100b6c20940f779a4589152b57d2dacb".to_string(),
/// );
/// let processor = Ap4CencDecryptingProcessor::new()
///     .keys(&keys)?
///     .build()?;
/// # Ok::<(), mp4decrypt::Error>(())
/// ```
#[derive(Default)]
pub struct Ap4CencDecryptingProcessorBuilder {
    keys: HashMap<[u8; 16], [u8; 16]>,
}

impl Ap4CencDecryptingProcessorBuilder {
    /// Adds a single KID/key pair for decryption.
    ///
    /// # Arguments
    ///
    /// * `kid` - The Key ID as a 32-character hexadecimal string (16 bytes)
    /// * `key` - The decryption key as a 32-character hexadecimal string (16 bytes)
    ///
    /// # Returns
    ///
    /// Returns `Ok(Self)` for method chaining, or an error if:
    /// - The hex string is invalid ([`Error::HexDecode`])
    /// - The hex string doesn't represent exactly 16 bytes ([`Error::InvalidHex`])
    ///
    /// # Example
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
    ///     .build()?;
    /// # Ok::<(), mp4decrypt::Error>(())
    /// ```
    pub fn key(mut self, kid: &str, key: &str) -> Result<Self, Error> {
        self.keys.insert(verify_hex(kid)?, verify_hex(key)?);
        Ok(self)
    }

    /// Adds multiple KID/key pairs from a HashMap.
    ///
    /// This is a convenience method for adding multiple keys at once,
    /// useful when keys are loaded from configuration files or external sources.
    ///
    /// # Arguments
    ///
    /// * `keys` - A HashMap where keys are KIDs and values are decryption keys,
    ///   both as 32-character hexadecimal strings
    ///
    /// # Returns
    ///
    /// Returns `Ok(Self)` for method chaining, or an error if any hex string is invalid.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    /// use std::collections::HashMap;
    ///
    /// let mut keys = HashMap::new();
    /// keys.insert(
    ///     "eb676abbcb345e96bbcf616630f1a3da".to_string(),
    ///     "100b6c20940f779a4589152b57d2dacb".to_string(),
    /// );
    /// keys.insert(
    ///     "63cb5f7184dd4b689a5c5ff11ee6a328".to_string(),
    ///     "3bda3329158a4789880816a70e7e436d".to_string(),
    /// );
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .keys(&keys)?
    ///     .build()?;
    /// # Ok::<(), mp4decrypt::Error>(())
    /// ```
    pub fn keys(mut self, keys: &HashMap<String, String>) -> Result<Self, Error> {
        for (kid, key) in keys {
            self.keys.insert(verify_hex(kid)?, verify_hex(key)?);
        }
        Ok(self)
    }

    /// Builds the [`Ap4CencDecryptingProcessor`] with the configured keys.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Ap4CencDecryptingProcessor)` on success, or [`Error::NoKeys`]
    /// if no keys were provided.
    ///
    /// # Example
    ///
    /// ```no_run
    /// use mp4decrypt::Ap4CencDecryptingProcessor;
    ///
    /// let processor = Ap4CencDecryptingProcessor::new()
    ///     .key("eb676abbcb345e96bbcf616630f1a3da", "100b6c20940f779a4589152b57d2dacb")?
    ///     .build()?;
    /// # Ok::<(), mp4decrypt::Error>(())
    /// ```
    pub fn build(self) -> Result<Ap4CencDecryptingProcessor, Error> {
        if self.keys.is_empty() {
            return Err(Error::NoKeys);
        }

        let size = self.keys.len();
        let mut buffer = Vec::with_capacity(size * 32);

        for (kid, key) in &self.keys {
            buffer.extend_from_slice(kid);
            buffer.extend_from_slice(key);
        }

        let ptr = {
            let _lock = AP4_LOCK.lock().unwrap();
            unsafe { ap4_processor_new(buffer.as_ptr(), size as c_uint) }
        };

        Ok(Ap4CencDecryptingProcessor { ptr })
    }
}

fn verify_hex(input: &str) -> Result<[u8; 16], Error> {
    let bytes = hex::decode(input)?;

    if bytes.len() != 16 {
        return Err(Error::InvalidHex {
            input: input.to_owned(),
            message: format!("expected 16 bytes got {} bytes", bytes.len()),
        });
    }

    let mut data = [0u8; 16];
    data.copy_from_slice(&bytes);
    Ok(data)
}