# PCI-MPG24

4-CH MPEG4 Hardware

Video Compression Card

Programming Guide

Manual Rev. 2.01

Revision Date: January 28, 2008

Part No: 50-15035-1040

![A black circle containing a white recycling symbol composed of three arrows arranged in a triangular loop. Each arrow features horizontal stripes along its inner edge.](.pci-mpg24-manual-18/120f0c52d3cc517fbb74b077de6840837fc6e4324f9f70cd988524479f469aed.jpg)
Recycled Paper

Copyright 2008 ADLINK TECHNOLOGY INC.

All Rights Reserved.

The information in this document is subject to change without prior notice in order to improve reliability, design, and function and does not represent a commitment on the part of the manufacturer.

In no event will the manufacturer be liable for direct, indirect, special, incidental, or consequential damages arising out of the use or inability to use the product or documentation, even if advised of the possibility of such damages.

This document contains proprietary information protected by copyright. All rights are reserved. No part of this manual may be reproduced by any mechanical, electronic, or other means in any form without prior written permission of the manufacturer.

# Trademarks

Microsoft®, Windows NT®, Windows 98®, Windows 2000®, and Windows XP® are registered trademarks of Microsoft Corporation. Borland C++ Builder® is a registered trademark of Borland International, Inc.

Other product names mentioned herein are used for identification purposes only and may be trademarks and/or registered trademarks of their respective companies.

# Getting Service from ADLINK

Customer Satisfaction is top priority for ADLINK Technology Inc. Please contact us should you require any service or assistance.

# ADLINK TECHNOLOGY INC.

Web Site: http://www.adlinktech.com

Sales & Service: Service@adlinktech.com

TEL: +886-2-82265877

FAX: +886-2-82265717

Address: 9F, No. 166, Jian Yi Road, Chungho City,

Taipei, 235 Taiwan

Please email or FAX this completed service form for prompt and satisfactory service.

<table><tr><td colspan="2">Company Information</td></tr><tr><td>Company/Organization</td><td></td></tr><tr><td>Contact Person</td><td></td></tr><tr><td>E-mail Address</td><td></td></tr><tr><td>Address</td><td></td></tr><tr><td>Country</td><td></td></tr><tr><td>TEL</td><td>FAX:</td></tr><tr><td>Web Site</td><td></td></tr><tr><td colspan="2">Product Information</td></tr><tr><td>Product Model</td><td></td></tr><tr><td>Environment</td><td>OS:M/B: CPU:Chipset: BIOS:</td></tr></table>

Please give a detailed description of the problem(s):

# Table of Contents

# 1 DirectX Programming Guide .... 1

1.1 DirectShow Application Programming Introduction ...... 1
1.2 Descriptions of Filters 2

Source Filter 2
Video Renderer Filter 4
MPEG4 AVI Mux Filter 5
MPEG4 File Writer 5
CrossBar Filter 6

1.3 Example Graphs 6

ADLink Bt878 Video Capture filter 7
ADLink Bt878 Crossbar filter 8
ADLINK Hardware MPEG4 Device 8
Preview 10
Capture 10

1.4 Controlling Driver 11

Preview 11
Capture 13

# 2 DirectX Reference Manual.... 15

2.1 Preview 15

GPIO Access 15
Bt878 GPIO PIN Definition 18
EEPROM Access 19

2.2 Capture 22

WDM Streaming Capture Filter 22
Media Types 23
Data Structures 24
Enumerations 55
Filter Interfaces 64
IOSD Interfaces 96
Pin Interfaces 98

2.3 OSD Programming 98

Introduction to OSD 98
Context 99
OSD Font Bitmaps 99
OSD Fonts Display 99
OSD Frame 100
OSD Algorithm 100

Bitmap Stored in SDRAM 101

OSD Pixel Color (4-bit OSD Data) 101

Know Limitations 103

OSD Data Structure 105

# 3 Windows API Functions.... 107

3.1 Introduction to Windows API Functions 107

3.2 Function List.... 107

3.3 Setting Up the Build Environment.... 109

Include Files 109

Library File 109

DLL Files 110

3.4 System Functions 110

Mpg24\_PreviewOpen(CardNo) 110

Mpg24\_EncoderOpen(CardNo, PortNo) 110

Mpg24\_PreviewClose(CardNo) 111

Mpg24\_EncoderClose(CardNo, PortNo) 111

Mpg24\_PlayFileClose(Index) 111

Mpg24\_ReadSerial(CardNo, HighByte, LowByte) ..... 112

3.5 Configuration Functions 113

Mpg24\_PreviewGetImageRange(CardNo, Property, Min, Max, SteppingDelta, Default) 113

Mpg24\_EncoderGetImageRange(CardNo, PortNo, Property, Min, Max, SteppingDelta, Default) ...... 113

Mpg24\_PreviewGetImageConfig(CardNo, Property, Value)
114

Mpg24\_EncoderGetImageConfig(CardNo, PortNo, Property, Value) 114

Mpg24\_PreviewSetImageConfig(CardNo, Property, Value)
116

Mpg24\_EncoderSetImageConfig(CardNo, PortNo, Property, Value) 116

Mpg24\_PreviewGetVideoFormat(CardNo, FormatIndex, Value) 117

Mpg24\_EncoderGetVideoFormat(CardNo, PortNo, Format-Index, Value) 117

Mpg24\_PreviewSetVideoFormat(CardNo, FormatIndex, Value) 119

Mpg24\_EncoderSetVideoFormat(CardNo, PortNo, Format-Index, Value) 119

Mpg24\_PreviewSetCustomSize(CardNo, Width, Height) . 120

Mpg24\_PreviewSetDisplay(CardNo, Handle, X, Y, AutoShow) 121

Mpg24\_PlayFileSetDisplay(Index, Handle, X, Y, Width, Height, AutoShow) 121

Mpg24\_EncoderSetFile(CardNo, PortNo, FileName) . 122

Mpg24\_PlayFileSetFile(Inex, FileName) 122

3.6 Action Functions 124

Mpg24\_PreviewRun(CardNo) 124

Mpg24\_EncoderRun(CardNo, PortNo) 124

Mpg24\_PlayFileRun(Index) 124

Mpg24\_PreviewPause(CardNo) 125

Mpg24\_PlayFilePause(Index) 125

Mpg24\_PreviewStop(CardNo) 126

Mpg24\_EncoderStop(CardNo, PortNo) 126

Mpg24\_PlayFileStop(Index) 126

Mpg24\_PreviewShow(CardNo, Visible) 127

Mpg24\_PlayFileShow(Index, Visible) 127

Mpg24\_PreviewSelectChannel(CardNo, PortNo, Mode) .. 128

Mpg24\_PreviewSaveImage(CardNo, FileName) ...... 129

Mpg24\_PlayFileSaveImage(Index, FileName) ...... 129

Mpg24\_EncoderSetOSD(CardNo, PortNo, OSDText, Len)
130

3.7 Watchdog Functions 131

Mpg24\_WatchdogConfig(CardNo, TriggerInterval) .... 131

Mpg24\_WatchdogEnable(CardNo) 132

Mpg24\_WatchdogDisable(CardNo) 133

Mpg24\_WatchdogTrigger(CardNo) 134

3.8 IO Functions 135

Mpg24\_SetGPIO(CardNo, PortNo, Status) 135

Mpg24\_GetGPIO(CardNo, PortNo, Status) 136

Mpg24\_WriteEEPROM(CardNo, Offset, Value) ...... 137

Mpg24\_ReadEEPROM(CardNo, Offset, Value) ...... 138

3.9 Miscellaneous Functions 139

Mpg24\_PreviewCallback(CardNo, CallbackProc) ..... 139

Mpg24\_EncoderCallback(CardNo, PortNo, CallbackProc)
139

Mpg24\_PlayFileCallback(Index, CallbackProc) ...... 139

Mpg24\_PreviewGetStatue(CardNo, Status) 140

Mpg24\_EncoderGetStatus(CardNo, PortNo, Status) . 140

Mpg24\_PlayFileGetStatus(Index, Status) 140

Mpg24\_GetLastErrorInfo(ErrorInfo) 141

3.10 Error Codes.... 142

# 4 ActiveX Control.... 143

4.1 PCI-MPG24 ActiveX Control Introduction 143
4.2 Setting Up the Build Environment.... 143
4.3 Properties and Methods.... 144

Preview control 144

Encoder Control 147

# 5 Linux Programming Guide.... 151

5.1 Overview.... 151
5.2 Encoder Linux SDK Architecture 152
5.3 Encoder LINUX SDK Interfaces.... 154

Initialization Methods 156

CreateInstance 156
Release 156
DeviceExist 157
GetBoardInfo 157

Video Operation Methods 158

SetVideoConfig 158
StartCapturing 158
StopCapturing 159
GetOneFrame 159
SetVideoSource 160
GetVideoSource 160
SetTVStandard 161
ChangePFrameRate 161
SetFPS 162
BitrateControl 162
ChangeIFrameQuantizer 165
ChangePFrameQuantizer 166
ChangeBrightness 166
ChangeContrast 167
ChangeHue 167
ChangeSaturation 168
ForceIFrame 168

sigDetect 169

SetMDRegions 170

SetMDThresholdsAndSensitivities 171

ResetMotionDetection 171

InitMotionDetection 172

OSD\_show 172

Debugging Operation Methods.... 174

ReadCBusReg 174

WriteCBusReg 174

ReadCBus 175

WriteCBus 175

I2C\_WriteRegister 176

GPIO\_Read 177

5.4 WIS-LIVE Interface 178

WIS-LIVE APIs 178

PlayMPEG4AudioVideoStream 178

PlayMPEG1or2AudioVideoStream 179

WIS-LIVE-STAND APIs 180

PlayAudioVideoStream 180

WIS-LIVE Structure 182

StreamBufQueue\_t 182

Stream\_buf\_s 182

5.5 OSD APIs 183

Purpose 183

API Description 183

init\_osd 183

get\_osd\_frame 184

show\_osd\_frame 185

clean\_osd 185

5.6 FFMPEG APIs 187

AV CODEC APIs 188

register\_avcodec 188

avcodec\_find\_encoder 188

avcodec\_find\_decoder 188

avcodec\_open 189

avcodec\_close 189

avcodec\_encode\_audio 190

avcodec\_decode\_audio 191

avcodec\_encode\_video 191

avcodec\_decode\_video 192

avpicture\_get\_size 193
avpicture\_fill 193
av\_mallocz 194
avcodec\_alloc\_context 194
avcodec\_alloc\_frame 195
avcodec\_get\_context\_defaults 195

# AV Format APIs 197

register\_protocol 197
mpegps\_init 197
Synopsis: 197
mp3\_init 198
wav\_init 198
guess\_format 199
url\_fopen 199
url\_fclose 200
av\_write\_frame 200
av\_set\_parameters 201
av\_write\_header 202
av\_probe\_input\_format 202
av\_write\_trailer 203
av\_gettime 203
av\_new\_stream 203
dump\_format 204
av\_write\_header 204

# Structures and Constants 206

# 5.7 CServer Interface.... 207

Purpose 207
Method Summary 207
Method Description 207
Start 207
Stop 209
init\_channel 209
do\_work\_thread 210
do\_audio\_work\_thread 210
do\_send\_thread 211
do\_send\_video\_thread 211
do\_md\_thread 211
do\_sigdet\_thread 212
send\_one\_frame 212
do\_mux\_thread\_simple 213

IsPFrame 213

GetVideoSource 213

SetVideoSource 214

SetTVStandard 214

# 5.8 Motion Detector Interface 216

Method Description 216

MotionDetector 216

MDSetEnable 216

SetPicSize 217

# 5.9 Structures and Enumerations 218

REVISION\_INFO Structure 218

Include 218

Syntax 218

Members 218

TCFGVIDEO Structure 220

Include 220

Syntax 220

Members 220

AUDIO\_CONFIG Structure.... 221

Include 221

Syntax 221

Members 221

TCFG\_HEADER Structure 222

Include 222

Syntax 222

Members 222

TCFGMISC Structure 223

Include 223

Syntax 223

Members 223

TCFGSTREAM Structure 226

Include 226

Syntax 226

Members 226

TCFGFRAMERATE Structure 229

Include 229

Syntax 229

Members 229

TCFGRESOLUTION Structure 231

Include 231

Syntax 231

Members 231

TCFGBRCTRL Structure 234

Include 234

Syntax 234

Members 234

TFrameInfo Structure 236

Include 236

Syntax 236

Members 236

BOARD\_CAP Enumeration 237

Include 237

Syntax 237

AUDIO\_FORMAT Enumeration 238

Include 238

Syntax 238

EVideoFormat Enumeration.... 239

Include 239

Syntax 239

ESequenceMode Enumeration 240

Include 240

Syntax 240

Typedef 240

Appendix A: Glossary 241

Brightness: 241

CCIR: 241

Composite Video: 241

CIF: 241

EIA: 241

Field: 241

Frame: 242

Gamma: 242

Hue: 242

NTSC: 242

PAL: 242

Saturation: 243

AGC 243

Appendix B: Standard Compliance 244

# List of Tables

Table 1-1: ADLink Bt878 Video Capture 3

Table 1-2: ADLINK Hardware MPEG4 Device 4

Table 1-3: Video Renderer Filter 4

Table 1-4: MPEG4 AVI Mux Filter 5

Table 1-5: MPEG4 File Writer 5

Table 1-6: CrossBar Filter 6

Table 2-1: Bt878 GPIO PIN Definition 18

Table 2-2: Function Table 19

Table 2-3: WDM Streaming Capture Filter 22

Table 2-4: DIVX\_MPEG4 23

Table 2-5: MICROSOFT\_MPEG4 23

Table 2-6: MPEG2 23

Table 2-7: MPEG1 24

Table 2-8: H263 24

Table 2-9: MJPG 24

Table 2-10: SPI Control Register Definition 88

Table 2-11: ADLINK Hardware MPEG4 Device GPIO Pinout ... 91

# List of Figures

Figure 1-1: ADLink Bt878 Crossbar 13

Figure 5-1: Application Based on LinuxSDK.... 152

Figure 5-2: DFD of Encoder Linux SDK.... 153

# 1 DirectX Programming Guide

# 1.1 DirectShow Application Programming Introduction

A complete documentation on DirectShow application programming can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/directx9\_c/directX/htm/introductiontodirectshow.asp. If a DirectX 9.0 is installed, this documentation is also available from DirectX SDK Help.

The purpose of writing a DirectShow Application is to build a filter graph by connecting several filters together to perform a given task such as previewing video/audio, capturing video/audio and multiplexing them to write into a file. Each filter performs a single operation and pass data from its output pin to the input pin of the next filter in the graph.

To build a capture graph using a program, first obtain the interface pointer of the capture filter. The ADLink Bt878 Video Capture filter and the ADLINK Hardware MPEG4 Device filter can be obtained through the system device enumerator. After holding an interface pointer to the capture filter object, use method IGraphBuilder::AddSourceFilter to add the source filter object to the filter graph. Use IFilterGraph::AddFilter to add other downstream filters to the filter graph. After filters are added, call IFilterGraph::ConnectDirect or IGraphBuilder::Connect methods to connect output pins from upstream filters to the input pins of the downstream filters. Calling methods such as IMediaControl::Run, IMediaControl::Pause, or IMediaControl::Stop will change filter state to running, paused or stopped.

The filters needed for capturing MPEG4 streams are listed in section 1.2, along with a detailed description for each filter and its pins. Example filter graphs for previewing/capturing MPEG4 streams are illustrated in section 1.3. Section 1.4 provides examples of two ways of controlling the device driver.

# 1.2 Descriptions of Filters

This chapter lists filters needed to build a filter graph for capturing MPEG4 video stream and previewing video stream.

# Source Filter

# ADLink Bt878 Video Capture

ADLink Bt878 Video Capture Filter belongs to the family of WDM Streaming Capture Devices. It is a kernel-mode KsProxy plug-in, where an application can treat it simply as a filter. Use the System Device Enumerator to add this filter to a filter graph.

<table><tr><td>Filter Name</td><td>ADLink Bt878 Video Capture</td></tr><tr><td>Filter CLSID</td><td>Not applicable</td></tr><tr><td>Filter Category Name</td><td>WDM Streaming Capture Devices</td></tr><tr><td>Filter Category</td><td>AM_KSCATEGORY_CAPTURE</td></tr><tr><td>Video Capture Pin Supported Media Types</td><td>MEDIATYPE_Video Subtypes:► MEDIASUBTYPE_YUY2► MEDIASUBTYPE_YVU9► MEDIASUBTYPE_UYVY► MEDIASUBTYPE_YV12► MEDIASUBTYPE_I420► MEDIASUBTYPE_Y41P► MEDIASUBTYPE_RGB24► MEDIASUBTYPE_RBG32► MEDIASUBTYPE_RBG565► MEDIASUBTYPE_RBG555</td></tr></table>

<table><tr><td>Video Preview Pin Supported Media Types</td><td>MEDIATYPE_Video Subtypes:► MEDIASUBTYPE_YUV2► MEDIASUBTYPE_YVU9► MEDIASUBTYPE_UYVY► MEDIASUBTYPE_YV12► MEDIASUBTYPE_I420► MEDIASUBTYPE_Y41P► MEDIASUBTYPE_RGB24► MEDIASUBTYPE_RBG32► MEDIASUBTYPE_RBG565► MEDIASUBTYPE_RBG555</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr></table>

Table 1-1: ADLink Bt878 Video Capture

# ADLINK Hardware MPEG4 Device

ADLINK Hardware MPEG4 Device belongs to the family of WDM Streaming Capture Devices. It is a kernel-mode KsProxy plug-in where an application can treat it simply as a filter. Use the System Device Enumerator to add this filter to a filter graph.

<table><tr><td>Filter Name</td><td>ADLINK Hardware MPEG4 Device</td></tr><tr><td>Filter CLSID</td><td>Not applicable</td></tr><tr><td>Filter Category Name</td><td>WDM Streaming Capture Devices</td></tr><tr><td>Filter Category</td><td>AM_KSCATEGORY_CAPTURE</td></tr><tr><td>Video Capture Pin Supported Media Types</td><td>DIVX_MPEG4, MICROSOFT_MPEG4,MPEG2,MPEG1,H.263,MJPG(For detailed definition of each media type,please refer to DirectX Reference Manual chapter 2.2: Media Types)</td></tr></table>

<table><tr><td>Video Preview Pin Supported Media Types</td><td>DIVX_MPEG4, MICROSOFT_MPEG4,MPEG2,MPEG1,H.263,MJPG(For detailed definition of each media type,please refer to DirectX Reference Manual chapter 2.2:Media Types)</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr></table>

Table 1-2: ADLINK Hardware MPEG4 Device

Video Renderer Filter

<table><tr><td>Filter Name</td><td>Video Renderer</td></tr><tr><td>Filter CLSID</td><td>CLSID_VideoRenderer</td></tr><tr><td>Filter Category Name</td><td>DirectShow Filters</td></tr><tr><td>Filter Category CLSID</td><td>CLSID_LegacyAmFilterCategory</td></tr><tr><td>Input Pin Media Types</td><td>MEDIATYPE_Video</td></tr><tr><td>Output Pin Media Types</td><td>Not Applicable</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr></table>

Table 1-3: Video Renderer Filter

# MPEG4 AVI Mux Filter

<table><tr><td>Filter Name</td><td>AVI Mux</td></tr><tr><td>Filter CLSID</td><td>CLSID_AviDest</td></tr><tr><td>Filter Category Name</td><td>DirectShow Filters</td></tr><tr><td>Filter Category CLSID</td><td>CLSID_LegacyAmFilterCategory</td></tr><tr><td>Input Pin Media Types</td><td>Any major type that corresponds to an old-style FOURCC, or MEDIATYPE_AUXLine21Data.► If the major type is MEDIATYPE_Audio, the format must be FORMAT_WaveFormatEx.► If the major type is MEDIATYPE_Video, the format must be FORMAT_VideoInfo or FORMAT_DvInfo.► If the major type is MEDIATYPE_Interleaved, the format must be FORMAT_DvInfo.</td></tr><tr><td>Output Pin Media Types</td><td>MEDIATYPE_Stream, MEDIASUBTYPE_Avi</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr></table>

Table 1-4: MPEG4 AVI Mux Filter

# MPEG4 File Writer

<table><tr><td>Filter Name</td><td>File writer</td></tr><tr><td>Filter CLSID</td><td>CLSID_FileWriter</td></tr><tr><td>Filter Category Name</td><td>DirectShow Filters</td></tr><tr><td>Filter Category CLSID</td><td>CLSID_LegacyAmFilterCategory</td></tr><tr><td>Input Pin Media Types</td><td>MEDIATYPE_Stream, MEDIASUBTYPE_NULL</td></tr><tr><td>Output Pin Media Types</td><td>Not Applicable</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr></table>

Table 1-5: MPEG4 File Writer

# CrossBar Filter

If the device is a capture board, a CrossBar filter is needed for switching video source.

<table><tr><td>Filter Name</td><td>ADLink Bt878 CrossBar</td></tr><tr><td>Filter Category Name</td><td>WDM_Streaming Crossbar Devices</td></tr></table>

Table 1-6: CrossBar Filter

# 1.3 Example Graphs

Microsoft DirectX SDK provides a very useful debugging utility - GraphEdit, which can be used to simulate graph building. From the Graph menu of the GraphEdit application, click Insert Filters... and choose the filters required. Filters are organized by categories. Click Insert Filter to add filters to a graph. Connect the two filters' pins by dragging the mouse from one filter's output pin to another filter's input pin. An arrow will be drawn if these two pins agree on the connection.

After inserting the ADLINK Bt878 Video Capture filter, the ADLink Bt878 Crossbar filter, and/or ADLINK Hardware MPEG4 Device filter, right-click on the rectangle and click Filter Properties.... The filter properties dialogue will appear. Use the property pages to set video settings before connecting video pins to other filters. The property pages are shown below:

# ADLink Bt878 Video Capture filter

# Video Decoder:

![ADLINK Bt878 Video Capture Properties\nVideo Decoder | Video Proc Amp | Capture | Preview | VBI | Analog Video In |\nVideo Standard: NTSC_M\nSignal Detected: 1\nLines detected: 525\n□ VCR Input\n□ Output Enable\nOK    Cancel    Apply    Help](.pci-mpg24-manual-18/4a1b6550487e97d569cda79a619ed73a92e1b563f02f3c9ee0b32bd937f5af93.jpg)

# Video Proc Amp:

![ADLINK Bt878 Video Capture Properties\nVideo Decoder | Video Proc Amp | Capture | Preview | VBI | Analog Video In |\nBrightness\nContrast\nHue\nSaturation\nSharpness\nGamma\nWhite Balance\nBacklight Comp\nColorEnable ✓\nDefault\n750\n100\n0\n100\n50\n1\n0\n1\nAuto\nOK    Cancel    Apply    Help](.pci-mpg24-manual-18/e8c32eaebb43364d3fc58e89d6e0bf87b71822e8ca7bfff33a423970db29381e.jpg)

# ADLink Bt878 Crossbar filter

![ADLINK Bt878 Crossbar Properties\n2: Video Composite In\n3: Video Composite In\n0: Video Decoder Out\n1: Audio Decoder Out\nCrossbar\n0: Video Composite In\n1: Video Composite In\nInput\n1: Video Composite In\nCurrent Input:\n1: Video Composite In\nRelated Pin:\n0: Video Composite In\nLink Related Streams\nOutput\n0: Video Decoder Out\nRelated Pin:\n1: Audio Decoder Out\nOK	Close	Apply	Help](.pci-mpg24-manual-18/884092b5fed61e1f3277217332897cab0e3c74f33d47e8c806bb113d45a63ef8.jpg)

Select video input before or during video previewing.

# ADLINK Hardware MPEG4 Device

# Video Setting:

![ADLINK Hardware MPEG4 Device Properties\nVideo Proc Amp	Video Decoder	Video Capture	Video Preview\nVideo Setting	Audio Setting	Camera Control\nSystem	TW2804 NTSC IPAL\nStream	Microsoft MPEG4, IP Only\nFrame Rate	NTSC 29.97fps\nResolution	NTSC SD\nBitrate	Constant 6M\nFrame Rate	0\nBitrate	0\nOK	Cancel	Apply	Help](.pci-mpg24-manual-18/de95716c77129e77b74cc6e449178e4d7d140639d9ec45668d3b60ce84a6d22d.jpg)

# Video Proc Amp:

![ADLINK Hardware MPEG4 Device Properties\nVideo Setting Audio Setting Camera Control\nVideo Proc Amp Video Decoder Video Capture Video Preview\nBrightness 50\nContrast 37\nHue 0\nSaturation 41\nSharpness 14\nGamma\nWhite Balance\nBacklight Comp\nColorEnable Default Auto\nOK Cancel Apply Help](.pci-mpg24-manual-18/a1a2dbd9ae8e4d9e43b9243df4aea4df418d3734c19e66dd45caba099b5acb7d.jpg)

# Video Decoder

![ADLINK Hardware MPEG4 Device Properties\nVideo Setting	Audio Setting	Camera Control\nVideo Proc Amp	Video Decoder	Video Capture	Video Preview\nVideo Standard: NTSC_M\nSignal Detected: 0\nLines detected: 525\n✓ VCR Input\n✓ Output Enable\nOK	Cancel	Apply	Help](.pci-mpg24-manual-18/e41f55112f08df72aa8a0f9ea7bea0b891910da5648f36bba2b9379dd9d85dbb.jpg)

# Preview

![Preview.GRF - GraphEdit\nFile Edit View Graph Favorites Options Help\nAnalog Video In\nADLINK Bt878 Video Capture\nCapture\nPreview\nVBI\nInput\nVideo Renderer\n0: Video Composite In\n1: Video Composite In\n2: Video Composite In\n3: Video Composite In\n0: Video Decoder Out\nADLINK Bt878 Crossbar\n1: Audio Decoder Out\nReady NUM](.pci-mpg24-manual-18/8aaaa72306d66a7866d3eee2da19150c6a4d10a646eb9e709d114eb1e758236e.jpg)

# Capture

![This flowchart depicts a video capture pipeline with three distinct blocks connected in a left-to-right sequence:\n\n1.  **Source Block (Left):** An orange rectangular block labeled 'ADLINK Hardware MPEG4' with 'Device' below it. To the right of the main text are smaller labels: 'Video Capture' at the top and 'Video Preview' at the bottom.\n2.  **Processing Block (Middle):** A light blue rectangular block labeled 'AVI Mux' in the center. It has 'Input 01' at the top left and 'Input 02' at the bottom left. 'AVI Out' is located at the top right.\n3.  **Sink Block (Right):** A light blue rectangular block labeled '1.avi' in the center with 'in' at the top left.\n\n**Connections:**\n*   An arrow connects the right side of the orange block to the left side of the middle 'AVI Mux' block.\n*   An arrow connects the right side of the 'AVI Mux' block (specifically from 'AVI Out') to the left side of the '1.avi' block (specifically to 'in').](.pci-mpg24-manual-18/12aaef521ce115ed3f219829ca15214033c8d13954d73b8d4f255f6a50b99368.jpg)

# 1.4 Controlling Driver

# Preview

# ADLINK Bt878 Video Capture

The ADLINK Bt878 Video Capture Filter provides property pages and exposes COM interfaces to control video. Hence, an application has two ways to control video configurations: via property pages or via the COM interfaces.

# Use Property Pages

There are two embedded property pages in the driver. To show these property pages, use Windows API: OleCreatePropertyFrame.

Documentation on Displaying a Filter's Property Page can be found on Microsoft MSDN homepage.

Below is an example code for adding property pages:

```c
// pFilter points to the capture filter

ISpecifyPropertyPages *pSpecify;
HRESULT hr;
hr = pFilter-
>QueryInterface(IID_ISpecifyPropertyPages, (void **)&pSpecify);
if (SUCCEDED(hr))
{
FILTER_INFO FilterInfo;
pFilter->QueryFilterInfo(&FilterInfo);
FilterInfo.pGraph->Release();

CAUUID caGUID;
pSpecify->GetPages(&caGUID);
pSpecify->Release();
```

```txt
OleCreatePropertyFrame(
NULL,    // Parent window
0,    // x (Reserved)
0,    // y (Reserved)
FilterInfo.achName,    // Caption for the
dialog box
1,    // Number of filters
(IUnknown **)&m_pFilter,  // Pointer to the filter
caGUID.cElems,    // Number of property
pages
caGUID.pElems,    // Pointer to property
page CLSIDs
0,    // Locale identifier
0,    // Reserved
NULL    // Reserved
);
CoTaskMemFree(caGUID.pElems);
}
```

# Use COM interfaces

Use the methods of the IAMVideoProvAmp interface of standard DirectShow Interface to retrieve or set the qualities of an incoming video signal.

# ADLINK Bt878 Crossbar

The ADLink Bt878 Crossbar filter implements an IAMCrossbar interface. It routes signals from an analog or digital source to a video capture filter.

The routing definition of PCI-MPG24 card is shown in the following figure:

![This block diagram illustrates a video routing process involving an ADLink Bt878 Crossbar.\n\n**Inputs:**\nOn the left, two arrows point towards a large rectangular block:\n*   The top arrow is labeled **'Monitor Quad mode video'**.\n*   The bottom arrow is labeled **'Monitor Single channel video'**.\n\n**Central Block:**\nInside the rectangular block, the text is arranged in three sections:\n*   **Left Side (Inputs):** A list of four video inputs labeled:\n    *   **'0: Video Composite In'**\n    *   **'1: Video Composite In'**\n    *   **'2: Video Composite In'**\n    *   **'3: Video Composite In'**\n*   **Center:** The device name **'ADLink Bt878 Crossbar'**.\n*   **Right Side (Outputs):** Two outputs labeled:\n    *   **'0: Video Decoder Out'**\n    *   **'1: Audio Decoder Out'**](.pci-mpg24-manual-18/6aad2cad4cf8bad5be48b32847477159249304312e8039109e2f626a8210bf64.jpg)

Figure 1-1: ADLink Bt878 Crossbar

For single video port selection please refer to the Bt878 GPIO pin definition in chapter 2.1.

# Capture

# ADLINK Hardware MPEG4 Device

The ADLINK Hardware MPEG4 Device Filter provides property pages and exposes COM interfaces to control video. Hence, an application can have two ways to control video configurations: via the property pages or via the COM interfaces.

# Use Property Pages

There are three embedded property pages in the driver. To show these property pages, use Windows API: OleCreatePropertyFrame.

Documentation on Displaying a Filter's Property Page can be found on Microsoft MSDN homepage.

The example code for adding property pages is the same as that of the ADLINK Bt878 Video Capture.

# Use COM interfaces

It is standard practice to use the standard DirectShow interfaces defined for A/V capture filter and output pin to retrieve and set video configurations. However, due to a known issue in the ADLINK Hardware MPEG4 device driver, the programmer has to use a proprietary interface, IGOChip in addition to the standard interfaces. Details about the IGOChip interface and a sample code are provided in the DirectX Reference Manual.

# 2 DirectX Reference Manual

# 2.1 Preview

# GPIO Access

The GPIO provides a method to read board information, select input channel, and control digital inputs/digital outputs.

Sample:
```c
#define INSTANCE_DATA_OF_PROPERTY_PTR(x) (
    (PKSPROPERTY ((x)) ) + 1
#define INSTANCE_DATA_OF_PROPERTY_SIZE(x) (
    sizeof((x)) - sizeof (KSPROPERTY)
void GPIOWrite(IBaseFilter* pFilter,DWORD bit,DWORD value)
{
IKsPropertySet *pKs = NULL;
DWORD TypeSupport = 0;
KSPROPERTY_CUSTOMBT848_GPIO_S rc;
HRESULT hr;
ULONG ret=0;

if (pFilter->QueryInterface(IID_IKsPropertySet,
    (void **)&pKs) == S_OK)
{
hr = pKs-
>QuerySupported(PROPSETID_CUSTOMBT848,KSPROPERTY _CUSTOMBT848_GPIO,&TypeSupport);
if(TypeSupport & KSPROPERTY_SUPPORT_GET)
{
ZeroMemory(&rc,sizeof(rc));
rc.dwOperation=BT848_CUSTPROP_GPIO_SETGPDATABITS;
```

