# Script forward frames

This example shows how to use [Script](https://docs.luxonis.com/software/depthai-components/nodes/script.md) node to forward
(demultiplex) frames to two different outputs - in this case directly to two
[XLinkOut](https://docs.luxonis.com/software/depthai-components/nodes/xlink_out.md) nodes. Script also changes exposure ratio for
each frame, which results in two streams, one lighter and one darker.

## Demo

## Setup

Please run the [install script](https://github.com/luxonis/depthai-python/blob/main/examples/install_requirements.py) to download
all required dependencies. Please note that this script must be ran from git context, so you have to download the
[depthai-python](https://github.com/luxonis/depthai-python) repository first and then run the script

```bash
git clone https://github.com/luxonis/depthai-python.git
cd depthai-python/examples
python3 install_requirements.py
```

For additional information, please follow the [installation guide](https://docs.luxonis.com/software/depthai/manual-install.md).

## Source code

#### Python

```python
#!/usr/bin/env python3
import cv2
import depthai as dai

# Start defining a pipeline
pipeline = dai.Pipeline()

cam = pipeline.create(dai.node.ColorCamera)
# Not needed, you can display 1080P frames as well
cam.setIspScale(1,2)

# Script node
script = pipeline.create(dai.node.Script)
script.setScript("""
    ctrl = CameraControl()
    ctrl.setCaptureStill(True)
    # Initially send still event
    node.io['ctrl'].send(ctrl)

    normal = True
    while True:
        frame = node.io['frames'].get()
        if normal:
            ctrl.setAutoExposureCompensation(3)
            node.io['stream1'].send(frame)
            normal = False
        else:
            ctrl.setAutoExposureCompensation(-3)
            node.io['stream2'].send(frame)
            normal = True
        node.io['ctrl'].send(ctrl)
""")
cam.still.link(script.inputs['frames'])

# XLinkOut
xout1 = pipeline.create(dai.node.XLinkOut)
xout1.setStreamName('stream1')
script.outputs['stream1'].link(xout1.input)

xout2 = pipeline.create(dai.node.XLinkOut)
xout2.setStreamName('stream2')
script.outputs['stream2'].link(xout2.input)

script.outputs['ctrl'].link(cam.inputControl)

# Connect to device with pipeline
with dai.Device(pipeline) as device:
    qStream1 = device.getOutputQueue("stream1")
    qStream2 = device.getOutputQueue("stream2")
    while True:
        cv2.imshow('stream1', qStream1.get().getCvFrame())
        cv2.imshow('stream2', qStream2.get().getCvFrame())
        if cv2.waitKey(1) == ord('q'):
            break
```

#### C++

```cpp
#include <iostream>

// Includes common necessary includes for development using depthai library
#include "depthai/depthai.hpp"

int main() {
    using namespace std;

    // Start defining a pipeline
    dai::Pipeline pipeline;

    // Define a source - color camera
    auto cam = pipeline.create<dai::node::ColorCamera>();
    // Not needed, you can display 1080P frames as well
    cam->setIspScale(1, 2);

    // Script node
    auto script = pipeline.create<dai::node::Script>();
    script->setScript(R"(
    ctrl = CameraControl()
    ctrl.setCaptureStill(True)
    # Initially send still event
    node.io['ctrl'].send(ctrl)

    normal = True
    while True:
        frame = node.io['frames'].get()
        if normal:
            ctrl.setAutoExposureCompensation(3)
            node.io['stream1'].send(frame)
            normal = False
        else:
            ctrl.setAutoExposureCompensation(-3)
            node.io['stream2'].send(frame)
            normal = True
        node.io['ctrl'].send(ctrl)
    )");

    cam->still.link(script->inputs["frames"]);

    // XLinkOut
    auto xout1 = pipeline.create<dai::node::XLinkOut>();
    xout1->setStreamName("stream1");
    script->outputs["stream1"].link(xout1->input);

    auto xout2 = pipeline.create<dai::node::XLinkOut>();
    xout2->setStreamName("stream2");
    script->outputs["stream2"].link(xout2->input);

    // Connections
    script->outputs["ctrl"].link(cam->inputControl);

    // Connect to device with pipeline
    dai::Device device(pipeline);
    auto qStream1 = device.getOutputQueue("stream1");
    auto qStream2 = device.getOutputQueue("stream2");
    while(true) {
        cv::imshow("stream1", qStream1->get<dai::ImgFrame>()->getCvFrame());
        cv::imshow("stream2", qStream2->get<dai::ImgFrame>()->getCvFrame());
        if(cv::waitKey(1) == 'q') {
            break;
        }
    }
}
```

## Pipeline

### examples/script_forward_frames.pipeline.json

```json
{
  "pipeline": {
    "connections": [
      {
        "node1Id": 0,
        "node1Output": "still",
        "node1OutputGroup": "",
        "node2Id": 1,
        "node2Input": "frames",
        "node2InputGroup": "io"
      },
      {
        "node1Id": 1,
        "node1Output": "stream1",
        "node1OutputGroup": "io",
        "node2Id": 2,
        "node2Input": "in",
        "node2InputGroup": ""
      },
      {
        "node1Id": 1,
        "node1Output": "stream2",
        "node1OutputGroup": "io",
        "node2Id": 3,
        "node2Input": "in",
        "node2InputGroup": ""
      },
      {
        "node1Id": 1,
        "node1Output": "ctrl",
        "node1OutputGroup": "io",
        "node2Id": 0,
        "node2Input": "inputControl",
        "node2InputGroup": ""
      }
    ],
    "globalProperties": {
      "calibData": null,
      "cameraTuningBlobSize": null,
      "cameraTuningBlobUri": "",
      "leonCssFrequencyHz": 700000000.0,
      "leonMssFrequencyHz": 700000000.0,
      "pipelineName": null,
      "pipelineVersion": null,
      "sippBufferSize": 18432,
      "sippDmaBufferSize": 16384,
      "xlinkChunkSize": -1
    },
    "nodes": [
      [
        0,
        {
          "id": 0,
          "ioInfo": [
            [
              [
                "",
                "inputConfig"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 1,
                "name": "inputConfig",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "raw"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 6,
                "name": "raw",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "still"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 7,
                "name": "still",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "inputControl"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 2,
                "name": "inputControl",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "video"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 3,
                "name": "video",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "isp"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 4,
                "name": "isp",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "preview"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 5,
                "name": "preview",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "",
                "frameEvent"
              ],
              {
                "blocking": false,
                "group": "",
                "id": 8,
                "name": "frameEvent",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "ColorCamera",
          "properties": {
            "boardSocket": -1,
            "cameraName": "",
            "colorOrder": 0,
            "fp16": false,
            "fps": 30.0,
            "imageOrientation": -1,
            "initialControl": {
              "aeLockMode": false,
              "aeMaxExposureTimeUs": 0,
              "aeRegion": {
                "height": 0,
                "priority": 0,
                "width": 0,
                "x": 0,
                "y": 0
              },
              "afRegion": {
                "height": 0,
                "priority": 0,
                "width": 0,
                "x": 0,
                "y": 0
              },
              "antiBandingMode": 0,
              "autoFocusMode": 3,
              "awbLockMode": false,
              "awbMode": 0,
              "brightness": 0,
              "captureIntent": 0,
              "chromaDenoise": 0,
              "cmdMask": 0,
              "contrast": 0,
              "controlMode": 0,
              "effectMode": 0,
              "expCompensation": 0,
              "expManual": {
                "exposureTimeUs": 0,
                "frameDurationUs": 0,
                "sensitivityIso": 0
              },
              "frameSyncMode": 0,
              "lensPosAutoInfinity": 0,
              "lensPosAutoMacro": 0,
              "lensPosition": 0,
              "lensPositionRaw": 0.0,
              "lowPowerNumFramesBurst": 0,
              "lowPowerNumFramesDiscard": 0,
              "lumaDenoise": 0,
              "saturation": 0,
              "sceneMode": 0,
              "sharpness": 0,
              "strobeConfig": {
                "activeLevel": 0,
                "enable": 0,
                "gpioNumber": 0
              },
              "strobeTimings": {
                "durationUs": 0,
                "exposureBeginOffsetUs": 0,
                "exposureEndOffsetUs": 0
              },
              "wbColorTemp": 0
            },
            "interleaved": true,
            "isp3aFps": 0,
            "ispScale": {
              "horizDenominator": 2,
              "horizNumerator": 1,
              "vertDenominator": 2,
              "vertNumerator": 1
            },
            "numFramesPoolIsp": 3,
            "numFramesPoolPreview": 4,
            "numFramesPoolRaw": 3,
            "numFramesPoolStill": 4,
            "numFramesPoolVideo": 4,
            "previewHeight": 300,
            "previewKeepAspectRatio": true,
            "previewWidth": 300,
            "rawPacked": null,
            "resolution": 0,
            "sensorCropX": -1.0,
            "sensorCropY": -1.0,
            "stillHeight": -1,
            "stillWidth": -1,
            "videoHeight": -1,
            "videoWidth": -1
          }
        }
      ],
      [
        1,
        {
          "id": 1,
          "ioInfo": [
            [
              [
                "io",
                "frames"
              ],
              {
                "blocking": true,
                "group": "io",
                "id": 9,
                "name": "frames",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": false
              }
            ],
            [
              [
                "io",
                "ctrl"
              ],
              {
                "blocking": false,
                "group": "io",
                "id": 10,
                "name": "ctrl",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "io",
                "stream1"
              ],
              {
                "blocking": false,
                "group": "io",
                "id": 11,
                "name": "stream1",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ],
            [
              [
                "io",
                "stream2"
              ],
              {
                "blocking": false,
                "group": "io",
                "id": 12,
                "name": "stream2",
                "queueSize": 8,
                "type": 0,
                "waitForMessage": false
              }
            ]
          ],
          "name": "Script",
          "properties": {
            "processor": 1,
            "scriptName": "<script>",
            "scriptUri": "asset:__script"
          }
        }
      ],
      [
        2,
        {
          "id": 2,
          "ioInfo": [
            [
              [
                "",
                "in"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 13,
                "name": "in",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": true
              }
            ]
          ],
          "name": "XLinkOut",
          "properties": {
            "maxFpsLimit": -1.0,
            "metadataOnly": false,
            "streamName": "stream1"
          }
        }
      ],
      [
        3,
        {
          "id": 3,
          "ioInfo": [
            [
              [
                "",
                "in"
              ],
              {
                "blocking": true,
                "group": "",
                "id": 14,
                "name": "in",
                "queueSize": 8,
                "type": 3,
                "waitForMessage": true
              }
            ]
          ],
          "name": "XLinkOut",
          "properties": {
            "maxFpsLimit": -1.0,
            "metadataOnly": false,
            "streamName": "stream2"
          }
        }
      ]
    ]
  }
}
```

### Need assistance?

Head over to [Discussion Forum](https://discuss.luxonis.com/) for technical support or any other questions you might have.
