Showing posts with label code. Show all posts
Showing posts with label code. Show all posts

Sunday, January 17, 2016

#C: fast string to hex string

following this post, i have also added a method to convert a char* buffer to a char* buffer which holds the hex values of each input character.

e.g.:
HelloWorld -> 48656c6c6f576f726c64

a branchless method with a lookup table is used again. it works for any type of data (e.g. UTF-16, UTF-8, etc.) as long as sizeof(char) is 1 byte, as is in the standard.

the cfg2 C library now includes the function cfg_char_to_hex(), which can be found here.
it's effectively the reverse of cfg_hex_to_char().

--

Monday, October 12, 2015

#C: fast parsing of hex strings to char buffers

the C library for parsing INI file syntax (cfg2) that i'm hobby-maintaining has recently been improved quite a lot. supports sections, the parser should be much better now, improved API and so on.

one of the features i've added is to be able to store HEX strings of binary data in the text file that can be optionally parsed into memory char buffers.

for example:
some_key=48656c6c6f77576f726c64

where the HEX string equals "HelloWorld".

problems at hand:
1) detect bad length
2) detect bad characters
3) support case-insensitive input

of course, most programmers can immediately start writing a solution for this type of parser and solve all 3 problems, but the question is - how to write this to be as efficient as possible?

solving 1) is quite easy. since we are working with 8 bit characters, we are going to have 256 values per character or a maximum of 0xFF (255). but instead of parsing bad characters we are strict and require the HEX string length to be divisible by 2:
if (len % 2)
    goto error;
one would approach solving 2) with "if, then, else" branches to see if a character in the HEX string is in the 0-9,A-F range of the ASCII table.

3) can be solved with toupper()/tolower()

but instead, a lookup table can be used to solve both 2) and 3) in a single pass. this lookup table could have 256 indexes, where most are filled with zero, while the valid indexes are filled with values of interested.

the table can be seen in this source file - named "hex_to_char_lookup".

so, when we first traverse the example HEX string we reach a couple of characters "48".
the first one "4" - this character has an ASCII decimal value of 52. the lookup table has mapped this value at index 52 as 5. the reason for 5 instead of 4 is that i wanted the table to look pretty, filled with zeroes and thus i increased each value by one so that "0" is mapped to 1, "1" is mapped to 2 and so on. this can be removed for a small optimization [1], but then one has to fill the table with values such as -1.

"8" which is mapped to ASCII index 56 in the table and a value 9 is returned.

if we reach a bad character, 0 will be returned in which case the program should return an error with the bad character position in the HEX string.

at some point in the example string, "c" will be reached and here we could have a case-sensitivity issue, but the lookup table has mapped both the ASCII "c" and "C" to return the same value which is 13 or the 12th index in hexadecimal, plus 1.
0 1 2 3 4 5 6 7 8 9 A B C D E F
                        ^ (12 + 1 = 13)
now, to obtain the resulting C char we have to form a hexadecimal value combining the two decimal values, as follows:
first = table[52]; // 5
second = table[56]; // 9
if (!first || !second)
    goto error;
first--; second--; // 4, 8; possible optimization [1]
unsigned char result = first * 16 + second; // 72 = "H"
and then the result can be written to the output char buffer.

that's all!
TMK, this parsing method would work for any string encoding UTF-8, UTF-16, etc. as long as sizeof(char) == 1, which should be very much true as it's in the ISO C standard.
 --

Wednesday, February 4, 2015

#libmodplugw

here is a small (wrapper / extension) library that can be used to manipulate libmodplug decoded buffers in terms of rows and patterns with sample accuracy:

https://github.com/neolit123/libmodplugw

--

Friday, December 19, 2014

#AS3 KeyboardHandler

