home :: event_mechanism
Event Mechanism
Each class in the coding element event class hierarchy implements an event-based mechanism for informing your code via callbacks when a particular coding element has been parsed. To explain how this mechanism works, let's take a closer look at how it is implemented in the root CodingElement class.
The CodingElement class defines a delegate with the following signature:
public delegate void Handler(BitStream bs, CodingElement e)
This is the signature that your callback must adhere to. The first argument BitStream bs will be set to the BitStream object that the coding element was parsed from. This is useful if you are trying to process more than one stream at a time and need a handler to disambiguate which stream the coding element came from. The second argument, CodingElement e is set to the actual coding element that was parsed.
Given a callback with the appropriate signature, you construct a delegate for the callback in the normal C# way. As a reminder, this means if your callback is defined as:
void my_callback(BitStream bs, CodingElement e) {...}Then you can create the delegate with code like:
CodingElement.Handler callback_delegate = new CodingElement.Handler(my_callback);
The delegate serves as a type-safe wrapper for the function pointer to your callback. Your callback can be an instance method of an object or a statically defined class method. The only requirement is that it match the signature given by the delegate definition. Once you have the delegate defined, you add it to the list of handlers for the coding element class using the statically defined event named handlers like so:
CodingElement.handlers += callback_delegate;
Now when a coding element is parsed, it publishes itself to all of the registered callbacks by invoking the registered delegates via the virtual protected method publish. This method first publishes the event to any parent classes. In this way, any and every callback registered with a particular coding element class or any ancestor of that class will be called for that coding element with the more general handlers being called before the more specific handlers.
Every subclass in the hierarchy under CodingElement implements this publication mechanism and by convention, each defines the delegate as Handler and maintains the registered callbacks in handlers. So, for example, the coding element class PictureCodingType, which is created when the picture coding type code is encountered in a picture header, defines the PictureCodingType.Handler delegate and maintains registered callbacks in the class variable PictureCodingType.handlers.
To remove a callback, simply "subtract" the delegate from the list of handlers like so:
CodingElement.handlers -= callback_delegate;
