Yamaha YM2151

Yamaha é uma conhecida e antiga companhia japonesa, com mais de 100 anos, cuja área de atuação vai desde a fabricação de motocicletas até equipamentos eletrônicos, mais notavelmente equipamentos musicais eletrônicos e não eletrônicos, sendo esse último segmento o que mais traz o reconhecimento da marca pelo público em geral.

Assim como a maioria das empresas japonesas, a Yamaha expandiu seus horizontes para além das fronteiras orientais entre os anos 60 e 70 onde adquiriu expertise suficiente para que enfim nos anos 80 conseguisse o reconhecimento da indústria e demais profissionais da musica, através de seus aclamados sintetizadores da série DX mais notavelmente o DX-7, usado por diversas bandas, como A-Ha, Whitney Houston, Phil Collins, dentre outros.

DX Series tribute

DX7 – classic logo

FM synthesis everywhere

A década de 80 foram os anos de ouro dos teclados e sintetizadores baseados em síntese FM, ou sintese de frequência modulada.

O que se conhecia de aplicação relativa a Frequência Modulada (FM), até o fim dos anos 60, estava relacionado a transmissões de rádio, sendo essa a aplicação a mais conhecida até os dias atuais sendo amplamente difundida através das rádios FM espalhadas pelo planeta.

No final dos anos 60, o professor, compositor e músico, John M. Chowning, descobriu e desenvolveu na Universidade de Stanford, o algorítmo de síntese baseado em Frequência Modulada (FM), tendo essa técnica sido patenteada por John e a Universidade de Stanford e posteriormente licenciada em 1974 para a Yamaha que no mesmo ano fez seu primeiro protótipo de um sintetizador baseado em FM.

Entretanto um sintetizador FM comercial da Yamaha, de fato só apareceu no mercado em 1980 através daquele que se tornou o primeiro produto comercial da empresa com sintetização FM, o Yamaha GS-1.

Um dos grandes diferenciais dos sintetizadores FM era justamente a sua capacidade de ser controlado “programáticamente”, algo até então impensável para os sintetizadores analógicos como os dominantes Moog da época.

O próprio GS-1 tinha um mecanismo rudimentar de carga e armazenamento de programas que poderiam modificar as “vozes” do sintetizador, o que era feito através cartões magnéticos desenvolvidos especificamente para esse sintetizador.

Tal técnica me levou a “fazer uma engenharia reversa mental aqui” e a concluir que tal mecanismo não é nada mais do que um leitor de fita magnética bem mais limitado, porém nos mesmos moldes conceituais dos utilizados nos micro computadores da década de 70 e 80, para ler e armazenar programas em uma era pré-dispositivo de armazenamento em massa (aka disquetes de 360 Kb e 720 Kb).

GS1 demo (GS1 voice library)

The Yamaha YM2151

O YM2151 é o primeiro sintetizador FM auto-contido em um único chip que não necessita de chips e circuitos adicionais para realizar uma sintetização de som FM e cuja aplicação inicial era para uso embarcado em teclados Yamaha, como o DX21 e o DX100.

Além disso o YM2151 também foi bastante usado em máquinas de arcade da Atari, Konami, Capcom e Namco e em computadores da linha MSX através de modelos da própria Yamaha, CX5M e também através das expansões SFG-01 e SFG-05 feitas pela própria Yamaha para computadores da linha MSX.

Além de teclados e computadores fabricados pela própria Yamaha, um outro dispositivo conhecido por embarcar um YM2151 internamente é o módulo MIDI FB-01, também da própria Yamaha.

Vampire Killer on Yamaha FB-01

O FB-01 é um módulo MIDI de baixo custo, portanto sem muitas features para edição de “vozes” e quaisquer controles adicionais, sendo possível fazê-lo através de editores de MIDI como Unisyn e talvez até o meu preferido Aria Maestosa (o mesmo usado no vídeo acima).

YM2151 meets MSX

Conforme descrito anteriormente, a própria Yamaha participou do consórcio MSX com os seus modelos CX5M e também com seus módulos externos SFG-01 e SFG-05, esses dois últimos também integrados aos CX5M via slot de expansão dessas máquinas.

