Template Information

Trang

Chủ đề

BSP (44) Device Drivers (43) WinCE (38) WINDOWS DRIVER (19) Linux Device Drivers (18) ARM (17) Android tools and tips (17) DRIVER FILES (16) Windows Device Driver (16) AUDIO DRIVER (12) 8051 (8) OMAP (7) PRINTER DRIVER FILES (7) C Programming (6) ASUS MOTHERBOARD (5) Interfacing (5) NETWORK ADAPTER (5) VIDEO DRIVER (5) CANON (3) Device Driver Downloads (3) MOBILE PHONE (3) Asus Driver (2) EPSON (2) Epson Printer Driver (2) HP LAPTOP DRIVER (2) LAPTOP DRIVER FILES (2) Logitech Driver (2) NETWORK ADAPTOR (2) OMAP 4430 (2) drivers download (2) ACER (1) ACER TABLET (1) ALL IN ONE DRIVER (1) Acer Aspire 5738 Drivers (1) Analog-to-Digital (1) Asus Drivers (1) Asus Motherboard Drivers (1) Chip Architecture (1) DELL (1) Dell D610 Drivers (1) Dell Drivers (1) Device Drivers Download (1) Device drivers interview questions (1) Display Driver (1) Drivers Download for Windows 7 (1) EEPROMs (1) Free Asus Motherboard Drivers (1) Free Drivers Download for Windows 7 (1) GRAPHIC DRIVER (1) HP Driver (1) Hardware (1) Intel Drivers (1) Intel P35 (1) Intel P35 chipset drivers (1) I²C (1) LAPTOP SERVICE MANUAL (1) LCD (1) Logitech Mouse Driver (1) Logitech webcam driver (1) MODEM DRIVER (1) Motherboard Drivers for Windows 7 (1) PARALLEL PORT (1) Pc Driver (1) RTOS (1) Real Time Clock (1) Sensors (1) USB CABLE DRIVER (1) WEBCAM DRIVER (1) WIRELESS ADAPTOR (1) Windows 7 Drivers (1) Windows Mobile (1) acer driver (1) acer driver downloads (1) acer laptop driver (1) chipset drivers (1) network card driver (1) network driver download (1) sdcc (1)

Bài viết ngẫu nhiên

Xem phim HD Online

Số lượt views

Hiển thị các bài đăng có nhãn Windows Device Driver. Hiển thị tất cả bài đăng
Hiển thị các bài đăng có nhãn Windows Device Driver. Hiển thị tất cả bài đăng

Notifications and Power Management under Windows Mobile: Benefit from Both

Thứ Bảy, 15 tháng 10, 2011 / 01:28

One misty moisty morning
When cloudy was the weather...

One day a good friend of mine, David Herman, came to me, claiming that a piece of software that was supposed to take its data automatically from a remote server in the middle of the night, stopped working on Windows Mobile 2003 devices. More exactly, it had started to operate, but could not perform all the required steps. Not that it didn't work at all, no, but the PDA's screen was turned off, communications weren't opened, and so forth. a After quick search on the Web, I found that, to my great surprise, there is nothing that might solve the problem. Well, maybe I did not search hard enough. Anyway, I've started to investigate the case, and so this article has begun...
This article isn't dedicated to all of title's topics in depth, but rather intends to combine bits from here and from there to get all the stuff working together. There is no need to dive into well-documented functionality, at least for Notifications. Windows CE Power Management articles are also presented in MSDN. It left us just to add one and one. Besides, Windows Mobile 5.0 gives a programmer a few more options for customization, so I will overview them as well.

Two Faces of Notifications

When one talks about Notifications under Windows Mobile, one usually means two main areas: shell notifications (defined in aygshell.h) and user notifications (notify.h respectively). The first type allows your application to inform the user that something important has just happened; for example, that a new message has arrived. The second type is used to deal with a dozen system-level events, such as network connection being established and so forth. This article will discuss both of the above notification types.

User Notifications

I will start from more traditional Windows CE notifications. Those of you who have developed for older versions of Windows CE are definitely familiar with them. You were able to program your application to respond to a set of system events or to be launched at some point in time. But, things have changed since those times, so now you can see the following statement in notify.h:
//
//Obsolete; provided to maintain compatibility only
//
HANDLE CeSetUserNotification (HANDLE hNotification,
TCHAR *pwszAppName,
SYSTEMTIME *lpTime,
PCE_USER_NOTIFICATION
lpUserNotification);
BOOL CeRunAppAtTime (TCHAR *pwszAppName, SYSTEMTIME *lpTime);
BOOL CeRunAppAtEvent(TCHAR *pwszAppName, LONG lWhichEvent);
BOOL CeHandleAppNotifications (TCHAR *pwszAppName);

It means that all those old buddies you used to rely on can stop working anytime. Instead of the above functions, the SDK offers you an equivalent means:
BOOL   CeGetUserNotificationPreferences (HWND hWndParent,
PCE_USER_NOTIFICATION
lpNotification);
HANDLE CeSetUserNotificationEx (HANDLE hNotification,
CE_NOTIFICATION_TRIGGER *pcnt,
CE_USER_NOTIFICATION *pceun);
BOOL CeClearUserNotification (HANDLE hNotification);
BOOL CeGetUserNotification (HANDLE hNotification,
DWORD cBufferSize,
LPDWORD pcBytesNeeded,
LPBYTE pBuffer);
BOOL CeGetUserNotificationHandles (HANDLE *rghNotifications,
DWORD cHandles,
LPDWORD pcHandlesNeeded);
In fact, these are the same APIs but rewritten in other terms. Windows Mobile SDK gives you even more. It defines and uses a CE_NOTIFICATION_TRIGGER struct to declare how to trigger the required entity:
typedef struct UserNotificationTrigger {
DWORD dwSize;
DWORD dwType; //dwType Notification type
//dwEvent - type of event if dwType == CNT_EVENT
DWORD dwEvent;
//lpszApplication - name of application to execute
TCHAR *lpszApplication;
//lpszArguments - command line (sans app name)
TCHAR *lpszArguments;
//stStartTime - begin of notification period
SYSTEMTIME stStartTime;
//stEndTime - end of notification period
SYSTEMTIME stEndTime;
} CE_NOTIFICATION_TRIGGER, *PCE_NOTIFICATION_TRIGGER;
In addition to running your application (with the appropriate command line) at a given time or event, now you can specify a time period. Besides, Windows Mobile or CE.NET supports named events, so you may want to use it for lpszApplication instead of the application name in the form of:
"\\.\Notifications\NamedEvents\Event Name"

Shell Notifications

This kind of notification is also pretty easy. Quite a few functions handle all the job:
LRESULT SHNotificationAdd(SHNOTIFICATIONDATA *pndAdd);
LRESULT SHNotificationUpdate(DWORD grnumUpdateMask,
SHNOTIFICATIONDATA *pndNew);
LRESULT SHNotificationRemove(const CLSID *pclsid, DWORD dwID);
LRESULT SHNotificationGetData(const CLSID *pclsid, DWORD dwID,
SHNOTIFICATIONDATA *pndBuffer);
They allow you manipulate the notification's look-and-feel and features. Windows Mobile 5.0 slightly extends WM 2003's functionality by adding new members to the SHNOTIFICATIONDATA struct:
typedef struct _SHNOTIFICATIONDATA
{
DWORD cbStruct; // for verification and versioning
DWORD dwID; // identifier for this particular
// notification
SHNP npPriority; // priority
DWORD csDuration; // duration of the notification
// (usage depends on prior)
HICON hicon; // the icon for the notification
DWORD grfFlags; // flags - see SHNF_ flags below
CLSID clsid; // unique identifier for the
// notification class
HWND hwndSink; // window to receive command choices,
// dismiss, etc.
LPCTSTR pszHTML; // HTML content for the bubble
LPCTSTR pszTitle; // Optional title for bubble
LPARAM lParam; // User-defined parameter
// From here, this is WM 5.0 stuff
union
{ // Defines the softkey bar for the
// notification
SOFTKEYMENU skm; // Either pass an HMENU in skn
// (and set SHNF_HASMENU)
// or two softkeys in rgskn.
SOFTKEYNOTIFY rgskn[NOTIF_NUM_SOFTKEYS];
};
// Text to put on SK2 on the Today screen. If NULL, will
// default to "Notification"
LPCTSTR pszTodaySK;
// What to execute when SK2 is pressed. If NULL, the toast
// will be displayed.
LPCTSTR pszTodayExec;

} SHNOTIFICATIONDATA;
The following code sample shows one simple scenario:
void ^157BOOL158^::OnBnClickedButton1()
{
SHNOTIFICATIONDATA sn = {0};

sn.cbStruct = sizeof(sn);
sn.dwID = 1971;
sn.npPriority = SHNP_INFORM;
sn.csDuration = 15;
sn.hicon = LoadIcon(AfxGetResourceHandle(),
MAKEINTRESOURCE(IDR_MAINFRAME));
sn.clsid = SAMPLE_GUID;
sn.grfFlags = 0;
sn.pszTitle = TEXT("Sample Notification");
sn.pszHTML = L"<html><body><p><form method="POST" action=>"
L"<p><font color="#0000FF">"
L"Visit <a href="www.developer.com">
<b>Developer.com</b></a> !"
L"</font></p>"
L"<p align=right>
<input type=button name='cmd:1001' value='OK'>"
L"<input type=button name='cmd:1002'
value='Cancel'></p>"
L"</body></html>";
sn.rgskn[0].pszTitle = TEXT("Dismiss");
sn.rgskn[0].skc.wpCmd = 1003;
sn.rgskn[0].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_DISABLED;
sn.rgskn[1].pszTitle = TEXT("Hide Me");
sn.rgskn[1].skc.wpCmd = 1004;
sn.rgskn[1].skc.grfFlags = NOTIF_SOFTKEY_FLAGS_HIDE;
sn.pszTodaySK = L"Run Calc";
sn.pszTodayExec = L"\windows\calc.exe";

//Add the notification to the tray
SHNotificationAdd(&sn);
}
Under WM 5.0, you can customize how your notification will appear when displayed for the user:

and on the Today screen:

Shortly speaking, both User or Shell Notifications API are intuitive enough; hence it isn't worth spending too much time on it now. There are a lot of samples all over the Web in C/C++ or C# or VB. That's not a point here. Real troubles start when a device gets turned off. And, here is when Power management can help us.

Involving Power Management

The Windows Mobile OS has a dozen functions that allow applications to control the power policy and query various information. Once again, I won't discuss them too much, but move on to the situation described in the preface.
When a device has been suspended and after any notification gets activated, the system turns to a "resuming" power state. In such a mode, the CPU is running, but the display is not powered to save the battery. Moreover, some of the PDA's features may be inactivated as well; for example, the GPRS modem. "Resuming" the power state continues for 15 seconds, and then, if nothing happens, a device will be suspended once again. Thus, you face the situation when your application is honestly called, but it can't interact with the external world or gain the user's attention. For background operations, it works like a charm, but for notifications, that is not the case. Thus, you need a way to turn on the system. The obvious answer is to call:
SetSystemPowerState(
LPCWSTR pwsSystemState,
DWORD StateFlags,
DWORD Options
);
as follows:
SetSystemPowerState(NULL, POWER_STATE_ON, 0);
In other words, such a call simply wakes up the device and gets it to its full live state. That is exactly what you need in many cases. Later on, you also can call:
SetPowerRequirement(
PVOID pvDevice,
CEDEVICE_POWER_STATE DeviceState,
ULONG DeviceFlags,
PVOID pvSystemState,
ULONG StateFlags
);
to require an 'always on' state while doing some lengthly operation; for example, communications. And with that said, this story has its "happy ending."
Thứ Bảy, 15 tháng 10, 2011 01:28 Đọc tiếp >>

