libytdlp 0.3.0

Safe Rust wrapper around the libytdlp C ABI
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
use std::future::Future;
use std::pin::Pin;
use std::ptr;
use std::sync::Arc;
use std::sync::Mutex;
use std::task::Context;
use std::task::Poll;
use std::task::Waker;

use libytdlp_sys as sys;

use crate::error::Error;
use crate::error::Kind;
use crate::job::DownloadJob;
use crate::media::MediaInfo;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlayerClient {
    Default,
    Android,
    TvEmbedded,
    Ios,
    Web,
}

impl PlayerClient {
    pub const RETRY_ORDER: [PlayerClient; 5] = [
        PlayerClient::Default,
        PlayerClient::Android,
        PlayerClient::TvEmbedded,
        PlayerClient::Ios,
        PlayerClient::Web,
    ];

    pub fn as_str(self) -> &'static str {
        match self {
            Self::Default => "default",
            Self::Android => "android",
            Self::TvEmbedded => "web_embedded",
            Self::Ios => "ios",
            Self::Web => "web",
        }
    }
}

pub fn player_client_options<I>(clients: I) -> Vec<String>
where
    I: IntoIterator<Item = PlayerClient>,
{
    clients
        .into_iter()
        .map(|client| {
            if client == PlayerClient::Default {
                return "{}".to_owned();
            }

            serde_json::json!({
                "extractor_args": {
                    "youtube": {
                        "player_client": [client.as_str()],
                    },
                },
            })
            .to_string()
        })
        .collect()
}

pub struct Client {
    raw: *mut sys::LyContext,
    options: String,
}

pub struct ClientBuilder {
    options: serde_json::Map<String, serde_json::Value>,
}

impl ClientBuilder {
    pub fn new() -> Self {
        Self {
            options: serde_json::Map::new(),
        }
    }

    pub fn options_json(mut self, options: &str) -> Result<Self, Error> {
        let parsed: serde_json::Value = serde_json::from_str(options)
            .map_err(|failed| Error::new(Kind::InvalidArgument, failed.to_string()))?;

        let object = parsed
            .as_object()
            .ok_or_else(|| Error::new(Kind::InvalidArgument, "options must be a JSON object"))?;

        for (key, value) in object {
            self.options.insert(key.clone(), value.clone());
        }

        Ok(self)
    }

    pub fn option(mut self, key: &str, value: serde_json::Value) -> Self {
        self.options.insert(key.to_owned(), value);

        self
    }

    pub fn extractor_args(mut self, plugin: &str, args: serde_json::Value) -> Self {
        let slot = self
            .options
            .entry("extractor_args")
            .or_insert_with(|| serde_json::Value::Object(serde_json::Map::new()));

        if !slot.is_object() {
            *slot = serde_json::Value::Object(serde_json::Map::new());
        }

        if let Some(table) = slot.as_object_mut() {
            table.insert(plugin.to_owned(), args);
        }

        self
    }

    pub fn youtube_player_client(self, client: PlayerClient) -> Self {
        if client == PlayerClient::Default {
            return self;
        }

        self.extractor_args(
            "youtube",
            serde_json::json!({"player_client": [client.as_str()]}),
        )
    }

    pub fn build(self) -> Result<Client, Error> {
        let text = serde_json::to_string(&serde_json::Value::Object(self.options))
            .map_err(|failed| Error::new(Kind::Internal, failed.to_string()))?;

        Client::new(&text)
    }
}

impl Default for ClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl Client {
    pub fn new(options_json: &str) -> Result<Self, Error> {
        crate::runtime::ensure_compatible_abi()?;

        let mut context: *mut sys::LyContext = ptr::null_mut();
        let mut error: *mut sys::LyError = ptr::null_mut();

        let status = unsafe {
            sys::ly_context_create(
                options_json.as_ptr().cast(),
                options_json.len(),
                &mut context,
                &mut error,
            )
        };

        if status != sys::LY_OK || context.is_null() {
            return Err(Error::from_ptr(error));
        }

        Ok(Self {
            raw: context,
            options: options_json.to_owned(),
        })
    }

    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    #[tracing::instrument(name = "libytdlp.extract", level = "debug", skip(self, url))]
    pub fn extract(&self, url: &str) -> Result<MediaInfo, Error> {
        if url.as_bytes().contains(&0) {
            return Err(Error::new(
                Kind::InvalidArgument,
                "url must not contain NUL bytes",
            ));
        }

        let mut result: *mut sys::LyResult = ptr::null_mut();
        let mut error: *mut sys::LyError = ptr::null_mut();

        let status = unsafe {
            sys::ly_extract(
                self.raw,
                url.as_ptr().cast(),
                url.len(),
                ptr::null(),
                0,
                &mut result,
                &mut error,
            )
        };

        if status != sys::LY_OK || result.is_null() {
            return Err(Error::from_ptr(error));
        }

        MediaInfo::from_raw(result)
    }

