driver-peripherals-audio-des.md 51.2 KB
Newer Older
A
annie_wangli 已提交
1 2
# Audio

A
annie_wangli 已提交
3 4

## Audio Driver Overview
A
annie_wangli 已提交
5

A
annie_wangli 已提交
6
A multimedia system is an indispensable part in Internet of Things (IoT) devices. Audio is an important module of the multimedia system, and building an audio driver model is particularly important in device development.
A
annie_wangli 已提交
7

A
annie_wangli 已提交
8
This document describes the audio driver architecture and functional modules and how to develop audio drivers based on the Hardware Driver Foundation (HDF). Chip vendors can develop their own drivers and invocation of Hardware Abstraction Layer (HAL) APIs based on the driver architecture.
A
annie_wangli 已提交
9 10 11



A
annie_wangli 已提交
12
## Audio Driver Architecture
A
annie_wangli 已提交
13 14

The audio driver architecture is implemented based on the [HDF](https://device.harmonyos.com/en/docs/documentation/guide/driver-hdf-overview-0000001051715456). The audio driver architecture is as follows:
A
annie_wangli 已提交
15

A
annie_wangli 已提交
16 17 18
![](figures/Audio_architecture.png)

The driver architecture consists of the following:
A
annie_wangli 已提交
19 20 21 22 23
- Hardware Device Interface (HDI) adapter: implements the audio HAL driver (HDI adaptation) and provides hardware driver capability interfaces for the audio service (frameworks). The HDI adapter provides interface objects such as Audio Manager, Audio Adapter, Audio Control, Audio Capture, and Audio Render.
- Audio Interface Lib: works with the Audio Driver Model (ADM) in the kernel to control audio hardware, read recording data, and write playback data. The **Stream_ctrl_common** in the Audio Interface Lib interacts with the audio HDI adapter layer.
- ADM: helps system developers to develop scenario-specific applications for the multimedia audio subsystem. With the ADM, codec and DSP device vendors can adapt their driver code based on the unified interfaces provided by the ADM and implement quick development and easy adaptation to the OpenHarmony system.
- Audio Control Dispatch: dispatches the control instructions from the Audio Interface Lib to the driver layer.
- Audio Stream Dispatch: dispatches the data from the Audio Interface Lib to the driver layer.
A
annie_wangli 已提交
24

A
annie_wangli 已提交
25
- Card Manager: manages multiple audio adapters. Each audio adapter consists of the digital audio interface (DAI), platform, codec, accessory, DSP, and Smart Audio Power Manager (SAPM) modules.
A
annie_wangli 已提交
26
- Platform Drivers: driver adaptation layer.
A
annie_wangli 已提交
27
- SAPM: optimizes the power consumption policy of the ADM.
A
annie_wangli 已提交
28

A
annie_wangli 已提交
29
## Audio Driver Development
A
annie_wangli 已提交
30

A
annie_wangli 已提交
31
The following uses the Hi3516D V300 as an example to describe how to develop drivers based on the audio driver architecture.
A
annie_wangli 已提交
32

A
annie_wangli 已提交
33
### Audio ADM Architecture
A
annie_wangli 已提交
34
The audio driver provides the **hdf_audio_render**, **hdf_audio_capture**, and **hdf_audio_control** services for the HDI layer. The driver service nodes in the **dev** directory of the development board are as follows:
A
annie_wangli 已提交
35 36 37

```c
# ls -l hdf_audio*
A
annie_wangli 已提交
38 39 40 41 42
crw-rw---- 1 system system 248, 6 1970-01-01 00:00 hdf_audio_capture // Voice recording service.
crw-rw---- 1 system system 248,   4 1970-01-01 00:00 hdf_audio_codec_dev0 // Name of audio adapter 0.
crw-rw---- 1 system system 248,   4 1970-01-01 00:00 hdf_audio_codec_dev1 // Name of audio adapter 1.
crw-rw---- 1 system system 248, 5 1970-01-01 00:00 hdf_audio_control // Audio control service.
crw-rw---- 1 system system 248,   7 1970-01-01 00:00 hdf_audio_render     // Audio playback service.
A
annie_wangli 已提交
43 44
```

A
annie_wangli 已提交
45
The audio adapters have the following driver services:
A
annie_wangli 已提交
46 47

hdf\_audio\_codec\_dev0
A
annie_wangli 已提交
48 49
- **dma\_service\_0**: direct memory access (DMA) service                 
- **dai_service**: CPU DAI service             
A
annie_wangli 已提交
50
- **codec\_service\_0**: codec service (built-in codec)
A
annie_wangli 已提交
51
- **dsp\_service\_0**: DSP service (optional)        
A
annie_wangli 已提交
52 53 54 55 56 57 58

hdf\_audio\_codec\_dev1
- **dma\_service\_0**: DMA service
- **dai_service**: CPU DAI service
- **codec\_service\_1**: accessory service (SmartPA)
- **dsp\_service\_0**: DSP service (optional)

A
annie_wangli 已提交
59
#### Startup Process
A
annie_wangli 已提交
60 61 62

![](figures/ADM_startup_flowchart.png)

A
annie_wangli 已提交
63
1. When the system starts, the platform, codec, accessory, DSP, and DAI drivers of the audio module are loaded first. Each driver obtains the configuration information from its configuration file and saves the obtained information to the data structures.
A
annie_wangli 已提交
64 65 66

2. Each driver module calls the ADM registration interface to add itself to the linked list of the driver module.

A
annie_wangli 已提交
67
3. The ADM obtains the hdf_audio_driver_0 and hdf_audio_driver_1 configuration and loads the devices of each module.
A
annie_wangli 已提交
68

A
annie_wangli 已提交
69
4. The ADM module initializes each module device by calling the initialization API of the respective module.
A
annie_wangli 已提交
70

A
annie_wangli 已提交
71
5. The initialized audio devices are added to the cardManager linked list.
A
annie_wangli 已提交
72

A
annie_wangli 已提交
73 74
#### Playback Process

A
annie_wangli 已提交
75
![=](figures/ADM_playback_flowchart.png)
A
annie_wangli 已提交
76

A
annie_wangli 已提交
77
1. The Audio Interface Lib sends the **Render Open** instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to deliver the instruction.
A
annie_wangli 已提交
78

A
annie_wangli 已提交
79
2. The Audio Interface Lib sends a path select instruction to the Control Dispatch service. The Control Dispatch service calls the DAI API to set the path.
A
annie_wangli 已提交
80

A
annie_wangli 已提交
81
3. The Audio Interface Lib sends hardware parameters to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to set the hardware parameters.
A
annie_wangli 已提交
82

A
annie_wangli 已提交
83
4. The Audio Interface Lib sends the start playing instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to perform related settings for each module.
A
annie_wangli 已提交
84

A
annie_wangli 已提交
85
5. The Audio Interface Lib sends audio data to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the **Platform AudioPcmWrite** API to send the audio data to DMA.
A
annie_wangli 已提交
86

A
annie_wangli 已提交
87
6. The Audio Interface Lib sends the stop playing instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the stop API of each module to perform related stop settings for each module.
A
annie_wangli 已提交
88

A
annie_wangli 已提交
89
7. The Audio Interface Lib sends the **Render Close** instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the **Platform AudioRenderClose** API to release resources.
A
annie_wangli 已提交
90

A
annie_wangli 已提交
91
#### Control Process
A
annie_wangli 已提交
92 93 94

![](figures/ADM_control_flowchart.png)

A
annie_wangli 已提交
95 96
1. When the volume needs to be adjusted, the Audio Interface Lib sends an instruction for obtaining the volume range to the Control Dispatch service. The Control Dispatch service parses the instruction and calls **get()** of the codec module to obtain the volume range.
2. The Audio Interface Lib sends an instruction for setting the volume to the Control Dispatch service. The Control Dispatch service parses the instruction and calls **Set()** of the codec module to set the volume.
A
annie_wangli 已提交
97

A
annie_wangli 已提交
98
### Audio Driver Development Procedure
A
annie_wangli 已提交
99

A
annie_wangli 已提交
100
#### Development on an Adapted Platform
A
annie_wangli 已提交
101

A
annie_wangli 已提交
102
The following figure shows the process for developing the codec or accessory (SmartPA) driver on a chip platform (Hi3516D V300) to which the ADM has adapted.
A
annie_wangli 已提交
103

A
annie_wangli 已提交
104
![](figures/audio_development_flowchart_1.png)
A
annie_wangli 已提交
105

A
annie_wangli 已提交
106
- Add register information to the private HDF configuration source (HCS) of the codec or SmartPA based on the chip description.
A
annie_wangli 已提交
107

A
annie_wangli 已提交
108
- If the workflow of the newly added codec or SmartPA is the same as that of the existing codec or SmartPA, you do not need to implement the operation function set or configure the compilation file for the newly added codec or SmartPA.
A
annie_wangli 已提交
109

A
annie_wangli 已提交
110
- Perform build, debugging, and testing.
A
annie_wangli 已提交
111

A
annie_wangli 已提交
112
#### Development on a New Platform
A
annie_wangli 已提交
113

A
annie_wangli 已提交
114
The following figure shows the driver development process if the ADM has not adapted to the platform.
A
annie_wangli 已提交
115

A
annie_wangli 已提交
116
![](figures/audio_development_flowchart_2.png)
A
annie_wangli 已提交
117

A
annie_wangli 已提交
118
The codec (optional), DAI, DMA, DSP (optional), and SmartPA (optional) modules of the audio adapter need to be adapted to the new platform.
A
annie_wangli 已提交
119

A
annie_wangli 已提交
120
- Add register information of each module driver to the private configuration file of the respective module according to the chip description.
A
annie_wangli 已提交
121

A
annie_wangli 已提交
122
- Implement the operation function set of each module.
A
annie_wangli 已提交
123

A
annie_wangli 已提交
124
- Modify the compilation file of the audio module.
A
annie_wangli 已提交
125

A
annie_wangli 已提交
126
- Perform build, debugging, and testing.
A
annie_wangli 已提交
127 128 129



A
annie_wangli 已提交
130
## Audio Driver Development Examples
A
annie_wangli 已提交
131 132 133

Code path: **drivers/peripheral/audio**

A
annie_wangli 已提交
134
The following uses Hi3516D V300 as an example to describe how to develop the audio codec driver, accessory driver, DAI driver, and platform driver.
A
annie_wangli 已提交
135

A
annie_wangli 已提交
136
### Codec Driver Development Example
A
annie_wangli 已提交
137 138 139 140 141 142 143 144
Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/codec**

The major steps for developing the codec driver are as follows:
1. Define and fill in a codec instance.
2. Implement callbacks for the codec instance.
3. Register and bind the codec instance to the HDF.
4. Configure the HCS and makefile.

A
annie_wangli 已提交
145
#### Filling in Codec Data Structures
A
annie_wangli 已提交
146 147 148 149 150

Fill in the following data structures for the codec module:

- **g_codecData**: operation function set and private data set of the codec device.

A
annie_wangli 已提交
151
- **g_codecDaiDeviceOps**: codec DAI device operation function set, including APIs for starting transmission and setting parameters.
A
annie_wangli 已提交
152 153 154 155 156 157

- **g_codecDaiData**: operation function set and private data set of the digital audio interface of the codec.

```c
struct CodecData g_codecData = {
  .Init = CodecDeviceInit,     // Initialize the codec device (need to be implemented for a new platform).
A
annie_wangli 已提交
158 159
  .Read = AudioDeviceReadReg,  // Read the register (already implemented in the existing framework and no adaptation needed).
  .Write = AudioDeviceWriteReg,  // Write the register (already implemented in the existing framework and no adaptation needed).
A
annie_wangli 已提交
160 161 162
};

struct AudioDaiOps g_codecDaiDeviceOps = {
A
annie_wangli 已提交
163
  .Startup = CodecDaiStartup,   // Start transmission (need to be implemented for a new platform).
A
annie_wangli 已提交
164 165 166 167
  .HwParams = CodecDaiHwParams, // Set parameters (need to be implemented for a new platform).
};

struct DaiData g_codecDaiData = {
A
annie_wangli 已提交
168 169
  .DaiInit = CodecDaiDeviceInit,  // Initialize the codec DAI device (need to be implemented for a new platform).
  .ops = &g_codecDaiDeviceOps,  // codec DAI device operation function set.
A
annie_wangli 已提交
170 171 172
};
```

A
annie_wangli 已提交
173
#### Initializing codecDevice and codecDai
A
annie_wangli 已提交
174

A
annie_wangli 已提交
175
**CODECDeviceInit** sets audio input/audio output (AIAO), initializes registers, inserts **g_audioControls** into the control linked list, initializes the power management, and selects a path.
A
annie_wangli 已提交
176 177 178 179 180

```c
int32_t CodecDeviceInit(struct AudioCard *audioCard, struct CodecDevice *codec)
{
  	...
A
annie_wangli 已提交
181
	/* Register set() and get() of the AIAO module on the Hi3516 platform. */
A
annie_wangli 已提交
182 183
	CodecSetCtlFunc(codec->devData, AudioCodecAiaoGetCtrlOps, AudioCodecAiaoSetCtrlOps)
  	...
A
annie_wangli 已提交
184
	/* Hi3516 codec register IoRemap */
A
annie_wangli 已提交
185 186
	CodecHalSysInit();
  	...
A
annie_wangli 已提交
187
	/* Initialize the codec registers of the Hi3516 platform. */
A
annie_wangli 已提交
188 189
	CodecRegDefaultInit(codec->devData->regCfgGroup);
  	...
A
annie_wangli 已提交
190
	/* Insert g_audioControls of the Hi3516 platform to the controller linked list.*/
A
annie_wangli 已提交
191 192
  	AudioAddControls(audioCard, codec->devData->controls, codec->devData->numControls);
  	...
A
annie_wangli 已提交
193
	/* Load the codec of the Hi3516 platform to the SAPM. */
A
annie_wangli 已提交
194 195
	AudioSapmNewComponents(audioCard, codec->devData->sapmComponents, codec->devData->numSapmComponent);
  	...
A
annie_wangli 已提交
196
	/* Insert the codec of the Hi3516 platform to the audioRoutes linked list. */
A
annie_wangli 已提交
197 198 199 200
  	AudioSapmAddRoutes(audioCard, g_audioRoutes, HDF_ARRAY_SIZE(g_audioRoutes);
   	...
	AudioSapmNewControls(audioCard);
  	...
A
annie_wangli 已提交
201
	/* Hi3516 codec power management */
A
annie_wangli 已提交
202 203 204 205 206 207
  	AudioSapmSleep(audioCard);
   	...
   	return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
208
**CodecDaiDeviceInit** initializes the codec DAI device. This API is not used on the Hi3516 and is reserved.
A
annie_wangli 已提交
209 210 211 212 213 214 215 216 217 218 219 220

```c
int32_t CodecDaiDeviceInit(struct AudioCard *card, const struct DaiDevice *device)

{
  	...
	AUDIO_DRIVER_LOG_DEBUG("codec dai device name: %s\n", device->devDaiName);
  	(void)card;
  	return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
221
#### Implementing the Codec Operation Function Set
A
annie_wangli 已提交
222 223 224

The codec module is encapsulated with the **read()** and **write()** functions of the read and write registers at the operating system abstraction layer (OSAL).

A
annie_wangli 已提交
225
If the new platform cannot use the OSAL **read()** and **write()** functions to operate registers, you should implement them.
A
annie_wangli 已提交
226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273

```c
int32_t AudioDeviceReadReg(unsigned long virtualAddress, uint32_t reg, uint32_t *val)
{
  ...
  *val = OSAL_READL((void *)((uintptr_t)(virtualAddress + reg)));
  return HDF_SUCCESS;
}

int32_t AudioDeviceWriteReg(unsigned long virtualAddress, uint32_t reg, uint32_t value)
{
  OSAL_WRITEL(value, (void *)((uintptr_t)(virtualAddress + reg)));
  return HDF_SUCCESS;
}
```

**CodecDaiStartup** completes startup settings.

```c
int32_t CodecDaiStartup(const struct AudioCard *card, const struct DaiDevice *device)
{
  int32_t ret;
  ...
  (void)card;
  ret = CodecSetAdcTuneEnable(device->devData->regCfgGroup);
  ...
  return HDF_SUCCESS;
}
```

**CodecDaiHwParams** sets parameters, including the sampling rate and bit width.

```c
int32_t CodecDaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param)
{
  unsigned int bitWidth;
  struct CodecDaiParamsVal codecDaiParamsVal;
  ...
  int ret = AudioFramatToBitWidth(param->format, &bitWidth);
  ...
  codecDaiParamsVal.frequencyVal = param->rate;
  codecDaiParamsVal.formatVal = bitWidth;
  ret = CodecDaiParamsUpdate(card->rtd->codecDai->devData->regCfgGroup, codecDaiParamsVal);
  ...
  return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
274
#### Registering and Binding Codec to HDF
A
annie_wangli 已提交
275

276
This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/Readme-EN.md).
A
annie_wangli 已提交
277

A
annie_wangli 已提交
278
Fill in the **g_codecDriverEntry** structure. Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. Implement the pointers to the **Bind**, **Init**, and **Release** functions.
A
annie_wangli 已提交
279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305

drivers/peripheral/audio/chipsets/hi3516dv300/codec/src/hi3516_codec_adapter.c

```c
struct HdfDriverEntry g_codecDriverEntry = {
   .moduleVersion = 1,
   .moduleName = "CODEC_HI3516",
   .Bind = CodecDriverBind,
   .Init = CodecDriverInit,
   .Release = CodecDriverRelease,
};
HDF_INIT(g_codecDriverEntry);
```

**CodecDriverBind** binds the device in the HDF to the codec and registers the codec service with the HDF.

```c
static int32_t CodecDriverBind(struct HdfDeviceObject *device)
{
  struct CodecHost *codecHost = (struct CodecHost *)OsalMemCalloc(sizeof(*codecHost));
  ...
  codecHost->device = device;
  device->service = &codecHost->service;
  return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
306
**CodecDriverInit** obtains the **codecService** name and private register configuration, and inserts them into the linked list by using **AudioRegisterCodec**.
A
annie_wangli 已提交
307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331

```c
static int32_t CodecDriverInit(struct HdfDeviceObject *device)
{
  ...
  CodecGetConfigInfo(device, &g_codecData);
  CodecSetConfigInfo(&g_codecData, &g_codecDaiData);
  CodecGetServiceName(device, &g_codecData.drvCodecName);
  CodecGetDaiName(device, &g_codecDaiData.drvDaiName);
  AudioRegisterCodec(device, &g_codecData, &g_codecDaiData);
  ...
  return HDF_SUCCESS;
}
```

**CodecDriverRelease** releases driver resources.

```c
static void CodecDriverRelease(struct HdfDeviceObject *device)
{
   codecHost = (struct CodecHost *)device->service;
   OsalMemFree(codecHost);
}
```

A
annie_wangli 已提交
332
#### Configuring HCS<a name="section4115"></a>
A
annie_wangli 已提交
333

A
annie_wangli 已提交
334
Configure the driver node, loading sequence, and service name in the .hcs file. For details about the HCS syntax, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md) in the HDF.
A
annie_wangli 已提交
335 336 337

Path of the standard-system configuration file:

338
**vendor/hisilicon/hispark_taurus_standard/hdf_config/khdf/**
A
annie_wangli 已提交
339 340 341

Path of the small-system configuration file:

A
annie_wangli 已提交
342
**vendor/hisilicon/hispark_taurus/hdf_config/**
A
annie_wangli 已提交
343 344 345

**Configuring Codec Device Information in device_info.hcs**

A
annie_wangli 已提交
346
Add codec node configuration. Modify **moduleName** in the configuration file. The value must be the same as **moduleName** in the **HdfDriverEntry** structure. Generally, the value should present the hardware platform. For example, moduleName = "CODEC_HI3516".
A
annie_wangli 已提交
347 348 349 350 351 352 353

The code snippet is as follows:

```c
     audio :: host {
      device_codec :: device {
         device0 :: deviceNode {
A
annie_wangli 已提交
354 355
           policy = 1;   // The codec module provides services only for the kernel.
           priority = 50;  // The codec module must be loaded before the load of the HDF_AUDIO module.
A
annie_wangli 已提交
356 357 358 359 360 361 362 363 364 365 366
           preload = 0;
           permission = 0666;
           moduleName = "CODEC_HI3516"; // The value must be the same as moduleName in HdfDriverEntry.
           serviceName = "codec_service_0"; // Name of the service provided externally.
           deviceMatchAttr = "hdf_codec_driver"; // Name of the private attribute, which is used to match the corresponding private data (including the register configuration).
         }
       }
```

**Configuring Dependencies in audio_config.hcs**

A
annie_wangli 已提交
367
Configure dependencies between the codec, platform, DAI, DSP, and accessory for the audio adapters.
A
annie_wangli 已提交
368 369 370 371 372

The code snippet is as follows:

```c
root {
A
annie_wangli 已提交
373
    platform {
A
annie_wangli 已提交
374 375 376 377 378 379 380 381 382 383
        ...
        controller_0x120c1001 :: card_controller {
            // Set the private data attribute name, which must be the same as deviceMatchAttr in device_info.hcs.
            match_attr = "hdf_audio_driver_1"; 
            serviceName = "hdf_audio_smartpa_dev0"; // Name of the service provided externally.
            accessoryName = "codec_service_1"; // External codec service name.
            platformName = "dma_service_0"; // DMA service.
            cpuDaiName = "dai_service"; // CPU DAI service.
            accessoryDaiName = "accessory_dai"; // External DAI.
            dspName = "dsp_service_0"; // DSP service name.
A
annie_wangli 已提交
384
            dspDaiName = "dsp_dai"; // DSP DAI.
A
annie_wangli 已提交
385 386 387 388 389 390 391 392 393
        }
    }
}
```

**Configuring Private Registers in codec_config.hcs**

The configuration matches **deviceMatchAttr** of the codec configured in **device_info.hcs**. It includes the register configuration.

A
annie_wangli 已提交
394
Binding the control functionality configuration is to configure the control functionalities and their register parameters in the .hcs file according to unified structure specifications. The configuration can be obtained and parsed, and added to the controller linked list.
A
annie_wangli 已提交
395

A
annie_wangli 已提交
396
- **regConfig**: register and control functionality configuration
A
annie_wangli 已提交
397

A
annie_wangli 已提交
398
- **ctrlParamsSeqConfig**: control functionality register configuration
A
annie_wangli 已提交
399 400 401 402 403 404 405 406 407

- **daiStartupSeqConfig**: DAI startup configuration

- **daiParamsSeqConfig**: playback parameter configuration

- **resetSeqConfig**: reset process register configuration

- **initSeqConfig**: initialization process register configuration

A
annie_wangli 已提交
408
- **controlsConfig**: control functionality configuration. The **array index** (specific service scenario) and **iface** (same as the HAL) are of fixed values.
A
annie_wangli 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431

```
array index
0: Main Playback Volume
1: Main Capture Volume
2: Playback Mute
3: Capture Mute
4: Mic Left Gain
5: Mic Right Gain
6: External Codec Enable
7: Internally Codec Enable
8: Render Channel Mode
9: Capture Channel Mode
iface
0: virtual dac device
1: virtual adc device
2: virtual adc device
3: virtual mixer device
4: Codec device
5: PGA device
6: AIAO device
```

A
annie_wangli 已提交
432
**ctrlParamsSeqConfig**: control function register configuration. The **item** sequence corresponds to the **item** sequence in **controlsConfig**, indicating the register configuration corresponding to a function.
A
annie_wangli 已提交
433 434 435

```c
 root {
A
annie_wangli 已提交
436
    platform {
A
annie_wangli 已提交
437 438 439 440 441 442 443 444 445 446 447 448
        template codec_controller {
            match_attr = "";
            serviceName = "";
            codecDaiName = "";
        }
        controller_0x120c1030 :: codec_controller {
            match_attr = "hdf_codec_driver";
            serviceName = "codec_service_0";
            codecDaiName = "codec_dai";
            
	        /* Base address of the Hi3516 register*/
            idInfo {
A
annie_wangli 已提交
449 450
                chipName = "hi3516";        // Codec name
                chipIdRegister = 0x113c0000;  // Codec base address
A
annie_wangli 已提交
451 452 453
                chipIdSize = 0x1000;        // Codec address offset
            }
            
A
annie_wangli 已提交
454
	       /* Register configuration, including configuration of registers */
A
annie_wangli 已提交
455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
            regConfig {                
               /*  reg: register address
                    rreg: register address
                    shift: shift bits
                    rshift: rshift bits
                    min: min value
                    max: max value
                    mask: mask of value
                    invert: enum InvertVal 0-uninvert 1-invert
                    value: value
                */

                /* reg, value */
                initSeqConfig = [
                    0x14,    0x04000002,
                    0x18,    0xFD200004,
                    0x1C,    0x00180018,
                    0x20,    0x83830028,
                    0x24,    0x00005C5C,
                    0x28,    0x00130000,
                    0x30,    0xFF035A00,
                    0x34,    0x08000001,
                    0x38,    0x06062424,
                    0x3C,    0x1E1EC001,
                    0x14,    0x04000002
                ];            
                
A
annie_wangli 已提交
482
                /* Control functionality configuration
A
annie_wangli 已提交
483 484 485 486 487 488 489 490 491 492 493
                   array index, iface, enable*/
                controlsConfig = [
                    0,  0,  0,  
                    1,  1,  1,
                    2,  0,  1,
                    3,  1,  1,
                    4,  2,  1,
                    5,  2,  1,
                    8,  6,  0,
                    9,  6,  0,
                ];                
A
annie_wangli 已提交
494
                /* Control functionality register configuration 
A
annie_wangli 已提交
495 496 497 498 499 500
                   reg, rreg, shift, rshift, min, max, mask, invert, value */
                ctrlParamsSeqConfig = [
                    0x3c, 0x3c, 24, 24, 0x0, 0x57, 0x7F, 1, 0,   //"Main Capture Volume"
                    0x38, 0x38, 31, 31, 0x0, 0x1, 0x1, 0, 0,     //"Playback Mute"
                    0x3c, 0x3c, 31, 31, 0x0, 0x1, 0x1, 0, 0,      //"Capture Mute"
                    0x20, 0x20, 16, 16, 0x0, 0xF, 0x1F, 0, 0,     //"Mic Left Gain"
A
annie_wangli 已提交
501 502
                    0x20, 0x20, 24, 24, 0x0, 0xF, 0x1F, 0, 0,     // "Mic Right Gain"
                    0x2000, 0x2000, 16, 16, 0x0, 0x7, 0x7, 0, 0,  // "Render Channel Mode"
A
annie_wangli 已提交
503
                    0x1000, 0x1000, 16, 16, 0x0, 0x7, 0x7, 0, 0  //"Capture Channel Mode"
A
annie_wangli 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613
                ];

                /* After the upper layer delivers parameters, write audio-related data to registers.
	               reg, rreg, shift, rshift, min, max, mask, invert, value */
                daiParamsSeqConfig = [  
                    0x30, 0x30, 13, 13, 0x0, 0x1F, 0x1F, 0, 0x0,    // i2s_frequency
                    0x1C, 0x1C, 6, 6, 0x0, 0x3, 0x3, 0, 0x0,       // adc_mode_sel
                    0x30, 0x30, 22, 22, 0x0, 0x3, 0x3, 0, 0x0,     // i2s_datawith
                ];

                /* Configuration of the power management function register.
                   reg, rreg, shift, rshift, min, max, mask, invert, value */
                ctrlSapmParamsSeqConfig = [  
                    0x20, 0x20, 23, 23, 0x0, 0x1, 0x1, 0, 0,  //LPGA MIC 0 -- connect MIC
                    0x20, 0x20, 31, 31, 0x0, 0x1, 0x1, 0, 0,  //RPGA MIC 0 -- connect MIC
                    0x30, 0x30, 27, 27, 0x0, 0x1, 0x1, 0, 0,  //dacl to dacr mixer
                    0x30, 0x30, 26, 26, 0x0, 0x1, 0x1, 0, 0  //dacr to dacl mixer
                ];

        		/*
                 Power management component configuration
                 componentName: function name, {"ADCL", "ADCR", "DACL", "DACR", "LPGA", "RPGA", "SPKL", "SPKR", "MIC"} array index.
                 sapmType,compNameIndex,reg, mask,shift,invert, kcontrolNews,kcontrolsNum
                */
                sapmComponent = [ 
                    10,  0,  0x20,  0x1,  15,  1,  0,  0,    //ADCL
                    10,  1,  0x20,  0x1,  14,  1,  0,  0,    //ADCR
                    11,  2,  0x14,  0x1,  11,  1,  0,  0,    //DACL
                    11,  3,  0x14,  0x1,  12,  1,  0,  0,    //DACR
                    8,   4,  0x20,  0x1,  13,  1,  1,  1,    //LPGA
                    8,   5,  0x20,  0x1,  12,  1,  2,  1,    //RPGA
                    15,  6,  0,     0x1,  0,   0,  3,  1,    //SPKL
                    15,  7,  0,     0x1,  0,   0,  4,  1,    //SPKR
                    0,   8,  0,     0x1,  0,   0,  0,  0     //MIC
                ];
                
	          /* Power management function configuration
                   array index,  iface,  enable
              */ 
                sapmConfig = [
        	        0,    5,    1,
                    1,    5,    1,
                    2,    0,    1,
                    3,    0,    1
                ];
            }
        }
    }
}
```

Read the .hcs files in the C code to obtain register configuration.

```c
static int32_t CodecDriverInit(struct HdfDeviceObject *device)
{
  ...
  CodecGetConfigInfo(device, &g_codecData) ;
  CodecSetConfigInfo(&g_codecData, &g_codecDaiData);
  ...
  return HDF_SUCCESS;
} 
```

When the codec is registered, the input parameter **device** contains controller_0x120c1030 node information. You only need to parse the node to obtain the configuration information.

```c
int32_t CodecGetConfigInfo(const struct HdfDeviceObject *device, struct CodecData *codecData)
{
  codecData->regConfig = (struct AudioRegCfgData *)OsalMemCalloc(sizeof(*(codecData->regConfig)));
  CodecGetRegConfig(device, codecData->regConfig);
  return HDF_SUCCESS;
}
```

Obtain the node configuration to configure the node.

```c
int32_t CodecGetRegConfig(const struct HdfDeviceObject *device, struct AudioRegCfgData *configData)
{
    ...
    drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE);
    ...
    idNode = drsOps->GetChildNode(root, "idInfo");
    ParseAudioAttr(drsOps, idNode, &configData->audioIdInfo);
    regCfgNode = drsOps->GetChildNode(root, "regConfig");
    ...
    DEV_RES_NODE_FOR_EACH_ATTR(regCfgNode, regAttr) {
    ...
    return HDF_SUCCESS;
}
```

Obtain and use the configuration of the **regConfig** node. After the configuration files are parsed, the register information in the code can be directly updated.

```c
int32_t CodecDeviceInit(struct AudioCard *audioCard, struct CodecDevice *codec)
{
...
    if (CodecRegDefaultInit(codec->devData->regCfgGroup) != HDF_SUCCESS) {
        AUDIO_DRIVER_LOG_ERR("CodecRegDefaultInit failed.");
        return HDF_FAILURE;
    }
...
    return HDF_SUCCESS;
}
```



A
annie_wangli 已提交
614
### Accessory Driver Development Example
A
annie_wangli 已提交
615 616 617 618 619 620 621 622
Code path: **drivers/peripheral/audio/chipsets/tfa9879/accessory**

SmartPA is a type of accessory driver. The SmartPA development procedure is similar to the codec development procedure.
1. Define and fill in an accessory instance.
2. Implement callbacks for the accessory instance.
3. Register and bind the accessory instance to the HDF.
4. Configure the HCS and makefile.

A
annie_wangli 已提交
623
#### Filling in Accessory Data Structures
A
annie_wangli 已提交
624 625 626

Fill in the following data structures for the accessory module:

A
annie_wangli 已提交
627
- **g_tfa9879Data**: operation function set of the accessory device. It contains the configuration in the .hcs file, and defines and maps the functions for initializing the accessory device and reading and writing registers.
A
annie_wangli 已提交
628

A
annie_wangli 已提交
629
- **g_tfa9879DaiDeviceOps**: data set of the DAI of the accessory device. It defines and maps the operation set of the accessory device DAI.
A
annie_wangli 已提交
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651

- **g_tfa9879DaiData**: data set of the DAI of the accessory device. It defines and maps the driver name, initialization, and operation set of the data access interface of the accessory device.

```c
struct AccessoryData g_tfa9879Data = {
    .Init = Tfa9879DeviceInit,
    .Read = AccessoryDeviceRegRead,
    .Write = AccessoryDeviceRegWrite,
};

