<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.xavierriley.co.uk/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.xavierriley.co.uk/" rel="alternate" type="text/html" /><updated>2026-02-23T13:48:29-08:00</updated><id>https://www.xavierriley.co.uk/feed.xml</id><title type="html">Xavier Riley / PhD Researcher</title><subtitle>Currently researching for a PhD at the Center for Digital Music (C4DM) at Queen Mary University of London</subtitle><author><name>Xavier Riley</name></author><entry><title type="html">Reviving a Roland VS880 with an SD card</title><link href="https://www.xavierriley.co.uk/posts/2023/01/reviving-a-roland-vs880-with-an-sd-card" rel="alternate" type="text/html" title="Reviving a Roland VS880 with an SD card" /><published>2023-01-18T00:00:00-08:00</published><updated>2023-01-18T00:00:00-08:00</updated><id>https://www.xavierriley.co.uk/posts/2023/01/reviving-a-roland-vs880-with-an-sd-card</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2023/01/reviving-a-roland-vs880-with-an-sd-card"><![CDATA[<p>This is more of a reminder to myself than a blog post, but it might prove useful to others.</p>

<p>I have an old Roland VS880 multitrack recorder which looks like this:</p>

<p><img src="https://static.roland.com/assets/images/products/gallery/vs-880_angle_gal.jpg" alt="Roland VS880 - what a beast" /></p>

<p>After letting it languish in my loft for a few years I had a need to do some location recording recently and decided to fix it up.</p>

<p>Following the instructions here https://untidymusic.com/roland-vs880/adventures-with-the-roland-vs880-cf-card-and-cf-to-ide-reader I bought myself the following:</p>

<ul>
  <li>a cheap Compact Flash to IDE adapter <a href="https://www.amazon.co.uk/dp/B07NS5JTP5?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details">link</a></li>
  <li>a more expensive Compact Flash to IDE adapter <a href="https://www.amazon.co.uk/dp/B0036DDXUM?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details">link</a></li>
  <li>an 8Gb Compact Flash card <a href="https://www.amazon.co.uk/dp/B008W2QHYQ?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details">link</a></li>
  <li>a 32Gb SD card <a href="https://www.amazon.co.uk/dp/B08GYG6T12?psc=1&amp;ref=ppx_yo2ov_dt_b_product_details">link</a></li>
  <li>a Compact Flash to SD adapter <a href="https://www.amazon.com/QUMOX-Compact-Memory-Adapter-Reader/dp/B019REDBY6/ref=sr_1_3?dchild=1&amp;keywords=sd%2Bto%2Bcf%2Badapter&amp;qid=1621264224&amp;sr=8-3&amp;th=1">link</a></li>
</ul>

<p>Basically, I tried every combination of the above but nothing worked. Whatever I did resulted in <code class="language-plaintext highlighter-rouge">SYS Init = No DRV</code> being shown after booting the VS880.</p>

<p>People on the <a href="http://www.vsplanet.com/">VS Planet</a> forum were complaining of similar issues, suggesting that manufacturers had silently changed the components which caused these parts to lose compatibility with the VS880 hardware.</p>

<p>I was ready to give up, but when trying to recover data from my (broken) old IDE drive that I pulled out, I noticed that the formatting was unusual</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/dev/disk5 (external, physical):
   #:                       TYPE NAME                    SIZE       IDENTIFIER
   0:     FDisk_partition_scheme                        *2.2 GB     disk5
   1:                 DOS_FAT_16 VS-880ST25B             1.1 GB     disk5s1
   2:                 DOS_FAT_16 VS-880ST25B             1.1 GB     disk5s2
   3:               DOS_FAT_16_S VS-880ST25B             20.2 MB    disk5s3
</code></pre></div></div>

<p>I thought I’d try formatting the SD card to match this using a Mac first and then see if the VS880 would recognize it. After some googling I came up with this command:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>diskutil partitionDisk /dev/disk2 MBR "MS-DOS FAT16" "VS880" 2048M free "" 0B
</code></pre></div></div>

<p>where <code class="language-plaintext highlighter-rouge">disk2</code> was the ID of my SD card - if you decide to run this, check where your SD card is mounted by looking at the output of <code class="language-plaintext highlighter-rouge">mount</code> first!</p>

<p>I think the <code class="language-plaintext highlighter-rouge">2048M</code> part here was important, as the next time I plugged it into the VS880 everything worked! I could follow the instructions to initialize the drive from here: https://www.sweetwater.com/sweetcare/articles/roland-vs-880-force-initializing-hard-drive-vs-880/</p>

<p>At the time of writing it is 17% of the way into a surface scan but I’m more hopeful that it’s back now.</p>]]></content><author><name>Xavier Riley</name></author><category term="vs880" /><category term="roland" /><category term="hardware" /><summary type="html"><![CDATA[This is more of a reminder to myself than a blog post, but it might prove useful to others.]]></summary></entry><entry><title type="html">Compiling packages from source on Heroku using buildpacks</title><link href="https://www.xavierriley.co.uk/posts/2017/05/compiling-packages-from-source-on-heroku-using-buildpacks" rel="alternate" type="text/html" title="Compiling packages from source on Heroku using buildpacks" /><published>2017-05-17T00:00:00-07:00</published><updated>2017-05-17T00:00:00-07:00</updated><id>https://www.xavierriley.co.uk/posts/2017/05/compiling-packages-from-source-on-heroku-using-buildpacks</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2017/05/compiling-packages-from-source-on-heroku-using-buildpacks"><![CDATA[<h5 id="warning-whilst-i-work-for-heroku-this-isnt-official-supported---its-just-something-i-discovered-in-my-spare-time-hopefully-this-helps-someone-but-leave-me-any-feedback-on-twitter-xavriley">(Warning: whilst I work for Heroku, this isn’t official supported - it’s just something I discovered in my spare time. Hopefully this helps someone but leave me any feedback on Twitter <code class="language-plaintext highlighter-rouge">@xavriley</code>)</h5>

<p>What do you do if you’re deploying an app on Heroku but you have a package your app depends on? The first thing is to check the list of default packages here https://devcenter.heroku.com/articles/stack-packages - if it already exists there then you don’t need to worry.</p>

<p>The next thing to checkout is the list of third party buildpacks here https://elements.heroku.com/buildpacks These are contributed by the community and it’s fairly likely that someone has gone down this path before.</p>

<p>If there’s no third party buildpack, or if the ones you’ve found are no longer maintained, then the next option is the <code class="language-plaintext highlighter-rouge">Apt</code> buildpack https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-apt This allows you to create a file named <code class="language-plaintext highlighter-rouge">Aptfile</code> at the root of your project which lists packages that you’d like to install. Bear in mind that this doesn’t resolve dependencies in quite the same way as <code class="language-plaintext highlighter-rouge">apt-get install</code> so you’ll need to list all the dependencies you want.</p>

<p>Right - with those out of the way, what about if none of them work? I came across this recently where someone wanted to use a version of <code class="language-plaintext highlighter-rouge">curl</code> that had support for HTTP/2 requests.</p>

<h3 id="building-curl-with-http2-support-from-source">Building <code class="language-plaintext highlighter-rouge">curl</code> with HTTP/2 support from source</h3>

<p>First, add the following buildpacks:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku buildpacks:add --index 1 https://github.com/heroku/heroku-buildpack-apt.git
heroku buildpacks:add https://github.com/weibeld/heroku-buildpack-run.git
</code></pre></div></div>

<p>Now install the dependencies - create a file named <code class="language-plaintext highlighter-rouge">Aptfile</code> in the root of the project with the following contents:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># Aptfile
nghttp2
libnghttp2-dev
</code></pre></div></div>

