homekit-camera-gstreamer 1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Naka-Masa19
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: homekit-camera-gstreamer
3
+ Version: 1.0
4
+ License-Expression: Apache-2.0
5
+ Requires-Python: >=3.10
6
+ License-File: LICENSE
7
+ Requires-Dist: HAP-Python
8
+ Requires-Dist: gstreamer-meta; sys_platform == "darwin" or sys_platform == "win32"
9
+ Dynamic: license-file
@@ -0,0 +1,135 @@
1
+ # HomeKit Camera GStreamer
2
+
3
+ [English version](README-en.md)
4
+
5
+ [![Lint](https://github.com/Naka-Masa19/homekit-camera-gstreamer/actions/workflows/lint.yml/badge.svg)](https://github.com/Naka-Masa19/homekit-camera-gstreamer/actions/workflows/lint.yml)
6
+
7
+ GStreamer の映像ソースを、Apple Home の HomeKit カメラとして公開するための Python ライブラリです。
8
+
9
+ Raspberry Pi Camera Module や USB/Web カメラ、PipeWire、ネットワークストリームなどを入力として利用できます。
10
+ 対応するエンコーダーを自動選択し、複数の Apple デバイスから同時に映像を確認できます。
11
+
12
+ ---
13
+ [サンプルプログラム](/examples)\
14
+ [Wiki](https://github.com/Naka-Masa19/homekit-camera-gstreamer/wiki)
15
+
16
+ ## 特徴
17
+ - マルチストリーミング対応
18
+ - 複数のデバイスへ同時にストリーミングできます。
19
+ - PipeWireやネットワークストリームなど、複数クライアントから同時に利用できる入力ソースが必要です。
20
+ - GStreamerが対応しているほぼすべてのソースに対応
21
+ - PipeWire
22
+ - USB/Webカメラ
23
+ - Raspberry Pi Camera Module
24
+ - ネットワークストリーム
25
+ - ファイル
26
+ - etc.
27
+ - H.264エンコーダーの自動選択 (`encodebin`)
28
+ - `openh264enc`
29
+ - `v4l2h264enc`
30
+ - `vtenc_h264`
31
+ - etc.
32
+ - ストリーミング中の動的な解像度変更
33
+ - HomeKitからの要求に応じて、ストリーミング中でも解像度を変更できます。
34
+
35
+ ## 動作確認済みの環境
36
+ - Raspberry Pi
37
+ - Model: Raspberry Pi 3 Model B Plus
38
+ - OS: Ubuntu Server 26.04 LTS
39
+ - Kernel: 7.0.0-1016-raspi
40
+ - Source: PipeWire
41
+ - Camera: Raspberry Pi Camera Module 2 (IMX219)
42
+ - Python: 3.14.4
43
+ - GStreamer: 1.28.2
44
+ - Encoder: `v4l2h264enc`
45
+ - PC
46
+ - OS: Fedora Linux 44 (Workstation Edition)
47
+ - Source: PipeWire
48
+ - Camera: MJPEGカメラ
49
+ - Python: 3.14.6
50
+ - GStreamer: 1.28.6
51
+ - Encoder: `openh264enc`
52
+
53
+ ## インストール
54
+ ### Debian (Ubuntu, Raspberry Pi OS)
55
+ ```bash
56
+ sudo apt install gstreamer1.0-plugins-good gstreamer1.0-plugins-bad libgstreamer1.0-0 gir1.2-gst-plugins-base-1.0 python3-gst-1.0 python3-gi python3-pip
57
+ pip3 install git+https://github.com/Naka-Masa19/homekit-camera-gstreamer.git --break-system-packages
58
+ ```
59
+ ### macOS / Windows
60
+ ``` zsh
61
+ pip3 install git+https://github.com/Naka-Masa19/homekit-camera-gstreamer.git
62
+ ```
63
+ > 初回起動時、時間がかかることがあります。
64
+
65
+ ## 構成例 (PipeWire経由のカメラ)
66
+
67
+ ### 1. PipeWireのインストール
68
+ ```bash
69
+ sudo apt install pipewire wireplumber gstreamer1.0-pipewire
70
+ ```
71
+ > Raspberry Pi Camera Moduleなどlibcameraを使用するカメラの場合は追加で以下のパッケージが必要です。
72
+ > ```bash
73
+ > sudo apt install libspa-0.2-libcamera libcamera-ipa
74
+ > ```
75
+ > `libspa-0.2-libcamera` が利用できない環境では、以下を試してください。
76
+ > ```bash
77
+ > sudo apt install pipewire-libcamera libcamera-ipa
78
+ > ```
79
+ ### 2. デフォルトカメラの設定
80
+ ``` bash
81
+ wpctl status
82
+ wpctl set-default [カメラのID]
83
+ ```
84
+ > [カメラのID]はwpctl statusのSourcesの結果に合わせて書き換えて下さい。
85
+
86
+ ### 3. 実行
87
+ 使用するカメラのアスペクト比に合わせてサンプルを選び、`camera.py`という名前で保存してください。
88
+
89
+ [16:9カメラ向けサンプルコード](examples/pipewire-16-9.py)
90
+ - 一般的なカメラ、Raspberry Pi Camera Module 3など
91
+
92
+ [4:3カメラ向けサンプルコード](examples/pipewire-4-3.py)
93
+ - Raspberry Pi Camera Module 1 / 2など
94
+
95
+ 保存したファイルを実行します。
96
+ ``` bash
97
+ python3 camera.py
98
+ ```
99
+ > `pipewiresrc` は環境によって低い解像度や狭い撮影範囲、意図しないフォーマットを選択する場合があります。必要に応じて、サンプルコード内の `source` をカメラに合わせて変更してください。特に Raspberry Pi Camera Moduleでは、色が正しく表示されず、撮影範囲も狭くなる場合があります。
100
+
101
+ ### 4. サービスとして登録
102
+ 以下の内容のファイルを`~/.config/systemd/user/homekit-camera.service`に配置してください。
103
+ ``` ini
104
+ [Unit]
105
+ Description=HomeKit camera daemon
106
+ Wants=pipewire.service
107
+ After=pipewire.service network-online.target
108
+
109
+ [Service]
110
+ ExecStart=/usr/bin/python3 /home/USER/camera.py
111
+ Restart=on-failure
112
+ #WorkingDirectory=/home/USER/HomeKit
113
+
114
+ [Install]
115
+ WantedBy=default.target
116
+ ```
117
+ > ExecStart のパスは、プログラムを配置した場所に合わせて変更してください。
118
+
119
+ サービスのテスト
120
+ ``` bash
121
+ systemctl --user start homekit-camera.service
122
+ systemctl --user status homekit-camera.service
123
+ journalctl --user -f -u homekit-camera.service
124
+ ```
125
+ サービスの有効化
126
+ ``` bash
127
+ loginctl enable-linger $USER
128
+ systemctl --user enable --now homekit-camera.service
129
+ ```
130
+
131
+ ## ライセンス
132
+
133
+ このプロジェクトは [Apache License 2.0](LICENSE) で公開されています。
134
+ サンプルコードに含まれる第三者ライセンスの通知は
135
+ [THIRD_PARTY_LICENSES.md](THIRD_PARTY_LICENSES.md) を参照してください。
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "homekit-camera-gstreamer"
3
+ version = "1.0"
4
+ requires-python = ">=3.10"
5
+ dependencies = [
6
+ "HAP-Python",
7
+ "gstreamer-meta; sys_platform == 'darwin' or sys_platform == 'win32'",
8
+ ]
9
+ license = "Apache-2.0"
10
+
11
+ [build-system]
12
+ requires = ["setuptools>=61.0"]
13
+ build-backend = "setuptools.build_meta"
14
+
15
+ [tool.ruff]
16
+ target-version = "py310"
17
+ line-length = 130
18
+
19
+ [tool.ruff.lint]
20
+ select = ["E", "F", "W", "N", "UP", "B"]
21
+
22
+ [tool.ruff.lint.per-file-ignores]
23
+ "examples/*.py" = ["E402"]
24
+ "src/gst_camera/core.py" = ["E402"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from .core import GstCamera
2
+
3
+ __all__ = ["GstCamera"]
@@ -0,0 +1,257 @@
1
+ from base64 import b64decode
2
+ from collections.abc import Callable
3
+ from pyhap import camera
4
+ from os import environ
5
+ import logging
6
+ import asyncio
7
+ from gi import require_versions
8
+
9
+ require_versions({"Gst": "1.0", "GstApp": "1.0", "GstPbutils": "1.0"})
10
+ from gi.repository import Gst, GstApp, GstPbutils # type:ignore
11
+
12
+ Gst.init()
13
+
14
+ logger = logging.getLogger(__name__)
15
+ logger.info(f"Initialized {Gst.version_string()}")
16
+
17
+ _ENCODE_PROFILE = {
18
+ camera.VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["BASELINE"]: "baseline",
19
+ camera.VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["MAIN"]: "main",
20
+ camera.VIDEO_CODEC_PARAM_PROFILE_ID_TYPES["HIGH"]: "high",
21
+ }
22
+
23
+ _ENCODE_LEVEL = {
24
+ camera.VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_1"]: "3.1",
25
+ camera.VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE3_2"]: "3.2",
26
+ camera.VIDEO_CODEC_PARAM_LEVEL_TYPES["TYPE4_0"]: "4",
27
+ }
28
+
29
+ if "GST_DEBUG" not in environ:
30
+ Gst.debug_set_default_threshold(
31
+ {
32
+ logging.CRITICAL: Gst.DebugLevel.NONE,
33
+ logging.ERROR: Gst.DebugLevel.ERROR,
34
+ logging.WARNING: Gst.DebugLevel.WARNING,
35
+ logging.INFO: Gst.DebugLevel.FIXME,
36
+ logging.DEBUG: Gst.DebugLevel.INFO,
37
+ }[logger.getEffectiveLevel()]
38
+ )
39
+
40
+ if not hasattr(asyncio, "SafeChildWatcher"):
41
+
42
+ class _DummyChildWatcher:
43
+ def __init__(self):
44
+ logger.warning("Class asyncio.SafeChildWatcher was removed in Python 3.14.")
45
+
46
+ def __getattr__(self, name):
47
+ return lambda *a, **ka: logger.warning(f"Called asyncio.SafeChildWatcher.{name}, ignored.")
48
+
49
+ asyncio.SafeChildWatcher = _DummyChildWatcher
50
+ asyncio.set_child_watcher = lambda w: logger.warning("Method asyncio.set_child_watcher was removed in Python 3.14, ignored.")
51
+
52
+
53
+ class StreamingSession:
54
+ def __init__(
55
+ self,
56
+ source: Callable[[], Gst.Bin],
57
+ stream_config: dict,
58
+ pre_encoder_format: str | None,
59
+ encoder_properties: Gst.Structure,
60
+ ):
61
+ self.stream_config = stream_config
62
+ self.pre_encoder_format = pre_encoder_format
63
+ self.encoder_properties = encoder_properties
64
+ self.pipeline = Gst.Pipeline.new()
65
+ self.bus = self.pipeline.get_bus()
66
+
67
+ self.src = source()
68
+ match self.src.iterate_all_by_element_factory_name("pipewiresrc").next():
69
+ case Gst.IteratorResult.OK, pipewiresrc:
70
+ pipewiresrc.set_properties(client_name=f"HomeKit Stream ({stream_config['address']})")
71
+ self.pipeline.add(self.src)
72
+
73
+ self._init_encodebin()
74
+
75
+ self.rtppay = self.pipeline.make_and_add("rtph264pay")
76
+ self.rtppay.set_properties(
77
+ config_interval=-1,
78
+ ssrc=stream_config["v_ssrc"],
79
+ mtu=int.from_bytes(stream_config["v_max_mtu"], "little"),
80
+ pt=int.from_bytes(stream_config["v_payload_type"], "little"),
81
+ )
82
+
83
+ srtp = self.pipeline.make_and_add("srtpenc")
84
+ srtp.set_properties(
85
+ rtp_cipher="aes-128-icm", rtp_auth="hmac-sha1-80", key=Gst.Buffer.new_wrapped(b64decode(stream_config["v_srtp_key"]))
86
+ )
87
+
88
+ sink = self.pipeline.make_and_add("udpsink")
89
+ sink.set_properties(sync=False, host=stream_config["address"], port=stream_config["v_port"])
90
+
91
+ Gst.Element.link_many(self.src, self.enc, self.rtppay, srtp, sink)
92
+
93
+ def _init_encodebin(self):
94
+ self.enc: Gst.Bin = self.pipeline.make_and_add("encodebin")
95
+
96
+ enc_format = Gst.Caps.new_empty_simple("video/x-h264")
97
+ enc_format.set_value("profile", _ENCODE_PROFILE[self.stream_config["v_profile_id"]])
98
+ enc_format.set_value("level", _ENCODE_LEVEL[self.stream_config["v_level"]])
99
+ enc_format.set_value("bitrate", self.stream_config["v_max_bitrate"])
100
+
101
+ enc_restriction = Gst.Caps.new_empty_simple("video/x-raw")
102
+ enc_restriction.set_value("width", self.stream_config["width"])
103
+ enc_restriction.set_value("height", self.stream_config["height"])
104
+ enc_restriction.set_value("framerate", Gst.Fraction(self.stream_config["fps"]))
105
+ if self.pre_encoder_format is not None:
106
+ enc_restriction.set_value("format", self.pre_encoder_format)
107
+
108
+ self.profile = GstPbutils.EncodingVideoProfile.new(enc_format, None, enc_restriction, 0)
109
+ self.profile.set_element_properties(self.encoder_properties)
110
+
111
+ self.enc.set_properties(profile=self.profile)
112
+
113
+ logger.info(f"Encodebin input caps: {enc_restriction.to_string()}")
114
+ logger.info(f"H264 profile: {enc_format.to_string()}")
115
+
116
+ def start_stream(self):
117
+ self.pipeline.set_state(Gst.State.PLAYING)
118
+ success = self.pipeline.get_state(Gst.SECOND * 10)[0] != Gst.StateChangeReturn.FAILURE
119
+
120
+ if logger.isEnabledFor(logging.INFO):
121
+ bin_list = list()
122
+ itr = self.enc.iterate_recurse()
123
+ while True:
124
+ match itr.next():
125
+ case Gst.IteratorResult.OK, element:
126
+ bin_list.append(element.get_name())
127
+ case Gst.IteratorResult.RESYNC, _:
128
+ bin_list.clear()
129
+ itr.resync()
130
+ case _:
131
+ break
132
+ logger.info(f"Encodebin chain: {' -> '.join(bin_list)}")
133
+
134
+ if not success:
135
+ self.stop_stream()
136
+ return success
137
+
138
+ def _reinit_encodebin(self, pad: Gst.Pad, info: Gst.PadProbeInfo):
139
+ self.src.unlink(self.enc)
140
+ self.enc.unlink(self.rtppay)
141
+
142
+ self.enc.set_state(Gst.State.NULL)
143
+ self.pipeline.remove(self.enc)
144
+
145
+ self._init_encodebin()
146
+
147
+ Gst.Element.link_many(self.src, self.enc, self.rtppay)
148
+
149
+ self.enc.sync_state_with_parent()
150
+ return Gst.PadProbeReturn.REMOVE
151
+
152
+ def reconfigure_stream(self, stream_config):
153
+ self.stream_config.update(stream_config)
154
+ self.src.get_static_pad("src").add_probe(Gst.PadProbeType.BLOCK_DOWNSTREAM, self._reinit_encodebin)
155
+ while self.bus.pop():
156
+ pass
157
+ return True
158
+
159
+ def stop_stream(self):
160
+ self.pipeline.set_state(Gst.State.NULL)
161
+
162
+
163
+ class GstCamera(camera.Camera):
164
+ StreamingSessionClass = StreamingSession
165
+
166
+ def __init__(self, source: str | Callable[[], Gst.Bin], options, *args, **kwargs):
167
+ super().__init__(options, *args, **kwargs)
168
+ self.set_info_service(firmware_revision=Gst.version_string())
169
+ self.snapshot_pipeline_wait_state = Gst.State.NULL if options.get("stream_count", 1) == 1 else Gst.State.READY
170
+ self.src = (lambda: Gst.parse_bin_from_description(f"{source} ! identity", True)) if isinstance(source, str) else source
171
+ self.ignore_reconfig = False
172
+ self.pre_encoder_format = None
173
+ self.encoder_properties = Gst.Structure.new_empty("encoder_properties")
174
+ self.snapshot_pipeline = Gst.Pipeline.new()
175
+ self.snapshot_bus = self.snapshot_pipeline.get_bus()
176
+
177
+ if not (callable(self.src) and isinstance(snapshot_src := self.src(), Gst.Bin)):
178
+ raise TypeError("source must be str or callable")
179
+ self.snapshot_pipeline.add(snapshot_src)
180
+ match snapshot_src.iterate_all_by_element_factory_name("pipewiresrc").next():
181
+ case Gst.IteratorResult.OK, pipewiresrc:
182
+ pipewiresrc.set_properties(client_name="HomeKit Snapshot")
183
+
184
+ snapshot_convertscale = self.snapshot_pipeline.make_and_add("videoconvertscale")
185
+ self.snapshot_caps = self.snapshot_pipeline.make_and_add("capsfilter")
186
+ snapshot_jpegenc = self.snapshot_pipeline.make_and_add("jpegenc")
187
+
188
+ self.snapshot_sink = GstApp.AppSink()
189
+ self.snapshot_pipeline.add(self.snapshot_sink)
190
+ self.snapshot_sink.set_max_buffers(1)
191
+ self.snapshot_sink.set_drop(True)
192
+
193
+ Gst.Element.link_many(snapshot_src, snapshot_convertscale, self.snapshot_caps, snapshot_jpegenc, self.snapshot_sink)
194
+
195
+ self.snapshot_pipeline.set_state(self.snapshot_pipeline_wait_state)
196
+
197
+ @property
198
+ def pre_encoder_format(self):
199
+ return self._pre_encoder_format
200
+
201
+ @pre_encoder_format.setter
202
+ def pre_encoder_format(self, arg: str | None):
203
+ if not isinstance(arg, str | None):
204
+ raise TypeError("pre_encoder_format must be str or None")
205
+ self._pre_encoder_format = arg
206
+
207
+ @property
208
+ def encoder_properties(self):
209
+ return self._encoder_properties
210
+
211
+ @encoder_properties.setter
212
+ def encoder_properties(self, arg: dict | Gst.Structure | None):
213
+ match arg:
214
+ case dict():
215
+ self._encoder_properties.remove_all_fields()
216
+ for key, value in arg.items():
217
+ self._encoder_properties.set_value(key, value)
218
+ case Gst.Structure():
219
+ self._encoder_properties = arg
220
+ case None:
221
+ self._encoder_properties.remove_all_fields()
222
+ case _:
223
+ raise TypeError("encoder_properties must be dict, Gst.Structure or None")
224
+
225
+ async def stop(self): # stop accessary
226
+ self.snapshot_pipeline.set_state(Gst.State.NULL)
227
+ return await super().stop()
228
+
229
+ async def start_stream(self, session_info, stream_config):
230
+ logger.info(f"[{session_info['id']}] Starting stream")
231
+ session_info["streaming_instance"] = self.StreamingSessionClass(
232
+ self.src, stream_config, self.pre_encoder_format, self.encoder_properties
233
+ )
234
+ return await asyncio.to_thread(session_info["streaming_instance"].start_stream)
235
+
236
+ async def reconfigure_stream(self, session_info, stream_config):
237
+ if self.ignore_reconfig:
238
+ logger.info(f"[{session_info['id']}] Ignoreing reconfig stream")
239
+ return True
240
+ logger.info(f"[{session_info['id']}] Reconfiguring stream")
241
+ return session_info["streaming_instance"].reconfigure_stream(stream_config)
242
+
243
+ async def stop_stream(self, session_info):
244
+ logger.info(f"[{session_info['id']}] Stopping stream")
245
+ session_info["streaming_instance"].stop_stream()
246
+
247
+ def get_snapshot(self, info):
248
+ while self.snapshot_bus.pop():
249
+ pass
250
+ caps = Gst.Caps.new_empty_simple("video/x-raw")
251
+ caps.set_value("width", info["image-width"])
252
+ caps.set_value("height", info["image-height"])
253
+ self.snapshot_caps.set_properties(caps=caps)
254
+ self.snapshot_pipeline.set_state(Gst.State.PLAYING)
255
+ sample = self.snapshot_sink.try_pull_sample(Gst.SECOND * 5)
256
+ self.snapshot_pipeline.set_state(self.snapshot_pipeline_wait_state)
257
+ return buf.extract_dup(0, buf.get_size()) if sample and (buf := sample.get_buffer()) else super().get_snapshot(info)
@@ -0,0 +1,9 @@
1
+ Metadata-Version: 2.4
2
+ Name: homekit-camera-gstreamer
3
+ Version: 1.0
4
+ License-Expression: Apache-2.0
5
+ Requires-Python: >=3.10
6
+ License-File: LICENSE
7
+ Requires-Dist: HAP-Python
8
+ Requires-Dist: gstreamer-meta; sys_platform == "darwin" or sys_platform == "win32"
9
+ Dynamic: license-file
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/gst_camera/__init__.py
5
+ src/gst_camera/core.py
6
+ src/homekit_camera_gstreamer.egg-info/PKG-INFO
7
+ src/homekit_camera_gstreamer.egg-info/SOURCES.txt
8
+ src/homekit_camera_gstreamer.egg-info/dependency_links.txt
9
+ src/homekit_camera_gstreamer.egg-info/requires.txt
10
+ src/homekit_camera_gstreamer.egg-info/top_level.txt
@@ -0,0 +1,4 @@
1
+ HAP-Python
2
+
3
+ [:sys_platform == "darwin" or sys_platform == "win32"]
4
+ gstreamer-meta