struct AudioDaiOps g_tfa9879DaiDeviceOps = {
    .Startup = Tfa9879DaiStartup,
    .HwParams = Tfa9879DaiHwParams,
};

struct DaiData g_tfa9879DaiData = {
    .drvDaiName = "accessory_dai",
    .DaiInit = Tfa9879DaiDeviceInit,
    .ops = &g_tfa9879DaiDeviceOps,
};
```

A
annie_wangli 已提交
652
#### Initializing accessoryDevice and accessoryDai
A
annie_wangli 已提交
653

A
annie_wangli 已提交
654
As the entry function for device initialization, **Tfa9879DeviceInit** sets the address of the SmartPA I2C device, obtains configuration data, initializes (including resets) the device registers, and adds the control functionality to the controller linked list. The current demo also includes the initialization of the registers related to the Hi3516D V300 device, such as initialization of GPIO pins.
A
annie_wangli 已提交
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670

```c
int32_t Tfa9879DeviceInit(struct AudioCard *audioCard, const struct AccessoryDevice *device)
{
    int32_t ret;
    ...
    g_accessoryTransferData.i2cDevAddr = TFA9879_I2C_DEV_ADDR;  // 0x6D
    // Obtain configuration data.
    ret = AccessoryDeviceCfgGet(device->devData, &g_accessoryTransferData);
    ...
    // Initialize GPIO pins.
    ret = Hi35xxGpioPinInit();
    ...
    // Initialize device registers.
    ret = AccessoryDeviceCtrlRegInit();
    ...
A
annie_wangli 已提交
671
    // Bind the control functionality configuration.
A
annie_wangli 已提交
672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
    ret = AudioAddControls(audioCard, g_accessoryTransferData.accessoryControls,
                           g_accessoryTransferData.accessoryCfgCtrlCount);
    ...
}
```

**AccessoryI2cReadWrite** reads and writes I2C registers.

```c
int32_t AccessoryI2cReadWrite(struct AudioAddrConfig *regAttr, uint16_t rwFlag)
{
    int32_t ret;
    DevHandle i2cHandle;
    int16_t transferMsgCount = 1;
    uint8_t regs[I2C_REG_LEN];
    struct I2cMsg msgs[I2C_MSG_NUM];
    ...
    i2cHandle = I2cOpen(I2C_BUS_NUM);
    ...
    if (rwFlag == I2C_FLAG_READ) {
        transferMsgCount = I2C_MSG_NUM;
    }
    ret = AccessoryI2cMsgFill(regAttr, rwFlag, regs, msgs);
    ...
    ret = I2cTransfer(i2cHandle, msgs, transferMsgCount);
    ...
    AccessoryI2cRelease(msgs, transferMsgCount, i2cHandle);
    return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
703
#### Implementing the Accessory Operation Function Set
A
annie_wangli 已提交
704

705
The callbacks **AccessoryDeviceRegRead** and **AccessoryDeviceRegWrite** invoke **AccessoryI2cReadWrite** to read and write the control register values.
A
annie_wangli 已提交
706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765

```c
int32_t AccessoryDeviceRegRead(const struct AccessoryDevice *codec, uint32_t reg, uint32_t *val)
{
    int32_t ret;
    struct AudioAddrConfig regAttr;
    ...
    (void)codec;
    regAttr.addr = (uint8_t)reg;
    regAttr.value = 0;
    ret = AccessoryI2cReadWrite(&regAttr, I2C_FLAG_READ);
    if (ret != HDF_SUCCESS) {
        AUDIO_DRIVER_LOG_ERR("failed.");
        return HDF_FAILURE;
    }
    *val = regAttr.value;
    ...
    return HDF_SUCCESS;
}

int32_t AccessoryDeviceRegWrite(const struct AccessoryDevice *codec, uint32_t reg, uint32_t value)
{
    int32_t ret;
    struct AudioAddrConfig regAttr;
    (void)codec;
    regAttr.addr = (uint8_t)reg;
    regAttr.value = (uint16_t)value;
    ret = AccessoryI2cReadWrite(&regAttr, 0);
    ...
    return HDF_SUCCESS;
}
```

**Tfa9879DaiStartup** performs startup settings. The code snippet is as follows:

```c
int32_t Tfa9879DaiStartup(const struct AudioCard *card, const struct DaiDevice *device)
{
    int ret;
    (void)card;
	(void)device;
	// Set the working status of SmartPA.
    ret = Tfa9879WorkStatusEnable();
    ...
    return HDF_SUCCESS;
}

```

**Tfa9879DaiHwParams** delivers playback parameters. The code snippet is as follows:

```c
int32_t Tfa9879DaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param)
{
    int32_t ret;
    uint16_t frequency, bitWidth;
    struct DaiParamsVal daiParamsVal;
    (void)card;
	...
	// Set the sampling rate.
A
annie_wangli 已提交
766
    ret = AccessoryDeviceFrequencyParse(param->rate, &frequency);
A
annie_wangli 已提交
767 768 769 770 771 772 773 774 775 776 777 778 779
	...
	// Set the bit width.
    ret = Tfa9879FormatParse(param->format, &bitWidth);
    ...
    daiParamsVal.frequencyVal = frequency;
    daiParamsVal.formatVal = bitWidth;
	daiParamsVal.channelVal = param->channels; // Set the audio channel.
    ret = AccessoryDaiParamsUpdate(daiParamsVal);
    ...
    return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
780
#### Registering and Binding Accessory to HDF
A
annie_wangli 已提交
781

782
This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/Readme-EN.md).
A
annie_wangli 已提交
783

A
annie_wangli 已提交
784
Fill in the **g_tfa9879DriverEntry** structure. Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. Implement the pointers to the **Bind**, **Init**, and **Release** functions.
A
annie_wangli 已提交
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820

drivers/peripheral/audio/chipsets/tfa9879/accessory/src/tfa9879_accessory_adapter.c

```c
static int32_t Tfa9879DriverBind(struct HdfDeviceObject *device)
{
    (void)device;
    AUDIO_DRIVER_LOG_INFO("success!");
    return HDF_SUCCESS;
}

static int32_t Tfa9879DriverInit(struct HdfDeviceObject *device)
{
    int32_t ret;
    ...
    // Obtain configuration data from .hcs files.
    ret = AccessoryGetConfigInfo(device, &g_tfa9879Data); 
    ...
    ret = ret = GetServiceName(device);
    ...
    ret = AudioRegisterAccessory(device, &g_tfa9879Data, &g_tfa9879DaiData);
    ....
    return HDF_SUCCESS;
}

/* HdfDriverEntry definitions */
struct HdfDriverEntry g_tfa9879DriverEntry = {
    .moduleVersion = 1,
    .moduleName = "CODEC_TFA9879",
    .Bind = Tfa9879DriverBind,
    .Init = Tfa9879DriverInit,
    .Release = NULL,
};
HDF_INIT(g_tfa9879DriverEntry);
```

A
annie_wangli 已提交
821
#### Configuring HCS
A
annie_wangli 已提交
822 823 824 825 826

For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**.



A
annie_wangli 已提交
827
### Platform Driver Development Example
A
annie_wangli 已提交
828 829
Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/soc**

A
annie_wangli 已提交
830
In audio driver development, the Platform module is configured to adapt to the DMA driver. The major steps for developing the platform driver are as follows:
A
annie_wangli 已提交
831 832 833 834 835
1. Define and fill in a platform instance.
2. Implement callbacks for the platform instance.
3. Register and bind the platform instance to the HDF.
4. Configure the HCS and makefile.

A
annie_wangli 已提交
836
#### Filling in Platform Data Structures
A
annie_wangli 已提交
837 838 839 840 841 842 843 844 845 846

Fill in the following structures for the platform module:

- **g_platformData**: private configuration of the platform device, including the initialization and operation functions of the platform device.

- **g_dmaDeviceOps**: DMA device operation function set, including the encapsulation of some common DMA APIs.

```c
struct AudioDmaOps g_dmaDeviceOps = {
    .DmaBufAlloc = Hi3516DmaBufAlloc,             // Apply for memory for the DMA device.
A
annie_wangli 已提交
847
    .DmaBufFree = Hi3516DmaBufFree,               // Release the memory of the DMA device.
A
annie_wangli 已提交
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863
    .DmaRequestChannel = Hi3516DmaRequestChannel, // Request a DMA channel.
    .DmaConfigChannel = Hi3516DmaConfigChannel,   // Configure the DMA channel.
    .DmaPrep = Hi3516DmaPrep,                     // Prepare for DMA.
    .DmaSubmit = Hi3516DmaSubmit,                 // Submit a DMA request. 
    .DmaPending = Hi3516DmaPending,               // Pend DMA.
    .DmaPause = Hi3516DmaPause,                   // Pause or stop DMA.
    .DmaResume = Hi3516DmaResume,                 // Resume DMA.
    .DmaPointer = Hi3516DmaPointer,               // Obtain the current playing or recording position.
};

struct PlatformData g_platformData = {
    .PlatformInit = AudioDmaDeviceInit, // Initialize the DMA device.
    .ops = &g_dmaDeviceOps,
};
```

A
annie_wangli 已提交
864
#### Initializing dmaDevice
A
annie_wangli 已提交
865

A
annie_wangli 已提交
866
**AudioDmaDeviceInit** initializes the DMA device, including setting the Hi3516 AIAO module.
A
annie_wangli 已提交
867 868 869 870 871 872 873 874 875 876

```c
int32_t AudioDmaDeviceInit(const struct AudioCard *card, const struct PlatformDevice *platformDevice)
{
... 
    AiaoHalSysInit();
    /* PIN MUX */
    AiaoSysPinMux();
    /* CLK reset */
    AiaoClockReset();
A
annie_wangli 已提交
877
    /* AIAO initialization */
A
annie_wangli 已提交
878 879 880 881 882 883
    AiaoDeviceInit(chnId);
...
    return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
884
#### Implementing the DMA Operation Function Set
A
annie_wangli 已提交
885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900

The DMA device operation function set includes the encapsulation of DMA common APIs. If the common APIs cannot meet development requirements, you can implement new DMA callbacks.

```c
int32_t Hi3516DmaBufAlloc(struct PlatformData *data, const enum AudioStreamType streamType);
int32_t Hi3516DmaBufFree(struct PlatformData *data, const enum AudioStreamType streamType);
int32_t Hi3516DmaRequestChannel(const struct PlatformData *data);
int32_t Hi3516DmaConfigChannel(const struct PlatformData *data);
int32_t Hi3516DmaPrep(const struct PlatformData *data);
int32_t Hi3516DmaSubmit(const struct PlatformData *data);
int32_t Hi3516DmaPending(struct PlatformData *data);
int32_t Hi3516DmaPause(struct PlatformData *data);
int32_t Hi3516DmaResume(const struct PlatformData *data);
int32_t Hi3516DmaPointer(struct PlatformData *data, uint32_t *pointer);
```

A
annie_wangli 已提交
901
#### Registering and Binding Platform to HDF
A
annie_wangli 已提交
902

903
This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/Readme-EN.md).
A
annie_wangli 已提交
904

A
annie_wangli 已提交
905
- Fill in the **g_platformDriverEntry** structure.
A
annie_wangli 已提交
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944
- Ensure that the value of **moduleName** is the same as that in **device_info.hcs**.
- Implement the pointers to the **Bind**, **Init**, and **Release** functions.

drivers/peripheral/audio/chipsets/hi3516dv300/soc/src/hi3516_dma_adapter.c

```c
static int32_t Hi3516DmaDriverInit(struct HdfDeviceObject *device)
{
...
    OsalMutexInit(&g_platformData.renderBufInfo.buffMutex);
    OsalMutexInit(&g_platformData.captureBufInfo.buffMutex);
    g_platformData.platformInitFlag = false;
    ret = AudioSocRegisterPlatform(device, &g_platformData);
...
    return HDF_SUCCESS;
}

static void Hi3516DmaDriverRelease(struct HdfDeviceObject *device)
{
    struct PlatformHost *platformHost = NULL;
...
    platformHost = (struct PlatformHost *)device->service;
...
    OsalMutexDestroy(&g_platformData.renderBufInfo.buffMutex);
    OsalMutexDestroy(&g_platformData.captureBufInfo.buffMutex);
    OsalMemFree(platformHost);
}

/* HdfDriverEntry definitions */
struct HdfDriverEntry g_platformDriverEntry = {
    .moduleVersion = 1,
    .moduleName = "DMA_HI3516",
    .Bind = Hi3516DmaDriverBind,
    .Init = Hi3516DmaDriverInit,
    .Release = Hi3516DmaDriverRelease,
};
HDF_INIT(g_platformDriverEntry);
```

A
annie_wangli 已提交
945
#### Configuring HCS
A
annie_wangli 已提交
946 947 948 949 950

For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**.



A
annie_wangli 已提交
951
### DAI Driver Development Example
A
annie_wangli 已提交
952 953 954 955 956 957 958 959
Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/soc**

The major steps for developing the DAI driver are as follows:
1. Define and fill in a DAI instance.
2. Implement callbacks for the DAI instance.
3. Register and bind the DAI instance to the HDF.
4. Configure the HCS and makefile.

A
annie_wangli 已提交
960
#### Filling in DAI Data Structures
A
annie_wangli 已提交
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982

Fill in the following structures for the DAI module:

- **g_daiData**: private configuration of the DAI device, including the initialization of the DAI device, read/write of registers, and operation functions.

- **g_daiDeviceOps**: DAI device operation function set, including setting DAI parameters and triggering and starting the DAI device.

```c
struct AudioDaiOps g_daiDeviceOps = {
    .HwParams = DaiHwParams,
    .Trigger = DaiTrigger,
    .Startup = DaiStartup,
};

struct DaiData g_daiData = {
    .DaiInit = DaiDeviceInit,
    .Read = AudioDeviceReadReg,
    .Write = AudioDeviceWriteReg,
    .ops = &g_daiDeviceOps,
};
```

A
annie_wangli 已提交
983
#### Initializing daiDevice
A
annie_wangli 已提交
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005

**DaiDeviceInit** initializes DAI configuration and adds the information to the controller linked list.

```c
int32_t DaiDeviceInit(struct AudioCard *audioCard, const struct DaiDevice *dai)
{
...
    struct DaiData *data = dai->devData;
    struct AudioRegCfgData *regConfig = dai->devData->regConfig;
...
    g_regCodecBase = OsalIoRemap(CODEC_REG_BASE, CODEC_MAX_REG_SIZE);
...
    data->regVirtualAddr = (uintptr_t)g_regCodecBase;
    DaiSetConfigInfo(data);
    AudioAddControls(audioCard, data->controls, data->numControls);
	I2c6PinInit();
...
    data->daiInitFlag = true;
    return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
1006
#### Implementing the DAI Operation Function Set
A
annie_wangli 已提交
1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064

**AudioDeviceReadReg** and **AudioDeviceWriteReg** are not used on the Hi3516 and are reserved.

**DaiHwParams** sets PCM stream information.

```c
int32_t DaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param)
{
    uint32_t bitWidth;
    struct DaiDevice *device = card->rtd->cpuDai;
...
    DaiCheckSampleRate(param->rate);
    struct DaiData *data = DaiDataFromCard(card);
    data->pcmInfo.channels = param->channels;
...
    AudioFramatToBitWidth(param->format, &bitWidth);
...
    data->pcmInfo.bitWidth = bitWidth;
    data->pcmInfo.rate = param->rate;
    data->pcmInfo.streamType = param->streamType;
    data->regVirtualAddr = (uintptr_t)g_regDaiBase;
...
	DaiParamsUpdate(device);
    data->regVirtualAddr = (uintptr_t)g_regCodecBase;
    return HDF_SUCCESS;
}
```

**DaiTrigger** is not used on the Hi3516 and is reserved.

**DaiStartup** updates the register configuration and configures the I2S.

```c
int32_t DaiStartup(const struct AudioCard *card, const struct DaiDevice *device)
{
    struct AudioMixerControl *regCfgItem = NULL;
...
    regCfgItem = device->devData->regConfig->audioRegParams[AUDIO_DAI_STARTUP_PATAM_GROUP]->regCfgItem;
    itemNum = device->devData->regConfig->audioRegParams[AUDIO_DAI_STARTUP_PATAM_GROUP]->itemNum;

    device->devData->regVirtualAddr = (uintptr_t)g_regDaiBase;
    for (int i = 0; i < itemNum; i++) {
        int ret = AudioUpdateDaiRegBits(device, &regCfgItem[i], regCfgItem[i].value);
        if (ret != HDF_SUCCESS) {
            AUDIO_DRIVER_LOG_ERR("set frequency fail.");
            return HDF_FAILURE;
        }
    }
    device->devData->regVirtualAddr = (uintptr_t)g_regCodecBase;

    if (I2sPinInit() != HDF_SUCCESS) {
        AUDIO_DRIVER_LOG_ERR("I2sPinInit fail.");
    }

    return HDF_SUCCESS;
}
```

A
annie_wangli 已提交
1065
#### Registering and Binding DAI to HDF
A
annie_wangli 已提交
1066

1067
This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/Readme-EN.md).
A
annie_wangli 已提交
1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120

- Fill in the **g_daiDriverEntry** structure.
- Ensure that the value of **moduleName** is the same as that in **device_info.hcs**.
- Implement the pointers to the **Bind**, **Init**, and **Release** functions.

drivers/peripheral/audio/chipsets/hi3516dv300/soc/src/hi3516_dai_adapter.c

```c
static int32_t DaiDriverBind(struct HdfDeviceObject *device)
{
...
    struct DaiHost *daiHost = (struct DaiHost *)OsalMemCalloc(sizeof(*daiHost));
...
    daiHost->device = device;
    device->service = &daiHost->service;
    g_daiData.daiInitFlag = false;
...
    return HDF_SUCCESS;
}

