Working ffmpeg custom IO code

July 14, 2011
FFmpeg

Image via Wikipedia

Since a lot of people were interested in the custom IO article, I thought I’d  upload the working code here. This is the video module taken as is from Conspiracies 2 : Lethal Networks source code:

Get it here.


How to study objective C under windows

October 6, 2010
Screenshot of Cygwin

Image via Wikipedia

Objective C seems to gain popularity nowadays. My only exposure to this language is through random snippets I saw here and there, mostly written by friends of mine, chasing the dream of becoming the next iPhone millionaire. And I have to say: I find it ugly. I mean really really ugly!

People say though, that once you get used to it, it seems natural and it has advantages (read: late binding) that make it a powerful tool for creating applications.

Well, after all its just another programming language. So I thought I’d give it a try.  Preferably without owning a mac.

Here is how I did it:

  • Download cygwin – install it with the default settings.
  • That’s about it! Cygwin comes with an objective C compiler, so you are good to go once you install it.

How to write a first objective c test program:

#import <stdio.h>
int main(int argc, char *argv[]) {
    printf("Hello, from objC!\n"); 
}

Create a file named “hello.m” in your cygwin home directory containing the above code. Then open a cygwin prompt and write the command: gcc -o hello hello.m

And there you have it, a free development environment to try out the language. Your next step (pun intended) might be a good tutorial or a book describing the language. I suggest something that covers the language only, not the common APIs (GNUstep, Cocoa, whatever). If you think you can stand the language itself, you can then try to learn the APIs and create that iPhone app you were dreaming about!


How to seek to the end of a video stream using ffmpeg

October 6, 2010
FFmpeg

Image via Wikipedia

This was really simple, but took me about a day to find out. A google search didn’t help this time so I post it here and maybe it is going to help someone else.

It turns out that the format context has a handy member: duration. This may or may not be valid, so it needs to be checked before using it. The following two lines of code will do the trick:

av_seek_frame(pFormatCtx, -1, pFormatCtx->duration, 0);
avcodec_flush_buffers(pCodecCtx);

When using -1 as a stream index, the time is measured in ffmpeg’s time base, which is the same unit the duration member is in.


A neat trick to remember pentatonics

July 14, 2010
The Cmaj chord in guitar, with bass in G

Image via Wikipedia

The minor pentatonic must be the most widely used scale when it comes to soloing and improvisation. There are many methods to learn it, usually involving boxes around the fretboard. I recently discovered a better method.

The minor pentatonic has only 5 notes, and its shape is really simple. It’s just a cross:

..*..
*.*.*
..*..

Every character in the above diagram represents a fret. Asterisks are frets inside the pentatonic and dots outside. It’s played as follows:

  1. Play ‘A’ with your 3rd finger, Bass E string, fret 5
  2. Play ‘C’ with your 1st finger, A string, fret 3
  3. Play ‘D’ with your 3rd finger, A string, fret 5
  4. Slide with your 3rd finger to reach ‘E’ in fret 7
  5. Play ‘G’ with your 1st finger, D string, fret 3
  6. Place your 3rd finger on fret 7 and continue from step 1

This pattern can be continued two more times. Then we reach the last string. There is also another position where you can start the cross pattern. Start from string A, fret 12, and continue on …

The only place where the pattern breaks is between strings G and B, because of the standard guitar tuning. When going from G to B, go one more fret to the right, and do the opposite when going from B to G.

It goes without saying that all minor pentatonics can be played this way. Just put the 3rd finger on any note and start the cross pattern. The scale’s root will always be the “tail” of the cross.

Major pentatonics can be played as easily as minors. You just start the pattern with your first finger from the “left hand” of the cross. For example to play the C major pentatonic all you have to do is start from step 2.

Although I also recommend studying the standard boxes for scales, this method has many advantages:

  1. It’s ridiculously easy to memorize
  2. You are using only fingers 1 (index) and 3 (ring) which are the stronger
  3. If you let the slide (in step 4) ring, you get a beautiful chromatic pass by the “blue note”. This will also remind you where that note is
  4. It covers the entire fretboard

… and one and two …


How to save global variables using the lua C API

June 26, 2010
Lua (programming language)

Image via Wikipedia

This function will save all the global variables in a lua state. Only string, number and boolean variables are supported, but this code can be easily extended to support tables as well.