(i've posted this as a comment in Starling bug report from a user)

for performance crucial sections such as keyboard interaction i would not use anything but callbacks.
the flash event system, and the alternatives such as signals are nice for higher level management, but they can't really beat callbacks for performance. what Starling does with the enhanced events is also fast, but here is my point.
the virtual machine and the garbage collector already provide you with the flexibility of one of the core features - everything is an Object including Function.
"functors" or function pointers is something that even languages like C++ don't handle that well, so you really should take advantage of this low level, yet still high level feature.
since the only way in flash to see if a key is pressed is via the KeyboardEvent, use that and build a callback system on top of it. only maintain the stage events and propagate manually not display objects but rather objects of interest.
check this concept i wrote quickly:
  • KeyboardHandler is a state machine that tracks keyboard isDown states for a keyCode and calls your registered callback.
  • it uses the native stage
  • it's super fast
  • it's worker safe
  • you can stop it at any time using "enabled = false"
  • it does call event.preventDefault(), event.stopImmediatePropagation(), but you can mod that yourself or simply call "enabled = false" when needed.
  • once a key is down it no longer registers as down until it up, this forces you to write your key logic smart.
  • if you don't track a key state yourself (which would be faster) at any time you can call supportedKeyIsDown(...) to see if a key is currently down. this allows easy checks for key combinations e.g ALT + SHIFT + LEFT.

Friday, September 13, 2013

#fast IEEE 754 double to int32 @ music-dsp

at the music-dsp mailing list there was a short discussion about a "double -> int" rounding hack present in the JUCE library. i've posted an alternative solution that does the same without IEE 754 arithmetic. i'm sure similar solutions can be found in libraries and for CPU's that don't have a floating point co-processor unit. code is for c99.

http://music.columbia.edu/pipermail/music-dsp/2013-September/071572.html

can be summarized into:
1) separate double into mantissa, exponent, sign bit
2) depending on exponent value shift the mantissa left or right by the difference of the exponent and the amount of bits in the mantissa
3) truncate and receive a 32bit integer, while applying the original double's sign

--

Thursday, May 26, 2011

#listing files in a remote git repository

here is a small batch script for windows (msysgit) that will list the files from a certain branch in a remote git repository. i wrote the initial script some time ago because i wanted git have this functionality with a single cmd line, but finished it just yesterday.

git_lrt.zip

it works as follows:
git_lrt some-url some-branch
git_lrt some-url some-branch > logfile.log


if no branch is given 'master' will be used.

what it does is (if you want to port to linux bash for example):
- create local temp folder
- init a git repository in there
- add remote from url
- fetch objects
- list remote files for branch
- clear local temp folder (& repository)

you may find the script useful to check the contents before cloning a small repository to your local windows hard drive. it seems there might be a possible vulnerability in msysgit where files that are part of the repository can be written to system folders. an example that mr. tale gives:
cockos forum post

--

Tuesday, June 8, 2010

#iso c99: some 64bit integer printing fun

a small article that gives tips on writing portable code for printing 64bit integers (printf):

i64_printf

source code for download is included

Monday, May 24, 2010

#iso c/c++: runtime and static assertion for gcc 4.4.0+

re: axonlib
we've made some very good progress on the library. v.0.1.0 is about to be released soon. we now have image transparency, scalable images, a lot of widgets, a custom set of stdlib routines for string and memory, a rather fragmenting but fast custom memory allocator and other. also we are now not using heavy c++ types such as 'vector' any more, while 'iostream' is only used for debug builds.

i have made a little page to write some articles on programming methods, optimization techniques, assembler trick and other things i've learned over the years or just recently.

http://sites.google.com/site/neolit123/

as far as programming goes i may be focusing more on assembler and c over c++ and higher level languages.

the first article that is done now is about assertion:
http://sites.google.com/site/neolit123/home/lassert

the original methods are part of axonlib but i release these to the public (under a fairly permissive license) as _none_ of the examples in the internet that i've tried out of interest worked properly and gave errors / warnings for either c or c++ code with the gcc compiler.

[edit] actually the following seems to work as well with not much overhead:


#define STATIC_ASSERT(e) switch(0) { case 0: case (e): ; }
/*
resulting in two errors:
file:line: error: duplicate case value
file:line: error: previously used here
*/