static int32_t DaiDriverInit(struct HdfDeviceObject *device)
{
...
    DaiGetConfigInfo(device, &g_daiData);
    DaiGetServiceName(device);
...
    OsalMutexInit(&g_daiData.mutex);
    AudioSocRegisterDai(device, &g_daiData);
...
    return HDF_SUCCESS;
}

static void DaiDriverRelease(struct HdfDeviceObject *device)
{
...
    OsalMutexDestroy(&g_daiData.mutex);
...
    struct DaiHost *daiHost = (struct DaiHost *)device->service;
...
    OsalMemFree(daiHost);
}

/* HdfDriverEntry definitions */
struct HdfDriverEntry g_daiDriverEntry = {
    .moduleVersion = 1,
    .moduleName = "DAI_HI3516",
    .Bind = DaiDriverBind,
    .Init = DaiDriverInit,
    .Release = DaiDriverRelease,
};
HDF_INIT(g_daiDriverEntry);
```

A
annie_wangli 已提交
1121
#### Configuring HCS
A
annie_wangli 已提交
1122 1123 1124 1125 1126

For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**.



A
annie_wangli 已提交
1127
### Adding Compilation Configuration to Makefile
A
annie_wangli 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167

Add the newly added files to the **Makefile** file to link them to the kernel image.

Standard system (Linux): **drivers/adapter/khdf/linux/model/audio/Makefile**

```makefile
obj-$(CONFIG_DRIVERS_HDF_AUDIO_CODEC) += \
$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_adapter.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_impl.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_impl.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_ops.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/dsp/src/dsp_adapter.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_adapter.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_ops.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_aiao_impl.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_ops.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_adapter.o \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.o
```

Small system (LiteOS): **drivers/adapter/khdf/liteos/model/audio/Makefile**

```makefile
LOCAL_SRCS += \
$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_adapter.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_impl.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_impl.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_ops.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/dsp/src/dsp_adapter.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_adapter.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_ops.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_aiao_impl.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_ops.c \
$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_adapter.c
```



A
annie_wangli 已提交
1168
### Source Code Structure and Directory
A
annie_wangli 已提交
1169 1170 1171

The development example implements the functions in the header file of the driver interface. The following uses Hi3516 as an example to describe the directory structure. 

A
annie_wangli 已提交
1172
Path of the driver implementation sample code: **drivers\peripheral\audio\chipsets\**
A
annie_wangli 已提交
1173 1174 1175 1176 1177 1178 1179 1180 1181

```
├── hi3516dv300
│   ├── codec
│   │   ├── include
│   │   │   ├── hi3516_codec_impl.h
│   │   │   └── hi3516_codec_ops.h
│   │   ├── src
│   │   │   ├── hi3516_codec_adapter.c  // Codec driver entry
A
annie_wangli 已提交
1182 1183
│   │   │   ├── hi3516_codec_impl.c     // Implement codec hardware operations.
│   │   │   └── hi3516_codec_ops.c      // Implement codec driver APIs.
A
annie_wangli 已提交
1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217
│   │   └── test
│   │       └── unittest
│   ├── dsp
│   │   └── include
│   │       └── dsp_ops.h          
│   │   └── src
│   │       └── dsp_adapter.c           // DSP driver entry
│   │       └── dsp_ops.c             
│   └── soc
│       ├── include
│       │   ├── hi3516_aiao_impl.h
│       │   ├── hi3516_dai_ops.h
│       │   └── hi3516_dma_ops.h
│       ├── src
│       │   ├── hi3516_aiao_impl.c
│       │   ├── hi3516_dai_adapter.c   // DAI driver entry
│       │   ├── hi3516_dai_ops.c
│       │   ├── hi3516_dma_adapter.c   // DMA driver entry
│       │   └── hi3516_dma_ops.c
│       └── test
│           └── unittest
└── tfa9879
    └── accessory
        ├── include
        │   └── tfa9879_accessory_impl.h
        └── src
            ├── tfa9879_accessory_adapter.c  // Accessory driver entry 
            └── tfa9879_accessory_impl.c