Porting Your Mobile Applications to the VS 2005 Environment

MS Visual Studio 2005: Why Be Bothered with It?

With the release of MS Visual Studio 2005 last November, Windows Mobile 5.0 at the very end of its beta cycle, and a proliferation of WinCE 5.0-powered devices, it is time to commence considering to move your C/C++ mobile applications from eMbedded Visual C++ to the new development environment. You can reasonably ask why you should do it at all and battle new headaches if you still can continue to use existing developing tools and libraries. In my opinion, there are serveral reasons that could cause you to think it over seriously right now. I will leave aside the features of the IDE itself and discuss the pros and cons with a developer's vision.

Porting Possibilities

If you have an existing eVC project and want to import it into VS 2005, you have two options. One is to use eVC Upgrade Wizard add-on for VS 2005, which is available for download from Microsoft's site here. If you take a look at the bottom part of this page, you will see a notice that this is an unsupported addon, so you have a good chance to experience some problems with it. Nevertheless, it may help you migrate your project easily enough. You might be required to adjust some of the project settings—for example, a way of MFC usage—but usually they are really minor ones.
The second way is to create a brand new solution and projects and then manually add all files. It looks more a more difficult method, but in some cases this is the only thing to do because you can get the standard header files and project settings. This allows you to avoid some weird warnings and problems during solution compilation and linkage. Links at the end of this article may help you get more details.
Whichever way you use, now you have your application available under the MS Visual Studio 2005 IDE.

Benefits and Issues

C/C++ projects support and emulators

First of all, VS 2005 comes with support for native C/C++ projects and new emulators for smart devices. If you have had the chance to code really large mobile projects with millions of code lines, you will agree that it was almost impossible to use SDK emulators from eVC 3.X or 4.X. They are slow, they are not robust, they are... This left only one alternative to a developer: to use the old Palm-Size 2.11 emulator. It obviously made a serious impact on such applications. With new emulators, you can get rid of the old dragon. Not only that it is fast enough, but also is able to execute the code compiled for real devices, which is a nice capability. Thus, your application will look and behave more like its real instance on the handheld.


Native device C/C++ projects support hasn't came for free. Microsoft made many additions to the C++ compiler ever since VS 2003 in comparison with eVC++, and the new Studio also keeps pace. It results in many tiny but annoying compiler errors like the following case:
//
for (int i = 0; i < nCount; i++)
{
...
}
...
for (i = 0; i < nCount2; i++)
{
...
}
The second for statement will generate an 'undeclared variable' error. I haven't yet seen any C++ programmer who would write the above code in C-style.
int i = 0;
...
for (i = 0; i < nCount; i++)
{
...
}
...
for (i = 0; i < nCount2; i++)
{
...
}
so you may evaluate a number of possible changes here. You will find additional info regarding new C/C++ compiler features among the links at the end of the article.

Moving Forward to MFC 8.0

If your application uses the MFC library for Windows CE, you can expect many surprises as well, and they are not always pleasant. Version 8 of MFC and ATL were significantly changed since previous MFC 3.0 times. Some changes were expected, for instance, new string classes, but other ones I honestly can't get. Just take a look at the following list of unsupported classes (you can get full info here):
  • CSplitterWnd
  • CDialogBar
  • CReBar
  • CColorDialog
  • CFindReplaceDialog
  • CFontDialog
  • CPrintDialog
  • COlePropertyPage
  • CEditView
  • CBitmapButton
  • CReBarCtrl
  • CSocketFile
  • CInternetFile
  • CHttpFile
  • CLongBinary
  • CInternetSession
  • CInternetConnection
  • CHttpConnection
  • COleSafeArray
  • CPrintInfo
  • COleCmdUI
  • CDAOFieldExchange
  • CDBVariant
  • CFieldExchange
  • COleDataObject
  • CRecentFileList
  • COleCurrency