A diferença entre a SFG-01 e a SFG-05 fica por conta do software embarcado em ROM desses módulos que são bem diferentes e também pelo fato do SFG-01 não poder receber comandos de entrada via porta MIDI, com isso esse módulo não pode ser conectado a um teclado via porta MIDI padrão, ficando restrito apenas à porta proprietária do módulo, compatível apenas com alguns teclados da Yamaha feitos exclusivamente para uso nesse módulo.

Já o SFG-05, além de melhorias no software embarcado em ROM, pode se conectar com qualquer dispositivo MIDI via porta de entrada padrão MIDI (IN) e receber comandos MIDI, possibilitando assim a integração do SFG-05 com qualquer dispositivo compatível com MIDI existente no mercado.

Lara plays, playlist (CX5M/SFG-05)

Além das diferenças descritas acima, os módulos SFG-05 receberam o chip YM2164 ao invés do YM2151, sendo ambos são compatíveis com pequenas diferenças, apenas na mudança dos registradores de teste e reset do operador de baixa frequência (Low Frequence Operator ou simplesmente LFO) e também no Timer B que teve sua resolução de tempo duplicada, de 1024 ciclos no YM2151 para 2048 ciclos no YM2164.

Apesar da diferença nos chips ser pequena e bem sutil, a parte de software pode sim ser influenciada a ponto de gerar incompatibilidade ou até mesmo um funcionamento indesejado, entretanto como a ROM BIOS desses módulos também foram mudadas, a própria Yamaha se encarregou de deixar as coisas funcionais, considerando o seu software sequenciador interno em ROM que, diga-se de passagem, no SFG-05 foi bastante modificado principalmente na parte da interface com o usuário.

Ainda no MSX, temos pelo menos dois programas reconhecidos por fazer uso do YM2151/YM2164. Um deles é o VGMPlay e o outro é o Pop!Art VGM Player, ambos tocadores de músicas no formato VGM, que é um formato que possibilita a reprodução de musicas de vídeo games nos mais variados chips de som suportados pelo formato, incluindo o próprio YM2151/YM2164.

Pop!Art first preview playing on SFG-05 card

YM2151 today

Atualmente chips com capacidade de sintetização FM, como o YM2151, devem estar cada vez mais restritos a nichos de música, uma vez que mesmo os vídeo games modernos tem uma capacidade fenomenal de processamento e com isso terminaram por abolir o uso desses chips como parte central de sua capacidade multimídia nesses consoles.

Com isso é bastante comum que a indústria de video-games se utilize cada vez mais de orquestras e sons gravados analogicamente, o que possibilita a convergência dos chips de som desses consoles para circuitos DACs de alta resolução.

Entretanto apesar de seu uso estar cada vez menor pelo mainstream, chips como o YM2151 encontraram um ótimo nicho no universo DIY (Do It Yourself), também conhecido como maker.

YM2151 Arcade Classic VGM Player (hardware)

Assim o “espírito da sintetização FM” deve permanecer preservado e garantido para as futuras gerações.

Resta apenas saber se empresas como a Yamaha continuarão fabricando chips como o YM2151, YM2164 e YM2413, futuramente….esperamos que sim 🙂

[]’s
PopolonY2k

Pop!Art VGM Player for MSX

Is known by the brazilian MSX community about the development of Pop!Art VGM player that I’m working on since middle 2014.

Some practical results about Pop!Art were reported in 2014 by one of the most important retrocomputing blogs in Brazil, the Retrocomputaria+ blog and by the biggest brazilian MSX community on FaceBook, the MSX Brasil Oficial.

Pop!Art VGM player already supports all existing chips on the MSX platform, like Konami SCC (K051649), PSG (AY8910), FM (YM2413), SFG01/05(YM2151), OPL3/OPL4 and the Philips Music Module (Y8950).

Note: Some months after I presented some Pop!Art results, another excellent VGM Player (VGMPLAY by Grauw) was released.

My first motivation to start this development was only for fun and also to start learning about how sound chips works. The second motivation was to start a big project in chiptune’s scene.

In fact to get information about these old chips was the biggest challenge because some of them just can be found on manufacturer’s data-sheet that sometimes are poorly written and with a small percentage of useful information.

In most cases these datasheet information are confused so the best alternative to these poor data-sheets are the Linux sound cards drivers source code.
After reading these drivers source code, I got some specific details about how several of these chips really work.

Custom chips like Konami SCC don’t have any data-sheets but fortunately are well documented by the international MSX community and sources like BiFi’s website were my main information source.

