<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Romain Beauxis on Medium]]></title>
        <description><![CDATA[Stories by Romain Beauxis on Medium]]></description>
        <link>https://medium.com/@romain.beauxis?source=rss-22dd29e3fc87------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qohQK8zqY9zkKoi8JmHiLw.jpeg</url>
            <title>Stories by Romain Beauxis on Medium</title>
            <link>https://medium.com/@romain.beauxis?source=rss-22dd29e3fc87------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 02:47:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@romain.beauxis/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Simple restream clone using liquidsoap]]></title>
            <link>https://medium.com/@romain.beauxis/simple-restream-clone-using-liquidsoap-be5f595fdd54?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/be5f595fdd54</guid>
            <category><![CDATA[live-streaming]]></category>
            <category><![CDATA[obs]]></category>
            <category><![CDATA[ffmpeg]]></category>
            <category><![CDATA[restream]]></category>
            <category><![CDATA[liquid-soap]]></category>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 16:52:49 GMT</pubDate>
            <atom:updated>2022-03-23T17:03:32.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R9BNoS98o0xiOjyVekd52Q.jpeg" /></figure><p>There’s been a lot of progress with the 2.0.x release cycle of <a href="https://www.liquidsoap.info/doc.html">liquidsoap</a>. One of the most exciting one being the possibility to stream already encoded streams, a long awaited user feature.</p><p>Also exciting are some improvements to the <a href="https://www.liquidsoap.info/doc-2.0.3/language.html">scripting language</a> that brings it to the level of a fully featured programming language and has made writing liquidsoap code much easier and natural.</p><p>The 2.0.x branch is still going through bug fixing iterations to stabilize all these new features. With the fixes pending from the upcoming 2.0.4 release, it will be possible to write a simple restream clone with just just a few lines of code.</p><p>Using this script, one can dynamically add or remove copies of an encoded media stream to send to different remote URLs, for instance Facebook live/Youtube live/etc..</p><p>It is written using the telnet command interface, for conciseness but liquidsoap also offers <a href="https://www.liquidsoap.info/doc-2.0.3/harbor_http.html">HTTP server functionalities</a> which make it possible to control the dynamic outputs using HTTP REST calls.</p><p>Here’s the code:</p><pre># Allow the script to start with no output<br>settings.init.force_start.set(true)<br>settings.server.telnet.set(true)</pre><pre># Replace the path here with a path to some video files:<br>s = playlist(&quot;/path/to/files&quot;)</pre><pre>streams = ref([])<br>count = ref(0)</pre><pre>encoder = %ffmpeg(<br>  format=&quot;flv&quot;,<br>  %audio.copy,<br>  %video.copy<br>)</pre><pre>def create_stream(url) =<br>  if list.assoc.mem(url, !streams) then<br>    &quot;Stream for url #{url} already exists!&quot;<br>  else<br>    out = output.url(https://medium.com/%3Cbr%3E%20%20%20%20%20%20id=&quot;restream-#{!count}&quot;,%3Cbr%3E%20%20%20%20%20%20fallible=true,%3Cbr%3E%20%20%20%20%20%20url=url,%3Cbr%3E%20%20%20%20%20%20encoder,%3Cbr%3E%20%20%20%20%20%20s)<br>    count := !count + 1<br>    streams := [...!streams, (url, out.shutdown)]<br>    &quot;OK!&quot;<br>  end<br>end</pre><pre>def delete_stream(url) =<br>  if not list.assoc.mem(url, !streams) then<br>    &quot;Stream for url #{url} does not exists!&quot;<br>  else<br>    shutdown = list.assoc(url, !streams)<br>    shutdown()<br>    streams := list.filter((fun (el) -&gt; fst(el) != url), !streams)<br>    &quot;OK!&quot;<br>  end<br>end</pre><pre>server.register(namespace=&quot;restream&quot;,<br>                description=&quot;Redirect a stream.&quot;,<br>                usage=&quot;start &lt;url&gt;&quot;,<br>                &quot;start&quot;,<br>                create_stream)<br>server.register(namespace=&quot;restream&quot;,<br>                description=&quot;Stop a dynamic playlist.&quot;,<br>                usage=&quot;stop &lt;url&gt;&quot;,<br>                &quot;stop&quot;,<br>                delete_stream)</pre><p>After running this script, you should have two new commands via telnet:</p><pre>% telnet localhost 1234<br>Trying ::1...<br>telnet: connect to address ::1: Connection refused<br>Trying 127.0.0.1...<br>Connected to localhost.<br>Escape character is &#39;^]&#39;.<br>help<br>Available commands:<br>...<br>| restream.start &lt;url&gt;<br>| restream.stop &lt;url&gt;<br>...</pre><pre>Type &quot;help &lt;command&gt;&quot; for more information.<br>END</pre><p>You can then use these commands to create and delete new dynamic restream :</p><pre>restream.start rtmps://live-api-s.facebook.com:443/rtmp/&lt;key&gt;<br>OK!<br>END<br>restream.start rtmp://a.rtmp.youtube.com/live2/&lt;key&gt;<br>OK!<br>END<br>restream.stop rtmps://live-api-s.facebook.com:443/rtmp/&lt;key&gt;<br>OK!<br>END<br>restream.stop rtmp://a.rtmp.youtube.com/live2/&lt;key&gt;<br>OK!<br>END<br>...</pre><p>If you are curious and want to learn more, we recommend checking out the <a href="https://www.liquidsoap.info/doc-dev/book.html">Liquidsoap Book</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be5f595fdd54" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced C binding using ocaml-ctypes and dune]]></title>
            <link>https://medium.com/@romain.beauxis/advanced-c-binding-using-ocaml-ctypes-and-dune-cc3f4cbab302?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc3f4cbab302</guid>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Sun, 01 Dec 2019 18:00:02 GMT</pubDate>
            <atom:updated>2019-12-02T21:52:22.222Z</atom:updated>
            <content:encoded><![CDATA[<p>I was working on a OCaml binding for <a href="https://github.com/Haivision/srt">libsrt</a> last summer, to add support for SRT real-time input and output to <a href="https://github.com/savonet/liquidsoap">liquidsoap</a>, and came across the need to access the <a href="https://pubs.opengroup.org/onlinepubs/7908799/xns/syssocket.h.html">sys/socket.h</a> C API.</p><p>I had already decided to use the very elegant <a href="https://github.com/ocamllabs/ocaml-ctypes">ocaml-ctypes</a> module for the SRT binding so I went with it and created a <a href="https://github.com/toots/ocaml-sys-socket">ocaml-sys-socket</a> module using it as well. It was a very interesting experience that I would like to describe here!</p><h3>ocaml-ctypes</h3><p>The idea behind OCaml ctypes is to create a binding against a C library without having to write C code, or as least as possible. The most straight-forward way of using it is via <a href="https://github.com/libffi/libffi">libffi</a> , providing access to dynamically-loaded libraries.</p><p>The second way of using it is by letting the module generate the basic C stubs required to build and link against a shared library. This is the mode that we’re going to use here. In this mode, the programmer has to describe the C headers of the library they intent to bind to using dedicated OCaml modules, operators and types. From that description, ocaml-ctypes is able to generate the required glue for the binding.</p><p>One advantage of using ocaml-ctypes is that the created bindings make as few assumptions as possible about the <a href="https://caml.inria.fr/pub/docs/manual-ocaml/intfc.html">OCaml C interfacing API</a>. This is pretty nice, in particular since the <a href="https://github.com/ocaml/ocaml">OCaml compiler</a> is moving pretty quickly these days (which is awesome!) and also if, perhaps one day, <a href="https://github.com/ocaml-multicore/ocaml-multicore">support for multi-core</a> is added to the compiler, which will undoubtedly change the C interface API quite a bit.</p><h3>dune</h3><p><a href="https://github.com/ocaml/dune">dune</a> (formally jbuilder ) is a build system for OCaml projects that has recently raised to much popularity, particularly due to its tight integration with the rest of the OCaml ecosystem, such as <a href="http://projects.camlcity.org/projects/findlib.html">ocamlfind</a> and <a href="https://opam.ocaml.org/">opam</a> .</p><p>My personal motto in programming in general is that <em>“Simple things should be simple, but complex things should be possible”</em>. dune certainly does not fit into that category but, rather, makes some complex things extremely easy to setup. It’s the kind of tool that will make your life incredibly easier when what you intent to do fits well within their workflow but might not be easy to bend to some very specific niche use. We will see one such case below.</p><p>At any rate, it’s been an amazing experience getting to learn how to use dune and the resulting code and build system is remarkably short and elegant, yet very powerful.</p><h3>socket.h</h3><p>socket.h is the Unix header that describes the C API to various socket operations, IP version 4 and 6 as well as unix file sockets. There is also a windows API mimicking it, which makes most code using it easily portable to windows.</p><p>Most network-based C libraries refer to socket.h to describe the type of socket that can be used with their API so it’s an important entry point for a lot of network operations and one that would be nice to support as generically as possible in OCaml.</p><p>The catch, though, is that, most likely for historical reasons¹, the <a href="https://pubs.opengroup.org/onlinepubs/7908799/xns/syssocket.h.html">POSIX specifications</a> only <em>partially</em> defines some of the required data structures and types, which makes it possible to write C code using them but does not give enough information to write C bindings without having to use the compiler to parse the actual system-specific headers of the running host.</p><p>For instance, here’s how the sockaddr structure is specified:</p><pre>The <em>&lt;sys/socket.h&gt;</em> header defines the <strong>sockaddr</strong> structure that includes at least the following members:</pre><pre>sa_family_t   sa_family       address family<br>char          sa_data[]       socket address (variable-length data)</pre><p>Likewise, here’s what is specified about the size of the socklen_t data type:</p><pre><em>&lt;sys/socket.h&gt;</em> makes available a type, <strong>socklen_t</strong>, which is an unsigned opaque integral type of length of at least 32 bits.</pre><p>Thus, in order to know the exact offset of sa_family inside the sockaddr structure or the actual size of a socklen_t integer, one has to include the OS-specific header, parse its definitions for that specific OS and, only then, is it possible to compute that offset or data size. Let’s see how it’s done in our binding now!</p><h3>Putting it together</h3><p>The C binding requires 4 separate passes:</p><ul><li>The <a href="https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/constants">constants</a> pass, which computes and exports some specific constant and data sizes, computed from the C headers</li><li>The <a href="https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/types">types</a> pass, which, given the system-specific constants and sizes exported in the previous phase, defines the actual C data structure bindings.</li><li>The <a href="https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/stubs">stubs</a> pass, where we define the actual bindings to the C functions that we wish to export in our API.</li><li>Finally, the <a href="https://github.com/toots/ocaml-sys-socket/blob/master/src/sys-socket/sys_socket.mli">last pass</a> does a cleanup of the stubs pass to export a relevant and OCaml- (and ocaml-ctypes) specific public API that is to be used by users of the module.</li></ul><p>dune makes each of these steps fairly easy to integrate into the next one, defining compilation elements and binaries to build before moving to the next pass.</p><h4>Constants pass</h4><p>During that pass, we compute and export all required C values defined in the headers. We also add our own constants, which give us the sizes that the POSIX specifications leave up to the OS. Here’s the OCaml code for it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93e5a4db0a5fdc9e9b0529b9f36e9aa/href">https://medium.com/media/f93e5a4db0a5fdc9e9b0529b9f36e9aa/href</a></iframe><p>Pretty straightforward! Some of these constants are defined by the POSIX headers and some are custom defined for our needs, for instance SOCKLEN_T_LEN . Here’s how they are extracted, using the dune build configuration for <a href="https://github.com/toots/ocaml-sys-socket/blob/master/src/sys-socket/generator/gen_constants_c.ml">gen_constants_c</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/820b311caee77876263869f6367992b2/href">https://medium.com/media/820b311caee77876263869f6367992b2/href</a></iframe><p>This OCaml code makes use of ocaml-ctypes to build a binary that exports the OCaml interface defined by Sys_socket_constants.Def . Once compiled, its output looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a662d280e9aebd876c9599f0ce2cf9f/href">https://medium.com/media/5a662d280e9aebd876c9599f0ce2cf9f/href</a></iframe><p>The files used to describe how to build this binary using dune are located in a separate <a href="https://github.com/toots/ocaml-sys-socket/tree/master/src/sys-socket/generator">generator</a> directory. Here’s the entry to build this one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d872ba80c21c5e4b2c9341731f4f858/href">https://medium.com/media/9d872ba80c21c5e4b2c9341731f4f858/href</a></iframe><p>This executable is compiled during the next phase. Let’s move into it now!</p><h4>Types pass</h4><p>During that phase, we use the constants exported during the previous phase to describe the various C structures and types. This is by far the most complex part of the code, making use of first-class modules and several OCaml tricks.</p><p>First, let’s look at how we tell dune that we need to generate the .ml file exporting our required constants from the previous pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/04aa1d692502cc14238ae1f56d117391/href">https://medium.com/media/04aa1d692502cc14238ae1f56d117391/href</a></iframe><p>With only this information, if the code refers to a Sys_socket_generated_constants module, dune will know that this module needs to be generated and how to do it. We will explain later the use of the exec.sh wrapper here.</p><p>Now that we can make use of the exported constants in our OCaml code, let’s see how we define the Socklen module, exporting abstract types and interface to use socklen_t integers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3023e7f6822cd259e8905ec68415ecf0/href">https://medium.com/media/3023e7f6822cd259e8905ec68415ecf0/href</a></iframe><p>As you can see, we make use of first-order modules and the size of the socklen_t integer to define the right API for the compiling host. Now let’s see how we define the sockaddr interface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cb2f09a505c1c2fee5dee2209684fc7/href">https://medium.com/media/8cb2f09a505c1c2fee5dee2209684fc7/href</a></iframe><p>Here, too, we make use of the size of sa_family as exported previously to define the right structure fields.</p><p>Next step, we need to compile this interface again to export the right offset for the various structures that have been defined. That’s dune’s job again!</p><p>First, the generator code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc51bcafc8f131beca3c2bede690edd2/href">https://medium.com/media/cc51bcafc8f131beca3c2bede690edd2/href</a></iframe><p>And the build instructions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e0574a7908995f9a54391691108cfda/href">https://medium.com/media/5e0574a7908995f9a54391691108cfda/href</a></iframe><p>Once, compiled, the exported .ml looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0780b7d8aaff315f583707980cec7490/href">https://medium.com/media/0780b7d8aaff315f583707980cec7490/href</a></iframe><p>As you can see, this exports all the offsets required to access the fields inside a sockaddr_t structure. We’re now ready to move to the final stage, which is the actual binding stubs!</p><h4>Binding stubs</h4><p>First step in this pass, just like with the previous ones, we need to configure dune to be able to build the exported .ml code from the types pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc8760c8cfb5b955f22eb5e188ac0a5d/href">https://medium.com/media/bc8760c8cfb5b955f22eb5e188ac0a5d/href</a></iframe><p>And we can now define the proper bindings. Here’s how it looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb0f17dc204f634153bf0fb8c6816859/href">https://medium.com/media/fb0f17dc204f634153bf0fb8c6816859/href</a></iframe><p>As you can see, we’re exporting the getnameinfo function, taking various arguments, including a pointer to a sockaddr_t structure and a couple of socklen_t integers, making use of all the various data types and structures previously defined. The exact specifications of this function can be found <a href="https://pubs.opengroup.org/onlinepubs/009695399/functions/getnameinfo.html">here</a>. We can now define out top-level API..</p><h4>Final API</h4><p>Building upon the previous modules, we export various OCaml idiomatic APIs that the binding user can now use to build new bindings against the socket.h APIs.</p><p>Just like with the previous steps, first we need to configure the build system:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48dd341c55a26b2530aa7245d575ab73/href">https://medium.com/media/48dd341c55a26b2530aa7245d575ab73/href</a></iframe><p>This time, we need ocaml-ctypes to generate two compilation units: a .ml file describing the API exported during the stubs phase, as well as the C code to glue it with the C APIs. Here’s the code for that generator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f202ff452486b5fdbe6e3bdc8f337d2c/href">https://medium.com/media/f202ff452486b5fdbe6e3bdc8f337d2c/href</a></iframe><p>The exported .ml and .c files are omitted here for simplicity but the reader can generated them themselves from the <a href="https://github.com/toots/ocaml-sys-socket">ocaml-sys-socket</a> repository if they are curious about their actual content.</p><p>We can now export our top-level API:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39ab0bfac9bf11bb2e8e1365d7860265/href">https://medium.com/media/39ab0bfac9bf11bb2e8e1365d7860265/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5162d72e0c611b9135738af602f6f2/href">https://medium.com/media/cd5162d72e0c611b9135738af602f6f2/href</a></iframe><p>That’s it! We now have ocaml-ctypes specific data types and structures that can be used to interface with the host’s native socket.h APIs. Note that we also worked on top of the original low-level binding to getnameinfo to export a higher-level function more idiomatic to the OCaml language.</p><h3>Lagniappe: cross-compilation to Windows</h3><p>On windows platforms, liquidsoap is compiled using <a href="https://github.com/ocaml-cross/opam-cross-windows">ocaml-cross-windows</a> and, since windows does have compatible socket APIs, we wanted to also look at cross-compiling for the windows target, which is where we hit a snag on the current dune support.</p><p>The problem is that, at each intermediary steps, in the case of a cross-compilation, the compiled binaries need to use the target’s OS headers and not the host’s headers, otherwise we end up using offsets specific to e.g. Debian but for a windows binary.</p><p>In this case, this means that the compiled .exe binaries need to be windows binaries and that we need to execute them as windows native binaries, using <a href="https://www.winehq.org/">wine</a> .</p><p>dune has a truly amazing <a href="https://dune.readthedocs.io/en/latest/cross-compilation.html">support for cross-compiling</a>, which we do not cover here, but, unfortunately, its primitives for building and executing binaries do not yet cover this use case. Thus we had to trick it into compiling things the way we wanted to do, which why we are using the exec.sh wrapper. Here’s its code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91773dfb31167aa4b0f64620388e32de/href">https://medium.com/media/91773dfb31167aa4b0f64620388e32de/href</a></iframe><p>Now, you can go back to the previous dune files and see how this wrapper allows to execute binaries according to the system that the corresponding ocamlopt compiler has been configured to build for.</p><h3>Conclusion</h3><p>It’s been a fun time working on this binding! It’s amazing to see the level of details that can be built through ocaml-ctypes using their provided primitives. Ultimately, the binding is very clean and elegant, with very few low-level assumptions.</p><p>Likewise, the simplicity and power of the dune build system makes this very fluid to build. Without it, each of the described steps above would have been much more painful to execute and compile.</p><p>[1]: My bet is that, at the time the POSIX specifications were being written, there we already several inconsistent socket.h headers out in the wild among the various historical UNIX flavors..</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc3f4cbab302" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Archiving Analog Audio on a Raspberry Pi using Liquidsoap]]></title>
            <link>https://medium.com/@romain.beauxis/archiving-analog-audio-on-a-raspberry-pi-using-liquidsoap-9a7feebe6af5?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a7feebe6af5</guid>
            <category><![CDATA[ocaml]]></category>
            <category><![CDATA[liquid-soap]]></category>
            <category><![CDATA[raspberry-pi]]></category>
            <category><![CDATA[audio-recording]]></category>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Tue, 25 Sep 2018 16:01:30 GMT</pubDate>
            <atom:updated>2018-09-26T14:13:13.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, a friend of mine came forward with a set of tapes that he wanted to digitize and archive. That’s always such a cool prospect, to bring back some of the old world analog recordings into a new digital life. To that end, we’ve seen numerous product come out, vinyl turntable with integrated USB interface and etc.</p><p>However, they all overlook one important aspect of this process: it is incredibly tedious. Usually, you’d need to plug your recording device to a computer, fire a recording software such as <a href="https://www.audacityteam.org/">Audacity</a>, hit record, start playing, monitor, stop the recording, repeat with the next side. And there’s even more work if you also want to split tracks and etc.</p><p>In order to make this process less annoying, I’ve been exploring a solution that involves <a href="https://www.liquidsoap.info/">Liquidsoap</a>, a specialized DSL language that I’ve been developing with some friends for quite a while. The Liquidsoap language is designed with first-class notion of audio (and video) streams and operators to manipulate them. It is a perfect tool for this kind of automation.</p><p>The other piece of this experiment is a <a href="https://www.raspberrypi.org/">Raspberry Pi</a>, an inexpensive small board that can be used for quick experiments using mainstream OSes.</p><p>Looking for online documentation on the process, I was happy to find Richard Campbell’s article on <a href="https://medium.com/@PTcampbell/recording-audio-on-a-raspberry-pi-3a51ae351b98">Recording Audio on a Raspberry Pi</a>. His story is the basis of this article and I’d recommend hitting it to get the basic things off the ground, installing the Raspberry Pi, setting up the recoding interface and Dropbox uploader and etc.</p><p>Now, let’s dive into the Liquidsoap part!</p><h3>Automated recording using Liquidsoap</h3><p>You can find instructions on how to install Liquidsoap <a href="https://www.liquidsoap.info/download.html">here</a>. Installing using the <a href="https://opam.ocaml.org/">opam</a> package manager is fairly easy and takes care of all external libraries you might to install as well.</p><p>The syntax of the Liquidsoap language is somewhat similar to ruby and is fairly easy to read. I won’t go into details about it but you can read the <a href="https://www.liquidsoap.info/doc-1.3.4/language.html">online documentation</a> for more details.</p><p>The first operator we’ll need here is input.alsa. This operator creates a audio stream from an <a href="https://en.wikipedia.org/wiki/Advanced_Linux_Sound_Architecture">alsa</a> input device. Referring back to Richard’s article, the USB input device we use is hw:1,0. Here we go:</p><pre>s = input.alsa(device=”hw:1,0&quot;, fallible=false)</pre><p>This is our basic stream. The idea of our script here is that this audio stream will be running at all times but only actually record when there is some audio coming in. This way, we can automatize the process and only have to play the audio from our analog source, say play one side of a record, let the script pick up audio data and archive it, wait until the side has played, flip it and play the next one without having to do anything on the digital side.</p><p>This is the reason we’re adding fallible=false here, it tells Liquidsoap that this stream will be running all the time.</p><p>Next, we need to detect silence:</p><pre>s = strip_blank(start_blank=true, max_blank=180., s)</pre><p>strip_blank is an operator that monitors the audio stream for silence and makes it unavailable after a certain amount of time with only silent audio. Here we use a fairly long time of 3 minutes in order to make sure that we do not inadvertently stop recording during a small gap in the original audio.</p><p>A shorter time might allow to split the audio between the tracks of a record, if those tracks have consistent audio and no silence (so, probably not good for <a href="https://www.youtube.com/watch?v=53N99Nim6WE&amp;t=3s">this song</a>!)</p><p>We’re using start_blank=true because we want the stream to be initially unavailable since we’ll start the Liquidsoap script before the analog playback.</p><p>Next, we need to save the stream in a file:</p><pre>output.file(%shine,fallible=true,<br>  on_close=upload_to_dropbox,<br>  &quot;/tmp/%Y-%m-%d-%H_%M_%S.mp3&quot;,<br>  s)</pre><p>output.file is the operator used to save to files. The %sine part specifies the encoder. Liquidsoap supports multiple formats, %lame (for mp3 encoding), %vorbis, %flac and even video formats. Here we use the <a href="https://github.com/toots/shine">shine encoder</a>, which is a fixed-point, small footprint encoder that is perfectly fitted for small devices such as the Raspberry Pi.</p><p>The encoded file name here is generated using the date of the recording, via the %Y-%m-%d-%H_%M_%S placeholders. The reason is that we want to make sure each file has a different name, so they will be uploaded and stored according to the time of recording.</p><p>Finally, when a file is done being encoded, we tell Liquidsoap to upload it to Dropbox via on_close=upload_to_dropbox. This is the last bit we need to describe:</p><pre>def upload_to_dropbox(path) =<br>  def upload() =<br>    basename = quote(&quot;recordings/#{basename(path)}&quot;)<br>    path = quote(path)</pre><pre>    cmd = &quot;/usr/local/bin/dropbox_uploader.sh upload \<br>       #{path} #{basename} &amp;&amp; rm -f #{path}&quot;<br>    system(cmd)</pre><pre>    (-1.)<br>  end</pre><pre>  add_timeout(fast=false,0.,upload)<br>end</pre><p>Now, this is the heart of what makes Liquidsoap such a cool tool: it is a fully featured language with quite powerful possibilities. Let’s look at what we have here…</p><p>upload() is our main upload function. It calls dropbox_uploader.sh to upload the file and then deletes the local copy. Again, you might want to refer to Richard Campbell’s story on how to set up the Dropbox uploader.</p><p>The upload() function returns the floating number -1. The reason for that is that uploading to Dropbox takes time. Since Liquidsoap is a streaming language, all the callbacks invoked in its operators need to return quickly in order to not halt the stream generation. Thus, we send the upload process to an asynchronous task processing mechanism via add_timeout.</p><p>add_timeout works as follows: it takes a function to be executed and a timeout and executes that task after the given timeout. Depending wether the task is marked as fast or not, it will be sent to an appropriate task queue.</p><p>When a task terminates, it tells the scheduler wether to execute it again after a certain amount of time or to just discard it. This is the reason for the returned value in upload(). If a tasks returns a value superior or equal to 0. it is executed again after that time has expired. Otherwise, if it returns a negative value, like here, the task is discarded.</p><p>So, what’s going on with our script? input.alsa continuously pulls data from the audio input, strip_blank monitors the audio and cuts it into tracks of non-silent data. Then output.file encodes and saves each track and calls upload_to_dropbox each time it is done encoding a file.</p><p>Finally, upload_to_dropbox creates an asynchronous tasks that sends the encoded data to Dropbox and deletes the local file.</p><p>Here is our complete script:</p><pre>s = input.alsa(device=&quot;hw:1,0&quot;, fallible=false)</pre><pre>s = strip_blank(start_blank=true, max_blank=180., s)</pre><pre>def upload_to_dropbox(path) =<br>  def upload() =<br>    basename = quote(&quot;recordings/#{basename(path)}&quot;)<br>    path = quote(path)</pre><pre>    cmd = &quot;/usr/local/bin/dropbox_uploader.sh \<br>        upload #{path} #{basename} &amp;&amp; rm -f #{path}&quot;<br>    system(cmd)</pre><pre>    (-1.)<br>  end</pre><pre>  add_timeout(fast=false,0.,upload)<br>end</pre><pre>output.file(%shine,fallible=true,<br>  on_close=upload_to_dropbox,<br>  &quot;/tmp/%Y-%m-%d-%H_%M_%S.mp3&quot;,<br>  s)</pre><p>To install and run it as a daemon on your Raspberry Pi, you can have a look at <a href="https://github.com/savonet/liquidsoap-daemon">liquidsoap-daemon</a>.</p><p>Now, it is time to start playing those records or cassette you’ve got pending!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a7feebe6af5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ultimate Discogs Seller Google Spreadsheet]]></title>
            <link>https://medium.com/@romain.beauxis/the-ultimate-discogs-seller-google-spreadsheet-cde00f83cad7?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/cde00f83cad7</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[discogs]]></category>
            <category><![CDATA[api-integration]]></category>
            <category><![CDATA[vinyl-record]]></category>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Sat, 26 May 2018 18:04:49 GMT</pubDate>
            <atom:updated>2018-05-28T19:18:14.645Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot has happened since my <a href="https://medium.com/@romain.beauxis/streamlined-listings-using-google-sheets-and-the-discogs-api-ebf79ae1bab0">last story</a> about using Discogs API and Google Sheets scripting to streamline the selling process. The code has been optimized and well tested so now it’s time for an update!</p><h3>1- Listing new items</h3><p>The listing process is now using a edit hook. In the previous story, I was pulling data and caching it, using custom cell formula/functions. This approach proved not to be scalable, too slow when opening the sheet and it would eventually run into the quotas for max number of script function executions, one of the zillion of annoyingly nitpicking quotas imposed by Google..</p><p>Instead, the sheet now has a trigger when editing a cell which, when editing a release ID, pulls the data from Discogs and stores it in the row. This way, the cells contains the actual data once and for all. Here’s how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vYqQcp_15Rl1Li0auTV1Bw.gif" /></figure><h3>2- Adding items to the inventory</h3><p>This part is pretty much similar to my previous posting. It’s been streamlined also by adding default values for the condition and status columns. Here’s how it looks:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*LabNTb2JaFAIqXvtLzxkYg.gif" /></figure><h3>3- Marking items as sold</h3><p>There seems to be a blind spot in the Discogs API to track sold items from the inventory. Fortunately, it’s not hard to do it yourself. Also, bonus, I’ve added an optional USPS tracking part! Check it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BiUhmYiBOj2tGKaPVtL5Yw.gif" /></figure><h3>How to use it?</h3><p>The sheet is public! You can access it here: <a href="https://docs.google.com/spreadsheets/d/17yMDsgNV693YZ4ocULE4Kl8v2j4l18-E3JVFXk5RZss">https://docs.google.com/spreadsheets/d/17yMDsgNV693YZ4ocULE4Kl8v2j4l18-E3JVFXk5RZss</a></p><p>The code I’ve used is here: <a href="https://github.com/toots/discogs-seller-gapps-script">https://github.com/toots/discogs-seller-gapps-script</a> Feel free to fork, contribute and report issues.</p><p>In order to use the sheet, you should first make your own copy (menu <strong>“File”</strong> then <strong>“Make a copy”</strong>). Then you’ll need to define the edit trigger and give the scripts edit access to your sheet. To do that, open the <strong>“Tools” </strong>menu and click on <strong>“Script editor”</strong>. Once in the script editor, go to<strong> “Edit”</strong> and <strong>“Current project trigger”</strong> and define the following trigger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iDeVOsSW4p9fWp6gWXoKPQ.png" /></figure><p>When saving this, you should be asked some questions related to giving the script the access it needs to your data.</p><p>Finally, you need to edit <strong>“Code.gs”</strong> in the script editor to add your <a href="https://www.discogs.com/developers/">Discogs API key</a> (variable discogsToken, line 2).</p><p>Likewise, if you wish to use the <a href="https://www.usps.com/business/web-tools-apis/welcome.htm">USPS tracking API</a>, you need to edit <strong>“Code.gs”</strong> and add your own USPS user (variable trackingUser , line 11).</p><p>That’s it, you can start listing and selling on discogs!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cde00f83cad7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlined listings using Google Sheets and the Discogs API]]></title>
            <link>https://medium.com/@romain.beauxis/streamlined-listings-using-google-sheets-and-the-discogs-api-ebf79ae1bab0?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf79ae1bab0</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[google-sheets]]></category>
            <category><![CDATA[record]]></category>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Sat, 11 Nov 2017 16:57:06 GMT</pubDate>
            <atom:updated>2017-11-12T01:32:35.751Z</atom:updated>
            <content:encoded><![CDATA[<p>For quite a while now, I have been collecting vintage LP records. It is a great occupation, which brings a lot of music back to life and is a great way to explore cities, through their record stores.</p><p>Lately, the website <a href="https://discogs.com/">discogs.com</a> has emerged as a fantastic companion service for records collectors. It features a huge, comprehensive database of records, with all the different editions, tracks, details and even preview of the songs when they are available online. On top of that, the website provides a market place to sell and buy records, with price history and all sort of cool tools. This website truly is a beautiful work on web design and application.</p><p>What’s even better, they also provide a <a href="https://www.discogs.com/developers/">API</a>, allowing programmatic access to their data. Needless to say, I’ve been itching for a while to play with it. So, I finally took a minute to look at it and ended-up connecting this API to a <a href="https://docs.google.com/spreadsheets">Google Sheet</a> that allows for fast records indexing and listing. Let me show you!</p><p>The base sheet used in the following can be found <a href="https://docs.google.com/spreadsheets/d/1ywhKlaUQ8-EBj-MNu5ot0zukkQhvpq1DYbtrF_kcAbo/edit">here</a>.</p><h4>Authentication</h4><p>The first thing you will need is a custom API token. You can obtain it at <a href="https://www.discogs.com/settings/developers">https://www.discogs.com/settings/developers</a>. Once generated, you should fill the sheet with it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*pn5sUzgv7mAAEIvOP0Na2g.gif" /></figure><h4>Indexing your records</h4><p>For fast indexing, the idea is to pull all the usual data, artist, album, label, from the discogs API so that one only has to enter a discogs release ID and let the script do the rest. Here’s the code:</p><pre>function discogsToken() {<br>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&quot;Records&quot;);<br>  return sheet.getRange(4,1).getValue();<br>}</pre><pre>function makeUrl(path) {<br>  return &quot;<a href="https://api.discogs.com/">https://api.discogs.com</a>&quot; + path + &quot;?token=&quot; + discogsToken();<br>}</pre><pre>function discogsRelease(id) {<br>  var key = &quot;discogs-&quot; + id;<br>  var cache = CacheService.getDocumentCache();<br>  var cached = cache.get(key);<br>  if (cached != null) {<br>    return JSON.parse(cached);<br>  }<br>  var url = makeUrl(&quot;/releases/&quot; + id);<br>  var response = UrlFetchApp.fetch(url);<br>  var json = response.getContentText();<br>  cache.put(key,json,864000); // 10 days cache..<br>  return JSON.parse(json);<br>}</pre><pre>function discogsThumbUrl(id) {<br>  return discogsRelease(id).thumb;<br>}</pre><pre>function discogsTitle(id) {<br>  return discogsRelease(id).title;<br>}</pre><pre>function discogsArtist(id) {<br>  return discogsRelease(id).artists[0].name;<br>}</pre><pre>function discogsLabel(id) {<br>  return discogsRelease(id).labels[0].name;<br>}</pre><pre>function discogsUrl(id) {<br>  return discogsRelease(id).uri;<br>}</pre><p>The language used here is google’s own <a href="https://www.google.com/script/start/">Google Script</a>. It’s essentially a spin-off of Javascript with integrated Google APIs and specific functionalities such as HTTP requests interfaces, making it pretty easy to get started quickly.</p><p>In this code, we fetch the API token previously entered, generate a URL for a release API request and distribute those results to the different target entries. We also cache the result as we can reasonably expect release data to not change too often and because Discogs is not happy when an application uses the API too frequently, which is bound to happen as the index grows bigger and bigger.</p><p>On the sheet side, we use those functions to populate our rows. On each target row, we use the functions discogsArtist , discogsAlbum, etc. Then, adding a new entry is as easy as extending the spreadsheet values with the usual select/drag method:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*04zbInfO5m3uLnwWPmzGlQ.gif" /></figure><h4><strong>Listing for sale</strong></h4><p>Finally, if you want to list records as available for sale, you can also use the discogs API, making extremely efficient to keep an inventory of the records you list online through a single spreadsheet and synchronize your listings on the website. Let’s look at the code first:</p><pre>var validConditions = [<br>  &quot;Mint (M)&quot;, &quot;Near Mint (NM or M-)&quot;,<br>  &quot;Very Good Plus (VG+)&quot;, &quot;Very Good (VG)&quot;,<br>  &quot;Good Plus (G+)&quot;, &quot;Good (G)&quot;,<br>  &quot;Fair (F)&quot;, &quot;Poor (P)&quot;<br>]</pre><pre>var validSleeveConditions = [<br>  &quot;Mint (M)&quot;, &quot;Near Mint (NM or M-)&quot;,<br>  &quot;Very Good Plus (VG+)&quot;, &quot;Very Good (VG)&quot;,<br>  &quot;Good Plus (G+)&quot;, &quot;Good (G)&quot;,<br>  &quot;Fair (F)&quot;, &quot;Poor (P)&quot;,<br>  &quot;Generic&quot;, &quot;Not Graded&quot;, &quot;No Cover&quot;<br>]</pre><pre>var validStates = [&quot;Draft&quot;, &quot;For Sale&quot;]</pre><pre>function syncDiscogsListing(sheet, header, index) {<br>  var row = sheet.getRange(index,1,1,header.length);<br>  var data = row.getValues()[0];<br>  <br>  var releaseIndex = header.indexOf(&quot;Release ID&quot;);<br>  var listingIndex = header.indexOf(&quot;Listing ID&quot;);<br>  var statusIndex = header.indexOf(&quot;Listing Status&quot;);<br>  var conditionIndex = header.indexOf(&quot;Condition&quot;);<br>  var sleeveConditionIndex = header.indexOf(&quot;Sleeve Condition&quot;);<br>  var priceIndex = header.indexOf(&quot;Price&quot;);<br>  var commentsIndex = header.indexOf(&quot;Comments&quot;);<br>  var listedOnIndex = header.indexOf(&quot;Listed On&quot;);<br>  var errorsIndex = header.indexOf(&quot;Errors&quot;);<br>  <br>  var errorCell = sheet.getRange(index,errorsIndex+1);<br>  errorCell.setValue(&quot;&quot;);<br>  <br>  if (!data[releaseIndex]) return;<br>  <br>  var errors = [];<br>  <br>  var checkError = function(index, values) {<br>    if (values.indexOf(data[index]) == -1) {<br>      var label = header[index];<br>      errors.push(&quot;Error: &quot; + label + &quot; should be one of: &quot; + values.join(&quot;, &quot;));<br>    }<br>  }<br>  <br>  checkError(statusIndex,validStates);<br>  checkError(conditionIndex,validConditions);<br>  checkError(sleeveConditionIndex,validSleeveConditions);<br>  <br>  if (errors.length &gt; 0) {<br>    errorCell.setValue(errors.join(&quot;, &quot;));<br>    return;<br>  }<br>  <br>  var options = {<br>    &quot;method&quot;:      &quot;post&quot;,<br>    &quot;contentType&quot;: &quot;application/json&quot;<br>  };<br>  <br>  var payload = {<br>      release_id:       data[releaseIndex],<br>      condition:        data[conditionIndex],<br>      sleeve_condition: data[sleeveConditionIndex],<br>      price:            data[priceIndex],<br>      comments:         data[commentsIndex],<br>      status:           data[statusIndex]<br>  };<br>  <br>  var url;<br>  if (data[listingIndex]) {<br>    url = makeUrl(&quot;/marketplace/listings/&quot; + data[listingIndex]);<br>  } else {<br>    url = makeUrl(&quot;/marketplace/listings&quot;);<br>  }<br>  <br>  options.payload = JSON.stringify(payload);<br>  var response = UrlFetchApp.fetch(url,options);</pre><pre>  if (!data[listingIndex]) {<br>    var ret = JSON.parse(response.getContentText());<br>    <br>    // Set Listing ID<br>    var cell = sheet.getRange(index,listingIndex+1);<br>    cell.setValue(ret.listing_id);<br>    <br>    // Set Listed On<br>    cell = sheet.getRange(index,listedOnIndex+1);<br>    cell.setValue((new Date).toLocaleDateString());<br>  }<br>}<br>  <br>function syncDiscogsListings() {<br>  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(&quot;Records&quot;);<br>  var lastRow = sheet.getLastRow();<br>  var header = sheet.getDataRange().getValues()[0];</pre><pre>  var index; <br>  for (index = 2; index &lt;= lastRow; index++) {<br>    syncDiscogsListing(sheet,header,index);<br>  }<br>}</pre><p>The top-level function syncDiscogsListings fetches the whole array of data and synchronizes the listings for each populated row, using the function syncDiscogsListing .</p><p>The function syncDiscogsListing takes the first row as header to find all the entry’s relevant information, performs basic data validation and generates a HTTP POST request that either creates a new listing if it was not present already or updates an existing one. That’s it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ypf-FKW-j5vGADEOv6soZw.gif" /></figure><h4>Last words</h4><p>This was a truly enjoyable experience. As we grow more and more connected, APIs such as this one create new ways of interacting with data and services that are really interesting and can make life much easier. The only drawbacks that I experienced were the following:</p><ul><li>Discogs does not provide a sandboxed version of their API. This means that you have to do your testing on live data. So, when creating a listing for sale, make sure that you swiftly delete it if that was just meant as a test!</li><li>There does not seem to be an easy path forward from sale listings to actual sales. I have not sold records through Discogs so I have not had a chance to play with real data though. It would be great to be able to wrap the whole workflow through a single spreadsheet. Here, too, a sandboxed API would be great.</li></ul><p>Hope you enjoyed this!</p><p>PS: No records emoji? Someone please tell <a href="https://twitter.com/sundarpichai/status/924487551372615680">@sundarpichai</a>! 😂</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf79ae1bab0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scalable and serverless media processing using BuckleScript/OCaml and AWS Lambda/API Gateway]]></title>
            <link>https://medium.com/@romain.beauxis/scalable-and-serverless-media-processing-using-bucklescript-ocaml-and-aws-lambda-api-gateway-4efe39331f33?source=rss-22dd29e3fc87------2</link>
            <guid isPermaLink="false">https://medium.com/p/4efe39331f33</guid>
            <category><![CDATA[media-processing]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[ocaml]]></category>
            <dc:creator><![CDATA[Romain Beauxis]]></dc:creator>
            <pubDate>Mon, 16 Oct 2017 19:23:37 GMT</pubDate>
            <atom:updated>2017-10-16T20:32:31.767Z</atom:updated>
            <content:encoded><![CDATA[<p>Being a Music Licensing company, we at <a href="https://www.audiosocket.com/">Audiosocket</a> have to process a lot of media files. From a tech perspective, the challenges to deploy, scale and maintain such applications have interesting issues that are much different from Web technologies. Today, I would like to talk about a stack that we’ve recently been pushing in production and which involves a couple of technologies that, combined together, are a pretty neat solution to a lot of our problems.</p><h3>The Plot</h3><p>Contrary to web requests, media processing does not require fast responses. Requests are processed asynchronously and the caller is notified whenever processing has finished. Such requests require much more resources in CPU and memory than a typical web response and those resources can vary greatly, depending on the processing pipeline, for instance applying audio compression, signal processing filters, etc.. Finally, these type of computation are blocking but, unlike with evented framework such as <a href="https://nodejs.org/">Node.js</a>, blocking is CPU-bound, a consequence of the heavy computations required to process media files. Therefore, an event loop, which works great when blocking is caused by networking delays, will not be of much help in our case.</p><p>Because of this, scaling a media processing pipeline requires understanding and anticipating how a bunch of resources are consumed such as CPU power, memory footprint and disk space. Previously, we used worker frameworks like <a href="https://github.com/mperham/sidekiq">sidekiq</a> and they worked great. But, this requires maintaining server instances with their usual burden of potential software crash, full hard drive, etc. Furthermore, deciding when and how many new servers to spin-up when requests load increase can be tricky. On top of that, the granularity of allocated resources is not great and there are delays waiting for new servers to be ready.</p><p>For these reasons, we decided to move to the <a href="https://aws.amazon.com/lambda/">AWS Lambda</a> service, which brings the granularity down to the function level and delegates scaling issues entirely to the service operator. In front of those Lambda functions, the <a href="https://aws.amazon.com/api-gateway/">AWS API Gateway</a> receives API requests and interfaces with the Lambda processes. Finally, in order to make that transition sustainable in the long-term, we have been using <a href="https://bucklescript.github.io/">BuckleScript</a>, an <a href="https://ocaml.org/">OCaml</a> interface to Javascript. Combined together, these three technologies result in a media processing architecture that is very robust, totally serverless and immediately scalable at the request level.</p><p>The chart below illustrates how the stack operates. If you are curious, there is a fully functional demonstration code available <a href="https://github.com/lidcore/bucklescript-serverless-media-pipeline-demo">here</a>. It is packed with all the tricks explained below plus some extra ones. For sake of simplicity, though, the DynamoDB part is not implemented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*ouLPxMy6GI64qkwtBM7kCw.png" /><figcaption>The Media Processing Pipeline</figcaption></figure><h3>Buckling Down</h3><p>When working in a startup environment, time to production is quite crucial. Putting together some code to prove an idea is feasible, releasing a Minimal Viable Product for demonstration purposes, oftentimes developers have to choose the quickest path to write down their code. Node.js is a great tool for such fast-paced work and we’ve used it a lot. Coincidentally, it is also one of the languages available as runtime for the Lambda platform.</p><p>However, as flexible as Javascript is, it is also quite difficult to maintain in the long run. There is an inherent lack of structure in it which makes it very easy to quickly patch together a small demonstration project but, later on, creates potential hassle when updating or refactoring parts of the code, or when asking new developers to work on code they’ve never seen before.</p><p>In order to make Javascript more suitable for large-scale industrial applications, the BuckleScript framework has recently emerged, originally supported by <a href="https://www.bloomberg.com/">Bloomberg</a>. BuckleScript interfaces Javascript native code with OCaml. You start by defining bindings from Javascript to OCaml, then write OCaml code using those bindings. Finally, the BuckleScript compiler creates Javascript code from your OCaml code that you can deploy as native Javascript. The benefit of this loop, or transpiling, is that you then get to use all the fabulous tools that the OCaml language provides in your Javascript application.</p><h4>OCaml’s Toolbox</h4><p>Developed initially at France’s <a href="https://www.inria.fr/">INRIA</a> research center, OCaml is a functional language, with a statically inferred type system, an efficient Garbage Collector and a pragmatic approach to the ML language paradigm. Similar to Haskell, it provides the usual tools of functional languages but is also amenable to some imperative primitives whenever appropriate, for instance for I/O programming. Recently, it has enjoyed an interesting surge in various industrial applications, from <a href="https://blog.janestreet.com/why-ocaml/">Financial Trading</a> to <a href="https://reasonml.github.io/">Facebook</a> and recently <a href="https://github.com/uber/logtron">Uber</a>. Its ecosystem of development tools has greatly improved in the past years, in particular with the addition of a solid package manager, <a href="https://opam.ocaml.org/">OPAM</a>. All-in-all, even though still a niche language, this constitutes a pretty successful transfer from academics to software industry.</p><p>One of the very important feature of OCaml is its static type system. In OCaml, every variable has a type that is determined at compile-time and, if your code isn’t too tricky, most of the time, you do not have to explicitly write which type those variables should have. This means that, if you code compiles, then you are guaranteed that your functions will always be called with arguments of a specific, fixed type.</p><p>In Javascript world, this means that you no longer have to deal with variables being null or receiving a string when you expected an int. Furthermore, when refactoring your code, any change in a function’s expected type trickles down via the compiler into each and every call to that function. The code will not compile until you have fixed all the calls to that function, making refactoring a safe and truly enjoyable experience — something that is very important when dealing with large scale applications and developer teams.</p><p>In the following, I’ll be showing some OCaml features that can be very useful when writing code for BuckleScript/Javascript. If you are not familiar with the language, you might want to start with taking a peek at <a href="https://realworldocaml.org/">Real World OCaml</a>, the reference book for OCaml programming.</p><h4>Lambda handler’s type</h4><p>In Lambda, a function is essentially a callback handler. It receives three arguments, a JSON object describing the function’s parameters, a context object, and a callback to be executed when the function has finished its execution. In OCaml/BuckleScript, this can be described with the following type:</p><pre>type error = exn Js.Nullable.t<br>type ‘a callback = error -&gt; ‘a -&gt; unit<br>type context<br>type (‘a, ‘b) lambda_function = ‘a -&gt; context -&gt; ‘b callback -&gt; unit</pre><p>A callback is a function that takes two arguments, an error, which can either be null or an exception, a result of universal type ‘a and returns nothing. This is the usual callback paradigm in asynchronous Javascript code where, if the error argument is null, the function is assumed to have executed successfully and possibly returned a value as its second argument.</p><p>Finally, the type for the Lambda function takes an input parameter of universal type ‘a, a context variable and a callback that returns a value of universal type ‘b. This function returns nothing or, if you prefer, its returned value is ignored.</p><p>Now, anticipating on what we’ll see later, it turns out that, when interfaced with AWS’s API Gateway through <a href="https://serverless.com/">serverless</a>, the returned value of a API handler should be a Javascript object of this form:</p><pre>{statusCode: &lt;int&gt;, body: &lt;string&gt;}</pre><p>In this case, we can amend our type declaration above and add:</p><pre>type api_response = &lt;<br>  statusCode: int;<br>  body: string<br>&gt; Js.t</pre><pre>type &#39;a api_handler = (‘a, api_response) lambda_function</pre><p>Now, each time that we declare a Lambda function to be of the type api_handler we will be guaranteed that this function returns the appropriate type of Javascript object.</p><h4>The Asynchronous Monad</h4><p>Another typical hassle in Javascript/Node.js world is the fact that one has to constantly deal with callback-based computations. Usually, this looks like this:</p><pre>function asynchronousProcessing(callback) {<br>  doSomeAsynchronousWork(function (err, result) {<br>    if (err) { return callback(err); }</pre><pre>    doMoreAsynchronousWork(result, function (err, newResult) {<br>      if (err) { return callback(err); }</pre><pre>      &lt;etc etc..&gt;<br>    })<br>});</pre><p>Having to repeat that pattern constantly is prone to making mistake. In order to make this less painful, APIs such as <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> have been introduced. However, none of those really solve the problem of having to repeat the same pattern over and over again. Here comes the notion of Monad!</p><p>Monads is quite a hip term with deep connections to <a href="https://en.wikipedia.org/wiki/Monad_(category_theory)">Category Theory</a> but, really, it is just a fancy way to describe a computing abstraction. Essentially, a monad describes a certain type of computation and how to combine them together. Let’s look at an example applied to our case:</p><pre>(* A asynchronous computation takes a callback and executes it when it has finished, either with an error or with a result of type &#39;a. *)<br>type error  = exn Js.Nullable.t<br>type &#39;a callback = error -&gt; &#39;a -&gt; unit<br>type &#39;a t = &#39;a callback -&gt; unit</pre><pre>(* A computation that returns a result of type &#39;a. *)<br>val return : &#39;a -&gt; &#39;a t</pre><pre>(* A computation that returns an error. *)<br>val fail : exn -&gt; &#39;a t</pre><pre>(* Combine two computations. *)<br>val (&gt;&gt;) : &#39;a t -&gt; (&#39;a -&gt; &#39;b t) -&gt; &#39;b t</pre><p>Now, let’s look at the implementation of this monad:</p><pre>let return result = fun callback -&gt;<br>  callback Js.Nullable.null result</pre><pre>let fail error = fun callback -&gt;<br>  callback (Js.Nullable.return error) (Obj.magic Js.Nullable.null)</pre><pre>let (&gt;&gt;) current next = fun callback -&gt;<br>  current (fun err result -&gt;<br>    match Js.toOption err with<br>      | Some exn -&gt; <br>         fail exn callback<br>      | None -&gt;<br>         next ret callback)</pre><p>The return function takes a callback and executes it with null for its error parameter and a given result. The fail function takes a callback and executes it with the given error and null result. We use a little trickery here with Obj.magic here to pass the result.</p><p>Finally, (&gt;&gt;) implements the usual pattern to combine asynchronous computations: given a callback, a current computation and the next one, it executes the current computation with a new callback which, if passed a non-null error, returns immediately by executing the original callback with that error or, else, passes result to the next computation, along with the original callback.</p><p>Now let’s look how the code above rewrites using this asynchronous monad:</p><pre>(* Define the asynchronous processing pipeline *)<br>asynchronous_computation =<br>  do_some_asynchronous_work &gt;&gt; fun result -&gt;<br>    do_more_asynchronous_work result &gt;&gt; fun (..) -&gt;<br>      (etc etc..)</pre><pre>(* Execute it! *)<br>asynchronous_computation callback</pre><p>No more repeated patterns, no more potential errors!</p><h4>Polymorphic variants and phantom types</h4><p>Finally, let’s look at a more tricky and fancier application of the OCaml type system using phantom types and polymorphic variants.</p><p>Phantom types are parametric types that are used to constrain sub-classes of an generic type for various API restriction purposes. This a very powerful tool. For instance, it makes it possible to force a API user to follow a pre-defined flow in its calls such as calling init followed by config and finally run. Here, we are going to use them to annotate the different events that the user can listen to on Node.js’s readable and writable <a href="https://nodejs.org/api/stream.html">streams</a>.</p><p>In order to do so, we use polymorphic variants, another power feature of the language which can be quite handy but sometimes requires a bit of work to understand and use properly. Polymorphic variants are collections of different labels that can be sub- or sur-classed. Let’s look at our code to fix the ideas. You might want to also check out the official Node.js Stream API <a href="https://nodejs.org/api/stream.html">here</a>.</p><pre>type &#39;a t</pre><pre>type write_events = [<br>  | `Close  of unit     -&gt; unit<br>  | `Drain  of unit     -&gt; unit<br>  | `Finish of unit     -&gt; unit<br>  | `Error  of exn      -&gt; unit<br>  | `Pipe   of readable -&gt; unit<br>  | `Unpipe of readable -&gt; unit<br>] and read_events = [<br>  | `Close    of unit   -&gt; unit<br>  | `End      of unit   -&gt; unit<br>  | `Readable of unit   -&gt; unit<br>  | `Data     of string -&gt; unit<br>  | `Error    of exn    -&gt; unit<br>] and writable = write_events t<br>  and readable = read_events t</pre><pre>type events = [write_events | read_events]</pre><pre>val on : ([&lt; events] as &#39;a) t -&gt; &#39;a -&gt; unit</pre><p>In this API, we define the list of events that readable and writable streams can receive. Each of these events is associated with a handler to process the type of data that will be received when the event occurs.</p><p>Then we sub-class the generic stream type ‘a t by annotating it with the events associated with each type of stream, readable and writable. Finally, the on function is typed so it will only accept events that are annotated in the stream type, making sure, for instance, that only a readable stream can be used to listen to the `Data event. Otherwise, the compiler will complain with a message such as:</p><pre>Stream.on writable (`Data (fun s -&gt; ...))<br>&gt;  Error: This expression has type [&gt; `Data of string -&gt; unit ]<br>&gt;         but an expression was expected of type Stream.write_events<br>&gt;         The second variant type does not allow tag(s) `Data</pre><p>Now, let’s peek under the hood to see how this is implemented:</p><pre>external on : &#39;a t -&gt; string -&gt; (&#39;b -&gt; unit) -&gt; unit = &quot;&quot; [@@bs.send]</pre><pre>let on stream = function<br>  | `Close    fn -&gt; on stream &quot;close&quot;    fn<br>  | `Drain    fn -&gt; on stream &quot;drain&quot;    fn<br>  | `Finish   fn -&gt; on stream &quot;finish&quot;   fn<br>  | `Error    fn -&gt; on stream &quot;error&quot;    fn<br>  | `Pipe     fn -&gt; on stream &quot;pipe&quot;     fn<br>  | `Unpipe   fn -&gt; on stream &quot;unpipe&quot;   fn<br>  | `End      fn -&gt; on stream &quot;end&quot;      fn<br>  | `Readable fn -&gt; on stream &quot;readable&quot; fn<br>  | `Data     fn -&gt; on stream &quot;data&quot;     fn</pre><p>Pretty simple after all! First, we declare an external on method on stream objects. It can receive any type of stream, a string-typed event name and a callback receiving a value of a yet unknown type. This is the low-level binding to the Node.js’s <a href="https://nodejs.org/api/events.html">EventEmitter API</a>.</p><p>Then, we decorate this function by re-defining it as a function that receives a polymorphic event type and handler and explicitly unwraps it down to the expected parameters on the Node.js side. Voila!¹</p><p>Let’s just finish here by noticing that the explicit type restriction on the on function is defined in the type interface. Without it, there is nothing that tells the compiler to only accept event handlers that are part of the stream’s type annotation.</p><h3>Serverless</h3><p>The last piece of our stack that puts everything together is <a href="https://serverless.com/">serverless</a>. Their motto, <em>“Focus on your application, not your infrastructure” </em>is actually quite a true statement.</p><p>The toolkit allows you to configure the whole combination of AWS services using a simple <a href="https://en.wikipedia.org/wiki/YAML">YAML</a> file. Here’s the gist of it from our <a href="https://github.com/lidcore/bucklescript-serverless-media-pipeline-demo">demo code</a>:</p><pre>service: media-pipeline-demo<br><br>provider:<br>  name: aws<br>  runtime: nodejs6.10<br>  region: us-east-1<br>  stage: production<br>  environment:<br>    MEDIA_BUCKET: media-pipeline.lidcore.com<br>  iamRoleStatements:<br>    - Effect: Allow<br>      Action:<br>        - s3:GetObject<br>        - s3:PutObject<br>      Resource: &quot;arn:aws:s3:::media-pipeline.lidcore.com*&quot;<br>    - Effect: Allow<br>      Action:<br>        - lambda:InvokeFunction<br>      Resource: &quot;arn:aws:lambda:us-east-1:478746233480:function:media-pipeline-encode-file&quot;<br><br>functions:<br>  encode-file:<br>    name: media-pipeline-encode-file<br>    handler: lib/js/src/index.encode_file<br>    memorySize: 1536<br>    timeout: 300<br><br>  queue-encoding:<br>    name: media-pipeline-queue-encoding<br>    handler: lib/js/src/index.queue_encoding<br>    events:<br>      - http:<br>          path: encodings<br>          method: post<br>          cors: true<br>          integration: lambda-proxy</pre><p>This file contains all the configuration you should need, including AWS access policies, environment variables and endpoint definitions.</p><p>The toolkit also has an offline plugin which allows you to test your endpoint locally:</p><pre>% serverless offline<br>Serverless: Starting Offline: production/us-east-1.</pre><pre>Serverless: Routes for encode-file:<br>Serverless: (none)</pre><pre>Serverless: Routes for queue-encoding:<br>Serverless: POST /encodings</pre><pre>Serverless: Offline listening on <a href="http://localhost:3000/">http://localhost:3000</a></pre><p>This makes it very convenient to test locally before deploying your code. However, calls to execute AWS lambda functions, here encode-file will still go to AWS.</p><p>Finally, when you are satisfied with your code, you can deploy:</p><pre>% serverless deploy<br>Serverless: Packaging service...<br>Serverless: Excluding development dependencies...<br>Serverless: Uploading CloudFormation file to S3...<br>Serverless: Uploading artifacts...<br>Serverless: Uploading service .zip file to S3 (23.95 MB)...<br>Serverless: Validating template...<br>Serverless: Updating Stack...<br>Serverless: Checking Stack update progress...<br>....................<br>Serverless: Stack update finished...<br>Service Information<br>service: media-pipeline-demo<br>stage: production<br>region: us-east-1<br>stack: media-pipeline-demo-production<br>api keys:<br>  None<br>endpoints:<br>  POST - <a href="https://kqi3ibkr42.execute-api.us-east-1.amazonaws.com/production/encodings">https://1234567890.execute-api.us-east-1.amazonaws.com/production/encodings</a><br>functions:<br>  encode-file: media-pipeline-demo-production-encode-file<br>  queue-encoding: media-pipeline-demo-production-queue-encoding<br>Serverless: Removing old service versions..</pre><p>Voila! You’re ready to go..</p><h4>Notes:</h4><p>[1] BuckleScript has a <a href="https://bucklescript.github.io/bucklescript/Manual.html#_using_polymorphic_variant_to_model_event_listener">specific annotation</a> to achieve the same purpose but it is the author’s opinion that it is not really usable. In particular, it cannot be used with a proper .ml /.mli interface declaration, which should always be considered good practice when writing OCaml code</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4efe39331f33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>