No doubt, classes such as CPrintDialog weren't useful under Windows CE, but CBitmapButton or CDialogBar did their jobs very well. A sad conclusion from those library changes is that you should hurry up and look for equivalent replacements for unsupported classes as soon as possible.
But this is not the end of the story. Far from it! If you will examine the MFC headers, you can find a lot of code similar to the following snippet:
class CFont : public CGdiObject
{
DECLARE_DYNAMIC(CFont)

public:
static CFont* PASCAL FromHandle(HFONT hFont);

// Constructors
CFont();
BOOL CreateFontIndirect(const LOGFONT* lpLogFont);
#ifndef _WIN32_WCE // Unsupported Win32 API call
BOOL CreateFont(int nHeight, int nWidth, int nEscapement,
int nOrientation, int nWeight, BYTE bItalic,
BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet,
BYTE nOutPrecision, BYTE nClipPrecision,
BYTE nQuality, BYTE nPitchAndFamily,
LPCTSTR lpszFacename);
#endif // !_WIN32_WCE
...
};
Once again, I appreciate the new MFC version. It required improvements, but this and similar differences may hurt your application badly. As the best case, you can inherit your own class—say, CMyFont—that implements a lack of functions:
class CMyFont : public CFont
{
public:

// Constructors
CMyFont();
BOOL CreateFont(int nHeight, int nWidth, int nEscapement,
int nOrientation, int nWeight, BYTE bItalic,
BYTE bUnderline, BYTE cStrikeOut, BYTE nCharSet,
BYTE nOutPrecision, BYTE nClipPrecision,
BYTE nQuality, BYTE nPitchAndFamily,
LPCTSTR lpszFacename)
{
LOGFONT lfFont;
memset(<lfFont,0,sizeof(lfFont));

lfFont.lfHeight = nHeight;
lfFont.lfWidth = nWidth;
lfFont.lfWeight = nWeight;
lfFont.lfEscapement = nEscapement;
lfFont.lfOrientation = nOrientation;
lfFont.lfWeight = nWeight;
lfFont.lfItalic = bItalic;
lfFont.lfUnderline = bUnderline;
lfFont.lfStrikeOut = cStrikeOut;
lfFont.lfCharSet = nCharSet;
lfFont.lfOutPrecision = nOutPrecision;
lfFont.lfClipPrecision = nClipPrecision;
lfFont.lfQuality = nQuality;
lfFont.lfPitchAndFamily = nPitchAndFamily;
_tcscpy(lfFont.lfFaceName,lpszFacename);

return CreateFontIndirect(&lfFont);
}
but this is not always feasible. Be ready for the black box job, folks!

Windows Mobile 5.0

The last, but not the least, thing is that VS 2005 is the only way now to develop for Windows Mobile 5.0. Handhelds with Windows Mobile 2003 OS or CE.NET 4.X are at the end of their lifetime. I guess it will take up to one or two years to wipe out any of them. Hence, the development for a new OS version becomes important 'today'—quite literarily. With many exciting features, Windows Mobile 5.0 will pass over its birthright issues and rise an applications development process to the next level, for our common happiness.

Related Links

Thứ Bảy, 15 tháng 10, 2011 01:26 Đọc tiếp >>

Porting Mobile Applications Between Windows Mobile and Symbian OS

Why May You Ever Need to Port Your Mobile Applications?

The recent state of the mobile market is quietly challenging from a developer's perspective. A competition among Symbian OS, Linux, Windows Mobilem and few others (Palm, BREW, Apple, and proprietary OSes, just to mention a few) demands some degree of flexibility from your product. It means that you need to keep in mind how to design your system to be able to support multiple operating systems with minimal headaches while porting. Obviously, you might choose not to bother with porting at all to make your developer's life easier, but more often than not you simply have no choice because your competitors do it. I don't mention such a motive as covering wider markets and so forth. Having said this, one needs to make a decision (and not always a simple one); is it worth it to port existing application to a new platform? In many cases, the answer is "YES;" you may choose to port it instead of re-writing it from scratch. It will require some additional work, of course, but the outcome may benefit you a lot. The porting assumes that you may re-use your code and even make it much more robust.

What Effort Will It Require?

There are several well-established patterns for cross-platform development. You can choose to use any of them if you designed your application recently. When you consider the possibility of porting an existing application, the answer may be not so encouraging. In the case of Symbian OS and Windows Mobile, the differences in the platform API are significant, so it is pretty possible that you will have to re-develop all from scratch. Nevertheless, there are many similar concepts and functional API/classes that may be easily replace each other. On the bright side, it may be possible to re-use your existing application design. You still have to create appropriate implementations, but at least the main application structure and control flow remain the same.
The main idea behind porting techniques in regard to the discussion may be expressed as follows: a separate GUI and engine for your application. Most recent frameworks use this paradigm in some form. Symbian OS applications have it naturally due to various GUIs built upon the same Core OS and multiple target platforms. MFC comes with a similar approach for SDI architecture (or WTL classes if you don't like MFC). Hence, if you followed the guidance and have an engine and the GUI separated, you're quite lucky. Most of the platform-independent code may be re-used with some modifications. If your application utilizes STL, that helps you too, because both platforms have STL support. POSIX-compliant applications are in the best position because they require minimal porting effort. So, generally speaking, the more platform-neutral code you have, the easier porting will go.
Obviously, the real situation is usually far from ideal. More often than not, you may have the GUI and engine mixing up, GUI handlers keeping some knowledge about the data, and so forth. Well, if you are already facing the need to port, maybe it is a good time to make the code cleaner. The minimal price you have to pay is to re-develop all GUI parts of the application because it will be certainly different between various OSes. As I said earlier, in case of using standard frameworks, it should not be a big issue, though. You still will be able to have the Application object, Document, and View objects in C++ code or use suitable classes in C# for the majority of the situations.
Another aspect of the porting process to consider will be some 'common type system.' Symbian OS C++ applications use (or at least are encouraged to use) prefix-based type names, such as 'T', 'C', 'M' and 'R' classes. T-classes may be easily #define-ed and mapped to standard C++ types; for example, Tint becomes int and vice versa, BOOL matches TBool, and so forth. Just keep in mind the size of the given type when doing such remapping to avoid any problems with using sizeof(); for example, sizeof(BOOL) and sizeof(bool) are different. For more complicated classes, #define directives also may help where possible. Nevertheless, usually you re-implement particular missing methods for either platform. Having such 'neutral' functions makes all the process much easier.

The Differences You Ought to Remember


There are a few basic differences between Symbian OS and Windows Mobile OS you will come across first. I will outline them as the following:
  • CBase class in Symbian OS
  • Two-phase construction in Symbian OS
  • Leaves in Symbian OS vs. Exceptions in Windows Mobile
  • Descriptors in Symbian OS vs. C-style strings or BSTR in Windows Mobile
Those are not the only differences you spot during the porting, but rather the most obvious ones. Let me talk about them one by one.
The CBase class in Symbian OS, being a base class for all heap-based 'C' classes, ensures that all class members are zeroed. This fact should be taken into account when you port in either direction to avoid unexpected or unpredictable behavior during code execution. If you port from Symbian OS to Windows Mobile, be sure that all class members are initialized properly. I would say that it is a good practice in general terms.
The next thing is a two-phase construction mechanism that is extensively employed in Symbian applications. It is a robust solution to prevent memory leaks during object initialization. Windows developers often allocate memory directly in constructors. I personally think that this is bad practice and should be avoided where possible because it is pretty hard to control the initialization process if something goes wrong. Imagine that you just declared a member of some class or even a variable on the stack. If a constructor may, for example, throw exceptions, it is quite possible that you will observe very strange behavior under stress conditions. Two-phase construction allows you to avoid such situations and proposes that your class has protected constructor (which only initializes class data members, no allocations there) to prevent direct instantiation of the class instances, static NewL() method to act as a class factory, and a protected Construct() method that performs all required allocations and other tasks. For the Symbian component, you will be forced to follow this coding style; for Windows Mobile applications, you may easily implement similar initialization scheme. So, you can swing from Symbian OS code:
// Typical Symbian OS class sample
EXPORT_C CYourClass* CYourClass::NewL()
{
CYourClass* self = new (ELeave) CYourClass;
CleanupStack::PushL(self);
self->ConstructL();
CleanupStack::Pop(self);
return self;
}

EXPORT_C void CYourClass::ConstructL()
{
// Put your implementation here
}

EXPORT_C CYourClass::CYourClass()
{
// Put your implementation here
}
to something like the following snippet in Windows Mobile:
// Windows Mobile implementation
CYourClass* CYourClass::NewL()
{
CYourClass* self = new CYourClass;
if (self == 0)
throw ("Memory allocation error for CYourClass");

//pass ownership to an auto_ptr
std::auto_ptr<CYourClass> aptrSelf(self);
aptrSelf->ConstructL();

// release self - if we did not, self is deleted when the
// auto_ptr goes out of scope
self = aptrSelf.release();
return self;
}

void CYourClass::ConstructL()
{
// Put your implementation here
}

CYourClass::CYourClass()
{
// Put your implementation here
}
The sample above shows also what a 'Symbian'-style for object's initialization is.
Once you have isolated your Engine code into a DLL, for Windows Mobile implementation you can provide simple C-style methods for creation, deletion, and other operations upon objects in a given library. Such an approach is convenient when you plan to use the component—for example, from C# code. The Symbian OS uses the method's index rather than name to get access to the code within the DLL, so you will be able to use exported classes directly from your Symbian application and don't need to bother about additional exported functions.
If you code for Symbian OS, you know what "Leave" means. For Windows developers, it should be treated as an alternative to an exception handling. Many people may blame Symbian for not supporting exceptions, but what's done is done, so you can't help but accept it. According to Symbian's coding convention, all functions with names ending with 'L' may leave. Hence, you should implement the same in your Windows Mobile code. And vice versa, in your Symbian code make the method leave when the original function throws an exception.
And finally, descriptors and strings. The former may be considered as an analogue to BSTR under Windows and can hold both string and binary data. Descriptor manipulation in Symbian OS is painful, no doubt, but with the Carbide.c++ IDE coming onto the scene, you will be able to see their values during debugging at the least. If you can afford using STL port for Symbian OS, it will be a bit easier. Thus, in many cases, std::wstring will be a sufficient replacement for various descriptor classes. With MFC/WTL, you may use CString class as well.

Conclusion

In this article, I discussed a few general topics that may help you when porting various applications between Symbian OS and Windows Mobile OS. As you have seen, such porting is not always possible and often requires too much effort. Nevertheless, you still can use some parts of your existing code, perhaps adopted to new environment. To get some initial feeling of the whole process, you might apply it to one of the samples coming with each SDK; for instance, with WM50 or S60 SDK. Enjoy!
Thứ Bảy, 15 tháng 10, 2011 01:22 Đọc tiếp >>

Touchscreen Support in Qualcomm Brew

Although the Apple iPhone was not the first touchscreen cell phone on the market (think back to Windows Mobile and Treo devices), it's certainly caused quite a fuss for carriers and manufacturers, all of whom have been in quite a rush to launch their own touchscreen devices. Many of these devices run Qualcomm Brew, and it's perhaps not surprising that Brew has had support for touchscreens for a long time—since BREW 2.x, in fact. In this article, I show you how to receive touchscreen events so you can add touchscreen support to your own applications. Everything I describe works in the simulator, so you can do your development normally, test in the simulator, and as you receive hardware for testing, be ready to deploy your application.

The IControl Interface and Touchscreen Events

The good news is that if you're one of the relatively few developers who are happy using Brew's IControl interface hierarchy, you get touchscreen support essentially for free. Text controls and menus accept touch input, so all you need to do is handle control selection by touch.
To make sure your IControl-based application is ready for touch support, you need to do two things:
  1. Ensure your application passes touch events to the controls.
  2. Be sure that when the user touches outside a control and on another control that you transfer focus to the touched control.
The first is relatively easy: Just be sure you pass all events to the underlying active control using ICONTROL_HandleEvent. Generally, it's best to do this at the beginning of your event handler, like this:
static boolean HandleEvent( CApp *pMe, AEEEvent ec, uint16 w,
uint32 dw ) { boolean result = FALSE;

if ( pMe->pIActiveCtl ) {
result = ICONTROL_HandleEvent( pMe->pIActiveCtl, ec, w, dw );
}

if ( !result ) switch( ec ) {
// Handle event cases here.
}
return result;
}
The second is easy, too, as long as you can do hit testing to determine where the user touched the screen. Once you do this—the subject of the next section—you should defocus the current control and give focus to the new control, doing something like this:
if ( pMe->pIActiveCtl ) {
ICONTROL_SetActive( pMe->pIActiveCtl, FALSE );
}
ICONTROL_SetActive( pINewFocusedCtl, TRUE );
pMe->pIActiveCtl = pINewFocusedCtl;

Accepting touchscreen Events

Under the hood, BREW defines the following events for touchscreens:
  • EVT_PEN_DOWN when the user touches the display
  • EVT_PEN_MOVE while the user moves along the display while touching the display
  • EVT_PEN_UP when the user stops touching the display
  • EVT_PEN_STALE_MOVE if the user has moved along the display while touching the display and there are newer EVT_PEN_MOVE events in the queue
Thus, the general sequence of events when the user touches the display is one of EVT_PEN_DOWN, EVT_PEN_UP (for quick taps) or EVT_PEN_DOWN, a series of EVT_PEN_MOVE (perhaps with one or more EVT_PEN_STALE_MOVE events). The coordinates (x and y) of the event are delivered to you as a set of packed integers in the uint32 that accompanies the event; you can get just the x- or y-coordinate from the packed integer using the BREW helper functions AEE_GET_X and AEE_GET_Y.
Consequently, hit-testing—detecting which item is touched—in your event handler is easy, especially if you keep a list of objects that can be touched by the user. This is especially important if your application is a game or another application that doesn't use the BREW IControl hierarchy of controls. The basic algorithm is:
// On EVT_PEN_UP
int x0 = AEE_GET_X( dw );
int y0 = AEE_GET_Y( dw );
while( there are more objects in the list ) {
int x = current object in list's x coordinate
int y = current object in list's y coordinate
int dx = current object in list's width
int dy = current object in list's height
if ( x0 > x && x0 < x + dx && y0 > y && y0 < y + dy ) {
// the current object is one hit by the touch event
// focus it, activate it, or what have you.
}
You want to do the hit testing on the EVT_PEN_UP event, not the EVT_PEN_DOWN event, because it gives the user a chance to cancel a selection by touching something, moving away from the item they touched while still touching the screen, and then releasing the screen. This is analogous to how buttons work in a desktop user interface: Try clicking down on the OK button of a dialog and then dragging the mouse away from the button; when you release the mouse, the OK action is only taken if the pointer is over the screen.
Handling EVT_PEN_MOVE is a different story; if you want to implement dragging, you must be prepared to do whatever additional work on each EVT_PEN_MOVE event that's required. Whatever work your application performs here should take as little time as possible because your application can receive a lot of EVT_PEN_MOVE events.

A Bit of Advice...

When implementing touch support, you should remember that touch positions are approximate. This doesn't so much reflect inaccuracies in the hardware as it reflects the inability of a user to precisely position their fingertip or a pen tip on exactly one spot of the screen. The user may be in motion (walking, riding a bus, or heaven forbid, driving), and both pointer and device will be in lateral motion, effectively adding noise to the input your application is trying to obtain.
To work with this, make your hit areas large. Some carriers may mandate hit area size on some phones, especially given the small dot pitch of today's screens. It's nearly impossible to hit a 16x16 rectangle when that's only two-tenths of an inch on a side! Controls should be properly sized—a line of text may not be tall enough to be a single control, so consider using the extra screen real estate these devices have to provide big fat touchable areas for your users. Some carriers may mandate a minimum hit size (probably around forty pixels on a side, but you should check with your carrier partners!) for specific devices, and you may fail carrier certification if you don't meet those requirements. This is especially true for devices directly competing with the iPhone, where users are expected to use their finger, not a stylus, to touch the display.

Conclusion

Adding touch support to your application isn't hard, especially if you're already leveraging Brew's IControl hierarchy of interfaces. Just be sure to send the pen events to the active control, and add hit testing to your application to determine which control should be activated. If you've created your own controls, it's a little more work: Be prepared to handle the trio of EVT_PEN_DOWN, EVT_PEN_MOVE, and EVT_PEN_UP events; most of your work is likely in handling EVT_PEN_UP, because that's what confirms what your user wants to do. Regardless, it's not difficult to be ready for the wave of touchscreen phones coming to market!
Thứ Bảy, 15 tháng 10, 2011 01:14 Đọc tiếp >>

DirectX Performance Improvements

Chủ Nhật, 2 tháng 10, 2011 / 08:47

The last few years has seen a tremendous evolution of DirectX in both hardware and software. There have been significant improvements in several areas, allowing games to run faster and perform better than ever before including more VRAM, AGP based textures, and a 133 MHz front bus. In addition, applications are better written and are performing better.
This analysis of performance issues in DirectX covers a number of topics including:
  • the necessity of adding a FIFO byte counter for tagging purposes;
  • the necessity of DDraw accepting WASSTILLDRAWING anytime;
  • how to make good use of these features in a DD/3D driver.

Graphic accelerators: bigger, faster and not always smarter

Years ago the graphic device was purely an output device with VScan retracing the that the device queried. Today, even with more sophisticated devices, the same philosophy prevails...
1. FIFO largesse
64 bytes FIFO... 4 KB FIFO... 128 KB FIFO... they keep getting larger and larger to the point where you can now almost drop things in the FIFO and they get executed without any further attention from the host. To many it seems that the bigger the pipeline the better.
A similar problem would occur for a memory-based source surface that is not created by the driver, because the driver punts back creation of memory-based objects. There is no guarantee that source bits would not be modified upon return, so even if the blitter is able to queue the operation in the FIFO as source reference only, it cannot afford to and has to wait for completion of the blit. Copying all source bits through the FIFO, no matter how big the surface is - does not look great as alternative, either. The best solution, even though it is the most expensive one, is to manage all heaps in the driver and provide DMA transfer in the hardware.
Waiting for the FIFO to get empty means losing all the advantages of parallel processing. The CPU must wait until the DD/3D accelerator is done with its job, and then the accelerator must wait for the application to update the texture. See example below:
Fig. 1 FIFO odometer
Every pipeline with complete functionality should have a FIFO odometer at its business end. Together with the FIFO watermark it is just enough for a tag to be calculated and kept in the surface structure.

2. Interrupt on demand
For true synchronization, triggering an interrupt from FIFO is needed. For most of the time, this is overkill, but will it be a year or two from now? Not just an interrupt is needed, but an interrupt with a tag. For the driver, this is like posting notes to itself. When the interrupt occurs, the reading dedicated IO register will tell if this is event is being triggered by the hardware, or if it is the driver that asked for it through the FIFO.
It is sufficient to have a 16 or 24-bit tag, the high-order byte being the IRQ request; similarly, the IRQ identification register will provide the tag ID in the lower two or three bytes, the high-order one may be used for HW identifications.
Fig. 2 Interrupt-on-demand placed in FIFO
The use of this technique will be discussed later in the article. For now it is worth mentioning that, with a large amount of data in the FIFO and a lot of milliseconds of execution time ahead, having such a flexible event-triggering mechanism could substantially improve synchronization.

About DX runtime

DX runtime has also improved in the last few years, mainly on applications' side. Yet, there are still a few things that may be done better for DD/3D drivers.
1. Where did the write-only flag for textures go?
All surfaces, testures included, could have write-only flag in their capabilities. Applications, however, frequenly omit setting that flag in order to avoid restrictions on the general usability of the surface. DdLock used to provide compensating mechanism for that with its write-only flag to indicate "writeonlyness" for the particular lock-unlock period only. Surprisingly, DDLOCK_READONLY and DDLOCK_WRITEONLY are not used in Windows 2000 any more - and this is unfortunate.
The fact is, if the application does not do read-modify-write on texture surfaces, it does not care about the contents of the surface bits. The implication is that synchronization may be postponed until DdUnlock time, meanwhile a block of user memory may be provided for writing instead.
Neither runtime nor application cares what pointer DdLock returns because EngAllocUserMem accommodates whether it is VRAM or AGP. This is adequate for deferred texture updates, not until DdUnlock, but even until later, when the texture has to be used.
There is one solution that seems most effective. The DD/3D driver should maintain a runtime flag that determines its behavior, treating all textures that are being updated from the host as write-only regardless whether or not they are write-only.

2. Is it OK to return STILLDRAWING anytime?
Texture update deference is good thing, but what do we do if the old bits are yet to be used while the application has already prepared the new bits in the temporary buffer, as explained above? Idling inside the driver seems the only answer.

There is no assurance that if DX runtime accepts DDERR_WASSTILLDRAWING, then the idling will not happen in it. It would be better if this error code were accepted at anytime.

3. Better helpers for AGP memory allocation
Helper support for AGP memory allocation currently consists of just one function - HeapVidMemAllocAligned. It would be beneficial if memory mapping to an application's linear space was also supported and such code definitely exists in the runtime. Returning NOTHANDLED causes allocation AGP memory for the user and memory locking when required avoiding duplication of already existing code. This will also work well for write-only textures.

Smarter DD/3D drivers

Before exploring what can be done in the driver to improve synchronization, we will review the present situation.

1. Possible bit-transfer scenarios
A driver can handle host-to-video transfer (local or non-local RAM does not matter) in many possible ways. The most frequently employed transfers are direct memory moves and data postings to the FIFO. The former requires waiting for the surface to become unused but the latter has no synchronization problems. It is this author's opinion . Especially for AGP memory, writing through the FIFO does not make much sense because writing data to the accelerator's memory-mapped ports asks it to drop bits back to host memory. A more efficient and recommended method would be to keep a reference of the bits and master the memory-to-memory transfer later.
It is important to note that this method has a hidden pitfall. Retaining only reference to the bits and returning immediately to the application may create race conditions. There is no guarantee that user application would not change the bits or simply discard the memory before the actual transferring operation starts. This may become obvious with faster CPUs and deeper FIFOs, where the application would 'recycle' the memory location for a newer bitmap.
Fig. 3 Possible effect of a posted DMA transfer request in FIFO
As demonstrated in the illustration above, after the driver has returned control, and before any DMA transfer could be initiated, the bitmap is partially updated. Synchronization now becomes an issue with a writeable resource that is referenced simultaneously by two different engines.
Exactly the same situation would occur if an application requests, and immediately receives, a lock on a certain surface while a graphic operation from that surface is still pending. If DdLock is called, synchronization issues cannot be avoided. This time, technically, it is the driver and the DD/3D accelerator that are resource owners, while the application is asking for reference.
2. DdLock / DdUnlock challenges and the deferred texture updates solution
Once in the pipeline, a texture (or any surface, for that matter) is lost out of sight. If at this moment the application requests a lock on the surface, the driver is bound to synchronize access to it. This is a well-known issue and that is precisely why DDERR_WASSTILLDRAWING is returned far too often.
If we have a FIFO byte counter and FIFO watermark in place, the status becomes controllable:
pSurfGbl->dwReserved1->LastTag = ReadMMIO(FIFO_ODOMETER) + ReadMMIO(FIFO_WATERMARK);
The tag will be updated every time this surface gets involved in any graphic operation, whether as a source or as a target. Later, it becomes simple to check if it is still in the pipeline:
If ( ( pSurfGbl->dwReserved1->LastTag - ReadMMIO(FIFO_ODOMETER) ) > 0 )
goto StillInThePipeline;
Now there is no need to wait for the entire FIFO to become empty.
If there are any additional active threads then the CPU will not be idling, but it will wait on lock inside the DX runtime if it is the only application thread needing attention. This process is unnecessary since the driver can allocate any memory and later return to reference to it, provided the application is not sensitive to the content (as is almost always the case.)
The above method is very effective for lock control because it only waits for what is necessary to complete. Even better results may be achieved for write-only textures, by deferring the actual update of the bits. The memory provided to the application by DdLock is as equally effective as the old host memory allocated with EngAllocUserMem. Waiting to update bits until DdUnlock time is particularly valuable for AGP textures. A majority of the time the host has enough memory bandwidth and time at that current moment to where an extra memory move will not compromise performance.
If DX runtime accepts WASSTILLDRAWING from DdUnlock, the driver will offload its wait loop and give the system a chance to switch to another task. And when the texture comes out of FIFO, the unlock operation will continue moving the bits and freeing user memory.
Actually, a texture update may even be postponed beyond DdUnlock if it remains busy when used again. It is highly unlikely that the surface will still be busy at unlock time, moreover, such an approach could introduce unnecessary complications and possible memory leakage, but may still be worth implementing.

3. The ultimate deference for surface updates
Looking again at Fig. 3., the problem arose from the fact that two different processors were accessing the same resource concurrently. This problem is avoided if the driver actually owns the extra memory buffer that contains the surface update. This memory will no longer be a shared resource once DdUnlock completes. The driver can retain the memory for as long as it is needed, placing reference to it in the FIFO without restriction and finally discarding it when it is indeed not necessary. Effectively this is a texture double buffering with an updated buffer hidden inside the driver.
For graphic accelerators supporting host-to-VRAM or host-to-AGP transfer by reference, this ia very attractive and beneficial methodology. All synchronization problems are eliminated when any type of DMA transfer request is posted in the FIFO provided the driver takes the precaution to block any subsequent lock or blit attempts until the current update is complete. Of course, the reference to the bits should be kept for a while in some suitable structure extension, to be used finally in EngFreeUserMem.
When the target is an AGP surface, the fastest way to update is to utilize the driver and avoid involving any DD/3D accelerator that is DMA-challenged. Keep in mind it is important to attend to synchronization. The transfer of the bits must occur after previous graphics operations are completed, and before a new one with the new bits has been initiated. This can be done efficiently by using FIFO odometer.

Fig. 4 Hidden double buffering for textures
What if the diver provides to the application an AGP memory block for AGP texture update? When there is enough room in the non-local heap and no tiling is used, the only requirement would be to replace the fpVidMem pointer in the DD_SURFACE_GLOBAL structure.
DX runtime keeps a single instance of a surface's global structure that the driver has it in its possession at the time of the call. If the driver replaces the fpVidMem pointer in the structure, that would mean updating the whole texture, all its bits, at once! It is even possible that quality tests will pass. I cannot imagine a more efficient way to update bits of any AGP surface than swapping pointers (possibly DdTexFlip)
It would be beneficial if Microsoft explicitly allowed such a solution and it would be even better would be a helper routine that swapped pointer to bits internally. Until that time, only developers too eager to gain a few more winmarks should take this approach.
For VRAM-based surfaces the proper approach is not so obvious. Providing a host memory block to the application at DdLock time is good, what should be done in DdUnlock depends on the quality of host-to-VRAM transfer. It is possible that a simple memory move would be more efficient than using FIFO, particularly for big amounts of data. At that moment, the availability of a FIFO odometer for synchronization would be priceless.
In an ideal world, if interrupt-on-request is available, the action would be precisely timed. With soft-IRQ placed in the FIFO before DdUnlock returns, a driver will make sure that it is called after all preceding blits are consumed, and before the next ones are placed in FIFO. The memory allocated in DdLock can then be safely discarded.
Of course, after DdUnlock exits with success, there is a possibility that an application will make a new lock attempt for the same surface before it actually gets updated. In this situation returning WASSTILLDRAWING is the only viable solution. This is an improbable scenario even if it does happen some considerable time for parallel processing will have been bought.

4. Implementation of software odometer
The same technique is applicable to any DD functions as well. An excellent candidate is DdGetBltStatus. Not knowing whether the surface in question is in the FIFO, the driver must wait until the DD/3D accelerator consumes all pending operations. This is extremely costly because it comes right after DdLock in wasted time. Since no hardware known to me at this time has a FIFO odometer, but almost all have a true FIFO watermark register, a good decision could be to implement a software odometer.
Looking at the odometer comparison:
if( ( pSurfGbl->dwReserved1->LastTag - ReadMMIO(FIFO_ODOMETER) ) > 0 )
goto StillInThePipeline;
The operation above will take care of the roll-over counter provided that all operands are signed integers. If any is declared unsigned, the comparison will yield a wrong result in the vicinity of 0xFFFFFFFF to 0 transition, precisely in -FIFO_DEPTH to 0xFFFFFFFF.
Implementation of FIFO counter software requires exemplary coding discipline and needs true hardware knowledge about present FIFO watermarks. All writes observe a dedicated routine - or dedicated macro - that will keep a global variable (a true global variable because in fact it will act as a shadow HW register) with total number of bytes sent to FIFO. The slightly change formula:
((UINT)iTotalBytesSentToFIFO)++; // counter is incremented as unsigned
pSurfGbl->dwReserved1->LastTag = iTotalBytesSentToFIFO;
The check for a surface still in the pipeline involves calculating the current head of the FIFO:
iCurrentHeadOfFIFO = iTotalBytesSentToFIFO - ReadMMIO(FIFO_WATERMARK);
if( ( pSurfGbl->dwReserved1->LastTag - iCurrentHeadOfFIFO ) > 0 )
goto StillInThePipeline;
There is no need to mention that any rogue coding (even for temporary purposes) will distort the calculations and yield any variant results.
Will a single odometer value be enough for a given surface? It is possible, but if waiting for blit complete and the completion of other operations may be executed differently, multiple counters (one for each category) shall be kept in the driver's private surface structures.
A truly sophisticated approach would be to maintain two tags for each category - read and write. Though it is difficult to find a situation where it could make a difference, there is still a chance one may exist.

Conclusion
Synchronization between DD/3D graphic accelerators and the host has been neglected for a long time and needs attention. Hopefully, this article will help developers improve the performance of DD/3D drivers. Although the observations were conducted mainly on Windows 2000 systems, they are valid for Windows 9X as well.
Rough estimates conservatively estimate that implementation of a FIFO counter - and consequently optimizing the waits on the FIFO - would improve performance by 20-25%. Maximum efficiency is achieved when the DD/3D accelerator is continuously kept busy without interruption. When all precautions to prevent overloading VRAM bandwidth are observed, then the gains may be measured in times, not percents.
Chủ Nhật, 2 tháng 10, 2011 08:47 Đọc tiếp >>

Writing windows Audio Driver

Advancing the Architecture

The introduction of the WDM Audio platform has created a unified architecture for implementing audio drivers for the Windows platform. New features and enhancements to this architecture have helped bring new types of applications to the Windows platform such as PC based soft DVD players, streaming high quality secure audio content, and home theater multi-channel surround sound support. This article focuses on some of the new challenges that face the audio driver developer when integrating support for these types of applications.

Surround Sound Playback

Many soft DVD players support the option of audio playback in several formats. These formats typically are DirectSound or waveOut, Multi-channel speaker configurations, and encoded AC3 digital output. The DirectSound / waveOut support requires no additional support from the driver, but this does not fully exploit the Dolby Digital 5.1 support featured on most DVD titles. For a true home theater experience either Multi-Channel support or encode AC3 digital output must be supported.

Supporting AC3 Dolby Digital Output over a Digital Interface

The most popular transport for AC3 encoded Dolby Digital 5.1 data is the Sony Phillips Digital Interface or SPDIF. SPDIF is a widely used digital interface that is implemented with some high-end sound cards. Including a SPDIF port on a sound card enables the audio card to support external AC3 decoder speakers for use in a home theater Surround Sound environment. Sound cards can be designed to transfer compressed AC3 data or raw PCM through the SPDIF interface.
Non-PCM Data Routing
Starting with Windows Me, AC3 encoded data (or any type of non-PCM) that is passed through the waveOut or DirectSound API data is routed directly to PortCls. This is a deviation from previous version of the Windows operating systems where all audio content was sent through KMixer. KMixer does not support private or encoded audio data formats like encoded Dolby Digital AC3.
Driver Requirements
In a WDM audio driver data flows in and out of an abstract object called a filter. Filters contain one or more arrays of PCPIN_DESCRIPTOR structures. These arrays are called pin factories because this information is used to generate pins on the filter. All data that flows in and out of a filter passes through the filters pins. To enable your driver to accept AC3 data from an application, you must first associate a pin in your filter to the AC3 data stream. Second, you must correctly define the pin factory that describes your drivers AC3 pin. These structures describe the nature of the flow of data from your driver. For example, can there be multiple instances of this pin (i.e. multiple streams), does the pin accept or receive data, what type of data format does this pin support, etc. There are several ways to define your pin and pin factory for your AC3 enabled hardware, however there are potential problems with some of these implementations. The safest approach is to create a separate pin factory for AC3 formatted data. This will allow for the creation of a separate pin that is exclusive to AC3 data. If your hardware supports only a single stream, you may need to arbitrate hardware access between your PCM pin and AC3 pin. In addition, you must define the AC3 pin on a filter that already supports PCM or your AC3 pin will not be utilized by DirectSound 8. The only way a device can support AC3 is to also support PCM.
In addition to the requirements listed above, you must also implement a DataRangeIntersection member function for your AC3 pin. You will need to override the default DataRangeIntersection handler provided by PortCls. The MSVAD sample in the Whistler DDK demonstrates the proper way to implement a DataRangeIntersection routine for accepting AC3 data. Use \tools\avstream\KsStudio.EXE in the Whistler DDK to test your intersection handler. This will allow you to instantiate your AC3 pin manually.
The DataRangeIntersection handler for your AC3 pin should return a properly formatted KSDATAFORMAT_WAVEFORMATEX structure in the ResultantFormat parameter. The KSDATAFORMAT_WAVEFORMATEX structure requires a GUID for the SubFormat field of the KSDATAFORMAT structure. This GUID is created by using the macro in DEFINE_WAVEFORMATEX_GUID in ksmedia.h. The macro utilizes a constant wave format type, which is defined in mmreg.h. WAVE_FORMAT_DOLBY_AC3_SPDIF is defined in mmreg.h as 0x0092. The following code demonstrates the use of this macro.
#define STATIC_KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF \
DEFINE_WAVEFORMATEX_GUID(WAVE_FORMAT_DOLBY_AC3_SPDIF)

DEFINE_GUIDSTRUCT("00000092-0000-0010-8000-00aa00389b71",
KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF);

#define KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF \
DEFINE_GUIDNAMED(KSDATAFORMAT_SUBTYPE_DOLBY_AC3_SPDIF)
...
// from DataRangeIntersection
INIT_WAVEFORMATEX_GUID(pMyGuid,myWaveFormatTag);
...
if (IS_VALID_WAVEFORMATEX_GUID(aWaveFormatExGuidPtr)) {
aWaveFormatTag = EXTRACT_WAVEFORMATEX_ID(aWaveFormatExGuidPtr);
}
In addition to a DataRangeIntersection handler, your mini port must also handle the format properly in the Init and NewStream member functions. Your stream interface must handle the SetFormat function properly for the AC3 format.
Additional Information
Currently the only shipping Operating system that supports the playback of non-PCM data via waveOut is Windows Me. Windows 2000 will add this support in Service Pack 2. Support for this feature is available for Windows 98 Second Edition by obtaining a Quick Fix Engineering (QFE) package from Microsoft Product Support Services. The QFE is titled 269601USA8.EXE. This QFE is not supported on the original release of Windows 98.
A bug in the system graph builder in Windows 98 requires that your AC3 pin be connected to at least one node. The QFE mentioned above will not work unless your data path has at least one node attached.
Additional information concerning non-PCM playback can be found in the following article:

Supporting Multi-Channel Playback

Most DVD titles and some games support an enhanced listening experience by providing content that is tailored for multi-speaker (channel) installations. In most cases, the audio content is channel specific. This section discusses implications and design strategy for writing multi-channel audio drivers. These drivers would support Dolby Digital 5.1 Surround Sound speaker configurations and the WAVEFORMATEXTENSIBLE format, which is needed for multi-channel support.
Introducing WAVEFORMATEXTENSIBLE
Due to the limited way that channel assignments were specified using the older WAVEFORMAT structure, a new extension was defined that will allow forward growth while maintaining backward compatibility. The WAVEFORMATEXTENSIBLE structure allows an audio format to be described in a way that overcomes the previous limitation of the WAVEFORMAT structure. Previously channel assignments were assumed when the numbers of channels were limited to WAVEFORMAT.nChannels. This value was typically either two (stereo) or one (mono). With the advent of advanced audio designs and the demand for home theater solutions, it became necessary to move beyond two channels and begin dealing with various speaker configurations. Quadraphonic (four-corner), 3.1 (front left, front center, front right, low frequency enhance), and 5.1 (front left, front center, front right, back left, back right, low frequency enhance) are some of the more popular speaker configurations. With all of these speaker configurations, there was no way to map specific channels to specific speakers and the layout of the wave data did not correspond to a specific channel of speaker. To over come this problem a default channel ordering was defined. This channel ordering specified how channels are mapped to speakers and how the audio data was interleaved in the actual wave file. The channel order is:
    1) Front Left - FL 2) Front Right - FR 3) Front Center - FC 4) Low Frequency - LF 5) Back Left - BL 6) Back Right - BR 7) Front Left of Center - FLC 8) Front Right of Center - FRC 9) Back Center - BC 10) Side Left - SL 11) Side Right - SR 12) Top Center - TC 13) Top Front Left - TFL 14) Top Front Center - TFC 15) Top Front Right - TFR 16) Top Back Left - TBL 17) Top Back Center - TBC 18) Top Back Right - TBR
