1# @ohos.PiPWindow (PiP Window)
2
3The **PiPWindow** module provides basic APIs for manipulating Picture in Picture (PiP). For example, you can use the APIs to check whether the PiP feature is enabled and create a PiP controller to start or stop a PiP window. PiP is mainly used in video playback, video call, or video meeting scenarios.
4
5> **NOTE**
6>
7> The initial APIs of this module are supported since API version 11. Newly added APIs will be marked with a superscript to indicate their earliest API version.
8>
9> This module must be used on the device that supports the **SystemCapability.Window.SessionManager** capability.<!--RP1--> For details, see [SystemCapability](../syscap.md).<!--RP1End-->
10
11## Modules to Import
12
13```ts
14import { PiPWindow } from '@kit.ArkUI';
15```
16
17## PiPWindow.isPiPEnabled
18
19isPiPEnabled(): boolean
20
21Checks whether the PiP feature is supported.
22
23**Atomic service API**: This API can be used in atomic services since API version 12.
24
25**System capability**: SystemCapability.Window.SessionManager
26
27**Return value**
28
29| Type      | Description                                 |
30|----------|-------------------------------------|
31| boolean  | Status of the PiP feature. The value **true** means that the PiP feature is supported, and **false** means the opposite.|
32
33**Example**
34
35```ts
36let enable: boolean = PiPWindow.isPiPEnabled();
37console.info('isPipEnabled:' + enable);
38```
39
40## PiPWindow.create
41
42create(config: PiPConfiguration): Promise&lt;PiPController&gt;
43
44Creates a PiP controller. This API uses a promise to return the result.
45
46**Atomic service API**: This API can be used in atomic services since API version 12.
47
48**System capability**: SystemCapability.Window.SessionManager
49
50**Parameters**
51
52| Name         | Type                                      | Mandatory       | Description                                                                                                                                                                                                                                    |
53|--------------|------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
54| config       | [PiPConfiguration](#pipconfiguration)    | Yes        | Options for creating the PiP controller. This parameter cannot be empty, and **context** and **componentController** that are used to construct this parameter cannot be empty. When constructing this parameter, **templateType** (if specified) must be a value defined in [PiPTemplateType](#piptemplatetype), and **controlGroups** (if specified) must match the value of **templateType**. For details, see [PiPControlGroup](#pipcontrolgroup12).|
55
56**Return value**
57
58| Type                                                        | Description                      |
59|------------------------------------------------------------|--------------------------|
60| Promise&lt;[PiPController](#pipcontroller)&gt;  | Promise used to return the PiP controller.|
61
62**Error codes**
63
64For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
65
66| ID| Error Message                                                                                                                                        |
67|-------|----------------------------------------------------------------------------------------------------------------------------------------------|
68| 401   | Params error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
69| 801   | Capability not supported.Failed to call the API due to limited device capabilities.                                                       |
70
71**Example**
72
73```ts
74import { BusinessError } from '@kit.BasicServicesKit';
75import { BuilderNode, FrameNode, NodeController, Size, UIContext } from '@kit.ArkUI';
76
77class Params {
78  text: string = '';
79  constructor(text: string) {
80    this.text = text;
81  }
82}
83
84// You can use the @Builder decorator to construct layouts.
85@Builder
86function buildText(params: Params) {
87  Column() {
88    Text(params.text)
89      .fontSize(20)
90      .fontColor(Color.Red)
91  }
92  .width('100%') // The PiP window is displayed at full size in the width direction.
93  .height('100%') // The PiP window is displayed at full size in the height direction.
94}
95
96// You can extend NodeController to customize the UI controller.
97class TextNodeController extends NodeController {
98  private message: string;
99  private textNode: BuilderNode<[Params]> | null = null;
100  constructor(message: string) {
101    super();
102    this.message = message;
103  }
104
105  // Use BuilderNode to load the custom layouts.
106  makeNode(context: UIContext): FrameNode | null {
107    this.textNode = new BuilderNode(context);
108    this.textNode.build(wrapBuilder<[Params]>(buildText), new Params(this.message));
109    return this.textNode.getFrameNode();
110  }
111
112  // You can customize this method to update layouts.
113  update(message: string) {
114    console.log(`update message: ${message}`);
115    if (this.textNode !== null) {
116      this.textNode.update(new Params(message));
117    }
118  }
119}
120
121let pipController: PiPWindow.PiPController | undefined = undefined;
122let mXComponentController: XComponentController = new XComponentController(); // Use the mXComponentController to initialize the XComponent: XComponent( {id: 'video', type: 'surface', controller: mXComponentController} ). This ensures that the XComponent content can be migrated to the PiP window.
123let nodeController: TextNodeController = new TextNodeController('this is custom UI');
124let navId: string = "page_1"; // The navigation ID of the current page is page_1. For details, see the definition of PiPConfiguration. The navigation name is customized.
125let contentWidth: number = 800; // The content width is 800 px.
126let contentHeight: number = 600; // The content height is 600 px.
127let config: PiPWindow.PiPConfiguration = {
128  context: getContext(this),
129  componentController: mXComponentController,
130  navigationId: navId,
131  templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
132  contentWidth: contentWidth,
133  contentHeight: contentHeight,
134  controlGroups: [PiPWindow.VideoPlayControlGroup.VIDEO_PREVIOUS_NEXT],
135  customUIController: nodeController, // Optional. Set this parameter if you want to display the custom UI at the top of the PiP window.
136};
137
138let promise : Promise<PiPWindow.PiPController> = PiPWindow.create(config);
139promise.then((data : PiPWindow.PiPController) => {
140  pipController = data;
141  console.info(`Succeeded in creating pip controller. Data:${data}`);
142}).catch((err: BusinessError) => {
143  console.error(`Failed to create pip controller. Cause:${err.code}, message:${err.message}`);
144});
145```
146
147## PiPWindow.create<sup>12+</sup>
148
149create(config: PiPConfiguration, contentNode: typeNode.XComponent): Promise&lt;PiPController&gt;
150
151Creates a PiP controller through a type node. This API uses a promise to return the result.
152
153**Atomic service API**: This API can be used in atomic services since API version 12.
154
155**System capability**: SystemCapability.Window.SessionManager
156
157**Parameters**
158
159| Name         | Type                                      | Mandatory       | Description                                                                                                                                                                                                                                    |
160|--------------|------------------------------------------|-----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
161| config       | [PiPConfiguration](#pipconfiguration)    | Yes        | Options for creating the PiP controller. This parameter cannot be empty, and **context** that is used to construct this parameter cannot be empty. When constructing this parameter, **templateType** (if specified) must be a value defined in [PiPTemplateType](#piptemplatetype), and **controlGroups** (if specified) must match the value of **templateType**. For details, see [PiPControlGroup](#pipcontrolgroup12).|
162| contentNode       | [typeNode.XComponent](js-apis-arkui-frameNode.md#xcomponent12)    | Yes        | Content to be rendered in the PiP window. The parameter value cannot be empty. |
163
164**Return value**
165
166| Type                                                        | Description                      |
167|------------------------------------------------------------|--------------------------|
168| Promise&lt;[PiPController](#pipcontroller)&gt;  | Promise used to return the PiP controller.|
169
170**Error codes**
171
172For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
173
174| ID| Error Message                                                                                                                                        |
175|-------|----------------------------------------------------------------------------------------------------------------------------------------------|
176| 401   | Params error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. 3.Parameter verification failed. |
177| 801   | Capability not supported.Failed to call the API due to limited device capabilities.                                                       |
178
179**Example**
180
181```ts
182import { BusinessError } from '@kit.BasicServicesKit';
183import { PiPWindow, UIContext } from '@kit.ArkUI';
184import { typeNode } from '@ohos.arkui.node';
185
186let pipController: PiPWindow.PiPController | undefined = undefined;
187let xComponentController: XComponentController = new XComponentController();
188let context: UIContext | undefined = undefined; // You can pass UIContext or use this.getUIContext () in the layout to assign a valid value to context.
189let xComponent = typeNode.createNode(context, 'XComponent');
190xComponent.initialize({
191  id:'xcomponent',
192  type:XComponentType.SURFACE,
193  controller:xComponentController
194});
195let contentWidth: number = 800; // The content width is 800 px.
196let contentHeight: number = 600; // The content height is 600 px.
197let config: PiPWindow.PiPConfiguration = {
198  context: getContext(this),
199  componentController: xComponentController,
200  templateType: PiPWindow.PiPTemplateType.VIDEO_PLAY,
201  contentWidth: contentWidth,
202  contentHeight: contentHeight
203};
204
205let promise : Promise<PiPWindow.PiPController> = PiPWindow.create(config, xComponent);
206promise.then((data : PiPWindow.PiPController) => {
207  pipController = data;
208  console.info(`Succeeded in creating pip controller. Data:${data}`);
209}).catch((err: BusinessError) => {
210  console.error(`Failed to create pip controller. Cause:${err.code}, message:${err.message}`);
211});
212```
213
214## PiPConfiguration
215
216Defines the parameters for creating a PiP controller.
217
218**Atomic service API**: This API can be used in atomic services since API version 12.
219
220**System capability**: SystemCapability.Window.SessionManager
221
222| Name                 | Type                                                                        | Mandatory | Description                                                                                                                                                                                                                                                                                                                                       |
223|---------------------|----------------------------------------------------------------------------|-----|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
224| context             | [BaseContext](../apis-ability-kit/js-apis-inner-application-baseContext.md) | Yes  | Context environment.                                                                                                                                                                                                                                                                                                                                 |
225| componentController | [XComponentController](arkui-ts/ts-basic-components-xcomponent.md)         | Yes  | Original [XComponent](arkui-ts/ts-basic-components-xcomponent.md) controller.                                                                                                                                                                                                                                                                     |
226| navigationId        | string                                                                     | No  | Navigation ID of the current page.<br>1. When the UIAbility uses [Navigation](arkui-ts/ts-basic-components-navigation.md) to manage pages, set the ID of the **Navigation** component for the PiP controller. This ensures that the original page can be restored from the PiP window.<br>2. When the UIAbility uses [Router](js-apis-router.md) to manage pages, you do not need to set the ID of the **Navigation** component for the PiP controller.<br>3. If the UIAbility has only one page, you do not need to set the navigation ID. The original page can be restored from the PiP window.|
227| templateType        | [PiPTemplateType](#piptemplatetype)                                        | No  | Template type, which is used to distinguish video playback, video call, and video meeting scenarios.                                                                                                                                                                                                                                                                                                                 |
228| contentWidth        | number                                                                     | No  | Width of the original content, in px. It is used to determine the aspect ratio of the PiP window. When the PiP controller is created in [typeNode mode](#pipwindowcreate12), the default value is 1920. When the PiP controller is created [not in typeNode mode](#pipwindowcreate), the default value is the width of the [XComponent](arkui-ts/ts-basic-components-xcomponent.md).                                                                |
229| contentHeight       | number                                                                     | No  | Height of the original content, in px. It is used to determine the aspect ratio of the PiP window. It is used to determine the aspect ratio of the PiP window. When the PiP controller is created in [typeNode mode](#pipwindowcreate12), the default value is 1080. When the PiP controller is created [not in typeNode mode](#pipwindowcreate), the default value is the height of the [XComponent](arkui-ts/ts-basic-components-xcomponent.md).                                                                |
230| controlGroups<sup>12+</sup>       | Array<[PiPControlGroup](#pipcontrolgroup12)>                               | No  | A list of optional component groups of the PiP controller. An application can configure whether to display these optional components. If this parameter is not set for an application, the basic components (for example, play/pause of the video playback component group) are displayed. A maximum of three components can be configured in the list.                                                                                                                                                                                                                                                  |
231| customUIController<sup>12+</sup>      | [NodeController](js-apis-arkui-nodeController.md)           | No  | Custom UI that can be displayed at the top of the PiP window.                                                                                                                                                                                                                                                                                            |
232
233## PiPTemplateType
234
235Enumerates the PIP template types.
236
237**Atomic service API**: This API can be used in atomic services since API version 12.
238
239**System capability**: SystemCapability.Window.SessionManager
240
241| Name           | Value  | Description                                  |
242|---------------|-----|--------------------------------------|
243| VIDEO_PLAY    | 0   | Video playback template. A PiP window will be started during video playback, and the video playback template is loaded.  |
244| VIDEO_CALL    | 1   | Video call template. A PiP window will be started during a video call, and the video call template will be loaded.|
245| VIDEO_MEETING | 2   | Video meeting template. A PiP window will be started during a video meeting, and the video meeting template will be loaded.|
246| VIDEO_LIVE    | 3   | Live template. A PiP window will be started during a live, and the live template is loaded.    |
247
248## PiPState
249
250Enumerates the PiP states.
251
252**Atomic service API**: This API can be used in atomic services since API version 12.
253
254**System capability**: SystemCapability.Window.SessionManager
255
256| Name                  | Value  | Description                   |
257|----------------------|-----|-----------------------|
258| ABOUT_TO_START       | 1   | PiP is about to start.           |
259| STARTED              | 2   | PiP is started.           |
260| ABOUT_TO_STOP        | 3   | PiP is about to stop.           |
261| STOPPED              | 4   | PiP is stopped.           |
262| ABOUT_TO_RESTORE     | 5   | The original page is about to restore.|
263| ERROR                | 6   | An error occurs during the execution of the PiP lifecycle.  |
264
265## PiPControlGroup<sup>12+</sup>
266
267type PiPControlGroup = VideoPlayControlGroup | VideoCallControlGroup | VideoMeetingControlGroup | VideoLiveControlGroup
268
269Describes the optional component groups of the PiP controller. An application can configure whether to display these optional components. By default, the controller displays only basic components (such as the play/pause component of the video playback component group).
270
271**Atomic service API**: This API can be used in atomic services since API version 12.
272
273**System capability**: SystemCapability.Window.SessionManager
274
275| Type                                             | Description         |
276|-------------------------------------------------|-------------|
277| [VideoPlayControlGroup](#videoplaycontrolgroup12)     | Video playback component group.|
278| [VideoCallControlGroup](#videocallcontrolgroup12)       | Video call component group.|
279| [VideoMeetingControlGroup](#videomeetingcontrolgroup12) | Video meeting component group.|
280| [VideoLiveControlGroup](#videolivecontrolgroup12)     | Live video component group.|
281
282
283## VideoPlayControlGroup<sup>12+</sup>
284
285Enumerates the video playback component groups. They are used only when [PiPTemplateType](#piptemplatetype) is set to **VIDEO_PLAY**.
286
287**Atomic service API**: This API can be used in atomic services since API version 12.
288
289**System capability**: SystemCapability.Window.SessionManager
290
291| Name                  | Value  | Description                   |
292|----------------------|-----|-----------------------|
293| VIDEO_PREVIOUS_NEXT       | 101   | Previous/Next component group for video playback.<br>This component group is mutually exclusive with the fast-forward/rewind component group. It cannot be added if the fast-forward/rewind component group is added.          |
294| FAST_FORWARD_BACKWARD    | 102   | Fast-forward/Rewind component group for video playback.<br>This component group is mutually exclusive with the previous/next component group. It cannot be added if the previous/next control component group is added.          |
295
296## VideoCallControlGroup<sup>12+</sup>
297
298Enumerates the video call component groups. They are used only when [PiPTemplateType](#piptemplatetype) is set to **VIDEO_CALL**.
299
300**Atomic service API**: This API can be used in atomic services since API version 12.
301
302**System capability**: SystemCapability.Window.SessionManager
303
304| Name                  | Value  | Description                   |
305|----------------------|-----|-----------------------|
306| MICROPHONE_SWITCH       | 201   | Microphone on/off component group.           |
307| HANG_UP_BUTTON    | 202   | Hang-up component group.          |
308| CAMERA_SWITCH    | 203   | Camera on/off component group.           |
309| MUTE_SWITCH    | 204   | Mute/Unmute component group.           |
310
311## VideoMeetingControlGroup<sup>12+</sup>
312
313Enumerates the video meeting component groups. They are used only when [PiPTemplateType](#piptemplatetype) is set to **VIDEO_MEETING**.
314
315**Atomic service API**: This API can be used in atomic services since API version 12.
316
317**System capability**: SystemCapability.Window.SessionManager
318
319| Name                  | Value  | Description                   |
320|----------------------|-----|-----------------------|
321| HANG_UP_BUTTON       | 301   | Hang-up component group.         |
322| CAMERA_SWITCH    | 302   | Camera on/off component group.          |
323| MUTE_SWITCH    | 303   | Mute/Unmute component group.           |
324| MICROPHONE_SWITCH       | 304   | Microphone on/off component group.           |
325
326## VideoLiveControlGroup<sup>12+</sup>
327
328Enumerates the live video component groups. They are used only when [PiPTemplateType](#piptemplatetype) is set to **VIDEO_LIVE**.
329
330**Atomic service API**: This API can be used in atomic services since API version 12.
331
332**System capability**: SystemCapability.Window.SessionManager
333
334| Name                  | Value  | Description                   |
335|----------------------|-----|-----------------------|
336| VIDEO_PLAY_PAUSE     | 401   |   Play/Pause component group for live video.  |
337| MUTE_SWITCH         | 402   | Mute/Unmute component group.           |
338
339## PiPActionEventType
340
341type PiPActionEventType = PiPVideoActionEvent | PiPCallActionEvent | PiPMeetingActionEvent | PiPLiveActionEvent
342
343Enumerates the types of action events of the PiP controller.
344
345**Atomic service API**: This API can be used in atomic services since API version 12.
346
347**System capability**: SystemCapability.Window.SessionManager
348
349| Type                                             | Description         |
350|-------------------------------------------------|-------------|
351| [PiPVideoActionEvent](#pipvideoactionevent)     | Action event for components displayed on the video playback controller.|
352| [PiPCallActionEvent](#pipcallactionevent)       | Action event for components displayed on the video call controller.|
353| [PiPMeetingActionEvent](#pipmeetingactionevent) | Action event for components displayed on the video meeting controller.|
354| [PiPLiveActionEvent](#pipliveactionevent)       | Action event for components displayed on the live video controller.  |
355
356## PiPVideoActionEvent
357
358type PiPVideoActionEvent = 'playbackStateChanged' | 'nextVideo' | 'previousVideo' | 'fastForward' | 'fastBackward'
359
360Defines the PiP action event during video playback.
361
362**Atomic service API**: This API can be used in atomic services since API version 12.
363
364**System capability**: SystemCapability.Window.SessionManager
365
366| Type                        | Description                                     |
367| ---------------------------- | ----------------------------------------- |
368| 'playbackStateChanged'       | The playback status changes.                     |
369| 'nextVideo'                  | Plays the next video.                         |
370| 'previousVideo'              | Plays the previous video.                         |
371| 'fastForward'<sup>12+</sup>  | Fast forwards the video. This value is supported since API version 12.|
372| 'fastBackward'<sup>12+</sup> | Rewinds the video. This value is supported since API version 12.|
373
374## PiPCallActionEvent
375
376type PiPCallActionEvent = 'hangUp' | 'micStateChanged' | 'videoStateChanged' | 'voiceStateChanged'
377
378Defines the PiP action event in a video call.
379
380**Atomic service API**: This API can be used in atomic services since API version 12.
381
382**System capability**: SystemCapability.Window.SessionManager
383
384| Type               | Description              |
385| ------------------- | ------------------ |
386| 'hangUp'             | The video call is hung up.    |
387| 'micStateChanged'   | The microphone is muted or unmuted.|
388| 'videoStateChanged' | The camera is turned on or off.|
389| 'voiceStateChanged'<sup>12+</sup> | The speaker is muted or unmuted.  |
390
391
392## PiPMeetingActionEvent
393
394type PiPMeetingActionEvent = 'hangUp' | 'voiceStateChanged' | 'videoStateChanged' | 'micStateChanged'
395
396Defines the PiP action event in a video meeting.
397
398**Atomic service API**: This API can be used in atomic services since API version 12.
399
400**System capability**: SystemCapability.Window.SessionManager
401
402| Type               | Description              |
403| ------------------- | ------------------ |
404| 'hangUp'            | The video meeting is hung up.    |
405| 'voiceStateChanged' | The speaker is muted or unmuted.  |
406| 'videoStateChanged' | The camera is turned on or off.|
407| 'micStateChanged'<sup>12+</sup>   | The microphone is muted or unmuted.|
408
409
410## PiPLiveActionEvent
411
412type PiPLiveActionEvent = 'playbackStateChanged' | 'voiceStateChanged'
413
414Defines the PiP action event in a live.
415
416**Atomic service API**: This API can be used in atomic services since API version 12.
417
418**System capability**: SystemCapability.Window.SessionManager
419
420| Type                  | Description            |
421| ---------------------- | ---------------- |
422| 'playbackStateChanged' | The live is played or paused.|
423| 'voiceStateChanged'<sup>12+</sup> | The speaker is muted or unmuted.  |
424
425
426## PiPControlStatus<sup>12+</sup>
427
428Enumerates the statuses of components displayed on the PiP controller.
429
430**Atomic service API**: This API can be used in atomic services since API version 12.
431
432**System capability**: SystemCapability.Window.SessionManager
433
434| Name                  | Value  | Description                   |
435|----------------------|-----|-----------------------|
436| PLAY       | 1   | Play.         |
437| PAUSE    | 0   | Pause.          |
438| OPEN    | 1   | Open.           |
439| CLOSE       | 0   | Close.         |
440
441## PiPControlType<sup>12+</sup>
442
443Enumerates the types of components displayed on the PiP controller.
444
445**Atomic service API**: This API can be used in atomic services since API version 12.
446
447**System capability**: SystemCapability.Window.SessionManager
448
449| Name               | Value  | Description                                  |
450|-------------------|-----|--------------------------------------|
451| VIDEO_PLAY_PAUSE  | 0   | Play/Pause component.  |
452| VIDEO_PREVIOUS    | 1   | Previous component in video scenarios.|
453| VIDEO_NEXT        | 2   | Next component in video scenarios.|
454| FAST_FORWARD      | 3   | Fast-forward component in video scenarios.    |
455| FAST_BACKWARD     | 4   | Rewind component in video scenarios.  |
456| HANG_UP_BUTTON           | 5   | Hang-up component.|
457| MICROPHONE_SWITCH | 6  | Microphone on/off component.|
458| CAMERA_SWITCH     | 7   | Camera on/off component.    |
459| MUTE_SWITCH       | 8   | Mute/Unmute component.    |
460
461
462## ControlPanelActionEventCallback<sup>12+</sup>
463
464type ControlPanelActionEventCallback = (event: PiPActionEventType, status?: number) => void
465
466Describes the action event callback of the PiP controller.
467
468**Atomic service API**: This API can be used in atomic services since API version 12.
469
470**System capability**: SystemCapability.Window.SessionManager
471
472**Parameters**
473
474| Name                      | Type          | Mandatory   | Description                               |
475|--------------------------|--------------|--------------|-----------------------------------|
476| event       |  [PiPActionEventType](#pipactioneventtype)       | Yes| Type of the action event of the PiP controller.<br>The application performs processing based on the action event. For example, if the **'playbackStateChanged'** event is triggered, the application starts or stops the video.|
477| status | number | No| Status of a component that can be switched. For example, for a microphone on/off component group, a camera on/off component group, and a mute/unmute component group, the value **1** means that the component is enabled and **0** means that the component is disabled. For other components, the default value **-1** is used.|
478
479## ControlEventParam<sup>12+</sup>
480
481Describes the parameters in the callback of the action event of the PiP controller.
482
483**Atomic service API**: This API can be used in atomic services since API version 12.
484
485**System capability**: SystemCapability.Window.SessionManager
486
487| Name                      | Type          | Mandatory   | Description                                                                                                                               |
488|--------------------------|--------------|--------------|-----------------------------------------------------------------------------------------------------------------------------------|
489| controlType       |  [PiPControlType](#pipcontroltype12)      | Yes| Type of the action event of the PiP controller. The application performs processing based on the component type. For example, if the video play/pause component is touched, the application starts or stops the video.                                                                     |
490| status | [PiPControlStatus](#pipcontrolstatus12) | No| Status of a component that can be switched. For example, for a microphone on/off component group, a camera on/off component group, and a mute/unmute component group, the value **PiPControlStatus.PLAY** means that the component is enabled and **PiPControlStatus.PAUSE** means that the component is disabled. For the hang-up component, the default value is **-1**.|
491
492## PiPController
493
494Implements a PiP controller that starts, stops, or updates a PiP window and registers callbacks.
495
496Before calling any of the following APIs, you must use [PiPWindow.create()](#pipwindowcreate) to create a **PiPController** instance.
497
498**System capability**: SystemCapability.Window.SessionManager
499
500### startPiP
501
502startPiP(): Promise&lt;void&gt;
503
504Starts a PiP window. This API uses a promise to return the result.
505
506**Atomic service API**: This API can be used in atomic services since API version 12.
507
508**System capability**: SystemCapability.Window.SessionManager
509
510**Return value**
511
512| Type                    | Description                |
513|------------------------|--------------------|
514| Promise&lt;void&gt;    | Promise that returns no value.  |
515
516**Error codes**
517
518For details about the error codes, see [Window Error Codes](errorcode-window.md).
519
520| ID   | Error Message                                               |
521|------------|--------------------------------------------------------|
522| 1300012    | The PiP window state is abnormal.                      |
523| 1300013    | Failed to create the PiP window.                       |
524| 1300014    | PiP internal error.                                    |
525| 1300015    | Repeated PiP operation.                                |
526
527**Example**
528
529```ts
530let promise : Promise<void> = pipController.startPiP();
531promise.then(() => {
532  console.info(`Succeeded in starting pip.`);
533}).catch((err: BusinessError) => {
534  console.error(`Failed to start pip. Cause:${err.code}, message:${err.message}`);
535});
536```
537
538### stopPiP
539
540stopPiP(): Promise&lt;void&gt;
541
542Stops a PiP window. This API uses a promise to return the result.
543
544**Atomic service API**: This API can be used in atomic services since API version 12.
545
546**System capability**: SystemCapability.Window.SessionManager
547
548**Return value**
549
550| Type                  | Description                 |
551|----------------------|---------------------|
552| Promise&lt;void&gt;  | Promise that returns no value.   |
553
554**Error codes**
555
556For details about the error codes, see [Window Error Codes](errorcode-window.md).
557
558| ID  | Error Message                         |
559|---------|-----------------------------------|
560| 1300011 | Failed to destroy the PiP window. |
561| 1300012 | The PiP window state is abnormal. |
562| 1300015 | Repeated PiP operation.           |
563
564**Example**
565
566```ts
567let promise : Promise<void> = pipController.stopPiP();
568promise.then(() => {
569  console.info(`Succeeded in stopping pip.`);
570}).catch((err: BusinessError) => {
571  console.error(`Failed to stop pip. Cause:${err.code}, message:${err.message}`);
572});
573```
574
575### setAutoStartEnabled
576
577setAutoStartEnabled(enable: boolean): void
578
579Sets whether to automatically start a PiP window when the user returns to the home screen.
580
581**Atomic service API**: This API can be used in atomic services since API version 12.
582
583**System capability**: SystemCapability.Window.SessionManager
584
585**Parameters**
586
587| Name     | Type       | Mandatory   | Description                             |
588|----------|-----------|-------|---------------------------------|
589| enable   | boolean   | Yes    | Whether to automatically start a PiP window when the user returns to the home screen. The value **true** means to automatically start a PiP window in such a case, and **false** means the opposite. If the automatic PiP startup feature is disabled in Settings, a PiP window will not be automatically started in such a case even if this parameter is set to **true**. |
590
591**Example**
592
593```ts
594let enable: boolean = true;
595pipController.setAutoStartEnabled(enable);
596```
597
598### updateContentSize
599
600updateContentSize(width: number, height: number): void
601
602Updates the media content size when the media content is switched.
603
604**Atomic service API**: This API can be used in atomic services since API version 12.
605
606**System capability**: SystemCapability.Window.SessionManager
607
608**Parameters**
609
610| Name   | Type    | Mandatory | Description                                    |
611|--------|--------|-----|----------------------------------------|
612| width  | number | Yes  | Width of the media content, in px. The value must be a number greater than 0. It is used to update the aspect ratio of the PiP window. |
613| height | number | Yes  | Height of the media content, in px. The value must be a number greater than 0. It is used to update the aspect ratio of the PiP window. |
614
615**Error codes**
616
617For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
618
619| ID| Error Message                                                                                                       |
620|-------|-------------------------------------------------------------------------------------------------------------|
621| 401   | Params error. Possible causes: 1.Mandatory parameters are left unspecified. 2.Incorrect parameter types. |
622
623**Example**
624
625```ts
626let width: number = 540; // The content width changes to 540 px.
627let height: number = 960; // The content height changes to 960 px.
628pipController.updateContentSize(width, height);
629```
630
631### updatePiPControlStatus<sup>12+</sup>
632updatePiPControlStatus(controlType: PiPControlType, status: PiPControlStatus): void
633
634Updates the enabled status of a component displayed on the PiP controller.
635
636**Atomic service API**: This API can be used in atomic services since API version 12.
637
638**System capability**: SystemCapability.Window.SessionManager
639
640**Parameters**
641
642| Name   | Type    | Mandatory | Description                                                                                                |
643|--------|--------|-----|----------------------------------------------------------------------------------------------------|
644| controlType  | [PiPControlType](#pipcontroltype12)  | Yes  | Type of the component displayed on the PiP controller. Currently, only **VIDEO_PLAY_PAUSE**, **MICROPHONE_SWITCH**, **CAMERA_SWITCH**, and **MUTE_SWITCH** are supported.|
645| status | [PiPControlStatus](#pipcontrolstatus12)  | Yes  | Status of the component displayed on the PiP controller.                                                                                    |
646
647**Error codes**
648
649For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
650
651| ID| Error Message                                                                                                       |
652|-------|-------------------------------------------------------------------------------------------------------------|
653| 401   | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed |
654
655**Example**
656
657```ts
658let controlType: PiPWindow.PiPControlType = PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE; // Play/Pause component displayed on the video playback control panel.
659let status: PiPWindow.PiPControlStatus = PiPWindow.PiPControlStatus.PLAY; // The Play/Pause component displayed on the video playback control panel is in the playing state.
660pipController.updatePiPControlStatus(controlType, status);
661```
662
663### setPiPControlEnabled<sup>12+</sup>
664setPiPControlEnabled(controlType: PiPControlType, enabled: boolean): void
665
666Sets the enabled status for a component displayed on the PiP controller.
667
668**Atomic service API**: This API can be used in atomic services since API version 12.
669
670**System capability**: SystemCapability.Window.SessionManager
671
672**Parameters**
673
674| Name        | Type    | Mandatory | Description                                    |
675|-------------|--------|-----|----------------------------------------|
676| controlType | [PiPControlType](#pipcontroltype12)  | Yes  | Type of the component displayed on the PiP controller. |
677| enabled     | boolean | Yes  | Enabled status of the component displayed on the PiP controller. The value **true** means that the component is enabled, and **false** means the opposite. |
678
679**Error codes**
680
681For details about the error codes, see [Universal Error Codes](../errorcode-universal.md).
682
683| ID| Error Message                                                                                                       |
684|-------|-------------------------------------------------------------------------------------------------------------|
685| 401   | Params error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed |
686
687**Example**
688
689```ts
690let controlType: PiPWindow.PiPControlType = PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE; // Play/Pause component displayed on the video playback control panel.
691let enabled: boolean = false; // The Play/Pause component displayed on the video playback control panel is in the disabled state.
692pipController.setPiPControlEnabled(controlType, enabled);
693```
694
695### on('stateChange')
696
697on(type: 'stateChange', callback: (state: PiPState, reason: string) => void): void
698
699Subscribes to PiP state events.
700
701**Atomic service API**: This API can be used in atomic services since API version 12.
702
703**System capability**: SystemCapability.Window.SessionManager
704
705**Parameters**
706
707| Name       | Type       | Mandatory  | Description                                                                                               |
708|------------|-----------|------|---------------------------------------------------------------------------------------------------|
709| type       | string    | Yes   | Event type. The event **'stateChange'** is triggered when the PiP state changes.                                                            |
710| callback   | function  | Yes   | Callback used to return the result, which includes the following information:<br>- **state**: [PiPState](#pipstate), indicating the new PiP state.<br>- **reason**: a string indicating the reason for the state change. |
711
712**Example**
713
714```ts
715pipController.on('stateChange', (state: PiPWindow.PiPState, reason: string) => {
716  let curState: string = '';
717  switch (state) {
718    case PiPWindow.PiPState.ABOUT_TO_START:
719      curState = 'ABOUT_TO_START';
720      break;
721    case PiPWindow.PiPState.STARTED:
722      curState = 'STARTED';
723      break;
724    case PiPWindow.PiPState.ABOUT_TO_STOP:
725      curState = 'ABOUT_TO_STOP';
726      break;
727    case PiPWindow.PiPState.STOPPED:
728      curState = 'STOPPED';
729      break;
730    case PiPWindow.PiPState.ABOUT_TO_RESTORE:
731      curState = 'ABOUT_TO_RESTORE';
732      break;
733    case PiPWindow.PiPState.ERROR:
734      curState = 'ERROR';
735      break;
736    default:
737      break;
738  }
739  console.info('stateChange:' + curState + ' reason:' + reason);
740});
741```
742
743### off('stateChange')
744
745off(type: 'stateChange'): void
746
747Unsubscribes from PiP state events.
748
749**Atomic service API**: This API can be used in atomic services since API version 12.
750
751**System capability**: SystemCapability.Window.SessionManager
752
753**Parameters**
754
755| Name      | Type           | Mandatory   | Description                                    |
756|-----------|---------------|-------|----------------------------------------|
757| type      | string        | Yes    | Event type. The event **'stateChange'** is triggered when the PiP state changes. |
758
759**Example**
760
761```ts
762pipController.off('stateChange');
763```
764
765### on('controlPanelActionEvent')
766
767on(type: 'controlPanelActionEvent', callback: ControlPanelActionEventCallback): void
768
769Subscribes to PiP action events. The [on('controlEvent')](#oncontrolevent12) API is preferred.
770
771**Atomic service API**: This API can be used in atomic services since API version 12.
772
773**System capability**: SystemCapability.Window.SessionManager
774
775**Parameters**
776
777| Name     | Type        | Mandatory   | Description                                               |
778|----------|------------|-------|---------------------------------------------------|
779| type     | string     | Yes    | Event type. The value **'controlPanelActionEvent'** indicates the PiP action event.|
780| callback | [ControlPanelActionEventCallback](#controlpanelactioneventcallback12)  | Yes    | Action event callback of the PiP controller.                               |
781
782**Example**
783
784```ts
785pipController.on('controlPanelActionEvent', (event: PiPWindow.PiPActionEventType, status?: number) => {
786  switch (event) {
787    case 'playbackStateChanged':
788      if (status === 0) {
789        // Stop the video.
790      } else if (status === 1) {
791        // Play the video.
792      }
793      break;
794    case 'nextVideo':
795      // Switch to the next video.
796      break;
797    case 'previousVideo':
798      // Switch to the previous video.
799      break;
800    case 'fastForward':
801      // Fast forward the video.
802      break;
803    case 'fastBackward':
804      // Rewind the video.
805      break;
806    default:
807      break;
808  }
809  console.info('registerActionEventCallback, event:' + event);
810});
811```
812
813### on('controlEvent')<sup>12+</sup>
814
815on(type: 'controlEvent', callback: Callback&lt;ControlEventParam&gt;): void
816
817Subscribes to PiP action events.
818
819**Atomic service API**: This API can be used in atomic services since API version 12.
820
821**System capability**: SystemCapability.Window.SessionManager
822
823**Parameters**
824
825| Name     | Type                                                 | Mandatory   | Description                                    |
826|----------|-----------------------------------------------------|-------|----------------------------------------|
827| type     | string                                              | Yes    | Event type. The value **'controlEvent'** indicates the PiP action event.|
828| callback | Callback<[ControlEventParam](#controleventparam12)> | Yes    | Action event callback of the PiP controller.                    |
829
830**Example**
831
832```ts
833pipController.on('controlEvent', (control) => {
834  switch (control.controlType) {
835    case PiPWindow.PiPControlType.VIDEO_PLAY_PAUSE:
836      if (control.status === PiPWindow.PiPControlStatus.PAUSE) {
837        // Stop the video.
838      } else if (control.status === PiPWindow.PiPControlStatus.PLAY) {
839        // Play the video.
840      }
841      break;
842    case PiPWindow.PiPControlType.VIDEO_NEXT:
843      // Switch to the next video.
844      break;
845    case PiPWindow.PiPControlType.VIDEO_PREVIOUS:
846      // Switch to the previous video.
847      break;
848    case PiPWindow.PiPControlType.FAST_FORWARD:
849      // Fast forward the video.
850      break;
851    case PiPWindow.PiPControlType.FAST_BACKWARD:
852      // Rewind the video.
853      break;
854    default:
855      break;
856  }
857  console.info('registerControlEventCallback, controlType:' + control.controlType + ', status' + control.status);
858});
859```
860
861### off('controlPanelActionEvent')
862
863off(type: 'controlPanelActionEvent'): void
864
865Unsubscribes from PiP action events. The **[off('controlEvent')](#offcontrolevent12)** API is preferred.
866
867**Atomic service API**: This API can be used in atomic services since API version 12.
868
869**System capability**: SystemCapability.Window.SessionManager
870
871**Parameters**
872
873| Name       | Type                          | Mandatory  | Description                                           |
874|------------|------------------------------|------|-----------------------------------------------|
875| type       | string                       | Yes   | Event type. The value **'controlPanelActionEvent'** indicates the PiP action event.  |
876
877**Example**
878
879```ts
880pipController.off('controlPanelActionEvent');
881```
882
883### off('controlEvent')<sup>12+</sup>
884
885off(type: 'controlEvent', callback?: Callback&lt;ControlEventParam&gt;): void
886
887Unsubscribes from PiP action events.
888
889**Atomic service API**: This API can be used in atomic services since API version 12.
890
891**System capability**: SystemCapability.Window.SessionManager
892
893**Parameters**
894
895| Name       | Type                                                 | Mandatory| Description                                                    |
896|------------|-----------------------------------------------------|----|--------------------------------------------------------|
897| type       | string                                              | Yes | Event type. The value **'controlEvent'** indicates the PiP action event.                |
898| callback | Callback<[ControlEventParam](#controleventparam12)> | No | Action event callback of the PiP controller. If no value is passed in, all subscriptions to the specified event are canceled.|
899
900**Example**
901
902```ts
903pipController.off('controlEvent', () => {});
904```
905