{
  "version": "https://jsonfeed.org/version/1.1",
  "title": "CelestialSynapse",
  "home_page_url": "https://www.celestialsynapse.xyz",
  "description": "Personal blog of CelestialSynapse",
  "authors": [],
  "items": [
    {
      "id": "https://www.celestialsynapse.xyz/2026-10-10-migration-to-makko.html",
      "url": "https://www.celestialsynapse.xyz/2026-10-10-migration-to-makko.html",
      "title": "Migrating my blog to Makko",
      "summary": "I migrated from Jekyll + Chirpy to Makko, it's worth it.",
      "contents": "My first website was Jekyll-powered\nWhen I was finishing my Master's degree, around 2024, I thought it would be a\ngood thing to have a personal website. Something like a browsable resume of\nsorts. I think at the time I was more interested in how it could carry me\nprofessionally than anything else. So I started experimenting with what was\navailable on the github pages. I found Jekyll and, after a bit more searching,\nthe Chirpy theme. It worked quite well, it was a modern webpage and, for what\nI needed at the time was good.\nSlowly, the project became a personal blog, under my civil name. I was torn\nbetween writing what I wanted to write and knowing that it would follow me in\nmy academic and professional life. And that made me quite uncomfortable.\nI still wrote a few articles, here and there, but little by little, the aim\nshifted, from a very professional page to a more personal blog. The change\nmostly occured when I order my domain name. Suddenly, this weird\npersonal/professional coupling became an irreconcilable clash. I wanted a\nspace that was more me. This would result in both trying to remove most\nmentions of my actual name and trying to get a more custom render.\nFalling out of love with Jekyll\nAnd here's where Jekyll + Chirpy sucked. The project is such a heavy soup of\ndiv inside div inside more wrapper div that it's basically impossible\nto patch the theming or templating without putting heavy work in understanding\nthe structure of the theme.\nWhat's more, it's very feature packed. CDN support, analytics integration,\ncomment integration, Javascript everywhere. I didn't need any of that. In fact,\nI value lean websites. Sites that go straight to the point. Projects that can\nbe the love-child of one determined individual without months of experience in\nwebdesign, Liquid, SCSS, JQuery, and all that. Many\nneocities websites capture this simple (and retro)\nvibe and, while I'm not great at design in general, I'd be fine with a simpler\nstructure.\nLooking for alternatives\nRealistically, what did I need? I wanted to:\n\nwrite articles in Markdown. I don't want to bother with HTML when writing.\nhave some sort of converter that generates HTML from the Markdown\ngenerate a homepage with the links to the articles\nhave a RSS/Atom feed containing the contents of the document\nsupport math and code\n\nThe hard part seemingly is the Markdown to HTML conversion. I know Pandoc can\ndo it moderately well while also converting the inlined LaTeX. And so, for a\nwhile, I thought about making my own static website generator. I debated how I\nwould make it, starting with &quot;What language should I design it in?&quot; The easy\nanswer is Python, I know it quite well. But I don't like the direction (cough\ncough AI cough cough) the language is taking and am always looking for new\nskills to learn. So I was thinking about Perl, Rust or Zig.\nHeaven-sent Makko\nOne day, as I was browsing Fedi, I found a post of someone asking for\nrecommendations about static website generators and Makko got mentioned. I took\na look and, what was my surprise when it looked like exactly what I wanted to\ndo, but already done.\nI'm not one to reinvent the wheel, especially on projects which seem to share\nmy values, so I took the pink rabbit software for a spin. With very little\nmodification of the YAML front matter, Makko generated a very decent draft of\nwhat I wanted. Everything is simple. Simple HTML, simple sample CSS and\ntemplates, no Javascript. It was such a breath of fresh air.\nI quickly realized that, for all its qualities, Makko had two main issues for me:\n\nLaTeX was not rendered\ncode is not highlighted\nRSS/Atom/JSON feeds don't get populated with the contents of the articles\n\nThe next sections on how I fixed these issues are re-narrated versions of the\nREADME of the website\nsource.\nPost-processing articles\nLooking through Makko's documentation, I see that there are callbacks called\nwhen articles are created, edited, etc. Based on what the project's site is\nshowing, I don't think it's really meant to edit the files, moreso to help with\ndeployment, version management and other administrative tasks.\nWithout any care for the intended usecases, I hack away a couple of Python\nscripts leveraging LaTeXML and\nPygments to render LaTeX to MathML (which should be\nbetter for accessiblity than a SVG with alt text, in addition to being lighter\nin ressources) and highlight code blocks.\nCode highlighting\nSee source code here\nParsing HTML is a complicated task. Tokenizing who knows how many languages to\nhighlight keywords as well. So, we delegate. beautifulsoup4 makes parsing HTML\nand navigating the DOM a breeze while pygments has so many lexers, added with\na HTML formatter, it would be silly to redo everything.\nI'm not a big fan of pygments however, for the simple reason they seem to be\nvery chill with AI usage for their codebase. I don't know of any other library\nthat does what pygments does however, so I guess we're stuck with it for now.\nLaTeX to MathML rendering\nSee source code here\nConverting the LaTeX to MathML is not the difficult part. Well, it should be,\nbut thanks to the magic of reusing software, we can delegate that to the\nLaTeXML project. We need only to find the math blocks.\nSince the input I have at this point is the HTML file rendered by Makko, the math\ncontents is stored in &lt;x-equation&gt; tags, with a type=&quot;display option for block\nequations.\nAnd so, I find all the opening tags (of both kinds) and the closing tags using\nregular expressions (even though, given that there are exactly three fixed\npatterns we are looking for, there could have been simpler ways to do the\nlookup), ensure no tomfoolery takes place (such as mismatched tags) and sort\nall the code that isn't &lt;x-equation&gt; tags in either &quot;generic&quot;, &quot;equation&quot; or\n&quot;block equation&quot; types, with their order of appearance.\nFinally, all equation and block equation get converted as they should and\ninserted back into the HTML file. Writeback everything and bingo.\nThe only &quot;problem&quot; with this approach is that using latexmlmath to render one\nequation at a time takes a long time. Every call of latexmlmath does a lot of\ncostly LaTeX engine initialization. It would be faster to make one LaTeX file\nwith all the equations, convert to MathML and extract the equations back. But\nhonestly, I don't mind waiting 30 seconds for the generation of one page once\nin a while so I'm fine with it.\nPatching Makko to get posts contents in Atom feeds\nHere's the big, scary part. Hijacking the feed generation process to include the\ncontents of the articles in the feeds. It's probably doable to do something with\ncallback scripts, but I leave that exercise to someone else, no thanks.\nIt was my first time reading or coding in Zig. And what a pleasure it was. It feels\nclean and sober, I respect that and will probably take some more time in the future\nto delve deeper in the language.\nThe good thing is that the feed generation functions already have the body of\nthe articles passed to them. So, we just add a &lt;contents&gt; tag, fill it in\nwith the XML-escaped version of the article and roll with it, right?\nNot so fast! The problem with including HTML in feeds like these is that not\nevery feed reader will parse it as such and you end up with text that's\ndifficult to read. Even morseo when the escaped character are not interpreted\nback. That's the case of the reader I use\n(newsraft). And, in general, plain\ntext is just more compatible. For stuff like images, links, tables etc, the\nfull webpage is still there.\nSo, I decided to simply strip all HTML tags before including the post contents\nin the feed. I don't do any kind of typesetting based on the tags, I don't\nextract links or alt text or anything. I wanted something simple. With that\nin mind, I only need to check whether a character is part of a tag or not.\nThe implementation is done with a 2-state stack automaton. Basically, we read\nevery character one by one and depending on what character we read and what\nstate we're in, we can do any of these:\n\nchange state\npush the character onto the stack\nwrite the character on the output\n\nThe three states are:\n\nNormal\nTag: After a &lt; and before &gt;\n\nIn a normal state:\n\non a &lt;, move to the Tag state\nelse, write the character to the output\n\nIn a Tag state:\n\non a /, move to the TagEnd state while adding / to the stack\non a &gt;, move to the Normal state and empty the stack\nelse, add the character to the stack\n\nIn practice, the code I implemented checks for nested tags (structures like\n&lt;some text &lt;/why would this happen&gt;&gt;), but this is not valid HTML so I didn't\ninclude it in this explaination.\nWe could make the state machine a bit more complicated to keep track of:\n\nthe opening tags\nthe closing tags\nthe singleton tags\nand check that the tags open/close properly, while taking different actions\nbased on the different tags, but this is out of the scope of this project.\n\nWith the HTML tag stripper in place, the contents of the posts can now by\nincluded in the feeds!\nStyling the website\nHomepage layout\nIf there was one thing about the Chirpy style I liked, it was the sidebar with\nthe avatar. So I extended on this idea to add a little bio and some credits.\nI spent way too much time trying to fiddle around the layout to make it look good\non both wide and narrow devices. In the case of narrow devices, I wanted to bio\nto go above the article list and the credits to go below.\nThe solution I ended up with is to have a grid layout which changes on\n@media all and (max-width: 700px).\nConclusion\nAll in all, this is about a week worth of tinkering. I'm quite happy with the\nresults (except with making it work with NixOS, but that's probably a me\nproblem and the topic of another post). Makko is a great tool. Its simplicity\nmeans it's so much more customizable. I really enjoyed working on extending it\nfor my purposes and will probably look to contribute to the project once in a\nwhile as well!\n",
      "date_published": "2026-10-10T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    },
    {
      "id": "https://www.celestialsynapse.xyz/2026-08-03-asyncio-cookbook.html",
      "url": "https://www.celestialsynapse.xyz/2026-08-03-asyncio-cookbook.html",
      "title": "Overengineering sharing one byte of information using async I/O over multiple protocols",
      "summary": "Real-life simple examples of asyncio programming in Python.",
      "contents": "A fun and useful project for a hackerspace is to be able to share whether the\nspace is openned or closed to the public at any given time.\nAt hackens, it's an idea that fermented for a while\nand I somehow ended up writing most of the communication code. It's 100% a\nplumbing project, so I'll at least try to make it worthwile.\nWhile looking online to learn about how to use asyncio, I mostly found\nexamples so minimal I struggled to see how they would fit in a real project.\nWading through the documentation, with a bit of trial and error, I learned a\nlot about asynchronous programming, from a client and server perspective, and I\nhope to give some insight into how some elements of the asyncio module in\nPython can be used in real-world examples.\nI will assume you have some notion of asynchronous computation, including what\nis a coroutine and how it differs from regular callables, and what is an event\nloop. If needed there's a quick refresher at the end.\nProject overview\nFirst, let me describe the overall architecture of the system. It's not too\ncomplicated, but there are just quite a few elements here. If you want to look\ninto it further, all the code for the project is publicly available on a git\nforge.\nThe data flows downstream, from the sensors, to a central orchestrator, to local\nnetwork clients and to the exterior through a proxy server.\n\nThe sensors do not do any computation, instead they send the raw data to the\norchestrator through a serial connection, which parses it, interprets it, and\nreturns a status (open/closed, forced/not forced) to the sensor box to\nindicate the status through a LED.\nThe orchestrator also publishes the status to all the registred clients. Currently,\nthis includes an ESP-32 at the entrance of the space which turns on a LED strip\nwhen the space is open, and a proxy server. Since the ESP-32 is on the same local\nnetwork, we chose to connect through a socket, and the connexion to the proxy\nserver is done through a (authenticated) websocket.\nSince there are only a few clients, the IO there is done synchronously. But,\nbecause we want to react to a change in the state without stalling the system and\nby sharing the change as soon as possible, I opted for an async protocol for\nthe serial connection.\nNow, the proxy server exposes one public websocket, which can have many clients\nconnected to it. This socket is purely one-directional: clients can't make requests\nto the server, they have to listen. Because of this, we opted for an async server\ndesign here.\nasync websockets: the easy part\nThe relevant part of the project is available\nhere.\nWe'll start with the proxy server. It's as simple as possible, one websocket\nlistens to the orchestrator to get the current status, and another publishes\nthe state.\nPython's websocket module,\nwebsockets has a very good\nasync workflow, taking a coroutine (that deals with one connection) and\ncreating another one (that deals with all connections throughout the life of\nthe server). It is then a matter of defining the desired behavior and\nscheduling the execution of the server. In its most simple form, it is built\nlike this:\nfrom websockets.asyncio.server import serve\nserver = await serve(\n  server_fn,\n  hostname,\n  port,\n  **kwargs\n)\n\n# Now, schedule `server.serve_forever()` for execution\n\nwhere server_fn is a coroutine with the signature server_fn(connection) -&gt; None.\nHere is the important bit: nothing will not run right now. We simply defined\nan object containing all the info needed. In order to actually run the server,\nwe need to:\n\nget a coroutine that handles the connections (e.g. server.serve_forever())\nschedule that coroutine\n\nBy defining several coroutines and scheduling them as tasks (typically using\nthe asyncio.TaskGroup mechanism), we can have multiple servers running\nconcurrently.\nSimply put, we have code that looks like this:\nimport asyncio\nfrom websockets.asyncio.server import serve\n\nasync def main():\n  listener = await serve(\n    listen_fn,\n    hostname_l,\n    port_l,\n    **kwargs_l\n  )\n  speaker = await serve(\n    speak_fn,\n    hostname_s,\n    port_s,\n    **kwargs_s\n  )\n\n  async with asyncio.TaskGroup() as tg:\n      tg.create_task(listener.serve_forever())\n      tg.create_task(speaker.serve_forever())\n\nasyncio.run(main())\n\nasyncio.Protocol-based subscribe/publish server\nThe relevant part of the project is available\nhere.\nThe orchestrator has the main challenge of dealing with serial connections, for\nwhich we don't have as nice an interface as for websockets. The module we use\nis serial_asyncio. If you\ndon't already know what you're doing, the documentation can be quite\nlackluster, basically telling you to write your own\nprotocol (factory).\nWhile it's presented mainly as a way to handle TCP/UDP/whatever network\nprotocol you want, at its core, an asyncio.Protocol is a way to do callbacks\non a connection. The actual detail of how the data is sent is not the job of\nthe protocol, but of its associated asyncio.Transport object, which will not\nbe covered here. The only thing you need to know about the Transport objects\nis that they have a reference to the underlying event loop and handle all the\nscheduling of I/O tasks, including of the callbacks defined in the Protocol.\n\nSince all the loop.call_{soon,later,...} methods take a callable (instead of\nthe coroutines we're used to now), the callbacks defined in Protocol are\nindeed functions, despite still being part of an asynchronous I/O pipeline.\n{: .prompt-info }\n\nBy writing your own protocol, you can customize the behavior when:\n\nthe connection is created (connection_made)\ndata is received (data_received, eof_received)\nthere is an interruption (pause_writing, resume_writing)\nthe connection is lost (connection_lost)\n\nFor us, the purpose of the protocol we implement is to:\n\nparse the incoming data\ntrigger a broadcast when a state change is noticed\n\nBasically, we want to override the data_received method and follow the\nrecipe given by serial_asyncio. So, that's what we do:\nimport asyncio\nimport serial_asyncio\n\n###############################################################################\n# Defining the protocol\n\nclass MyProtocol(asyncio.Protocol):\n  &quot;&quot;&quot;Splits data per line and processes each line individually.&quot;&quot;&quot;\n  def __init__(self):\n    self.buffer = &quot;&quot;\n\n  def data_recieved(self, data: bytes):\n    self.buffer += str(data, encoding=&quot;utf-8&quot;)\n    if &quot;\\n&quot; in self.chunk:\n      messages = self.chunk.split(&quot;\\n&quot;)\n      self.chunk = messages[-1]\n      self.process(messages[:-1])\n\n  def process(self, messages: list[str]):\n    # Do stuff here\n\n\n###############################################################################\n# Instanciating and running the protocol\n\n# Replace with asyncio.get_event_loop if needed\nevent_loop = asyncio.new_event_loop()\n\nasync def reader():\n  transport, protocol = await serial_asyncio.create_serial_connection(\n    event_loop,\n    MyProtocol,\n    serial_port,\n    baudrate=115200,\n  )\nevent_loop.run_until_complete(reader())\nevent_loop.close()\n\nNow, we have the structure of the reader server. But how do we trigger\nside-effects? Well, serial_asyncio.create_serial_connection takes a protocol\nfactory. So, we can just hide any and all arguments inside a lambda, with\nsomething that looks like:\nclass MyProtocol(asyncio.Protocol):\n  def __init__(self, arg):\n    self.thing = arg\n\n  def process(self, messages):\n    self.thing.do_whatever(messages)\n\n  ...\n\n  transport, protocol = await serial_asyncio.create_serial_connection(\n    event_loop,\n    lambda: MyProtocol(arg),\n    serial_port,\n    baudrate=115200,\n  )\n\nIn practice, we have a State class that stores the current state and signals\nthe clients to broadcast whenever a change occurs. The specifics of broadcaster\ndepends on which clients are registered and don't really matter here.\nIf you're curious, the concrete implementation is\nhere\nSo, in the end, we have:\nimport asyncio\nimport serial_asyncio\n\n###############################################################################\n# Defining the state keeper\n\nclass State:\n    def __init__(self, broadcaster: Broadcaster):\n        self._current_status = OutsideStatus.CLOSED\n        self.broadcaster = broadcaster\n\n    @property\n    def current_status(self) -&gt; OutsideStatus:\n        return self._current_status\n\n    @current_status.setter\n    def current_status(self, val) -&gt; None:\n        if self._current_status != val:\n            self._current_status = val\n            self.broadcaster.broadcast(self._current_status)\n\n\n###############################################################################\n# Defining the protocol\n\nclass MyProtocol(asyncio.Protocol):\n  &quot;&quot;&quot;Splits data per line and processes each line individually.&quot;&quot;&quot;\n  def __init__(self, state: State):\n    self.buffer = &quot;&quot;\n    self.state = state\n\n  def data_recieved(self, data: bytes):\n    self.buffer += str(data, encoding=&quot;utf-8&quot;)\n    if &quot;\\n&quot; in self.chunk:\n      messages = self.chunk.split(&quot;\\n&quot;)\n      self.chunk = messages[-1]\n      self.process(messages[:-1])\n\n  def process(self, messages: list[str]):\n    new_status = self.get_stats_from_messages(messages)\n    self.state.current_status = new_status\n\n\n###############################################################################\n# Instanciating and running the protocol\n\n# Replace with asyncio.get_event_loop if needed\nevent_loop = asyncio.new_event_loop()\nstate = State(broadcaster = ...)\n\nasync def reader():\n  transport, protocol = await serial_asyncio.create_serial_connection(\n    event_loop,\n    lambda: MyProtocol(state),\n    serial_port,\n    baudrate=115200,\n  )\nevent_loop.run_until_complete(reader())\nevent_loop.close()\n\nNow, I mentionned that, because in our case we know the subscribed clients, that\nthere are only a handful of them, we do not need to have the broadcast itself\nbe asynchronous.\nIf we wanted to go a step further and actually have the broadcast itself be\nasynchronous, I think a way to do it would be to:\n\nhave self.broadcaster.broadcast be a coroutine (details depend on the\nunderlying connection),\npass the event_loop object to the state\nreplace self.broadcaster.broadcast(...) by\nevent_loop.create_task(self.broadcaster.broadcast(...)\n\nConclusion\nThis was a very technical article, more than I usually like to write, but I\nfigured some simple but actually useful examples of using asyncio in\ndifferent contexts are always useful to have around.\nWriting the code for this project, I had to rethink the architecture quite a\nfew times to accomodate for the async pipeline, which is not something I\nusually care for. Hopefully, with these examples in mind, you can get some idea\nof how to structure a project around these IO tasks, whether by having a\nserver-based or a protocol-based architecture.\nAsync refresher\nTraditionally, we think of programs as a list of instructions being ran from top\nto bottom, one after another, in a well specified order. This has the benefit\nof being easier to write and more predictible. But it has the drawback of\npotentially waiting on IO bound tasks.\nAsynchronous programming, for the most part, is designed around finding a way\nnot to wait while there is still something else to be done. A typical example\nis a web server. If a server has several clients to serve, you could:\n\nsend a ressource to client 1\nwait that client 1 acknowledges\nsend a ressource to client 2\nwait that client 2 acknowledges\nbe happy that both clients are served\n\nOr, you could reorder the operations and:\n\nsend a ressource to client 1\nsend a ressource to client 2\nwait that both clients 1 and 2 acknowledge\nbe happier that both clients are served at more or less the same time\n\nIn other words, if you have two letters to send, you can either wait for the\ndelivery notice before sending the next one (synchronous case) or send both\nletters at the same time and wait only once for the delivery notices. In\nparticular, if something went wrong and the first letter took forever to\ndeliver, we don't have to wait to send the second letter, and both letter\ndelivery times are uncorrelated.\nBut how do we do this in practice? Well, we schedule, much like an operating\nsystem schedules which process to run at any given CPU cycle. Essentially,\nour program is a big loop that looks like this pseudocode:\nwhile True:\n  new_task = select_task_to_run()\n  execute_a_bit(new_task)\n\nThat loop is called an event loop. It's the brain of the operations. You, as\nthe programmer, will interact with this loop by creating coroutines and\nscheduling them.\nA coroutine is a partially ran function, and is defined like so:\n\nasync def send_letter():\n  print(&quot;Sending letter.&quot;)\n  await async.time(1)\n  print(&quot;Letter has been received!&quot;)\n\ncoro = send_letter()  # &lt;-- this is a coroutine\n\nWhen defined, a coroutine doesn't do anything. It's because it has not been\nscheduled yet. To schedule a coroutine, you can do it in several ways:\n\nimplicitely inside another async block using the keyword await\nexplicitely by using any high-level function like asyncio.run or low-level\nmethods of the event loop.\n\nThe await keyword is a fence, the execution can't go further without having\nexecuted what's behind. You ask the program to wait until the instruction is\nfinished to continue. But this doesn't mean that unrelated tasks can't run at\nthe same time, and that's the magic of it!\nIf we continue our example, send_letter prints a first message and waits for\n1 second before printing a message. If we only run this once, it's not much\ndifferent from having a synchronous code. However, if we run it several times\nin quick succession, it's like the letter example, we will send multiple\nexecutions at once and all the prints will arrive more or less at the same\ntime.\n\nasync def main():\n  coros = [send_letter() for _ in range(5)]\n  tasks = [asyncio.create_task(coro) for coro in coros]\n  for t in tasks:\n    await t\n\nif __name__ == &quot;__main__&quot;:\n  asyncio.run(main())\n\nIf we run this code, the output will be:\nSending letter.\nSending letter.\nSending letter.\nSending letter.\nSending letter.\nLetter has been recieved!\nLetter has been recieved!\nLetter has been recieved!\nLetter has been recieved!\nLetter has been recieved!\n\nWhat we did here is, first, create a new coroutine (main) which:\n\nget 5 coroutines of the same function\nschedule their execution (using the task mechanism)\nwait for all tasks to finish before returning\nAnd finally, execute main (asyncio.run).\n\nUnder the hood, asyncio manages the event loop so you don't have to think\nabout it and have a nicer interface to work with.\nThat's all for the refresher on async programming in Python, now go back to the article!\n",
      "date_published": "2026-08-08T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    },
    {
      "id": "https://www.celestialsynapse.xyz/2025-11-17-Volume-normalization.html",
      "url": "https://www.celestialsynapse.xyz/2025-11-17-Volume-normalization.html",
      "title": "Volume normalization in music streaming services",
      "summary": "Studying the effects of volume normalization on audio quality.",
      "contents": "A while back, I started listening more to music with CDs. I've always been an avid enjoyer of music and I want to support artists as best I can so buying CDs during shows is something I like doing.\nBut then, something struck me, the music sounded better, way better, on CD compared to Tidal, which is supposed to deliver lossless, 16 bit per sample, 44.1kHz recordings, the same standard as CDs. With a bit of fiddling around the settings, I tried to remove the volume normalization option, and golly gee, the richness and the warmth came back.\nBut then why? I figured I needed an experimental setup to check what happens. Here's the rough idea:\nFirst, record the output of CD recording, Tidal lossless with volume normalization and Tidal lossless without volume normalization.\nThen, import these recordings in Python and take a look at the distribution of power in the different frequency bands across time.\nRecording\nTo perform the recording, since only my desktop Windows machine has a CD player, I used it. With Audacity, it's not too bad, you can put loopbacks using the WASAPI interface.\nThe most important part is to record both with and without volume normalization using the same sound settings. Same volume everywhere so as not to introduce any bias. We also want to try to have settings that match as best we can for the CD recording.\nAnother trick that will help us down the line is to record some silence before the actual recording. Since we will be recording the same audio file, it will be the same length so syncing the start is the only thing we need to worry about and having some silence is an easy way to get that.\nLooking at the recordings directly, the main difference we see is the magnitude of the signal. Whether this is the reason of the degraded sound quality or not is something we'll investigate next.\nOnce everything is recorded, you can export in Audacity. It has an option to export per track and cut the leading silence so everything is very easy. As a format, I chose WAV with 16bit PCM, 44.1kHz.\nAnalysis\nCool, we have our data. Now we can analyze it. I use Python because it's what I know best, but the principles can apply elsewhere too. For reference, the track I used for this analysis is Bomb.com from RedHook, from the album Mutation, which is quite an energetic track, with loud drums, vocals, guitar and bass as well as some electronic parts, with loud and some more quiet parts.\n\n\nWaveform and instantaneous power (smoothed over 1sec) of the recording we study in this section\nFor importing the files, scipy.io.wavfile.read is a very good interface, it gives the sampling rate and the data in the form of a numpy array, with both channels.\nFor analyzing, I used scipy.signal.ShortTimeFFT, with a 1024-length Hamming window, 256 hop. Then, extract the spectrogram, convert it to dB: A_{dB} = 20\\cdot\\log A, clipping at -200dB (10^-10 amplitude) for numerical stability.\nLooking at the spectrograms directly, nothing is striking directly. But when looking at some higher-frequency harmonics, it seems to fade faster in the volume-normalized recording.\nOne thing I'm used to doing (mainly because it's what we do when working on brain waves), is to cut the signal in different frequency bands and study how they relate to each other.\nFor the human hearing, we usually think of &quot;bass&quot; (&lt;250Hz), &quot;mid&quot; (between 250Hz and 4kHz) and &quot;treble&quot; (&gt;4kHz). I needed something a bit less coarse so I settled on this division.\nArguably it's very arbitrary and we don't really care that much about the exact thresholds, but it will give us a base that is sensible enough.\nWith this in mind, we can compute the average power in each band for the different recordings and see if there is something different.\n\n\nPlot of the relative difference between the relative power of each frequency band without and with volume normalization.\nEach row is a different frequency band. Positive values mean that the recording without volume normalization has more relative power in this frequency band.\nWhat we could expect if the volume normalization operation is a simple rescaling of the signal, without modulation across time, would be a (near-)footnote1zero difference in all frequency bands, as we are looking at the relative power in each frequency band. The overall power may change, but not its distribution across frequencies.\nWe see differences of about 1-3% depending on the frequency band. The interesting result is that:\n\nfor ranges 20-4kHz (sub-bass to mid-range), the volume-normalized recording is stronger\nfor the lower and higher ranges, the non-volume-normalized recording is a bit higher\nat certain parts of the music, the non-volume-normalized recording has peaks in both low- and high-range frequency\n\nSo, what this means is that, in practice, volume-normalization tends to smother the ends of the spectrum, leading to a more muffled sound. The effects are not super big, but enough to be noticeable with some decent equipment (even a 80$ bluetooth headset can make the difference).\nLet's take another approach to confirm what we see here. Instead of comparing the relative power of frequency bands, we can compute the gain on each frequency band (instead of doing (P_1 - P_2) / P_1, we do P_2/P_1, and express the result in dB).\n\n\nComparison of the gain of different frequency bands.\nThis plot is a bit dense, so let's break it down.\nThe top square of plots features:\n\nin the diagonal, the gain for this frequency band (lower value means more attenuation after volume normalization);\nin the top-half, the difference between the gains of different frequency bands (the difference is lower frequency - higher frequency);\nin the bottom half, the same difference, but smoothed in time over 20ms.\n\nThe bottom rows show the maximum difference of the gain for this frequency band and all the others.\nRaw for the top one, smoothed over 20ms for the bottom one.\nWhat we're tying to get here is if some frequency band gets sacrificed for another and if so, when. Interestingly, some of the big changes happen when the music shifts from loud to quiet and vice-verse, but not always. Lower frequencies respond more to these big changes than mids and treble.\nWhat this ultimately means and what we can deduce from the underlying algorithm is a bit out of reach right now, but it's nonetheless an interesting observation.\nReproducibility\nNow, it's all well and good to do this on one track, but we can gather data for more recordings, of different styles.\nThe next tracks I will analyze will be the following:\n\n\n\nTitle\nAlbum\nArtist\nGenre\n\n\n\n\nAltered Perspective Two\nAlone\nEvan Brewer\nInstrumental\n\n\nMuma\nAD:Trance 10\nNhato\nTrance\n\n\nMARVYN\nMARVYN\nChangeline\nRap\n\n\nNon, je ne regrette rien\nPlatinum Collection\nÉdith Piaf\nFrench oldie\n\n\n3 Gyménopédies: No. 1, Lent et Douloureux (Orch. Ducros)\nÉmotions\nGautier Capuçon\nClassical\n\n\n\nThey are chosen quite arbitrarily, but the aim is to get titles which are quite different to get at least somewhat of a decent sample. Let's show the results below, quickly. For each title, I'll show the three same figures as before, and I'll draw a global conclusion after.\nAltered Perspective Two\n\n\n\n\n\n\nMuma\n\n\n\n\n\n\nMARVYN\n\n\n\n\n\n\nNon, je ne regrette rien\n\n\n\n\n\n\nGyménopédies\n\n\n\n\n\n\nConclusion\nFrom all these recordings, we can confirm that there is some change in the sound. The effect is roughly the same on every recording, a change in 1~5% of the relative power of the frequency band due to the volume normalization.\nIt also seems to be sensitive to the overall power of the track: patterns in the power are preserved in the effect we see from volume normalization. In particular, quiet parts seem to have their treble boosted and their bass lowered, and vice-versa.\nI wanted to include some personal notes from my listening of these tracks as well. People who've been next to me when I listen to music can attest as such, I usually listen to music very loud in my headphones. I know it's not great, but it's not the topic. Listening to music very loud often means contending with the limits of what my headphones can accurately render, and having some saturation going on. I was half-expecting that wuth volume normalization, because the waveform is ~2x as energetic as witout, saturation would go away. But as a matter of fact, for some tracks it got worse! I think the worst was for MARVYN. I know my headphones mostly saturate on high-frequencies, so the increase in treble due to the volume normalization really explains why it was so painful to listen to this way.\nInterpretation\nAn idea as to why quiet parts have their trebled empowered while their bass is dimished is psychoacoustics. The human ear does not process all frequencies the same. After all, we're mainly &quot;designed&quot; to react to human speech and nature sounds, which lie mostly in the mids. So, psychoacoustic research gives us some insight as to how sensitive we are to some frequencies compared to others. The subject is quite vast, and prone to refinements ad infinitum, so we'll only consider one aspect of it: equal-loudness contours.\nDefined in the ISO 226 norm, equal-loudness contours basically give us a set of (frequency, air pressure level in dB) that &quot;all seem as loud as each other&quot;. The exact details of the definition doesn't really matter here, what does matter is that we tend to percieve bass as not very loud and high-mids/treble as quite loud. The contour changes a bit of shape depending on the loudness level we consider as well, we are less sensitive to changes in bass for example.\n Equal loudness contours as defined in the ISO 226 norm. Image from Wikimedia\nAll this is coherent with the decisions made by engineers when they designed the volume normalization. By choosing not to reduce the intensity of the signal uniformly across all frequencies, but to adjust to the loudness of the current part of the song, we can artificially make the track seem louder or quieter than it actually is.\nIt's quite clever, but it introduces one major artifact: harmonics distortion. As you may know, a single sound has a specific fundamental frequency and harmonics (integer-multiple of the fundamental). So, a piano and a guitar may play a 440Hz A, both will have the same fundamental but different harmonics.\nHere's the issue, if you choose to scale one frequency band differently than another, it means that the harmonics will be changed as well. In our case, it's not changed enough to really change how we interpret the sound, but it can make it seem a bit different. Less warm, less full, more restrained... It's very qualitative and subjective, so I will let you give the words that feel adequate for your experience.\ntl;dr: my guess is that the volume normalization tries to take into account some psychoacoustics to trick the ear into having a similar loudness with a more constrained waveform, but messes with the harmonics in the process.\nConclusion\nWhile the exact algorithm of volume normalization is unclear and properly reverse-engineering it is way out of league -- whether thinking time, motivation or skills -- it is quite clear that it changes the feel of the music. This is due to a change in the relative power of the different frequency bands, treble is heightened during quiet parts and bass is heightened during loud parts.\nIn my experience, I had mixed results when it comes to listening to music with and without volume normalization. With proper sound equipment (a half-decent headset counts here), I think removing the option improves the quality of the sound. Without such equipment, such as when listening directly on the speaker of a phone, I found that enabling volume normalization on the contrary helped quite a bit to avoid saturation.\nI think the option is there for a reason. I would argue that it's not really well labeled and it's quite unclear what it does from the context of the app. But please try with and without the option for your favorite music, you'll hear a difference and you can choose which setting fits you best.\nSource code\nAll the souce code is available on my GitHub.\n\n\n\n\nEven in this case, we may see some fluctuations because both recordings are encoded on 16 bit integers. Reducing the amplitude means reducing the precision, so there's some &quot;bit-noise&quot; thrown in there as well.\n\n\n",
      "date_published": "2025-11-17T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    },
    {
      "id": "https://www.celestialsynapse.xyz/2025-10-19-hash.html",
      "url": "https://www.celestialsynapse.xyz/2025-10-19-hash.html",
      "title": "Shuffling hashing on builtin ints in Python",
      "summary": "Hashing in Python does not shuffle ints, let's see how to do this.",
      "contents": "Background\nPython builtin hashing\nPython has this really convenient feature where hashing is a builtin function. It works great for many things, including dictionnaries (hashmaps).\nIt also does a great job at making sure you don't need to take a look at its inner workings or even just the result of the hashing function itself. It works, and that's good enough.\nHashing for lossy label compression\nHowever, I had a situation where I have labeled regions of space in a volumetric image. A lot of regions, more than would comfortably fit in a 16-bit integer. But I really want to use 16 bits of resolution so as not to blow up the file size - in volumetric images, this adds up quickly and can be the difference between a manageable 4GB file and an unmanageable 8GB one.\nSo, I figured out that having a 16-bit hash of the &quot;true&quot; label would be a good enough approximation. There is the obvious problem of hash collision, which I deemed insignificant enough for my use-case (the probability of having two regions that touch each other and have the same hash out of 65536 possible values is small enough).\nAdditionally, a hash function applied on the labels would break the structure given by the iteration order of the labelling function, which is a net positive for visualization (two regions close have different labels, so they have different colors).\nWhy the builtin hash is not good enough\nMy first idea was to simply use Python's hash function. I never really used it explicitely before, so I tried and... I didn't see any difference.\nWait a minute.\n&gt;&gt;&gt; hash(1)\n1\n&gt;&gt;&gt; hash(70_000)\n70000\n&gt;&gt;&gt; hash(int(2**32))\n\nShoot. Let's see how it holds up.\nfor pow in range(64):\n  print(f&quot;For power {pow}: {hash(int(2**pow - 1)) == int(2**pow - 1)=}&quot;)\n\nThis snippet shows me that it is true until pow=60 inclusive. In fact, 2**61 - 1 is the first value where this pattern breaks down.\nI wanted to make sure why this happens: the hash is based on value modulo 2**p - 1 with p being 31 or 61 depending on the system being 32 or 64 bits respectively.\nIt's no coincidence that these are Mersenne prime exponents. See the CPython source code for computing hashes and for defining the relevant constants.\nIt's an implementation detail and can change for other Python implementations and/or versions.\nAnyways, what matters for me here is that for small integer values of x, hash(x)==x, which is not what I want.\nSolution\nIt turns out that compound objects have their hash computed based on their address in memory. So, if we can encapsulate our label in a lightweight wrapper that changes the hashing strategy, we can get the properties we want. In my case, I simply used a 1-tuple.\nAs an added bonus, we clip the value to only take the least significant bits to ensure our hash fits in 16-bits (or however many you need).\nA full implementation is given below.\nfrom typing import Callable\n\n\ndef hash_factory(n) -&gt; Callable[..., int]:\n    &quot;&quot;&quot;\n    Creates a hash function that produces non-negative\n    integer hashes of a specified bit length.\n\n    Parameters\n    ----------\n    n : int\n        The number of bits for the hash output.\n        The resulting hash will be in the range [0, 2^n - 2].\n\n    Returns\n    -------\n    function\n        A function that takes an input (int or tuple)\n        and returns a non-negative integer hash of n bits.\n\n    Notes\n    -----\n    - If the input is an int, it is converted to a tuple before hashing.\n    This is to ensure that hash(n) != n.\n    - The hash value is always non-negative and fits within n bits.\n    &quot;&quot;&quot;\n    def _hash(input) -&gt; int:\n        if isinstance(input, int):\n            x = (input,)\n        else:\n            x = input\n        h = hash(x)\n        # turn as non-negative and clip to n bits\n        return abs(h) % ((1&lt;&lt;n)-1)\n    _hash.__doc__ = f&quot;&quot;&quot;\\\nComputes a non-negative integer hash of the input, constrained to {n} bits.\n\nParameters\n----------\ninput : int or tuple\n    The value to hash. If an int is provided, it is converted\n    to a tuple to avoid collisions with tuple inputs.\n\nReturns\n-------\nint\n    A non-negative integer hash value in the range [0, 2^{n} - 1].\n&quot;&quot;&quot;\n    return _hash\n\n\n\n",
      "date_published": "2025-10-16T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    },
    {
      "id": "https://www.celestialsynapse.xyz/2025-09-07-spirit_swap.html",
      "url": "https://www.celestialsynapse.xyz/2025-09-07-spirit_swap.html",
      "title": "Spirit Swap: Lofi Beats to Match-3 To",
      "summary": "",
      "contents": "Spirit Swap: Lofi Beats to Match-3 To is an indie game available on\nitch.io and\nSteam\nfor around 20€. Developped by softnotweak with music from Meltycanon. A demo is\navailable on the storefront pages.\nDisclaimer: I got the game as part of a\nbundle\nIt's chill, it's queer and so very charming. I would describe it as a mix of a\nmatch-3 type of game with a visual novel aspect to it.\nI will mostly talk about the first half of the game, which is more story-driven\nand linear. It introduces all the characters and mechanics.\nGameplay\nThe main match-3 gameplay is quite different from what I expected. I am not\nthat much a match-3 player to begin with so, in my mind, match-3 rings\n&quot;Bejewled&quot; or &quot;Candy Crush&quot;, games where you have to match-3 by swapping two\ndifferent adjacent pieces (left, right, up, down) so as to make a match at\nevery turn. Here, it is more time-based than turn-based, and is reminiscent of\nPuyo Puyo. Blocks (spirits, in this game) fall from the sky, and you have to\neliminate them. The catch is you can only swap 2 spirits if they are at the\nsame height. So only left/right, not up/down. To move blocks vertically, you\nhave to make use of the gravity. If spirits reach the top, you loose.\nFurthermore, all the gameplay is in a versus mode. So, if you can make more\nmoves in the same amount of time, you have an advantage. And eliminating big\nhunks of spirits at the same time sends trash blocks that are more difficult to\nremove to the opponent. To help you, you have 3-different powers that are\nlinked with specific conformations of spirits you remove (a squre, a + sign, a\n× sign) that you can customize.\nOn top of that, there are 3 different difficulty settings: Chill (&quot;Easy&quot;),\nwhich was too easy for me, Spicy (&quot;Medium&quot;), a good middle ground for me and\nSheesh (&quot;Hard&quot;), too difficult for me. These, as far as I know, increase the\nnumber of colors you have to manage, the input speed needed to compete with the\nCPU and the overall level of skill of the CPU. In there, I find that the game\nstrikes a good balance. It's quite easy to pick up, has a good progression\ncurve and difficulty levels to accomodate every skill level. It can be very\nchill or very challenging, depending on what you're looking for and how good\nyou are.\nCharacters\nI found the characters quite diverse in personality, all very charming and\nhuman in their own way. I feel that some people would criticize the cast for\nbeing too &quot;woke&quot;, but I appreciated having a truly diverse cast of characters.\nSomething I really enjoyed about the character design is that, while being\novertly very queer, the game doesn't make a big deal of it. Yeah, they are\nBIPOC queer character but most importantly they are just silly human goofballs.\nEvery character seems like they would be good company, and that if further\nreinforced by their voice-acted dialogues.\nSpecial mention to &quot;The Polycule&quot;. The way it was presented, without further\ncontext and with this specific capitalization, I thought of it for a brief\nmoment as some sort of Greek mythology entity, like the Moirai. Very cool.\nIt is also possible to romance the different characters after the main story\nbit.\nI won't go into more detail here as I don't want to spoil anything if you want\nto play the game!\nGraphics\nThe game is very, very cheerful, and this is something you feel on every single\nscreen of the game. It's bright, it's colorful, it's got stars, sprinkles,\ncute smiley 3-eyed cubes, I just love it.\nThe animations are bouncy, soft, smooth, it pops.\nMusic\nWell, the title is not misleading here, it's lofi beats, and it's chill!\nUsually, I'm not a big fan of lofi, precisely because it is low fidelity and it\nfeels bad to listen to on headphones. It lacks bass, treble and depth. Here,\nyou can feel the inspiration of lofi, it's very chill indeed, but it has a bit\nmore acoustic depth, allowing the player to be fully immersed in the music,\nvibing to it while getting to learn the characters or eliminating spirits! I\noften found myself bobbing my head to the beat while playing, even when I was\nfully focused.\nIf you want more of the music, it's available on\nbandcamp.\nConclusion\nOverall, I feel like Spirit Swap: Lofi Beats to Match-3 To is a very good game\nwhich delivers on its promise. If you enjoy match-3 games, if you just want to\nchill for a while, it's definitely a good choice.\n",
      "date_published": "2025-09-07T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    },
    {
      "id": "https://www.celestialsynapse.xyz/2025-09-06-boots_quest_dx.html",
      "url": "https://www.celestialsynapse.xyz/2025-09-06-boots_quest_dx.html",
      "title": "Boots Quest DX",
      "summary": "",
      "contents": "Boots Quest DX is an indie game available on itch.io and Steam for around 10€. Developped by Discount Realms with music by Dragon Warrior,\nDisclaimer: I got the game as part of a bundle\nBoots Quest DX is a really fun, really charming short game about finding the best boots. I find the atmosphere to be very reminiscent of some Flash games.\nWhat is not to love about Boots Quest DX? Itś fun, witty, charming, chill, dream-like. It is a piece of art which relies on heart to convey a very heartwarming experience.\nAt first glance, it seems very unassuming: hand-drawn, crayon-style 2-frame idle animations; and the wonder of what will come next.\nThen comes the first NPCs. And with them, the tone of the game is given. The graphics are this way not because it is cheap (asset packs would have done the trick in this case), but because they are a key component of the aesthetics.\nThe game is goofy, carefree, and you know it as soon as you set foot in the Outside Inn.\nThe objective is very simple: explore the land and find the best boots. That's it. No fancy combat, no platforming, nothing complicated. Just exploration. You, going places, finding boots, hats, tangerines, other random items, finding friends, finding people who don't seem friendly but actually are.\nIt is very simple at its core, and it is part of its charm.\nIt subverts references to classical adventure tropes, it brings a bit of nostalgia and a very oniric mood.\nThis game is an adventure. A short one. It's probably not going to last as a lifelong memory, but it will be an enjoable experience. A dream in video game format. Give it a try and see for yourself!\n",
      "date_published": "2025-09-06T09:27:14",
      "authors": [{"name": "CelestialSynapse"}]
    }
  ]
}
