Categories
C Perl XS

If you program in Perl and learn XS is like you have super powers.

Perl has a big amount of modules available, but sometimes you need a library from C, in my case that library was Duktape to embed a JS interpreter in my application to be able to use a scrapped function from the Youtube video player to implement download videos with obfuscated signatures in Peertube-dl.

XS allows you to embed C libraries in Perl, this opens the door to many applications from writting programs using GTK to fast a critical in performance subroutine, tons of CPAN modules use it to extend the Perl’s capabilities.

The main resources to learn XS are: https://perldoc.perl.org/perlxs and https://perldoc.perl.org/perlguts.

This is how a very basic XS Perl module look:

#define PERL_NO_GET_CONTEXT
#include "EXTERN.h"
#include "perl.h"
#include "XSUB.h"
#include "duktape.h"
#include "duk_config.h"
#include "javascript_builtins.h"

MODULE = Peertube::DL::Javascript  PACKAGE = Peertube::DL::Javascript
PROTOTYPES: ENABLE

SV *
_duk_create_heap_default()
    CODE:
        duk_context *context = duk_create_heap_default();
        if (context) {
            duk_push_c_function(context, js_builtin_print, 1);
            duk_put_global_string(context, "print");
            RETVAL = newSVuv((size_t)context);
        } else {
            RETVAL = &PL_sv_undef;
        }
    OUTPUT:
        RETVAL

This is how the loader Perl module would look:

package Peertube::DL::Javascript;

use strict;
use warnings;

use feature 'say';

use XSLoader;
use Data::Dumper;

XSLoader::load();

sub new {
    my $class = shift;
    my $self  = bless {}, $class;
    $self->{___ContextPrivateDONOTTOUCH} =
      Peertube::DL::Javascript::_duk_create_heap_default();
    return $self;
}

You can check for a complete example on the source of Peertube-dl: https://gitea.sergiotarxz.freemyip.com/sergiotarxz/Peertube-dl

Categories
C Docker Javascript Peertube-dl Perl XS

What is Peertube-dl?

Peertube-dl aims to be a alternative to youtube-dl written in Perl providing a library, a cli utility and a webpage.

I am currently developing that project, I licensed it under the AGPLv3, a Free Software license.

It provides a Dockerfile which allows you to run the program in a container.

I hope you find it useful, beware it is provided to you without any warranty, but I will be happy to help you with any issues you find on https://gitea.sergiotarxz.freemyip.com/sergiotarxz/Peertube-dl/issues