    #[tracing::instrument(name = "libytdlp.extract", level = "debug", skip(self, url, options))]
    pub fn extract_with_options(&self, url: &str, options: &str) -> Result<MediaInfo, Error> {
        if url.as_bytes().contains(&0) {
            return Err(Error::new(
                Kind::InvalidArgument,
                "url must not contain NUL bytes",
            ));
        }

        if options.as_bytes().contains(&0) {
            return Err(Error::new(
                Kind::InvalidArgument,
                "options must not contain NUL bytes",
            ));
        }

        let (options_ptr, options_len) = if options.is_empty() {
            (ptr::null(), 0)
        } else {
            (options.as_ptr().cast(), options.len())
        };

        let mut result: *mut sys::LyResult = ptr::null_mut();
        let mut error: *mut sys::LyError = ptr::null_mut();

        let status = unsafe {
            sys::ly_extract(
                self.raw,
                url.as_ptr().cast(),
                url.len(),
                options_ptr,
                options_len,
                &mut result,
                &mut error,
            )
        };

        if status != sys::LY_OK || result.is_null() {
            return Err(Error::from_ptr(error));
        }

        MediaInfo::from_raw(result)
    }

    #[tracing::instrument(name = "libytdlp.extract", level = "debug", skip(self, url, options))]
    pub fn extract_first(&self, url: &str, options: Vec<String>) -> Result<MediaInfo, Error> {
        if options.is_empty() {
            return Err(Error::new(Kind::InvalidArgument, "no retry options"));
        }

        let mut last: Option<Error> = None;

        for entry in &options {
            match self.extract_with_options(url, entry) {
                Ok(found) => return Ok(found),
                Err(failed) => last = Some(failed),
            }
        }

        Err(last.expect("non-empty options must leave an error"))
    }

    #[tracing::instrument(name = "libytdlp.search", level = "debug", skip(self, query))]
    pub fn search_flat(&self, query: &str, limit: u32) -> Result<MediaInfo, Error> {
        let target = format!("ytsearch{limit}:{query}");

        self.extract_with_options(&target, r#"{"flat_playlist": true}"#)
    }

    #[tracing::instrument(name = "libytdlp.extract_async", level = "debug", skip(self, url))]
    pub fn extract_async(&self, url: String) -> WaitForExtract {
        WaitForExtract {
            pending: Some((url, self.options.clone())),
            shared: Arc::new(Shared {
                waker: Mutex::new(None),
                outcome: Mutex::new(None),
            }),
        }
    }

    #[tracing::instrument(name = "libytdlp.download", level = "debug", skip(self, url, options))]
    pub fn download(&self, url: &str, options: &str) -> Result<DownloadJob, Error> {
        if url.as_bytes().contains(&0) {
            return Err(Error::new(
                Kind::InvalidArgument,
                "url must not contain NUL bytes",
            ));
        }

        if options.as_bytes().contains(&0) {
            return Err(Error::new(
                Kind::InvalidArgument,
                "options must not contain NUL bytes",
            ));
        }

        let mut job: *mut sys::LyJob = ptr::null_mut();
        let mut error: *mut sys::LyError = ptr::null_mut();

        let status = unsafe {
            sys::ly_download_start(
                self.raw,
                url.as_ptr().cast(),
                url.len(),
                options.as_ptr().cast(),
                options.len(),
                &mut job,
                &mut error,
            )
        };

        if status != sys::LY_OK || job.is_null() {
            return Err(Error::from_ptr(error));
        }

        Ok(DownloadJob::from_raw(job))
    }
}

impl Drop for Client {
    fn drop(&mut self) {
        unsafe {
            sys::ly_context_release(self.raw);
        }
    }
}

unsafe impl Send for Client {}

unsafe impl Sync for Client {}

struct Shared {
    waker: Mutex<Option<Waker>>,
    outcome: Mutex<Option<Result<MediaInfo, Error>>>,
}

pub struct WaitForExtract {
    pending: Option<(String, String)>,
    shared: Arc<Shared>,
}

impl Future for WaitForExtract {
    type Output = Result<MediaInfo, Error>;

    fn poll(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Self::Output> {
        if let Some(outcome) = self.shared.outcome.lock().expect("outcome lock").take() {
            return Poll::Ready(outcome);
        }

        *self.shared.waker.lock().expect("waker lock") = Some(context.waker().clone());

        if let Some(outcome) = self.shared.outcome.lock().expect("outcome lock").take() {
            return Poll::Ready(outcome);
        }

        let Some((url, options)) = self.pending.take() else {
            return Poll::Pending;
        };

        let shared = Arc::clone(&self.shared);

        std::thread::spawn(move || {
            let outcome = isolated_extract(url, options);

            *shared.outcome.lock().expect("outcome lock") = Some(outcome);

            let waker = shared.waker.lock().expect("waker lock").take();

            if let Some(waker) = waker {
                waker.wake();
            }
        });

        Poll::Pending
    }
}

fn isolated_extract(url: String, options: String) -> Result<MediaInfo, Error> {
    crate::runtime::ensure_compatible_abi()?;

    let mut context: *mut sys::LyContext = ptr::null_mut();
    let mut error: *mut sys::LyError = ptr::null_mut();

    let status = unsafe {
        sys::ly_context_create(
            options.as_ptr().cast(),
            options.len(),
            &mut context,
            &mut error,
        )
    };

    if status != sys::LY_OK || context.is_null() {
        return Err(Error::from_ptr(error));
    }

    let client = Client {
        raw: context,
        options,
    };

    client.extract(&url)
}