```c
rc.dwFromBit = bit;
rc.dwToBit = bit;
rc.dwValue = value;
rc.dwOffset = 0;
hr = pKs->Get(
PROPSETID_CUSTOMBT848, // identificador del driver
KSPROPERTY_CUSTOMBT848_GPIO,
INSTANCE_DATA_OF_PROPERTY_PTR(&rc),
INSTANCE_DATA_OF_PROPERTY_SIZE(rc),
&rc, // variable a rellenar con los datos
sizeof(rc),
&ret);
}
pKs->Release();
}
}

DWORD GPIORead(IBaseFilter* pFilter,DWORD bit)
{
IKsPropertySet *pKs = NULL;
DWORD TypeSupport = 0;
KSPROPERTY_CUSTOMBT848_GPIO_S rc;
HRESULT hr;
ULONG ret=0;
DWORD ReturnValue=0;

if (pFilter->QueryInterface(IID_IKsPropertySet,
(void **) &pKs) == S_OK)
{
hr = pKs-
>QuerySupported(PROPSETID_CUSTOMBT848,KSPROPERTY
_CUSTOMBT848_GPIO,&TypeSupport);
if(TypeSupport & KSPROPERTY_SUPPORT_GET)
```

```txt
{
    ZeroMemory(&rc,sizeof(rc));
    rc.dwOperation = BT848_CUSTPROP_GPIO_GETGPDATABITS;
    rc.dwFromBit = bit;
    rc.dwToBit = bit;
    rc.dwOffset = 0;
    hr = pKs->Get(
    PROPSETID_CUSTOMBT848, // identificador del driver
    KSPROPERTY_CUSTOMBT848_GPIO,
    INSTANCE_DATA_OF_PROPERTY_PTR(&rc),
    INSTANCE_DATA_OF_PROPERTY_SIZE(rc),
    &rc, // variable a rellenar con los datos
    sizeof(rc),
    &ret);
   ReturnValue = rc.dwValue;
    }
    pKs->Release();
    }
    returnReturnValue;
}
```

Bt878 GPIO PIN Definition

<table><tr><td>Pin</td><td>Type</td><td>Function</td></tr><tr><td>GPIO0</td><td>Output</td><td>--</td></tr><tr><td>GPIO1</td><td>Output</td><td>Set watchdog timer enable / disableSet “1” =&gt; disable (default),set &quot;0&quot; =&gt; enable</td></tr><tr><td>GPIO2</td><td>Output</td><td rowspan="2">Control the watch dog timer count down time</td></tr><tr><td>GPIO3</td><td>Output</td></tr><tr><td>GPIO4</td><td>Input</td><td>Card ID bit 0 (setting by dip switch)</td></tr><tr><td>GPIO5</td><td>Input</td><td>Card ID bit 1 (setting by dip switch)</td></tr><tr><td>GPIO6</td><td>Input</td><td>Card ID bit 2 (setting by dip switch)</td></tr><tr><td>GPIO7</td><td>Input</td><td>--</td></tr><tr><td>GPIO8</td><td>Input</td><td>Port 1 DI</td></tr><tr><td>GPIO9</td><td>Input</td><td>Port 2 DI</td></tr><tr><td>GPIO10</td><td>Input</td><td>Port 3 DI</td></tr><tr><td>GPIO11</td><td>Input</td><td>Port 4 DI</td></tr><tr><td>GPIO12</td><td>Output</td><td>Port 1 DO</td></tr><tr><td>GPIO13</td><td>Output</td><td>Port 2 DO</td></tr><tr><td>GPIO14</td><td>Output</td><td>Port 3 DO</td></tr><tr><td>GPIO15</td><td>Output</td><td>Port 4 DO</td></tr><tr><td>GPIO16</td><td>Output</td><td>Monitor single channel, data enable (low active) (E#)</td></tr><tr><td>GPIO17</td><td>Output</td><td>Monitor single channel, data 0 (S0)</td></tr><tr><td>GPIO18</td><td>Output</td><td>Monitor single channel, data 1 (S1)</td></tr><tr><td>GPIO19</td><td>Output</td><td>Monitor single channel, data 2 (S2)</td></tr></table>

Table 2-1: Bt878 GPIO PIN Definition

![| INPUTS | channel ON | Channel 0 | Channel 1 | Channel 2 | Channel 3 |\n|---|---|---|---|---|---|\n| E | | | | | |\n| S₂ | | | | | |\n| S₁ | | | | | |\n| S₀ | | | | | |\n| L | Y₀ - Z | | | | |\n| L | Y₁ - Z | | | | |\n| L | Y₂ - Z | | | | |\n| L | Y₃ - Z | | | | |\n| L | Y₄ - Z | | | | |\n| L | Y₅ - Z | | | | |\n| L | Y₆ - Z | | | | |\n| L | Y₇ - Z | | | | |\n| H | none | Quad Mode | X | X | X |\nL H L H L H\nL H H H\nH X X X](.pci-mpg24-manual-18/71082a0c85eb26fe4a2fb64aae74eb998472d9697b6490241ea3eca5cec25d6f.jpg)

Table 2-2: Function Table

# EEPROM Access

ADLink Bt878 Video Capture provides a method for accessing the I2C register. The interface can store a few data, for example, board identification.

# Sample

```c
#define INSTANCE_DATA_OF_PROPERTY_PTR(x) (PKSPROPERTY ((x))) + 1 )
```

```c
#define INSTANCE_DATA_OF_PROPERTY_SIZE(x) (
    sizeof((x)) - sizeof(KSPROPERTY)
)

BYTE EEPROMRead(IBaseFilter *pFilter, BYTE offset)
{
IKsPropertySet *pKs = NULL;
DWORD TypeSupport = 0;
KSPROPERTY_CUSTOMBT848_I2C_S I2C;
BYTE uAddress;
HRESULT hr;
ULONG ret=0;
```

```c
if((hr=pFilter->QueryInterface(IID_IKsPropertySet, (void **)&pKs)) == S_OK)
{
hr = pKs-
>QuerySupported(PROPSETID_CUSTOMBT848,KSPROPERTY _CUSTOMBT848_I2C,&TypeSupport);
if(TypeSupport & KSPROPERTY_SUPPORT_GET)
{
uAddress = 0xa0;
ZeroMemory(&I2C,sizeof(I2C));
I2C.bDontWaitACK = true;
I2C.dwOperation = BT848_CUSTPROP_I2C_SETFREQ;
I2C.dwFreq = 100000;
hr = pKs->Get(
PROPSETID_CUSTOMBT848,
KSPROPERTY_CUSTOMBT848_I2C,
INSTANCE_DATA_OF_PROPERTY_PTR(&I2C),
INSTANCE_DATA_OF_PROPERTY_SIZE(I2C),
&I2C,
sizeof(I2C),
&ret);
I2C.dwOperation=BT848_CUSTPROP_I2C_R3;
I2C.ucAddress=uAddress;
I2C.ucInBuf[0] = offset;
I2C.dwOutLen = 0;
I2C.dwInLen = 1;
I2C.bDontWaitACK = TRUE;
hr = pKs->Get(
PROPSETID_CUSTOMBT848,
KSPROPERTY_CUSTOMBT848_I2C,
INSTANCE_DATA_OF_PROPERTY_PTR(&I2C),
INSTANCE_DATA_OF_PROPERTY_SIZE(I2C),
&I2C,
```

```c
sizeof(I2C), &ret);
}
pKs->Release();
}
return I2C.ucInBuf[1];
}
```

# 2.2 Capture

WDM Streaming Capture Filter

<table><tr><td>Filter Interfaces</td><td>Microsoft DirectShow Interfaces:IAMAnalogVideoDecoder, IAMCameraControl,IAMDroppedFrames, IAMVideoProcAmp,IBaseFilter, IKsPropertySet, ISpecifyPropertyPagesCapture Interfaces:IGOChip, IGOChipConfig, IGOInfo, IAccess-Func, IAdvanced</td></tr><tr><td>Video Capture Pin Supported Media Types</td><td>DIVX_MPEG4, MICROSOFT_MPEG4,MPEG2, MPEG1, H263, MJPG</td></tr><tr><td>Video Capture Pin Interfaces</td><td>Microsoft DirectShow Interfaces:IAMStreamConfig, IKsPin, IKsPropertySet, IPin</td></tr><tr><td>Video Preview Pin Supported Media Types</td><td>DIVX_MPEG4, MICROSOFT_MPEG4,MPEG2, MPEG1, H263, MJPG</td></tr><tr><td>Video Preview Pin Interfaces</td><td>Microsoft DirectShow Interfaces:IAMStreamConfig, IKsPin, IKsPropertySet, IPin</td></tr><tr><td>Audio Capture Pin Supported Media Types</td><td>MEDIATYPE_Audio, MEDIASUBTYPE_PCM,MEDIASUBTYPE_ADPCM,MEDIASUBTYPE_IMA_ADPCM</td></tr><tr><td>Audio Capture Pin Interfaces</td><td>Microsoft DirectShow Interfaces:IAMBufferNegotiation, IAMStreamConfig, IAMStreamControl, IKsPin, IKsPropertySet, IStreamBuilder, IMediaSeeking, IPin,IQualityControl</td></tr><tr><td>Filter CLSID</td><td>Not applicable.</td></tr><tr><td>Property Page CLSID</td><td>Video Control Property Page:35D3656A-6C20-46B0-B44A-DC8E861F1205Audio Control Property Page:8ED37ED7-477B-4764-B72E-DFC2D1899C6C</td></tr><tr><td>Merit</td><td>MERIT_DO_NOT_USE</td></tr><tr><td>Filter Category</td><td>AM_KSCATEGORY_CAPTURECLSID_VideoInputDeviceCategoryCLSID_AudioInputDeviceCategory</td></tr></table>

Table 2-3: WDM Streaming Capture Filter

For Microsoft DirectShow interfaces, follow the links for online reference. Alternatively, please visit http://msdn.microsoft.com/library/ and from the left panel navigation, select Graphics and Multimedia -> DirectX -> SDK Documentation -> DirectX 9.0 (C++) -> DirectShow -> DirectShow Reference -> Interfaces for a complete list of Microsoft DirectShow filter interfaces references.

Media Types
DIVX\_MPEG4

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>‘D’, ‘X’, ‘5’, ‘0’, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71</td></tr><tr><td>Format Type</td><td>FORMAT_Videoinfo</td></tr></table>

Table 2-4: DIVX\_MPEG4

MICROSOFT\_MPEG4

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>‘M’, ‘P’, ‘4’, ‘S’, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71</td></tr><tr><td>Format Type</td><td>FORMAT_Videoinfo</td></tr></table>

Table 2-5: MICROSOFT\_MPEG4

MPEG2

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>MEDIASUBTYPE_MPEG2_VIDEO</td></tr><tr><td>Format Type</td><td>FORMAT_MPEG2Video</td></tr></table>

Table 2-6: MPEG2

# MPEG1

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>MEDIASUBTYPE_MPEG1Payload</td></tr><tr><td>Format Type</td><td>FORMAT_MPEGVideo</td></tr></table>

Table 2-7: MPEG1

# H263

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>‘W’, ‘M’, ‘P’, 0x3, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71</td></tr><tr><td>Format Type</td><td>FORMAT_Videoinfo</td></tr></table>

Table 2-8: H263

# MJPG

<table><tr><td>Major type</td><td>MEDIATYPE_Video</td></tr><tr><td>Subtype</td><td>‘M’, ‘J’, ‘P’, ‘G’, 0x0000, 0x0010, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71</td></tr><tr><td>Format Type</td><td>FORMAT_Videoinfo</td></tr></table>

Table 2-9: MJPG

# Data Structures

# TCFG\_HEADER Structure

The TCFGHEADER structure will be used in the following structures: TCFGSYSTEM, TCFGSTREAM, TCFGFRAMER-ATE, TCFGRESOLUTION, TCFGBRCTRL, and TCFGMISC. It provides general information about the structure it resides in.

# Syntax

```txt
typedef struct
{
char name[MAX_NAME];
char desc[MAX_DESC];
```

```txt
unsigned long flags;
unsigned long size;
} TCFG_HEADER;
```

# Members

# name

The name of the configuration. It uses a string less than MAX\_NAME (64) characters included in quotes. For example: "MPEG2, IPB" for a stream setting and "4M" for a bitrate setting.

# desc

The description of the configuration. Use a string of less than MAX\_DESC (256) characters included in quotes.

# flags

The flags member provides information on what fields are provided in the structure where the TCFG\_HEADER is located. Each bit in flags corresponds to one field. Each TCFGxxxx structure (except for TCFGSYSTEM) has a corresponding FLAGS\_xxxx enumeration that shows the relationship between field and bit position. The enumeration also has a FLAGS\_xxxx\_MANDETORY field indicating which fields have to be provided. Set a bit as 1 if the corresponding field value is provided. Take the TCFGFRAMERATE structure as an example, if only the mandatory fields are provided, which are frame rate and tv\_standard, then the flags should be 0x9 (1001).

# size

The size of the structure is where the TCFGHEADER is located. For example, in a TCFGSTREAM structure, the size in TCFG\_HEADER is the size of TCFGSTREAM.

# TCFGSYSTEM Structure

The TCFGSYSTEM structure describes settings of the sensor (image sensor or video decoder) being used to capture video and some general settings of the MPEG4 chip.

Syntax
```c
typedef struct
{
TCFG_HEADER header;

TV_STANDARDtv_standard;
long framerate;
long sensor_h;
long sensor_v;
char format;
char pformat;

char sensor_656_mode;
char valid_enable;
char valid_polar;
char href_polar;
char vref_polar;
char field_id_polar;
char sensor_bit_width;
char hv_resync_enable;

long reserved;
} TCFGSYSTEM;
```

# Members

# header

Header information about the structure.

# tv\_standard

tv\_standard can only be set as TVStandard\_NTSC\_Mask or TVStandard\_PAL\_Mask.

# framerate

The real frame rate will be the value of frame rate divided by 1001. For example: if frame rate = 30000, then the real frame rate = 30000 / 1001 = 29.97.

# sensor\_h

The horizontal resolution of the sensor source input, in pixels.

# sensor\_v

The vertical resolution of the sensor source input, in pixels.

sensor\_h and sensor\_v constitute the source video size.

The common source video sizes are:

▶ 320 \* 240 (QVGA)
▶ 352 \* 288 (CIF)
▶ 640 \* 480 (VGA)
▶ 720 \* 480 (Full D1, NTSC)
▶ 720 \* 576 (Full D1, PAL)

# Format

Sensor pixel format:

▶ 0: YUV progressive
▶ 1: YUV interlace
▶ 2: RGB Bayer

# pformat

Sensor pixel format. Valid only if format is RGB Bayer.

▶ 2: RGB-Bayer in GB-format
▶ 3: RGB-Bayer in GR-format
▶ 4: RGB-Bayer in BG-format
▶ 5: RGB-Bayer in RG-format

# sensor\_656\_mode

Specifies if the sensor input is in 656 mode.

▶ 0: The sensor is not in 656 mode
▶ 1: The sensor is in 656 mode

# valid\_enable

If valid\_enable is set, then input image data is valid only if valid signal is active.

▶ 0: Disable valid signal.
▶ 1: Enable valid signal.

# valid\_polar

Specifies the polarity of the valid signal provided by the sensor or emulator.

▶ 0: Vvalid signal polarity will be active-high
▶ 1: Valid signal polarity will be active-low

# href\_polar

Specifies the polarity of the horizontal reference signal provided by the sensor or emulator. Only valid in non-656 mode.

▶ 0: H reference polarity will be active-high
▶ 1: H reference polarity will be active-low

# vref\_polar

Specifies the polarity of the vertical reference signal provided by the sensor or emulator. Only valid in non-656 mode.

▶ 0: V reference polarity will be active-high
▶ 1: V reference polarity will be active-low

# field\_id\_polar

Specifies the polarity of the field ID.

▶ 0: Top field ID = 0; Bottom field ID = 1
▶ 1: Top field ID = 1; Bottom field ID = 0

# sensor\_bit\_width

The bit width of the image data provided by sensor or emulator.

▶ 0: Data is 8-bit wide
▶ 1: Data is 10-bit wide

# hv\_resync\_enable

By enabling this option, the video compression process pauses when the input video signal is temporarily out-of-sync. It will resume and re-synchronize to the video input signal when regular synchronization signals are recovered. Video signals from some image sensors have constantly changing horizontal and vertical periods. This option needs to be disabled when working with such sensors.

# reserved

Reserved for future use.

# TCFGSTREAM Structure

The TCFGSTREAM structure describes settings of the output video stream of the MPEG4 chip.

# Syntax

```c
typedef struct
{
TCFG_HEADER header;

EVideoFormat compress_mode;
ESequenceMode sequence;

unsigned char gop_mode;
unsigned char gop_size;
unsigned char mpeg4_mode;
unsigned char DVD_compliant;
unsigned char deinterlace_mode;

unsigned char search_range;
unsigned char gop_head_enable;
unsigned char seq_head_enable;
unsigned char aspect_ratio;
long reserved;
} TCFGSTREAM;
```

# Members

# header

Header information about the structure.

# compress\_mode

The stream's compression mode. Refer to Eumeration: EVideoFormat for details.

▶ MPEG1: 0x00
▶ MPEG2: 0x01
▶ H263: 0x03
▶ MPEG4: 0x04
▶ MOTIONJPEG: 0x08

# sequence

The sequence mode of the encoding stream. There are three types of frames used in a stream sequence: Intra frames (I), Predictive frames (P), and Bi-directional frames (B). This member indicates the types of frames being used in a stream sequence. Refer to Enumeration: ESequenceMode for details.

▶ IONLY: Only I-frames in the stream sequence (1)
▶ IPONLY: Only I and P frames in the stream sequence (2)
▶ IPB: All types of frames (I, P and B) in the stream sequence (3)

# gop\_mode

The GOP (Group Of Picture) mode of the encoding stream sequence. Encoding DivX format MPEG4 stream requires closed GOP mode.

▶ GOP\_MODE\_OPEN: 0
▶ GOP\_MODE\_CLOSE: 1

# gop\_size

The Group of Pictures (GOP) size. This value is the key frame interval. Note that in the IPB sequence mode, the value must be a multiple of 3. If the stream is preferred to be DVD compliant, the GOP size must be less than or equal to 18.

# mpeg4\_mode

MPEG4 stream mode. Valid only when compress\_mode is four.

Refer to Enumeration: MPEG4\_MODE for details.

▶ WIS\_MPEG4: 0
▶ DIVX\_MPEG4: 1
▶ MICROSOFT\_MPEG4: 2

# DVD\_compliant

Specifies if the stream is to be DVD compliant. Valid only when the compression mode is MPEG2.

▶ 0: Disable DVD\_compliant
▶ 1: Enable DVD\_compliant

# deinterlace\_mode

▶ 0: Use one field only
▶ 1: Use MPEG4 deinterlace algorithm
▶ 2: Interlace coding is used; no de-interlacing performed

# search\_range

The searching range for motion vectors. Typical values are 16, 32, 64, or 128. Microsoft format MPEG4 stream requires that the search range be 64. H.263 format stream requires the search range to be 32.

# gop\_head\_enable

Only encoding the Microsoft format MPEG4 stream requires disabling the GOP head. All other format streams require enabling the GOP head.

▶ 0: Disable GOP head
▶ 1: Enable GOP head

# seq\_head\_enable

Only encoding Microsoft format MPEG4 stream requires disabling the sequence head. All other format streams require enabling sequence head.

▶ 0: Disable sequence head
▶ 1: Enable sequence head

# aspect\_ratio

The ratio between the width and the height of the picture. This information is included in the sequence header.

▶ 1:1:1
▶ 2:4:3
▶ 3:16:9

# reserved

Reserved for future use.

# TCFGFRAMERATE Structure

The TCFGFRAMERATE structure describes frame rate related settings of the output video stream of MPEG4 chip.

# Syntax

```txt
typedef struct
{
TCFG_HEADER header;

TV_STANDARD tv_standard;
unsigned longframe_rate;
unsigned long drop_frame;
unsigned charivtc_enable;
long reserved;
```

} TCFGFRAMERATE;

# Members

# header

Header information about the structure

# tv\_standard

tv\_standard can only be set as TVStandard\_NTSC\_Mask or TVStandard\_PAL\_Mask.

# frame\_rate

Output frame rate

# drop\_frame

▶ 0: Keep original frame rate. No frames dropped
▶ 1: Keep 1/2 original frame rate
▶ 2: Keep 1/3 original frame rate
▶ n: Keep 1/(n+1) original frame rate

# ivtc\_enable

IVTC (InVerse TeleCine) is a process where video editing tools reverse the Telecine process. Basically IVTC brings back movie's original frame rate from NTSC's 29.97fps to 24fps.

▶ 0: Disable IVTC
▶ 1: Enable IVTC

# reserved

Reserved for future use

# TCFGRESOLUTION Structure

The TCFGRESOLUTION structure describes the resolution of an encoded stream.

Syntax
```txt
typedef struct
{
TCFG_HEADER header;
TV_STANDARD tv_standard;

unsigned long width;
unsigned long height;

unsigned char h_sub_window;
unsigned char v_sub_window;
unsigned long h_sub_offset;
unsigned long v_sub_offset;

unsigned char h_scale_enb;
unsigned char v_scale_enb;
unsigned char sub_sample;

unsigned long max_bitrate;
unsigned long min_bitrate;

long reserved;
} TCFGRESOLUTION;
```

# Members

# header

Header information about the structure.

# tv\_standard

tv\_standard can only be set as TVStandard\_NTSC\_Mask or TVStandard\_PAL\_Mask.

# width

The desired output stream resolution: horizontal size.

# height

The desired output stream resolution: vertical size.

# h\_sub\_window

Specify if performing sub-window (cropping) in the horizontal direction.

▶ 0: Disable sub-window

▶ 1: Enable sub-window

# v\_sub\_window

Specify if performing sub-window (cropping) in the vertical direction.

▶ 0: Disable sub-window

▶ 1: Enable sub-window

# h\_sub\_offset

If h\_sub\_window is performed, this parameter specifies a relative offset between the leftmost pixel of the output stream and the leftmost pixel of the source stream, in pixels.

# v\_sub\_offset

If v\_sub\_window is performed, this parameter specifies a relative offset between the topmost pixel of the output stream and the topmost pixel of the source stream, in pixels.

# h\_scale\_enb

Specify if it will perform $\frac{1}{2}$ scaling in the horizontal direction.

▶ 0: Disable scaling
▶ 1: Enable scaling

# v\_scale\_enb

Specify if it will perform $\frac{1}{2}$ scaling in the vertical direction.

▶ 0: Disable scaling
▶ 1: Enable scaling

# sub\_sample

Specify if it is performing sub\_sampling. Sub-sampling will perform $\frac{1}{2}$ scaling down to the stream in both horizontal and vertical directions.

▶ 0: Disable sub\_sampling
▶ 1: Enable sub\_sampling

# Note:

Sub-sampling, sub-windowing, and scaling are three different methods provided by the chip to reduce the source stream size, and performed in the sequence above. If sub-sampling and sub-windowing are both enabled, the sub-offset for sub-window will be relative to the leftmost pixel of the stream AFTER sub-sampling is performed.

# max\_bitrate

The maximum bit rate allowed for this resolution.

# min\_bitrate

The minimum bit rate allowed for this resolution.

# reserved

Reserved for future use.

# TCFGBRCTRL Structure

The TCFGBRCTRL structure describes the bit-rate control setting of encoded stream.

Syntax
```c
typedef struct
{
TCFG_HEADER header;

unsigned long target_bitrate;
unsigned long peak_bitrate;
unsigned long vbv_buffer;
unsigned char converge_speed;
unsigned char lambda;

unsigned long Q;
unsigned char IQ;
unsigned char PQ;
unsigned char BQ;

long reserved;
} TCFGBRCTRL;
```

# Members

# header

Header information about the structure.

# target\_bitrate

The desired average target bit rate of the encoded stream, in bits per second (bps).

▶ 0: If Q>0, apply the variable bitrate control (VBR) using the value of Q. If Q=0, no bitrate control algorithm is applied. Bitrate will be determined by values of IQ, PQ, and BQ provided by the user.

▶ >0: Apply constant bitrate control (CBR) using the value of target\_bitrate.

# peak\_bitrate

The highest bit rate allowed in the encoded stream, in bits per second (bps). This parameter is only valid when applying constant bitrate control (both Q and target\_bitrate are greater than 0).

# vbv\_buffer

Specifies VBV buffer size. Video Buffering Verifier (VBV) is a hypothetical decoder that is conceptually connected to the output of the encoder. Its purpose is to provide a constraint on the variability of the data rate that an encoder or editing process may produce.

# converge\_speed

Specifies the converging speed of bit rate control process. Its value range is [0, 100]. The larger the value, the faster the converging speed.

# lambda

The factor determining stream quality. Its value range is [0, 100]. The larger the value, the smoother the stream however, the quality of each frame decreases. This is inversely true for smaller values. However, due to frame drops, the entire video stream would appear “jumpy”.

# Q

Initial quantizer. This value is divided by four.

▶ 0: If target\_bitrate>0, apply constant bitrate control. The initial quantizer value is calculated. If target\_bitrate=0, no bitrate control algorithm is applied. Use IQ, PQ, and BQ values provided by the user to determine the bitrate value.
▶ >0: If target\_bitrate is set to 0, apply VBR (variable bitrate) using the value of Q. If target\_bitrate is greater than 0, apply CBR (constant bitrate) using the value of target\_bitrate.

# IQ

The fixed quantized scale for I-frames during the entire encoding session. This member is valid only when Q and target\_bitrate are both set to '0'.

# PQ

The fixed quantized scale for P-frames during the entire encoding session. This member is valid only when Q and target\_bitrate are both set to '0'.

# BQ

The fixed quantized scale for B-frames during the entire encoding session. This member is valid only when Q and target\_bitrate are both set to '0'.

# reserved

Reserved for future use.

# TCFGMISC Structure

The TCFGSTREAM structure describes miscellaneous settings of the output video stream of MPEG4 chip.

# Syntax

```c
typedef struct
{
TCFG_HEADER header;

unsigned char av_sync_enable;
unsigned char iip_enable;
unsigned char vbi_enable;
unsigned char four_channel_enable;

FilterMode h_filter_mode;
FilterMode v_filter_mode;
char filter_nAX;
char filter_nBX;
char filter_nCX;
char filter_nAY;
char filter_nBY;
char filter_nCY;

long reserved;
} TCFGMISC;
```

# Members

# Header

Header information about the structure.

# av\_sync\_enable

▶ 0: Disable WIS Audio/Video Synchronization algorithm
▶ 1: Enable WIS Audio/Video Synchronization algorithm

# iip\_enable

Specifies if enabling Input Image Processing. Only valid when sensor pixel format is RGB Bayer.

▶ 0: Disable IIP
▶ 1: Enable IIP

# vbi\_enable

▶ 0: Disable VBI
▶ 1: Enable VBI

# four\_channel\_enable

If four\_channel\_enable is set, each frame of the encoded stream will be divided into four quadrants. Motion search will be confined in each quadrant and will not be performed in other quadrants.

▶ 0: Disable four channel feature
▶ 1: Enable four channel feature

# h\_filter\_mode

The mode of pre-filtering in a horizontal direction.

▶ 0: No pre-filtering in the horizontal direction before encoding
▶ 1: Median filter applied in the horizontal direction before encoding
▶ 2: Linear filter applied in the horizontal direction before encoding

# v\_filter\_mode

The mode of pre-filtering in a vertical direction.

▶ 0: No pre-filtering in the vertical direction before encoding
▶ 1: Median filter applied in the vertical direction before encoding
▶ 2: Linear filter applied in the vertical direction before encoding

filter\_nAX

filter\_nBX

filter\_nCX

The coefficients of linear filter in horizontal direction. Valid only if the h\_filter\_mode equals to two.

filter\_nAX, filter\_nBX, and filter\_nCX correspond to precedent pixel, current pixel, and following pixel respectively. These three coefficients are all 5-bit values. filter\_nBX is an unsigned value. filter\_nAX and filter\_nCX are signed values, with the highest bit indicating the sign and the rest four bits indicating the absolute value.

Typically, if filter\_nAX and filter\_nCX are positive, the filter will be a low-pass filter. Otherwise, if filter\_nAX and filter\_nCX are negative, the filter is a high-pass filter. A typical requirement for the coefficients is:

filter\_nAX + filter\_nBX + filter\_nCX = 16.

filter\_nAY

filter\_nBY

filter\_nCY

The coefficients of linear filter in vertical direction. Valid only if v\_filter\_mode is 2.

filter\_nAY, filter\_nBY and filter\_nCY correspond to precedent pixel, current pixel, and following pixel respectively. These three coefficients are all 5-bit values. filter\_nBY is an unsigned value. filter\_nAY and filter\_nCY are signed values, with the highest bit indicating the sign and the remaining four bits indi-

cating the absolute value.

Typically, if filter\_nAY and filter\_nCY are positive, the filter will be a low-pass filter. If filter\_nAY and filter\_nCY are negative, the filter is a high-pass filter. A typical requirement for the coefficients is:

filter\_nAY + filter\_nBY + filter\_nCY = 16.

# reserved

Reserved for future use.

# TCFGVIDEO Structure

The TCFGVIDEO structure describes a complete video setting, including miscellaneous setting, stream setting, resolution setting, frame rate setting, and bitrate control setting.

# Syntax

```c
typedef struct
{
TCFGMISC misccfg;
TCFGSTREAM strcfg;
TCFGRESOLUTION rescfg;
TCFGFRAMERATE fpscfg;
TCFGBRCTRL ctlcfg;
} TCFGVIDEO;
```

# Members

# misccfg

A TCFGMISC structure for miscellaneous settings.

# strcfg

A TCFGSTREAM structure for stream settings.

# rescfg

A TCFGRESOLUTION structure for resolution settings.

# fpscfg

A TCFGFRAMERATE structure for frame rate settings.

# ctlcfg

A TCFGBRCTRL structure for bitrate control settings.

# TCFGVIDEOEX Structure

The TCFGVIDEOEX structure describes both system and video settings.

# Syntax

```txt
typedef struct
{
TCFGSYSTEM syscfg;
TCFGMISC misccfg;
TCFGSTREAM strcfg;
TCFGRESOLUTION rescfg;
TCFGFRAMERATE fpscfg;
TCFGBRCTRL ctlcfg;
} TCFGVIDEOEX;
```

# Members

# syscfg

A TCFGSYSTEM structure for system settings.

# misccfg

A TCFGMISC structure for miscellaneous settings.

# strcfg

A TCFGSTREAM structure for stream settings.

# rescfg

A TCFGRESOLUTION structure for resolution settings.

# fpscfg

A TCFGFRAMERATE structure for frame rate settings.

# ctlcfg

A TCFGBRCTRL structure for bit rate control settings.

# TCFG\_FORMAT\_EXTENSION Structure

An extension to be appended to format information that will be set to video pin.

# Syntax

```txt
typedef struct
{
TCFGSTREAM strcfg;
TCFGFRAMERATE fpscfg;
TCFGRESOLUTION rescfg;
TCFGBRCTRL ctlcfg;
} TCFG_FORMAT_EXTENSION;
```

# Members

# strcfg

A TCFGSTREAM structure for stream settings.

# fpscfg

A TCFGFRAMERATE structure for frame rate settings.

# rescfg

A TCFGRESOLUTION structure for resolution settings.

# ctlcfg

A TCFGBRCTRL structure for bitrate control settings.

# \_VIDEO\_CAPABILITIES Structure

# Syntax

```c
typedef struct
{
    unsigned long _num_of_system_configs;
    TCFGSYSTEM_system _configs[MAX_SYSTEM_CONFIG];

    unsigned long _num_of_stream_configs;
    TCFGSTREAM _stream_configs[MAX_STREAM_CONFIG];

    unsigned long _num_of_resolution_configs;
    TCFGRESOLUTION _resolution_configs[MAX_RESOLUTION_CONFIG];

    unsigned long _num_of_framerate_configs;
```