Enjoy :)

void LuaState::DumpGlobals()
{
	// push the first key (nil = beginning of table)
	lua_pushnil(L);

	// lua_next will:
	// 1 - pop the key
	// 2 - push the next key
	// 3 - push the value at that key
	// ... so the key will be at index -2 and the value at index -1
	while (lua_next(L, LUA_GLOBALSINDEX) != 0) {
		// get type of key and value
		int key_type = lua_type(L, -2);
		int value_type = lua_type(L, -1);

		// support only string keys
		// globals aren't likely to have a non-string key, but just to be certain ...
		if (key_type != LUA_TSTRING) {
			lua_pop(L, 1); // pop the value so that the top contains the key for the next iteration
			continue;
		}

		// support only number, boolean and string values
		if (value_type != LUA_TNUMBER &&
			value_type != LUA_TBOOLEAN &&
			value_type != LUA_TSTRING) {
			lua_pop(L, 1); // again, pop the value before going to the next loop iteration
			continue;
		}

		// get the key as a string
		string key_string = lua_tostring(L, -2); // no copy required - we already know this is a string

		// do not support variables that start with '_'
		// lua has some predefined values like _VERSION. They all start with underscore

		if (!key_string.size()) { // this again is highly unlikely, but still ...
			lua_pop(L, 1);
			continue;
		}
		if (key_string[0] == '_') {
			lua_pop(L, 1);
			continue;
		}

		string value_string;

		// convert the value to a string. This depends on its type
		switch (value_type) {
		case LUA_TSTRING:
		case LUA_TNUMBER:
			// numbers can be converted to strings

			// get the value as a string (this requires a copy because traversing tables
			// uses the top of the stack as an index. If conversion from a number to string
			// happens, the top of the stack will be altered and the table index will become invalid)
			lua_pushvalue(L, -1);
			value_string = lua_tostring(L, -1);
			lua_pop(L, 1);
			break;
		case LUA_TBOOLEAN:
			value_string = lua_toboolean(L, -1) == 0 ? "false" : "true";
			break;
		}

		// enclose the value in "" if it is a string
		if (value_type == LUA_TSTRING) {
			value_string = "\"" + value_string + "\"";
		}

		// resulting line. Somehow save this and when you need to restore it, just
		// call luaL_dostring with that line.
		SaveLine(key_string + " = " + value_string);		// Pop the value so the index remains on top of the stack for the next iteration
		lua_pop(L, 1);
	}
}

Seeing Evolution with Blind eyes

May 10, 2010
The Blind Watchmaker

Image via Wikipedia

This is the second time I read “The Blind Watchmaker“. This is an excellent book and in my opinion its a must-read for everyone. It is written in plain English, with no heavy terminology, and besides its brilliant counterarguments against the ones used by creationists, it talks about genetic algorithms as a bonus!

Yesterday night I started reading chapter 3, which presents an excellent argument that I’d like to repeat here. The usual arguments against evolution revolve around complexity and chance. Something along the lines of “Living things are extremely complex, so they couldn’t have been created by chance”. In order to address this argument one must differentiate between types of chance and that’s what this argument does:

Ask yourself two questions:

  1. Can something that is not a human eye transform into a human eye by chance?
  2. Can X transform into a human eye by chance, given that X is something very similar to a human eye?

The answer to the first question is by all means, “no”.

The answer to the second one must be a strict “yes”. If you did not answer yes to the second question then you have chosen a wrong X, a very distant from a human eye. Find another one, halfway between your X and the human eye and ask yourself again. Do this for as many times as it takes until the answer is positive. Then you will have a good understanding of the role that chance plays in the process of evolution. Evolution needs just as little luck as that to work!

You can then ask yourself the same question for X itself: Find another X (let’s call it X’) that could have been transformed to an X by chance. Repeat the process many times until you reach an X that is not at all a human eye. Then the process of evolving an eye from no eye at all breaks down into a series of events, that each of them has a relatively high probability of taking place spontaneously.

Even though the concept of very small changes is basic in order to even begin understanding evolution, this is by far the best way to put it, with no technical terms at all but still completely accurate! Dawkins has  a rare talent of describing complex things with simple words. I really admire him and I started studying biology because of his books. I only wish there were more people like him among our professors :)