The audio channels are interleaved in the order listed. If a channel is not included in the wave file, then the channel is omitted from the interleaved data. This allows for any number of channels (from 1 to 18).
As you can see below, WAVEFORMATEXTENSIBLE includes WAVEFORMATEX as a member of the structure. This allows WAVEFORMATEXTENSIBLE to provide maximum compatibility with previous methods of specifying the wave format.
typedef struct {
WAVEFORMATEX Format;
union {
WORD wValidBitsPerSample;
WORD wSamplesPerBlock;
WORD wReserved;
} Samples;
DWORD dwChannelMask;
GUID SubFormat;
} WAVEFORMATEXTENSIBLE, *PWAVEFORMATEXTENSIBLE;
The dwChannelMask field was designed to provide a mapping of channels to actual speakers that are available. The following constants are defined in mmreg.h:
    #define SPEAKER_FRONT_LEFT                0x1
    #define SPEAKER_FRONT_RIGHT 0x2
    #define SPEAKER_FRONT_CENTER 0x4
    #define SPEAKER_LOW_FREQUENCY 0x8
    #define SPEAKER_BACK_LEFT 0x10
    #define SPEAKER_BACK_RIGHT 0x20
    #define SPEAKER_FRONT_LEFT_OF_CENTER 0x40
    #define SPEAKER_FRONT_RIGHT_OF_CENTER 0x80
    #define SPEAKER_BACK_CENTER 0x100
    #define SPEAKER_SIDE_LEFT 0x200
    #define SPEAKER_SIDE_RIGHT 0x400
    #define SPEAKER_TOP_CENTER 0x800
    #define SPEAKER_TOP_FRONT_LEFT 0x1000
    #define SPEAKER_TOP_FRONT_CENTER 0x2000
    #define SPEAKER_TOP_FRONT_RIGHT 0x4000
    #define SPEAKER_TOP_BACK_LEFT 0x8000
    #define SPEAKER_TOP_BACK_CENTER 0x10000
    #define SPEAKER_TOP_BACK_RIGHT 0x20000
    #define SPEAKER_RESERVED 0x80000000