<p>To trigger the compilation (on each build unfortunately) create a file named <code class="language-plaintext highlighter-rouge">buildpack-run.sh</code> in the root of the project with the following contents:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># buildpack-run.sh
wget http://curl.haxx.se/download/curl-7.46.0.tar.bz2
tar -xvjf curl-7.46.0.tar.bz2
cd curl-7.46.0
./configure  --disable-shared --with-nghttp2 --prefix=/app/.apt/usr
make
</code></pre></div></div>

<blockquote>
  <h4 id="finding-libraries-in-the-right-places">Finding libraries in the right places</h4>

  <p>The missing piece of the puzzle was to use the <code class="language-plaintext highlighter-rouge">--disable-shared</code> flag with <code class="language-plaintext highlighter-rouge">./config</code>. When the app is building on Heroku it uses funky folders in <code class="language-plaintext highlighter-rouge">/tmp</code> and the compiled binary tries to link against those paths. By disabling shared libs, it pulls in all the necessary code to the resulting binary so you can move it around the system without problems.</p>
</blockquote>

<p>You will then need to add these new files and deploy. This should build a version of curl for you in the root of the project.</p>

<p>You can then test this in a one-off dyno as follows:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ heroku run bash
...
~ $ ./curl-7.46.0/src/curl --http2 -I https://nghttp2.org/
HTTP/2.0 200
date:Thu, 27 Apr 2017 11:21:13 GMT
content-type:text/html
last-modified:Mon, 24 Apr 2017 13:50:42 GMT
etag:"58fe02b2-19ff"
accept-ranges:bytes
content-length:6655
x-backend-header-rtt:0.001139
strict-transport-security:max-age=31536000
server:nghttpx
via:2 nghttpx
x-frame-options:SAMEORIGIN
x-xss-protection:1; mode=block
x-content-type-options:nosniff
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">curl</code> binary and object files are located in <code class="language-plaintext highlighter-rouge">/app/curl-7.46.0/src/</code> (Heroku deploys your code to the <code class="language-plaintext highlighter-rouge">/app</code> folder by default).</p>

<p>Note that the dyno now has two versions of <code class="language-plaintext highlighter-rouge">curl</code> installed! If you need to use the one with HTTP/2 support you have to be careful and specify the full path <code class="language-plaintext highlighter-rouge">./curl-7.46.0/src/curl --http2 -I https://nghttp2.org/</code> or add it to the front of the <code class="language-plaintext highlighter-rouge">$PATH</code> variable.</p>]]></content><author><name>Xavier Riley</name></author><category term="heroku" /><summary type="html"><![CDATA[(Warning: whilst I work for Heroku, this isn’t official supported - it’s just something I discovered in my spare time. Hopefully this helps someone but leave me any feedback on Twitter @xavriley)]]></summary></entry><entry><title type="html">Using OpenVPN from a Heroku dyno</title><link href="https://www.xavierriley.co.uk/posts/2017/05/using-openvpn-from-a-heroku-dyno" rel="alternate" type="text/html" title="Using OpenVPN from a Heroku dyno" /><published>2017-05-09T00:00:00-07:00</published><updated>2017-05-09T00:00:00-07:00</updated><id>https://www.xavierriley.co.uk/posts/2017/05/using-openvpn-from-a-heroku-dyno</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2017/05/using-openvpn-from-a-heroku-dyno"><![CDATA[<h5 id="warning-whilst-i-work-for-heroku-this-isnt-official-supported---its-just-something-i-discovered-in-my-spare-time-hopefully-this-helps-someone-but-leave-me-any-feedback-on-twitter-xavriley">(Warning: whilst I work for Heroku, this isn’t official supported - it’s just something I discovered in my spare time. Hopefully this helps someone but leave me any feedback on Twitter <code class="language-plaintext highlighter-rouge">@xavriley</code>)</h5>

<h2 id="update-this-wont-work">Update: this won’t work</h2>

<p>After some more research, the advice below will allow you to install the relevant packages but the Heroku dynos won’t have the necessary permissions to rewrite the outgoing network packets. For an alternative way of setting up a secure tunnel to a dyno, you could try looking at https://github.com/koding/tunnel or https://github.com/jpillora/chisel instead.</p>

<hr />

<p>In terms of getting a VPN client working there’s no official support for this as part of the default image. To get something working you will need to add another buildpack to your app. If you haven’t worked with multiple buildpacks before, read up on the best approach for those here https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app</p>

<p>You can then try this experimental buildpack to add additional packages:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku buildpacks:add --index 1 https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-apt
</code></pre></div></div>

<p>You would then create a file named <code class="language-plaintext highlighter-rouge">Aptfile</code> at the root of your project with the following contents:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>liblzo2-2
openvpn
</code></pre></div></div>

<p>You would then need to add those new files to git and deploy for those changes to take effect.</p>

<p>Once the deploy completes, you can try out the VPN connection using the following commands whilst running a <code class="language-plaintext highlighter-rouge">heroku run bash</code> session in a one-off dyno.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ heroku run bash
...
# Bash session running on a dyno
# This line is necessary because the apt version of openvpn doesn't link against libzo correctly otherwise
~ $ export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/app/.apt/lib/x86_64-linux-gnu/"
~ $ .apt/usr/sbin/openvpn --client --remote vpnhost.ac.uk --auth-user-pass --dev tunX --capath /etc/ssl/certs --daemon
</code></pre></div></div>

<p>That will get you a VPN session running with a user/password prompt to start. From there you’ll need to look at the various ways of configuring <code class="language-plaintext highlighter-rouge">openvpn</code> to make it do what you need.</p>

<p>To set the <code class="language-plaintext highlighter-rouge">LD_LIBRARY_PATH</code> for every dyno, you can add a file named <code class="language-plaintext highlighter-rouge">.profile</code> to the root of your project with the following contents:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/app/.apt/lib/x86_64-linux-gnu/"
</code></pre></div></div>

<p>You can find out more about the <code class="language-plaintext highlighter-rouge">.profile</code> script on Heroku here: https://devcenter.heroku.com/articles/dynos#the-profile-file</p>]]></content><author><name>Xavier Riley</name></author><category term="heroku" /><summary type="html"><![CDATA[(Warning: whilst I work for Heroku, this isn’t official supported - it’s just something I discovered in my spare time. Hopefully this helps someone but leave me any feedback on Twitter @xavriley)]]></summary></entry><entry><title type="html">10,000 hours - as told by jazz musicians</title><link href="https://www.xavierriley.co.uk/posts/2017/04/10-000-hours-as-told-by-jazz-musicians" rel="alternate" type="text/html" title="10,000 hours - as told by jazz musicians" /><published>2017-04-13T00:00:00-07:00</published><updated>2017-04-13T00:00:00-07:00</updated><id>https://www.xavierriley.co.uk/posts/2017/04/10-000-hours-as-told-by-jazz-musicians</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2017/04/10-000-hours-as-told-by-jazz-musicians"><![CDATA[<p>In a 1993 paper by Anders Ericsson, he was one of the first to make the claim that <em>mastery</em> of a skill took around <em>10 years</em> (about 10,000 hours) of <em>deliberate practice</em>.</p>

<blockquote>
  <p>In most domains of expertise, individuals begin in their childhood a regimen of
effortful activities (deliberate practice) designed to optimize improvement. Individual differences,
even among elite performers, are closely related to assessed amounts of deliberate practice. Many
characteristics once believed to reflect innate talent are actually the result of intense practice
extended for a minimum of 10 years. 
http://projects.ict.usc.edu/itw/gel/EricssonDeliberatePracticePR93.PDF</p>
</blockquote>

<p>Whilst most people reading this will probably be fellow computer programmers clicking around from my other posts, I’m also a jazz guitar nut and have been for some time. I thought it would be fun to look at quotes from jazz players to see what they can tell us about getting better at something.</p>

<p>Whilst lots of people subscribe to the “talent” theory of development, that dream for me died a long time ago. Instead I feel like the stories of excellence (particularly in jazz) almost always have these common themes:</p>