```c
TCFGFRAMERATE
    _framerate_configs[MAX_FRAMERATE_CONFIG];

unsigned long    _num_of_associations;
TCFGASSOCIATION    _associations[MAX_ASSOCIATION];

unsigned long    _num_of_configurations;
TVCFG_ENTRY*    _configurations;
} _VIDEO_CAPABILITIES;
```

# Members

# \_num\_of\_system\_configs

The count of all system configurations.

# \_system\_configs

An array of TCFGSYSTEM structures to hold all system configurations.

# \_num\_of\_stream\_configs

The count of all stream configurations.

# \_stream\_configs

An array of TCFGSTREAM structures to hold all stream configurations.

# \_num\_of\_resolution\_configs

The count of all resolution configurations.

# \_resolution\_configs

An array of TCFGRESOLUTION structures to hold all resolu-

tion configurations.

# \_num\_of\_framerate\_configs

The count of all frame rate configurations.

# \_framerate\_configs

An array of TCFGFRAMERATE structures to hold all frame rate configurations.

# \_num\_of\_associations

The count of all associations.

# \_associations

An array of TCFGASSOCIATION structures to hold all associations.

# \_num\_of\_configurations

The count of all video configuration entries.

# \_configurations

A pointer to TVCFG\_ENTRY structures.

# TCFGASSOCIATION Structure

The TCFGASSOCIATION structure allows users to define relationship between any two types of settings from system setting, stream setting, resolution setting, frame rate setting, and bitrate control setting, if any.

Syntax
```c
typedef struct
{
Enum ASSOCIATION_TYPE_master_type;
unsigned long _master_id;
Enum ASSOCIATION_TYPE_slave_type;
unsigned long _slave_id;
unsigned char _associate_type;
} TCFGASSOCIATION;
```

# Members

\_master\_type

Type of master video setting.

\_master\_id

ID of the specific master setting.

\_slave\_type

Type of slave video setting.

\_slave\_id

ID of the specific slave setting.

# \_associate\_type

Type of this association. Refer to the Enumeration: ASSOCIATION\_TYPE.

# TVCFG\_ENTRY Structure

The TVCFG\_ENTRY structure describes one entry for video configuration.

# Syntax

```c
typedef struct
{
    unsigned long stream_index;
    unsigned long resolution_index;
    unsigned long framerate_index;
} TVCFG_ENTRY;
```

# Members

stream\_index

Index of stream configuration.

# resolution\_index

Index of resolution configuration.

# framerate\_index

Index of frame rate configuration.

# AUDIO\_CONFIG Structure

# Syntax

```c
typedef struct _AUDIO_CONFIG
{
    unsigned long Format;
    unsigned long SampleRate;
    unsigned long Channels;
    unsigned long SampleBits;

    unsigned short BlockAlign;
    unsigned long AvgBytesPerSec;
    unsigned short SamplesPerBlock;
    unsigned short ExtSize;
} AUDIO_CONFIG;
```

# Members

# sormat

Audio format. Possible values are included in the Enumeration: AUDIO\_FORMAT.

# sampleRate

Audio sample rate, in byte. Possible values are 44100, 48000, etc for PCM, 48000 for ADPCM.

# channels

Audio channels. Possible values are 1 for Mono and 2 for Stereo.

# SampleBits

Audio sample bits. Possible values are 8 bits and 16 bits for PCM, 4 bits for ADPCM.

# STATISTIC Structure

# Syntax

```c
typedef struct _STATISTIC
{
UINT32 VideoByte;
UINT32 FrameCount;
} STATISTIC;
```

# Members

# VideoByte

Total video bytes obtained since starting capturing.

# FrameCount

Total video frames obtained since starting capturing.

# REVISION\_INFO Structure

# Syntax

```c
typedef struct {
int DriverMajor;
int DriverMinor;
int BoardRevision;
char BoardName[MAX_NAME];
int BoardCapability;
int MaxBandWidth;
int SourceWidth;
int SourceHeight;
} REVISION_INFO;
```

# Members

# DriverMajor

Major revision number of driver.

# DriverMinor

Minor revision number of driver.

# BoardRevision

Revision number of reference board.

# BoardName

Name of reference board.

# BoardCapability

An integer with each bit representing one kind of capability of board, using values in Enumeration: BOARD\_CAP.

# MaxBandWidth

Reserved for future use.

# SourceWidth

Width of source video.

# SourceHeight

Height of source video.

# Enumerations

# EVideoFormat Enumeration

Syntax
```c
typedef enum
{
MPEG1 = 0x00,
MPEG2 = 0x01,
H261 = 0x02,
H263 = 0x03,
MPEG4 = 0x04,
MPEG4XGO = 0x05,
MPEG2X4 = 0x06,
MOTIONJPEG = 0x08,
DV = 0x09,
H26L = 0x20,
GO = 0x40
} EVideoFormat;
```

# ESequenceMode Enumeration

Syntax
```txt
typedef enum
{
    IONLY = 1,
    IPONLY = 2,
    IPB = 3,
    IPBDROP = 4
} ESequenceMode;
```

# TV\_STANDARD Enumeration

# Syntax

```c
typedef enum
{
    TVStandard_None= 0x00000000,
    TVStandard_NTSC_M= 0x00000001,
    TVStandard_NTSC_M_J= 0x00000002,
    TVStandard_NTSC_433= 0x00000004,

    TVStandard_PAL_B= 0x00000010,
    TVStandard_PAL_D= 0x00000020,
    TVStandard_PAL_G= 0x00000040,
    TVStandard_PAL_H= 0x00000080,
    TVStandard_PAL_I= 0x00000100,
    TVStandard_PAL_M= 0x00000200,
    TVStandard_PAL_N= 0x00000400,

    TVStandard_PAL_60= 0x00000800,

    TVStandard_SECAM_B= 0x00001000,
    TVStandard_SECAM_D= 0x00002000,
    TVStandard_SECAM_G= 0x00004000,
    TVStandard_SECAM_H= 0x00008000,
    TVStandard_SECAM_K= 0x00010000,
    TVStandard_SECAM_K1= 0x00020000,
    TVStandard_SECAM_L= 0x00040000,
    TVStandard_SECAM_L1= 0x00080000
} TV_STANDARD;
```

FilterMode Enumeration
Syntax
```c
typedef enum
{
GO7007SB_MIDIAN= 1,
GO7007SB_LOWPASS= 2,
GO7007SB_NOFILTER= 0
} FilterMode;
```

MPEG4\_MODE Enumeration
Syntax
```c
enum MPEG4_MODE
{
WIS_MPEG4= 0,
DIVX_MPEG4= 1,
MICROSOFT_MPEG4= 2,
};
```

FLAGS\_STREAM Enumeration
Syntax
```python
enum FLAGS_STREAM
{
FLAGS_STREAM_COMPRESS_MODE= 0x00000001,
FLAGS_STREAM_SEQUENCE_MODE= 0x00000002,
FLAGS_STREAM_GOP_MODE= 0x00000004,
FLAGS_STREAM_GOP_SIZE= 0x00000008,
FLAGS_STREAM_MPEG4_MODE= 0x00000010,
FLAGS_STREAM_DEINTERLACE_MODE= 0x00000020,
FLAGS_STREAM_SEARCH_RANGE= 0x00000040,
```

```c
FLAGS_STREAM_GOPHEAD_ENABLE= 0x00000080,
FLAGS_STREAM_SEQHEAD_ENABLE= 0x00000100,
FLAGS_STREAM_ASPECT_RATIO= 0x00000200,
FLAGS_STREAM_DVD_COMPLIANT= 0x00000400,
FLAGS_STREAM_MPEG4_MANDETORY=
FLAGS_STREAM_COMPRESS_MODE +
FLAGS_STREAM_MPEG4_MODE,
};
```

# FLAGS\_FRAMERATE Enumeration

# Syntax

```txt
enum FLAGS_FRAMERATE
{
FLAGS_FRAMERATE_FRAMERATE = 0x00000001,
FLAGS_FRAMERATE_IVTC_ENABLE = 0x00000002,
FLAGS_FRAMERATE_DROP_FRAME = 0x00000004,
FLAGS_FRAMERATE_TVSTANDARD = 0x00000008,
FLAGS_FRAMERATE_MANDETORY =
    FLAGS_FRAMERATE_FRAMERATE +
    FLAGS_FRAMERATE_TVSTANDARD,
};
```

FLAGS\_RESOLUTION Enumeration
Syntax
```lisp
enum FLAGS_RESOLUTION
{
FLAGS_RESOLUTION_WIDTH=0x00000001,
FLAGS_RESOLUTION_HEIGHT=0x00000002,
FLAGS_RESOLUTION_H_SUBWINDOW=0x00000004,
FLAGS_RESOLUTION_V_SUBWINDOW=0x00000008,
FLAGS_RESOLUTION_SCALE_OFFSET=0x00000010,
FLAGS_RESOLUTION_SUBSAMPLE=0x00000100,
FLAGS_RESOLUTION_TVSTANDARD=0x00000200,
FLAGS_RESOLUTION_MAX_BITRATE=0x00000400,
FLAGS_RESOLUTION_MIN_BITRATE=0x00000800,
FLAGS_RESOLUTION_H_SUBOFFSET=0x00001000, // used only in parser
FLAGS_RESOLUTION_V_SUBOFFSET=0x00002000, // used only in parser
FLAGS_RESOLUTION_H_SCALE_ENABLE = 0x00004000, // used only in parser
FLAGS_RESOLUTION_V_SCALE_ENABLE = 0x00008000, // used only in parser

FLAGS_RESOLUTION_MANDETORY =
FLAGS_RESOLUTION_WIDTH

+FLAGS_RESOLUTION_HEIGHT

+FLAGS_RESOLUTION_TVSTANDARD

+FLAGS_RESOLUTION_MAX_BITRATE

+FLAGS_RESOLUTION_MIN_BITRATE,
};
```

# FLAGS\_BITRATE Enumeration

# Syntax

```txt
enum FLAGS_BITRATE
{
FLAGS_BITRATE_TARGET= 0x00000004,
FLAGS_BITRATE_PEAK= 0x00000008,
FLAGS_BITRATE_VBV_BUFFER= 0x00000010,
FLAGS_BITRATE_CONVERGE_SPEED= 0x00000020,
FLAGS_BITRATE_LAMBDA= 0x00000040,
FLAGS_BITRATE_Q= 0x00000080,
FLAGS_BITRATE_IPBQ= 0x00000100,
FLAGS_BITRATE_IQ= 0x00000200, // used only in parser
FLAGS_BITRATE_PQ= 0x00000400, // used only in parser
FLAGS_BITRATE_BQ= 0x00000800, // used only in parser

FLAGS_BITRATE_MANDETORY= FLAGS_BITRATE_TARGET +
FLAGS_BITRATE_Q
};
```

# FLAGS\_MISC Enumeration

# Syntax

```c
enum FLAGS_MISC
{
FLAGS_MISC_AV_SYNC_ENABLE= 0x00000001,
FLAGS_MISC_IIP_ENABLE= 0x00000002,
FLAGS_MISC_VBI_ENABLE= 0x00000004,
FLAGS_MISC_FOUR_CHANNEL_ENABLE= 0x00000008,
```

```txt
FLAGS_MISC_FILTER= 0x00000010,
FLAGS_MISC_MANDETORY= 0
};
```

# SENSOR\_CAPABILITIES Enumeration

# Syntax

```python
enum SENSOR_CAPABILITIES
{
CAP_SENSOR_VIDEO_SOURCE= 0x00000001,
CAP_SENSOR_VIDEO_BRIGHTNESS= 0x00000004,
CAP_SENSOR_VIDEO_BRIGHTNESS_AUTO= 0x00000008,
CAP_SENSOR_VIDEO_CONTRAST= 0x00000010,
CAP_SENSOR_VIDEO_CONTRAST_AUTO= 0x00000020,
CAP_SENSOR_VIDEO_HUE= 0x00000040,
CAP_SENSOR_VIDEO_HUE_AUTO= 0x00000080,
CAP_SENSOR_VIDEO_SATURATION= 0x00000100,
CAP_SENSOR_VIDEO_SATURATION_AUTO= 0x00000200,
CAP_SENSOR_VIDEO_SHARPNESS= 0x00000400,
CAP_SENSOR_VIDEO_SHARPNESS_AUTO= 0x00000800,
CAP_SENSOR_VIDEO_GAMMA= 0x00001000,
CAP_SENSOR_VIDEO_GAMMA_AUTO= 0x00002000,
CAP_SENSOR_VIDEO_WHITEBALANCE= 0x00004000,
```

```c
CAP_SENSOR_VIDEO_WHITEBALANCE_AUTO= 0x00008000,
CAP_SENSOR_VIDEO_BACKLIGHT_COMPENSATION=
0x00010000,
CAP_SENSOR_VIDEO_BACKLIGHT_COMPENSATION_AUTO =
0x00020000,
CAP_SENSOR_VIDEO_COLORENABLE= 0x00040000,
};
```

# Remark

A DWORD with each bit represents one kind of sensor capability.

# AUDIO\_CAPS Enumeration

# Syntax

```txt
enum AUDIO_CAPS
{
CAP_AUDIO_FORMAT_PCM= 0x00000001,
CAP_AUDIO_FORMAT_ADPCM_MS= 0x00000002,
CAP_AUDIO_FORMAT_ADPCM_IMA= 0x00000004,
CAP_AUDIO_FORMAT_ALAW= 0x00000008,
CAP_AUDIO_FORMAT_ULAW= 0x00000010,
CAP_AUDIO_FORMAT_MP3= 0x00000020,

CAP_AUDIO_SAMPLERATE_8K= 0x00000100,
CAP_AUDIO_SAMPLERATE_11025= 0x00000200,
CAP_AUDIO_SAMPLERATE_16K= 0x00000400,
CAP_AUDIO_SAMPLERATE_22050= 0x00000800,
CAP_AUDIO_SAMPLERATE_32K= 0x00001000,
CAP_AUDIO_SAMPLERATE_44100= 0x00002000,
```

```txt
CAP_AUDIO_SAMPLERATE_48K= 0x00004000,
CAP_AUDIO_CHANNEL_MONO= 0x00010000,
CAP_AUDIO_CHANNEL_STEREO= 0x00020000,
CAP_AUDIO_SAMPLE_8BIT= 0x00040000,
CAP_AUDIO_SAMPLE_16BIT= 0x00080000,
};
```

# Remark

A DWORD with each bit represents one kind of audio capability.

# AUDIO\_FORMAT Enumeration

# Syntax

```txt
enum AUDIO_FORMAT
{
AUDIO_FORMAT_PCM=1,
AUDIO_FORMAT_ADPCM_MS=2,
AUDIO_FORMAT_ADPCM_IMA=11,
AUDIO_FORMAT_ALAW,
AUDIO_FORMAT_ULAW,
AUDIO_FORMAT_MP3=0x55
};
```

# Remark

This enumeration lists various kinds of audio formats.

# ASSOCIATION\_TYPE Enumeration

# Syntax

```txt
enum ASSOCIATION_TYPE
{
TYPE_SYSTEM_CONFIG,
TYPE_STREAM_CONFIG,
TYPE_RESOLUTION_CONFIG,
TYPE_BITRATE_CONFIG,
TYPE_FRAMERATE_CONFIG
};
```

# BOARD\_CAP Enumeration

# Syntax

```txt
typedef enum
{
BC_VIDEO= 0x00000001,
BC_AUDIO= 0x00000002,
BC_TVTUNER= 0x00000004,
BC_XBAR= 0x00000008,
BC_VBI= 0x00000010,
} BOARD_CAP;
```

# Filter Interfaces

Included in this chapter are descriptions of the interfaces exposed by the WDM streaming capture filter (ADLINK Hardware MPEG4 Device filter).

For Microsoft DirectShow interfaces follow these links: IAMAnalogVideoDecoder, IAMCameraControl, IAMDropped-Frames, IAMVideoProcAmp, IBaseFilter, IKsPropertySet, and

ISpecifyPropertyPages.

Alternatively, visit http://msdn.microsoft.com/library/ and from the left panel navigation, select Graphics and Multimedia -> DirectX -> SDK Documentation -> DirectX 9.0 (C++) -> DirectShow -> DirectShow Reference -> Interfaces for a complete list of standard DirectShow filter interfaces references.

The ADLINK Hardware MPEG4 Device private interfaces are described in this chapter.

# IGOChip Interface

# IGOChip::SetVideoConfig

The SetVideoConfig method sets the video configurations.

# Syntax

```sql
HRESULT SetVideoConfig(
TCFG_FORMAT_EXTENSION* pConfig,
unsigned int* pError
);
```

# Parameters

pConfig: [Out] Pointer to a structure
TCFG\_FORMAT\_EXTENSION that contains video configurations.

pError: [Out] Error information

# Return Value

HRESULT

# Remarks

Normally, format information for DirectShow applications is configured via the IAMStreamConfig interface. This interface is exposed by both video and audio pins of WIS driver. The video and audio capabilities of the driver, the mean time, and the default format of these capabilities can be retrieved by using this interface. It is common to have multiple capabilities for both audio and video. Follow the instructions below to configure:

Inspect all capabilities to check which capability is the one you want to set, using IAMStreamConfig::GetStreamCaps.

The default format for this capability can be modified as needed. This format is the second out parameter of the GetStreamCaps.

Use IAMStreamConfig->SetFormat to set the modified format to the driver.

The following sample code - SetPinFormat function shows the video configuration setup process. The audio configuration can also be set in a similar way.

The proprietary interface IGOChip::SetVideoConfig is necessary here is due to a known issue on the VideoInfoHeader format, preventing the format information to be set in the standard way. The code in the SetPinFormat function indicates this patch. After this problem is solved, there will be no need to use any non-standard interface.

The private format information is appended as an extension (TCFG\_FORMAT\_EXTENSION structure) to the normal format information of DirectShow, (AM\_MEDIA\_TYPE->pbFormat). The format size of cbFormat reflects this extension.

Sample Code
```cpp
void
CVideoControlPropertyPage::SetPinFormat(IAMStreamConfig* stream_config,

TCFGVIDEOEX* video_config)
{
    AM_MEDIA_TYPE* pmt;
    VIDEO_STREAM_CONFIG_CAPS caps;

    if (stream_config == NULL) return;

    int caps_count = 0, caps_size = 0;
    stream_config->GetNumberOfCapabilities(&caps_count, &caps_size);

    char szDebugInfo[1000];

    for (int i = 0; i &lt; caps_count; i++)
    {
    HRESULT hr = stream_config-&gt;GetStreamCaps(i, &pmt, (BYTE*)&caps);
    if (FAILED(hr)) {
    OutputDebugString("[wisproxy]: GetSteamCaps Failed!"); continue;
    }

    unsigned long normal_format_size;
    switch (video_config->strcfg.compress_mode)
    {
    case MPEG1:
    {
    if (pmt->subtype != MEDIASUBTYPE_MPEG1Payload) goto next_stream_caps;
    }
}
```

```c
if (pmt->formattype != FORMAT_MPEGVideo) goto
next_stream_caps;
MPEG1VIDEOINFO* format = (MPEG1VIDEOINFO*)pmt-
>pbFormat;
if (format->hdr.bmiHeader.biWidth !=
(int)video_config->rescfg.width)
    goto next_stream_caps;
if (format->hdr.bmiHeader.biHeight !=
(int)video_config->rescfg.height)
    goto next_stream_caps;

normal_format_size =
SIZE_MPEG1VIDEOINFO(format);
format->hdr.AvgTimePerFrame =
(ULONGLONG)(10010000000) / video_config-
>fpscfg.frame_rate;
format->hdr.bmiHeader.biWidth = video_config-
>rescfg.width;
format->hdr.bmiHeader.biHeight = video_config-
>rescfg.height;
format->hdr.bmiHeader.biSizeImage =
video_config->rescfg.width * video_config-
>rescfg.height * 3 / 2;
format->hdr.dwBitRate = video_config-
>ctlcfg.target_bitrate;

if (pmt->cbFormat > normal_format_size)
{
    assert( pmt->cbFormat == normal_format_size +
sizeof(TCFG_FORMAT_EXTENSION));
TCFG_FORMAT_EXTENSION* extension =
(TCFG_FORMAT_EXTENSION*) (pmt->pbFormat +
normal_format_size);
    extension->_stream =
video_config->strcfg;
```

```c
extension->_framerate = video_config->fpscfg;
extension->_resolution = video_config->rescfg;
extension->_bitrate = video_config->ctlcfg;
}

sprintf(szDebugInfo, "MPEG1 width: %d height: %d fps: %d bps: %d",
    format->hdr.bmiHeader.biWidth,
    format->hdr.bmiHeader.biHeight,
    long(format->hdr.AvgTimePerFrame),
    format->hdr.dwBitRate);

OutputDebugString(szDebugInfo);

break;
case MPEG2:
{
    if (pmt->subtype != MEDIASUBTYPE_MPEG2_VIDEO) goto next_stream_caps;
    if (pmt->formattype != FORMAT_MPEG2Video) goto next_stream_caps;
    MPEG2VIDEOINFO* format = (MPEG2VIDEOINFO*)pmt->pbFormat;
    if (format->hdr.bmiHeader.biWidth != (int)video_config->rescfg.width)
    goto next_stream_caps;
    if (format->hdr.bmiHeader.biHeight != (int)video_config->rescfg.height)
    goto next_stream_caps;

    normal_format_size = SIZE_MPEG2VIDEOINFO(format);
    format->hdr.AvgTimePerFrame =
```

```c
(ULONGLONG)(10010000000) / video_config->fpscfg.frame_rate;
    format->hdr.bmiHeader.biWidth = video_config->rescfg.width;
    format->hdr.bmiHeader.biHeight = video_config->rescfg.height;
    format->hdr.bmiHeader.biSizeImage = video_config->rescfg.width * video_config->rescfg.height * 3 / 2;
    format->hdr.dwBitRate = video_config->ctlcfg.target_bitrate;
    format->hdr.dwPictAspectRatioX = video_config->rescfg.width;
    format->hdr.dwPictAspectRatioY = video_config->rescfg.height;

    if (pmt->cbFormat > normal_format_size)
    {
    assert(pmt->cbFormat == normal_format_size + sizeof(TCFG_FORMAT_EXTENSION));
    TCFG_FORMAT_EXTENSION* extension = (TCFG_FORMAT_EXTENSION*)(pmt->pbFormat + normal_format_size);
    extension->_stream = video_config->strcfg;
    extension->_framerate = video_config->fpscfg;
    extension->_resolution = video_config->rescfg;
    extension->_bitrate = video_config->ctlcfg;
    }

    sprintf(szDebugInfo, "MPEG2 width: %d height: %d fps: %d bps: %d",
```

```c
format->hdr.bmiHeader.biWidth,
    format->hdr.bmiHeader.biHeight,
    long(format->hdr.AvgTimePerFrame),
    format->hdr.dwBitRate);

OutputDebugString(szDebugInfo);

break;
}
case MPEG4:
case H263:
case MOTIONJPEG:
{
    if (pmt->formattype != FORMAT_VideoInfo)
    goto next_stream_caps;

    VIDEOINFOHEADER* format = (VIDEOINFOHEADER*)pmt->pbFormat;
    if (format->bmiHeader.biWidth != (int)video_config->rescfg.width) goto next_stream_caps;
    if (format->bmiHeader.biHeight != (int)video_config->rescfg.height) goto next_stream_caps;
    if (video_config->strcfg.compress_mode == MPEG4)
    {
    switch (video_config->strcfg.mpeg4_mode)
    {
    case DIVX_MPEG4:
    if (format->bmiHeader.biCompression != FCC_FORMAT_DIVX_MPEG4)
    goto next_stream_caps;
    break;
```

```c
case MICROSOFT_MPEG4:
    if ( format->bmiHeader.biCompression != FCC_FORMAT_MICROSOFT_MPEG4 )
    goto next_stream_caps;
    break;
    case WIS_MPEG4:
    if ( format->bmiHeader.biCompression != FCC_FORMAT_WIS_MPEG4 )
    goto next_stream_caps;
    break;
    default:
    assert(false);
    }
    }
    else if ( video_config->strcfg.compress_mode == H263 )
    {
    if ( format->bmiHeader.biCompression != FCC_FORMAT_H263 )
    goto next_stream_caps;
    }
    else if ( video_config->strcfg.compress_mode == MOTIONJPEG )
    {
    if ( format->bmiHeader.biCompression != FCC_FORMAT_MOTION_JPEG )
    goto next_stream_caps;
    }

    normal_format_size = format->bmiHeader.biSize + SIZE_PREHEADER - sizeof(TCFG_FORMAT_EXTENSION);
    format->AvgTimePerFrame =
```

```c
(ULONGLONG)(10010000000) / video_config->fpscfg.frame_rate;
    format->bmiHeader.biWidth = video_config->rescfg.width;
    format->bmiHeader.biHeight = video_config->rescfg.height;
    format->bmiHeader.biSizeImage = video_config->rescfg.width * video_config->rescfg.height * 3 / 2;
    format->dwBitRate = video_config->ctlcfg.target_bitrate;

    if (pmt->cbFormat > normal_format_size)
    {
    assert(pmt->cbFormat == normal_format_size + sizeof(TCFG_FORMAT_EXTENSION));
    TCFG_FORMAT_EXTENSION* extension = (TCFG_FORMAT_EXTENSION*)(pmt->pbFormat + normal_format_size);
    extension->_stream = video_config->strcfg;
    extension->_framerate = video_config->fpscfg;
    extension->_resolution = video_config->rescfg;
    extension->_bitrate = video_config->ctlcfg;

    if (video_config->strcfg.mpeg4_mode == MICROSOFT_MPEG4)
    {
    char* seq_header;
    UINT32 seq_length = FormatMPEG4StreamSEQHeader(&m_VideoCaps, extension, &seq_header);
```

```cpp
memcpy( pmt->pbFormat + normal_format_size - seq_length, seq_header, seq_length);
    }
    if ( m_pIGOChipConfig ) // patch
    {
    IGOChip* pIGOChip;
    m_pIGOChipConfig->QueryInterface(IID_IGOChip, reinterpret_cast&lt;void**&gt;( &pIGOChip));
    unsigned int error;
    pIGOChip->SetVideoConfig(extension, &error);
    pIGOChip->Release();
    }
    }

    sprintf(szDebugInfo, "videoinfo width: %d height: %d fps: %d bps: %d",
    format->bmiHeader.biWidth,
    format->bmiHeader.biHeight,
    long(format->AvgTimePerFrame),
    format->dwBitRate);

    OutputDebugString(szDebugInfo);

    break;
    }
default:
    assert(false);
    DeleteMediaType(pmt);
    return;
}
```

```cpp
AM_MEDIA_TYPE* pmt1;

hr = stream_config->GetFormat(&pmt1);
DeleteMediaType(pmt1);

hr = stream_config->SetFormat(pmt);
if (FAILED(hr) { OutputDebugString("wisproxy: set pin format failed"); };
DeleteMediaType(pmt);

hr = stream_config->GetFormat(&pmt);
DeleteMediaType(pmt);

return;

next_stream_caps:
DeleteMediaType(pmt);
}
```

# IGOChipConfig Interface

<table><tr><td>Note:</td><td>This interface has now been phased out. It will continue to be supported for backward compatibility with existing applications, but new applications and filters should not use this interface. The functionality of this interface can be achieved by using Microsoft Direct-Show interfaces.</td></tr></table>

# 1. IGOChipConfig::GetVideoConfig

The GetVideoConfig method retrieves the video configurations.

# Syntax

```txt
HRESULT GetVideoConfig(
TCFGVIDEOEX *pVal
);
```

# Parameters

pVal: [Out] Pointer to a structure TCFGVIDEOEX to receive video configurations.

# Return Value

HRESULT

# Related Items

IGOChip::SetVideoConfig()

# 2. IGOChipConfig::GetVideoSource

The GetVideoSource method retrieves the video source that is in use.

# Syntax

```sql
HRESULT GetVideoSource(
    unsigned int *pVal
);
```

# Parameters

pVal: [Out] Pointer to an integer that represents video source in use. 0 represents S-video and 1 represents composite.

# Return Value

# HRESULT

# 3. IGOChipConfig::SetVideoSource

The SetVideoSource method sets the video source as either S-video or composite.

# Syntax

```txt
HRESULT SetVideoSource(
    unsigned int newVal
);
```

# Parameters

newVal: [In]Specifies what kind of video source is in use. 0 represents S-video and 1 represents composite.

# Return Value

HRESULT

# 4. IGOChipConfig::GetSensorCapability

The GetSensorCapability method retrieves the sensor capabilities.

# Syntax

```txt
HRESULT GetSensorCapability(
    unsigned int *pVal
);
```

# Parameters

pVal: [Out] Pointer to an unsigned integer that is Enumeration: SENSOR\_CAPABILITIES.

# Return Value

HRESULT

# 5. IGOChipConfig::GetStatisticInfo

The GetStatisticInfo method retrieves the statistical information about video bytes and frames obtained since starting the capture.

# Syntax

```txt
HRESULT GetStatisticInfo(
    STATISTIC *pVal
);
```

# Parameters

pVal: [Out] Pointer to a STATISTIC structure to receive statistic info.

# Return Value

HRESULT

# 6. IGOChipConfig::GetVideoCapabilities

The GetVideoCapabilities method retrieves the information about video capabilities.

# Syntax

```sql
HRESULT GetVideoCapabilities(
    _VIDEO_CAPABILITIES* pCaps
);
```

# Parameters

pCaps: [Out] Pointer to a \_VIDEO\_CAPABILITIES structure to receive video capabilities.

# Return Value

HRESULT

7. IGOChipConfig::GetAudioConfig

The GetAudioConfig method retrieves the audio configurations.

# Syntax

```txt
HRESULT GetAudioConfig(
AUDIO_CONFIG *pConfig
);
```

# Parameters

pConfig: [Out] Pointer to a structure AUDIO\_CONFIG to receive audio configurations.

# Return Value

HRESULT

# Related Items

IGOChipConfig::SetAudioConfig()

8. IGOChipConfig::SetAudioConfig

The SetAudioConfig method sets the audio configurations.

# Syntax

```txt
HRESULT SetAudioConfig(
AUDIO_CONFIG *pConfig
);
```

# Parameters

pConfig: [Out] Pointer to a structure AUDIO\_CONFIG that contains audio configurations.

# Return Value

HRESULT

# Related Items

IGOChipConfig::GetAudioConfig()

# 9. IGOChipConfig::GetAudioCapability

The GetAudioCapability method retrieves the audio capabilities.

# Syntax

```sql
HRESULT GetAudioCapability(
    unsigned int *pAudioCap
);
```

# Parameters

pAudioCap: [Out] Pointer to an unsigned integer that is Enumeration: AUDIO\_CAPS.

# Return Value

HRESULT

# IGOInfo Interface

# 1. IGOInfo::GetRevisionInfo

The GetRevisoinInfo method retrieves revision information of driver and board.

# Syntax

```txt
HRESULT GetRevisionInfo( REVISION_INFO *pRevInfo );
```

# Parameters

pRevInfo: [In] A pointer to REVISION\_INFO structure to hold driver and board revision information.

# Return Value

HRESULT

# 2. IGOInfo::GetMacrovision

The GetMacrovision method ascertains whether the video stream is protected by Macrovision.

# Syntax

```txt
HRESULT GetMacrovision(
int *pMacrovision
);
```

# Parameters

pMacrovision: [In] 1 indicates the stream is protected. 0 indicates the stream is not protected.

# Return Value

HRESULT

# IAccessFunc Interface

This interface provides methods for accessing I2C, SPI and

# GPIO.

# 1. IAccessFunc::I2C\_WriteRegister

The I2C\_WriteRegister method writes a single I2C register.

# Syntax