..and is a portable solution, but not very useful because the macro will expand to a switch call but in the same time (e) has to be a constant.

Sunday, April 4, 2010

#send to cmd.exe

here is an useful trick. wonder if you can always right click a file under windows and open the file location in a command prompt?

on win xp. navigate to:
"[Drive]:\Documents and Settings\[Username]\Sendto"

on vista or 7 the folder should be at:
"[Drive]:\users\[Username]\AppData\Roaming\Microsoft\Windows\SendTo"

create a new file called "SendTo.cmd", place the following line of code inside it and save:

@cmd /a /k cd /d %~d1%~p1
what this commands does is:
echo off, open cmd.exe with ansi output, carry out a command and remain, change directory to the first input file's drive and path

now every time you right click a file or a folder and call "Send To -> SendTo.cmd" you will have a command prompt with its parent folder open.

for example:
right clicking + "sendto.cmd" any file or sub-folder in "c:\windows\system32\"
will open a command prompt showing:
"c:\windows\system32>"

lubomir

Tuesday, March 9, 2010

#gcc: speed-tests, inline assembly & volatile declarations

here are some quick tests with gcc (3.x / 4.x) and axonlib.
note: "axAbs" (alt: fabs) and "axExp" (alt: expf) are part of "axMath.h"

[*] gcc speed comparison (win32)

gcc-3.4.2 is the official mingw build, while gcc-4.4.1 is an unofficial build.

test::

n of iterations:
10e+6

calculation:
expf(axAbs(-3.141592))

flag: -O2
gcc-3.4.2: 143 ms
gcc-4.4.1: 6 ms

flag: -O3
gcc-3.4.2: 130ms
gcc-4.4.1: 5ms

conclusion:
gcc-4.4.1 generates faster code.

[*] gcc: macros vs inline functions.

an article with some more in depth information.

test::

n of iterations:
10e+6

calculation:
axAbs(x) in the forms of macro vs inline and expf(x) for weight.


#define t0(x) \
({ \
  register float _x; \
  __asm__ ( "andl $0x7fffffff, %0;" : "=r" (_x) : "0" ((float)x) ); \
  expf(_x); \
})

// -- vs --

inline float t1(float x)
{
  __asm__ ( "andl $0x7fffffff, %0;" : "=r" (x) : "0" (x) );
  return expf(x);
}


flag:
-O2

gcc-3.4.2:
macro: 143ms
inline: 145ms

gcc-4.4.1:
macro: 5ms
inline: 6ms

conclusion:
inline functions are safer. not much difference in performance.

[*] gcc: to "volatile" or not and its impact on performance.

a volatile declared function or variable will not be optimized.

quote:
(on writing code for hardware control) Any self-respecting optimizing compiler would notice that the loop tests the same memory address over and over again. It would almost certainly arrange to reference memory once only, and copy the value into a hardware register, thus speeding up the loop. This is, of course, exactly what we don't want; this is one of the few places where we must look at the place where the pointer points, every time around the loop.

test:::
asm volatile (..) vs asm (..)

calculation:
axExp(x)

n of iterations:
10e+7

flag::
-O2

gcc-4.4.1:
asm volatile: 298ms
asm: 2ms

gcc-3.4.2:
asm volatile: 291ms
asm: 13ms

flag::
-O3

gcc-4.4.1:
asm volatile: 297ms
asm: 2ms

gcc-3.4.2:
asm volatile: 290ms
asm: 12ms

conclusion:
functions declared as "volatile" perform much slower from both compilers.

----------
tested with athlon xp 1800+

lubomir

Thursday, February 25, 2010

#c++: function callbacks between classes and accessing non-static members from static methods

i was looking for a way to use a class in c++ as a processing container, which does callbacks to methods in another class. an example in digital signal processing can be given as: a tone generator which normally operates at sample rate fs=44100 Hz, but is oversampled to fs * 2 via an oversampling container.

now, of course the above can be inlined in a single method, which will be essentially faster, but leaves us with a composite method, instead of a case where both processes (tone generator and oversampler) are separated in classes and can be reused by other processes in a more object oriented class structure.