<ul>
  <li>starting young</li>
  <li>taking lessons with a good teacher early in their development</li>
  <li>some period of <em>intense</em> practice, especially for those with great chops (technique)</li>
  <li>lots and lots and lots of gigs</li>
</ul>

<p>Let’s see some quotes to back that up!</p>

<h2 id="joe-pass">Joe Pass</h2>

<blockquote>
  <blockquote>
    <p>Was guitar playing easy for you in the beginning?</p>
  </blockquote>

  <p>I guess it came sort of easy for me; I have certain difficulties, not a lot. But you’ve got to remember that I grew up playing the guitar. I started when I was nine, and by the time I was nine and a half or ten, I was doing seven or eight hours’ practice every day. I did two hours’ practice at six o’clock in the morning before I went to school, and another two hours as soon as I got home from school in the afternoon. Then I did four hours at night before I went to bed.</p>

  <p>I did that until I was fourteen or fifteen. I didn’t like it - I hated it, but my father was very firm about it; he saw a little something happening, so he figured he’d just push. I don’t remember too much how I felt about it except that I’d rather be outside playing ball and things. I never could ride a bike, like even today I can’t do these things.
<a href="https://web.archive.org/web/20070102092642/http://www.gould68.freeserve.co.uk/Joe%20Pass%20Int_view.html">Joe Pass Interview Guitar Magazine in June 1974</a></p>
</blockquote>

<p>8 hours a day for five years, all before the age of 15!</p>

<blockquote>
  <blockquote>
    <p>But one wouldn’t recognise any resemblance between your playing and Django’s,</p>
  </blockquote>

  <p>Well I never copied him. I don’t remember that I copied any guitar player note-for-note. But I remember copying Charlie Parker note for note.</p>
</blockquote>

<p>I’ve <a href="https://www.youtube.com/watch?v=YPMLKKJgjEE">transcribed one Charlie Parker solo for guitar</a>, and that stuff is hard!</p>

<h2 id="george-benson">George Benson</h2>

<blockquote>
  <p>I’m writing this in 2014, a year that, professionally speaking, was pretty much the same as 2004, which was pretty much the same as 1994, and so on all the way back till the 1950s. And I don’t mean that in a bad way - it’s more about the magic of consistency. See, I’m a creature of (jazz) habit: I practice every day, I gig a lot, and I record almost every year. I keep going.</p>
</blockquote>

<p>From <a href="https://books.google.co.uk/books?id=v25KDgAAQBAJ">“Benson: The Autobiography”</a></p>

<p>I also remember reading a quote in a YouTube comment, possibly on a Jack McDuff video, (so sad that folk histories are locked up in there, mixed in with vile trolling etc. completely unsearchable) that someone had a friend who knew Benson in the early days. They claimed that he could sing around 20 (or 21 or 22, can’t remember exactly) Charlie Parker solos <em>from memory</em> when he was around 18.</p>

<h2 id="charlie-parker">Charlie Parker</h2>

<blockquote>
  <p>I put quite a bit of study into the horn (saxophone), that’s true. In fact, the neighbours threatened to ask my mother to move once… She said I was driving them crazy with the horn. I used to put in at least 11 to 15 hours a day.</p>
</blockquote>

<p>As quoted in <a href="https://books.google.co.uk/books?id=ijEGzLKQY5kC&amp;pg=PA17#v=onepage&amp;q&amp;f=false">Chasin’ the Bird: The Life and Legacy of Charlie Parker</a></p>

<p>He was around 15 at the time as far as I can tell. The same book describes him learning Lester Young solos note-for-note.</p>

<h2 id="pat-metheny">Pat Metheny</h2>

<blockquote>
  <p>and of course, you HAVE to practice like crazy. during the years between when i was 13 til 19, i would guess i averaged around 10 to 12 hours a day with the guitar in my hands or sitting at the piano studying harmony.</p>
</blockquote>

<p>http://www.patmetheny.com/qa/questionView.cfm?queID=49</p>

<p>That’s enough for now but I’ll add more here as I find them.</p>]]></content><author><name>Xavier Riley</name></author><category term="jazz" /><summary type="html"><![CDATA[In a 1993 paper by Anders Ericsson, he was one of the first to make the claim that mastery of a skill took around 10 years (about 10,000 hours) of deliberate practice.]]></summary></entry><entry><title type="html">Writing a C extension for Ruby in 2016</title><link href="https://www.xavierriley.co.uk/posts/2016/11/writing-a-c-extension-for-ruby-in-2016/" rel="alternate" type="text/html" title="Writing a C extension for Ruby in 2016" /><published>2016-11-12T00:00:00-08:00</published><updated>2016-11-12T00:00:00-08:00</updated><id>https://www.xavierriley.co.uk/posts/2016/11/writing-a-c-extension-for-ruby-in-2016</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2016/11/writing-a-c-extension-for-ruby-in-2016/"><![CDATA[<p>Now that Ruby has crested the hype cycle, settled down and taken out a mortgage, you’d expect the posts around the community to be more about big business concerns. Whilst that might be true, I’d like to row against the tide by telling you about the fun I had figuring out how to write my first C extension - <a href="https://github.com/xavriley/fast_osc/"><code class="language-plaintext highlighter-rouge">fast_osc</code></a> - and how I made Sonic Pi 10x faster in the process.</p>

<p>Before we get stuck into the details of that, what is a C extension and why would you want to write one in 2016?</p>

<h2 id="why">Why?</h2>

<p>Two reasons - speed and leverage. If you have a need for speed and a small well defined problem then writing an extension may be the way to go. Whilst working on <a href="http://sonic-pi.net">Sonic Pi</a> we have to target the resource constrained Raspberry Pi Model B+ . With a 700MHz CPU and 512Mb we often have to party like its 1999. After some recent profiling work we identified that the <a href="http://opensoundcontrol.org/spec-1_0">Open Sound Control</a> message encoding/decoding was a big hotspot in terms of performance and this was causing audio dropouts as the CPU struggled to keep up with our example pieces.</p>

<h3 id="speed">Speed</h3>

<p>We optimised as far as we could with plain Ruby, but our implementations relied on <a href="http://www.rubydoc.info/stdlib/core/Array%3Apack"><code class="language-plaintext highlighter-rouge">Array#pack</code></a> and <a href="http://www.rubydoc.info/stdlib/core/String%3Aunpack"><code class="language-plaintext highlighter-rouge">String#unpack</code></a> to get data in and out of the right binary format. If you take a peek at the <code class="language-plaintext highlighter-rouge">View source</code> links for these at the bottom of those pages, you might be able to see why they were a bit slow. The implementations run to hundreds of lines, many of which we didn’t need as OSC only uses a limited number of types.</p>

<h3 id="leverage">Leverage</h3>

<p><a href="http://opensoundcontrol.org/spec-1_0">Open Sound Control</a> is a widely used messaging format in music applications so there are plenty of good implementations in <a href="https://libraries.io/search?q=osc&amp;sort=">most languages</a>. One of the great use cases for a C extension is when you don’t want to reinvent the wheel as you can use the great work of others instead.</p>

<h2 id="before-diving-in">Before diving in…</h2>

<p>Writing a C extension is a little bit like doing distributed computing - it’s best to avoid it until you <em>have no other option</em>. I’d initially wanted to use FFI (which I’ll talk more about in another post) because, frankly, I was scared of writing any C that was going into a widely used app.</p>

<p>The issue with FFI is that it largely depends on the library you want to wrap - if it has C macros and structs flying around all over the place then it’s likely to be more work writing the FFI wrapper than just writing the C extension in the first place.</p>

<p>It’s also worth mentioning that there are great options for writing Ruby extensions in Go, Rust, Crystal and many other languages that can expose C bindings. I didn’t choose to go with those for this project because the OSC libs weren’t as mature but I’d definitely consider them in future.</p>