Another big source of information for MSX developers in general is the MSX Assembly Pages (brought by the same author of VGMPLAY, Grauw) that in my opinion is the best source of information for developers who want to make useful and cool things for MSX computers.

Presenting Pop!Art

Pop!Art is an original software made using Turbo Pascal 3, almost 97% of it’s code is written in Pascal, with some parts written in Z80 ASM. If you want to compile it’s source code and modify it, feel free because the source code was released under GPLv3 and can be reached at OldSkoolTech SVN’s repositories on SourceForge.net.

It is compatible with Borland Turbo Pascal 3.0 (CP/M80-MSXDOS), Turbo Pascal 3.3f from MSX Club Enschede, (MSXDOS 1 & 2), and it also can be ported to others newer Pascal compilers, like FreePascal (Lazarus) and maybe newer versions of Delphi compiler.

The source code is fully commented and several parts of Pop!Art software were incorporated to the framework that I’m developing since I had started the development of the MSXDUMP in 1995 (best known as PopolonY2k Framework).

This framework can deal with several technologies present on MSX architecture, like IDE device handling, MSXDOS and MSXBIOS function calls and direct console handling.

Pop!Art introduces some important features in the framework, like support to Z80 interrupts, all MSX sound chips handling (K051649 aka SCC, YM2413 aka FM, YM2151 aka SFG01/05, OPL3/OPL4, Y8950 aka Philips Music Module, AY8910 aka PSG) and a better and accurate “wait” routines that can deal with resolutions below 50Hz or 60Hz, fixing time errors caused by songs with “tempo” below these resolutions (50Hz or 60Hz), that minimizes any standard deviation.

The current Pop!Art engine also supports all existing chips for the MSX platform and in future, newer chips supported by the VGM format similar to any existing on MSX platform will be added to the Pop!Art engine.

The VGM file format

VGM, aka Video Game Music, is a logging format based on GYM format which is another video game format used specifically to store Sega Mega Drive (Genesis) songs, but contrary to GYM, the VGM format can be used with several other chips different to Mega Drive sound chip. The first version of VGM was released in 2005 and after this release, six new format specifications were released until the current 1.70.

Another curiosity about VGM is that the format was very popular with Winamp users because this music player was the first player capable of playing VGM songs through a plugin specially created for it.

GD3 tag format

The VGM format has a GD3 metadata present in file header specification. The GD3 format is the same format used by MP3 files to store several tracks information, like author, song name and so on.

Pop!Art VGM Support

Pop!Art supports all VGM version’s format, since 1.0 to 1.70 and the GD3 tag format is partially implemented in Pop!Art engine but will be finished in future releases.

The VGM format contains all data samples sent to the sound chips using a speed rate of 41,000 samples per second, so your library must be very fast and precise to deal with VGM files in an accurate way and basically just assembly codes can reach this performance using all of the chip’s power….right ???

Hummm…..maybe not.

Turbo Pascal

I’m really thinking to start writing code to MSX using modern compilers, like SDCC C compiler, which is known to be one of the most powerful and optimized compilers for small devices, but I have written a lot of code to the old Turbo Pascal 3 for CP-M80/MSX for years and my framework has increased a lot its capabilities to handle several standard devices present in MSX world.

Turbo Pascal

In fact I’m using this good, but not so optimized compiler, to learn about new optimization techniques and about the Turbo Pascal internals. And also how to avoid not optimized coding style when you’re programming for machines with low resources. Maybe in the future I can write a new, modern and optimized Pascal compiler (maybe a cross-compiler) for MSX machines, but this is another dream.

When I started writing this article in 2015, FreePascal compiler was not an alternative because it lacked Z80 binary generation support, but since beginning 2020 FreePascal started supporting Z80 platform.

https://wiki.freepascal.org/Z80

Borland Turbo Pascal 3.0 is an impressive compiler because it is a very fast compiler but unfortunately there are several things that were created to be generic and problem solving in a generic way are known to be slower than a more specialized code generation.

I’m dedicated to improve my framework to be so generic as possible but sometimes I’ll need to be more specific to resolve big performance problems using Turbo Pascal code instead using assembly code.

The small list below can help programmers who are thinking start coding in Turbo Pascal, C and another language different of ASM.