lets take a look at a case where the main processing method is in the parent class and the other processing method (a processing container) is in a sub class (or a class which is initiated inside the parent class).

here is an example:

// include a class from a header
#include "childclass.h";
// define parent class
class parentclass
{
  private:
    // child class instance
    childclass _childclass;
    // some variable
    float some_variable;
    
  public:
    // constructor
    parentclass()
    {
      // init stuff
      some_variable = 5.f;
    }
    
    // the main method
    virtual void processing_main_method(const float input)
    {
      // call a method from the child class and pass the input variable
      _childclass.some_method(input);
    }
}


how about callbacks i.e. passing a method which to be called from another method? in the c programming language to achieve that function pointers are used.here is a nice article that covers mostly everything on the subject of function pointers on callbacks:
http://www.newty.de/fpt/callback.html

but what if we decide to make a callback from the child class to a method in the parent class? the logical way to achieve that is to declare a method in the parent class as static. http://www.eelab.usyd.edu.au/ee_database/programming/c++/cplusplus-5.html:

...member of a class can be declared static; be it in the public or private part of the class definition. Such a data member is created and initialized only once; in contrast to non-static data members, which are created for each object of the class. A static data member is created when the program starts executing; but is nevertheless part of the class.

(note: info on static functions in the same article - section 5.2)

some code for our example:

// ==============
// program.cpp
// ==============
// include a class from a header
#include "childclass.h";
// define parent class
class parentclass
{
  private:
    // child class instance
    childclass _childclass;
    // some variable
    float some_variable;
    
  public:
    // constructor
    parentclass()
    {
      // init stuff
      some_variable = 5.f;
    }
    
    // ************************
    // the callback method
    // ************************
    static float processing_callback_method(const float input)
    {
      // do something
    }
    
    // the main method
    virtual void processing_main_method(const float input)
    {
      // call a method from the child class and pass the input variable
      // and also the local processing_callback_method
      _childclass.some_method(processing_callback_method, input);
    }
}

// ===============
// childclass.h
// ===============
// define child class
class childclass
{
  private:    
    float some_variable;
    
  public:
    // constructor
    childclass()
    {
      // init stuff
      some_variable = 5.f;
    }
    
    // ********************************************
    // the method that is called from parent
    // notice how the function pointer is passed
    // ********************************************
    virtual float some_method(float (*callback_function)(float), const float input)
    {
      // do something with input
      // ....
      
      // then do a callback
      return(*callback_function)(input);
    }
}


here is a quick diagram of the above:

.------------------------------------------.
|[*mainclass]                              |
|                                          |
|     processing_main_method               |
|           |                              |
|           |  processing_callback_method  |
|           V                  ^           |
|           |                  |           |
|  .--------|------------------|---.       |
|  |        |                  |   |       |
|  |        '--> some_method ->'   |       |
|  |[*subclass]                    |       |
|  '-------------------------------'       |
'------------------------------------------'


so far so good...
but now we face the issue that static methods cannot access non-static members. actually there is much sense in that if we think about it:

Besides static data, C++ allows the definition of static functions. Similar to the concept of static data, in which these variables are shared by all objects of the class, static functions apply to all objects of the class.

The static functions can therefore address only the static data of a class; non-static data are unavailable to these functions. If non-static data could be addressed, to which object would they belong? Similarly, static functions cannot call non-static functions of the class. All this is caused by the fact that static functions have no this pointer.


the way to solve this would be to pass an instance to the parent class to the subclass function (some_method) and then pass this instance back to the static callback function (processing_callback_method). an example (with void pointers):

// ==============
// program.cpp
// ==============
// include a class from a header
#include "childclass.h";
// define parent class
class parentclass
{
  private:
    // child class instance
    childclass _childclass;
    // some variable
    float some_variable;
    
  public:
    // constructor
    parentclass()
    {
      // init stuff
      some_variable = 5.f;
    }
    