<h2 id="rtosc---nice-clean-c"><code class="language-plaintext highlighter-rouge">rtosc</code> - nice, clean C</h2>

<p>After looking at several OSC implementations I was starting to despair - I’d never written any C before and the canonical implementation, <code class="language-plaintext highlighter-rouge">liblo</code>, made use of macros and structs that I didn’t completely understand at the time. After nearly giving up I stumbled on the <a href="https://github.com/fundamental/rtosc/"><code class="language-plaintext highlighter-rouge">rtosc</code></a> library which had embedding in mind. It consisted of two files (<code class="language-plaintext highlighter-rouge">rtosc.h</code> and <code class="language-plaintext highlighter-rouge">rtosc.c</code>) and emphasised speed by pre-allocating a buffer for the message so that assignments were kept to a minimum.</p>

<p>In the best spirit of open source, I enquired with the author via a <a href="https://github.com/fundamental/rtosc/issues/28">GitHub issue</a> and got a thoughtful, well-reasoned and polite response within a few hours - viva la internet!</p>

<p>This managed to convince me to try writing a C extension and I’m glad I did.</p>

<h2 id="getting-started">Getting started</h2>

<p>In terms of bootstrapping the project, I followed this excellent blog post by James Coglan - <a href="https://blog.jcoglan.com/2012/07/29/your-first-ruby-native-extension-c/">Your first Ruby native extension</a> Between this and <a href="https://tenderlovemaking.com/2009/12/18/writing-ruby-c-extensions-part-1.html">the older blog posts by Aaron Patterson</a> I was able to suss out the minimum project structure to add a method to a Ruby object from C.</p>

<h2 id="open-sound-control-and-the-fast_osc-api">Open Sound Control and the <code class="language-plaintext highlighter-rouge">fast_osc</code> API</h2>

<p>OSC is a binary protocol which looks a bit like RPC. There’s a “path” which represents the name of a remote method, a tag string which identifies the type of the args and then a series of binary encoded arguments. You can think of a basic message looking something like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>/methodname, "sif", ["This is a string", 123, 3.14]
</code></pre></div></div>

<p>You can see that the type of the arguments corresponds to a tag - <code class="language-plaintext highlighter-rouge">s</code> for a string, <code class="language-plaintext highlighter-rouge">i</code> for an int and so on. For the Ruby API I wanted to hide this so that you weren’t thinking about types e.g.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>&gt;&gt; FastOsc.encode_single_message("/foo", ["baz", 1, 2.0])
=&gt; "/foo\x00\x00\x00\x00,sif\x00\x00\x00\x00baz\x00\x00\x00\x00\x01@\x00\x00\x00"
</code></pre></div></div>

<p>This meant that the C extension would have to take a Ruby array, do some kind of switch case statement on the type of each element, and finally build a tag string and an output array of the encoded versions according to the OSC spec.</p>

<p>This is pretty much the whole challenge but it did mean I need to touch Ruby’s mysterious C API for quite a few different types. You can checkout the source to see how these fit together but I’ll comment on a few here:</p>

<h3 id="rubys-c-api">Ruby’s C API</h3>

<h4 id="working-out-the-type">Working out the type</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>switch(TYPE(current_arg))
</code></pre></div></div>

<h4 id="ints-and-longs">Ints and Longs</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case T_FIXNUM
</code></pre></div></div>

<p>In the OSC spec there’s a distinction between integers less than <code class="language-plaintext highlighter-rouge">2^32</code> (ints) and those larger (longs). In the source <a href="https://github.com/xavriley/fast_osc/blob/master/ext/fast_osc/fast_osc_wrapper.c#L189">I convert the Ruby Fixnum to the relevant one using the <code class="language-plaintext highlighter-rouge">FIX2INT</code> and <code class="language-plaintext highlighter-rouge">FIX2LONG</code> macros</a>.</p>

<h4 id="floats">Floats</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case T_FLOAT:
</code></pre></div></div>

<p>Easy enough to convert from Ruby to C using <code class="language-plaintext highlighter-rouge">NUM2DBL</code></p>

<h4 id="strings-and-symbols">Strings and Symbols</h4>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case T_STRING:
</code></pre></div></div>

<p>Again this seemed pretty straightforward using the <code class="language-plaintext highlighter-rouge">StringValueCStr()</code> method. Ruby symbols can be converted to strings using <code class="language-plaintext highlighter-rouge">rb_sym_to_s()</code>.</p>

<h4 id="what-about-unicode">What about Unicode?</h4>

<p>The trouble came when we worked out that I had broken Unicode strings. Since Sonic Pi aims to be fully emoji compliant, this had to be fixed. Luckily the Tenderlove blog came to the rescue again:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>string_arg = rb_str_new2(string_from_c);
enc = rb_enc_find_index("UTF-8");
rb_enc_associate_index(string_arg, enc);
</code></pre></div></div>

<p>This little snippet made sure that the decoded string was passed back to Ruby as <code class="language-plaintext highlighter-rouge">UTF-8</code> rather than <code class="language-plaintext highlighter-rouge">US-ASCII</code> - phew!</p>

<h4 id="ruby-time-objects">Ruby <code class="language-plaintext highlighter-rouge">Time</code> objects</h4>

<p>OSC also has a concept of timestamps which are pretty integral to music applications. I wanted the API to transparently convert these to and from <code class="language-plaintext highlighter-rouge">Time</code> objects. First you have to check for the object type:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>case T_DATA:
</code></pre></div></div>

<p>This means that you have a Ruby object. From there we check specifically for time using this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>if (CLASS_OF(current_arg) == rb_cTime)
</code></pre></div></div>

<p>Now <code class="language-plaintext highlighter-rouge">rb_cTime</code> is one of the many examples of why I called the Ruby C API mysterious. This was quite tricky to find out and one of the main reasons I’m writing up this log to aid future intrepid explorers.</p>

<h4 id="osc-timestamps-ntp">OSC Timestamps (NTP)</h4>

<p>Finally, the OSC spec encodes time in two parts - first as the number of seconds since the year <code class="language-plaintext highlighter-rouge">1900</code> with the other part for the fraction of a second passed. This is what NTP servers use and it differs from the more common “seconds since 1970” (Unix epoch) that <code class="language-plaintext highlighter-rouge">Time.new</code> and others deal with.</p>

<p>The method for this was a bit hairy but after working out that I needed to Google “Unix to NTP timestamp conversion” I found something close enough on Stack Overflow and adapted it to Ruby like so:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>#define JAN_1970 2208988800.0     /* 2208988800 time from 1900 to 1970 in seconds */

uint64_t ruby_time_to_osc_timetag(VALUE rubytime) {
  uint64_t timetag;
  double floattime;
  uint32_t sec;
  uint32_t frac;

  switch(TYPE(rubytime)) {
    case T_NIL:
      timetag = 1;
      break;
    default:
      // convert Time object to ntp
      floattime = JAN_1970 + NUM2DBL(rb_funcall(rubytime, rb_intern("to_f"), 0));

      sec = floor(floattime);
      frac = (uint32_t)(fmod(floattime, 1.0) * 4294967296); // * (2 ** 32)
      // printf("\nsec: %04x\n", sec);
      // printf("\nfrac: %04x\n", frac);
      timetag = (uint64_t)((uint64_t)sec &lt;&lt; 32 | (uint64_t)frac);
      // printf("\ntimetag: %08llx\n", timetag);
      break;
  }

  return timetag;
}
</code></pre></div></div>

<h3 id="memory-management">Memory management</h3>