For example, if you have a Quadraphonic (four speaker) configuration, nChannels = 4 and dwChannelMask = 0x00000033. This would specify the playback was intended for the front left, front right, back left and back right speakers. The audio data would be interleaved in that order.
For a detailed description of WAVFORMATEXTENSIBLE, see the article at http://www.microsoft.com/hwdev/audio/multichaud.htm
Modifications Required to Support Multi-Channel Playback
To add support for multi-channel playback in your audio driver you must make the WDM audio system aware of the capabilities of your hardware. First you must use an extend version of KSDATAFORMAT_WAVEFORMATEX. The example below shows a typical use of the extend format structure.
DataFormat.FormatSize  = sizeof(KSDATAFORMAT) + sizeof(WAVEFORMATEXTENSIBLE);
DataFormat.Flags = 0;
DataFormat.SampleSize = 0;
DataFormat.Reserved = 0;
DataFormat.MajorFormat = STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO);
DataFormat.SubFormat = STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM);
DataFormat.Specifier = STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX);
Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
Format.nChannels = 4;
Format.nSamplesPerSec = 44100;
Format.nAvgBytesPerSec = 352800;
Format.nBlockAlign = 8;
Format.wBitsPerSample = 16;
Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);
Format.wValidBitesPerSample = 16;
Format.dwChannelMask = KSAUDIO_SPEAKER_SURROUND;
Format.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
The second thing that you should add to your driver to inform the operating system that you support multi-channel playback is to modify KSDATARANGE_AUDIO structure that is specified for your playback pin. Below is an example of a typical KSDATARANGE_AUDIO structure.
DataRange.FormatSize = sizeof(KSDATARANGE_AUDIO);
DataRange.Flags = 0;
DataRange.SampleSize = 0;
DataRange.Reserved = 0;
DataRange.MajorFormat = STATICGUIDOF(KSDATAFORMAT_TYPE_AUDIO);
DataRange.SubFormat = STATICGUIDOF(KSDATAFORMAT_SUBTYPE_PCM);
DataRange.Specifier = STATICGUIDOF(KSDATAFORMAT_SPECIFIER_WAVEFORMATEX);
MaximumChannels = 4; // max number of channels or -1 for unlimited
MinimumBitsPerSample = 2;
MaximumBitsPerSample = 16;
MinimumSampleFrequency = 5000;
MaximumSampleFrequency = 48000;
In addition to the above modification, you will also need to modify your drivers DataRangeIntersection member function of your stream interface object to support the WAVEFORMATEXTENSIBLE format. Refer to the latest Windows 2000 DDK in winddk\src\wdm\audio\ac97 for a multi-channel enabled driver sample.
Other Multi-Channel Considerations
  • All multi-channel data from the WDM audio system is interleaved. If your hardware does not understand the interleaved format of the rear channels then you will need to de-interleave the data before it is passed to your hardware.
  • Your hardware must support volume and mute control on all channels. Your hardware may implement a separate volume control for each channel, or it may implement a master volume control for all channels. These controls can be implemented in either the host audio controller or the audio codec. Your topology will need to reflect the volume that matches your hardware.
  • If your hardware supports multiple speaker configurations, you may need to update your topology if a speaker assignment is changed. At this time the WDM audio system does not support dynamic topology updates so a reboot may be required if the speaker configuration changes.