```sql
HRESULT I2C_WriteRegister(
unsigned char DevAddr,
int AddrWidth,
unsigned short RegAddr,
unsigned char RegValue,
int I2CMode
);
```

# Parameters

DevAddr: [In] Device address.

AddrWidth: [In] Length of register address, in bits. Typical values can either be 8 or 16.

RegAddr: [In] Register address. If its higher byte is 0, the register is considered to have an 8-bit address; otherwise, the address length is 16 bits.

RegValue: [In] Value to be written to the I²C register.

I2Cmode: [In] I²C mode. The value can be set at:

▶ 0x0000: Use I²C protocol via on chip I²C controller.
▶ 0x0001: Use SCCB protocol via on chip I²C controller.
▶ 0x8000: Use I²C protocol via Cypress I²C controller.

# Return Value

HRESULT

# 2. IAccessFunc::I2C\_ReadRegister

The I2C\_ReadRegister method reads a single I2C register.

# Syntax

```sql
HRESULT I2C_ReadRegister(
Unsigned char DevAddr,
int AddrWidth,
unsigned short RegAddr,
unsigned char *pRegValue,
int I2CMode
);
```

# Parameters

DevAddr: [In] Device address.

AddrWidth: [In] Length of register address, in bits. Typical values can be either 8 or 16.

RegAddr: [In] Register address. If its higher byte is 0, the register is considered to have an 8-bit address; otherwise, the address length is 16 bits.

pRegValue: [Out] Value read from the I²C register.

I2CMode: [In] I²C mode. The value can be set at:

▶ 0x0000: Use I²C protocol via on chip I²C controller.
▶ 0x0001: Use SCCB protocol via on chip I²C controller.
▶ 0x8000: Use I²C protocol via Cypress I²C controller.

# Return Value

HRESULT

# 3. IAccessFunc::I2C\_BurstWriteRegister

The I2C\_BurstWriteRegister method writes multiple continuous I2C registers (burst mode).

# Syntax

```sql
HRESULT I2C_BurstWriteRegister(
unsigned char DevAddr,
int AddrWidth,
unsigned short StartRegAddr,
int RegNum,
unsigned char *pRegValue,
int I2CMode
);
```

# Parameters

DevAddr: [In] Device address.

AddrWidth: [In] Length of register address, in bits. Typical values can be either 8 or 16.

StartRegAddr: [In] Address of the first register. If its higher byte is 0, the register is considered to have an 8-bit address; otherwise, the address length is 16 bits.

RegNum: [In] Number of registers to be written.

pRegValue: [In] Pointer to an array of values to be written to the I²C registers.

I2CMode: [In] I²C mode. The value can be set at:

▶ 0x0000:Use I²C protocol via on chip I²C controller.
▶ 0x0001:Use SCCB protocol via on chip I²C controller.
▶ 0x8000:Use I²C protocol via Cypress I²C controller.

# Return Value

# HRESULT

# 4. IAccessFunc::I2C\_BurstReadRegister

The I2C\_BurstReadRegister method reads multiple continuous I2C registers (burst mode).

# Syntax

```sql
HRESULT I2C_BurstReadRegister(
unsigned char DevAddr,
int AddrWidth,
unsigned short StartRegAddr,
int RegNum,
unsigned char *pRegValue,
int I2CMode
);
```

# Parameters

DevAddr: [In] Device address.

AddrWidth: [In] Length of register address, in bits. Typical values can either be 8 or 16.

StartRegAddr: [In] Address of the first register. If its higher byte is 0, the register is considered to have an 8-bit address; otherwise the address length is 16 bits.

RegNum: [In] Number of registers to be read.

pRegValue: [Out] Pointer to an array which will receive the values read from I²C registers.

I2CMode: [In] I²C mode. The value can be set at:

▶ 0x0000: Use I²C protocol via on chip I²C controller.
▶ 0x0001:Use SCCB protocol via on chip I²C controller.
▶ 0x8000:Use I²C protocol via Cypress I²C controller.

# Return Value

HRESULT

# 5. IAccessFunc::SPI\_WriteRegister

The SPI\_WriteRegister method writes a single SPI register.

# Syntax

```sql
HRESULT SPI_WriteRegister(
int OpLen,
unsigned char OpCode,
int AddrLen,
unsigned short RegAddr,
int DataLen,
unsigned short RegData,
int SPIMode
);
```

# Parameters

OpLen: [In] Operation code length, in bits. The typical range is 1 - 8.

OpCode: [In] Operation code.

AddrLen: [In] Length of register address, in bits. The typical range is 1 - 16.

RegAddr: [In] Register address.

DataLen: [In] Length of data, in bits. The typical range is 0 - 16.

RegData: [In] Value to be written to the SPI register.

SPI\_mode: [In] SPI mode, a 16-bit data. Refer to the following table for definitions for each bit.

<table><tr><td>Bit</td><td>Name</td><td>Type</td><td>Default Value</td><td>Description</td></tr><tr><td>15:11</td><td>Reserved</td><td></td><td></td><td></td></tr><tr><td>10</td><td>three_wire_en</td><td>RW</td><td>1&#x27;b0</td><td>1 = 3-wire is enabled;0 = 3-wire is not enabled;</td></tr><tr><td>9</td><td>bst_end</td><td>RW</td><td>1&#x27;b0</td><td>1 = the next R/W access is the last access of a burst access;0 = the next R/W access is not the last access of a burst access (only valid for burst mode)</td></tr><tr><td>8</td><td>sdo_separate</td><td>RW</td><td>1&#x27;b0</td><td>1 = pin sdi and pin sdo are separated;0 = pin sdi and pin sdo are shared;</td></tr><tr><td>7</td><td>cs1_en_value</td><td>RW</td><td>1&#x27;b0</td><td>1 = the chip-select enable logic value for cs1 is 10 = the chip-select enable logic value for cs1 is 0</td></tr><tr><td>6</td><td>cs0_en_value</td><td>RW</td><td>1&#x27;b0</td><td>1 = the chip-select enable logic value for cs0 is 10 = the chip-select enable logic value for cs0 is 0</td></tr><tr><td>5</td><td>cs1_en</td><td>RW</td><td>1&#x27;b0</td><td>1 = output cs1 is enabled;0 = output cs1 is disabled;</td></tr><tr><td>4</td><td>cs0_en</td><td>RW</td><td>1&#x27;b1</td><td>1 = output cs0 is enabled;0 = output cs0 is disabled;</td></tr><tr><td>3</td><td>read</td><td>RW</td><td>1&#x27;b0</td><td>1 = do read access;0 = do non-read access (write or other operation like erase, erase_write_enable/disable);</td></tr></table>

<table><tr><td>Bit</td><td>Name</td><td>Type</td><td>Default Value</td><td>Description</td></tr><tr><td>2</td><td>bst_rw</td><td>RW</td><td>1&#x27;b0</td><td>1 = burst R/W mode (burst R for 3-wire device is not supported, the read data of 3-wire device is half spi clock cycle later than that of spi device);0 = single R/W mode;</td></tr><tr><td>1:0</td><td>spi_mode</td><td>RW</td><td>2&#x27;h0</td><td>2&#x27;h0 = spi mode 0;2&#x27;h1 = spi mode 1;2&#x27;h2 = spi mode 2;2&#x27;h3 = spi mode 3;Note: for 3-wire, mode 0 should be used.</td></tr></table>

Table 2-10: SPI Control Register Definition

# Return Value

HRESULT

# 6. IAccessFunc::SPI\_ReadRegister

The SPI\_ReadRegister method reads a single SPI register.

# Syntax

```sql
HRESULT SPI_ReadRegister(
int OpLen,
unsigned char OpCode,
int AddrLen,
unsigned short RegAddr,
int DataLen,
unsigned short *pRegData,
int SPIMode
);
```

# Parameters

OpLen: [In] Operation code length, in bits. The typical range is 1 - 8.

OpCode: [In] Operation code.

AddrLen: [In] Length of register address, in bits. The typical range is 1 - 16.

RegAddr: [In] Register address.

DataLen: Length of data, in bits. The typical range is 0 – 16.

pRegData: [Out] Value to be written to the SPI register.

SPIMode: [In] SPI mode, a 16-bit data. Refer to Table 1 SPI Control Register Definition for definitions of each bit.

# Return Value

HRESULT

# 7. IAccessFunc::GPIO\_WritePins

The GPIO\_WritePins method toggles the signal on one or multiple GPIO pins.

# Syntax

```txt
HRESULT GPIO_WritePins(
int WriteNum,
int *Index,
int *Value,
int Mode
);
```

# Parameters

WriteNum: [In] Number of pins to write.

Index: [In] Indexes of GPIO pins.

Value: [In] The signal written to the GPIO pins. The value must be either 0 or 1.

Mode: [In] 0: On chip GPIO controller; 1: Cypress GPIO controller.

# Return Value

HRESULT

# 8. IAccessFunc::GPIO\_ReadPins

The GPIO\_ReadPins method reads the signal on one or multiple GPIO pins.

# Syntax

```txt
HRESULT GPIO_ReadPins(
int ReadNum,
int *Index,
int *Value,
int Mode
);
```

# Parameters

ReadNum: [In] Number of pins to read.

Index: [In] Indexes of GPIO pins.

Value: [In] The signal read from the GPIO pins.

Mode: [In] 0: via on chip GPIO controller; 1: via Cypress GPIO controller.

# Return Value

HRESULT

# ADLINK Hardware MPEG4 Device GPIO Pin Definition

<table><tr><td>PIN</td><td>Type</td><td>FUNCTION</td></tr><tr><td>GPIO0</td><td>Input</td><td>Channel ID bit 0</td></tr><tr><td>GPIO1</td><td>Input</td><td>Channel ID bit 1</td></tr><tr><td>GPIO2</td><td>Input</td><td>Card ID bit 0 (setting by dip switch)</td></tr><tr><td>GPIO3</td><td>Input</td><td>Card ID bit 1 (setting by dip switch)</td></tr><tr><td>GPIO4</td><td>Input</td><td>Card ID bit 2 (setting by dip switch)</td></tr></table>

Table 2-11: ADLINK Hardware MPEG4 Device GPIO Pinout

# IAdvanced Interface

This interface provides advanced access to CBUS registers and HPI registers. Some methods are for internal testing use purposes only, and hence are not documented in this document.

# 1. IAdvanced::ReadCBusRegFW

The ReadCBusRegFW method reads a single CBus register.

# Syntax

```txt
HRESULT ReadCBusRegFW(
unsigned short Addr,
unsigned short *pData,
);
```

# Parameters

Addr: [In] CBus register address.

pData: [Out] pointer to an unsigned short to hold the register value read.

# Return Value

HRESULT

# 2. IAdvanced::WriteCBusRegFW

The WriteCBusRegFW method writes a single CBus register.

# Syntax

```txt
HRESULT WriteCBusRegFW(
unsigned short Addr,
unsigned short Data,
);
```

# Parameters

Addr: [In] CBus register address.

Data: [In] CBus register value.

# Return Value

HRESULT

# IMotionDetection Interface

WIS Windows SDK supports Motion Detection(MD). This IMotionDetection interface let upper application to send the configurations of MD to WIS firmware.

# 1. IMOTIONDETECTION::SetUpMDInterface

The SetUpMDInterface method sends MD configurations to firmware and starts MD. Data of MD will be gotten by interruption of WIS firmware after MD starts.

Note: The chip supports four regions when we use MD, but only three regions can be used and the fourth region is invalid temporarily.

# Syntax

```txt
HRESULT SetUpMDInterface( [in] MDConfig_t* pData );
```

```c
Parameters
pData: [In] structure contains MD input information.
#define MAX_REGIONS_OF_INTEREST 4
MDConfig_t structure:
typedef struct sPointCoords
{
int CoordsX;
int CoordsY;
} PointCorrds_t;

typedef struct sMDConfig
{
PointCorrds_t ULPoint[MAX_REGIONS_OF_INTEREST];
PointCorrds_t BRPoint[MAX_REGIONS_OF_INTEREST];
unsigned short
    u32SADThresholdValues[MAX_REGIONS_OF_INTEREST];
unsigned short
    u32MVThresholdValues[MAX_REGIONS_OF_INTEREST];
unsigned short
    u32SensitivityValues[MAX_REGIONS_OF_INTEREST];
}MDConfig_t;
```

# Description

ULPoint Upper-left coordinate of region.

BRPoint Bottom-right coordinate of region.

U32SADThresholdValues The value of SADThreshold. This range of SADThreshold is from 0 to 32767. Higher the value, lower the sensitivity.

U32MVThresholdValues The value of MVThreshold. This range of MVThreshold is from 0 to 32767. Higher the value, lower the sensitivity.

u32SensitivityValues The value of Sensitivity. This range of Sensitivity is from 0 to 100. Higher the value, lower the sensitivity.

# Return Value

HRESULT

# 2. IMOTIONDETECTION::StopMDInterface

The StopMDInterface method sends a group of default configurations to WIS firmware and close MD.

# Syntax

HRESULT StopMDInterface();

# Parameters

Null

# Return Value

HRESULT

# INotify Interface

The Interface of INotify provides a field that upper application communicates with lower driver by event.

# 1. INotify::EnableEvent

The EnableEvent method may notify application whenever a specific event action occurs.

# Syntax

```sql
HRESULT EnableEvent(
ULONG event_id,
ULONG event_handle,
ULONG *cookie
);
```

# Parameters

Event\_id: [in] contain id of event that application want to enable it.

Event\_handle: [in] a handle is defined by application.

Cookie: [out] point to an array that is used to store the event data

# Return Value

HRESULT

# 2. INotify::GetEventData

The GetEventData method gets EventData from event which is produced by firmware.

# Syntax

```sql
HRESULT GetEventData(
ULONG event_id,
ULONG cookie,
ULONG buf_len,
unsigned char * buf,
ULONG *data_size
);
```

# Parameters

Event\_id: [in] contain id of event that application want to enable it.

cookie: [in] contain event data.

Buf\_len: [in] Size, in bytes, of the buffer at buf

Buf: [in] Pointer to a buffer that receive data for the operation.

Data\_size: [out] Pointer to a variable that receives the size, in bytes, of the data that stores in the buffer at buf

# Return Value

HRESULT

# 3. INotify::DisableEvent

The DisableEvent method informs the KS object specified by Handle to stop notifying the

application whenever a specific event action occurs.

# Syntax

```sql
HRESULT DisableEvent(
ULONG event_id,
ULONG cookie
);
```

# Parameters

Event\_id: [in] contain id of event that application want to enable it.

Cookie: [in] Pointer to a buffer that contains data that specifies the operation to perform

# Return Value

HRESULT

# IOSD Interfaces

ADLINK Hardware MPEG4 Device supports up to 94 Unicode character On Screen Display (OSD). This IOSD interface let upper application to send On Screen Display (OSD) string to the firmware, which will generate a corresponding OSD effect. The OSD string font size is limited to 94.

# 1. IOSD::Textout

The Textout method sends OSD frame to firmware to display. An OSD frame is composed multiple OSD strings. See OSD programming for details.

# Syntax

HRESULT Textout(

OSDTextoutInfo info

);

# Parameters

info: [In] structure contains OSD output information.

▶ OSDTextoutInfo structure:

typedef struct

```txt
{
    unsigned short TotalLength;
    unsigned short text[MAX OSDSTRING_LEN];
} OSDTextoutInfo;
```

Description: TotalLength: Describes the length of OSD frame contained in text[].

Text[]: OSD frame in word, refer to OSD programming chapter for OSD frame structure.

# Return Value

HRESULT

# 2. IOSD::Show

The Show method sends the firmware the command to start OSD.

# Syntax

```sql
HRESULT Textout( );
```

# Parameters

Null

# Return Value

HRESULT

# Pin Interfaces

The pins of ADLINK Hardware MPEG4 Device filter expose Microsoft DirectShow interfaces: IAMBufferNegotiation, IAMStreamConfig, IAMStreamControl, IKsPin, IKsPropertySet, IStreamBuilder, IMediaSeeking, IPin, and IQualityControl. Follow the links of the interfaces for further detail.

Alternatively, please visit http://msdn.microsoft.com/library/ and from the left panel navigation, select Graphics and Multimedia -> DirectX -> SDK Documentation -> DirectX 9.0 (C++) -> DirectShow -> DirectShow Reference -> Interfaces for a complete list of standard DirectShow filter interfaces references.

# 2.3 OSD Programming

# Introduction to OSD

OSD (On-Screen-Display) is supported by the ADLINK Hardware MPEG4 Device. During the Motion Estimation and Compensation (MEC) stage, firmware can load the OSD bitmap and overlay with video, thus modifying output bitmap. By default, the ASCII bitmaps are prepared at boot-up and saved in DRAM. Customers can also choose or generate their own bitmaps, such as UNICODE. However, font base address space is limited to no more than 16-bit. Drivers can download the customized bitmap font file or the default font bitmap file into firmware, and enabled firmware to do OSD bitmap overlap to show user required characters.

Context
![The flowchart depicts a data flow involving five main blocks: **Proxy**, **Customer Bitmap file**, **AVStream Driver**, **KS**, and **FW**.\n\n**Blocks:**\n*   **Proxy** (Top)\n*   **Customer Bitmap file** (Left)\n*   **AVStream Driver** (Center, rounded rectangle)\n*   **KS** (Right)\n*   **FW** (Bottom)\n\n**Connections:**\n*   **Proxy** sends data to **AVStream Driver** via an arrow labeled '**Required OSD characters**'.\n*   **Customer Bitmap file** sends data to **AVStream Driver** via an arrow with no label.\n*   **AVStream Driver** sends data to **KS** via an arrow labeled '**A/V frame**'.\n*   **AVStream Driver** sends data to **FW** via two downward arrows:\n    *   One arrow is labeled with stacked text: '**Initialization packet**' and '**OSD font image**'.\n    *   One arrow is labeled '**OSD frame**'.\n*   **FW** sends data back to **AVStream Driver** via an upward arrow labeled '**A/V frame**'.](.pci-mpg24-manual-18/efc6bb3378cd28150ec3e18b1c721a629b628c43f15f55c2cf503119867766e4.jpg)

# OSD Font Bitmaps

All OSD font bitmaps are stored in the off-chip DRAM. The address is from 0xA0100 to 0xAF8FF (if 8M SDRAM and IP\_ONLY), or from 0x140100 to 0x14F8FF (if 8M SDRAM and IPB). Each font occupies 32 consecutive DWORD, supporting up to 1984 font bitmaps. After downloading to DRAM, the bitmaps are never changed.

# OSD Fonts Display

There is a 192-WORD font index buffer in the on-chip SRAM. It is separated into two 96-WORD buffers: index\_buffer1 (0x3A00-0x3A5F) and index\_buffer2 (0x3A60-0x3ABF). At any time, one of them contains an OSD frame which is currently in use; the other is open for editing the next OSD frame. Here, an OSD frame means a layout of OSD fonts. A series of consecutive video frames may share one single OSD frame.

# OSD Frame

An OSD frame is made up with at least one OSD string and one OSD\_EOF. An OSD string starts with a ST\_CD which is followed by a series of font base addresses, and ends with an OSD\_EOS. An example is shown as follows:

<table><tr><td>ST_CD</td><td>ADDR0</td><td>ADDR1</td><td>...</td><td>ADDRn</td><td>OSD_EOS</td><td>ST_CD</td><td>ADDR0</td><td>...</td><td>OSD_EOS</td><td>OSD_EOF</td></tr></table>

ST\_CD: 16-bit, as the macroblock coordinate (x, y) for the first font of this string.

ST\_CD[15:8] = y, ST\_CD[7:0] = x.

Example: Preview window is 720\*480, max value of X is 720/16-1=44, max value of Y is 480/16-1 = 29.

ADDRx: 16-bit, as the base address for the its font of this string

Notes: n in ADDRn is from 0 to 93.

OSD\_EOS: 0x0000

OSD\_EOF: 0xAAAA.

# OSD Algorithm

Before encoding each macroblock, the firmware makes an OSD function call. In this call, the chip decides if the current macroblock has an OSD font over it. If so, it obtains this font's base address and sends it to the DMA controller. Then, a 32-DWORD bitmap of this font will be overlapped to that macroblock. At the first macroblock (0, 0) of each video frame, the firmware determines which buffer (index\_buffer1 or index\_buffer2) is in use. The firmware keeps comparing the ST\_CD of each OSD string with current macroblock's coordinate until they match. After getting ST\_CD, the firmware reads the next base address and sends it to the DMA controller, until an OSD\_EOS is met.

# Bitmap Stored in SDRAM

For every pixel in the bitmap, 4 bit data will be used to describe OSD behavior of the pixel. Format of BITMAP in SDRAM is:

<table><tr><td>bit 0</td><td></td><td></td><td></td><td></td><td></td><td></td><td>bit 31</td><td></td></tr><tr><td>dword 0</td><td>P(0,0)</td><td>P(0,1)</td><td>P(0,2)</td><td>P(0,3)</td><td>P(0,4)</td><td>P(0,5)</td><td>P(0,6)</td><td>P(0,7)</td></tr><tr><td>.</td><td>P(1,0)</td><td>P(1,1)</td><td>P(1,2)</td><td>P(1,3)</td><td>P(1,4)</td><td>P(1,5)</td><td>P(1,6)</td><td>P(1,7)</td></tr><tr><td>.</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr><tr><td>.</td><td>P(15,0)</td><td>P(15,1)</td><td>P(15,2)</td><td>P(15,3)</td><td>P(15,4)</td><td>P(15,5)</td><td>P(15,6)</td><td>P(15,7)</td></tr><tr><td>.</td><td>P(0,8)</td><td>P(0,9)</td><td>P(0,10)</td><td>P(0,11)</td><td>P(0,12)</td><td>P(0,13)</td><td>P(0,14)</td><td>P(0,15)</td></tr><tr><td>.</td><td>P(1,8)</td><td>P(1,9)</td><td>P(1,10)</td><td>P(1,11)</td><td>P(1,12)</td><td>P(1,13)</td><td>P(1,14)</td><td>P(1,15)</td></tr><tr><td>.</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td><td>...</td></tr></table>

P(x, y) means 4 bit data of pixel at column x and line y.

# OSD Pixel Color (4-bit OSD Data)

For every pixel, there are 4 bits to present the OSD behavior. It means:

<table><tr><td>Bit(s)</td><td>Description</td></tr><tr><td rowspan="3">[3]</td><td>OSD mode</td></tr><tr><td>0 – Background blending</td></tr><tr><td>1 – Foreground blending</td></tr><tr><td>[2:0]</td><td>Alpha blending level (0 - 7)</td></tr></table>

For mode 0, the algorithm is:

$$
X _ {d} = \frac {C _ {0} \cdot \alpha + X _ {s} \cdot (8 - \alpha) + 4}{8}
$$

For mode 1, the algorithm is:

$$
X _ {d} = \frac {C _ {0} \cdot \alpha + C _ {1} \cdot (8 - \alpha) + 4}{8}
$$

In the previous equations, $X_{s}$ is the source data (Y or U or V), $X_{d}$ is the result (Y or U or V), $\alpha$ is the alpha blending level which is defined in bit 2 to bit 0. $C_{0}$ is the background color and $C_{1}$ is the foreground color. As there are three channels (YUV), $C_{0}$ and $C_{1}$ could be programmable from C-Bus for every channel.

So there are two ways to change the OSD color:

1. Change the YUV value in Fix\_setting.txt

// osd setting

osdcfg.DoOSD = 1

osdcfg.OSDyc0 = 0

osdcfg.OSDyc1 = 255

osdcfg.OSDuc0 = 0

osdcfg.OSDuc1 = 128

osdcfg.OSDvc0 = 0

osdcfg.OSDvc1 = 128

2. Change the alpha blending level (a) as the above algorithm definition.

Refer the following YUV to RGB converting algorithm for detail.

$$
Y = 0. 2 9 9 R + 0. 5 8 7 G + 0. 1 1 4 B
$$

$$
U = - 0. 1 4 7 R - 0. 2 8 9 G + 0. 4 3 6 B
$$

$$
V = 0. 6 1 5 R - 0. 5 1 5 G - 0. 1 0 0 B
$$

Or

$$
\left[ \begin{array}{c} Y \\ U \\ V \end{array} \right] = \left[ \begin{array}{c c c} 0. 2 9 9 & 0. 5 8 7 & 0. 1 1 4 \\ - 0. 1 4 7 & - 0. 2 8 9 & 0. 4 3 6 \\ 0. 6 1 5 & - 0. 5 1 5 & - 0. 1 0 0 \end{array} \right] \left[ \begin{array}{c} R \\ G \\ B \end{array} \right]
$$

# Know Limitations

1. Each OSD frame can only contain up to 90 fonts in the single OSD string case.
2. Font size can only be 16\*16, which is macro block based.

# How to display customer defined size bitmap

The firmware only can display 16\*16 OSD bitmaps. However, customers can still show bigger bitmaps by proper software programming skills. For example, a 32\*32 pixel bitmap, software can display 32\*32's bitmap by dividing it into 4 small 16\*16 bitmap, first download the divided 16\*16 bitmap to the firmware, then display the small bitmap corresponding to their X,Y position. See following description:

![1\n2\n3\n4](.pci-mpg24-manual-18/b7f1e7ed61135cfcb96c3363655836083da4d6a4bc50b15740dcea0e6a6db056.jpg)

To display a 32\*32 pixel “A”, we can divide a 32\*32 “A” into 416\*16 sub bitmap, 1, 2, 3, 4, then create a OSD frame containing 2 (or 4) OSD string:

# 2 OSD string frame

X1, Y1, address1, address 2, 0x0000, X3, Y3, address 3, address 4, 0x0000, 0xAAAA

# 4 OSD string frame

X1, Y1, address1, 0x0000, X2, Y2, address 2, X3, Y3, address 3, X4, Y4, address 4, 0x0000, 0xAAAA

# Notes:

Xn, Yn means the 1, 2, 3, 4 sub bitmap's X,Y position, for example, sub bitmap 1's X/Y is (0,0), sub bitmap 3's X/Y is (0,1)
- Address[n] means 1,2,3,4 sub bitmap's address in firmware, this address is decided when bitmap is downloaded.
32\*32 bitmap are software features, customer application should know the bitmap address map in firmware and create the corresponding OSD frame which contains multiple OSD string, with corresponding X/Y value. The Avstream driver only provides API functions to download bitmap and write OSD frames to the firmware.

# OSD features in Demo application

Customer scan develop their own font bitmap for their certain application.

We provided the following features by providing 6 demo font files:

Eng16\_1.osd 16\*16 ASCII characters, default color

Eng16\_2.osd 16\*16 ASCII characters, customized color

Eng\_hollow.osd 32\*32 ASCII characters, two colors (body/boarder)

Chn16\_1.osd 16\*16 Chinese characters, default

Chn16\_2.osd 16\*16 Chinese characters, customized color