1) In Pascal avoid nested functions – This kind of structured feature is not optimized in Turbo Pascal 3;

2) In any high level language with floating point builtin data types support, like Pascal and C, try to avoid real time processing using these floating point types (float/double in C and Real in Pascal).
These data types can deal with an “excellent” precision but is known that when you have, or want, an “excellent” precision, the processor will pay the price for this precision, so avoid floating point real time operations if is possible. Sometimes this can be done performing some data pre-processing or using fixed point, instead floating point;

3) Use integer instead floating point data and byte instead of Integer data, depending on numeric range, for the same reason of previous item;

4) Try “think” your application in JUMP TABLES, instead nested IF’s or even switch-case (case-of for Pascal programmers);

5) Read this article before coding http://www.popolony2k.com.br/?p=2402

NOTE ABOUT THE 5th ITEM: I’m using GOTO in small pieces of code, because old compilers like Turbo Pascal 3 are very antique, so features like “break” and “continue”, widely used in loop iterations, can be “simulated” by using GOTO.

PopolonY2k framework

As I wrote at the beginning of this text that I’m working on a framework fully written in Turbo Pascal, with some parts in ASM, since I released the MSX DUMP (part of MSX Disk Doctor suite). I thought that this framework was optimized but I was completely wrong, because there’s no framework or any other piece of code which the performance can be measured when discs and slow devices are used by these codes.

So when I tested this framework using my MSX Turbo R machine, everything seemed to be 100% ok and fast, but when I tested the same code on a MSX, running a slower Z80 processor, some problems started to be more visible, then fixing these problems and keep everything working fast using a Z80 in the same way like a R800 processor is a hard work.

This framework was started 20 years ago, when I was leaving the university and in those days I just wrote code for old devices like, disk drives and some generic code code to access the MSXBIOS and MSXDOS (1).
When I restarted coding this framework in 2011, I quickly improved it by adding features to access new devices, like Sunrise IDE devices, Network socket API, UNAPI and RS232 support are still WIP (Work in Progress).

Bellow is the list of all features present on this framework

1) FOUNDATION MODULES – New modules to make Turbo Pascal “more compatible” with new Turbo Pascal releases. New features like Big Integer handling;

2) MSX INTERNALS MODULES – MSX related functions and information (e.g. MSX System Variables);

3) BIOS MODULES – MSX BIOS functions by category;

4) MSXDOS (1 & 2) MODULES – MSX DOS functions;

5) SLOT MANAGEMENT – Functions related to slot manipulation;

6) INTERRUPT HANDLING – Functions to enable interrupt vector function handling using Turbo Pascal;

7) COMMUNICATION – Functions related to communication (RS232 (Work in progress), Sockets);

8) COMMUNICATION DRIVERS – Drivers written to support the Sockets implementation above. Support to OPTONET cards;

9) UNAPI FRAMEWORK – Support to UNAPI framework in Turbo Pascal (Work in progress);

10) SOUND CHIP DRIVERS – Drivers for all sound chips found on MSX standard;

11) VGM PLAYER FRAMEWORK – Functions to play songs in VGM format;

12) IDE SUNRISE-LIKE FRAMEWORK – Functions to handle Sunrise-like IDE devices;

13) USER INTERFACE AND OPTIMIZED CONSOLE MODULES – New functions to increase the speed of console applications and to handle user interface;

14) UNIT TEST FRAMEWORKPopolonY2k TEST SUITE (PTEST) – Functions providing UNIT tests capabilities for Turbo Pascal 3 projects (widely used in the Big Integer implementation);

An updated framework features list can be reached here.

Pop!Art features list

  1. VGM file support (1.0 up to 1.70 – some commands are still disabled. eg. non MSX existing chip commands);
  2. Memory Mapper support (VGM files longer than 64Kb can be loaded and played);
  3. MSXDOS2 only support (sub-directories access). Maybe MSXDOS1 will be supported in future releases;
  4. AY8910 support;
  5. YM2413 support;
  6. YM2151 (SFG 01/05) support;
  7. Y8950 (Philips Music Module) support;
  8. YMF278 (OPL4) support;
  9. K051649 (SCC) support;

Known Pop!Art missing features in this release (0.0).

  1. VGZ file support (in fact is VGM inside a .tar.gz file);
  2. MSXDOS1 support;

Pop!Art memory layout