<p>Thankfully this wasn’t to complicated as the underlying <code class="language-plaintext highlighter-rouge">rtosc</code> library just expects you to allocate a buffer big enough to hold the message you want to encode. This meant keeping track of the size for each of the different types above and summing them for a given message. For strings (which vary in size) I took the <em><code class="language-plaintext highlighter-rouge">bytesize()</code></em> and then rounded up to the next power of two just to be safe.</p>

<h2 id="conclusion-and-further-reading">Conclusion and further reading</h2>

<p>After a lot of Googling, head scratching and running <code class="language-plaintext highlighter-rouge">rake compile</code> I finally had something that worked but I had no idea whether it was actually any faster. Thankfully, the benchmarks came in and they were good:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Encoding
-------------------------------------------------
            fast_osc    909.680k (±21.4%) i/s -      4.328M
             samsosc    271.908k (±19.3%) i/s -      1.327M
             oscruby     94.678k (±14.5%) i/s -    468.968k

Decoding
-------------------------------------------------
            fast_osc      2.635M (±22.2%) i/s -     12.435M
             samsosc    264.614k (±16.1%) i/s -      1.304M
             oscruby     36.362k (±16.3%) i/s -    179.622k
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">oscruby</code> here is the non-optimised library for Ruby. <code class="language-plaintext highlighter-rouge">samosc</code> is our hand rolled optimised pure Ruby version and <code class="language-plaintext highlighter-rouge">fast_osc</code> is this C extension. As you can see there was something like a 4x improvement in Encoding to OSC and a 10x improvement in Decoding over the fastest pure Ruby implementation.</p>

<p>This new extension shipped with Sonic Pi v2.11 last week and has been battle tested in 1000s of live coding performances without missing a beat, so I can say that it was a complete success! (it’s not often I get to say that about software projects…)</p>

<p>The code is all available here: https://github.com/xavriley/fast_osc</p>

<p>In terms of links I used whilst working on this, I’m have a gist here: https://gist.github.com/xavriley/507eff0a75d4552fa56e as there are too many to cover in detail.</p>

<p>One that does deserve a special mention though is the <a href="https://rxr.whitequark.org/mri/source">The Ruby Cross Reference</a> maintained by whitequark which offers a search over all the symbols in the Ruby C source. I found this helpful for some of the more obscure parts (like <code class="language-plaintext highlighter-rouge">rb_cTime</code>) but sadly this resource appears to be shutting down on 2016-12-31 unless it finds a new owner - any takers? If you’re interested you can contact them via the banner at the top of the site.</p>

<p>If you’ve been inspired to write your own extension, or if you have any feedback on my awful C I’d love to hear from you -  I’m @xavriley on Twitter - thanks for reading.</p>

<p>EDIT - one of the comments on <a href="https://www.reddit.com/r/ruby/comments/5cmux3/writing_a_c_extension_for_ruby_in_2016/">Reddit</a> reminded me of this awesome and very helpful ebook <a href="http://silverhammermba.github.io/emberb/">The Definitive Guide to Ruby’s C API</a> which I used for reference as well.</p>]]></content><author><name>Xavier Riley</name></author><category term="Sonic Pi" /><category term="ruby" /><summary type="html"><![CDATA[Now that Ruby has crested the hype cycle, settled down and taken out a mortgage, you’d expect the posts around the community to be more about big business concerns. Whilst that might be true, I’d like to row against the tide by telling you about the fun I had figuring out how to write my first C extension - fast_osc - and how I made Sonic Pi 10x faster in the process.]]></summary></entry><entry><title type="html">Installing Boost C++ libraries (libboost) on Heroku</title><link href="https://www.xavierriley.co.uk/posts/2016/06/libboost-on-heroku/" rel="alternate" type="text/html" title="Installing Boost C++ libraries (libboost) on Heroku" /><published>2016-06-03T00:00:00-07:00</published><updated>2016-06-03T00:00:00-07:00</updated><id>https://www.xavierriley.co.uk/posts/2016/06/libboost-on-heroku</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2016/06/libboost-on-heroku/"><![CDATA[<p>A quick note for anyone else who runs into this.</p>

<p>You can try this experimental <a href="https://github.com/heroku/heroku-buildpack-apt">Heroku Apt buildpack</a>. The documentation is a little out of date as it’s best to use it with the <a href="https://devcenter.heroku.com/articles/using-multiple-buildpacks-for-an-app">multiple buildpacks support</a>. Buildpacks are order dependent so you’ll want to add this one first in the list:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>heroku buildpacks:add https://github.com/heroku/heroku-buildpack-apt --index 1
</code></pre></div></div>

<p>You’ll need to add a file name <code class="language-plaintext highlighter-rouge">Aptfile</code> at the root of the project with the following contents:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>libstdc++-4.8-dev
libboost1.42-dev
libboost1.46-dev
libboost1.48-dev
libboost1.49-dev
libboost1.50-dev
libboost1.52-dev
libboost1.53-dev
libboost-atomic1.54-dev
libboost-chrono1.54-dev
libboost-context1.54-dev
libboost-coroutine.54-dev
libboost-date-time1.54-dev
libboost-exception1.54-dev
libboost-filesystem1.54-dev
libboost-graph-parallel1.54-dev
libboost-graph1.54-dev
libboost-iostreams1.54-dev
libboost-locale1.54-dev
libboost-log.54-dev
libboost-math1.54-dev
libboost-mpi-python1.54-dev
libboost-mpi1.54-dev
libboost-program-options1.54-dev
libboost-python1.54-dev
libboost-random1.54-dev
libboost-regex1.54-dev
libboost-serialization1.54-dev
libboost-signals1.54-dev
libboost-system1.54-dev
libboost-test1.54-dev
libboost-thread1.54-dev
libboost-timer1.54-dev
libboost-wave1.54-dev
libboost1.54-doc
libboost1.54-tools-dev
libmpfrc++-dev
libntl-dev
</code></pre></div></div>

<p>Then you can do an empty deploy and boost should be available:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ git add Aptfile
$ git commit -m "Add libboost"
$ git push heroku master
</code></pre></div></div>

<p>You’ll see a lot of error messages but yolo…</p>

<p>The files are installed to <code class="language-plaintext highlighter-rouge">/app/.apt/usr/lib/x86_64-linux-gnu/</code></p>

<h3 id="why-not-just-use-libboost-all-dev">Why not just use <code class="language-plaintext highlighter-rouge">libboost-all-dev</code>?</h3>

<p>I’m so glad you asked. The Heroku Apt buildpack isn’t the same as <code class="language-plaintext highlighter-rouge">apt-get</code> or <code class="language-plaintext highlighter-rouge">aptitude</code> so it doesn’t have any dependency resolution. That means you have to specify <em>every</em> dependency in the <code class="language-plaintext highlighter-rouge">Aptfile</code>.</p>]]></content><author><name>Xavier Riley</name></author><category term="heroku" /><summary type="html"><![CDATA[A quick note for anyone else who runs into this.]]></summary></entry><entry><title type="html">Neutron Accelerators and Drum Machines with Sonic Pi</title><link href="https://www.xavierriley.co.uk/posts/2015/01/neutron-accelerators-and-drum-machines-with-sonic-pi/" rel="alternate" type="text/html" title="Neutron Accelerators and Drum Machines with Sonic Pi" /><published>2015-01-22T00:00:00-08:00</published><updated>2015-01-22T00:00:00-08:00</updated><id>https://www.xavierriley.co.uk/posts/2015/01/neutron-accelerators-and-drum-machines-with-sonic-pi</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2015/01/neutron-accelerators-and-drum-machines-with-sonic-pi/"><![CDATA[<p>Working with <a href="http://sonic-pi.net">Sonic Pi</a> one of the exciting things about being able to code music is the potential for using algorithms. For the non-technical reader, I like to think of algorithms like following a recipe. You might start with the same ingredients but the order in which you do things can affect to outcome.</p>