Side note: Evolution is not a theory. I hear that a lot, usually in the form of a cheap argument. Evolution is a fact as well documented as gravity. Theories like soft inheritance and natural selection attempt to explain the fact of evolution, just like the inverse square law and the general theory of relativity attempt to explain the fact of gravity.

Happy evolving!


Gamedev tip #2 : Divide and conquer

April 29, 2010
Rubik's Cube

Image via Wikipedia

Even today, I am overwhelmed by the difficulty in creating a video game. Since the first years I learned how to program it seemed like a relatively easy task. Ok. I could draw a teapot on the screen. I could play sounds and music. It was ridiculously easy to see what keys was the user pressing, to read a file from disk and what not.

It’s not about the lines of code

So why is making a game more difficult than the sum of all these? This is something I found out the hard way! The relationship between the size of a project and its difficulty is not linear. Games today are usually large projects with a magnitude of tens to hundreds thousands lines of code. Thus, creating an average game today presents a challenge that requires taking a very different approach than someone is used to when dealing with small scale projects.

When a project grows, its difficulty grows not with the lines of code, but with the number of interactions that exist between the various parts of the code. These interactions must be taken into account all the time. Let us define a fully unstructured project as one in which every part of the code is able to interact with every other part. In that case these interactions are not proportional to the project’s size, but to its square.

Someone with background on algorithms can easily see where this is going… When a project is not structured, it becomes increasingly difficult to manage, until it eventually reaches a point where any addition or change becomes prohibitively troublesome.

Fortunately there exists a solution, but it requires a somehow different mindset than the one we are used to when working with small projects.

High level design

Apologizing in advance to all the people who have devoted their lives to software development and have read and written dozens of books on the subject, I am just going to say here what in my opinion is most important with respect to our context:

High level design is all about separating a large project into logical parts which are mostly independent from each other. Ideally this way we can treat every part (or module) as a small program. The keyword here is “independent”, and represents the change in mindset I was talking about earlier.

When working on a small project, we are most concerned about writing the least amount of code possible  in order to achieve our goal. As a result we focus more on reusability and we try to reuse pieces of code regardless of where in the code they exist. In essence there is no distinction between parts of code. Everything belongs to a single entity, our program, which we can manage as long as it stays small.

On the other hand, when we design something bigger, our first concern is different. We must focus on making sure that the project ever gets completed. And to achieve this we have to find a way to fight its tendency to become harder as it grows. We saw that this tendency springs from the interactions between code rather than the size of the code itself.

Preparing for a large project

So how do we deal with these interactions? Its simple: Forbid them! This is what high level design is all about. Forbiding interactions (or dependencies) between modules. The first step is to divide our code to logical parts our program will consist of. For example: graphics, sound, math, input, game logic.

We then document which modules will be allowed to depend on each other. For instance it must be obvious that graphics must not depend on sound. But there are more subtle cases. Does the sound module need to depend on math? Modern games feature 3d sound with various sound sources placed in different positions in the game world. Setting their position and velocity using a vector class might seem like an attractive idea:

sound_source->SetPosition(Vector3 pos);

How elegant is that. However is that enough to support the addition of one more dependency? The answer is no. Every dependency between modules must justify its existence beyond any doubt. We could have easily avoided the dependency like this:

sound_source->SetPosition(float x, float y, float z);

Maybe not as appealing as the former, but its not so much more troublesome either, and its enough to get rid of a dependency which is our very first priority here.

There will certainly be situations where its difficult to decide if a dependency is justified or not. I have a rule of thumb for these: “When in doubt, forbid!“, and here is why:

  • Dependencies are evil! Believe a man who has suffered!
  • If you are in doubt, you are probably already thinking about a way around the dependency. If that way was not easily implementable, you would not have been in doubt in the first place.
  • Even if you took a wrong decision, adding a new dependency is always easier than removing an already existing one.

So to summarize:

In order to give a large project a hope of ever being completed, we must divide it into small entities and forbid as many dependencies between them as possible.

I intended to add more here about my own frightening experiences, in order to show how troublesome can underestimating dependencies be, but this post already exceeded the size of a “tip”. So I will be postponing the terror for my next tip about unit testing which is somewhat related anyway.

Set your modules free!


Follow

Get every new post delivered to your Inbox.