> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/deployment/ko/self-hosted/enterprise/stream-management-api.md).

# 스트림 관리 API

Stream Management API로 Roboflow Inference 비디오 파이프라인을 원격 관리합니다 - Docker에서 실행하고, HTTP로 통합하며, Stream Manager 프로토콜을 사용합니다.

{% hint style="warning" %}
독립형 서비스로는 더 이상 제공되지 않습니다. 자체 호스팅 동영상 처리를 사용하려면 Inference SDK WebRTC 클라이언트와 [Inference Server](https://docs.roboflow.com/deployment/ko/self-hosted/inference-server.md)를 사용하세요. 새로운 관리형 실시간 카메라 배포에는 [Cloud Streaming](https://docs.roboflow.com/deployment/ko/roboflow-cloud/cloud-streaming.md)을 사용하세요. 경로를 선택하려면 [동영상 처리](https://docs.roboflow.com/workflows/deploy/video-processing) 를 참조하세요.
{% endhint %}

{% hint style="warning" %}
이 페이지의 독립형 서비스를 프로덕션 환경에서 사용하려면 Roboflow Enterprise 라이선스가 필요합니다. 자세한 내용은 [Roboflow 라이선스](https://roboflow.com/licensing) 를 참조하세요. 현재 Inference 릴리스에는 더 이상 서비스의 소스 코드, Docker Compose 파일 또는 Dockerfile이 포함되지 않습니다. 아래에 게시된 이미지는 더 이상 업데이트되지 않습니다. API에는 인증 기능이 없으며 모든 네트워크 인터페이스에서 수신 대기합니다. 신뢰할 수 있는 네트워크 내부에서만 실행하거나 방화벽 또는 인증 프록시 뒤에서 실행하세요. 현재 Inference Server에서 동영상을 사용하는 방법은 [동영상 구성](https://docs.roboflow.com/deployment/ko/self-hosted/inference-server/configuration/video-configuration.md).
{% endhint %}

## 소개

Stream Management API는 온라인 비디오 스트림에서 Roboflow 객체 감지 모델을 사용해 예측을 생성했습니다. 비디오 작업자를 원격으로 제어할 수 있도록 HTTP 관리 계층을 추가했습니다.

다음과 같은 시나리오에서 유용합니다. 단, 이에 국한되지는 않습니다.

* 여러 온라인 비디오 스트림에서 동시에 추론을 수행합니다.
* 조율이 필요한 여러 장치에서 추론을 실행합니다.
* 비디오 처리를 감독하는 모니터링 계층을 구축합니다.

![Stream Management 설계](https://storage.googleapis.com/com-roboflow-marketing/inference/stream_management_api_design.jpg)

### 사용 사례 예시

Joe는 공장에 설치된 여러 IP 카메라로 촬영한 영상 속 객체를 모니터링하고자 합니다. Roboflow 플랫폼에서 객체 감지 모델을 학습한 뒤 배포를 준비합니다. 공장에 카메라가 네 대 있는 Joe는 Jetson 장치에서 초당 30회 이상의 추론을 수행할 수 있을 만큼 작은 모델을 선택합니다. 장치별 연산 예산을 고려할 때, 모든 카메라의 영상을 처리하려면 Jetson 장치 두 대가 필요하며, 각 비디오 소스당 초당 약 15프레임을 처리합니다.

배포를 간소화하기 위해 Joe는 로컬 네트워크의 모든 Jetson 장치에 Stream Management 컨테이너를 배포합니다. 이를 통해 HTTP를 사용해 각 장치와 통신하고 처리 작업을 조정할 수 있습니다. 장치에 명령을 전송하고 각 비디오 스트림의 상태 지표를 가져오는 웹 앱을 만듭니다. 마지막으로 예측을 수신할 UDP 서버를 구현하고, 영상 속 객체를 추적하는 데 `supervision` 패키지를 사용합니다.

## 실행 방법

### Docker에서

{% tabs %}
{% tab title="CPU" %}

```bash
docker run -d --name stream_manager --network host roboflow/roboflow-inference-stream-manager-cpu:latest
docker run -d --name stream_management_api --network host roboflow/roboflow-inference-stream-management-api:latest
```

{% endtab %}

{% tab title="GPU" %}

```bash
docker run -d --name stream_manager --network host --runtime nvidia roboflow/roboflow-inference-stream-manager-gpu:latest
docker run -d --name stream_management_api --network host roboflow/roboflow-inference-stream-management-api:latest
```

{% endtab %}

{% tab title="Jetson (JetPack 5.1.1)" %}

```bash
docker run -d --name stream_manager --network host --runtime nvidia roboflow/roboflow-inference-stream-manager-jetson-5.1.1:latest
docker run -d --name stream_management_api --network host roboflow/roboflow-inference-stream-management-api:latest
```

{% endtab %}
{% endtabs %}

#### 구성 매개변수

Stream Management API:

* `STREAM_MANAGER_HOST` - 스트림 관리자 컨테이너의 호스트 이름입니다. --network host를 사용하지 않거나 원격 머신을 대상으로 하는 경우 컨테이너 이름으로 변경하세요. `--network host` 를 사용하지 않거나 원격 머신을 대상으로 하는 경우입니다.
* `STREAM_MANAGER_PORT` - 스트림 관리자와 통신하는 데 사용하는 포트입니다. 스트림 관리자 컨테이너의 포트와 일치해야 합니다.

Stream Manager:

* `PORT` - 서버가 실행되는 포트입니다.
* 컨테이너의 `/tmp/cache` 에 볼륨을 마운트하면 모델을 영구 저장하여 추론 파이프라인 초기화를 더 빠르게 할 수 있습니다.
* 카메라 연결은 이 컨테이너 수준에서 활성화해야 합니다. 따라서 장치를 Docker에 전달해야 한다면 여기서 설정하세요.

## 통합 방법

다음을 실행한 후 `roboflow-inference-stream-management-api` 컨테이너를 실행하면 HTTP API를 다음 주소에서 사용할 수 있습니다. `http://127.0.0.1:8080` 기본 구성으로 실행됩니다.

다음을 호출하세요 `wget http://127.0.0.1:8080/openapi.json` API의 OpenAPI 사양을 가져오면 다음에서 렌더링할 수 있습니다: [Swagger 편집기](https://editor.swagger.io/).

Python 클라이언트 예시:

```python
import requests
from typing import Optional

URL = "http://127.0.0.1:8080"

def list_pipelines() -> dict:
    response = requests.get(f"{URL}/list_pipelines")
    return response.json()


def get_pipeline_status(pipeline_id: str) -> dict:
    response = requests.get(f"{URL}/status/{pipeline_id}")
    return response.json()


def pause_pipeline(pipeline_id: str) -> dict:
    response = requests.post(f"{URL}/pause/{pipeline_id}")
    return response.json()


def resume_pipeline(pipeline_id: str) -> dict:
    response = requests.post(f"{URL}/resume/{pipeline_id}")
    return response.json()


def terminate_pipeline(pipeline_id: str) -> dict:
    response = requests.post(f"{URL}/terminate/{pipeline_id}")
    return response.json()


def initialise_pipeline(
    video_reference: str,
    model_id: str,
    api_key: str,
    sink_host: str,
    sink_port: int,
    max_fps: Optional[int] = None,
) -> dict:
    response = requests.post(
        f"{URL}/initialise",
        json={
            "type": "init",
            "sink_configuration": {
                "type": "udp_sink",
                "host": sink_host,
                "port": sink_port,
            },
            "video_reference": video_reference,
            "model_id": model_id,
            "api_key": api_key,
            "max_fps": max_fps,
        },
    )
    return response.json()
```

{% hint style="info" %}
`initialise_pipeline()` 에는 다음이 필요합니다: `video_reference` 및 `sink_configuration` 모든 리소스(비디오 파일 또는 카메라 장치)와 URI(스트림 참조, 싱크 참조)에 Stream Manager 환경에서 접근할 수 있어야 합니다. 예를 들어 Docker 컨테이너 내부에서는 `localhost` 가 호스트 머신의 localhost가 아니라 컨테이너의 localhost를 가리킵니다.
{% endhint %}

## 개발자 참고 사항

구현의 핵심 요소는 단일 스레드 TCP 서버로 작동하는 Stream Manager 구성 요소입니다. TCP 소켓에서 수신한 요청을 처리하고 비디오 워커 프로세스를 감독합니다. 멀티프로세싱 큐를 통해 워커와 Stream Manager 간에 명령과 결과를 전달합니다.

Stream Manager에 대한 요청은 블로킹 모드에서 순차적으로 처리되므로, 다음 요청이 시작되기 전에 각 요청의 처리가 완료되어야 합니다.

### 통신 프로토콜: 요청

Stream Manager는 다음 바이너리 프로토콜을 지원합니다. 각 페이로드는 다음으로 구성됩니다.

```
[HEADER: 4B, big-endian, unsigned - int value with message size][MESSAGE: utf-8 serialised json of size dictated by header]
```

디코딩한 결과가 유효한 JSON이어야 하며, 유효한 명령을 나타내야 합니다.

`list_pipelines`:

```json
{
  "type": "list_pipelines"
}
```

`init`:

```json
{
  "type": "init",
  "model_id": "some/1",
  "video_reference": "rtsp://192.168.0.1:554",
  "sink_configuration": {
    "type": "udp_sink",
    "host": "192.168.0.3",
    "port": 9999
  },
  "api_key": "YOUR_API_KEY",
  "max_fps": 16,
  "model_configuration": {
    "type": "object-detection",
    "class_agnostic_nms": true,
    "confidence": 0.5,
    "iou_threshold": 0.4,
    "max_candidates": 300,
    "max_detections": 3000
  },
  "video_source_properties": {
    "frame_width": 1920,
    "frame_height": 1080,
    "fps": 30
  }
}
```

{% hint style="info" %}
모델 ID는 다음 문자열로 구성됩니다. `<project_id>/<version_id>`. 다음을 참조하세요. [모델 ID](https://docs.roboflow.com/models/model-ids) 에서 이 값을 확인할 수 있습니다.
{% endhint %}

`terminate`:

```json
{
  "type": "terminate",
  "pipeline_id": "my_pipeline"
}
```

`pause`:

```json
{
  "type": "mute",
  "pipeline_id": "my_pipeline"
}
```

`resume`:

```json
{
  "type": "resume",
  "pipeline_id": "my_pipeline"
}
```

`status`:

```json
{
  "type": "status",
  "pipeline_id": "my_pipeline"
}
```

### 통신 프로토콜: 응답

처리 가능한 각 요청(시간 초과 또는 소스 연결 끊김이 없는 경우)에 대해 Stream Manager는 다음 형식으로 결과를 반환합니다.

```
[HEADER: 4B, big-endian, unsigned - int value with result size][RESULT: utf-8 serialised json of size dictated by header]
```

결과에는 다음이 포함됩니다.

* `request_id` - 디버깅을 쉽게 하기 위해 Stream Manager가 할당한 요청 ID를 나타내는 임의의 문자열입니다.
* `pipeline_id` - 해당하는 경우 명령이 연결된 파이프라인입니다.
* `response` - 작업 응답의 페이로드입니다.

각 `response` 에는 `status` 키가 있으며, 값은 다음 두 가지 중 하나입니다: `success` 또는 `failure`. 실패 응답에는 `error_type` 키가 포함되어 오류 처리를 분기하며, 내부 오류 세부 정보를 담는 선택적 `error_class` 및 `error_message` 필드도 포함됩니다. 성공 응답의 내용은 작업 유형에 따라 달라집니다.