Protecting Content with Digital Rights Management

Streaming Media and downloadable music are two applications that have created an industry need to provide the protection of digital media. Digital Rights Management (DRM) is the technology that allows for protection of digital media on the WDM audio platform. The Secure Audio Path (SAP) architecture implements DRM to allow the content provider to control the level and manor of the protection of their copyrighted content.

DRM and SAP, the Big Picture

DRM utilizes encrypted data to apply copy protection against copyrighted audio content. On Windows 98, and Windows 2000 this encryption is limited to application level. On Windows Me and later, the DRM encryption is maintained into the operating system kernel. Windows Me and later also support the concept of a trusted device driver. A trusted driver is a device driver that obeys the copy protection that is specified by the content provider and passed through the DRM system. Once the encrypted data reaches the device driver, the audio is played if the driver is trusted. Currently DRM is implemented only for digital audio. MIDI and DLS sets are not supported under the current DRM system.

Implementing DRM in Your WDM Audio Device Driver

Before you begin adding support for your DRM enabled device driver, you must first download the Windows Millennium Edition DRM Supplement to the Windows 2000 DDK. This supplement is available at http://www.microsoft.com/hwdev/audio/DRMsup.htm. This update includes updated header files that define the interfaces that are required for supporting DRM.
The first step in supporting DRM in your driver is adding the IDrmAudioStream interface to your WaveCyclic and WavePci mini-port objects. Once the driver is loaded, if a secure audio path is requested, the DRM system component above PortCls calls the QueryInterface method on the IMiniPortWavePciStream or IMiniPortWaveCyclicStream interface. You must return an IDrmAudioStream interface in response to a QueryInterface call that specifies a reference ID of IDrmAudioStream. This allows the system to obtain a reference to the streams IID_IDrmAudioStream. Once the DRM system has a reference to the IDrmAudioStream interface, it can then call the SetContentId method. SetContentId is used to pass the content ID and the rights for a specific stream. The content ID is used by the DRM system to identify protected content in an audio stream.
NTSTATUS
IDrmAudioStream::SetContentId(
IN ULONG ContentId,
IN PCDRMRIGHTS DrmRights
);
The second parameter of SetContentId is a pointer to a DRMRIGHTS structure. This structure contains two flags that describe the associated rights for the ContentId.
typedef struct tagDRMRIGHTS {
BOOL CopyProtect;
ULONG Reserved;
BOOL DigitalOutputDisable;
} DRMRIGHTS , *PDRMRIGHTS;
These two flags are described below.
CopyProtect
Specifies one of the following copy-protection values:
Value Meaning
TRUE (nonzero) A software component must not:


Store the content in any form in any nonvolatile storage.


Pass the content by reference or value to any other component within the host system that is not authenticated by the DRM system.
FALSE (zero) There are no restrictions on copying the content.


DigitalOutputDisable
Specifies one of the following digital output protection values:
Value Meaning
TRUE (nonzero) A software component must not transfer the content out of the host system through any type of digital interface.


Note that digital output protection does not affect USB devices because the host system includes USB devices.
FALSE (zero) There are no restrictions on transferring the content from the host system to an external component.


Supporting DRM with Advanced Audio Features

The DigitalOutputDisable flag of the DRMRIGHTS structure applies primarily to S/PDIF or AES/BEU outputs. If this flag is TRUE, the digital output must be disabled. This does not apply to USB digital audio. DRM support for USB will be addressed in future versions of Windows. Although it is not required for WHQL DRM certification, it is a good practice to set the SCMS in the SPDIF stream to prohibit copying if DRMRIGHTS.CopyProtect is TRUE.
Some audio devices handle multiple audio streams and mix these streams into a single output at the hardware level. In this scenario, the driver must keep up with the content IDs and the associated content rights of all streams. In addition, the driver must also keep track of the composite rights of all of the mixed streams. The system provides the IDrmPort interface to help manage the composite rights of the mixed streams. IDrmPort contains the following functions:
  • IDrmPort::CreateContentMixed
  • IDrmPort::DestroyContent
  • IDrmPort::ForwardContentToFileObject
  • IDrmPort::ForwardContentToInterface
  • IDrmPort::GetContentRights

Testing Your DRM Enabled Driver

To qualify as a trusted DRM driver, your device driver must pass the Microsoft Windows Hardware Quality Lab (WHQL) DRM compliance test. This test is performed by WHQL once your driver has passed the standard Audio WHQL Windows logo test. A driver that has obtained the Windows logo will be marked as DRM certified or non-certified. The DRM certification test is performed at the vendors request. To pass the DRM certification a driver must do the following:
  • The audio miniport driver must correctly implement the IDrmAudioStream interface.
  • The driver must disable the ability to capture the stream currently being played back if DRMRIGHTS.CopyProtect= TRUE. The driver must not store the unprotected digital content to any other medium, including hard disk, EEPROM, memory card, and memory stick. The driver must disable the loopback of digital audio data on the audio device
  • The driver must disable any digital output on the device if DRMRIGHTS.DigitalOutputDisable = TRUE. Digital outputs include, but are not limited to SPDIF, IEEE 1394, serial, parallel, modem, and network ports. Note: This does not currently apply to USB.
  • The driver must never attach to an untrusted driver when handling secure content. The driver must only rely on components that contain a DRM signature. If protected audio is passed from one module to another, the driver must utilize the DRM APIs in the Kernel to inform the DRM system of the transfer of protected data.

Acronyms

DRM - Digital Rights Management
SPDIF - Sony Phillips Digital Interface
SAP - Secure Audio Path
WHQL - Windows Hardware Quality Lab
Microsoft, DirectX, MS-DOS, Win32, Win64, Windows, and Windows NT are registered trademarks of Microsoft Corporation. Other product and company names mentioned herein may be the trademarks of their respective owners.
Chủ Nhật, 2 tháng 10, 2011 08:46 Đọc tiếp >>

Writing Windows CE Display Drivers

Introduction

For many developers, writing display drivers can be an intimidating task. Windows CE, Microsoft's operating system targeted toward embedded devices, is no exception. Fortunately, Microsoft provides C++ classes that can be used to simplify writing display drivers. As convenient as these classes are, there are improvements than can be made to them that can further simplify display driver development and make display drivers more portable across Windows CE devices.
Increased portability provides additional value for display drivers as Windows CE moves to different platforms with various display requirements, such as Internet appliances, video conferencing systems, and game consoles. Even within a product family, such as HPCs, this portability is valuable as each generation of product adds more features and functionality and moves to different display hardware.
This article reviews the fundamentals of graphics, display hardware, and Windows CE display driver development, including the display driver C++ classes. It then explores improvements to the C++ classes that will simplify display driver development. At the end, you will have a set of improved display driver classes that should be simple enough to quickly and easily get running on any device, yet complete enough to support any additional hardware features. Of course, this doesn't prevent you from making your own improvements as well.

Fundamentals of Graphics and Display Hardware

For those developers not familiar with the principles of graphics hardware, it is worth providing a quick overview of the fundamentals of graphics and display technology in the context of a typical Windows CE display device. Graphics hardware is primarily composed of a display controller, a frame buffer and a DAC. The display controller handles access to the frame buffer by the CPU, generates the video timing for the current display mode, and fetches the display data from the frame buffer to be displayed. The frame buffer stores the display data. The DAC, or digital to analog converter, converts the digital display data to an analog format to be sent to the monitor. This is necessary since most monitors expect analog voltage levels that represent the intensity of each color channel. The diagram below demonstrates the relationship among these components. It should be noted that as a result of the high level of integration achieved in today's silicon, all three components can be found in a single chip from some manufacturers.
WinCE Driver Development article1
Because most monitors cannot maintain the display image on their own, the display must be continuously refreshed. For the standard non-interlaced display, this is done one line at a time in sequence. Interlaced displays, such as televisions, refresh all the even lines first, then all the odd lines, sometimes resulting in display flicker. The time after one display line is completed and before the next one is started is called the horizontal blanking period. The time after a complete display refresh is done and until the next display refresh is started is called the vertical blanking period. These blanking periods are the result of monitor technology requirements. Cathode ray tubes, or CRTs, used in monitors direct a beam along the face of the tube. This beam causes phosphors on the tube to emit light, which you see as the display. After the beam traces a line across the tube, it needs to retrace to the beginning of the next line. While it is retracing, the beam is shut off, or blanked. The same applies for a complete display with vertical retracing and blanking.
The display itself is organized in rows and columns. Each element, or pixel, in the display is stored in the frame buffer, where between one and thirty-two bits are used per pixel. The color of a pixel is represented by the intensity of each of the red, green, and blue color channels. These intensities are represented directly by the pixel data in modes where a pixel is 16 bits or more. When a pixel is 8 bits or less, the pixel data usually represents an index into a color look-up table. This look-up table stores the red, green, and blue intensities for each index in the palette of currently available colors. In this case, the look-up table values are passed to the DAC.
WinCE Driver Development article2
In Windows, bitmaps are used to represent graphical images. A bitmap typically contains the pixel data for the image, the dimensions and color depth of the image, and possibly the palette for the image, among other things. Information in a Windows bitmap is not directly available, but is abstracted and only accessible through calls to Win32 APIs. A Windows CE display driver typically sees bitmaps in a format called a surface. These surfaces contain the information of the bitmap, but in a format that is directly accessible by the display driver.
If you require additional background information before getting started on display driver development, there are plenty of good video and graphics books available to cover the basics of these topics in more detail.

Display Driver Overview

The Graphics Device Interface, or GDI, is the system component that loads and calls the display driver. It is also where bit block transfers, or blits, and drawing related Win32 APIs are handled. In Windows CE, GDI is contained in the Graphic, Windowing, and Event Subsystem, or GWES. An interesting thing to note is that in Windows CE, GWES is an optional component, making the display driver optional as well. It is therefore possible to make Windows CE devices that are "headless", that is, with no graphic display interface. This is useful to be aware of when writing other device drivers since you may not be able to depend on having access to graphical objects, such as dialog boxes, to communicate with the user.
The display driver is a native driver in Windows CE. This means that it has a custom interface that provides a standard set of functionality for display devices. As a matter of fact, this display device driver interface, or DDI, is a subset of the Windows NT DDI. One of the major differences is that all Windows CE display drivers have the same level of functionality, so there is no "punting" of complex operations back to GDI. A windows CE display driver has only one function that it is required to export, DrvEnableDriver(). This function is called by GDI when the driver is loaded and is responsible for returning pointers to the other DDI functions.
Writing display drivers using the DDI directly can involve a lot of duplication of code from one display driver to the next. To greatly simplify and speed up development, Microsoft has provided a set of C++ classes that contain most of the base code that is required from any display driver. What this means for the display driver developer in Windows CE is that code only needs to be added for functionality that is specific to the device, such as initialization and mode setting, hardware cursors, and accelerated blits and line drawing. You can really appreciate how much time these classes save if you have ever done display driver development for other Windows operating systems. In a typical Windows CE display driver, the most time consuming tasks usually involve device initialization and mode setting. This is due to the fact that Windows CE does not support executing a video BIOS, where initialization and mode setting would normally be handled. The one exception to this is the CEPC platform, where the bootloader, LOADCEPC, does make video BIOS calls to initialize and set the mode for the display device. This is possible since LOADCEPC is actually a DOS application. However, for the typical Windows CE system this is not an option.
Microsoft makes several recommendations for display hardware, intended to improve driver performance and simplify development. The most important of these is that the display hardware uses a linear frame buffer. What this means is that the display memory needs to be contiguous, with this entire block of memory being directly accessible by the CPU. Therefore, access to display memory through bank selection, should not be used. Another important recommendation is not to use bit planes. This is when each color channel or intensity component is in a separate buffer. Display memory bank selection and bit planes exist as part of legacy VGA support, with most newer VGA controllers now also including support for a linear frame buffer as well as for packed pixel, or non-planar, display modes. It is important to follow these recommendations if you wish to take advantage of the default blit and line drawing functions provided in the C++ classes.