    // *******************************
    // a non-static member function
    // *******************************
    virtual float non_static_method(const float input)
    {
      return input * 2.f;
    }
    
    // ************************
    // the callback method
    // ************************
    static float processing_callback_method(void* _this, const float input)
    {
      // cast the class
      childclass* _pthis = (childclass*) _this;
          
      // do something with a non-static member
      _pthis->some_variable = 1.f;
      
      // call a non-static member function
      return _pthis->non_static_method(input * 0.5f);
    }
    
    // the main method
    virtual void processing_main_method(const float input)
    {
      // call a method from the child class and pass the input variable
      // and also the local processing_callback_method
      _childclass.some_method(processing_callback_method, input);
    }
}

// ===============
// childclass.h
// ===============
// define child class
class childclass
{
  private:
    float some_variable;
    
  public:
    // constructor
    childclass()
    {
      // init stuff
      some_variable = 5.f;
    }
    
    // ********************************************
    // the method that is called from parent
    // notice how the function pointer is passed
    // but also an instance of the parent class
    // ********************************************
    virtual float some_method(void* _parent, float (*callback_function)(void*, float), const float input)
    {
      // do something with input
      // ....
      
      // then do a callback
      return (*callback_function)(_parent, input);
    }
}


so that is all.

please note that i have not tested any of the code from above and its just provided as a guideline.

lubomir

Saturday, December 19, 2009

#axonlib: A cross-platform VST effect framework

ccernn, not so long ago, started the work on a cross-platform vst framework for linux and windows.

axonlib home
Its in an early version currently, but has proven quite stable already.


some screenshots:




I've joined in to help (as much as i can) with some cross platform tests, ideas and possibly with development once we set a version control repository.

Lubomir

Saturday, August 1, 2009

#JSFXGEN - Modular environment for generating dsp code. (update 01.10.09)

I've started working on a "modular environment for generating dsp code" similar to synthmaker/max/synthedit. The target dsp platform is JesuSonic.

First on the list is an online version made with flash/php?/javascirpt/html/xml.

The idea is to be able to add different editable modules, design custom routings and possibly some graphic front-ends.
I'm going to take my time with this one, while keeping it as simple-to-code and user-friendly as possible.

Working project title for now is "jsfxgen".

update v0.1.0 (01.10.09)
screenshot from 0.1.0
new stuff:
- moved to air/flex sdk for primary local version with save/load (online version is still possible)
- integrated a build in editor with scrollbar, undo, line numbers, syntax highlighting.
- variable based drag and drop routing between modules
tbd:
- solid xml data model for the modules
- module export
- open/save file format structure

Lubomir

Wednesday, May 13, 2009

#dBFS calculator

Here is a simple dBFS calculator:

You can download it in Flash SWF format or as a C source / Win32 binary (binary compiled with the DJGPP online-compiler).





The summing of decibel values is a bit of a confusing subject, i believe because decibels are units with no dimension (ratio like %) and also that they are logarithmic.

You can read this whole article for more information:
http://www.homeandprojectstudio.com/features/feature001.html

...Using dB FS (full-scale) in digital audio means that a change of +6 dB FS is the same as +10 dB spl (sound pressure level); in other words, twice as loud. How can this be? We know that each bit in a digital audio system increases the sampling resolution by approximately 6 dB. In essence, each bit represents an exponential increase in the sampling resolution, doubling the value with each bit. That’s why in a digital audio system, +6 dB FS, and not +10 dB spl, represents a doubling in sound levels. Not coincidentally, this corroborates the earlier statement that an increase of 6 dB is really a doubling of sound pressure, although not the perceived doubling of sound pressure. This is true for both analog and digital measurements.
The important bit here is to learn to distinguish different types of measurement (decibels). What you are seeing on the meters in your audio program is dbFS originally designed for ADCs (analog-to-digital converters) and assimilated by modern audio tools. dbFS is the reverse of dbSPL.

The above article explains an easy way to sum dbSPL values and also provides a table to convert dbSPL to dbFS (16bit only):