Chn\_hollow.osd 32\*32 Chinese characters, two colors (body/

# boarder)

▶ Basic font bitmap display

▷ 16\*16 bitmap size, customer defined font style and size
▷ Customer defined alpha blending level and YUV (Can be converted to RGB) color
▷ Single OSD string in OSD frame

▶ Advanced font bitmap display

32\*32 bitmap size, customer defined font style and size, which is simulated by software, to display the 4 sub-bit-maps for composing 32\*32 bitmap.
▶ Multiple OSD strings in OSD frame
▷ Hollow font with different colors between font boarder and body.

# OSD Data Structure

A filter interface (IOSD) is described to use OSD, through this interface, upper application send structured OSD frame to driver, driver writes the frame to the firmware. OSD data structure is defined as following fields:

#define MAX OSDSTRING\_LEN 96

typedef struct

{

unsigned short TotalLength; //Total length of OSD frame

unsigned short text[MAX OSDSTRING\_LEN]; //OSD frame

} OSDTextoutInfo;

# 3 Windows API Functions

# 3.1 Introduction to Windows API Functions

The Application Program Interface (API) functions are based on DirectX 9.0. DirectX 9.0 need to be installed, and then the API functions can work.

The main goal of API functions is to simplify the programming. DirectShow is good at developing media stream program. DirectX SDK is a powerful developer kit and provides many programming interfaces to developer. But most applications don't need the full range of DirectShow's capabilities; in fact, very few do. The API Functions reduce the interfaces and pack them to easy understanding functions. These functions are dedicated to PCI-MPG24. Users can use them to develop applications under Visual C++, Visual Basic, C++ Builder, and Delphi.

# 3.2 Function List

Some key words in the following table mean:

Preview: Displays video images coming from ‘ADLINK Bt878 Video Capture’ device.

Encoder: Saves media samples into a file. The media data come from 'ADLINK Hardware MPEG4 Device' device and its format is MPEG4.

PlayFile: Display images from a video file.

<table><tr><td>Category</td><td>Section</td><td>Function</td></tr><tr><td rowspan="6">System</td><td rowspan="6">3.4</td><td>Mpg24_PreviewOpen(CardNo)</td></tr><tr><td>Mpg24_PreviewClose(CardNo)</td></tr><tr><td>Mpg24_EncoderOpen(CardNo, PortNo)</td></tr><tr><td>Mpg24_EncoderClose(CardNo, PortNo)</td></tr><tr><td>Mpg24_PlayFileClose(Index)</td></tr><tr><td>Mpg24_ReadSerial(CardNo, HighByte, LowByte)</td></tr><tr><td rowspan="15">Configuration</td><td rowspan="15">3.5</td><td>Mpg24_PreviewGetImageRange(CardNo, Property, Min, Max, SteppingDelta, Default)</td></tr><tr><td>Mpg24_PreviewSetImageConfig(CardNo, Property, Value)</td></tr><tr><td>Mpg24_PreviewGetImageConfig(CardNo, Property, Value)</td></tr><tr><td>Mpg24_PreviewSetVideoFormat(CardNo, FormatIndex, Value)</td></tr><tr><td>Mpg24_PreviewGetVideoFormat(CardNo, FormatIndex, Value)</td></tr><tr><td>Mpg24_PreviewSetDisplay(CardNo, Handle, X, Y, AutoShow)</td></tr><tr><td>Mpg24_PreviewSetCustomSize(CardNo, Width, Height)</td></tr><tr><td>Mpg24_EncoderGetImageRange(CardNo, PortNo, Property, Min, Max, SteppingDelta, Default)</td></tr><tr><td>Mpg24_EncoderSetImageConfig(CardNo, PortNo, Property, Value)</td></tr><tr><td>Mpg24_EncoderGetImageConfig(CardNo, PortNoProperty, Value)</td></tr><tr><td>Mpg24_EncoderSetVideoFormat(CardNo, PortNo, FormatIndex, Value)</td></tr><tr><td>Mpg24_EncoderGetVideoFormat(CardNo, PortNo, FormatIndex, Value)</td></tr><tr><td>Mpg24_EncoderSetFile(CardNo, PortNo, FileName)</td></tr><tr><td>Mpg24_PlayFileSetFile(Index, FileName)</td></tr><tr><td>Mpg24_PlayFileSetDisplay(Index, Handle, X, Y, Width, Height, AutoShow)</td></tr><tr><td rowspan="14">Action</td><td rowspan="14">3.6</td><td>Mpg24_PreviewRun(CardNo)</td></tr><tr><td>Mpg24_PreviewPause(CardNo)</td></tr><tr><td>Mpg24_PreviewStop(CardNo)</td></tr><tr><td>Mpg24_PreviewSavelmage(CardNo, FileName)</td></tr><tr><td>Mpg24_PreviewSelectChannel(CardNo, PortNo, Mode)</td></tr><tr><td>Mpg24_PreviewShow(CardNo, Visible)</td></tr><tr><td>Mpg24_EncoderSetOSD(CardNo, PortNo, OSDText, Len)</td></tr><tr><td>Mpg24_EncoderRun(CardNo, PortNo)</td></tr><tr><td>Mpg24_EncoderStop(CardNo, PortNo)</td></tr><tr><td>Mpg24_PlayFileRun(Index)</td></tr><tr><td>Mpg24_PlayFilePause(Index)</td></tr><tr><td>Mpg24_PlayFileStop(Index)</td></tr><tr><td>Mpg24_PlayFileShow(Index, Visible)</td></tr><tr><td>Mpg24_PlayFileSavelmage(Index, FileName)</td></tr><tr><td rowspan="4">Watchdog</td><td rowspan="4">3.7</td><td>Mpg24_WatchdogConfig(CardNo, TriggerInterval)</td></tr><tr><td>Mpg24_WatchdogEnable(CardNo)</td></tr><tr><td>Mpg24_WatchdogDisable(CardNo)</td></tr><tr><td>Mpg24_WatchdogTrigger(CardNo)</td></tr><tr><td rowspan="4">IO</td><td rowspan="4">3.8</td><td>Mpg24_SetGPIO(CardNo, PortNo, Status)</td></tr><tr><td>Mpg24_GetGPIO(CardNo, PortNo, Status)</td></tr><tr><td>Mpg24_WriteEEPROM(CardNo, Offset, Value)</td></tr><tr><td>Mpg24_ReadEEPROM(CardNo, Offset, Value)</td></tr><tr><td rowspan="7">Misc.</td><td rowspan="7">3.9</td><td>Mpg24_PreviewCallback(CardNo, CallbackProc)</td></tr><tr><td>Mpg24_PreviewGetStatus(CardNo, Status)</td></tr><tr><td>Mpg24_EncoderCallback(CardNo, PortNo, CallbackProc)</td></tr><tr><td>Mpg24_EncoderGetStatus(CardNo, PortNo, Status)</td></tr><tr><td>Mpg24_PlayFileCallback(Index, CallbackProc)</td></tr><tr><td>Mpg24_PlayFileGetStatus(Index, Status)</td></tr><tr><td>Mpg24_GetLastErrorInfo(ErrorInfo)</td></tr></table>

# 3.3 Setting Up the Build Environment

# Include Files

All applications using the APIs need include the file shown the following table.

<table><tr><td>Include File</td><td>Description</td></tr><tr><td>PCI_MPG24.h</td><td>The header file required for all C/C++ applications.</td></tr><tr><td>PCI_MPG24.bas</td><td>The function definitions required for all VB applications.</td></tr></table>

These files are located on the directory [Program Files]\ADLINK\PCI-MPG24\Include\.

# Library File

All C/C++ applications using the APIs need the library file shown in the following table.

<table><tr><td>Library File</td><td>Description</td></tr><tr><td>PCI_MPG24.lib</td><td>Exports API function definitions. Required for all C/C++ applications.</td></tr></table>

These files are located on the directory [Program Files]\ADLINK\PCI-MPG24\Include\.

# DLL Files

All applications using the APIs need the DLL file shown in the following table.

<table><tr><td>Library File</td><td>Description</td></tr><tr><td>PCI_MPG24.dll</td><td>Dynamic link library. Required for all applications.</td></tr></table>

These files are located on the directory [WINDOWS]\system32\.

# 3.4 System Functions

# Mpg24\_PreviewOpen(CardNo)

# Mpg24\_EncoderOpen(CardNo, PortNo)

The Open function initialize the device and open it for later use. Application need call this function before using any other functions. One device only can be opened once before you close it.

There is no Mpg24\_PlayFileOpen() function. The system will automatically allocate the resources when application call other PlayFile functions.

# Syntax

C/C++

```txt
int Mpg24_PreviewOpen(short CardNo)
int Mpg24_EncoderOpen(short CardNo, short PortNo)
```

VB

```txt
Mpg24_ PreviewOpen (ByVal CardNo as Integer) as Long
Mpg24_ EncoderOpen (ByVal CardNo as Integer, ByVal PortNo as Integer) as Long
```

Delphi

```txt
Mpg24_PreviewOpen(CardNo:Smallint):Smallint
Mpg24_EncoderOpen(CardNo:Smallint, PortNo:Smallint) : Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

PortNo: The video input channel which value is between 0 and 3.

# Return Value

0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_PreviewClose(CardNo)

# Mpg24\_EncoderClose(CardNo, PortNo)

# Mpg24\_PlayFileClose(Index)

The Close function closes the opened device and release the resources the device occupied.

# Syntax

# C/C++

int Mpg24\_PreviewClose(short CardNo)
int Mpg24\_EncoderClose(short CardNo, short PortNo)

# VB

Mpg24\_ PreviewClose (ByVal CardNo as Integer) as Long

Mpg24\_ EncoderClose (ByVal CardNo as Integer, ByVal PortNo as Integer) as Long

# Delphi

Mpg24\_PreviewClose(CardNo:Smallint):Smallint
Mpg24\_EncoderClose(CardNo:Smallint,
PortNo:Smallint) : Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

PortNo: The video input channel which value is between 0 and 3.

Index: The index of playing back file which value is between 0 and 15.

# Return Value

0 : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_ReadSerial(CardNo, HighByte, LowByte)

The ReadSerial function reads the unique 48 bits serial number. Each PCI-MPG24 has a ROM what stores a unique serial number. Application can check this number to enable your software function.

# Syntax

C/C++

int Mpg24\_ReadSerial(short CardNo,UINT \*High-Byte,UINT \*LowByte)

VB

Mpg24\_ReadSerial(ByVal CardNo as Integer, ByRef HighByte as Long, ByRef LowByte as Long) as Long

Delphi

Mpg24\_ReadSerial(CardNo:Smallint, Var HightByte:Longint, Var LowByte:Longint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

HighByte: The upper 16-bit of serial number.
LowByte: The lower 32-bit of serial number.

# Return Value

0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# 3.5 Configuration Functions

# Mpg24\_PreviewGetImageRange(CardNo, Property, Min, Max, SteppingDelta, Default)

# Mpg24\_EncoderGetImageRange(CardNo, PortNo, Property, Min, Max, SteppingDelta, Default)

The GetImageRange function retrieves the range and default value of a specified video property such as brightness, contrast, hue, saturation, gamma, and sharpness.

# Syntax

C/C++
```txt
int Mpg24_PreviewGetImageRange(short CardNo, int Property, int *Min, int *Max, int *SteppingDelta, int *Default)
int Mpg24_EncoderGetImageRange(short CardNo, short PortNo, int Property, int *Min, int *Max, int *SteppingDelta, int *Default)
```
VB

```txt
Mpg24_PreviewGetImageRange(ByVal CardNo As Integer, ByVal Property As Long, ByRef Min As Long, ByRef Max As Long, ByRef SteppingDelta As Long, ByRef Default As Long) As Long
Mpg24_EncoderGetImageRange(ByVal CardNo As Integer, ByVal PortNo as Integer, ByVal Property As Long, ByRef Min As Long, ByRef Max As Long, ByRef SteppingDelta As Long, ByRef Default As Long) As Long
```
Delphi

```txt
Mpg24_PreviewGetImageRange(CardNo:Smallint, Property:Longint, Var Min :Longint, Var Max:Longint, Var SteppingDelta:Longint, Var Default:Longint):Longint
Mpg24_EncoderGetImageRange(CardNo:Smallint, PortNo:Smallint, Property:Longint, Var Min :Longint, Var Max:Longint, Var SteppingDelta:Longint, Var Default:Longint):Longint
```

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

PortNo: The video input channel which value is between 0 and 3.

# Property

&lt;table&gt;<tr><td>Property</td><td>Enum Value</td><td>Preview</td><td>Encoder</td></tr><tr><td>Brightness</td><td>0</td><td>O</td><td>O</td></tr><tr><td>Contrast</td><td>1</td><td>O</td><td>O</td></tr><tr><td>Hue</td><td>2</td><td>O</td><td>O</td></tr><tr><td>Saturation</td><td>3</td><td>O</td><td>O</td></tr><tr><td>Sharpness</td><td>4</td><td>O</td><td>O</td></tr><tr><td>Gamma</td><td>5</td><td>O</td><td>X</td></tr><tr><td>Color Enable</td><td>6</td><td>O</td><td>X</td></tr><tr><td>White Balance</td><td>7</td><td>O</td><td>X</td></tr><tr><td>Backlight Compensation</td><td>8</td><td>O</td><td>X</td></tr></table>

# O: Support, X: Not support

Min: Minimum value of the property.

Max: Maximum value of the property.

SteppingDelta: Step size for the property. The step size is the smallest increment by which the property can change.

Default: Default value of the property.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_PreviewGetImageConfig(CardNo, Property, Value)

# Mpg24\_EncoderGetImageConfig(CardNo, PortNo, Property, Value)

The GetImageConfig function retrieves video quality of a specified property.

# Syntax

# C/C++

```txt
int Mpg24_PreviewGetImageConfig(short CardNo, int Property, int *Value)
int Mpg24_EncoderGetImageConfig(short CardNo, short PortNo, int Property, int *Value)
```

# VB

```txt
Mpg24_PreviewGetImageConfig(ByVal CardNo as Integer, ByVal Property as Long, ByRef Value as Long) as Long
Mpg24_EncoderGetImageConfig(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal Property as Long, ByRef Value as Long) as Long
```

# Delphi

```txt
Mpg24_PreviewGetImageConfig(CardNo:Smallint, Property:Longint, Var Value:Longint):Longint
Mpg24_EncoderGetImageConfig(CardNo:Smallint, PortNo:Smallint, Property:Longint, Var Value:Longint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Property: Please refer to section 7.5.1 for the meaning of property.
Value: The value of the property.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewSetImageConfig(CardNo, Property, Value)

# Mpg24\_EncoderSetImageConfig(CardNo, PortNo, Property, Value)

The SetImageConfig function sets video quality of a specified property.

# Syntax

# C/C++

```txt
int Mpg24_PreviewSetImageConfig(short CardNo, int Property, int Value)
int Mpg24_EncoderSetImageConfig(short CardNo, short PortNo, int Property, int Value)
```

# VB

```txt
Mpg24_PreviewSetImageConfig(ByVal CardNo as Integer, ByVal Property as Long, ByVal Value as Long) as Long
Mpg24_EncoderSetImageConfig(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal Property as Long, ByVal Value as Long) as Long
```

# Delphi

```txt
Mpg24_PreviewSetImageConfig(CardNo:Smallint, Property:Longint, Value:Longint):Longint
Mpg24_EncoderSetImageConfig(CardNo:Smallint, PortNo:Smallint, Property:Longint, Value:Longint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Property:
Please refer to section 7.5.1 for the meaning of porperty.
Value: The value of the property.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewGetVideoFormat(CardNo, FormatIndex, Value)

# Mpg24\_EncoderGetVideoFormat(CardNo, PortNo, Format-Index, Value)

The GetVideoFormat function retrieves the value of a specified video configuration such as video standard, video size, and frame rate.

# Syntax

C/C++
```txt
int Mpg24_PreviewGetVideoFormat(short CardNo, short FormatIndex, short *Value)
int Mpg24_EncoderGetVideoFormat(short CardNo, short PortNo, short FormatIndex, short *Value)
```
VB

```txt
Mpg24_PreviewGetVideoFormat(ByVal CardNo as Integer, ByVal FormatIndex as Integer, ByRef Value as Integer) as Long
Mpg24_EncoderGetVideoFormat(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal FormatIndex as Integer, ByRef Value as Integer) as Long
```
Delphi

```txt
Mpg24_PreviewGetVideoFormat(CardNo:Smallint, FormatIndex:Smallint, Var Value:Smallint):Longint
Mpg24_EncoderGetVideoFormat(CardNo:Smallint, PortNo:Smallint, FormatIndex:Smallint, Var Value:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

```txt
PortNo: The video input channel which value is between 0 and 3.
```

FormatIndex:

&lt;table&gt;<tr><td rowspan="2">Type</td><td rowspan="2">Enum Value</td><td rowspan="2">Value</td><td colspan="2">Default</td></tr><tr><td>Preview</td><td>Encoder</td></tr><tr><td rowspan="2">Standard</td><td rowspan="2">0</td><td>0: NTSC</td><td rowspan="2">NTSC</td><td rowspan="2">NTSC</td></tr><tr><td>1: PAL</td></tr><tr><td>Size</td><td>1</td><td>0: FULL D11: CIF2: QCIF3: VGA4: QVGA</td><td>CIF</td><td>FULL D1(QCIF size not supported)</td></tr><tr><td>Frame Rate</td><td>2</td><td>0: 30 fps(NTSC), 25 fps(PAL)1: 15 fps(NTSC), 12.5 fps(PAL)2: 10 fps(NTSC), 8.3 fps(PAL)3: 5 fps(NTSC), 5 fps(PAL)4: 1 fps(NTSC), 1fps(PAL)</td><td>30 or 25 fps</td><td>30 or 25 fps</td></tr><tr><td>Target Bitrate</td><td>3</td><td>0: 4M bps1: 2M bps2: 1.5M bps3: 1M bps4: 750k bps5: 500k bps6: 384k bps</td><td>Not supported</td><td>4M bps</td></tr><tr><td>Codec</td><td>4</td><td>0: DivX1: Microsoft</td><td>Not supported</td><td>DivX</td></tr></table>

# P.S. Video Size:

▶ FULL D1: 720 x 480(NTSC), 720 x 576(PAL)
▶ CIF: 352 x 240(NTSC), 352 x 288(PAL)
▶ QCIF: 176 x 144(NTSC), 176 x 144(PAL)
▶ VGA: 640 x 480(NTSC), PAL doesn't support this format.
- QVGA: 320 x 240(NTSC), PAL doesn't support this format.

Value: The value of the specified format.

# Return Value

0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_PreviewSetVideoFormat(CardNo, FormatIndex, Value)

# Mpg24\_EncoderSetVideoFormat(CardNo, PortNo, Format-Index, Value)

The SetVideoFormat function sets the value of a specified video configuration. You can't set video format while preview or encoder is running.

# Syntax

C/C++
```txt
int Mpg24_PreviewSetVideoFormat(short CardNo, short FormatIndex, short Value)
int Mpg24_EncoderSetVideoFormat(short CardNo, short PortNo, short FormatIndex, short Value)
```
VB

```txt
Mpg24_PreviewSetVideoFormat(ByVal CardNo as Integer, ByVal FormatIndex as Integer, ByVal Value as Integer) as Long
Mpg24_EncoderSetVideoFormat(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal FormatIndex as Integer, ByVal Value as Integer) as Long
```
Delphi

```txt
Mpg24_PreviewSetVideoFormat(CardNo:Smallint, FormatIndex:Smallint, Value:Smallint):Longint
Mpg24_EncoderSetVideoFormat(CardNo:Smallint, PortNo:Smallint, FormatIndex:Smallint, Value:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
FormatIndex: Please refer to section 7.5.4 for the meaning of FormatIndex.
Value: The value of the specified format.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewSetCustomSize(CardNo, Width, Height)

The SetCustomSize function sets a customizing size of video image. You also can use the Mpg24\_PreviewSetVideoFormat function to set a predefined video size.

# Syntax

C/C++

```txt
int Mpg24_PreviewSetCustomSize(short CardNo, short Width, short Height)
```

VB

```txt
Mpg24_PreviewSetCustomSize(ByVal CardNo as Integer, ByVal Width as Integer, ByVal Height as Integer) as Long
```

Delphi

```objectivec
Mpg24_PreviewSetCustomSize(CardNo:Smallint, Width:Smallint, Height:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

```txt
Width: The width of video window.
```

```txt
Height: The height of video window.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewSetDisplay(CardNo, Handle, X, Y, AutoShow)

# Mpg24\_PlayFileSetDisplay(Index, Handle, X, Y, Width, Height, AutoShow)

The SetDisplay function sets properties on the video window. Application can use it to set the window owner, the position and dimensions of the window, and automatically showing the video window.

# Syntax

C/C++
```txt
int Mpg24_PreviewSetDisplay(short CardNo, int Handle, short X, short Y, short AutoShow)
int Mpg24_PlayFileSetDisplay(short Index, int Handle, short X, short Y, short Width, short Height, short AutoShow)
```
VB

```txt
Mpg24_PreviewSetDisplay(ByVal CardNo as Integer, ByVal Handle as Long, ByVal X as Integer, ByVal Y as Integer, ByVal AutoShow as Integer) as Long
Mpg24_PlayFileSetDisplay(ByVal Index as Integer, ByVal Handle as Long, ByVal X as Integer, ByVal Y as Integer, ByVal Width as Integer, ByVal Height as Integer, ByVal AutoShow as Integer) as Long
```

Delphi
```objectivec
Mpg24_PreviewSetDisplay(CardNo:Smallint, Handle:Longint, X:Smallint, Y:Smallint, AutoShow:Smallint):Longint
Mpg24_PlayFileSetDisplay(Index:Smallint, Handle:Longint, X:Smallint, Y:Smallint, Width:Smallint, Height:Smallint, AutoShow:Smallint):Longint
```

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

```txt
Index: The index of playing back file which value is between 0 and 15.
Handle: Specifies a handle to the parent window that the video image show on it. If Handle is 0, the video image will show on a new window.
X: Sets the video window's x-coordinate.
Y: Sets the video window's y-coordinate.
Width: The width of video window.
Height: The height of video window.
AutoShow: Specifies whether the video renderer automatically shows the video window when it receives video data.
0: FALSE; Hide the video window.
other: TRUE; Show the video window.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_EncoderSetFile(CardNo, PortNo, FileName)

# Mpg24\_PlayFileSetFile(Inex, FileName)

The SetFile function sets the name of the file into which media samples will be written or from which media samples will be read.

# Syntax

# C/C++

```c
int Mpg24_EncoderSetFile(short CardNo, short PortNo, char *FileName)
int Mpg24_PlayFileSetFile(short Index, char *FileName)
```

# VB

```txt
Mpg24_EncoderSetFile(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal FileName as String) as Long
Mpg24_PlayFileSetFile(ByVal Index as Integer, ByVal FileName as String) as Long
```

# Delphi

```txt
Mpg24_EncoderSetFile(CardNo:Smallint, PortNo:Smallint, FileName:String):Longint
```

Mpg24\_PlayFileSetFile(Index:Smallint, Name:String):Longint

File-

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

PortNo: The video input channel which value is between 0 and 3.

Index: The index of playing back file which value is between 0 and 15.

FileName: The name of the media file.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# 3.6 Action Functions

# Mpg24\_PreviewRun(CardNo)

# Mpg24\_EncoderRun(CardNo, PortNo)

# Mpg24\_PlayFileRun(Index)

The Run function starts to display the video window or starts to save the media samples into a file.

# Syntax

C/C++
```txt
int Mpg24_PreviewRun(short CardNo)
int Mpg24_EncoderRun(short CardNo, short PortNo)
int Mpg24_PlayFileRun(short Index)
```
VB

```txt
Mpg24_PreviewRun(ByVal CardNo as Integer) as Long
Mpg24_EncoderRun(ByVal CardNo as Integer, ByVal PortNo as Integer) as Long
Mpg24_PlayFileRun(ByVal Index as Integer) as Long
```
Delphi

```txt
Mpg24_PreviewRun(CardNo:Smallint) :Longint
Mpg24_EncoderRun(CardNo:Smallint, PortNo:Smallint):Longint
Mpg24_PlayFileRun(Index:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Index: The index of playing back file which value is between 0 and 15.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewPause(CardNo)

# Mpg24\_PlayFilePause(Index)

The Pause function pauses playing the video window.

# Syntax

C/C++

int Mpg24\_PreviewPause(short CardNo)

int Mpg24\_PlayFilePause(short Index)

VB

Mpg24\_PreviewPause(ByVal CardNo as Integer) as Long

Mpg24\_PlayFilePause(ByVal Index as Integer) as Long

Delphi

Mpg24\_PreviewPause(CardNo:Smallint) :Longint

Mpg24\_PlayFilePause(Index:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

Index: The index of playing back file which value is between 0 and 15.

# Return Value

0 : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_PreviewStop(CardNo)

# Mpg24\_EncoderStop(CardNo, PortNo)

# Mpg24\_PlayFileStop(Index)

The Stop function stops displaying the video window or closes the saving media file.

# Syntax

# C/C++

```txt
int Mpg24_PreviewStop(short CardNo)
int Mpg24_EncoderStop(short CardNo, short PortNo)
int Mpg24_PlayFileStop(short Index)
```

# VB

```txt
Mpg24_PreviewStop(ByVal CardNo as Integer) as Long
Mpg24_EncoderStop(ByVal CardNo as Integer, ByVal PortNo as Integer) as Long
Mpg24_PlayFileStop(ByVal Index as Integer) as Long
```

# Delphi

```txt
Mpg24_PreviewStop(CardNo:Smallint) :Longint
Mpg24_EncoderStop(CardNo:Smallint, PortNo:Smallint):Longint
Mpg24_PlayFileStop(Index:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Index: The index of playing back file which value is between 0 and 15.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewShow(CardNo, Visible)

# Mpg24\_PlayFileShow(Index, Visible)

The Show function shows or hides displaying video window. This function take effect only when video window runs.

# Syntax

C/C++
```txt
int Mpg24_PreviewShow(short CardNo, short Visible)
int Mpg24_PlayFileShow(short Index, short Visible)
```
VB

```txt
Mpg24_PreviewShow(ByVal CardNo as Integer, ByVal Visible as Integer) as Long
Mpg24_PlayFileShow(ByVal Index as Integer, ByVal Visible as Integer) as Long
```

Delphi
```txt
Mpg24_PreviewShow(CardNo:Smallint, Visible:Smallint):Longint
Mpg24_PlayFileShow(Index:Smallint, Visible:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

```txt
Index: The index of playing back file which value is between 0 and 15.
```

```txt
Visible: Specifies whether to show or hide the window. The value can be:
```

```batch
0: FALSE; Hide the video window.
```

```txt
other: TRUE; Show the video window.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewSelectChannel(CardNo, PortNo, Mode)

The SelectChannel function routes the input sources to the video window.

# Syntax

# C/C++

int Mpg24\_PreviewSelectChannel(short CardNo, short PortNo, short Mode)

# VB

Mpg24\_PreviewSelectChannel(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal Mode as Integer) as Long

# Delphi

Mpg24\_PreviewSelectChannel(CardNo:Smallint, PortNo:Smallint, Mode:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

PortNo: The video input channel which value is between 0 and 3.

Mode: Specifies whether to display QUAD video or single channel video. The value can be:

0: QUAD mode; Hide the video window. The value of PortNo doesn't matter.

1: Single mode; According to the value of PortNo, shows the input source.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_PreviewSavelImage(CardNo, FileName)

# Mpg24\_PlayFileSavelImage(Index, FileName)

The Savelmage function captures one frame from the video samples and writes it to a bitmap (.bmp) file.

# Syntax

C/C++
```c
int Mpg24_PreviewSaveImage(short CardNo, char *FileName)
int Mpg24_PlayFileSaveImage(short Index, char *FileName)
```

VB
```txt
Mpg24_PreviewSaveImage(ByVal CardNo as Integer, ByVal FileName as String) as Long
Mpg24_PlayFileSaveImage(ByVal Index as Integer, ByVal FileName as String) as Long
```

Delphi
```txt
Mpg24_PreviewSaveImage(CardNo:Smallint,FileName:String):Longint
Mpg24_PlayFileSaveImage(Index:Smallint,FileName:String):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
Index: The index of playing back file which value is between 0 and 15.
FileName: The bitmap file name.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_EncoderSetOSD(CardNo, PortNo, OSDText, Len)

The SetOSD function blends text and video to the saving file.

# Syntax

# C/C++

int Mpg24\_EncoderSetOSD(short CardNo, short PortNo, BYTE \*OSDText, short Len)

# VB

Mpg24\_EncoderSetOSD(ByVal CardNo as Integer, ByVal PortNo as Integer, ByRef OSDText As Byte, ByVal Len As Integer) as Long

# Delphi

Mpg24\_EncoderSetOSD(CardNo:Smallint,
    PortNo:Smallint, Var OSDText:Byte,
    Len:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

PortNo: The video input number which value is between 0 and 3.

OSDText: The OSD string contains header, Unicode text, and EOF. Please refer to chapter 2.3 for detail description.

Len: How many words the OSD text has.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# 3.7 Watchdog Functions

# Mpg24\_WatchdogConfig(CardNo, TriggerInterval)

The WatchdogConfig function sets the maximum time that application need to re-trigger Watchdog register to prevent computer from restarting.

# Syntax

C/C++
```txt
int Mpg24_WatchdogConfig(short CardNo, short TriggerInterval)
```
VB

```txt
Mpg24_WatchdogConfig(ByVal CardNo as Integer, ByVal TriggerInterval As Integer) as Long
```
Delphi

```txt
Mpg24_WatchdogConfig(CardNo:Smallint, Trigger-Interval:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

```txt
TriggerInterval: The trigger time. The value can be:
```

▷ 0: 0 second; Reset computer immediately.
▷ 1: 8 seconds
▷ 2: 16 seconds
▷ 3: 32 seconds

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_WatchdogEnable(CardNo)

The WatchdogEnable function enables watch dog.

# Syntax

C/C++

int Mpg24\_WatchdogEnable(short CardNo)

VB

Mpg24\_WatchdogEnable(ByVal CardNo as Integer) as Long

Delphi

Mpg24\_WatchdogEnable(CardNo:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_WatchdogDisable(CardNo)

The WatchdogDisable function disables watch dog.

# Syntax

# C/C++

int Mpg24\_WatchdogDisable(short CardNo)

# VB

Mpg24\_WatchdogDisable(ByVal CardNo as Integer) as Long

# Delphi

Mpg24\_WatchdogDisable(CardNo:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_WatchdogTrigger(CardNo)

The WatchdogTrigger function triggers watch dog to prevent computer from restarting.

# Syntax

# C/C++

int Mpg24\_WatchdogTrigger(short CardNo)

# VB

Mpg24\_WatchdogTrigger(ByVal CardNo as Integer) as Long

# Delphi

Mpg24\_WatchdogTrigger(CardNo:Smallint):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# 3.8 IO Functions

# Mpg24\_SetGPIO(CardNo, PortNo, Status)

The SetGPIO function sets the GPIO pin to high voltage or low voltage.

# Syntax

C/C++

```c
int Mpg24_SetGPIO(short CardNo, short PortNo, BYTE Status)
```

VB

```txt
Mpg24_SetGPIO(ByVal CardNo as Integer, ByVal PortNo as Integer, ByVal Status as Byte) as Long
```

Delphi

```objectivec
Mpg24_SetGPIO(CardNo:Smallint, PortNo:Smallint, Status:Byte):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
```

```txt
PortNo: The GPIO number which value is between 0 and 3.
```

```txt
Status: Sets the voltage level of output pin. The vale is:
```

```txt
0: Low voltage
```

```txt
1: High voltage
```

# Return Value

```txt
O : No error.
```

```txt
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_GetGPIO(CardNo, PortNo, Status)

The GetGPIO function retrieves the status of GPIO pin.

# Syntax

# C/C++

```c
int Mpg24_GetGPIO(short CardNo, short PortNo, BYTE *Status)
```

# VB

```txt
Mpg24_GetGPIO(ByVal CardNo as Integer, ByVal PortNo as Integer, ByRef Status as Byte) as Long
```

# Delphi

```txt
Mpg24_GetGPIO(CardNo:Smallint, PortNo:Smallint, Var Status:Byte):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The GPIO number which value is between 0 and 3.
Status: The voltage level of output pin. The vale is:
0: Low voltage
1: High voltage
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_WriteEEPROM(CardNo, Offset, Value)

The WriteEEPROM function writes the onboard EEPROM.

# Syntax

C/C++

int Mpg24\_WriteEEPROM(short CardNo, BYTE Offset, BYTE Value)

VB

Mpg24\_WriteEEPROM(ByVal CardNo as Integer, ByVal Offset as Byte, ByVal Value as Byte) as Long

Delphi

Mpg24\_WriteEEPROM(CardNo:Smallint, Offset:Byte, Value:Byte):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

Offset: The address in EEPROM which value is between 0 and 127.

Value: The value of the address which value is between 0 and 255.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# Mpg24\_ReadEEPROM(CardNo, Offset, Value)

The WriteEEPROM function read the value of onboard EEPROM.

# Syntax

# C/C++

int Mpg24\_ReadEEPROM(short CardNo, BYTE Offset, BYTE \*Value)

# VB

Mpg24\_ReadEEPROM(ByVal CardNo as Integer, ByVal Offset as Byte, ByRef Value as Byte) as Long

# Delphi

Mpg24\_ReadEEPROM(CardNo:Smallint, Offset:Byte, Var Value:Byte):Longint

# Parameters

CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

Offset: The address in EEPROM which value is between 0 and 127.

Value: The value of the address which value is between 0 and 255.

# Return Value

O : No error.

&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.

# 3.9 Miscellaneous Functions

# Mpg24\_PreviewCallback(CardNo, CallbackProc)

# Mpg24\_EncoderCallback(CardNo, PortNo, CallbackProc)

# Mpg24\_PlayFileCallback(Index, CallbackProc)

The Callback function sets which procedure to be called when the frame data ready. User need write a callback procedure following the predefined format.

# Syntax

C/C++
```txt
int Mpg24_PreviewCallback(short CardNo, void (_stdcall *CallbackProc)(BYTE * pBuffer, int lBufferSize))
int Mpg24_EncoderCallback(short CardNo, short PortNo, void (_stdcall *CallbackProc)(BYTE * pBuffer, int lBufferSize))
int Mpg24_PlayFileCallback(short Index, void (_stdcall *CallbackProc)(BYTE * pBuffer, int lBufferSize))
```
VB

```txt
Mpg24_PreviewCallback(ByVal CardNo As Integer, ByVal CallbackProc As Long) as Long
Mpg24_EncoderCallback(ByVal CardNo As Integer, ByVal PortNo As Integer, ByVal CallbackProc As Long) as Long
Mpg24_PlayFileCallback(ByVal Index As Integer, ByVal CallbackProc As Long) as Long
```
Delphi

```txt
Mpg24_PreviewCallback(CardNo:Smallint, CallbackProc:CallbackFunc):Longint
Mpg24_EncoderCallback(CardNo:Smallint, PortNo:Smallint    CallbackProc:CallbackFunc):Longint
Mpg24_PlayFileCallback(Index:Smallint, CallbackProc:CallbackFunc):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip
```

```txt
switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Index: The index of playing back file which value is between 0 and 15.
CallbackProc: The prototype of the callback function is CallbackProc(BYTE * pBuffer, int lBufferSize).
pBuffer: The pointer of frame data.
lBufferSize: The size of frame data.
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_PreviewGetStatue(CardNo, Status)

# Mpg24\_EncoderGetStatus(CardNo, PortNo, Status)

# Mpg24\_PlayFileGetStatus(Index, Status)

The GetStatus function retrieves the status – running, paused, or stopped and detects the state of signal input – video present or video loss.

# Syntax

C/C++
```txt
int Mpg24_PreviewGetStatus(short CardNo, short *Status)
int Mpg24_EncoderGetStatus(short CardNo, short PortNo, short *Status)
int Mpg24_PlayFileGetStatus(short Index, short *Status)
```
VB

```txt
Mpg24_PreviewGetStatus(ByVal CardNo As Integer, ByRef Status As Integer) as Long
Mpg24_EncoderGetStatus(ByVal CardNo As Integer, ByVal PortNo As Integer, ByRef Status As Integer) as Long
Mpg24_PlayFileGetStatus(ByVal Index As Integer, ByRef Status As Integer) as Long
```

# Delphi

```txt
Mpg24_PreviewGetStatus(CardNo:Smallint, Var Status:Smallint):Longint
Mpg24_EncoderGetStatus(CardNo:Smallint, PortNo:Smallint Var Status:Smallint):Longint
Mpg24_PlayFileGetStatus(Index:Smallint, Var Status:Smallint):Longint
```

# Parameters

```txt
CardNo: The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Index: The index of playing back file which value is between 0 and 15.
Status: The Value can be:
Bit 0-1: 0: stopped, 1: paused, 2: running
Bit 2: 0: video loss, 1: video present
```

# Return Value

```txt
0 : No error.
&lt;0 : Error occurred. Please see section 3.10 for the detail description of error code.
```

# Mpg24\_GetLastErrorInfo(ErrorInfo)

The GetLastErrorInfo function retrieves the last error message.

# Syntax

C/C++

```txt
int Mpg24_GetLastErrorInfo(TCHAR *ErrorInfo)
```

# Parameters

```txt
ErrorInfo: The last error message. Please refer to section 3.10 for detailed.
```

# Return Value

```txt
O : No error.
E_UNKNOWN_ERROR : Please see section 3.10 for the detail description of error code.
```

# 3.10 Error Codes

When application gets a non-zero code, you can query its meaning from below table.

&lt;table&gt;<tr><td>Error constant</td><td>Value</td><td>Description</td></tr><tr><td></td><td>0</td><td>No error.</td></tr><tr><td>E_INVALID_ARGUMENT</td><td>-1</td><td>Invalid argument. Maybe wrong CardNo , wrong PortNo, or the arguments exceed its range.</td></tr><tr><td>E_IN_USE</td><td>-2</td><td>This device is already in use. You need to close it and then you can use it again.</td></tr><tr><td>E_DEVICE_NOT_FOUND</td><td>-3</td><td>Can&#x27;t find this device.</td></tr><tr><td>E_DEVICE_NOT_READY</td><td>-4</td><td>Device is not initialized.</td></tr><tr><td>E_FILE_NOT_FOUND</td><td>-5</td><td>This file cannot be found.</td></tr><tr><td>E_DIRECTX_NOT_INSTALL</td><td>-6</td><td>DirectX Runtime or DirectX SDK doesn&#x27;t be installed.</td></tr><tr><td>E_UNKNOWN_FORMAT</td><td>-7</td><td>The video format is not the predefined one that the error is returned by callingMpg24_xxxxGetVideoFormat function.xxxx is Preview or Encoder.</td></tr><tr><td>E_SERIAL_READ</td><td>-8</td><td>Error occurs when read the serial number.</td></tr><tr><td>E_NON_STOP</td><td>-9</td><td>Cannot set video format while running.</td></tr><tr><td>E_DIRTECTX_INTERNAL</td><td>-10</td><td>Other error. Please call Mpg24_LastErrorInfo function to get the error message.</td></tr><tr><td>E_UNKNOWN_ERROR</td><td>-11</td><td>This is an unknown error.</td></tr></table>

# 4 ActiveX Control

# 4.1 PCI-MPG24 ActiveX Control Introduction

The PCI-MPG24 ActiveX Control (ocx) are based on API library and DirectX 9.0. PCI\_MPG24.dll and DirectX 9.0 need to be installed, and then the ActiveX Control can work.

ActiveX control is a reusable object what includes visual elements and codes. It can be used in many different container applications such as VB application, MS Office document, and web pages. PCI-MPG24 ActiveX control has two components in it, MPG24Preview and MPG24Encoder. They implement almost all ability of preview and encoder API functions.

# 4.2 Setting Up the Build Environment

All applications using the ActiveX control need the OCX file shown in the following table.

<table><tr><td>Library File</td><td>Description</td></tr><tr><td>PCI_MPG24.ocx</td><td>PCI-MPG24 ActiveX control. Required for all applications.</td></tr></table>

The file is located on [WINDOWS]\system32\.

If you are a VB user, please add this file into your VB project. The component name is 'ADLink PCI-MPG24 ActiveX Control'. After you add the control into your project, there are two controls, MPG24Preview and MPG24Encoder, on VB toolbox.

If you are a HTML user, add the following code to your HTML page:

```html
&lt;OBJECT ID="MPG24Preview"
CLASSID="CLSID:70B4054C-CC5B-435F-B0F4-A7A12F9238C2"
CODEBASE="PCI_MPG24.OCX#version=1,2,0,0"&gt;
&lt;/OBJECT&gt;
&lt;OBJECT ID="MPG24Encoder"
CLASSID="CLSID:476167C5-8310-4209-8039-E1E71A3C6971"
CODEBASE="PCI_MPG24.OCX#version=1,2,0,0"&gt;
```

&lt;/OBJECT&gt;

# 4.3 Properties and Methods

# Preview control

# Property:

CardNo, Brightness, Contrast, Hue, Saturation, Sharpness, Gamma, ColorEnable, WhiteBalance, BacklightCompensation, VideoStandard, VideoSize, FrameRate, AutoShow, Status, DI0, DI1, DI2, DI3, DO0, DO1, DO2, DO3, Show, CustomWidth, CustomHeight

# Method:

OpenDevice(), CloseDevice(), GetImageRange(Property, Max, Min, SteppingDelta, Default), Play(), PausePlay(), StopPlay(), SetCallback(CallbackProc), SaveImage(FileName), WriteEEPROM(Offset, Value), ReadEEPROM(Offset), ReadSerial(HighByte, LowByte)

# Meaning

CardNo: A read/write integer value. The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.

Brightness: A read/write long value. Default value is 750.

Contrast: A read/write long value. Default value is 100.

Hue: A read/write long value. Default value is 100.

Saturation: A read/write long value. Default value is 100.

Sharpness: A read/write long value. Default value is 50.

Gamma: A read/write long value. Default value is 140.

ColorEnable: A read/write boolean value. Default value is true.

WhiteBalance: A read/write long value. Default value is 0.

```txt
BacklightCompensation: A read/write boolean value. Default value is true.
VideoStandard: A read/write integer value. Default value is 0. The value can be:
▷ 0 - NTSC
▷ 1 - PAL
VideoSize: A read/write integer value. Default value is 1. The value can be:
▷ 0 - FULL D1
▷ 1 - CIF
▷ 2 - QCIF
▷ 3 - VGA
▷ 4 - QVGA
▷ 5 - Custom (The size depends on CustomWidth and CustomHeight)
```

Please refer to chapter 3.5 for the value of video size.

```txt
FrameRate: A read/write integer value. Default value is 0. The value can be:
▷ 0 - NTSC_30fps or PAL_25fps
▷ 1 - NTSC_15fps
▷ 2 - NTSC_10fps
▷ 3 - NTSC_5fps
AutoShow: A read/write boolean value. Default value is true. Specifies whether the video renderer automatically shows the video window when it receives video data.
Status: A read only integer value. The Value can be:
Bit 0-1: 0: stopped, 1: paused, 2: running
Bit 2: 0: video loss, 1: video present
DI0~DI3: Read only boolean values. A digital input.
DO0~DO3: Read only boolean values. Default value is false. A digital output.
Show: A read/write boolean value. Default value is true. Shows/Hides video window.
```

CustomWidth: A read/write integer value. Default value is 352. Sets the width of video window.

CustomHeight: A read/write integer value. Default value is 240. Sets the height of video window.

OpenDevice() as Long: Initializes the device and opens it for later use. Application need call this function before using any other methods. One device only can be opened once before you close it. This function returns an error code.

CloseDevice() as Long: Closes the opened device and releases the resources it occupied. This function returns an error code.

GetImageRange(Property As Long, ByRef Min As Long, ByRef Max As Long, ByRef SteppingDelta As Long, ByRef Default As Long) As Long: The GetImageRange function retrieves the range and default value of a specified video property such as brightness, contrast, hue, saturation, gamma, and sharpness. This function returns an error code.

# Please refer to chapter 3.5 for the meaning of arguments.

Play() as Long: Starts to display the video window. This function returns an error code.

PausePlay() as Long: Pauses displaying the video window. This function returns an error code.

StopPlay() as Long: Stops displaying the video window. This function returns an error code.

SetCallback(CallbackProc As Long) As Long: Sets which procedure to be called when the frame data ready. User need write a callback procedure following the predefined format. This function returns an error code. The prototype of the callback function is CallbackProc(ByRef pBuffer as Byte, ByVal lBufferSize as Long).

pBuffer: The buffer of frame data.

lBufferSize: The size of frame data.

SaveImage(FileName As String) As Long: Captures one frame from the video samples and writes

it to a bitmap (.bmp) file. This function returns an error code.
ReadEEPROM(Offset As Byte) As Byte: This function return the offset address value of the on-board EEPROM.
WriteEEPROM(Offset As Byte, Value As Byte) As Long: Writes a value to offset address of the on-board EEPROM. This function returns an error code.
ReadSerial(ByRef HighByte As Long, ByRef LowByte As Long) As Long: This function reads the unique 48 bits serial number. Each PCI-MPG24 has a ROM what stores a unique serial number. The function stores the number at the two variables, HighByte and LowByte, and returns an error code. HighByte is the upper 16-bit of serial number. LowByte is the lower 32-bit of serial number.

Please refer to 3.10 for the meaning of error code.

# Encoder Control

# Property:

CardNo, PortNo, Brightness, Contrast, Hue, Saturation, Sharpness, VideoStandard, VideoSize, FrameRate, TargetBitrate, MPEG4Mode, FileName, Status

# Method:

OpenDevice(), CloseDevice(), GetImageRange(Property, Max, Min, SteppingDelta, Default), Play(), StopPlay(), SetCallback(CallbackProc)

# Meaning

CardNo: A read/write integer value. The card ID which value is between 0 and 7. The card ID can be got from S1 dip switch. Please refer to Hardware Reference chapter.
PortNo: The video input channel which value is between 0 and 3.
Brightness: A read/write long value. Default value is 32.

```txt
Contrast: A read/write long value. Default value is 57.
Hue: A read/write long value. Default value is 0.
Saturation: A read/write long value. Default value is 50.
Sharpness: A read/write long value. Default value is 14.
VideoStandard: A read/write integer value. Default value is 0. The value can be:
▷ 0 - NTSC
▷ 1 - PAL
VideoSize: A read/write integer value. Default value is 3. The value can be:
▷ 0 - FULL D1
▷ 1 - CIF
▷ 2 - QCIF (Not support)
▷ 3 - VGA
▷ 4 - QVGA
▷ 5 - Custom (Not support)
```
Please refer to chapter 3.5 for the value of video size.

```yaml
FrameRate: A read/write integer value. Default value is 0. The value can be:
▷ 0 - NTSC_30fps or PAL_25fps
▷ 1 - NTSC_15fps
▷ 2 - NTSC_10fps
▷ 3 - NTSC_5fps
TargetBitrate: A read/write integer value. Default value is 0. The value can be:
▷ 0 - Bitrate_4M
▷ 1 - Bitrate_2M
▷ 2 - Bitrate_1500K
▷ 3 - Bitrate_1M
▷ 4 - Bitrate_750K
▷ 5 - Bitrate_500K
▷ 6 - Bitrate_384K
```

MPEG4Mode: A read/write integer value. Default value is 0. The value can be:

▷ 0 - DivX-Codec
▷ 1 - Microsoft\_Codec

FileName: A read only integer value. sets the name of the file into which media samples will be written.

Status: A read only integer value. The Value can be:

Bit 0-1: 0: stopped, 1: paused, 2: running

Bit 2: 0: video loss, 1: video present

OpenDevice() as Long: Initializes the device and opens it for later use. Application need call this function before using any other methods. One device only can be opened once before you close it. This function returns an error code.

CloseDevice() as Long: Closes the opened device and releases the resources it occupied. This function returns an error code.

GetImageRange(Property As Long, ByRef Min As Long, ByRef Max As Long, ByRef SteppingDelta As Long, ByRef Default As Long) As Long: The GetImageRange function retrieves the range and default value of a specified video property such as brightness, contrast, hue, saturation, gamma, and sharpness. This function returns an error code.

Please refer to chapter 3.5 for the meaning of arguments.

Play() as Long: Starts to display the video window. This function returns an error code.

StopPlay() as Long: Stops displaying the video window. This function returns an error code.

SetCallback(CallbackProc As Long) As Long: Sets which procedure to be called when the frame data ready. User need write a callback procedure following the predefined format. This function returns an error code.

The prototype of the callback function is Call-backProc(ByRef pBuffer as Byte, ByVal lBufferSize as Long).

pBuffer: The buffer of frame data.

lBufferSize: The size of frame data.

Please refer to 3.10 for the meaning of error codes.

# 5 Linux Programming Guide

# 5.1 Overview

PCI-MPG24 Linux SDK is a LINUX 2.6.9 based video capture and MPEG encoder development package. It includes different levels of APIs and objects and developers can use different interface to meet user's requirements.

The PCI-MPG24 software includes the following different level interfaces:

# Preview:

▶ Video4Linux: Providing a SDK for video capture/overlay. Please refer to the document of Video for Linux API. You can download this manual from http://linux.bytesex.org/v4l2/
▶ V4lsample: An application developed on and distributed with LINUX SDK. This application is developed based on Video for Linux Two API.

# Encoder:

▶ CVideoCapture: Providing an interface separating server from encoder driver. This interface enables an application to invoke I/O actions on an instance of a videocapture through an I/O packet.
▶ Go-server: An application developed on and distributed with LINUX SDK. This application is developed based on CServer. It can be discarded or customized if users want to develop their own application.

# 5.2 Encoder Linux SDK Architecture

This chapter describes the architecture of Encoder Linux SDK. First, we introduce the application based on Encoder Linux SDK; then describe the Data Flow Diagram (DFD) of Encoder Linux SDK.

# Application on Encoder LINUX SDK

Application is a user application implemented by customer.

![The diagram displays a system architecture with the following labeled blocks and connections:\n\n**Blocks:**\n*   MPEG File\n*   Graph Editor\n*   Application\n*   Go-Client\n*   Linux SDK\n*   Linux USB Interface\n*   WIS Board\n\n**Connections:**\n*   **MPEG File** points downward to **Graph Editor**.\n*   **Application** points leftward to **MPEG File** via an arrow labeled 'Saved file'.\n*   **Application** points rightward to **Go-Client** via an arrow labeled 'Ethernet Packet'.\n*   **Linux SDK** points upward to **Application** via an arrow labeled 'Stream'.\n*   **Application** points downward to **Linux SDK** via an arrow labeled 'Para_value'.\n*   **Linux SDK** points downward to **Linux USB Interface** via an arrow labeled 'Para_value'.\n*   **Linux USB Interface** points upward to **Linux SDK** via an arrow labeled 'Stream'.\n*   **WIS Board** points upward to **Linux USB Interface** via an arrow labeled 'Stream'.\n*   **Linux USB Interface** points downward to **WIS Board** via an arrow labeled 'USB Packet'.](.pci-mpg24-manual-18/5abb7a79ebe57fd5bea58d768eb0e6490c4b673c8649d966662a82b485ba8775.jpg)

Figure 5-1: Application Based on LinuxSDK

# DFD of Encoder LINUX SDK

The following graph describes the DFD of Encoder Linux SDK. User can use different level APIs to implement their own application according to their requirement.

![Based on the provided image, here is the description of the flowchart blocks and connections:\n\n**Blocks:**\n*   CLI\n*   CServer\n*   CVideoCapture\n*   Linux I/O Interface\n*   WIS Go Driver\n*   FFMPEG APIs\n*   Player\n*   A/V File\n*   USB Base\n*   Board Module\n*   I2C I/O\n*   Linux USB Interface\n*   WIS Board\n\n**Connections:**\n*   **CLI** connects to **CServer** via an arrow labeled 'Command, Value'.\n*   **CServer** connects to **CVideoCapture** via an arrow labeled 'Command, Value'.\n*   **CVideoCapture** connects back to **CServer** via an arrow labeled 'Stream'.\n*   **CServer** connects to **FFMPEG APIs** via an arrow labeled 'CODEC Command, File name'.\n*   **FFMPEG APIs** connects to **Player** via an arrow labeled 'Ethernet Packet'.\n*   **FFMPEG APIs** connects to **A/V File** via an arrow labeled 'A/V stream'.\n*   **CVideoCapture** connects to **Linux I/O Interface** via an arrow labeled 'I/O packet'.\n*   **Linux I/O Interface** connects back to **CVideoCapture** via an arrow labeled 'Stream'.\n*   **Linux I/O Interface** connects to **WIS Go Driver** via an arrow labeled 'I/O packet'.\n*   **WIS Go Driver** connects back to **Linux I/O Interface** via an arrow labeled 'Stream'.\n*   **WIS Go Driver** connects to **USB Base** via an arrow labeled 'Config USB Packet'.\n*   **USB Base** connects back to **WIS Go Driver** via an arrow labeled 'Stream'.\n*   **USB Base** connects to **Linux USB Interface** via a downward arrow.\n*   **Linux USB Interface** connects to **WIS Board** via a downward arrow.\n*   **WIS Board** connects back to **Linux USB Interface** via an arrow labeled 'Stream'.\n*   **WIS Go Driver** connects to **Board Module** via an arrow labeled 'value'.\n*   **Board Module** connects to **I2C I/O** via an arrow labeled 'Reg_addr, reg_value'.\n*   **I2C I/O** connects to **Linux USB Interface** via a downward arrow.](.pci-mpg24-manual-18/83c3bd13621219d892f23b0e9f83a9d7313a378bbcc0ef7e9b2fe8e9304b1dd8.jpg)

Figure 5-2: DFD of Encoder Linux SDK

# 5.3 Encoder LINUX SDK Interfaces

This chapter describes the class or APIs.

# CVideoCapture Interface

# Purpose

This class provides an interface separating server from encoder driver. This interface enables an application to invoke I/O actions on an instance of a videocapture through an I/O packet.

Method Summary

<table><tr><td>Method</td><td>Description</td></tr><tr><td colspan="2">Initialization Operation Method</td></tr><tr><td>CreateInstance</td><td>Create an instance for this interface.</td></tr><tr><td>Release</td><td>Release the instance for this interface.</td></tr><tr><td>DeviceExist</td><td>Specify if a device is present</td></tr><tr><td>GetBoardInfo</td><td>Get board information</td></tr><tr><td colspan="2">Video Operation Method</td></tr><tr><td>SetVideoConfig</td><td>Set the video config. The setting will not take effect until next call of StartCapturing.</td></tr><tr><td>StartCapturing</td><td>start capturing video from chip using the pre-set stream and bitrate setting</td></tr><tr><td>StopCapturing</td><td>Stop capturing</td></tr><tr><td>GetOneFrame</td><td>Get one video frame from chip, this function works in block mode, it will not return until a frame is unavailable or StopCapturing is called.</td></tr><tr><td>SetVideoSource</td><td>Set video input source.</td></tr><tr><td>GetVideoSource</td><td>Get video input source.</td></tr><tr><td>SetTVStandard</td><td>Specify TV standard.</td></tr><tr><td>ChangePFrameRate</td><td>Change frame rate only for P frame.</td></tr><tr><td>SetFPS</td><td>Set frame rate for I, P and B frame.</td></tr><tr><td>BitrateControl</td><td>Specify bitrate of the output video.</td></tr><tr><td>SetResolution</td><td>Specify the output video stream resolution.</td></tr><tr><td>ChangeIFrameQuantizer</td><td>Change quantized scale only for I frame.</td></tr><tr><td>ChangePFrameQuantizer</td><td>Change quantized scale only for P frame.</td></tr><tr><td>ChangeBrightness</td><td>Specify brightness value of output video.</td></tr><tr><td>ChangeContrast</td><td>Specify contrast value of output video.</td></tr><tr><td>ChangeHue</td><td>Specify hue value of output video.</td></tr><tr><td>ChangeSaturation</td><td>Specify saturation value of output video.</td></tr><tr><td>ForceIFrame</td><td>Insert an Iframe.</td></tr><tr><td>InsertNewSequenceHeader</td><td>Insert a new sequence header.</td></tr><tr><td>sigDetect</td><td>Monitor signal lost</td></tr><tr><td>SetMDRegions</td><td>Set motion detection region.</td></tr><tr><td>SetMDThresholdsAndSensitivities</td><td>Set threshold and sensitivity value for motion detection</td></tr><tr><td>ResetMotionDetection</td><td>Reset motion detection.</td></tr><tr><td>InitMotionDetection</td><td>Initialize motion detection</td></tr><tr><td>osd_show</td><td>Show osd</td></tr><tr><td colspan="2">Debugging Operation Method</td></tr><tr><td>ReadCBusReg</td><td>Read from c-bus registers for debugging.</td></tr><tr><td>WriteCBusReg</td><td>Write to c-bus registers for debugging.</td></tr><tr><td>ReadCBus</td><td>Read from c-bus register</td></tr><tr><td>WriteCBus</td><td>Write data to c-bus register</td></tr><tr><td>I2C_WriteRegister</td><td>Write peripheral chip registers via I2C bus</td></tr><tr><td>GPIO_Read</td><td>Read the status of GPIO pins.</td></tr></table>

# Initialization Methods

# CreateInstance

# Synopsis:

STATIC SINT32 CreateInstance (VOID \*\*pp, SINT8 instance)

# Description:

This function creates an instance for CVideoCapture interface.

# Arguments:

VOID \*\*pp – [out] Pointer to this new instance. It should be allocated memory by the caller.

SINT8 instance – [in] Index number of the connected device. The range should be from 0 to the return value of GetDeviceNumber () - 1.

# Returns:

SINT32 – Status of whether the new instance is created successfully.

SUCCESS (0x0000) – success;

ERR\_MEMORY (0x0002) – no enough memory to create a new instance;

ERR\_DEVICE (0x0001) – device file can not be opened.

# Notes:

The argument, pp, is checked to ensure that it is not NULL. If yes, ERR\_MEMORY will be returned.

# Release

# Synopsis:

VOID Release ()

# Description:

This function releases the instance of CVideoCapture interface. And it also frees its allocated memory.

# Arguments:

None

# Returns:

None

# DeviceExist

# Synopsis:

SINT32 DeviceExist ()

# Description:

This function specifies if a device is present.

# Arguments:

None

# Returns:

SINT32 – Status of whether the device exists.

0 – device not exists

1 – device exists

# GetBoardInfo

# Synopsis:

void GetBoardInfo (REVISION\_INFO \*p\_bi)

# Description:

This function gets the encoder information.

# Arguments:

REVISION\_INFO \*p\_bi - [out] A pointer to board information, caller is responsible to allocate memory for it.

# Returns:

None

# Video Operation Methods

# SetVideoConfig

# Synopsis:

void SetVideoConfig (TCFGVIDEO \*pcfgvideo)

# Description:

This function sets the video configuration but not take effect immediately until next call of StartCapturing ().

# Arguments:

TCFGVIDEO \*pcfgvideo – [in] A pointer to an instance of structure TCFGVIDEO. The caller should allocate memory for it.

# Returns:

None

# Notes:

This setting will not take effect until next call of StartCapturing.

# StartCapturing

# Synopsis:

SINT32 StartCapturing ()

# Description:

This function starts capturing video from chip using the pre-set stream and bit rate setting.

# Arguments:

None

# Returns:

SINT32 – status of whether video capture starts successfully

SUCCESS (0) – success

ERR\_DEVICE (0x0001) – device initialization failed.

# Notes:

The function configures audio and video with pre-set value. The device will be put into DS\_RUNNING status if start successfully.

# StopCapturing

# Synopsis:

SINT32 StopCapturing ()

# Description:

This function stops capturing.

# Arguments:

None

# Returns:

SINT32 – status of if capture stops successfully

SUCCESS (0) – device stops successfully

ERR\_DEVICE (0x0001) – chip is not in running state

# GetOneFrame

# Synopsis:

SINT32 GetOneFrame (UINT8 \*pBuf, SINT32 BufLen, TFrameInfo \*pFI)

# Description:

This function gets one video frame from chip and stores into pBuf.

# Arguments:

UINT8 \*pBuf – [out] Buffer for receiving the video stream, caller is responsible for allocating a buffer big enough.

SINT32 BufLen – [in] Buffer length, caller is responsible for setting a valid buffer length.

TFrameInfo \*pFI – [out] A pointer to TFrameInfo structure, it will save the returned frame information; caller is responsible for allocating memory for it.

# Returns:

SINT32 – status of if get one frame successfully

SUCCESS (0) – get one frame from chip successfully

ERR\_DEVICE (0x0001) – device not open or chip is not in running state ERR\_NOMOREFRAME (0x1000) – no more frame is available in chip.

# Notes:

This function works in block mode, it will not return until a frame is unavailable or StopCapturing () is called. If return ERR\_NOMOREFRAME, StopCapturing () is called.

# SetVideoSource

# Synopsis:

SINT32 SetVideoSource (SINT32 source)

# Description:

This function set the input video source.

# Arguments:

SINT32 source – [in] input video source: 1 for Composite and 0 for S-Video

# Returns:

SINT32 – status of video source setting:

0 - success

-1 – error input source

# Notes:

This function will check the validity of input source. The input source is one of SVideo and Composite; if invalid it does nothing.

# GetVideoSource

# Synopsis:

SINT32 GetVideoSource (void)

# Description:

This function gets the current video input source.

# Arguments:

None

# Returns:

SINT32 – the input video source retrieved from board module.

1 – Composite

0 - SVideo

-3 – Unknown

# SetTVStandard

# Synopsis:

SINT32 SetTVStandard (UINT32 mask)

# Description:

This function specifies TV standard.

# Arguments:

UINT32 mask – [in] the TV standard: PAL and NTSC.

# Returns:

SINT32 – status of whether TV standard set successfully

0 – set TV standard successfully

-1 – no match configuration or argument error

-3 - error of unknown register

# ChangePFrameRate

# Synopsis:

SINT32 ChangePFrameRate (UINT16 rate)

# Description:

This function changes P frame rate.

# Arguments:

UINT16 rate – [in] the frame rate value.

# Returns:

SINT32 -status of this function.

0 – P Frame rate set successfully

1 – write interrupt of ON CHIP Mode is timeout

100 – MAXUSBPOLLING, write interrupt error

# SetFPS

# Synopsis:

SINT32 SetFPS (SINT32 fps)

# Description:

This function specifies frame rate for output video.

# Arguments:

SINT32 fps – [in] frame rate, the range of this value depend on the TV standard: NTSC: 30, 15, 10, 7, 6, 5, 4, 3, 2, 1;

PAL: 25, 12.5, 6.25, 5, 4, 3, 2, 1

# Returns:

SINT32 – return the frame rate value just setting.

# Notes:

This function changes frame rate in effect by quickly resetting and restarting the encoder.

# BitrateControl

# Synopsis:

SINT32 BitrateControl (SINT32 change\_direction,

SINT32 new\_i\_qscale,

SINT32 new\_p\_qscale,

SINT32 new\_target\_bitrate,

SINT32 new\_peak\_rate,

SINT32 new\_vbv\_buffer,

SINT32 new\_converge\_speed,

SINT32 new\_lambda)

# Description:

This function controls bit rate.

# Arguments:

SINT32 change\_direction – [in] the data direction when switching encode mode. This value is one of:

0: switching from VBR to VBR;
1: switching from CBR to VBR;
2: switching from VBR to CBR;
3: switching from CBR to CBR.

SINT32 new\_i\_qscale - [in] The quantized scale for I-frames. The range of this value is from 2 to 31.

SINT32 new\_p\_qscale – [in] The quantized scale for P-frames. The range of this value is from 2 to 31.

SINT32 new\_target\_bitrate - [in] The target bite rate of the encoded stream. The range of this value is from 0 to 0x1000000.

SINT32 new\_peak\_rate - [in] The peak bite rate in the encoded stream. The range of this value is from 0 to 0x4000000.

SINT32 new\_vbv\_buffer – [in] The vbv buffer size. The range of this value is from 0 to 112\*16\*1024(1835008)

SINT32 new\_converge\_speed - [in] The converge speed for CBR. The range of this value is from 0 to 100.

SINT32 new\_lambda - [in] The lambda for CBR. The range of this value is from 0 to 100.

# Returns:

SINT32 – status of if bit rate set successfully.

0 – change bit rate successfully and update the TCFGBRCTRL structure.

1 – write interrupt time out

-1 - change\_direction parameter error
-2 - new\_i\_qscale parameter out of range
-3 - new\_p\_qscale parameter out of range
-4 – new\_target\_bitrate parameter out of range
-5 – new\_peak\_rate parameter out of range
-6 – new\_converge\_speed parameter out of range
-7 - new\_lambda parameter out of range
-8 - new\_vbv\_buffer parameter out of range

# Notes:

new\_target\_bitrate parameter is the desired average target bit rate of the encoded stream, in bits per second (bps):

0: If Q>0, apply variable bit rate control (VBR) using the value of Q. If Q=0, no bit rate control algorithm is applied. Bit rate will be determined by values of IQ, PQ, BQ provided by user.

>0: Apply constant bit rate control (CBR) using the value of target\_bitrate.

new\_peak\_rate parameter is the highest bit rate allowed in the encoded stream, in bits per second (bps). This parameter is only valid when applying constant bit rate control. The larger this value is, the higher the peak bit rate is.

new\_vbv\_buffer parameter is a hypothetical decoder that is conceptually connected to the output of the encoder. Its purpose is to provide a constraint on the variability of the data rate that an encoder or editing process may produce.

For new\_converge\_speed parameter, the larger value means faster converging speed.

new\_lambda parameter is the factor determining stream quality. The larger the value is, the smoother the stream will be, but the quality of each frame will decrease. The smaller the value is, the better each picture quality in the stream will be, but the entire video stream will look jumpy due to frame drop.

# SetResolution

Synopsis:

void SetResolution (TCFGVIDEO \*pcfgvideo)

# Description:

This function specifies the output video stream resolution mode.

# Arguments:

TCFGVIDEO \*pcfgvideo – [in] A pointer to structure TCF-GVIDEO presenting one of the following mode: D1, D.5, 4SIF, 2SIF, SIF, CIF-N, CIF-P, QCIF.

Caller is responsible to allocate memory for it.

# Returns:

None

# Notes:

This function changes resolution parameters by quickly resetting and restarting the encoder.

# ChangelFrameQuantizer

# Synopsis:

SINT32 ChangeIFrameQuantizer (UINT16 iqscale)

# Description:

This function changes quantized scale for I frame.

# Arguments:

UINT16 iqscale – [in] the quantized scale value, the range of value is from 2 to 30.

# Returns:

SINT32 –status of this function:

0 – I Frame quantizer set successfully or board information can not be identified

1 – write interrupt of ON CHIP Mode is timeout

100 – MAXUSBPOLLING, write interrupt error

# Notes:

Note that higher the iqscale value, lower the image quality and lower the bit rate.

# ChangePFrameQuantizer

# Synopsis:

SINT32 ChangePFrameQuantizer (UINT16 pqscale)

# Description:

This function changes quantized scale for P frame.

# Arguments:

UINT16 iqscale – [in] the quantized scale value, the range of value is from 2 to 30.

# Returns:

SINT32 –status of this function:

0 – P Frame quantizer set successfully or board information can not be identified

1 – write interrupt of ON CHIP Mode is timeout

100 – MAXUSBPOLLING, write interrupt error

# Notes:

Note that higher the iqscale value, lower the image quality and lower the bit rate.

# ChangeBrightness

# Synopsis:

SINT32 ChangeBrightness (SINT32 brightness\_value)

# Description:

This function configures video brightness.

# Arguments:

SINT32 brightness\_value - [in] brightness value. The range of this value is from 0 to 100. Greater value means brighter.

# Returns:

SINT32 - return the input brightness value.

# Notes:

This function validates input value and if it is invalid, function does nothing.

# ChangeContrast

# Synopsis:

SINT32 ChangeContrast (SINT32 contrast\_value)

# Description:

This function configures video contrast.

# Arguments:

SINT32 contrast\_value - [in] contrast value, the range of this value is from 0 to 100. Greater value means higher the contrast.

# Returns:

SINT32 – return the input contrast value.

# Notes:

This function validates input and if it is invalid, it does nothing.

# ChangeHue

# Synopsis:

SINT32 ChangeHue (SINT32 hue\_value)

# Description:

This function configures video hue.

# Arguments:

SINT32 hue\_value - [in] hue value, the range of this value is from -50 to 50. Greater value means higher hue.

# Returns:

SINT32 – return the input hue value.

# Notes:

This function validates input and if it is invalid, function does nothing.

# ChangeSaturation

# Synopsis:

SINT32 ChangeSaturation (SINT32 saturation\_value)

# Description:

This function configures video saturation.

# Arguments:

SITN32 saturation\_value – [in] saturation value. The range of this value is from 0 to 100. Greater value means higher saturation.

# Returns:

SINT32 – return the input saturation value.

# Notes:

This function valididates input and if it is invalid, function does nothing.

# ForcelFrame

# Synopsis:

SINT32 ForceIFrame (void)

# Description:

This function inserts an Iframe into the encoded video stream.

# Arguments:

None.

# Returns:

SINT32 – status of this function:

0 – force lframe successfully or board information can not be identified

1 – write interrupt of ON CHIP Mode time out

100 – MAXUSBPOLLING, write interrupt error

InsertNewSequenceHeader

# Synopsis:

SINT32 InsertNewSequenceHeader (void)

# Description:

This function inserts a new sequence header at next GOP.

# Arguments:

None

# Returns:

SINT32 –status of this function:

0 – force a new sequence head successfully or board information can not be identified

1 – write interrupt of ON CHIP Mode is timeout

100 – MAXUSBPOLLING, write interrupt error

# sigDetect

# Synopsis:

SINT32 sigDetect (void)

# Description:

This function checks if the input signal is lost.

# Arguments:

None

# Returns:

SINT32 – status of the input signal

0 – signal lost is detected

1 – no signal lost is detected

-3 - I2C read fails

# SetMDRegions Synopsis:

SINT32 SetMDRegions (UINT8 \*arru8MotionCoordinates,

UINT32 u32MaxXCoord,

UINT32 u32MaxYCoord)

# Description:

This function set the region numbers for every macro block to watch for motion.

# Arguments:

UINT8 \*arru8MotionCoordinates – [in] Two dimensional array of region numbers where each [x][y] location contains the region number for that macro block. This argument MUST be exactly the same number of macro blocks as the current picture. If there is a size mismatch the results are undetermined.

UINT32 u32MaxXCoord – [in] The maximum X coordinate for the picture size. This is really just used for error checking.

UINT32 u32MaxYCoord – [in] The maximum Y coordinate for the picture size. This is really just used for error checking.

# Returns:

SINT32 – whether the macro block map successfully

0 - SUCCESS, the macro block map has been set in the device.

1 – ERR\_DEVICE, the macro block map had invalid regions or there was a mismatch in the picture size.

# Notes:

Be careful that this array is the same size as the picture (in macro blocks) and that the caller has initialized every location in this array to ensure that the map is correctly set.

# SetMDThresholdsAndSensitivities

# Synopsis:

SINT32 SetMDThresholdsAndSensitivities (UINT16 arrs16MotionThresholds

[MAX\_REGIONS\_OF\_INTEREST][NUM\_MOTION\_TYPES],

UINT8 \*arru8MotionSensitivity)

# Description:

Set the motion vector and SAD (Sum of Absolute Differences) thresholds for each region. Also set the sensitivity thresholds for each region.

# Arguments:

UINT16 arrs16MotionThresholds – [in] two dimensional array of thresholds of thresholds for the device.

UINT8 \*arru8MotionSensitivity – [in] one dimensional array of sensitivities.

# Returns:

SINT32 – status of if thresholds have been set successfully:

0 – SUCCESS, the macro block thresholds have been set in the device. 1 – ERR\_DEVICE, the macro block thresholds are invalid.

# Notes:

This function validates threshold input and returns ERR\_DEVICE for invalid.

# ResetMotionDetection

# Synopsis:

SINT32 ResetMotionDetection (void)

# Description:

This function reset the state array of motion detection.

# Arguments:

None

# Returns:

SINT32 – return 0 always

# InitMotionDetection

# Synopsis:

SINT32 InitMotionDetection (void)

# Description:

This function is to initialize and enable the motion detector. It is to be called before the initial package is generated as it only affects the initial package.

# Arguments:

None

# Returns:

SINT32 – return 0 always.

# Notes:

Call this before Pacgen. If you don't call this, you can't use motion detection.

# OSD\_show

# Synopsis:

SINT32 osd\_show(unsigned char x, unsigned char y, void \*String)

# Description:

This function shows osd information with the IO\_OSD\_DISPLAY IO command.

# Arguments:

unsigned char x - [in] type of osd operation:

0 – clean OSD display with writing the OSD frame EOF to the start address of current frame buffer;

1 – prepare OSD data from user to OSD buffer with OSD string format.

2 – write the prepared OSD data from the OSD buffer to firmware and display on screen.

Unsigned char y – [in] the string number of OSD data; User can input multi string to OSD buffer with the total length of OSD\_STRING\_LEN\_MAX-3.

Void \*string – [in] in order to show osd correctly, user should pass a pointer to osd\_string\_t struct, define in Include/osd.h.

x: the x coordinate of the location to show osd; in the unit of MB\_SIZE (16 pixels)

y: the y coordinate of the location to show osd in the unit of MB\_SIZE (16 pixels);

osd\_string[]: the content of string text. The max lenght is OSD\_STRING\_LEN\_MAX -3

# Returns:

SINT32 – return 0 always.

# Debugging Operation Methods

# ReadCBusReg

# Synopsis:

int ReadCBusReg (SINT32 RegNum,UINT16 Addr[],UINT16 Data[ ])

# Description:

This function reads several encoder chip registers through firmware for debugging.

# Arguments:

SINT32 RegNum – [in] Register number to identify the buffer length for register address and register data.

UINT16 Addr[ ] - [in] Array of address where read registers, caller is responsible for allocating buffer big enough.

UINT16 Data[ ] – [out] Array of data read from register, caller is responsible for allocating buffer big enough.

# Returns:

int – status of if read register successfully.

0 - success

1 – download buffer error

2 - check interrupt pipe error

# Notes:

Address and data are all in 16 bits.

# WriteCBusReg

# Synopsis:

int WriteCBusReg (SINT32 RegNum, UINT16 AddrData[])

# Description:

This function writes data to a register on the C-bus for debugging.

# Arguments:

SINT32 RegNum - [in] Register number to identify buffer length for register address.

UINT16 AddrData[ ] – [in] Array of address and data pair, caller is responsible for allocating buffer that is big enough.

# Returns:

int – status of if write register successfully.

0 – write data to cbus register successfully

1 – write data operation time out

100 – write data interrupt error

# Notes:

Address and data are all in 16 bits.

# ReadCBus

# Synopsis:

SINT32 ReadCBus (UINT16 addr, UINT16\* data)

# Description:

This function reads a register on the C-bus.

# Arguments:

UINT16 addr – [in] register address of read from

UINT16 \*data – [out] data read from register

# Returns:

SINT32 – status of if read register successfully.

0 - success

1 – download buffer error

2 - check interrupt pipe error

# WriteCBus

# Synopsis:

SINT32 WriteCBus (UINT16 addr, UINT16 data)

# Description:

This function writes data to c-bus.

# Arguments:

UINT16 addr – [in] register address to write to

UINT16 data – [in] data to write to a register

# Returns:

SINT32 – status of if write to C-bus register

0 – write data to cbus successfully

1 – write data operation time out

100 – write data interrupt error

# I2C\_WriteRegister

# Synopsis:

int I2C\_WriteRegister (UINT16 Addr, UINT8 Data)

# Description:

This function writes I2C registers for programming/debugging purpose.

# Arguments:

UINT16 Addr – [in] I2c register address

UINT8 Data – [in] data to write to I2C register

# Returns:

int – status of I2C write register operation.

0 – write I2C register successfully

1 – write I2C register interrupt time out or read CBus error

2 – write I2C control register error

3 – write I2C loaddr register error

4 – write I2C data register error

5 – write i2c\_devaddr\_upaddr\_reg register error

100 – write I2C register interrupt error

# GPIO\_Read

# Synopsis:

int GPIO\_Read(SINT32 Index, SINT32 \*pValue)

# Description:

This function read a signal on a GPIO pins.

# Arguments:

SINT32 Index – [in] Index of GPIO pins, should be between 0 and 4. Pin0 and Pin1 are used for channel ID; Pin2, Pin3, and Pin4 are used for Card ID.

SINT32 \*pValue – [out] The signal of GPIO pin.

# Returns:

int – status of GPIO read operation.

0 – read GPIO successfully

ERR\_DEVICE (0x0001) – device operation failed.

ERR\_PARAMETER(0x0007) – bad parameter of Index.

# 5.4 WIS-LIVE Interface

WIS-LIVE is an interface to convert the encoded A/V stream to the LIVE streaming libraries which is an OpenSource library.

WIS-LIVE provides the following two libraries:

Wis-live is a library containint the APIs for go-server application.

Wis-live\_stand is a library containing the APIs for live-server application.

# WIS-LIVE APIs

# PlayMPEG4AudioVideoStream

# Synopsis:

```txt
void PlayMPEG4AudioVideoStream(StreamBufQueue_t * pABuf,
StreamBufQueue_t* pVBuf,
char *pIpAddr,
int Aport,
int Vport,
int RTSPport,
int audioIsPCM)
```

# Description:

This function can be used to play MPEG4 video and mp2 audio with Live.com library.

# Arguments:

StreamBufQueue\_t \*pABuf – [in] Pointer to audio buffer queue
StreamBufQueue\_t \*pVBuf – [in] Pointer to video buffer queue
char \*plpAddr – [in] destination ip address, NULL means use Unicast

int Aport – [in] audio destination port
int Vport – [in] video destination port
int RTSPport – [in] rtsp listen port
int audiolsPCM – [in] whether the input audio stream is raw PCM rather than MPEG audio

# Returns:

None;

# PlayMPEG1or2AudioVideoStream

# Synopsis:

```txt
void
    PlayMPEG1or2AudioVideoStream(StreamBufQueue_t * pABuf,
    StreamBufQueue_t * pVBuf,
    char *pIpAddr,
    int Aport,
    int Vport,
    int RTSPport,
    int audioIsPCM)
```

# Description:

This function is used to play MPEG1 and MPEG2 AV with Live.com library.

# Arguments:

StreamBufQueue\_t \*pABuf – [in] Pointer to audio buffer queue StreamBufQueue\_t \*pVBuf – [in] Pointer to video buffer queue char \*plpAddr – [in] destination ip address, NULL means use Unicast

int Aport – [in] audio destination port
int Vport – [in] video destination port
int RTSPport – [in] rtsp listen port
int audiolsPCM – [in] whether the input audio stream is raw PCM rather than MPEG audio

# Returns:

None;

# WIS-LIVE-STAND APIs

# PlayAudioVideoStream

# Synopsis:

```txt
void PlayAudioVideoStream( FrameReadFunc* aRead, FrameReadFunc* vRead,
char *pIpAddr,
int Aport,
int Vport,
int RTSPport,
char* RTSPaddr,
int audioNumChannels,
int audioSamplingRate,
int audioOutputMode,
int videoOutputMode,
char const* allowedUsername,
char const* allowedPassword)
```

# Description:

This function is used to play MPEG4 video and mp2 audio with Live.com library.

# Arguments:

ReadFrameFunc \*aRead – [in] functions that read audio/video frames

ReadFrameFunc \*vRead – [in] functions that read audio/video frames

char \*plpAddr - [in] destination ip address, NULL means use Unicast

int Aport – [in] audio destination port

int Vport – [in] video destination port

int RTSPport – [in] rtsp listen port

char\* RTSPaddr - [in] IP address to use for RTSP server (NULL for default)

int audioNumChannels – [in] number of channels of PCM audio

int audioSamplingRate – [in] sampling frequency of audio (if PCM only)

int audioOutputMode – [in] the mode of audio output.

0: => 16-bit PCM;

1: => 8-bit u-law;

any other value (x) => x kbps MPEG-1 audio

int videoOutputMode – [in] the mode of video output

0: => MPEG-4;

1: => H.263

char const\* allowedUsername – [in] user name to authorize access to the server;

NULL to allow anyone access

char const\* allowedPassword - [in] password to authorize access to the server;

NULL to allow anyone access

# Returns:

None;

# WIS-LIVE Structure

StreamBufQueue\_t
```txt
typedef struct StreamBufQueue_s
{
    struct stream_buf_s stream_buf[MAX_NUM_BUFFER];/
    /stream buffer queue
    int head; // queue header, value is between 0 - MAX_NUM_BUFFER
    int tail; // queue tail, value is between 0 - MAX_NUM_BUFFER
    int type; // 1: audio stream buffer queue, 2: video stream buffer queue
    pthread_mutex_t mutex; //pthread mutex
} StreamBufQueue_t ;
```

Stream\_buf\_s
```c
struct stream_buf_s
{
char *p; // buffer pointer
char *cur; // Current position
int len; // the current string length
struct timeval creationTime; // when the data was created
};

#define MAX_NUM_BUFFER 128
```

# 5.5 OSD APIs

# Purpose

This section describes how to use OSD APIs.

# API Description

# init\_osd

# Synopsis:

osd\_error\_t init\_osd (void \*pdxc, long video\_frame\_width, long video\_frame\_height)

# Description:

This function initializes the encoder chip to handle OSD command.

# Arguments:

void \*pdxc - [in] pointer to DEVICE\_EXTENSION\_COMMON struct. User is responsible for its allocation and initialization.

long video\_frame\_widht – [in] width of input video frame. Unit is number of pixels.

long video\_rame\_height - [in] height of input video frame. Unit is number of pixels.

# Returns:

osd\_error\_t: return the status of OSD initialization. osd\_error\_t is a enumeration type defined in src/drv/osd.h

OSD\_ERROR\_OUTOFMEMORY - system has not enough memory for osd.

OSD\_ERROR\_OK – initialization succeed.

# Notes:

This function is called when initializing device.

# get\_osd\_frame

# Synopsis:

osd\_error\_t get\_osd\_frame (unsigned char num, void \*string\_ptr)

# Description:

This function actually transfers to be displayed string from user program to the OSD internal buffer.

# Arguments:

unsigned char num – [in] number of osd string. User shall specify a set of X, Y coordinates and data strings in the following structure passed by \*string\_ptr. This is number specifies number of valid strings in the structure.

void \*string\_ptr - [in] in order to show osd correctly, user should pass a pointer to osd\_string\_t struct defined in Include/osd.h:

The struct of osd\_string\_t contains the following:

unsigned char x: the x coordinate of the location to show osd; unit is number of macro blocks (a macro block is 16\*16 pixels)

unsigned char y: the y coordinate of the location to show osd; unit is number of macro blocks (a macro block is 16\*16 pixels).

Example: Preview window is 720\*480, max value of x is 720/16-1=44, max value of y is 480/16-1 = 29.

char osd\_string[]: the content of string text. The max lenght is OSD\_STRING\_LEN\_MAX -3

# Returns:

osd\_error\_t - return OSD\_ERROR\_OK, get OSD frame successfully.

# Notes:

The function name should be named as send\_osd\_data(void \*string\_ptr).

# show\_osd\_frame

# Synopsis:

osd\_error\_t show\_osd\_frame (osd\_display\_mode\_t mode)

# Description:

This function writes the prepared OSD data to OSD font index buffer for chip to display.

# Arguments:

osd\_display\_mode\_t mode - [in] the mode to update current buffer of write to a new buffer.

OSD\_NORMAL: 0

OSD\_REFRESH: 1

# Returns:

osd\_error\_t – return the status of OSD show.

OSD\_ERROR\_BUS\_WRITE\_FAIL – write CBus failed.

OSD\_ERROR\_OK - succeed.

# Notes:

# clean\_osd

# Synopsis:

osd\_error\_t clean\_osd ()

# Description:

When user want to clear the strings displayed by osd, just call this function.

# Arguments:

None

# Returns:

osd\_error\_t - return the status of OSD clean.

OSD\_ERROR\_OK – clean OSD successfully.

# Notes:

# Example:

Here is an example to show how to use OSD APIs.

# 1. initialize OSD

```c
In the function initializeDevice(PDEVICE_EXTENSION_COMMON context), call function init_osd() to initialize OSD.init_osd(context, video_config->rescfg.width, video_config->rescfg.height);
```

# 2. send string to OSD module

```c
sd_string_t osd_str[2] = {
{1, 6, "How are you today?"}, {4, 9, "Wish you a good day"}
};
get_osd_frame(2, &osd_str[0]);
```

# 3. show OSD

```javascript
show_osd_frame(0);
```

It will show the string “How are you today?” at $(1,6)$ macro block.

"Wish you a good day" at (4,9) macro block.

# 4. clear OSD

```txt
clean_osd();
```

# 5.6 FFMPEG APIs

FFMPEG is a very fast video and audio converter. It can also grab from a live audio/video source. The command line interface is designed to be intuitive, in the sense that FFMPEG tries to figure out all the parameters, when possible. You have usually to give only the target bit rate you want.

FFMPEG can also convert from any sample rate to any other, and resize video on the fly with a high quality poly-phase filter.

FFMPEG provides the following two libraries:

Libavcodec is the library containing the codecs (both encoding and decoding). See \`libavcodec/apiexample.c' to see how to use it.

Libavformat is the library containing the file formats handling (mux and demux code for several formats). See \`ffplay.c' to use it in a player. See \`output\_example.c' to use it to generate audio or video streams.

You can integrate all the source code of the libraries to link them statically to avoid any version problem. All you need is to provide a 'config.mak' and a 'config.h' in the parent directory. See the defines generated by ./configure to understand what is needed.

Some of FFMPEG APIs are called by methods of CServer. Main FFMPEG APIs will be described in this section. User can customize its own CServer for its own functionality using FFMPEG APIs.

# AV CODEC APIs

# register\_avcodec

# Synopsis:

void register\_avcodec(AVCodec \*format)

# Description:

This function is used for registering CODEC; the specified CODEC will be linked to the CODEC list first\_avcodec;

# Arguments:

AVCodec \*format – [in] Points to the specified CODEC to be registered;

# Returns:

None;

# avcodec\_find\_encoder

# Synopsis:

AVCodec \*avcodec\_find\_encoder(enum CodecID id)

# Description:

This function is used for finding the specified encoder in the CODEC list first\_avcodec of FFMPEG.

# Arguments:

enum CodecID id – [in] The CODEC id of the encoder to be found;

# Returns:

AVCodec \* - null, not found; Or the pointer to the struct AVCode for the encoder found.

# avcodec\_find\_decoder

# Synopsis:

AVCodec \*avcodec\_find\_decoder(enum CodecID id)

# Description:

This function is used for finding the decoder according to the specified CODEC id in the CODEC list first\_avcodec of FFMPEG.

# Arguments:

enum CodecID – The CODEC id of the decoder to be found;

# Returns:

AVCodec \* - null, not found; Otherwise, the pointer to AVCodec of the CODEC found;

# avcodec\_open

# Synopsis:

int avcodec\_open(AVCodecContext \*avctx, AVCodec \*codec)

# Description:

This function opens the specified CODEC in order to code or encode.

# Arguments:

AVCodecContext \*avctx – Points to the context of the CODEC.

AVCodec \*codec – Points to the CODEC used for coding or encoding.

# Returns:

int – status of open:

-1 – the codec has been open

0 – open successfully

12 – not big enough memory to allocate

&lt;0 – the codec initialized failed

# avcodec\_close

# Synopsis:

int avcodec\_close(AVCodecContext \*avctx)

# Description:

This function is used for closing the specified CODEC not to be used for coding or encoding any more;

# Arguments:

AVCodecContext \*avctx – Points to the context of the CODEC;

# Returns:

int - 0;

# avcodec\_encode\_audio

# Synopsis:

int avcodec\_encode\_audio(AVCodecContext \*avctx,

uint8\_t \*buf,

int buf\_size,

const short \*samples)

# Description:

This function is used for encoding an audio stream.

# Arguments:

AVCodecContext \*avctx - [in] Points to the CODEC context used for encoding audio stream.

uint8\_t \*buf - [out] Points to the buffer for storing the returned encoded audio stream.

int buf\_size - [in] The buffer size of the buffer pointed to by buf.

const short \*samples – [in] Points to the buffer storing the audio stream.

# Returns:

int – status of audio encoding:

-1, error;

Others, the number of bytes of returned encoded audio stream;

# avcodec\_decode\_audio

# Synopsis:

int avcodec\_decode\_audio(AVCodecContext \*avctx,
int16\_t \*samples,
int \*frame\_size\_ptr,
uint8\_t \*buf,
int buf\_size)

# Description:

This function is used for decoding an audio frame.

# Arguments:

AVCodecContext \*avctx - [in] Points to the context of the CODEC used for decoding audio stream;

int16\_t \* samples – [out] Points to the buffer for storing the decompressed audio stream;

int \*frame\_size\_ptr -- [out] Points to the variable used for storing the decompressed size in BYTES.

uint8\_t \*buf - [in] Points to the buffer storing the audio stream to be decompressed;

int buf\_size -- [in] The size of the audio stream to be decompressed;

# Returns:

int - 1, error; Others, the number of bytes have been used by decompressing

# avcodec\_encode\_video

# Synopsis:

int avcodec\_encode\_video(AVCodecContext \*avctx,
    uint8\_t \*buf,
    int buf\_size,
    const AVFrame \*pict)

# Description:

This function is used for encoding video stream.

# Arguments:

AVCodecContext \*avctx -[in] Points to the CODEC context used for encoding video stream;

uint8\_t \*buf - [out] Points to the buffer for storing the returned encoded video stream;

int buf\_size - [in] The buffer size of the buffer pointed to by buf;

const AVFrame \*pict – [in] Points to the buffer storing the video stream to be encoded.

# Returns:

int – The size of the encoded output stream in bytes;

# avcodec\_decode\_video

# Synopsis:

int avcodec\_decode\_video(AVCodecContext \*avctx,

AVFrame \*picture,

int \*got\_picture\_ptr,

uint8\_t \*buf,

int buf\_size)

Description:

This function is used for decoding a frame;

# Arguments:

AVCodecContext \*avctx - [in] Points to the context of the CODEC used for decoding the video;

AVFrame \*picture – [out] Points to an AVFrame

int \*got\_picture\_ptr - [out] 0, No frame could be decompressed; otherwise, it is nonzero;

uint8\_t \*buf - [in] Points to the begin of bit stream buffer, must be FF\_INPUT\_BUFFER\_PADDING\_SIZE larger then the actual read bytes because some optimized bit stream readers read 32 or 64 bit at once and could read over the end;

int buf\_size - [in] The size in bytes of the buffer pointed by buf;

# Returns:

int -1, error; Others, the number of bytes have been used for decompressing;

# avpicture\_get\_size

# Synopsis:

int avpicture\_get\_size(int pix\_fmt, int width, int height)

# Description:

This function used for getting the necessary buffer size for the raw picture to be encoded;

# Arguments:

int pix\_fmt – Pixel format of the raw picture to be encoded;

int width – Width in pixel for the raw picture to be encoded;

int height – Height in pixel for the raw picture to be encoded;

# Returns:

int – the size in bytes for the raw picture to be encoded;

# avpicture\_fill

# Synopsis:

int avpicture\_fill(AVPicture \*picture, uint8\_t \*ptr, int pix\_fmt, int width, int height)

# Description:

This function is used for setting the data[i] and linesize[i] (the range of i is from 0 to 2) fields through computation.

# Arguments:

AVPicture \*picture – [in] Points to the AVPicture whose data and linesize field is to be filled;

uint8\_t \*ptr - [in] data[0] field is filled with ptr;

data[1] is the start address for Y data; data[1] is the start address for U data;

data[2] is the start address for V data;

int pix\_fmt - [in] Pixel format of the raw picture;

int width – [in] Width in pixel of the raw picture;

int height – [in] Height in pixel of the raw picture;

# Returns:

int - 1, the input pixel format cannot be recognized; Others, the size in bytes for the raw picture to be encoded

# av\_mallocz

# Synopsis:

void \*av\_mallocz(unsigned int size)

# Description:

This function is used for allocating memory for libavcodec; the allocated memory is aligned at 16-byte boundary.

# Arguments:

unsigned int size – The specified size of memory to be allocated;

# Returns:

void \* - null, no memory can be allocated; Others, points to the allocated memory;

# avcodec\_alloc\_context

# Synopsis:

AVCodecContext \*avcodec\_alloc\_context(void)

# Description:

Allocates an AVCodecContext and set it to defaults.

# Arguments:

None

# Returns:

AVCodecContext \* - null, no memory can be allocated;

The pointers to the allocated AVCodecContext;

# Notes:

This can be deallocated by simply calling free();

# avcodec\_alloc\_frame

# Synopsis:

AVFrame \*avcodec\_alloc\_frame(void)

# Description:

This function is used for allocating an AVFrame and set it to defaults.

# Arguments:

None;

# Returns:

AVFrame \* - null, no AVFrame is allocated;

Others, the pointer to the allocated AVFrame;

# Notes:

This can be deallocated by simply calling free().

This function uses av\_mallocz to allocate memory; so the allocated memory is 16-byte alignment

# avcodec\_get\_context\_defaults

# Synopsis:

void avcodec\_get\_context\_defaults(AVCodecContext \*s)

# Description:

This function is used for setting CODEC context with default values;

# Arguments:

AVCodecContext \*s - [in] Pointer to the CODEC context to be set with default values;

# Returns:

None.

# AV Format APIs

# register\_protocol

# Synopsis:

int register\_protocol(URLProtocol \*protocol)

# Description:

This function is used for registering file I/O operations.

# Arguments:

URLProtocol \*protocol – Points to the URLProtocol to be registered;

# Returns:

int - 0;

# mpegps\_init

# Synopsis:

int mpegps\_init(void)

# Description:

This function is used for registering the MPEGI and MPEG II formats;

# Arguments:

None;

# Returns:

int 0;

raw\_init

# Synopsis:

int raw\_init(void)

# Description:

This function is used for registering with the following raw formats:

Input format: ac3; h263; MPEG4; H264; MPEG video; MJPEG video; raw video;

For output format, null raw video is added besides the above formats;

# Arguments:

None;

# Returns:

int - 0;

# mp3\_init

# Synopsis:

int mp3\_init(void)

# Description:

This function is used for registering with the following formats,

Input: mp3;

Output: mp2, mp3;

# Arguments:

None;

# Returns:

int - 0;

# wav\_init

# Synopsis:

int wav\_init(void)

# Description:

This function register wave format;

# Arguments:

None;

# Returns:

int - 0;

# guess\_format

# Synopsis:

AVOutputFormat \*guess\_format(const char \*short\_name,

const char \*filename,

const char \*mime\_type)

# Description:

This function is used for finding the matched output file format. It will match according the following parameters: short\_name, mime\_type, filename;

# Arguments:

const char \*short\_name - [in] File name;

const char \*filename –[in] File extension;

const char \*mime\_type –[in] Mime type;

# Returns:

AVOutputFormat \* - Null, no matching file format exist; Others, the pointer to the matched file format;

# url\_fopen

# Synopsis:

int url\_fopen(ByteIOContext \*s, const char \*filename, int flags)

# Description:

This function opens a file with a registered URLProtocol.

# Arguments:

ByteIOContext \*s – [out] A pointer to ByteIOContext, its fields will be set according to the specified filename and flags;

const char \*filename - [in] The filename of the file to be opened;

int flags -- #define URL\_RDONLY 0

#define URL\_WRONLY 1

#define URL\_RDWR 2

# Returns:

int – status of file open:

0, ok;

-ENOMEM, no memory;

-EIO, IO error;

# Notes:

When opened as read/write, the buffers are only used for reading.

# url\_fclose

# Synopsis:

int url fclose(ByteIOContext \*s)

# Description:

This function is used for freeing the buffer allocated to the specified byte IO context;

# Arguments:

ByteIOContext \*s – [in] Pointer to the ByteIOContext, the buffer of which will be freed.

# Returns:

0, ok;

Others, IO error;

Decided by the registered URLProtocol;

# av\_write\_frame

# Synopsis:

int av\_write\_frame(AVFormatContext \*s,

int stream\_index,

const uint8\_t \*buf,

int size)

# Description:

Write a packet to an output media file. The packet shall contain one audio or video frame.

# Arguments:

AVFormatContext \*s – [in] Media file handle;

int stream\_index – [in] Stream index;

const uint8\_t \*buf - [in] Points to buffer containing the frame data;

int size – [in] Size of buffer in bytes;

# Returns:

int – status of frame write

&lt; 0, error,

= 0, ok,

=1, end of stream wanted.

# av\_set\_parameters

# Synopsis:

int av\_set\_parameters(AVFormatContext \*s, AVFormatParameters \*ap)

# Description:

This function currently is only used for setting pixel format if not YUV420P

# Arguments:

AVFormatContext \*s – [in] Media file handle;

AVFormatParameters \*ap - [in] Pointer to the audio/video parameters structure

# Returns:

int – status of parameters setting

0, OK;

&lt;0, Error;

Others, no use;

# av\_write\_header

# Synopsis:

int av\_write\_header(AVFormatContext \*s)

# Description:

Allocate the stream private data and write the stream header to an output media file

# Arguments:

AVFormatContext \*s - media file handle

# Returns:

int - 0, ok; AVERROR\_xxx, error.

# av\_probe\_input\_format

# Synopsis:

AVInputFormat \*av\_probe\_input\_format(AVProbeData \*pd, int is\_opened)

# Description:

This function is used for detecting file or stream format.

# Arguments:

AVProbeData \*pd – The pointer to the AVProbeData containing the data to be checked. The following fields of filename: buf, buf\_size of this should be set;

int is\_opened - 1, file is opened;

0, file is not opened;

# Returns:

AVInputFormat \* - null, not found;

Others, points to the AVInputFormat matching the specified stream of file;

# av\_write\_trailer

# Synopsis:

int av\_write\_trailer(AVFormatContext \*s)

# Description:

This function is used for writing the stream trailer to an output media file and free the file private data.

# Arguments:

AVFormatContext \*s – [in] media file handle

# Returns:

int - 0, OK; AVERROR\_xxx, error.

# av\_gettime

# Synopsis:

int64\_t av\_gettime(void)

# Description:

This function is used for getting system time in microseconds;

# Arguments:

None

# Returns:

int64\_t - System time in microseconds;

# av\_new\_stream

# Synopsis:

AVStream \*av\_new\_stream(AVFormatContext \*s, int id)

# Description:

This function is used for adding a new stream to a media file.

# Arguments:

AVFormatContext \*s - Media file handle;

int id - File format dependent stream id;

# Returns:

AVStream \* - Null, no stream can be allocated; Others, the pointer to the allocated AVStream;

# Notes:

It can only be called in the read\_header function.

If the flag AVFMTCTX\_NOHEADER is in the format context, then new streams can be added in read\_packet too.

# dump\_format

# Synopsis:

void dump\_format(AVFormatContext \*ic,

int index,

const char \*url,

int is\_output)

# Description:

This function dumps the audio / video format to standard output.

# Arguments:

AVFormatContext \* - [in] Points to the AVFormatContext to be dumped;

int index – not used;

const char \*url – [in] Pointer to the sting for URL;

int is\_output - [in] 1 on output; 0 on input;

# Returns:

None;

# av\_write\_header

# Synopsis:

int av\_write\_header(AVFormatContext \*s)

# Description:

Allocate the stream private data and write the stream header to an output media file

# Arguments:

AVFormatContext \*s –[in] Media file handle;

# Returns:

int - 0, OK; AVERROR\_xxx, error;

# Structures and Constants

Pease refer to libavcodec\avcodec.h for the following structures and constants:

```csv
AVCodec
AVCodecContext
AVFrame
AVPicture
enum CodecID
```

Please refer to libavformat\Avformat.h for the following structures and constants:

```txt
AVFormatContext
AVProbeData
AVStream
AVFormatParameters
```

Please refer to libavformat\avio.h for the following structures and constants:

```txt
ByteIOContext
URLProtocol
```

Please refer to libavcodec\common.h for the following types:

```c
int16_t
uint8_t
int64_t
```

# 5.7 CServer Interface

# Purpose

CServer is an application level class developed based on CVideoCapture. This class includes a series of methods through calling Linux thread APIs to implement its own functions. These methods presenting the go-server features are implemented in this class.

Method Summary

&lt;table&gt;<tr><td>Methods</td><td>Description</td></tr><tr><td>Start</td><td>Start server.</td></tr><tr><td>Stop</td><td>Stop server.</td></tr><tr><td>init_channel</td><td>Initialize rtp or sockets for multicast packets.</td></tr><tr><td>do_work_thread</td><td>Get video frame from chip to its own stream buffer.</td></tr><tr><td>do_audio_work_thread</td><td>This function gets audio sample from driver</td></tr><tr><td>do_send_thread</td><td>Multicast video and audio frame from its own buffer to go-client</td></tr><tr><td>do_send_video_thread</td><td>Multicast only video frame from its own buffer to go-client</td></tr><tr><td>do_md_thread</td><td>Enable motion detection thread</td></tr><tr><td>do_sigdet_thread</td><td>Detect if signal lost</td></tr><tr><td>send_one_frame</td><td>Send one video and audio frame packet by packet to go-client</td></tr><tr><td>do_mux_thread_simple</td><td>Mux video and audio stream into a media file</td></tr><tr><td>IsPFrame</td><td>Determine whether the frame is a P frame.</td></tr><tr><td>GetVideoSource</td><td>Gets the current video input source.</td></tr><tr><td>SetVideoSource</td><td>Set video input source on CServer level.</td></tr><tr><td>SetTVStandard</td><td>Set TV standard on CServer level.</td></tr></table>

# Method Description

# Start

Synopsis:

int Start (TCFGVIDEO \*videoconfig,

AUDIO\_CONFIG \*audioconfig,

char \*multicast\_addr,

char \*save\_filename,

int use\_rtp,

int rtp\_port)

# Description:

This function starts the following threads according to different configuration:

do\_work\_thread, do\_audio\_work\_thread, do\_send\_thread, do\_send\_video\_thread, do\_md\_thread, do\_sigdet\_thread, do\_mux\_thread\_simple

# Arguments:

TCFGVIDEO \*videoconfig – [in] Pointer to TCFGVIDEO, a completed video setting, caller is responsible to allocate memory for it.

AUDIO\_CONFIG \*audioconfig - [in] Pointer to AUDIO\_CONFIG, a audio setting, caller is responsible to allocate memory for it.

char \*multicast\_addr - [in] Pointer to multicast address, caller is responsible to ensure the validity of this address.

char \*save\_filename – [in] save file name.

int use\_rtp - [in] A flag of if do rtp transport.

int rtp\_port - [in] The rtp port value.

# Returns:

int – status of if server start successfully.

0 - success.

1 – the device status error, not in stop status and cannot be start again

2 – the initialization of transmission channel for rtp or multicast failed

3 – start capturing video from chip failed

-1 – file I/O operation failed

# Stop

# Synopsis:

int Stop ()

# Description:

This function stops all actions running in server and change device to stop status. Also it deletes the buffers of server.

# Arguments:

None

# Returns:

int – status of if stop successfully.

0 - success

1 – device error and device is not running

# init\_channel

# Synopsis:

int init\_channel (char \*addr)

# Description:

This function initializes RTP packets or socket for multicasting packets.

# Arguments:

char \*addr – [in] Pointer to ip address for RTP transport or multicast. Caller is responsible for ensuring the validity of this value.

# Returns:

int – status of if channel initialization successfully.

0 - success

-1 – RTP initialization failed

1 - Socket initialization error

# Notes:

If need multicast, this function will be called.

# do\_work\_thread

# Synopsis:

void do\_work\_thread ()

# Description:

This function gets one video frame from the chip to its own stream buffer.

# Arguments:

None

# Returns:

None

# Notes:

This function is called by the work\_thread. It will always run and get video frame to its own stream buffer until the Stop() function is called by server.

# do\_audio\_work\_thread

# Synopsis:

void do\_audio\_work\_thread ()

# Description:

This function gets audio sample from driver and write them to test.wav.

# Arguments:

None

# Returns:

None

# Notes:

This function is called by the audio\_work\_thread. It will always run and get audio sample to its own stream buffer until the Stop() function is called by server.

# do\_send\_thread

# Synopsis:

void do\_send\_thread ()

# Description:

This function multicast video frames and audio samples from send buffer to go-client.

# Arguments:

None

# Returns:

None

# do\_send\_video\_thread

# Synopsis:

void do\_send\_video\_thread ()

# Description:

This function only multicasts video from its own buffer to the go-client.

# Arguments:

None

# Returns:

None

# do\_md\_thread

# Synopsis:

void do\_md\_thread ()

# Description:

This function enables motion detection.

# Arguments:

None

# Returns:

None

# do\_sigdet\_thread

# Synopsis:

void do\_sigdet\_thread ()

# Description:

This function enables signal detection.

# Arguments:

None

# Returns:

None

# send\_one\_frame

# Synopsis:

int send\_one\_frame (char \*pframe, int frame\_len, unsigned char SubId)

# Description:

This function sends one video or audio frame packet by packet through RTP transport or multicast.

# Arguments:

char \*pframe – [in] Pointer to buffer of video or audio which is to be sent. Caller is responsible to allocate buffer big enough.

int frame\_len - [in] buffer length, caller is responsible to ensure its validity.

unsigned char SubId – [in] type of stream, 0 is video stream and 1 is audio stream

# Returns:

int – flag of if send one frame successfully.

0 - success

-1 - send error

# do\_mux\_thread\_simple

# Synopsis:

void do\_mux\_thread\_simple ()

# Description:

This function muxes audio and video stream into a file.

# Arguments:

None.

# Returns:

None.

# IsPFrame

# Synopsis:

static bool IsPFrame (unsigned char\* pdata, unsigned long len)

# Description:

This function specifies whether the frame is a P frame.

# Arguments:

Unsigned char \*pdata – [in] buffer to a frame, caller is responsible to allocate buffer big enough.

Unsigned long len - [in] frame length

# Returns:

bool – whether is a P frame

true – is a P frame

false – is not a P frame

# GetVideoSource

# Synopsis:

SINT32 GetVideoSource (void)

# Description:

This function gets the current video in source.

# Arguments:

None.

# Returns:

SINT32 – the input video source retrieved from board module.

0 - Composite

1 - SVideo

2 - TV tuner

-3 – Unknown

# SetVideoSource

# Synopsis:

SINT32 SetVideoSource (SINT32 source)

# Description:

This function set video input source on CServer level.

# Arguments:

SINT32 source – [in] video input source, user is responsible to ensure the validity of input source. The valid value range is within the enumeration:

VIDEO\_SOURCE, defined in Include/struct.h.

# Returns:

SINT32 – status of if set video input source successfully.

# Notes:

This function will check the validity of input source. The input source is one of value of VIDEO\_SOURCE; if invalid it does nothing.

# SetTVStandard

# Synopsis:

SINT32 SetTVStandard (UINT32 mask)

# Description:

This function set TV standard on CServer level.

# Arguments:

UINT32 mask – [in] TV standard mask, user is responsible to ensure the validity of TV standard value. The valid value range is within the enumeration:

TV\_STANDARD, defined in Include/struct.h.

# Returns:

SINT32 – status of whether TV standard set successfully

0 – set TV standard successfully

-1 – no match configuration or argument error

-3 - error of unknown register

# 5.8 Motion Detector Interface

# Purpose

This provides a motion detection API at CServer level.

# Method Summary

<table><tr><td>Methods</td><td>Description</td></tr><tr><td>MotionDetector</td><td>Create MotionDetector</td></tr><tr><td>MDSetEnable</td><td>Set MD status.</td></tr><tr><td>SetPicSize</td><td>Set macro block size for MD.</td></tr></table>

# Method Description

# MotionDetector

# Synopsis:

MotionDetector::MotionDetector (IVideoCapture\*\* vc, int width, int height)

# Description:

This function create a motion detector.

# Arguments:

IVideoCapture\*\* vc - [in] pointer of pointer to IVideoCapture struct.

int width – [in] the input source piture width, in pixel unit.

int height - [in] the input source picture height, in pixel unit.

# Returns:

None

# MDSetEnable

# Synopsis:

Int MotionDetector::MDSetEnable(int bEnable)

# Description:

This function set motion detection status.

# Arguments:

Int bEnable – [in] motion detection status.

0: MD\_STATE\_DISABLE\_NO\_THRESHOLD, disabled and no threshold defined;

1: MD\_STATE\_DISABLED, disabled with previous set threshold

2: MD\_STATE\_ENABLED, enabled

# Returns:

Int – status of md setting.

SET\_SUCCESS - 0, set MD success.

SET\_DISABLE\_FAILURE - 1, set MD thresholds failure.

DISABLE\_ALREADY - 2, disable MD already.

ENABLED\_ALREADY - 3, enable MD already.

NO\_THRESHOLD\_DEFINED - 4, enable MD but no thresholds for it.

SET\_ENABLE\_FAILURE - 5, enable MD failure for the macro block map with an invalid region number; or set MD thresholds error.

# SetPicSize

# Synopsis:

Void MotionDetector::SetPicSize(int width, int height)

# Description:

This function set macro block size for picture, in pixel unit.

# Arguments:

int width - [in] input picture width, in pixel unit.

int height—[in] input picture height, in pixel unit.

# Returns:

None.

# 5.9 Structures and Enumerations

This section describes the important structure for developing SDK APIs and calling APIs. Note that this section is only for reference and will change without any notice. For detailed information, please refer to file: Include\struct.h

# REVISION\_INFO Structure

The REVISION\_INFO structure describes the board reversion information.

# Include

Include\struct.h

# Syntax

```c
typedef struct {
    int DriverMajor;
    int DriverMinor;
    int BoardRevision;
    char BoardName[MAX_NAME];
    int BoardCapability;
    int MaxBandWidth;
    int SourceWidth;
    int SourceHeight;
} REVISION_INFO;
```

# Members

driverMajor

Major ID of device

driverMinor

Minor ID of device

boardRevision

Board revision ID

boardName

Board name, use a string less than MAX\_NAME (64) characters included in quotes.

# boardCapability

An integer with each bit representing one kind of capability of board, using values in Enumeration: BOARD\_CAP.

# maxBandWidth

Reserved for future use.

# sourceWidth

Width of source video

# sourceHeight

Height of source video

# TCFGVIDEO Structure

The TCFGVIDEO structure describes a complete video setting, including miscellaneous setting, stream setting, resolution setting, frame rate setting and bitrate control setting.

# Include

Include\struct.h

# Syntax

```txt
typedef struct{
    TCFGMISC misccfg;
    TCFGSTREAM strcfg;
    TCFGRESOLUTIONrescfg;
    TCFGFRAMERATEfpscfg;
    TCFGBRCTRL ctlcfg;
} TCFGVIDEO;
```

# Members

# misccfg

A TCFGMISC structure for miscellaneous settings.

# strcfg

A TCFGSTREAM structure for stream settings.

# rescfg

A TCFGRESOLUTION structure for resolution settings.

# fpscfg

A TCFGFRAMERATE structure for frame rate settings.

# ctlcfg

A TCFGBRCTRL structure for bitrate control settings.

# AUDIO\_CONFIG Structure

The AUDIO\_CONFIG structure describes the audio setting.

# Include

Include\struct.h

# Syntax

```c
typedef struct _AUDIO_CONFIG{
    unsigned longFormat;
    unsigned longSampleRate;
    unsigned longChannels;
    unsigned longSampleBits;
    unsigned shortBlockAlign;
    unsigned longAvgBytesPerSec;
    unsigned shortSamplesPerBlock;
    unsigned shortExtSize;
} AUDIO_CONFIG;
```

# Members

# Format

Audio format, refer to Enumeration: AUDIO\_FORMAT.

# SampleRate

Audio sample rate, in byte. Possible values are 44100, 48000, etc.

# Channels

Audio channels. Possible values are 1 for Mono and 2 for Stereo.

# SampleBits

Audio sample bits. Possible values are 8 bits and 16 bits.

# TCFG\_HEADER Structure

The TCFG\_HEADER structure is used in structures: TCFGSYSTEM, TCFGSTREAM, TCFGFRAMERATE, TCFGRESOLUTION, TCFGBRCTRL and TCFGMISC. It provides general information about the structure it resides in.

# Include

Include\struct.h

# Syntax

```txt
typedef struct{
    char name[MAX_NAME];
    char desc[MAX_DESC];
    unsigned longflags;
    unsigned longsize;
} TCFG_HEADER;
```

# Members

# Name

The name of the configuration. Use a string less than MAX\_NAME (64) characters included in quotes.

# Desc

The description of the configuration. Use a string less than MAX\_DESC (256) characters included in quotes.

# Flags

The flags member provides information of what fields are provided in the structure where the TCFG\_HEADER is located. Each bit in flags corresponds to one field.

# Size

The size of the structure where the TCFGHEADER is located.

# TCFGMISC Structure

The TCFGMISC structure describes miscellaneous settings of the output video stream of encoder chip.

# Include

Include\struct.h

# Syntax

```c
typedef struct{
    TCFG_HEADERheader;
    unsigned char av_sync_enable;
    unsigned chariip_enable;
    unsigned charvbi_enable;
    unsigned charfour_channel_enable;
    FilterMode h_filter_mode;
    FilterMode v_filter_mode;
    char filter_nAX;
    char filter_nBX;
    char filter_nCX;
    char filter_nAY;
    char filter_nBY;
    char filter_nCY;
    long reserved;
} TCFGMISC;
```

# Members

# header

Header information about the structure.

# av\_sync\_enable

0: disable Audio/Video Synchronization algorithm

1: enable Audio/Video Synchronization algorithm

# iip\_enable

Specifies if enabling Input Image Processing. Only valid when sensor pixel format is RGB Bayer.

0: disable IIP

1: enable IIP

# vbi\_enable

0: disable VBI
1: enable VBI

# four\_channel\_enable

If four\_channel\_enable is set, each frame of the encoded stream will be divided into four quadrants. Motion search will be confined in each quadrant and will not be performed in other quadrants.

0: disable four channel feature
1: enable four channel feature

# h\_filter\_mode

The mode of pre-filtering in a horizontal direction.

0: No pre-filtering in the horizontal direction before encoding
1: Median filter applied in the horizontal direction before encoding
2: Linear filter applied in the horizontal direction before encoding

# v\_filter\_mode

The mode of pre-filtering in a vertical direction.

0: No pre-filtering in the vertical direction before encoding

1: Median filter applied in the vertical direction before encoding
2: Linear filter applied in the vertical direction before encoding

# filter\_nAX

# filter\_nBX

# filter\_nCX

The coefficients of linear filter in horizontal direction. Valid only if h\_filter\_mode is 2. A typical requirement for the coefficients is:filter\_nAX + filter\_nBX + filter\_nCX = 16.

# filter\_nAY

# filter\_nBY

# filter\_nCY

The coefficients of linear filter in vertical direction. Valid only if v\_filter\_mode is 2. A typical requirement for the coefficients is: filter\_nAY + filter\_nBY + filter\_nCY = 16.

# reserved

Reserved for future use.

# TCFGSTREAM Structure

The TCFGSTREAM structure describes settings of the output video stream of encoder chip.

# Include

Include\struct.h

# Syntax

```c
typedef struct {
    TCFG_HEADERheader;
    EVideoFormatcompress_mode;
    ESequenceModesequence;
    unsigned char gop_mode;
    unsigned chargop_size;
    unsigned charmpeg4_mode;
    unsigned char DVD_compliant;
    unsigned chardeinterlace_mode;
    unsigned charsearch_range;
    unsigned chargop_head_enable;
    unsigned charseq_head_enable;
    unsigned charaspect_ratio;
    long reserved;
} TCFGSTREAM;
```

# Members

# header

Header information about the structure.

# compress\_mode

The stream's compression mode, refer to Enumeration: EVideoFormat.

MPEG1: 0x00

MPEG2: 0x01

H263: 0x03

MPEG4: 0x04

MOTIONJPEG: 0x08

# sequence

The types of frame being used in a stream sequence. Refer to Enumeration:ESequenceMode for details.

GOP\_MODE\_OPEN: 0

IONLY: Only I-frames in the stream sequence (1)

IPONLY: Only I and P frames in the stream sequence (2)

IPB: All types of frames (I, P and B) in the stream sequence (3)

# gop\_mode

The GOP (Group of Picture) mode of the encoding stream sequence. EncodingDivX format MPEG4 stream requires closed GOP mode.

GOP\_MODE\_OPEN:0

GOP\_MODE\_CLOSE:1

# gop\_size

The Group of Pictures (GOP) size. This value is the key frame interval.

# mpeg4\_mode

MPEG4 stream mode. Valid only when compress\_mode is 4.

WIS\_MPEG4:0

DIVX\_MPEG4: 1

MICROSOFT\_MPEG4:2

# DVD\_compliant

Specify if the stream is desired to be DVD compliant. Valid only when the compression mode is MPEG2.

0: disable DVD\_compliant

1: enable DVD\_compliant deinterlace\_mode

0: use one field only

1: use WIS deinterlace algorithm

2: interlace coding is used; no deinterlacing performed

# search\_range

The searching range for motion vectors. Typical values are 16, 32, 64 or 128. Microsoft format MPEG4 stream requires that search range must be 64. H.263 format stream requires that search range must be 32.

# gop\_head\_enable

Only encoding Microsoft format MPEG4 stream requires disabling GOP head. Il other format streams require enabling GOP head.

0: isable GOP head

1: nable GOP head

# seq\_head\_enable

Only encoding Microsoft format MPEG4 stream requires disabling sequence head. All other format streams require enabling sequence head.

0: isable sequence head

1: nable sequence head

# aspect\_ratio

The ratio between the width and the height of the picture.

1: 1:1

2:4:3

3:16:9

# reserved

Reserved for future use.

# TCFGFRAMERATE Structure

The TCFGFRAMERATE structure describes frame rate related settings of the output video stream of encoder chip.

# Include

Include\struct.h

# Syntax

```c
typedef struct{
    TCFG_HEADERheader;
    TV_STANDARDtv_standard;
    unsigned longframe_rate;
    unsigned long drop_frame;
    unsigned charivtc_enable;
    long reserved;
} TCFGFRAMERATE;
```

# Members

# hader

Header information about the structure.

# tv\_standard

Can be only set as TVStandard\_NTSC\_Mask or VStandard\_PAL\_Mask

# frame\_rate

output frame rate.

# drop\_frame

0: keep original frame rate. No frames dropped.

1: keep 1/2 original frame rate.

2: keep 1/3 original frame rate.

n:keep 1/(n+1) original frame rate.

# ivtc\_enable

IVTC (InVerse TeleCine) is a process where video editing tools reverse Telecine rocess. Basically IVTC brings back movie's original frame rate from NTSC's 9.97fps to 24fps.

0: disable IVTC
1: enable IVTC

# reserved

Reserved for future use.

# TCFGRESOLUTION Structure

The TCFGRESOLUTION structure describes the resolution of encoded stream.

# Include

Include\struct.h

# Syntax

```c
typedef struct {
    TCFG_HEADER header;
    TV_STANDARD tv_standard;
    unsigned longwidth;
    unsigned longheight;
    unsigned charh_sub_window;
    unsigned charv_sub_window;
    unsigned longh_sub_offset;
    unsigned longv_sub_offset;
    unsigned charh_scale_enb;
    unsigned charv_scale_enb;
    unsigned charsub_sample;
    unsigned longmax_bitrate;
    unsigned longmin_bitrate;
    long reserved;
} TCFGRESOLUTION;
```

# Members

hader

Header information about the structure.

tv\_standard

Can only be set as TVStandard\_NTSC\_Mask or VStandard\_PAL\_Mask

width

The desired output stream resolution: horizontal size.

Height

The desired output stream resolution: vertical size.

# h\_sub\_window

Specify if performing sub-window (cropping) in the horizontal direction.

0: disable sub-window

1: enable sub-window

# v\_sub\_window

Specify if performing sub-window (cropping) in the vertical direction.

0: disable sub-window

1: enable sub-window

# h\_sub\_offset

If h\_sub\_window is set, it specifies a relative offset between the leftmost pixel of he output stream and the leftmost pixel of the source stream, in pixels.

# v\_sub\_offset

If v\_sub\_window is set, it specifies a relative offset between the topmost pixel of he output stream and the topmost pixel of the source stream, in pixels.

# h\_scale\_enb

Specify if performing $\frac{1}{2}$ scaling in the horizontal direction.

0: disable scaling

1: enable scaling

# v\_scale\_enb

Specify if performing $\frac{1}{2}$ scaling in the vertical direction.

0: disable scaling

1: enable scaling

# sub\_sample

Specify if performing sub sampling. Sub-sampling will perform $\frac{1}{2}$ scaling down o the stream in both horizontal and vertical directions.

0: disable sub\_sampling

1: enable sub\_sampling

max\_bitrate

The maximum bit rate allowed for this resolution.

min\_bitrate

The minimum bit rate allowed for this resolution.

Reserved

Reserved for future use.

# TCFGBRCTRL Structure

The TCFGBRCTRL structure describes the bitrate control setting of encoded stream.

# Include

Include\struct.h

# Syntax

```c
typedef struct {
    TCFG_HEADERheader;
    unsigned longtarget_bitrate;
    unsigned longpeak_bitrate;
    unsigned longvby_buffer;
    unsigned charconverge_speed;
    unsigned charlambda;
    unsigned longQ;
    unsigned charIQ;
    unsigned charPQ;
    unsigned charBQ;
    long reserved;
} TCFGBRCTRL;
```

# Members

# hader

Header information about the structure.

# target\_bitrate

The desired average target bit rate of encoded stream, in bits per second (bps).

0: If Q>0, apply variable bitrate control (VBR) using the value of Q. If Q=0, no bitrate control algorithm applied. Bitrate will be determined by values of IQ, PQ, BQ provided by user.

>0: Apply constant bitrate control (CBR) using the value of arget\_bitrate.

# peak\_bitrate

The highest bit rate allowed in the encoded stream, in bps. This parameter is only valid when applying constant bitrate control (both Q and target\_bitrate are greater than 0).

# vbv\_buffer

Specifies VBV (Video Buffering Verifier) buffer size.

# converge\_speed

Specifies the converging speed of bit rate control process, from 0 to 100.

# lambda

The factor determining stream quality. Its value range is from 0 to 100.

# Q

Initial quantizer. This value will be divided by 4.

0: If target\_bitrate > 0, apply constant bitrate control. Initial quantizer value will be calculated. If target\_bitrate = 0, no bitrate control algorithm applied. Use IQ, PQ and BQ provided by user to determine bitrate value.

>0: If target\_bitrate is set to 0, apply VBR (variable bitrate) using the value of Q. If target\_bitrate is greater than 0, apply CBR (constant bitrate) using the value of target\_bitrate.

# IQ

The fixed quantize scale for I-frames during the entire encoding session.

# PQ

The fixed quantize scale for P-frames during the entire encoding session.

# BQ

The fixed quantize scale for B-frames during the entire encoding session.

# Reserved

Reserved for future use.

# TFrameInfo Structure

The TFrameInfo structure provides the frame information.

# Include

Include\VideoCapture.h

# Syntax

```cpp
typedef struct _TFrameInfo {
    SINT32 VideoLength; // video frame length
    SINT32 VBILength;
    SINT32AudioFingerprint;
    SINT32VIPNumber;
    SINT32AudioTimestamp; // time stamp for audio
    SINT32 FrameType; // I, P or B frame
    SINT32 MDRegionMap; // bitmap region for motion detection
    SINT32 MDMapFlag;
    UINT16 MDMacroblockMap[86]; //
    MACROBLOCK_MAP_SIZE];
} TFrameInfo;
```

# Members

# BOARD\_CAP Enumeration

Enumeration for encoder chip capability

# Include

Include\struct.h

# Syntax

```txt
typedef enum {
    BC_VIDEO= 0x00000001,
    BC_AUDIO= 0x00000002,
    BC_TVTUNER= 0x00000004,
    BC_XBAR = 0x00000008,
    BC_VBI = 0x00000010,
} BOARD_CAP;
```

# AUDIO\_FORMAT Enumeration

Audio format which encoder chip supports now

# Include

Include\struct.h

# Syntax

```txt
enum AUDIO_FORMAT
{
    AUDIO_FORMAT_PCM= 0x1,
    AUDIO_FORMAT_ADPCM_MS= 0x2,
    AUDIO_FORMAT_ADPCM_IMA= 0x6,
    AUDIO_FORMAT_ALAW= 0x7,
    AUDIO_FORMAT_ULAW= 0x11,
    AUDIO_FORMAT_MP3= 0x55
};
```

# EVideoFormat Enumeration

Video format

# Include

Include\Multimedia.h

# Syntax

```txt
typedef enum {
    MPEG1 = 0x00,
    MPEG2 = 0x01,
    H261 = 0x02,
    H263 = 0x03,
    MPEG4 = 0x04,
    MPEG4XGO= 0x05,
    MPEG2X4 = 0x06,
    MOTIONJPEG= 0x08,
    DV = 0x09,
    H26L = 0x20,
    GO = 0x40
} EVideoFormat;
```

# ESequenceMode Enumeration

Frame type in a video sequence

# Include

Include\Multimedia.h

# Syntax

```txt
typedef enum{
    IONLY = 1, // only I frame in this sequence
    IPONLY = 2, // only I and P frame in this sequence
    IPB = 3, // I, P and B frame in this sequence
    IPBDROP = 4 // I, P and B frame drop in this sequence
} ESequenceMode;
```

# Typedef

The following data type is defined in "Typedef.h" file:

```c
Typedef int SINT32;
Typedef char SINT8;
Typedef unsigned char UINT8;
Typedef unsigned short UINT16;
Typedef void VOID;
```

# Appendix

# Appendix A: Glossary

# Brightness:

Attribute of a visual sensation according to which an area appears to exhibit more or less light

# CCIR:

Committee Consulat International Radiotelegraphique. This is a standards committee of the International Telecommunications Union, which made the technical recommendation for European 625 line standard for video signals.

# Composite Video:

Composite video (CVS/CVBS) signal carries video picture information for color, brightness, and synchronizing signals for both horizontal and vertical scans.

# CIF:

CIF has 352(H) x 288(V) luminance pixels, and 176(H) x 144(V) chrominance pixels. QCIF is a similar picture format with one-quarter the size of CIF.

# EIA:

Electronic Industry Association. An industry lobbying group; it collects statistics and establishes testing standards for many types of home electronics.

# Field:

For interlaced video the total picture is divided into two fields, one even and one odd, each containing one half of the total vertical information. Each field takes one sixtieth of a second (one fiftieth for PAL) to complete. Two fields make a complete frame of video.

# Frame:

One frame (two fields) of video contains the full vertical interlaced information content of the picture. For NTSC this consists of 525 lines and PAL a frame is consisted of 625 lines.

# Gamma:

Cathode ray tubes (CRTs) do not have a linear relationship between brightness and the input voltage applied. To compensate for this non-linearity, a pre distortion or gamma correction is applied, generally at the camera source. A value of gamma equal to 2.2 is typical, but can vary for different CRT phosphors.

# Hue:

Attribution of visual sensation according to which area appears to be similar to one, or proportions of two, of the perceived colors red, yellow, green, and blue.

# NTSC:

Color TV standard developed in the U.S. in 1953 by National Television System Committee. NTSC is used in United States, Canada, Japan, in most of the American continent countries and in various Asian countries. The rest of the world uses either some variety of PAL or SECAM standards.

NTSC runs on 525 lines/frame and it's vertical frequency is 60Hz. NTSC's framerate is 29, 97 frames/sec.

# PAL:

PAL (Phase Alternating Line) TV standard was introduced in the early 1960's in Europe. It has better resolution than in NTSC, having 625 lines/frame, but the frame rate is slightly lower - 25 frames/sec. PAL is used in most of the western European countries (except France, where SECAM is used instead), Australia, various countries in Africa and in South America and in some Asian countries. There are various versions of PAL, the most commonly used method is PAL B/G, but others include PAL I (used in the UK and in

Ireland) and PAL M (hybrid standard, having the same resolution as NTSC, but uses PAL transmission and color coding technology).

# Saturation:

A characteristic describing color amplitude or intensity. A color of a given hue may consist of low or high saturation value, which relates to the vividness of color.

# AGC

Abbreviation for automatic gain control. On a TV or VCR, AGC is a circuit that automatically adjusts the incoming signal to the proper levels for display or recording. On a video camera, AGC is a circuit that automatically adjusts the sensitivity of the pickup tube to render the most pleasing image.

# Appendix B: Standard Compliance

# Notice for USA

![The image displays the letters 'F' and 'C' in a bold, black sans-serif font against a white background. The letter 'F' is positioned on the left, and the letter 'C' is on the right, curving around the right side of the 'F'.](.pci-mpg24-manual-18/5c30477a099ebbb6c490015b7154b985b8725c1c6550310060a1681b9996bce7.jpg)

Compliance Information Statement (Declaration of Conformity Procedure) DoC FCC Part 15

This equipment has been tested and found to comply with the limits for a Class A digital device, pursuant to Part 15 of the FCC Rules.

These limits are designed to provide reasonable protection against harmful interference in a residential installation or when the equipment is operated in a commercial environment.

This equipment generates, uses and can radiate radio frequency energy and, if not installed and used in accordance with the instructions, may cause harmful interference to radio communications. However, there is no guarantee that interference will not occur in a particular installation.

If this equipment does cause harmful interference to radio or television reception, which can be determined by turning the equipment off and on, the user is encouraged to try to correct the interference by one or more of the following measures:

▶ Reorient or relocate the receiving antenna.
▶ Increase the separation between the equipment and receiver.
▶ Connect the equipment into an outlet on a circuit different from that to which the receiver is connected.
- Consult the dealer or an experienced radio/TV technician for help.

# CE

# Notice for Europe

This product is in conformity with the Council Directive 89/336/EEC amended by 92/31/EEC and 93/68/EEC

This equipment has been tested and found to comply with EN55022/CISPR22 and EN55024/CISPR24. To meet EC requirements, shielded cables must be used to connect a peripheral to the card. This product has been tested in a typical class B compliant host system. It is assumed that this product will also achieve compliance in any class A compliant unit.

# Warranty Policy

Thank you for choosing ADLINK. To understand your rights and enjoy all the after-sales services we offer, please read the following carefully.

1. Before using ADLINK's products please read the user manual and follow the instructions exactly. When sending in damaged products for repair, please attach an RMA application form which can be downloaded from: http://rma.adlinktech.com/policy/.

2. All ADLINK products come with a limited two-year warranty, one year for products bought in China:

The warranty period starts on the day the product is shipped from ADLINK's factory.
▶ Peripherals and third-party products not manufactured by ADLINK will be covered by the original manufacturers' warranty.
For products containing storage devices (hard drives, flash cards, etc.), please back up your data before sending them for repair. ADLINK is not responsible for any loss of data.
▶ Please ensure the use of properly licensed software with our systems. ADLINK does not condone the use of pirated software and will not service systems using such software. ADLINK will not be held legally responsible for products shipped with unlicensed software installed by the user.
For general repairs, please do not include peripheral accessories. If peripherals need to be included, be certain to specify which items you sent on the RMA Request & Confirmation Form. ADLINK is not responsible for items not listed on the RMA Request & Confirmation Form.

3. Our repair service is not covered by ADLINK's guarantee in the following situations:

▶ Damage caused by not following instructions in the User's Manual.
▶ Damage caused by carelessness on the user's part during product transportation.
▶ Damage caused by fire, earthquakes, floods, lightening, pollution, other acts of God, and/or incorrect usage of voltage transformers.
▶ Damage caused by unsuitable storage environments (i.e. high temperatures, high humidity, or volatile chemicals).
▶ Damage caused by leakage of battery fluid during or after change of batteries by customer/user.
▶ Damage from improper repair by unauthorized ADLINK technicians.
▶ Products with altered and/or damaged serial numbers are not entitled to our service.
▶ This warranty is not transferable or extendible.
▶ Other categories not protected under our warranty.

4. Customers are responsible for shipping costs to transport damaged products to our company or sales office.

5. To ensure the speed and quality of product repair, please download an RMA application form from our company website: http://rma.adlinktech.com/policy. Damaged products with attached RMA forms receive priority.

If you have any further questions, please email our FAE staff: service@adlinktech.com.
[🔗 Link to the original document](.pci-mpg24-manual-18/pci-mpg24-manual-18.pdf)