```

HCS Files and Directory

```
Standard system:
1218
vendor/hisilicon/hispark_taurus_standard/
A
annie_wangli 已提交
1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247
└── hdf_config
    └── khdf
        ├── audio
        │   ├── audio_config.hcs
        │   ├── codec_config.hcs
        │   ├── dai_config.hcs
        │   ├── dma_config.hcs
        │   └── dsp_config.hcs
        ├── device_info
        │   └── device_info.hcs
        └── hdf.hcs

Small system:
vendor/hisilicon/hispark_taurus/
├── config.json
└── hdf_config
    ├── audio
    │   ├── audio_config.hcs
    │   ├── codec_config.hcs
    │   ├── dai_config.hcs
    │   ├── dma_config.hcs
    │   └── dsp_config.hcs
    ├── device_info
    │   └── device_info.hcs
    └── hdf.hcs
```



A
annie_wangli 已提交
1248
## HAL-based Development Procedure and Example
A
annie_wangli 已提交
1249 1250 1251 1252 1253
The Hardware Abstraction Layer (HAL) provides the following functions:

1. Provides audio HDIs for audio services to implement basic audio features on applications.
2. Provides standard interfaces for device developers to comply with the HDI adapter standards. This promises a healthy evolution of the ecosystem.

A
annie_wangli 已提交
1254 1255
Code path: **drivers/peripheral/audio/hal**

A
annie_wangli 已提交
1256
### Development procedure
A
annie_wangli 已提交
1257 1258 1259 1260 1261

![](figures/HAL_flowchart.png)

1. Call **GetAudioManagerFuncs()** to obtain functions.

A
annie_wangli 已提交
1262
2. Call **GetAllAdapters()** to obtain information about the supported audio adapters and call **LoadAdapter()** to load the corresponding audio adapter.
A
annie_wangli 已提交
1263 1264 1265 1266 1267

3. Create an audio player class by calling **CreateRender()** or create a recorder class and deliver audio attributes.

4. Call the methods mounted to the created audio player class to call **render->control.Start()** and **render->RenderFrame()** to dispatch the start instruction and deliver audio data cyclically.

A
annie_wangli 已提交
1268
5. During the playback, call **render->control.Pause()**, **render->control.Resume()**, or **render->volume.SetVolume()** to control the audio player service, for example, pausing the playback, resuming the playback, and adjusting the volume.
A
annie_wangli 已提交
1269 1270 1271 1272 1273 1274 1275 1276 1277

6. After the audio player service is complete, stop the playback, destroy the audio player class, and unload the audio adapter.

    1. render->control.Stop();

    2. adapter->DestroyRender();

    3. manager->UnloadAdapter();

A
annie_wangli 已提交
1278
### Development Example
A
annie_wangli 已提交
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293

```c
#include <string.h>
#include <stdio.h>
#include "audio_types.h"
#include <pthread.h>
#include "audio_manager.h"

 /* Open the dynamic link to the so library. */