If you have 80dbSPL + 80dbSPL the result would be approx 83dbSPL (80+3), because the difference between the two is 0 units - from the "rule of thumb".

--------

a dbSPL calculator works with the following equation:

result = 10*(log(10^(input1/10)+10^(input2/10))/log(10)
where "input1" and "input2" are the dbSPL (!!) values you want to sum. 80db+80db=83db

--------

to sum two sinewaves in your audio program (with dbFS measures):

result = 20*(log(10^(input1/20)+10^(input2/20))/log(10)
But why 20*? Here is a explanation quote from wikipedia:

20 log rule, and similarly the formula for ratios of powers is the 10 log rule, and similarly for other factors. The factor of 20 is explained as: 10 is because it is in decibels (10ths of bels), and 2 is because it is a ratio of powers (squares of amplitudes): the product is 20.
So result for the sum of -9dbFS and -9dbFS, would be -2.97940008672037 for equal input/output impedance.

Lubomir

Thursday, March 5, 2009

#Designing an analog VU meter in DSP

Here are some notes on how to design a VU meter DSP fx.
I won't be getting much into the signal detection, but mostly into the visual of the plugin. If you wish to know more about it, please feel free to send me an email and I will be happy to respond to your questions.

Here is what we are going to use as an example. This is a very simple JesuSonic fx:



Setting some dimensions
We begin by setting the width and height for the visualization.
Its important to set the dimensions first, because they will determine the radius of the needle and the span of our scale.

We are going to make a rather large VU meter - 425x260px, with needle radius of 200px. You should be able to create an arch withing these dimensions using the needle radius.

Designing the VU meter scale
After the dimensions are set we can start creating our scale.
You can very easily design the scale, try to approximate other scales, or use ready equations.

In this example we are going to design our own scale by roughly approximating to an actual scale. There are a lot of photos of analog VU meter over the net. Different manufacturers have patented different scales. We will create our own (in a way).
Similar to this one for example:



We can use it as our base. In general its very difficult to make the approximation 100% accurate if you don't know the original function. Still there are ways to (try) to do so. For example LaGrange polynomials can help you with that. It may require a lot of points to be interpolated and the resulting function and the algorithm may became much more inefficient than a simple exp(). Also by using interpolation there might be some minor unavoidable and unwanted deviations between points.

First thing to do is to set some scale markings in dB:
-20, -10, -7, -5, -3, -2, -1, 0, +1, +2, +3

Here is how to convert amp signal in dB and then get the value of X (dB -> pixels on the X axis):



//code executed at bigger intervals - 1024 samples for example

//amp2dB
//take only abs(input) of input
//6/log(2) is our dB scale
in_db = log(abs(input))*6/log(2);

//then

//xl - is the value of X
//in_db - is the value in decibels
//use numbers 2.1 and 285 to tweak the equation
xl = floor(exp(log(1.055)*2.1*in_db)*285);


xl is the result we are looking for here, after converting amp into dB.
A very useful thing to do is to use some sort of a plotting program which can make calculations and draw some lines at the same time. I've used Adobe Flash which is quite fast to work with.


fig.1

The vertical lines on the left and right represent our width. Point O is the center the circle. Point A lies on the circle therefore OA = r. Point S0 represents a point from our scale using the above equations. To draw the actual lines from the scale, two additional large arches may be used (colored in blue). If we connect O with S0 an intersection will occur between the new cirlces and OS0. These are points D01, D02. So lines such as D01D02 will be visible on our scale. When we know all the coordinates of the points we can make an arrayand draw these 'markings' on plugin initialization.

Drawing the needle in realtime
After we have the result on the X axis we can start drawing the needle.
Of course if you wish to use a bitmap as the needle you should use a different method here (i.e. calculate angle of rotation).


fig.2

The math method used here to calculate point A's X,Y coordinates is by using proportional triangles and Pitagor theorem - as simple as it gets. Where: S0A / AO = P1A / AP2 etc. And since we know some of the lengths and coordinates of points we can get point A very easily.


//get y from x and radius - r
//Pitagor and proportional triangles used here
l=sqrt(sqr(r)+sqr(212-xlt));
h=((l-r)*r/l);
m=sqrt(sqr(l-r)-sqr(h));
ylt=35+h;
xlt < 212 ? xlt=xlt+m : xlt=xlt-m; // check if x is < of middle point 212


The results - xlt & ylt are the A's x,y coordinates and after we have them, we can draw a line between O and A in realtime.

Needle response
Updating the needle per sample is not advisable so I suggest that you use some sort of a countdown before make the above calculations. After some trial and error you will get an acceptable 'response' speed. You should know that the magnetic-electric system (inductor+constant magnet) of an analog vu-meter has response of 300ms. This is quite slow but of course you can tweak it.

Another characteristic of the needle response is the inertial fallback. This is due to the inductor exponential discharge. After executing the x,y calculation code you can add the fallback by simply subtracting pixels from X (original exp() scale) while multiplying the result by some factor for adding inertia (emulating the discharge).

Limiting x and y of A may also be a good thing since the given log scale in dB can go as low as -350db. Or you can just limit the input gain value to -25,+3.5 db

RMS window
Adding a RMS detector isn't very difficult to make in DSP either. Here is an example:


//***per sample
//cs - current sample counter
//300 - window in ms
//sum - peak values stored here
if (cs == (0.001*300*44100)) {
cs = 0;
sum = 0;
} else {
cs += 1;
//square the abs value of the input
sum += sqr(abs(input));
}
//***execute at bigger intervals - at sample block for example
//calculate value while converting into dB
//*100/100 is to output the values in the X.XX format
rms = floor(6/log(2)*log(sqrt(sum/cs))*100)/100;


So 'rms' would be our RMS value for a 300ms window.

Thats all...well mostly. If you have any question post a comment here or send me an email.

I leave that task of making the VU meter look good to you.

Lubomir

Saturday, January 10, 2009

#SJEA - Simple Java Encryption Algorithm

Not long ago (around 2007), I wrote this very simple encryption algorithm to help out a friend with the master's degree in computing. After a while I realized this could turn out to be a great stand alone project.

It was collecting dust for quite some time (one year or so) and I've decided that I should work more on this and complete it as a accessible public package. So recently I've managed to tidy the source, make some examples, write the documentation and now its finished - SJEA (Simple Java Encryption Algorithm). I have to admit the name is a bit silly for the simple reason that the 'J' can be replaced very easily (with source porting) to 'C' as a 'Simple C Encryption Algorithm' SCEA or anything else to be honest.

Going back to cryptography studies was pure fun. Back in the day around y2000 I was reading a lot on the subject and this resulted a lot of drafts. I guess this project will be the first I release under GPL. Now back on the topic.
SJEA v1.0SJEA started when I was looking for an alternative solution (a completely custom algorithm) to all the pre-made libraries in JAVA, C etc. Having something for granted is cool, but making your own tools may give you some great satisfaction. The idea of the project was that the result are good (not that easy to hack/decrypt with conventional tools) but the source (roots of the algorithm) easy to understand by people who are new to this type of study. So I've decided to have a go with Block and XOR ciphers. I was dealing with such for quite a while, so it wasn't a problem to implement them into some sort of a starting template.

The XOR method (the method behind all the calculation) is quite simple to understand:
We have an input byte that we sum with a key (modifier) and then we have a result. But if we subtract the key from the end result we will get the original input byte.

where A-input, B-mod, C-sum for a single byte entry
A+B=C //encryption
C-B=A //decryption


In SJEA the 'ECB' (Electronic codebook) window method can be found since we use a user password as our key. The password is used as a first layer of encryption. A vector byte-array is also present as a second layer. This complicates things a little (not that much) since even if you know the key modifier layer you wouldn't know the value of the vector.

Here is the 2-layer encryption scheme:

     (bytes)
      input: AAAAAAAAAAAAAAAAAAAAA + (sum)
     vector: 01234567890ABCDEF0123 + (sum)
   password: HELLOHELLOHELLOHELLOH =
     result: XXXXXXXXXXXXXXXXXXXXX


The project can be aimed at the following audiences:
- students of computing
- future algorithm programmers
- people who a learning into cryptography

It may eventually grow into a lot bigger project with many different encryption examples.

And here is a brand new website hosted by sourceforge.net:


http://sjea.sourceforge.net/


or the googlecode page:
http://code.google.com/p/sjea/

Lubomir

Wednesday, January 7, 2009

#MP3 player in blog - done easy

I've extended the 'hcon' JS lib to allow quick embedding of MP3 files.

The MP3 embed code is also stored here:
<script src='http://sites.google.com/site/neolit123/Home/hcon' type='text/javascript'/>
The above line should be embedded in you blog template.

How does it work:
<mp3 file="http://locationtomyfile.com/file.mp3" title="Song title goes in here"></mp3>
Demo:


The code is using 'innerHTML' once again so it may not work under IE.
If you wish to modify the JS (mp3 player URL, style etc) download it from here(rename to .js). More info about the player: http://www.1pixelout.net/.

Enjoy
Lubomir

Tuesday, January 6, 2009

#Show/Hide information in blog posts

This is probably the easiest way I've found so far to show/hide contents in posts. There are other solutions floating around but I think this one is the most user-friendly.

To enable the show/hide functionality open you blog-template (customize-layout-edit html) scroll down to the bottom and copy/paste the following code just above the end [/body] tag:

<script src='http://sites.google.com/site/neolit123/Home/hcon' type='text/javascript'/>
Save the template.
This enables the use of a simple [hcon] tag to hide/show contents. Here is an example:
<hcon open="[+]Open..." close="[-]Close...">Loooong text<hcon>More long text</hcon></hcon>
The 'open' and 'close' attributes are used to specify text names for the buttons. If no values are given [+]More... and [-]Less will be used by default. Also you can see that nesting is possible - as complex trees of [hcon] tags.

Here is a demo:
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec lacus. Donec ultricies sem id nunc. Integer dignissim aliquam nisi. Phasellus varius. Suspendisse sit amet diam id libero pulvinar commodo. Vivamus a ante. Aenean non nisl. Morbi a turpis id sem gravida accumsan. Vestibulum sollicitudin, ligula sit amet consequat lacinia, neque ante condimentum neque, mollis bibendum quam lacus vel ipsum. Duis ac lectus a ante convallis commodo.
Praesent ac ligula. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Quisque lacus. Vivamus purus. Phasellus quam lectus, volutpat nec, tempor quis, facilisis nec, ligula. Nam fermentum eros eu enim. Maecenas est magna, bibendum eget, auctor vel, ultricies et, ligula. Maecenas id arcu et magna congue posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse potenti. Phasellus interdum. Ut nisi augue, fermentum vel, tempor sed, accumsan vitae, augue. Duis eget tellus. Etiam vulputate aliquet massa. Suspendisse potenti. Curabitur interdum porttitor velit. Ut et arcu et est dapibus porta.

Some notes:
- You can download and modify the hcon file (rename to .js). Also upload it to a faster server.
- Its working with the latest FF, Opera. With IE there seems to be a problem with innerHtml(the bug is described here).
- Under the K-Meleon browser I've noticed that the "blockquote", "div", "h" tags break the [hcon]. Also the the nesting is not working correctly.
- It also supports the [mp3] tag now: Link


Lubomir

Sunday, January 4, 2009

#JesuSonic plugins for Reaper

JesuSonic from Cockos proved to be a very efficient and flexible platform for designing DSP effects. The JS engine is bundled with Reaper (aka the ultimate secret weapon DAW).

I have created a small pack of JS fx that I regulary update (or used to) at the Cockos forum. The pack includes various filter implementations such as the the classic Moog, Butterworth, Chebyshev Type I and various fx that I have either ported/modified from other programming languages or designed from scratch.

You can always check for the latest version of the pack at this page:
Link

Lubomir