<p>When we think about music people often understand things at an intuitive level but become uneasy about the idea of using rules or recipes to generate it. “Formulaic” is a dirty word when used to describe pop songs for example, but it doesn’t have to be that way. I’m going to look at one particular algorithm, Euclid’s algorithm, to create musical rhythms.</p>

<h2 id="a-method-for-spacing-out-rhythms">A method for spacing out rhythms</h2>

<p>Despite all the complex words I’m about to use, if all boils down to this: if I have a number of beats that I want to play in a given space (say 2 bars), how do I space those out as evenly as possible?</p>

<p>That’s obviously easy with regular rhythms that divide cleanly. If I want to play 8 beats across two bars of 8th notes it would look like this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>x . x . x . x . | x . x . x . x .
</code></pre></div></div>

<p>That’s 8 <code class="language-plaintext highlighter-rouge">x</code>’s spaced across the 16 possible beats. Easy peasy.</p>

<p>But what about numbers that don’t divide cleanly, for example, 3 into 8?</p>

<p>Let’s start with the solution first:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>x . . x . . x .
</code></pre></div></div>

<p>You can see we have to use a combination of long and short notes to fill the bar evenly. The above pattern uses groups of 3’s and 2’s to fill the space. You could easily notate it as:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>332
</code></pre></div></div>

<p>if you count the distances from one beat to the next. Let’s look at a few more examples of these odd rhythms:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># 5 into 8
x . x . x x . x
22121

# 13 into 16
x . x x x x . x | x x x . x x x x
2111211121111
</code></pre></div></div>

<p>One thing you might notice is that these aren’t the only way to divide up the bar. To take our 3 into 8 rhythm there are actually three possible options:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>x . . x . . x . #== 332
x . x . . x . . #== 233
x . . x . x . . #== 323
</code></pre></div></div>

<p>The last of those options appears so often in so many kinds of music that it’s often called “the mother rhythm”. Everything from Cuban clave to Elvis’ “Hound dog”. That said, if you look closely they are all variations on the same grouping: 2 lots of 3 and one lot of 2. That means we only need to generate one version and then we can rotate it to produce the others. So how are we going to generate it then?</p>

<h2 id="back-to-the-future-euclids-algorithm-from-300-bc">Back to the future: Euclid’s algorithm from 300 B.C.</h2>