Graphics Primitive Engine Classes

As previously mentioned, Microsoft provides a set of C++ classes called the Graphics Primitive Engine, or GPE, that simplify display driver development in Windows CE. The most important of these is the GPE class, which represents the display device. It is a pure virtual class, which means that it must be derived from and that certain base class functions must be implemented. Since source code is not provided in Platform Builder for this class or how the DDI functions interface with it, it is useful to review these functions that require implementation. They are:
  • NumModes - Returns the number of display modes supported by the display driver.
  • GetModeInfo - Returns information about a specific display mode, such as display width and height in pixels and number of bits per pixel. This function should handle the number of display modes returned by the NumModes() function. The first mode entry in the list of supported modes is always the one selected for configuration when SetMode() is later called.
  • SetMode - Sets the display mode. This can be the most time consuming function to write in the entire driver, especially for VGA controllers, since configuration of the display device can be a fairly involved process.
  • AllocSurface - Allocates a surface, which is just a block of system or video memory to store pixel data. The GPESurf class can be used to represent surfaces in system memory. To represent surfaces in video memory, the GPESurf class must be derived from. The GPESurf class is discussed in more detail later.
  • SetPointerShape - Sets the cursor bitmap and cursor hotspot.
  • MovePointer - Moves the cursor.
  • BltPrepare - Called before the blit operation is performed. It allows the driver to setup the blit hardware for performing the operation, if it is supported. It must return the actual function to be called to perform the blit operation, which can be the default blit function provided in the GPE class.
  • BltComplete - Called after the blit operation has been performed. It allows the driver to do any cleanup required after the blit operation, if necessary.
  • Line - Called before and after a line drawing operation. When it is called before the line drawing is done, the function can setup the line drawing hardware for performing the operation, if it is supported. It must return the actual function to be called to perform the line drawing operation, which can be the default line drawing function in the GPE class. When it is called after the line drawing is done, the function can do any cleanup required after the line drawing operation, if necessary.
  • SetPalette - Sets the palette. This only applies for modes that support a palette, which is typically 8 bits per pixel or less.
  • InVBlank - Indicates if the display update is in the vertical blanking period. This is useful for reducing an animation problem known as tearing, where the display memory update is not in sync with the display refresh on the monitor.
There are other functions in the GPE class that have default implementations, but can be overridden for non-default behavior. These functions are:
  • IsPaletteSettable - Returns TRUE if the palette is settable or FALSE if the palette is fixed or if the mode doesn't require a palette, such as 16-bit or 24-bit per pixel modes. The default implementation checks the Bpp field of the m_pMode variable and returns TRUE if it equals 8, otherwise it returns FALSE.
  • GetGraphicsCaps - Indicates if the display driver supports additional graphics features. The default implementation returns 0.
  • ContrastControl - Receives commands related to contrast control, such as getting and setting the current contrast value. It is useful if the display is a LCD panel. The default implementation does nothing and always returns 1.
  • PowerHandler - Receives power on and power off notification. The function can be used to suspend or resume power to the display device. As with any driver that receives power notifications, it is important to note that this function should not make any calls that could cause the thread to block as it is the only thread running at the time it is called.
Besides these, there is a set of functions in the GPE class that are described as being required for DDHAL support. The implication is that these functions are part of the DirectDraw hardware abstraction layer, or HAL. Since the display driver model for version 2.0 was developed well ahead of the release of DirectDraw for Windows CE, these functions were probably included as a best "guess" of the display driver requirements for DirectDraw support. As it stands, these functions are only part of the story for DirectDraw support and are not required for a standard display driver so I will not specifically discuss them here. I will add, however, that these functions do provide additional capabilities that, if properly exported, could be used by applications to bypass GDI for improved performance.
If your display device is VGA based, you may choose to derive your device class from the GPEVGA class rather than GPE. GPEVGA is itself derived from GPE, and is still pure virtual. It contains function implementations for SetPalette() and InVBlank(), using standard VGA accesses. It also contains I/O mappings to standard VGA registers. Beyond this, you will still need to implement the remaining functionality required in the GPE base class.
There is a variation of the GPE based driver, called a dirty rectangle driver. Its purpose is to allow a display driver based on the GPE class to work with a banked memory display device. An example of this is the sample driver VGA8BPP. It is a very inefficient driver from both a system resource and performance standpoint and should really only be used if a linear frame buffer is not available. It works by creating a frame buffer in system memory that is the size of the display. This is very inefficient from a system memory standpoint since memory is usually a critical resource in a Windows CE device. All drawing by the GPE default drawing functions is done into this system memory frame buffer. These areas where drawing is done, or dirty rectangles, are then copied to the display memory on a bank by bank basis. The inefficiency here, of having to do the drawing in two steps, is obvious.
Another important class is GPESurf, which is used to represent surfaces located in system memory. If the driver supports the creation of surfaces in video memory, then the GPESurf class will need to be derived from. However, these changes are fairly minor and mostly require capturing of the Node2D information, mentioned later, and setting the flag to indicate that this surface is located in video memory.
The last class I'm going to mention is Node2D. This class is used for managing video memory surfaces. An instance of a Node2D object is initially created that contains the pixel dimensions of the total video memory. Allocation of video memory for surfaces, including the primary display surface, is then handled through this Node2D instance. Within the class itself, the video memory is managed as a list of free and allocated rectangles, with all coordinates handled in pixel dimensions. The limitations of this class are that video memory surfaces cannot be created that are wider than the pixel dimensions supplied when the instance of the class was created and that video memory surfaces must be the same color depth as the display.
It is important to note that the GPE classes haven't changed very much since version 2.0, so the information presented here should be useful and accurate across many different versions of Windows CE.

Improving the Display Driver Classes

As useful as these C++ classes are for writing display drivers in Windows CE, it is clear that additional base functionality can be included to further simplify display driver development. The two classes to be improved upon are GPE and GPESurf. Since the source for these classes is not provided, we need to derive classes from them in order to improve them. These new classes are called NewGPE and NewGPESurf.
A good starting point for building the NewGPE class is configuration and initialization. The NewGPE class is designed to require as little modification or overriding of functions as possible. The class constructor, NewGPE(), provides default initialization for the variables. Currently, the only variable that would need to be changed here is m_bIsVGADevice, if a non-VGA device is being used. This variable is used to enable mapping of the VGA registers as well as selection of some default VGA functionality, done elsewhere in the driver.
NewGPE::NewGPE()
{
// Flags for hardware features
//
m_bIsVGADevice = TRUE; // default to VGA device
m_bHWCursor = FALSE; // default to software cursor
m_b555Mode = FALSE; // default to 5-6-5 mode for 16Bpp

// NOTE:
// The following data members are modified to their final values
// by the default implementation of SetMode and shouldn't need to
// modified here or in ModeInit.
//
m_pPrimarySurface = NULL; // pointer to primary display surface
m_nScreenWidth = 0; // display width
m_nScreenHeight = 0; // display height
m_pMode = NULL; // pointer to information on current mode
m_p2DVideoMemory = NULL; // pointer to video memory manager
m_pLAW = NULL; // pointer to linear access window
memset(&m_ulBitMasks[0], 0, sizeof(m_ulBitMasks)); // bit masks

// NOTE:
// The following data members MUST be modified to their final
// values by the display hardware specific function ModeInit.
//
m_nLAWPhysical = 0; // the physical address of the linear access
// window for accessing the frame buffer
m_nLAWSize = 0; // size of linear access window
m_nVideoMemorySize = 0; // size of video memory, which can be different
// than the linear access window
m_nVideoMemoryStart = 0;// offset within the linear access window to the
// start of video memory (usually is 0)
m_nScreenStride = 0; // number of bytes per display line
}
To allow these functions to be hardware independent, mode information used by NumModes() and GetModeInfo() is taken from the variable m_gpeModeTable, a table of the supported display modes. This variable needs to be initialized by the driver developer based on the modes that will be supported by the driver. It is statically defined in the provided source file NEWGPE.CPP. However, this could be changed so that the table is instead loaded from the registry or a file when the driver is first run.
int NewGPE::NumModes()
{
// count the number of entries in the mode table

BOOL bDone = FALSE;
int nIndex = 0;
while (!bDone) {
if (m_gpeModeTable[nIndex].Bpp==0) {
// no more entries in the table
bDone = TRUE;
}
else {
// count entry and go to next entry
nIndex++;
}
}

return nIndex;
}

SCODE NewGPE::GetModeInfo(
GPEMode *pMode,
int modeNo )
{
// make sure that the mode is valid (index is zero based)
if ((modeNo<0) || (modeNo>=NumModes()))
return E_INVALIDARG;

// get data from mode table
*pMode = m_gpeModeTable[modeNo];

return S_OK;
}
The SetMode() function has been written to require no additional modification. It handles all the hardware independent mode initialization. The first step is to verify the selected mode from the list of supported modes. Once this is complete, the hardware dependent mode initialization function, ModeInit(), is called. The ModeInit() function must be overridden or modified to initialize the specific hardware and setup certain variables used elsewhere in the initialization process. These variables are:
 
  • m_nLAWPhysical - This specifies the physical address of the linear access window of the display device for accessing the frame buffer.
  • m_nLAWSize - The size of the linear access window.
  • m_nVideoMemorySize - The total amount of video memory available.
  • m_nVideoMemoryStart - The offset of video memory in the linear access window. This is usually 0.
  • m_nScreenStride - The number of bytes per display line.
  • m_bHWCursor - Flag to indicate support for hardware cursor, which is used to bypass existing software cursor support. The actual implementation for hardware cursors still would need to be included.
  • m_b555Mode - Flag to indicate that the 16-bit mode uses 5 bits each for red, green, and blue.
  • m_bIsVGADevice - Flag to indicate that the device is VGA based. This should actually be cleared in the constructor to prevent mapping of VGA registers, but at this point is still useful in bypassing default VGA implementations for SetPalette() and InVBlank().
Once the hardware specific initialization is completed in ModeInit(), the SetMode() function continues the hardware independent mode initialization. The m_pMode, m_nScreenWidth and m_nScreenHeight variables, used by other functions, are set for the new display mode. Then a pointer, m_pLAW, to be used later for accessing video memory, is mapped to the physical address of the linear access window of the display device. To do this, calls to the VirtualAlloc() and VirtualCopy() functions are required. See the Platform Builder help for more information on these functions. Next, a Node2D object, m_p2DVideoMemory, representing all of available video memory is created. This Node2D object manages video memory for the AllocSurface() function, which is then called to create the primary display surface, m_pPrimarySurface. Finally, the bit mask is initialized and the default palette is setup. It may not be clear within this function, but there are really two different 16-bit display modes in common use. One mode uses 5 bits each for red, green and blue, while the other mode uses 5 bits for red and blue and 6 bits for green. The mask values are used by GDI to generate the correct pixel value to represent a particular color. The flag m_b555Mode is used in the driver to determine which 16-bit display mode has been set in the hardware when initializing the mask values. For modes other than 16-bit, this flag is ignored. It is worth noting that the bit mask created here, m_ulBitMasks, is also used by the DDI function DrvGetMasks() to return pixel formatting information.
 