The application memory layout is described below:

  1. $0000-$3FFF – MSXDOS CP/M-80 + Turbo Pascal runtime workspace;
  2. $4000-$7FFF – Application object code;
  3. $8000-$BFFF – VGM Song data (16Kb memory mapped paged system);
  4. $C000-$FFFF – Unused;

Pop!Art in action

After writing a long story and mainly a lot of technical stuff, it is time to play some song using Pop!Art finally after 5 years 🙂

Check the video below where I explain technical details about how Pop!Art works internally.

Pop!Art in action (portuguese video only)

Downloading Pop!Art

Pop!Art binaries can be downloaded here, https://sourceforge.net/projects/oldskooltech/files/MSX/Pop%21Art/

Enter the version directory you want (e.g v0.0, etc) and download a preferred compressed file (pop_art_v_?_?.zip or pop_art_v_?_?.lhz).

After downloading and decompressing the chosen file, popvgm.com and popplay.chn files will be extracted, put them together in the same directory and then execute popvgm.com.

These files are the two main modules of Pop!Art described below.

  • popvgm.com is the VGM loader;
  • popplay.chn is the VGM player itself.

Hidden gems

Unfortunately all Turbo Pascal 3.x for MSX, both Borland and MSX Club Enschede, are too old products and are both an one pass compiler, so generated binaries are not so optimized as newer compilers like Free Pascal compiler.

Borland did an excellent work when decided create a powerful runtime not just placing the biggest part of standard library there but all comparison test routines are placed there too.

Using this model, the amount of binary code generated by the compiler was decreased considerably but on the other hand they sacrificed performance with this strategy.

I realized that all If’s in the main Pop!Art streaming routine was jumping to the respectives runtime routines and this behavior was decreasing performance a lot, so after a long time think about this problem finally I decided to change the Borland Turbo Pascal 3.0 binary by adding an extra pre-processing compiler directive to generate inline code for all comparison routines and consider Integer (-32768 .. 32767) like Word/Unsigned int (0 .. 65535).

But changing this behavior could turn specific code written to this specific Turbo Pascal version, incompatible with both Borland and MSX Club Enschede, so instead using the standard compiler directive {$ }, I created an extended compiler directive {% } that is considered by Borland and MSX Club Enschede Turbo Pascal as a regular comment but for my modified Turbo Pascal version is an extended compiler directive.

The first extended directive is {%W} and is a scoped directive, so to activate the starting scope the programmer must start with {%W+} and finish the scope with {%W-}.

This will inform the compiler to treat comparison routines as unsigned integer and generating inline code from starting point {%W+} to ending point {%W-}.

Below a small piece of Pop!Art code using this technique:

Procedure __MoveMapper16BitData{( __pSndChipArrayParms : Pointer )};
  Begin
    {%W+}
    If( nCurrentStreamPos < __ctMapperBufferEndAddr ) Then
    {%W-}
    Begin
      __pSndChipArrayParms := Ptr( nCurrentStreamPos );
      nCurrentStreamPos := nCurrentStreamPos + 2;

      (* Direct jump to command processing routine *)
      Inline( $2A/nFnJmpAddr   { LD HL,(nFnJmpAddr) }
              /$E9             { JP (HL)            } );
    End
    Else
    Begin
      __pSndChipArrayParms := Ptr( Addr( aSndBuffer ) );
      aSndBuffer[0] := Mem[nCurrentStreamPos];
      __ExecMapperPaging;
      aSndBuffer[1] := Mem[nCurrentStreamPos];
      nCurrentStreamPos := Succ( nCurrentStreamPos );

      (* Direct jump to command processing routine *)
      Inline( $2A/nFnJmpAddr   { LD HL,(nFnJmpAddr) }
              /$E9             { JP (HL)            } );
    End;
  End;

All comparison structures below are covered by this extended directive:

  • While .. Do
  • Repeat .. Until
  • If… Then … Else

Conclusion

Pop!Art can still be considered a work in progress and soon some extra and useful features will be added to it’s core engine, like:

  • Add support to VGZ (compressed VGM) file format;
  • Chip sound drivers improvement, adding chip specific extra features still not implemented;
  • Core engine speed optimization (improving Turbo Pascal performance);
  • Add full support to VGM 1.70;

So, I hope you enjoy Pop!Art and thanks for reading.

[]’s
PopolonY2k