char *soPathHdi = "/system/lib/libhdi_audio.z.so";  
void *g_handle = dlopen(soPathHdi , 1);

int32_t FrameStart(void *param)
{
...
A
annie_wangli 已提交
1294
    /* Send audio data cyclically. */
A
annie_wangli 已提交
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305
    do {
        readSize = (remainingDataSize > bufferSize) ? bufferSize : remainingDataSize;
        numRead = fread(frame, 1, readSize, g_file);
        if (numRead > 0) {
            ret = render->RenderFrame(render, frame, numRead, &replyBytes);
            if (ret == HDF_ERR_INVALID_OBJECT) {
                LOG_FUN_ERR("Render already stop!");
                break;
            }
            remainingDataSize -= numRead;
        }
A
annie_wangli 已提交
1306
        /* Pause the playback and wait. */
A
annie_wangli 已提交
1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317
        while (g_waitSleep) {
            printf("music pause now.\n");
            pthread_cond_wait(&g_functionCond, &g_mutex);
            printf("music resume now.\n");
        }
    } while (!g_closeEnd && numRead > 0 && remainingDataSize > 0);
...
}

static void *hal_main()
{
A
annie_wangli 已提交
1318
    /* Map and call the entry function. */
A
annie_wangli 已提交
1319 1320 1321 1322
    struct AudioManager *(*getAudioManager)() =
    (struct AudioManager *(*)())(dlsym(g_handle, "GetAudioManagerFuncs"));
    struct AudioManager *manager = getAudioManager();
    
A
annie_wangli 已提交
1323
    /* Obtain the audio adapter list. */
A
annie_wangli 已提交
1324 1325 1326 1327
    struct AudioAdapterDescriptor *descs = NULL;
    int32_t size = 0;
    int32_t ret = manager->GetAllAdapters(manager, &descs, &size);

A
annie_wangli 已提交
1328
    /* Locate the audio adapter and port based on the specified audio adapter name and port description. */
A
annie_wangli 已提交
1329 1330 1331 1332 1333
    enum AudioPortDirection port = PORT_OUT;  // The port type OUT means to play the audio.
    struct AudioPort renderPort;
    char * adapterNameCase = "usb";
    int32_t index = SwitchAdapter(descs, adapterNameCase, port, &renderPort, size);

A
annie_wangli 已提交
1334
    /* Load the audio adapter based on the matched audio adapter information. */
A
annie_wangli 已提交
1335
    struct AudioAdapter *adapter = NULL;
A
annie_wangli 已提交
1336 1337
    struct AudioAdapterDescriptor *desc = &descs[index];  // Obtain the device based on the matched audio adapter information.
    manager->LoadAdapter(manager, desc, &adapter); // Load the audio adapter and obtain the audio adapter instance.
A
annie_wangli 已提交
1338

A
annie_wangli 已提交
1339
    /* Create an audio player class. */
A
annie_wangli 已提交
1340 1341 1342 1343 1344 1345 1346
    struct AudioRender *render;
    struct AudioDeviceDescriptor devDesc;  
    struct AudioSampleAttributes attrs;
    InitDevDesc(&devDesc, renderPort.portId);  // Initialize device parameters.
    WavHeadAnalysis(g_file, &attrs);  // Parse the audio file to set attributes.
    adapter->CreateRender(adapter, &devDesc, &attrs, &render);

1347
    /* Deliver the audio data to play. */
A
annie_wangli 已提交
1348 1349 1350
    render->control.Start((AudioHandle)render);   // Dispatch the start instruction and prepare for the action.
    pthread_create(&g_tids, NULL, (void *)(&FrameStart), &g_str); // Start the thread to play the audio clip. 

A
annie_wangli 已提交
1351
    /* Control instructions */
A
annie_wangli 已提交
1352 1353 1354 1355
    render->control.Pause((AudioHandle)render);  // Pause the playback. 
    render->control.Resume((AudioHandle)render); // Resume the playback.
    render->volume.SetVolume((AudioHandle)render, 0.5); // Set the volume.

A
annie_wangli 已提交
1356
     /* Stop playback and destroy the audio player class. */
A
annie_wangli 已提交
1357 1358
    render->control.Stop((AudioHandle)render);
    adapter->DestroyRender(adapter, render);
A
annie_wangli 已提交
1359
     /* Unload the audio adapter. */
A
annie_wangli 已提交
1360 1361 1362 1363 1364 1365
    manager->UnloadAdapter(manager, adapter);
}
```

 

A
annie_wangli 已提交
1366
## Summary
A
annie_wangli 已提交
1367

A
annie_wangli 已提交
1368
This document provides all the key adaptations involved in the audio driver development. It elaborates how to adapt the audio driver and use HDI APIs. You can conduct development based on the chip you use. After reading this document, you will be able to master the audio driver development based on the HDF framework.