SCODE NewGPE::SetMode(
int modeId,
HPALETTE *pPaletteHandle )
{
int nModeNum = 0;
GPEMode gpeMode;
// get mode entry that matches modeId
BOOL bDone = FALSE;
int nNumModes = NumModes();
while (!bDone) {
if (nModeNum>=nNumModes) {
// failed to find matching mode entry
bDone = TRUE;
}
else if ((GetModeInfo(&gpeMode, nModeNum)==S_OK) &&
(gpeMode.modeId==modeId)) {
// found matching mode entry
bDone = TRUE;
}
else {
// check next entry
nModeNum++;
}
}
// check if mode number is valid
if (nModeNum>=nNumModes) {
return E_INVALIDARG;
}

// pass mode info to the hardware specific initialization
// function
SCODE scInit = ModeInit(&m_gpeModeTable[nModeNum]);

if (scInit!=S_OK) {
// something failed here, don't go any further
return scInit;
}
// verify parameters ModeInit is required to initialize
if ((m_nLAWPhysical==0) || (m_nLAWSize==0) || (m_nVideoMemorySize==0) ||
(m_nScreenStride==0)) {
// ERROR: ModeInit failed to properly initialize some data
// members that are required. These data members need
// to be initialized for this function to work.
return E_FAIL;
}

// continue with hardware independent initialization
//
// Using the following values initialized by ModeInit:
// * m_nLAWPhysical
// * m_nLAWSize
// * m_nVideoMemorySize
// * m_nVideoMemoryStart
// * m_nScreenStride
// * m_bHWCursor (optional)
// * m_b555Mode (optional)
//
// Initialize the remaining values:
// * m_pMode
// * m_nScreenWidth
// * m_nScreenHeight
// * m_pLAW
// * m_p2DVideoMemory
// * m_pPrimanrySurface
// * m_ulBitMasks
//
// And don't forget to initialize the palette parameter
// pPaletteHandle.

// initialize remaining values
//
m_pMode = &m_gpeModeTable[nModeNum]; // current mode
m_nScreenWidth = m_pMode->width; // current display width
m_nScreenHeight = m_pMode->height; // current display height

// generate pointer to linear access window
// (can't address physical memory directly, but need to
// create and map a pointer)
m_pLAW = (unsigned char *) VirtualAlloc(NULL, m_nLAWSize, MEM_RESERVE, PAGE_NOACCESS);
BOOL bCreateLAW;
if (m_nLAWPhysical<0x20000000) { // handle <512MB address differently
bCreateLAW = VirtualCopy(m_pLAW, (LPVOID) (m_nLAWPhysical|0x80000000), m_nLAWSize,
PAGE_READWRITE|PAGE_NOCACHE);
}
else {
bCreateLAW = VirtualCopy(m_pLAW, (LPVOID) (m_nLAWPhysical>>8), m_nLAWSize,
PAGE_READWRITE|PAGE_NOCACHE|PAGE_PHYSICAL);
}
// check for error creating LAW pointer
if (!bCreateLAW) {
return E_FAIL;
}

// create Node2D instance (for managing video memory)
m_p2DVideoMemory = new Node2D(m_nScreenWidth, m_nVideoMemorySize/m_nScreenStride,
0, 0, 32/m_pMode->Bpp);
// check for error creating Node2D instance
if (m_p2DVideoMemory==NULL) {
return E_FAIL;
}

// create primary surface
SCODE scAlloc = AllocSurface(
&m_pPrimarySurface,
m_nScreenWidth,
m_nScreenHeight,
m_pMode->format,
GPE_REQUIRE_VIDEO_MEMORY);
// check for error allocating primary surface
if (scAlloc!=S_OK) {
return E_FAIL;
}

// initialize bitmasks based on current bits per pixel
memset(&m_ulBitMasks[0], 0, sizeof(m_ulBitMasks));
if (m_pMode->Bpp==16) {
// 16Bpp has two mask options
if (m_b555Mode) { // 5-5-5 mode
m_ulBitMasks[0] = 0x7c00; // red
m_ulBitMasks[1] = 0x03e0; // green
m_ulBitMasks[2] = 0x001f; // blue
}
else { // 5-6-5 mode
m_ulBitMasks[0] = 0xf800; // red
m_ulBitMasks[1] = 0x07e0; // green
m_ulBitMasks[2] = 0x001f; // blue
}
}

// create a default palette, if necessary
if (pPaletteHandle!=NULL) {
// create palette
switch (m_pMode->Bpp) {
case 24:
case 32:
*pPaletteHandle = EngCreatePalette (PAL_BGR, 0, NULL, 0, 0, 0);
break;
case 16:
*pPaletteHandle = EngCreatePalette(PAL_BITFIELDS, 0, NULL, m_ulBitMasks[0],
m_ulBitMasks[1], m_ulBitMasks[2]);
break;
case 8:
*pPaletteHandle = EngCreatePalette(PAL_INDEXED,256,(ULONG *)m_rgbIdentityPal,0,0,0);
SetPalette(m_rgbIdentityPal, 0, 256); // palette needs to be set here
break;
case 4:
*pPaletteHandle = EngCreatePalette(PAL_INDEXED,16,(ULONG *)m_rgbIdentityPal16,0,0,0);
SetPalette(m_rgbIdentityPal16, 0, 16); // palette needs to be set
break;
default:
RETAILMSG(1,(TEXT("NewGPE::SetMode Failed to create unknown palette type.\r\n")));
break;
}
}

return S_OK;
}
The base surface class, GPESurf, must be derived from in order to support the creation of video memory surfaces. Since default management of video memory is already defined within the NewGPE class through the Node2D object m_p2DVideoMemory, it makes sense to include support for the creation of video memory surfaces in our derived surface class, NewGPESurf. This is accomplished by providing a constructor that sets the video memory flag and maintains the Node2D instance for the video memory of this surface. The destructor is then responsible for deleting the saved Node2D instance, thus freeing the video memory occupied by this surface. This is all that needs to be done for the NewGPESurf class.
NewGPESurf::NewGPESurf(
int width,
int height,
void *pBits,
int stride,
EGPEFormat format,
int offset,
Node2D *pNode)
{
// call general GPESurf initialization
Init(width, height, pBits, stride, format);
m_pNode2D = pNode;

if (pNode!=NULL) {
// surface in video memory, set flags and parameters
m_fInVideoMemory = TRUE;
}
}

NewGPESurf::~NewGPESurf()
{
// free video memory if applicable
if (m_fInVideoMemory && (m_pNode2D!=NULL)) {
delete m_pNode2D;
}
}
The AllocSurface() function in the NewGPE class is responsible for handling the creation of system and video memory surfaces. It uses m_p2DVideoMemory, the Node2D object previously created in the SetMode() function, for allocating video memory. The surface itself is then created using our derived NewGPESurf class. As was previously noted, video memory surfaces can only be created in the same pixel format as the current display mode due to limitations in Node2D. System memory surfaces are created using the base GPESurf class.
SCODE NewGPE::AllocSurface(
GPESurf **ppSurf,
int width,
int height,
EGPEFormat format,
int surfaceFlags )
{
SCODE scRet = S_OK;
*ppSurf = NULL;

// check parameters are valid:
// video memory surface must have same pixel format as display
if (surfaceFlags & GPE_REQUIRE_VIDEO_MEMORY) {
// video memory surface must have same pixel format as display
if (format!=m_pMode->format)
return E_INVALIDARG;
}

// check if video memory surface requested
if ((surfaceFlags & GPE_REQUIRE_VIDEO_MEMORY) ||
((surfaceFlags & GPE_PREFER_VIDEO_MEMORY) &&
(format==m_pMode->format))) {
// try allocating out of video memory
Node2D *pNode = m_p2DVideoMemory->Alloc(width, height);

if (pNode!=NULL) {
// get offset into video memory
DWORD dwOffset = (m_nScreenStride * pNode->Top()) +
((pNode->Left() * EGPEFormatToBpp[format]) / 8);

// now create a surface for the allocated video memory
*ppSurf = new NewGPESurf(
width,
height,
m_pLAW + dwOffset,
m_nScreenStride,
format,
dwOffset,
pNode);
if (*ppSurf!=NULL) {
// video memory surface allocated successfully
return S_OK;
}

// failed creating surface for video memory
delete pNode; // free video memory
}

// if we got here then unable to allocate out of video memory
if (surfaceFlags & GPE_REQUIRE_VIDEO_MEMORY)
return E_OUTOFMEMORY; // fail since surface requires video memory
}

// Allocate surface from system memory if not in video memory
*ppSurf = new GPESurf(width, height, format);
if (*ppSurf!=NULL) {
// make sure system memory allocated
if ((*ppSurf)->Buffer()!=NULL) {
// system memory surface allocated successfully
return S_OK;
}

// system memory surface allocation failed
delete *ppSurf;
// just fall through to fail
}

// if we got here then something failed
return E_OUTOFMEMORY;
}
The most straightforward places to provide default implementations are the line drawing and blit functions. For BltPrepare(), all that needs to be done is to specify the default GPE blit function. For BltComplete(), nothing needs to be done.
SCODE NewGPE::BltPrepare( GPEBltParms *pBltParms )
{
// use the default blit function
pBltParms->pBlt = EmulatedBlt;

return S_OK;
}

SCODE NewGPE::BltComplete( GPEBltParms *pBltParms )
{
// don't need to do anything here
return S_OK;
}
As with BltPrepare(), the function Line() can simply specify the default GPE line drawing function.
SCODE NewGPE::Line(
GPELineParms *pLineParms,
EGPEPhase phase /* = gpeSingle */ )
{
// use the default line function
pLineParms->pLine = EmulatedLine;

return S_OK;
}
For display devices that handle cursors in hardware, the cursor functions SetPointerShape() and MovePointer() need to be changed or overridden to include this support. Since this functionality is not available in all display hardware or only in certain display modes, I have provided software cursor support in the base implementation of these functions. See the provided source file CURSOR.CPP for the details of software cursor support. It should be noted that software cursor management required changes in other sections of the driver as well. Searching the provided source files for the variable m_bHWCursor, the flag for selecting between software and hardware cursor, will highlight these additional changes.
For SetPalette() and InVBlank(), the VGA implementations are well defined and are even provided in the GPEVGA class. Therefore, default VGA support is included in the NewGPE class as well. For non-VGA display devices, support will have to be added to these functions. For reference, see the implementation of these functions in the provided source file MISC.CPP.
As you have seen, the NewGPE class requires only the ModeInit() function to be modified or overridden when using a VGA display device that supports a linear frame buffer. For non-VGA display devices, the only additional functions that need to be modified are SetPalette() and InVBlank(). In addition, for any display device type, the m_gpeModeTable variable needs to be initialized with the modes supported by the driver. It would be difficult to make driver development any simpler than this.

Conclusion

As you have seen, the Windows CE display driver model and the Microsoft provided C++ classes are a good starting point for display driver development. The improvements made here to these C++ classes can further simplify this development process, while still allowing for the same level of flexibility as provided in the original classes. As well, these changes should make the classes more portable as you go from project to project. However, it is important to keep in mind that this discussion is by no means comprehensive in its coverage of display driver related development in Windows CE, and that there are plenty of other topics for you still to explore.
Chủ Nhật, 2 tháng 10, 2011 08:44 Đọc tiếp >>