<p>It turns out that Euclid thought about this too - how do you space things out as evenly as possible? Thousands of years later a scientist named Bjorklund was facing the same problem when he was setting up a Neutron Accelerator. He needed to fire neutrons evenly in a given space of time (a bit like our rhythm problem) and, being a scientist, he came up with a clever way of doing that.</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code>    <span class="k">def</span> <span class="nf">distribute</span><span class="p">(</span><span class="n">accents</span><span class="p">,</span> <span class="n">total_beats</span><span class="p">)</span>
      <span class="n">res</span> <span class="o">=</span> <span class="p">[]</span>

      <span class="n">total_beats</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span>
        <span class="c1"># makes a boolean based on the index</span>
        <span class="c1"># true is an accent, false is a rest</span>
        <span class="n">res</span> <span class="o">&lt;&lt;</span> <span class="p">((</span><span class="n">i</span> <span class="o">*</span> <span class="n">accents</span> <span class="o">%</span> <span class="n">total_beats</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">accents</span><span class="p">)</span>
      <span class="k">end</span>

	  <span class="n">res</span>
    <span class="k">end</span>
</code></pre></div></div>

<p>That’s the algorithm represented in Ruby. You don’t have to understand it as it’s probably not the simplest way of explaining it, but it’s there to show how concise a problem like this can be when expressed in code.</p>

<p>Years later a percussion-playing, scientifically-minded music professor was looking at the same problem applied to musical rhythms and came across Bjorklund’s research. He took the idea and explored it in a paper <a href="http://cgm.cs.mcgill.ca/~godfried/publications/banff.pdf">“The Euclidean Algorithm Generates Traditional Musical Rhythms” (Toussaint 2005)</a> from which I’ve taken these ideas.</p>

<h2 id="in-sonic-pi">In Sonic Pi…</h2>

<p>I’ve added a function to Sonic Pi called <code class="language-plaintext highlighter-rouge">distribute</code> which allows you to generate arrays that fit these evenly spaced patterns. Here’s some sample code:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">distribute</span><span class="p">(</span><span class="n">accents</span><span class="p">,</span> <span class="n">total_beats</span><span class="p">,</span> <span class="n">beat_rotations</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
  <span class="n">res</span> <span class="o">=</span> <span class="p">[]</span>

  <span class="n">total_beats</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span>
    <span class="c1"># makes a boolean based on the index</span>
    <span class="c1"># true is an accent, false is a rest</span>
    <span class="n">res</span> <span class="o">&lt;&lt;</span> <span class="p">((</span><span class="n">i</span> <span class="o">*</span> <span class="n">accents</span> <span class="o">%</span> <span class="n">total_beats</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">accents</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="n">res</span><span class="p">.</span><span class="nf">ring</span>
<span class="k">end</span>

<span class="k">class</span> <span class="nc">SonicPi::Core::RingArray</span>
  <span class="k">def</span> <span class="nf">as_x_notation</span>
    <span class="nb">self</span><span class="p">.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span><span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">?</span> <span class="s1">'x'</span> <span class="p">:</span> <span class="s1">'.'</span><span class="p">}.</span><span class="nf">join</span><span class="p">(</span><span class="s1">' '</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">as_beat_groups</span>
    <span class="nb">self</span><span class="p">.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">slice_before</span> <span class="p">{</span><span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">}.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:count</span><span class="p">).</span><span class="nf">join</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="nb">puts</span> <span class="n">distribute</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">).</span><span class="nf">inspect</span>
<span class="nb">puts</span> <span class="n">distribute</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">).</span><span class="nf">as_beat_groups</span>
<span class="nb">puts</span> <span class="n">distribute</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">0</span><span class="p">).</span><span class="nf">as_x_notation</span>
</code></pre></div></div>

<p>If you paste in the above code to SonicPi and run it, you should see this in the output window:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> ├─ [true, false, false, true, false, false, true, false]
 ├─ 332
 └─ x . . x . . x .
</code></pre></div></div>

<p>From here it’s not too hard to map over those arrays to turn them into musical patterns. Here’s an example you can play with:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">comment</span> <span class="k">do</span>
  <span class="c1"># this function is available in SonicPi v2.4 and upwards</span>
  <span class="c1"># if you're using a version with this included you can </span>
  <span class="c1"># delete this distribute function, otherwise uncomment it</span>
  <span class="c1"># above</span>
  <span class="k">def</span> <span class="nf">distribute</span><span class="p">(</span><span class="n">accents</span><span class="p">,</span> <span class="n">total_beats</span><span class="p">,</span> <span class="n">beat_rotations</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
    <span class="n">res</span> <span class="o">=</span> <span class="p">[]</span>

    <span class="n">total_beats</span><span class="p">.</span><span class="nf">times</span> <span class="k">do</span> <span class="o">|</span><span class="n">i</span><span class="o">|</span>
      <span class="c1"># makes a boolean based on the index</span>
      <span class="c1"># true is an accent, false is a rest</span>
      <span class="n">res</span> <span class="o">&lt;&lt;</span> <span class="p">((</span><span class="n">i</span> <span class="o">*</span> <span class="n">accents</span> <span class="o">%</span> <span class="n">total_beats</span><span class="p">)</span> <span class="o">&lt;</span> <span class="n">accents</span><span class="p">)</span>
    <span class="k">end</span>

    <span class="n">res</span><span class="p">.</span><span class="nf">ring</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="c1"># Monkey patching is never a good idea</span>
<span class="c1"># just say no kids...</span>
<span class="k">class</span> <span class="nc">SonicPi::Core::RingArray</span>
  <span class="k">def</span> <span class="nf">as_x_notation</span>
    <span class="nb">self</span><span class="p">.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">map</span> <span class="p">{</span><span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">?</span> <span class="s1">'x'</span> <span class="p">:</span> <span class="s1">'.'</span><span class="p">}.</span><span class="nf">join</span><span class="p">(</span><span class="s1">' '</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="k">def</span> <span class="nf">as_beat_groups</span>
    <span class="nb">self</span><span class="p">.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">slice_before</span> <span class="p">{</span><span class="o">|</span><span class="n">x</span><span class="o">|</span> <span class="n">x</span> <span class="p">}.</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">map</span><span class="p">(</span><span class="o">&amp;</span><span class="ss">:count</span><span class="p">).</span><span class="nf">join</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="n">use_bpm</span><span class="p">(</span><span class="mi">120</span><span class="p">)</span>

<span class="k">def</span> <span class="nf">play_sample_for_sequence</span><span class="p">(</span><span class="n">pattern</span><span class="p">,</span> <span class="n">sample_name</span><span class="p">,</span> <span class="n">sleep_time</span> <span class="o">=</span> <span class="mf">0.25</span><span class="p">)</span>
  <span class="n">pattern</span><span class="p">.</span><span class="nf">each</span><span class="p">.</span><span class="nf">with_index</span> <span class="k">do</span> <span class="o">|</span><span class="n">beat</span><span class="p">,</span> <span class="n">i</span><span class="o">|</span>
    <span class="n">sample</span> <span class="n">sample_name</span> <span class="k">if</span> <span class="o">!!</span><span class="n">beat</span>
    <span class="nb">sleep</span> <span class="n">sleep_time</span>
  <span class="k">end</span>
<span class="k">end</span>

<span class="n">uncomment</span> <span class="k">do</span>
  <span class="n">live_loop</span><span class="p">(</span><span class="ss">:hh</span><span class="p">)</span> <span class="k">do</span>
    <span class="n">with_fx</span> <span class="ss">:level</span><span class="p">,</span> <span class="ss">amp: </span><span class="mi">1</span> <span class="k">do</span>
      <span class="n">cue</span> <span class="ss">:heartbeat</span>
      <span class="n">play_sample_for_sequence</span><span class="p">(</span><span class="n">distribute</span><span class="p">(</span><span class="mi">11</span><span class="p">,</span> <span class="mi">16</span><span class="p">),</span> <span class="ss">:drum_cymbal_closed</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="n">live_loop</span><span class="p">(</span><span class="ss">:bd</span><span class="p">)</span> <span class="k">do</span>
    <span class="n">sync</span> <span class="ss">:heartbeat</span>
    <span class="n">play_sample_for_sequence</span><span class="p">(</span><span class="n">distribute</span><span class="p">(</span><span class="mi">5</span><span class="p">,</span> <span class="mi">16</span><span class="p">),</span> <span class="ss">:drum_bass_hard</span><span class="p">)</span>
  <span class="k">end</span>

  <span class="n">live_loop</span><span class="p">(</span><span class="ss">:sn</span><span class="p">)</span> <span class="k">do</span>
    <span class="n">with_fx</span> <span class="ss">:level</span><span class="p">,</span> <span class="ss">amp: </span><span class="mi">1</span> <span class="k">do</span>
      <span class="n">cue</span> <span class="ss">:heartbeat</span>
      <span class="n">play_sample_for_sequence</span><span class="p">(</span><span class="n">distribute</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span> <span class="mi">16</span><span class="p">).</span><span class="nf">to_a</span><span class="p">.</span><span class="nf">rotate</span><span class="p">(</span><span class="mi">4</span><span class="p">),</span> <span class="ss">:drum_snare_hard</span><span class="p">)</span>
    <span class="k">end</span>
  <span class="k">end</span>

  <span class="n">live_loop</span><span class="p">(</span><span class="ss">:bass</span><span class="p">)</span> <span class="k">do</span>
    <span class="n">with_fx</span> <span class="ss">:level</span><span class="p">,</span> <span class="ss">amp: </span><span class="mi">1</span> <span class="k">do</span>
      <span class="n">use_synth</span> <span class="ss">:tb303</span>
      <span class="n">cue</span> <span class="ss">:heartbeat</span>
      <span class="n">distribute</span><span class="p">(</span><span class="mi">3</span><span class="p">,</span> <span class="mi">8</span><span class="p">).</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">beat</span><span class="o">|</span>
        <span class="n">play</span> <span class="n">scale</span><span class="p">(</span><span class="ss">:a2</span><span class="p">,</span> <span class="ss">:minor_pentatonic</span><span class="p">).</span><span class="nf">choose</span><span class="p">,</span> <span class="ss">release: </span><span class="mf">0.3</span> <span class="k">if</span> <span class="n">beat</span>
        <span class="nb">sleep</span> <span class="mf">0.5</span>
      <span class="k">end</span>
    <span class="k">end</span>
  <span class="k">end</span>
<span class="k">end</span>
</code></pre></div></div>

<p>Here’s a demo of me live coding with the above:</p>

<iframe width="100%" height="166" scrolling="no" frameborder="no" src="https://w.soundcloud.com/player/?url=https%3A//api.soundcloud.com/tracks/187459917&amp;color=ff5500&amp;auto_play=false&amp;hide_related=false&amp;show_comments=true&amp;show_user=true&amp;show_reposts=false"></iframe>

<h2 id="why-does-this-work">Why does this work?</h2>

<p>Musically I think it’s fair to say that last example sounds pretty cool. But why? I think that the appeal of these rhythms (“Euclidean Rhythms” as Toussaint calls them) boils down to this: because the spacing is always even, when we layer these kinds of beats on top of each other we get strong “cross rhythms”. In the example above I’ve deliberately put the snare on beats 2 and 4 to provide a strong backbeat. All the other rhythms bounce off the strength of the snare rhythm.</p>

<p>I think another possible reason is that our brains enjoy patterns and order even if we can’t quite tell what the pattern is. Imagine the difference between two knitted jumpers, one with a completely random colour for every stitch, the other with a strong geometric pattern. Psychologically we’re more likely to prefer the geometric pattern (unless the random knit <em>happens</em> to be really cool).</p>

<p>Having these functions in our toolkit means that we can reach musical sounding results even faster, without having to rely on things being <em>totally</em> random but still retaining an element of surprise.</p>

<p>What do you think? Does it sound cool to you? Will algorithmic music ever be widely accepted? Hit me up on twitter @xavriley if you have any comments or questions.</p>

<h2 id="further-rhythming">Further rhythming</h2>

<p>This topic has already been covered in several other places, but not as far as I know in Sonic Pi yet. There’s a very cool HTML5/Javascript version of this kind of drum machine available at <a href="http://www.groovemechanics.com/euclid/">http://www.groovemechanics.com/euclid/</a> which has been on Hacker news. Also there’s a patch for Max called <a href="https://www.youtube.com/watch?v=14tw_DRev_4">Polyrhythmus</a> which is along the same lines. I wanted to cover the musical aspects behind the algorithm in a bit more depth for this post. There’s also a good Wikipedia page on <a href="https://en.wikipedia.org/wiki/Euclidean_rhythm">Euclidean rhythm</a> with links to other resources.</p>]]></content><author><name>Xavier Riley</name></author><category term="Sonic Pi" /><summary type="html"><![CDATA[Working with Sonic Pi one of the exciting things about being able to code music is the potential for using algorithms. For the non-technical reader, I like to think of algorithms like following a recipe. You might start with the same ingredients but the order in which you do things can affect to outcome.]]></summary></entry><entry><title type="html">Getting data from PDFs with JRuby</title><link href="https://www.xavierriley.co.uk/posts/2014/10/getting-data-from-pdfs-with-jruby/" rel="alternate" type="text/html" title="Getting data from PDFs with JRuby" /><published>2014-10-06T00:00:00-07:00</published><updated>2014-10-06T00:00:00-07:00</updated><id>https://www.xavierriley.co.uk/posts/2014/10/getting-data-from-pdfs-with-jruby</id><content type="html" xml:base="https://www.xavierriley.co.uk/posts/2014/10/getting-data-from-pdfs-with-jruby/"><![CDATA[<p>There are many solutions for getting data from pdfs. I’m going to describe how to use the excellent Java library PDFTextStream by Chas Emerick (of Clojure fame) to get data out of tricky pdfs.</p>

<p>## Why PDFTextStream?</p>

<p>Quite simply, it’s the best PDF extraction library I’ve come across in terms of features and performance. It handles layouts and formatting very well and the xml output gives some useful tags for data extraction.</p>

<p>### Getting the library</p>

<p>Head over to <a href="http://snowtide.com/downloads">http://snowtide.com/downloads</a> and download the latest Java version (2.7.0 at the time of writing) and unzip into a folder called <code class="language-plaintext highlighter-rouge">jruby-demo</code>.</p>

<p>### Some JRuby/Java interop</p>

<p>Create a file at <code class="language-plaintext highlighter-rouge">jruby-demo/pdf-extractor.rb</code> with the following contents:</p>

<div class="language-ruby highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="nb">require</span> <span class="s1">'java'</span>
 <span class="nb">require</span> <span class="s1">'json'</span>
 <span class="nb">require</span> <span class="s1">'PDFTextStream.Java-2.7.0/lib/PDFTextStream.jar'</span>
 <span class="vg">$CLASSPATH</span> <span class="o">&lt;&lt;</span> <span class="s1">'PDFTextStream.Java-2.7.0/src'</span>

 <span class="n">java_import</span> <span class="n">com</span><span class="p">.</span><span class="nf">snowtide</span><span class="p">.</span><span class="nf">pdf</span><span class="o">.</span><span class="no">PDFTextStream</span>
 <span class="n">java_import</span> <span class="n">com</span><span class="p">.</span><span class="nf">snowtide</span><span class="p">.</span><span class="nf">pdf</span><span class="o">.</span><span class="no">OutputTarget</span> <span class="c1"># To output plain text</span>
 <span class="n">java_import</span> <span class="s2">"pdfts.examples.XMLOutputTarget"</span> <span class="c1"># To output XML</span>
 <span class="n">java_import</span> <span class="n">java</span><span class="p">.</span><span class="nf">lang</span><span class="o">.</span><span class="no">StringBuilder</span>

 <span class="n">pdf_file_path</span> <span class="o">=</span> <span class="no">File</span><span class="p">.</span><span class="nf">join</span><span class="p">(</span><span class="no">Dir</span><span class="p">.</span><span class="nf">pwd</span><span class="p">,</span> <span class="no">ARGV</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>

   <span class="n">sb</span> <span class="o">=</span> <span class="no">StringBuilder</span><span class="p">.</span><span class="nf">new</span> <span class="c1"># Requires Java StringBuilder for some reason</span>
   <span class="n">pdfts</span> <span class="o">=</span> <span class="no">Java</span><span class="o">::</span><span class="no">ComSnowtidePdf</span><span class="o">::</span><span class="no">PDFTextStream</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">pdf_file_path</span><span class="p">)</span>

   <span class="k">case</span> <span class="no">ARGV</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span>
     <span class="k">when</span> <span class="s2">"xml"</span>
       <span class="c1"># XMLOutputTarget keeps the formatting tags of</span>
       <span class="c1"># the input PDF - useful if the source uses bold or italics etc.</span>
       <span class="n">ot</span> <span class="o">=</span> <span class="no">XMLOutputTarget</span><span class="p">.</span><span class="nf">new</span>

       <span class="n">pdfts</span><span class="p">.</span><span class="nf">pipe</span><span class="p">(</span><span class="n">ot</span><span class="p">)</span>
       <span class="n">pdfts</span><span class="p">.</span><span class="nf">close</span>
       <span class="nb">puts</span> <span class="n">ot</span><span class="p">.</span><span class="nf">getXMLAsString</span>
     <span class="k">when</span> <span class="s2">"standard"</span>
       <span class="c1"># Normal OutputTarget reformats the text to handle</span>
       <span class="c1"># column layouts</span>
       <span class="n">ot</span> <span class="o">=</span> <span class="no">Java</span><span class="o">::</span><span class="no">ComSnowtidePdf</span><span class="o">::</span><span class="no">OutputTarget</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">sb</span><span class="p">)</span>

       <span class="n">pdfts</span><span class="p">.</span><span class="nf">pipe</span><span class="p">(</span><span class="n">ot</span><span class="p">)</span>
       <span class="n">pdfts</span><span class="p">.</span><span class="nf">close</span>
       <span class="nb">puts</span> <span class="n">sb</span><span class="p">.</span><span class="nf">to_s</span>
     <span class="k">when</span> <span class="s2">"visual"</span>
       <span class="c1"># VisualOutputTarget is better at preserving layout in</span>
       <span class="c1"># the conversion to text e.g. tables</span>
       <span class="n">ot</span> <span class="o">=</span> <span class="no">Java</span><span class="o">::</span><span class="no">ComSnowtidePdf</span><span class="o">::</span><span class="no">VisualOutputTarget</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">sb</span><span class="p">)</span>

       <span class="n">pdfts</span><span class="p">.</span><span class="nf">pipe</span><span class="p">(</span><span class="n">ot</span><span class="p">)</span>
       <span class="n">pdfts</span><span class="p">.</span><span class="nf">close</span>
       <span class="nb">puts</span> <span class="n">sb</span><span class="p">.</span><span class="nf">to_s</span>
     <span class="k">else</span>
       <span class="c1"># VisualOutputTarget is better at preserving layout in</span>
       <span class="c1"># the conversion to text e.g. tables</span>
       <span class="n">ot</span> <span class="o">=</span> <span class="no">Java</span><span class="o">::</span><span class="no">ComSnowtidePdf</span><span class="o">::</span><span class="no">VisualOutputTarget</span><span class="p">.</span><span class="nf">new</span><span class="p">(</span><span class="n">sb</span><span class="p">)</span>

       <span class="n">pdfts</span><span class="p">.</span><span class="nf">pipe</span><span class="p">(</span><span class="n">ot</span><span class="p">)</span>
       <span class="n">pdfts</span><span class="p">.</span><span class="nf">close</span>
       <span class="nb">puts</span> <span class="n">sb</span><span class="p">.</span><span class="nf">to_s</span>
   <span class="k">end</span>

</code></pre></div></div>

<p>### Extracting some text</p>

<p>Move a pdf into the folder, install jruby and then run:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code> <span class="nb">cd </span>jruby-demo
 jruby pdf-extractor.rb name-of-your-pdf.pdf standard
</code></pre></div></div>

<p>and after a few seconds of jvm warm up time you should start to see text on STDOUT.</p>

<p>### Different extraction modes</p>

<p><code class="language-plaintext highlighter-rouge">standard</code> - This handles column layouts (common in pdfs) and reflows them to make sure the text reads in the correct order.</p>

<p><code class="language-plaintext highlighter-rouge">visual</code> - This preserves the text spacing on the page which is useful for tabular data.</p>

<p><code class="language-plaintext highlighter-rouge">xml</code> - If the source data has bold or italic text, this processor outputs xml markup which can be useful for further processing with Nokogiri or other similar libraries.</p>]]></content><author><name>Xavier Riley</name></author><category term="ruby" /><category term="archive" /><summary type="html"><![CDATA[There are many solutions for getting data from pdfs. I’m going to describe how to use the excellent Java library PDFTextStream by Chas Emerick (of Clojure fame) to get data out of tricky pdfs.]]></summary></entry></feed>