删除未使用的相机和记录类来重构记录功能;更新pubspec中的依赖项。Yaml为本地插件路径;简化MainActivity和相关类,以提高性能和可维护性。

This commit is contained in:
2026-07-09 16:17:34 +08:00
parent 75c42ea168
commit 6138eddc16
65 changed files with 3677 additions and 2672 deletions
+82
View File
@@ -0,0 +1,82 @@
# Changelog
All changes to this project will be documented in this file.
## [1.2.0] - 2024-02-12
- Add a `fit` parameter to `ApiVideoCameraPreview` to control the fit of the preview inside its
parent widget
- Improve and fix few video resolution issues
- Android: The package automatically requests the camera and microphone permissions
- Android: upgrade gradle, kotlin, AGP and other dependencies
- iOS: add missing `getVideoSize` method
- iOS: send events from the main thread
- Example: lower default bitrate to run the example effortlessly
- Example: enable wake lock to keep the device awake during the live stream
- Example: put the application in the safe area
## [1.1.3] - 2023-10-16
- Android: call `disconnect` event when `stopStream` is explicitly called
- Add api.video application icon for Android and iOS
## [1.1.2] - 2023-08-16
- Android: fix the `videoSize` cast
## [1.1.1] - 2023-01-23
- iOS: fix the orientation when device is turned
## [1.1.0] - 2023-01-11
- Major refactor:
- use `initialize` instead of `create` and pass default parameters
to `ApiVideoLiveStreamController` constructor
- simplified usage of `CameraPreview` (and renamed to `ApiVideoCameraPreview`)
- Getter for properties such as `isMuted`, `cameraPosition`, ... (
see [#13](https://github.com/apivideo/api.video-flutter-live-stream/issues/13))
- Few fixes on Android and iOS
## [1.0.7] - 2022-10-12
- Fix crash on `stopStreaming`.
See [#14](https://github.com/apivideo/api.video-flutter-live-stream/issues/14)
## [1.0.6] - 2022-09-30
- Fix 1080p configuration.
See [#16](https://github.com/apivideo/api.video-flutter-live-stream/issues/16)
- Upgrade HaishinKit to 1.3.0.
See [#15](https://github.com/apivideo/api.video-flutter-live-stream/issues/15)
- Upgrade dependencies
## [1.0.5] - 2022-08-03
- Few fixes on FLV/RTMP to increase compatibility
- iOS: fix landscape orientation.
See [#12](https://github.com/apivideo/api.video-flutter-live-stream/issues/12)
## [1.0.4] - 2022-06-01
- iOS: Fix the random aspect ratio of the preview and random crashes.
See [#7](https://github.com/apivideo/api.video-flutter-live-stream/issues/7)
## [1.0.3] - 2022-05-30
- Android: do not obfuscate rtmpdroid classes to
fix [#6](https://github.com/apivideo/api.video-flutter-live-stream/issues/6)
## [1.0.2] - 2022-05-25
- iOS: implements `stopPreview` and `startPreview` to
fix [#4](https://github.com/apivideo/api.video-flutter-live-stream/issues/4)
## [1.0.1] - 2022-04-13
- Fix audio and video configuration for iOS
- Fix setAudioConfig when preview is running for Android
## [1.0.0] - 2022-04-08
- Initial release.
@@ -0,0 +1,228 @@
# Contributing to api.video
:movie_camera::+1::tada: Thank you for taking the time to contribute and participate in the implementation of a Video First World! :tada::+1::movie_camera:
The following is a set of guidelines for contributing to api.video and its packages, which are hosted in the [api.video Organization](https://github.com/apivideo) on GitHub.
#### Table of contents
- [Contributing to api.video](#contributing-to-apivideo)
- [Table of contents](#table-of-contents)
- [Code of conduct](#code-of-conduct)
- [I just have a question!](#i-just-have-a-question)
- [How can I contribute?](#how-can-i-contribute)
- [Reporting bugs](#reporting-bugs)
- [Before submitting a bug report](#before-submitting-a-bug-report)
- [How do I submit a (good) bug report?](#how-do-i-submit-a-good-bug-report)
- [Suggesting enhancements](#suggesting-enhancements)
- [How do I submit a (good) enhancement suggestion?](#how-do-i-submit-a-good-enhancement-suggestion)
- [Pull requests](#pull-requests)
- [Style guides](#style-guides)
- [Git commit messages](#git-commit-messages)
- [Documentation style guide](#documentation-style-guide)
- [Additional notes](#additional-notes)
- [Issue and pull request labels](#issue-and-pull-request-labels)
- [Type of issue and issue state](#type-of-issue-and-issue-state)
- [Topic categories](#topic-categories)
- [Pull request labels](#pull-request-labels)
## Code of conduct
This project and everyone participating in it is governed by the [api.video Code of Conduct](https://github.com/apivideo/.github/blob/main/CODE_OF_CONDUCT.md). By participating, you are expected to uphold this code. Please report unacceptable behavior to [help@api.video](mailto:help@api.video).
## I just have a question!
> **Note:** [Please don't file an issue to ask a question.] You'll get faster results by using the resources below.
We have an official message board with a detailed FAQ and where the community chimes in with helpful advice if you have questions.
* [The official api.video's Community](https://community.api.video/)
* [api.video FAQ](https://community.api.video/c/faq/)
## How can I contribute?
### Reporting bugs
This section guides you through submitting a bug report for api.video. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer:, and find related reports :mag_right:.
Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). Fill out [the required template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/bug_report.yml), the information it asks for helps us resolve issues faster.
> **Note:** If you find a **Closed** issue that seems like it is the same thing that you're experiencing, open a new issue and include a link to the original issue in the body of your new one.
#### Before submitting a bug report
* **Check the [The official api.video's Community](https://community.api.video/)** for a list of common questions and problems.
* **Determine which repository the problem should be reported in**.
* **Perform a [cursory search](https://github.com/search?q=is%3Aissue+user%3Aapivideo)** to see if the problem has already been reported. If it has **and the issue is still open**, add a comment to the existing issue instead of opening a new one.
#### How do I submit a (good) bug report?
Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your bug is related to, create an issue on that repository and provide the following information by filling in [the template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/bug_report.yml).
Explain the problem and include additional details to help maintainers reproduce the problem:
* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible. When listing steps, **don't just say what you did, but explain how you did it**.
* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
* **Explain which behavior you expected to see instead and why.**
* **Include screenshots or videos** which show you following the described steps and clearly demonstrate the problem.
* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below.
Provide more context by answering these questions:
* **Did the problem start happening recently** (e.g. after updating to a new version of api.video) or was this always a problem?
* If the problem started happening recently.**
* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.
Include details about your configuration and environment:
* **Which version of the api.video package are you using?**
* **What's the name and version of the OS you're using?**
### Suggesting enhancements
This section guides you through submitting an enhancement suggestion for api.video project, including completely new features and minor improvements to existing functionality. Following these guidelines helps maintainers and the community understand your suggestion :pencil: and find related suggestions :mag_right:.
When you are creating an enhancement suggestion, please [include as many details as possible](#how-do-i-submit-a-good-enhancement-suggestion). Fill in [the template](https://github.com/apivideo/.github/blob/main/.github/ISSUE_TEMPLATE/feature_request.yml), including the steps that you imagine you would take if the feature you're requesting existed.
#### How do I submit a (good) enhancement suggestion?
Enhancement suggestions are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined which repository your enhancement suggestion is related to, create an issue on that repository and provide the following information:
* **Use a clear and descriptive title** for the issue to identify the suggestion.
* **Provide a step-by-step description of the suggested enhancement** in as many details as possible.
* **Provide specific examples to demonstrate the steps**. Include copy/pasteable snippets which you use in those examples, as [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the current behavior** and **explain which behavior you expected to see instead** and why.
* **Include screenshots** which help you demonstrate the steps or point out the part of api.video which the suggestion is related to.
* **Explain why this enhancement would be useful** to most api.video users and isn't something that can or should be implemented as a community package.
* **Specify which version of the api.video package you're using.**
* **Specify the name and version of the OS you're using.**
### Pull requests
The process described here has several goals:
- Maintain api.video's quality
- Fix problems that are important to users
- Engage the community in working toward the best possible api.video
- Enable a sustainable system for api.video's maintainers to review contributions
Please follow these steps to have your contribution considered by the maintainers:
1. Explain what, why and how you resolved the issue. If you have a related issue, please mention it.
2. Follow the [style guides](#style-guides)
3. After you submit your pull request, verify that all [status checks](https://help.github.com/articles/about-status-checks/) are passing <details><summary>What if the status checks are failing?</summary>If a status check is failing, and you believe that the failure is unrelated to your change, please leave a comment on the pull request explaining why you believe the failure is unrelated. A maintainer will re-run the status check for you. If we conclude that the failure was a false positive, then we will open an issue to track that problem with our status check suite.</details>
While the prerequisites above must be satisfied prior to having your pull request reviewed, the reviewer(s) may ask you to complete additional design work, tests, or other changes before your pull request can be ultimately accepted.
## Style guides
### Git commit messages
* Use the present tense ("Add feature" not "Added feature")
* Limit the first line to 72 characters or less
* Reference issues and pull requests after the first line
* Consider starting the commit message with an applicable emoji:
* :art: `:art:` when improving the format/structure of the code
* :racehorse: `:racehorse:` when improving performance
* :non-potable_water: `:non-potable_water:` when plugging memory leaks
* :memo: `:memo:` when writing docs
* :penguin: `:penguin:` when fixing something on Linux
* :apple: `:apple:` when fixing something on macOS
* :checkered_flag: `:checkered_flag:` when fixing something on Windows
* :bug: `:bug:` when fixing a bug
* :fire: `:fire:` when removing code or files
* :green_heart: `:green_heart:` when fixing the CI build
* :white_check_mark: `:white_check_mark:` when adding tests
* :lock: `:lock:` when dealing with security
* :arrow_up: `:arrow_up:` when upgrading dependencies
* :arrow_down: `:arrow_down:` when downgrading dependencies
* :shirt: `:shirt:` when removing linter warnings
### Documentation style guide
* Use [Markdown](https://daringfireball.net/projects/markdown).
## Additional notes
### Issue and pull request labels
This section lists the labels we use to help us track and manage issues and pull requests on all api.video repositories.
[GitHub search](https://help.github.com/articles/searching-issues/) makes it easy to use labels for finding groups of issues or pull requests you're interested in. We encourage you to read about [other search filters](https://help.github.com/articles/searching-issues/) which will help you write more focused queries.
#### Type of issue and issue state
| Label name | `apivideo` :mag_right: | Description |
| --- | --- | --- |
| `enhancement` | [search][search-apivideo-org-label-enhancement] | Feature requests. |
| `bug` | [search][search-apivideo-org-label-bug] | Confirmed bugs or reports that are very likely to be bugs. |
| `question` | [search][search-apivideo-org-label-question] | Questions more than bug reports or feature requests (e.g. how do I do X). |
| `feedback` | [search][search-apivideo-org-label-feedback] | General feedback more than bug reports or feature requests. |
| `help-wanted` | [search][search-apivideo-org-label-help-wanted] | The api.video team would appreciate help from the community in resolving these issues. |
| `more-information-needed` | [search][search-apivideo-org-label-more-information-needed] | More information needs to be collected about these problems or feature requests (e.g. steps to reproduce). |
| `needs-reproduction` | [search][search-apivideo-org-label-needs-reproduction] | Likely bugs, but haven't been reliably reproduced. |
| `blocked` | [search][search-apivideo-org-label-blocked] | Issues blocked on other issues. |
| `duplicate` | [search][search-apivideo-org-label-duplicate] | Issues which are duplicates of other issues, i.e. they have been reported before. |
| `wontfix` | [search][search-apivideo-org-label-wontfix] | The api.video team has decided not to fix these issues for now, either because they're working as intended or for some other reason. |
| `invalid` | [search][search-apivideo-org-label-invalid] | Issues which aren't valid (e.g. user errors). |
| `package-idea` | [search][search-apivideo-org-label-package-idea] | Feature request which might be good candidates for new packages, instead of extending api.video packages. |
| `wrong-repo` | [search][search-apivideo-org-label-wrong-repo] | Issues reported on the wrong repository. |
#### Topic categories
| Label name | `apivideo` :mag_right: | Description |
| --- | --- | --- |
| `windows` | [search][search-apivideo-org-label-windows] | Related to api.video running on Windows. |
| `linux` | [search][search-apivideo-org-label-linux] | Related to api.video running on Linux. |
| `mac` | [search][search-apivideo-org-label-mac] | Related to api.video running on macOS. |
| `documentation` | [search][search-apivideo-org-label-documentation] | Related to any type of documentation. |
| `performance` | [search][search-apivideo-org-label-performance] | Related to performance. |
| `security` | [search][search-apivideo-org-label-security] | Related to security. |
| `ui` | [search][search-apivideo-org-label-ui] | Related to visual design. |
| `api` | [search][search-apivideo-org-label-api] | Related to api.video's public APIs. |
#### Pull request labels
| Label name | `apivideo` :mag_right: | Description
| --- | --- | --- |
| `work-in-progress` | [search][search-apivideo-org-label-work-in-progress] | Pull requests which are still being worked on, more changes will follow. |
| `needs-review` | [search][search-apivideo-org-label-needs-review] | Pull requests which need code review, and approval from maintainers or api.video team. |
| `under-review` | [search][search-apivideo-org-label-under-review] | Pull requests being reviewed by maintainers or api.video team. |
| `requires-changes` | [search][search-apivideo-org-label-requires-changes] | Pull requests which need to be updated based on review comments and then reviewed again. |
| `needs-testing` | [search][search-apivideo-org-label-needs-testing] | Pull requests which need manual testing. |
[search-apivideo-org-label-enhancement]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aenhancement
[search-apivideo-org-label-bug]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Abug
[search-apivideo-org-label-question]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aquestion
[search-apivideo-org-label-feedback]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Afeedback
[search-apivideo-org-label-help-wanted]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ahelp-wanted
[search-apivideo-org-label-more-information-needed]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Amore-information-needed
[search-apivideo-org-label-needs-reproduction]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aneeds-reproduction
[search-apivideo-org-label-windows]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awindows
[search-apivideo-org-label-linux]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Alinux
[search-apivideo-org-label-mac]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Amac
[search-apivideo-org-label-documentation]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Adocumentation
[search-apivideo-org-label-performance]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aperformance
[search-apivideo-org-label-security]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Asecurity
[search-apivideo-org-label-ui]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aui
[search-apivideo-org-label-api]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aapi
[search-apivideo-org-label-blocked]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ablocked
[search-apivideo-org-label-duplicate]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Aduplicate
[search-apivideo-org-label-wontfix]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awontfix
[search-apivideo-org-label-invalid]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Ainvalid
[search-apivideo-org-label-package-idea]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Apackage-idea
[search-apivideo-org-label-wrong-repo]: https://github.com/search?q=is%3Aopen+is%3Aissue+user%3Aapivideo+label%3Awrong-repo
[search-apivideo-org-label-work-in-progress]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Awork-in-progress
[search-apivideo-org-label-needs-review]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aneeds-review
[search-apivideo-org-label-under-review]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aunder-review
[search-apivideo-org-label-requires-changes]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Arequires-changes
[search-apivideo-org-label-needs-testing]: https://github.com/search?q=is%3Aopen+is%3Apr+repo%3Aapivideo%2Fapivideo+label%3Aneeds-testing
[help-wanted]:https://github.com/search?q=is%3Aopen+is%3Aissue+label%3Ahelp-wanted+user%3Aapivideo+sort%3Acomments-desc
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 api.video
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+214
View File
@@ -0,0 +1,214 @@
<!--<documentation_excluded>-->
[![badge](https://img.shields.io/twitter/follow/api_video?style=social)](https://twitter.com/intent/follow?screen_name=api_video)
&nbsp; [![badge](https://img.shields.io/github/stars/apivideo/api.video-flutter-live-stream?style=social)](https://github.com/apivideo/api.video-flutter-live-stream)
&nbsp; [![badge](https://img.shields.io/discourse/topics?server=https%3A%2F%2Fcommunity.api.video)](https://community.api.video)
![](https://github.com/apivideo/.github/blob/main/assets/apivideo_banner.png)
<h1 align="center">Flutter RTMP live stream client</h1>
[api.video](https://api.video) is the video infrastructure for product builders. Lightning fast
video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in
your app.
## Table of contents
- [Table of contents](#table-of-contents)
- [Project description](#project-description)
- [Getting started](#getting-started)
- [Installation](#installation)
- [Permissions](#permissions)
- [Code sample](#code-sample)
- [Manage application lifecycle](#manage-application-lifecycle)
- [Example App](#example-app)
- [Setup](#setup)
- [Android](#android)
- [iOS](#ios)
- [Plugins](#plugins)
- [FAQ](#faq)
<!--</documentation_excluded>-->
<!--<documentation_only>
---
title: Flutter RTMP live stream client
meta:
description: The official Flutter RTMP live stream client for
api.video. [api.video](https://api.video/) is the video infrastructure for product builders.
Lightning fast video APIs for integrating, scaling, and managing on-demand & low latency live
streaming features in your app.
---
# Flutter RTMP Live stream Client
[api.video](https://api.video/) is the video infrastructure for product builders. Lightning fast
video APIs for integrating, scaling, and managing on-demand & low latency live streaming features in
your app.
</documentation_only>-->
## Project description
This module is made for broadcasting RTMP live stream from smartphone camera.
## Getting started
### Installation
Run the following command at the root of your project:
```shell
flutter pub add apivideo_live_stream
```
In your dart file, import the package:
```dart
import 'package:apivideo_live_stream/apivideo_live_stream.dart';
```
### Permissions
To be able to broadcast, you must:
1. On Android: ask for internet, camera and microphone permissions:
```xml
<manifest>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
</manifest>
```
The library will require android.permission.CAMERA and android.permission.RECORD_AUDIO at runtime.
You don't need to request them.
2. On iOS: update the Info.plist with a usage description for camera and microphone
```xml
<key>NSCameraUsageDescription</key>
<string>Your own description of the purpose</string>
<key>NSMicrophoneUsageDescription</key>
<string>Your own description of the purpose</string>
```
### Code sample
1. Creates a live stream controller
```dart
final ApiVideoLiveStreamController _controller = ApiVideoLiveStreamController(
initialAudioConfig: AudioConfig(), initialVideoConfig: VideoConfig.withDefaultBitrate());
```
2. Initializes the live stream controller
```dart
await _controller.initialize();
```
3. Adds a CameraPreview widget as a child of your view
```dart
@override
Widget build(BuildContext context) {
return SizedBox(
width: 300.0,
height: 300.0,
child: ApiVideoCameraPreview(controller: _controller));
}
```
`ApiVideoCameraPreview` parameters:
- `controller`: the live stream controller
- `fit`: the fit of the preview (default is BoxFit.contain,
see [BoxFit](https://api.flutter.dev/flutter/painting/BoxFit.html) for more information)
- `child`: a child widget to overlay on top of the preview (optional)
4. Starts a live stream
```dart
_controller.startStreaming("YOUR_STREAM_KEY");
```
5. Stops streaming and preview
```dart
_controller.stop();
```
#### Manage application lifecycle
On the application side, you must manage application lifecycle:
```dart
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.inactive) {
_controller.stop();
} else if (state == AppLifecycleState.resumed) {
_controller.startPreview();
}
}
```
## Example App
You can try
our [example app](https://github.com/apivideo/api.video-flutter-live-stream/tree/master/example),
feel free to test it.
### Setup
Be sure to follow the [Flutter installation steps](https://docs.flutter.dev/get-started/) before
anything.
1) Open Android Studio
2) File > New > Project from Version Control
In URL field, type:
```shell
git@github.com:apivideo/api.video-flutter-live-stream.git
```
Wait for the indexation to finish.
#### Android
Connect an Android device to your computer and click on the `Run main.dart` button.
#### iOS
1) Connect an iOS device to your computer and click on the `Run main.dart` button.
2) The build will fail because you haven't set your development profile, sign your application:
Open Xcode, click on "Open a project or file" and open
the `YOUR_PROJECT_NAME/example/ios/Runner.xcworkspace` file.
<br />Click on Example, go in `Signin & Capabilities` tab, add your team and create a unique bundle
identifier.
## Plugins
api.video Flutter live stream library is using external native libraries:
| Plugin | README |
|------------|--------------|
| StreamPack | [StreamPack] |
| HaishinKit | [HaishinKit] |
## FAQ
If you have any questions, ask us in the [community](https://community.api.video) or
use [issues](https://github.com/apivideo/api.video-flutter-live-stream/issues).
[//]: # (These are reference links used in the body of this note and get stripped out when the markdown processor does its job. There is no need to format nicely because it shouldn't be seen. Thanks SO - http://stackoverflow.com/questions/4823468/store-comments-in-markdown-syntax)
[StreamPack]: <https://github.com/ThibaultBee/StreamPack>
[HaishinKit]: <https://github.com/shogo4405/HaishinKit.swift>
@@ -0,0 +1,7 @@
include: package:flutter_lints/flutter.yaml
linter:
rules:
constant_identifier_names: false
prefer_final_fields: false
prefer_single_quotes: false
@@ -0,0 +1,62 @@
group 'video.api.flutter.livestream'
version '1.0-SNAPSHOT'
buildscript {
ext {
kotlin_version = '1.9.22'
streamPackVersion = '2.6.0'
}
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:8.2.2'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
rootProject.allprojects {
repositories {
google()
mavenCentral()
}
}
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
android {
compileSdk 34
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
defaultConfig {
minSdkVersion 21
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
kotlinOptions {
jvmTarget = '1.8'
}
namespace "video.api.flutter.livestream"
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.7.3'
implementation 'androidx.appcompat:appcompat:1.6.1'
implementation "io.github.thibaultbee:streampack:$streamPackVersion"
implementation "io.github.thibaultbee:streampack-extension-rtmp:$streamPackVersion"
}
@@ -0,0 +1,3 @@
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.2-all.zip
@@ -0,0 +1 @@
rootProject.name = 'apivideo_live_stream'
@@ -0,0 +1,9 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-feature
android:name="android.hardware.camera"
android:required="true"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
</manifest>
@@ -0,0 +1,54 @@
package video.api.flutter.livestream
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.FlutterPlugin.FlutterPluginBinding
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
/** ApiVideoLiveStreamPlugin */
class ApiVideoLiveStreamPlugin : FlutterPlugin, ActivityAware {
private var permissionsManager: PermissionsManager? = null
private var methodCallHandlerImpl: MethodCallHandlerImpl? = null
override fun onAttachedToEngine(binding: FlutterPluginBinding) {
permissionsManager = PermissionsManager(binding.applicationContext).apply {
methodCallHandlerImpl = MethodCallHandlerImpl(
binding.applicationContext,
binding.binaryMessenger,
this,
binding.textureRegistry
).apply {
startListening()
}
}
}
override fun onDetachedFromEngine(binding: FlutterPluginBinding) {
methodCallHandlerImpl?.stopListening()
methodCallHandlerImpl = null
permissionsManager = null
}
override fun onAttachedToActivity(binding: ActivityPluginBinding) {
val activity = binding.activity
permissionsManager?.let {
it.activity = activity
binding.addRequestPermissionsResultListener(it)
}
}
override fun onDetachedFromActivityForConfigChanges() {
permissionsManager?.activity = null
}
override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
permissionsManager?.let {
it.activity = null
binding.addRequestPermissionsResultListener(it)
}
}
override fun onDetachedFromActivity() {
permissionsManager?.activity = null
}
}
@@ -0,0 +1,274 @@
package video.api.flutter.livestream
import android.Manifest
import android.content.Context
import android.util.Size
import android.view.Surface
import io.flutter.view.TextureRegistry
import io.github.thibaultbee.streampack.data.AudioConfig
import io.github.thibaultbee.streampack.data.VideoConfig
import io.github.thibaultbee.streampack.error.StreamPackError
import io.github.thibaultbee.streampack.ext.rtmp.streamers.CameraRtmpLiveStreamer
import io.github.thibaultbee.streampack.listeners.OnConnectionListener
import io.github.thibaultbee.streampack.listeners.OnErrorListener
import io.github.thibaultbee.streampack.utils.backCameraList
import io.github.thibaultbee.streampack.utils.externalCameraList
import io.github.thibaultbee.streampack.utils.frontCameraList
import io.github.thibaultbee.streampack.utils.isBackCamera
import io.github.thibaultbee.streampack.utils.isExternalCamera
import io.github.thibaultbee.streampack.utils.isFrontCamera
import kotlinx.coroutines.runBlocking
class FlutterLiveStreamView(
private val context: Context,
textureRegistry: TextureRegistry,
private val permissionsManager: PermissionsManager,
private val onConnectionSucceeded: () -> Unit,
private val onDisconnected: () -> Unit,
private val onConnectionFailed: (String) -> Unit,
private val onGenericError: (Exception) -> Unit,
private val onVideoSizeChanged: (Size) -> Unit,
) :
OnConnectionListener, OnErrorListener {
private val flutterTexture = textureRegistry.createSurfaceTexture()
val textureId: Long
get() = flutterTexture.id()
private val streamer = CameraRtmpLiveStreamer(
context = context,
initialOnConnectionListener = this,
initialOnErrorListener = this
)
private var _isPreviewing = false
private var _isStreaming = false
val isStreaming: Boolean
get() = _isStreaming
private var _videoConfig: VideoConfig? = null
val videoConfig: VideoConfig
get() = _videoConfig!!
fun setVideoConfig(
videoConfig: VideoConfig,
onSuccess: () -> Unit,
onError: (Exception) -> Unit
) {
if (isStreaming) {
throw UnsupportedOperationException("You have to stop streaming first")
}
onVideoSizeChanged(videoConfig.resolution)
val wasPreviewing = _isPreviewing
if (wasPreviewing) {
stopPreview()
}
streamer.configure(videoConfig)
_videoConfig = videoConfig
if (wasPreviewing) {
startPreview(onSuccess, onError)
} else {
onSuccess()
}
}
private var _audioConfig: AudioConfig? = null
val audioConfig: AudioConfig
get() = _audioConfig!!
fun setAudioConfig(
audioConfig: AudioConfig,
onSuccess: () -> Unit,
onError: (Exception) -> Unit
) {
if (isStreaming) {
throw UnsupportedOperationException("You have to stop streaming first")
}
permissionsManager.requestPermission(
Manifest.permission.RECORD_AUDIO,
onGranted = {
try {
streamer.configure(audioConfig)
_audioConfig = audioConfig
onSuccess()
} catch (e: Exception) {
onError(e)
}
},
onShowPermissionRationale = { _ ->
/**
* Require an AppCompat theme to use MaterialAlertDialogBuilder
*
context.showDialog(
R.string.permission_required,
R.string.record_audio_permission_required_message,
android.R.string.ok,
onPositiveButtonClick = { onRequiredPermissionLastTime() }
) */
onError(SecurityException("Missing permission Manifest.permission.RECORD_AUDIO"))
},
onDenied = {
onError(SecurityException("Missing permission Manifest.permission.RECORD_AUDIO"))
})
}
var isMuted: Boolean
get() = streamer.settings.audio.isMuted
set(value) {
streamer.settings.audio.isMuted = value
}
val camera: String
get() = streamer.camera
fun setCamera(camera: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) {
permissionsManager.requestPermission(
Manifest.permission.CAMERA,
onGranted = {
try {
streamer.camera = camera
onSuccess()
} catch (e: Exception) {
onError(e)
}
},
onShowPermissionRationale = { _ ->
/**
* Require an AppCompat theme to use MaterialAlertDialogBuilder
*
* context.showDialog(
R.string.permission_required,
R.string.camera_permission_required_message,
android.R.string.ok,
onPositiveButtonClick = { onRequiredPermissionLastTime() }
)*/
onError(SecurityException("Missing permission Manifest.permission.CAMERA"))
},
onDenied = {
onError(SecurityException("Missing permission Manifest.permission.CAMERA"))
})
}
fun setCameraId(cameraId: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) {
setCamera(cameraId, onSuccess, onError)
}
val cameraPosition: String
get() = when {
context.isFrontCamera(streamer.camera) -> "front"
context.isBackCamera(streamer.camera) -> "back"
context.isExternalCamera(streamer.camera) -> "other"
else -> throw IllegalArgumentException("Invalid camera position for camera ${streamer.camera}")
}
fun setCameraPosition(position: String, onSuccess: () -> Unit, onError: (Exception) -> Unit) {
val cameraList = when (position) {
"front" -> context.frontCameraList
"back" -> context.backCameraList
"other" -> context.externalCameraList
else -> throw IllegalArgumentException("Invalid camera position: $position")
}
setCamera(cameraList.first(), onSuccess, onError)
}
fun dispose() {
stopStream()
streamer.stopPreview()
flutterTexture.release()
}
fun startStream(url: String) {
runBlocking {
streamer.connect(url)
try {
streamer.startStream()
_isStreaming = true
} catch (e: Exception) {
streamer.disconnect()
onLost("Failed to start stream: ${e.message}")
throw e
}
}
}
fun stopStream() {
val isConnected = streamer.isConnected
runBlocking {
streamer.stopStream()
streamer.disconnect()
if (isConnected) {
onDisconnected()
}
_isStreaming = false
}
}
fun startPreview(onSuccess: () -> Unit, onError: (Exception) -> Unit) {
permissionsManager.requestPermission(
Manifest.permission.CAMERA,
onGranted = {
if (_videoConfig == null) {
onError(IllegalStateException("Video has not been configured!"))
} else {
try {
streamer.startPreview(getSurface(videoConfig.resolution))
_isPreviewing = true
onSuccess()
} catch (e: Exception) {
onError(e)
}
}
},
onShowPermissionRationale = { _ ->
/**
* Require an AppCompat theme to use MaterialAlertDialogBuilder
*
* context.showDialog(
R.string.permission_required,
R.string.camera_permission_required_message,
android.R.string.ok,
onPositiveButtonClick = { onRequiredPermissionLastTime() }
)*/
onError(SecurityException("Missing permission Manifest.permission.CAMERA"))
},
onDenied = {
onError(SecurityException("Missing permission Manifest.permission.CAMERA"))
})
}
fun stopPreview() {
streamer.stopPreview()
_isPreviewing = false
}
private fun getSurface(resolution: Size): Surface {
val surfaceTexture = flutterTexture.surfaceTexture().apply {
setDefaultBufferSize(
resolution.width,
resolution.height
)
}
return Surface(surfaceTexture)
}
override fun onSuccess() {
onConnectionSucceeded()
}
override fun onLost(message: String) {
onDisconnected()
}
override fun onFailed(message: String) {
onConnectionFailed(message)
}
override fun onError(error: StreamPackError) {
_isStreaming = false
onGenericError(error)
}
}
@@ -0,0 +1,341 @@
package video.api.flutter.livestream
import android.content.Context
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CameraManager
import android.os.Handler
import android.os.Looper
import android.util.Size
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.view.TextureRegistry
import video.api.flutter.livestream.utils.addTrailingSlashIfNeeded
import video.api.flutter.livestream.utils.toAudioConfig
import video.api.flutter.livestream.utils.toVideoConfig
import kotlin.math.atan
class MethodCallHandlerImpl(
private val context: Context,
messenger: BinaryMessenger,
private val permissionsManager: PermissionsManager,
private val textureRegistry: TextureRegistry
) : MethodChannel.MethodCallHandler {
private val methodChannel = MethodChannel(messenger, METHOD_CHANNEL_NAME)
private val eventChannel = EventChannel(messenger, EVENT_CHANNEL_NAME)
private var eventSink: EventChannel.EventSink? = null
private var flutterView: FlutterLiveStreamView? = null
fun startListening() {
methodChannel.setMethodCallHandler(this)
eventChannel.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
eventSink = events
}
override fun onCancel(arguments: Any?) {
eventSink?.endOfStream()
eventSink = null
}
})
}
fun stopListening() {
methodChannel.setMethodCallHandler(null)
eventChannel.setStreamHandler(null)
}
override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
when (call.method) {
"create" -> {
try {
flutterView?.dispose()
flutterView = FlutterLiveStreamView(
context,
textureRegistry,
permissionsManager,
{ sendConnected() },
{ sendDisconnected() },
{ sendConnectionFailed(it) },
{ sendError(it) },
{ sendVideoSizeChanged(it) }
)
result.success(mapOf("textureId" to flutterView!!.textureId))
} catch (e: Exception) {
result.error("failed_to_create_live_stream", e.message, null)
}
}
"dispose" -> {
flutterView?.dispose()
flutterView = null
}
"setVideoConfig" -> {
try {
@Suppress("UNCHECKED_CAST")
val videoConfig = (call.arguments as Map<String, Any>).toVideoConfig()
flutterView!!.setVideoConfig(
videoConfig,
{ result.success(null) },
{
result.error(
"failed_to_set_video_config",
it.message,
null
)
})
} catch (e: Exception) {
result.error("failed_to_set_video_config", e.message, null)
}
}
"setAudioConfig" -> {
try {
@Suppress("UNCHECKED_CAST")
val audioConfig = (call.arguments as Map<String, Any>).toAudioConfig()
flutterView!!.setAudioConfig(
audioConfig,
{ result.success(null) },
{
result.error(
"failed_to_set_audio_config",
it.message,
null
)
})
} catch (e: Exception) {
result.error("failed_to_set_audio_config", e.message, null)
}
}
"startPreview" -> {
try {
flutterView!!.startPreview(
{ result.success(null) },
{
result.error(
"failed_to_start_preview",
it.message,
null
)
})
} catch (e: Exception) {
result.error("failed_to_start_preview", e.message, null)
}
}
"stopPreview" -> {
flutterView?.stopPreview()
result.success(null)
}
"startStreaming" -> {
val streamKey = call.argument<String>("streamKey")
val url = call.argument<String>("url")
when {
streamKey == null -> result.error(
"missing_stream_key", "Stream key is missing", null
)
streamKey.isEmpty() -> result.error(
"empty_stream_key", "Stream key is empty", null
)
url == null -> result.error(
"missing_rtmp_url",
"RTMP URL is missing",
null
)
url.isEmpty() -> result.error("empty_rtmp_url", "RTMP URL is empty", null)
else ->
try {
flutterView!!.startStream(url.addTrailingSlashIfNeeded() + streamKey)
result.success(null)
} catch (e: Exception) {
result.error("failed_to_start_stream", e.message, null)
}
}
}
"stopStreaming" -> {
flutterView?.stopStream()
result.success(null)
}
"getIsStreaming" -> result.success(mapOf("isStreaming" to flutterView!!.isStreaming))
"getCameraPosition" -> {
try {
result.success(mapOf("position" to flutterView!!.cameraPosition))
} catch (e: Exception) {
result.error("failed_to_get_camera_position", e.message, null)
}
}
"setCameraPosition" -> {
val cameraPosition = try {
((call.arguments as Map<*, *>)["position"] as String)
} catch (e: Exception) {
result.error("invalid_parameter", "Invalid camera position", e)
return
}
try {
flutterView!!.setCameraPosition(cameraPosition,
{ result.success(null) },
{
result.error(
"failed_to_set_camera_position",
it.message,
null
)
})
} catch (e: Exception) {
result.error("failed_to_set_camera_position", e.message, null)
}
}
"getBackCameras" -> {
try {
result.success(getBackCameras())
} catch (e: Exception) {
result.error("failed_to_get_back_cameras", e.message, null)
}
}
"setCameraId" -> {
val cameraId = try {
((call.arguments as Map<*, *>)["cameraId"] as String)
} catch (e: Exception) {
result.error("invalid_parameter", "Invalid cameraId", e)
return
}
try {
flutterView!!.setCameraId(cameraId,
{ result.success(null) },
{
result.error(
"failed_to_set_camera_id",
it.message,
null
)
})
} catch (e: Exception) {
result.error("failed_to_set_camera_id", e.message, null)
}
}
"getIsMuted" -> {
try {
result.success(mapOf("isMuted" to flutterView!!.isMuted))
} catch (e: Exception) {
result.error("failed_to_get_is_muted", e.message, null)
}
}
"setIsMuted" -> {
val isMuted = try {
((call.arguments as Map<*, *>)["isMuted"] as Boolean)
} catch (e: Exception) {
result.error("invalid_parameter", "Invalid isMuted", e)
return
}
try {
flutterView!!.isMuted = isMuted
result.success(null)
} catch (e: Exception) {
result.error("failed_to_set_is_muted", e.message, null)
}
}
"getVideoSize" -> {
try {
val videoSize = flutterView!!.videoConfig.resolution
result.success(
mapOf(
"width" to videoSize.width.toDouble(),
"height" to videoSize.height.toDouble()
)
)
} catch (e: Exception) {
result.error("failed_to_get_video_size", e.message, null)
}
}
else -> result.notImplemented()
}
}
private fun sendEvent(type: String) {
Handler(Looper.getMainLooper()).post {
eventSink?.success(mapOf("type" to type))
}
}
private fun sendConnected() {
sendEvent("connected")
}
private fun sendDisconnected() {
sendEvent("disconnected")
}
private fun sendConnectionFailed(message: String) {
Handler(Looper.getMainLooper()).post {
eventSink?.success(mapOf("type" to "connectionFailed", "message" to message))
}
}
private fun sendError(error: Exception) {
Handler(Looper.getMainLooper()).post {
eventSink?.error(error::class.java.name, error.message, error)
}
}
private fun sendVideoSizeChanged(resolution: Size) {
Handler(Looper.getMainLooper()).post {
eventSink?.success(
mapOf(
"type" to "videoSizeChanged",
"width" to resolution.width.toDouble(),
"height" to resolution.height.toDouble() // Dart size fields are in double
)
)
}
}
private fun getBackCameras(): List<Map<String, Any>> {
val manager = context.getSystemService(Context.CAMERA_SERVICE) as CameraManager
return manager.cameraIdList.mapNotNull { cameraId ->
val characteristics = manager.getCameraCharacteristics(cameraId)
val facing = characteristics.get(CameraCharacteristics.LENS_FACING)
if (facing != CameraCharacteristics.LENS_FACING_BACK) {
return@mapNotNull null
}
val focalLengths =
characteristics.get(CameraCharacteristics.LENS_INFO_AVAILABLE_FOCAL_LENGTHS)
?: return@mapNotNull null
val sensorSize =
characteristics.get(CameraCharacteristics.SENSOR_INFO_PHYSICAL_SIZE)
?: return@mapNotNull null
val minFocalLength = focalLengths.minOrNull() ?: return@mapNotNull null
val horizontalFov =
2.0 * atan((sensorSize.width / (2.0f * minFocalLength)).toDouble())
mapOf(
"cameraId" to cameraId,
"minFocalLength" to minFocalLength.toDouble(),
"sensorWidth" to sensorSize.width.toDouble(),
"sensorHeight" to sensorSize.height.toDouble(),
"horizontalFov" to horizontalFov,
)
}
}
companion object {
private const val METHOD_CHANNEL_NAME = "video.api.livestream/controller"
private const val EVENT_CHANNEL_NAME = "video.api.livestream/events"
}
}
@@ -0,0 +1,164 @@
package video.api.flutter.livestream
import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import io.flutter.plugin.common.PluginRegistry
/**
* Check if the app has the given permissions.
* For a single permission or multiple permissions.
*/
class PermissionsManager(
private val context: Context,
) : PluginRegistry.RequestPermissionsResultListener {
private var uniqueRequestCode = 1
// To request permission, we need the activity
var activity: Activity? = null
private val listeners = mutableMapOf<Int, IListener>()
private fun hasPermission(permission: String) =
ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED
private fun hasAllPermissions(permissions: List<String>) = permissions.all { permission ->
ContextCompat.checkSelfPermission(
context,
permission
) == PackageManager.PERMISSION_GRANTED
}
private fun shouldShowRequestPermissionRationale(
activity: Activity,
permissions: List<String>
) =
permissions.filter { permission ->
ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)
}
fun requestPermissions(
permissions: List<String>,
onAllGranted: () -> Unit,
onShowPermissionRationale: (List<String>, () -> Unit) -> Unit,
onAtLeastOnePermissionDenied: () -> Unit
) {
activity?.let {
requestPermissions(it, permissions, object : IListener {
override fun onAllGranted() {
onAllGranted()
}
override fun onShowPermissionRationale(
permissions: List<String>,
onRequiredPermissionLastTime: () -> Unit
) {
onShowPermissionRationale(permissions, onRequiredPermissionLastTime)
}
override fun onAtLeastOnePermissionDenied() {
onAtLeastOnePermissionDenied()
}
})
} ?: throw IllegalStateException("Missing Activity")
}
private fun requestPermissions(
activity: Activity,
permissions: List<String>,
listener: IListener
) {
val currentRequestCode = synchronized(this) {
uniqueRequestCode++
}
listeners[currentRequestCode] = listener
when {
hasAllPermissions(permissions) -> listener.onAllGranted()
shouldShowRequestPermissionRationale(activity, permissions).isNotEmpty() -> {
val missingPermissions = shouldShowRequestPermissionRationale(activity, permissions)
listener.onShowPermissionRationale(missingPermissions) {
ActivityCompat.requestPermissions(
activity,
missingPermissions.toTypedArray(),
currentRequestCode
)
}
}
else -> ActivityCompat.requestPermissions(
activity,
permissions.toTypedArray(),
currentRequestCode
)
}
}
fun requestPermission(
permission: String,
onGranted: () -> Unit,
onShowPermissionRationale: (() -> Unit) -> Unit,
onDenied: () -> Unit
) {
activity?.let {
requestPermissions(it, listOf(permission), object : IListener {
override fun onAllGranted() {
onGranted()
}
override fun onShowPermissionRationale(
permissions: List<String>,
onRequiredPermissionLastTime: () -> Unit
) {
onShowPermissionRationale(onRequiredPermissionLastTime)
}
override fun onAtLeastOnePermissionDenied() {
onDenied()
}
})
} ?: throw IllegalStateException("Missing Activity")
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
): Boolean {
val listener = listeners[requestCode] ?: return false
listeners.remove(requestCode)
if (grantResults.isEmpty()) {
return false
}
grantResults.forEach {
if (it == PackageManager.PERMISSION_GRANTED) {
listener.onGranted(permissions[grantResults.indexOf(it)])
} else {
listener.onDenied(permissions[grantResults.indexOf(it)])
}
}
if (grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {
listener.onAllGranted()
} else {
listener.onAtLeastOnePermissionDenied()
}
return listeners.isEmpty()
}
interface IListener {
fun onAllGranted() {}
fun onGranted(permission: String) {}
fun onShowPermissionRationale(
permissions: List<String>,
onRequiredPermissionLastTime: () -> Unit
) {
}
fun onDenied(permission: String) {}
fun onAtLeastOnePermissionDenied() {}
}
}
@@ -0,0 +1,41 @@
package video.api.flutter.livestream.utils
import android.content.Context
import android.content.DialogInterface
import androidx.annotation.StringRes
import androidx.appcompat.app.AlertDialog
/**
* Show a dialog with the given title and message.
*/
fun Context.showDialog(
@StringRes title: Int,
@StringRes message: Int = 0,
@StringRes
positiveButtonText: Int = android.R.string.ok,
@StringRes
negativeButtonText: Int = 0,
onPositiveButtonClick: () -> Unit = {},
onNegativeButtonClick: () -> Unit = {}
) {
AlertDialog.Builder(this)
.setTitle(title)
.setMessage(message)
.apply {
if (positiveButtonText != 0) {
setPositiveButton(positiveButtonText) { dialogInterface: DialogInterface, _: Int ->
dialogInterface.dismiss()
onPositiveButtonClick()
}
}
if (negativeButtonText != 0) {
setNegativeButton(negativeButtonText) { dialogInterface: DialogInterface, _: Int ->
dialogInterface.dismiss()
onNegativeButtonClick()
}
}
}
.show()
}
@@ -0,0 +1,52 @@
package video.api.flutter.livestream.utils
import android.util.Size
import io.github.thibaultbee.streampack.data.AudioConfig
import io.github.thibaultbee.streampack.data.VideoConfig
fun Map<String, Any>.toVideoConfig(): VideoConfig {
return VideoConfig(
startBitrate = this["bitrate"] as Int,
resolution = (this["resolution"] as String).toResolution(),
fps = this["fps"] as Int
)
}
fun Map<String, Any>.toAudioConfig(): AudioConfig {
return AudioConfig(
startBitrate = this["bitrate"] as Int,
sampleRate = this["sampleRate"] as Int,
channelConfig = AudioConfig.getChannelConfig(
if (this["channel"] == "stereo") {
2
} else {
1
}
),
enableNoiseSuppressor = this["enableNoiseSuppressor"] as Boolean,
enableEchoCanceler = this["enableEchoCanceler"] as Boolean
)
}
fun String.toResolution(): Size {
return when (this) {
"240p" -> Size(426, 240)
"360p" -> Size(640, 360)
"480p" -> Size(854, 480)
"720p" -> Size(1280, 720)
"1080p" -> Size(1920, 1080)
else -> throw IllegalArgumentException("Unknown resolution: $this")
}
}
/**
* Add a slash at the end of a [String] only if it is missing.
*
* @return the given string with a trailing slash.
*/
fun String.addTrailingSlashIfNeeded(): String {
return if (this.endsWith("/")) this else "$this/"
}
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="permission_required">Permission required</string>
<string name="record_audio_permission_required_message">You have to grant the record audio permission to stream.</string>
<string name="camera_permission_required_message">You have to grant the camera permission to stream.</string>
</resources>
@@ -0,0 +1,4 @@
#import <Flutter/Flutter.h>
@interface ApiVideoLiveStreamPlugin : NSObject<FlutterPlugin>
@end
@@ -0,0 +1,15 @@
#import "ApiVideoLiveStreamPlugin.h"
#if __has_include(<apivideo_live_stream/apivideo_live_stream-Swift.h>)
#import <apivideo_live_stream/apivideo_live_stream-Swift.h>
#else
// Support project import fallback if the generated compatibility header
// is not copied when this plugin is created as a library.
// https://forums.swift.org/t/swift-static-libraries-dont-copy-generated-objective-c-header/19816
#import "apivideo_live_stream-Swift.h"
#endif
@implementation ApiVideoLiveStreamPlugin
+ (void)registerWithRegistrar:(NSObject<FlutterPluginRegistrar>*)registrar {
[SwiftApiVideoLiveStreamPlugin registerWithRegistrar:registrar];
}
@end
@@ -0,0 +1,148 @@
import ApiVideoLiveStream
import AVFoundation
import Foundation
class FlutterLiveStreamView: NSObject {
private let previewTexture: PreviewTexture
private let liveStream: ApiVideoLiveStream
private let eventChannel: FlutterEventChannel
private var eventSink: FlutterEventSink?
init(binaryMessenger: FlutterBinaryMessenger, textureRegistry: FlutterTextureRegistry) throws {
previewTexture = PreviewTexture(registry: textureRegistry)
liveStream = try ApiVideoLiveStream(preview: previewTexture, initialAudioConfig: nil, initialVideoConfig: nil, initialCamera: nil)
eventChannel = FlutterEventChannel(name: "video.api.livestream/events", binaryMessenger: binaryMessenger)
super.init()
liveStream.delegate = self
eventChannel.setStreamHandler(self)
}
var textureId: Int64 {
previewTexture.textureId
}
private(set) var isStreaming = false
var videoConfig: VideoConfig {
get {
liveStream.videoConfig
}
set {
sendEvent(["type": "videoSizeChanged", "width": Double(newValue.resolution.width), "height": Double(newValue.resolution.height)])
liveStream.videoConfig = newValue
}
}
var audioConfig: AudioConfig {
get {
liveStream.audioConfig
}
set {
liveStream.audioConfig = newValue
}
}
var isMuted: Bool {
get {
liveStream.isMuted
}
set {
liveStream.isMuted = newValue
}
}
var cameraPosition: String {
get {
if liveStream.cameraPosition == AVCaptureDevice.Position.back {
return "back"
} else if liveStream.cameraPosition == AVCaptureDevice.Position.front {
return "front"
} else {
return "other"
}
}
set {
if newValue == "back" {
liveStream.cameraPosition = AVCaptureDevice.Position.back
} else if newValue == "front" {
liveStream.cameraPosition = AVCaptureDevice.Position.front
}
}
}
func dispose() {
liveStream.stopStreaming()
liveStream.stopPreview()
previewTexture.dispose()
}
func startPreview() {
liveStream.startPreview()
}
func stopPreview() {
liveStream.stopPreview()
}
func startStreaming(streamKey: String, url: String) throws {
try liveStream.startStreaming(streamKey: streamKey, url: url)
isStreaming = true
}
func stopStreaming() {
liveStream.stopStreaming()
isStreaming = false
}
}
extension FlutterLiveStreamView: FlutterStreamHandler {
func onListen(withArguments _: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
eventSink = events
return nil
}
func onCancel(withArguments _: Any?) -> FlutterError? {
eventSink = nil
return nil
}
private func sendEvent(_ event: [String: Any]) {
DispatchQueue.main.async {
self.eventSink?(event)
}
}
}
extension FlutterLiveStreamView: ApiVideoLiveStreamDelegate {
/// Called when the connection to the rtmp server is successful
func connectionSuccess() {
sendEvent(["type": "connected"])
}
/// Called when the connection to the rtmp server failed
func connectionFailed(_: String) {
isStreaming = false
sendEvent(["type": "connectionFailed", "message": "Failed to connect"])
}
/// Called when the connection to the rtmp server is closed
func disconnection() {
isStreaming = false
sendEvent(["type": "disconnected"])
}
/// Called if an error happened during the audio configuration
func audioError(_ error: Error) {
print("audio error: \(error)")
}
/// Called if an error happened during the video configuration
func videoError(_ error: Error) {
print("video error: \(error)")
}
}
@@ -0,0 +1,56 @@
import AVFoundation
import Foundation
import HaishinKit
class PreviewTexture: NSObject, FlutterTexture {
var videoOrientation: AVCaptureVideoOrientation = .portrait
var isCaptureVideoPreviewEnabled: Bool = false
private weak var currentStream: IOStream? {
didSet {
currentStream?.drawable = self
}
}
private var currentSampleBuffer: CMSampleBuffer?
private let registry: FlutterTextureRegistry
private(set) var textureId: Int64 = 0
public init(registry: FlutterTextureRegistry) {
self.registry = registry
super.init()
textureId = self.registry.register(self)
}
func copyPixelBuffer() -> Unmanaged<CVPixelBuffer>? {
guard let currentSampleBuffer = currentSampleBuffer,
let imageBuffer = CMSampleBufferGetImageBuffer(currentSampleBuffer)
else {
return nil
}
return Unmanaged<CVPixelBuffer>.passRetained(imageBuffer)
}
func dispose() {
registry.unregisterTexture(textureId)
}
}
extension PreviewTexture: IOStreamDrawable {
// MARK: - IOStreamDrawable
func attachStream(_ stream: IOStream?) {
if Thread.isMainThread {
currentStream = stream
} else {
DispatchQueue.main.async {
self.currentStream = stream
}
}
}
func enqueue(_ sampleBuffer: CMSampleBuffer?) {
currentSampleBuffer = sampleBuffer
registry.textureFrameAvailable(textureId)
}
}
@@ -0,0 +1,205 @@
import ApiVideoLiveStream
import AVFoundation
import Flutter
import HaishinKit
import Network
import UIKit
enum ApiVideoLiveStreamError: Error {
case invalidAVSession
}
public class SwiftApiVideoLiveStreamPlugin: NSObject, FlutterPlugin {
private let binaryMessenger: FlutterBinaryMessenger
private let channel: FlutterMethodChannel
private let registry: FlutterTextureRegistry
private var flutterView: FlutterLiveStreamView?
public static func register(with registrar: FlutterPluginRegistrar) {
let instance = SwiftApiVideoLiveStreamPlugin(registrar: registrar)
registrar.publish(instance)
}
public init(registrar: FlutterPluginRegistrar) {
binaryMessenger = registrar.messenger()
channel = FlutterMethodChannel(name: "video.api.livestream/controller", binaryMessenger: binaryMessenger)
registry = registrar.textures()
super.init()
registrar.addMethodCallDelegate(self, channel: channel)
}
public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
switch call.method {
case "create":
flutterView?.dispose()
do {
flutterView = try FlutterLiveStreamView(binaryMessenger: binaryMessenger, textureRegistry: registry)
if let previewTexture = flutterView?.textureId {
result(["textureId": previewTexture])
} else {
result(FlutterError(code: "failed_to_create_live_stream", message: "Failed to create camera preview surface", details: nil))
}
} catch {
result(FlutterError(code: "failed_to_create_live_stream", message: error.localizedDescription, details: nil))
}
case "dispose":
flutterView?.dispose()
case "setVideoConfig":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
guard let videoParameters = call.arguments as? [String: Any] else {
result(FlutterError(code: "invalid_parameter", message: "Invalid video config", details: nil))
return
}
applyVideoConfig(config: videoParameters, flutterView: flutterView, result: result)
case "setAudioConfig":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
guard let audioParameters = call.arguments as? [String: Any] else {
result(FlutterError(code: "invalid_parameter", message: "Invalid audio config", details: nil))
return
}
applyAudioConfig(config: audioParameters, flutterView: flutterView, result: result)
case "startPreview":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
flutterView.startPreview()
result(nil)
case "stopPreview":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
flutterView.stopPreview()
result(nil)
case "startStreaming":
if let args = call.arguments as? [String: Any] {
let streamKey = args["streamKey"] as? String
let url = args["url"] as? String
if streamKey == nil {
result(FlutterError(code: "missing_stream_key", message: "Stream key is missing", details: nil))
} else if url == nil {
result(FlutterError(code: "missing_rtmp_url", message: "RTMP URL is missing", details: nil))
} else {
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
do {
try flutterView.startStreaming(streamKey: streamKey!, url: url!)
result(nil)
} catch {
result(FlutterError(code: "missing_live_stream", message: error.localizedDescription, details: nil))
}
}
}
case "stopStreaming":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
flutterView.stopStreaming()
result(nil)
case "getIsStreaming":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
result(["isStreaming": flutterView.isStreaming])
case "getCameraPosition":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
result(["position": flutterView.cameraPosition])
case "setCameraPosition":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
guard let args = call.arguments as? [String: Any],
let cameraPosition = args["position"] as? String
else {
result(FlutterError(code: "invalid_parameter", message: "Invalid camera position", details: nil))
return
}
flutterView.cameraPosition = cameraPosition
result(nil)
case "getIsMuted":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
result(["isMuted": flutterView.isMuted])
case "setIsMuted":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
guard let args = call.arguments as? [String: Any],
let isMuted = args["isMuted"] as? Bool
else {
result(FlutterError(code: "invalid_parameter", message: "Invalid isMuted", details: nil))
return
}
flutterView.isMuted = isMuted
result(nil)
case "getVideoSize":
guard let flutterView = flutterView else {
result(FlutterError(code: "missing_live_stream", message: "Live stream must exist at this point", details: nil))
return
}
result(["width": flutterView.videoConfig.resolution.width, "height": flutterView.videoConfig.resolution.height])
default:
result(FlutterMethodNotImplemented)
}
}
private func applyVideoConfig(config: Dictionary<String, Any>, flutterView: FlutterLiveStreamView, result: @escaping FlutterResult) {
let resolutionString = config["resolution"] as! String?
guard let resolutionString else {
result(FlutterError(code: "missing_parameter", message: "Resolution is missing", details: nil))
return
}
let resolution = resolutionString.toResolution()
guard let resolution else {
result(FlutterError(code: "invalid_parameter", message: "Invalid resolution \(resolutionString)", details: nil))
return
}
flutterView.videoConfig = VideoConfig(bitrate: config["bitrate"] as! Int,
resolution: resolution.rawValue,
fps: config["fps"] as! Float64)
result(nil)
}
private func applyAudioConfig(config: Dictionary<String, Any>, flutterView: FlutterLiveStreamView, result: @escaping FlutterResult) {
flutterView.audioConfig = AudioConfig(bitrate: config["bitrate"] as! Int)
result(nil)
}
}
extension String {
func toResolution() -> Resolution? {
switch self {
case "240p":
return Resolution.RESOLUTION_16_9_240P
case "360p":
return Resolution.RESOLUTION_16_9_360P
case "480p":
return Resolution.RESOLUTION_16_9_480P
case "720p":
return Resolution.RESOLUTION_16_9_720P
case "1080p":
return Resolution.RESOLUTION_16_9_1080P
default:
return nil
}
}
}
@@ -0,0 +1,24 @@
#
# To learn more about a Podspec see http://guides.cocoapods.org/syntax/podspec.html.
# Run `pod lib lint apivideo_live_stream.podspec` to validate before publishing.
#
Pod::Spec.new do |s|
s.name = 'apivideo_live_stream'
s.version = '0.0.1'
s.summary = 'A new flutter plugin project.'
s.description = <<-DESC
A new flutter plugin project.
DESC
s.homepage = 'http://example.com'
s.license = { :file => '../LICENSE' }
s.author = { 'Your Company' => 'email@example.com' }
s.source = { :path => '.' }
s.source_files = 'Classes/**/*'
s.dependency 'Flutter'
s.dependency 'ApiVideoLiveStream', "1.4.1"
s.platform = :ios, '12.0'
# Flutter.framework does not contain a i386 slice.
s.pod_target_xcconfig = { 'DEFINES_MODULE' => 'YES', 'EXCLUDED_ARCHS[sdk=iphonesimulator*]' => 'i386' }
s.swift_version = '5.0'
end
@@ -0,0 +1,4 @@
export 'src/apivideo_camera_preview.dart';
export 'src/apivideo_live_stream_controller.dart';
export 'src/apivideo_live_stream_mobile_platform.dart';
export 'src/types.dart';
@@ -0,0 +1,183 @@
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:native_device_orientation/native_device_orientation.dart';
import 'apivideo_live_stream_controller.dart';
/// Widget that displays the camera preview of [controller].
///
class ApiVideoCameraPreview extends StatefulWidget {
/// Creates a new [ApiVideoCameraPreview] instance for [controller] and a [child] overlay.
const ApiVideoCameraPreview(
{super.key,
required this.controller,
this.fit = BoxFit.contain,
this.child});
/// The controller for the camera to display the preview for.
final ApiVideoLiveStreamController controller;
/// The [BoxFit] for the video. The [child] is scale to the preview box.
final BoxFit fit;
/// A widget to overlay on top of the camera preview. It is scaled to the camera preview [FittedBox].
final Widget? child;
@override
State<ApiVideoCameraPreview> createState() => _ApiVideoCameraPreviewState();
}
class _ApiVideoCameraPreviewState extends State<ApiVideoCameraPreview> {
_ApiVideoCameraPreviewState() {
_widgetListener = ApiVideoLiveStreamWidgetListener(onTextureReady: () {
final int newTextureId = widget.controller.textureId;
if (newTextureId != _textureId) {
setState(() {
_textureId = newTextureId;
});
}
});
_eventsListener =
ApiVideoLiveStreamEventsListener(onVideoSizeChanged: (size) {
_updateAspectRatio(size);
});
}
late ApiVideoLiveStreamWidgetListener _widgetListener;
late ApiVideoLiveStreamEventsListener _eventsListener;
late int _textureId;
double _aspectRatio = 1.77;
Size _size = const Size(1280, 720);
@override
void initState() {
super.initState();
_textureId = widget.controller.textureId;
widget.controller.addWidgetListener(_widgetListener);
widget.controller.addEventsListener(_eventsListener);
if (widget.controller.isInitialized) {
widget.controller.videoSize.then((size) {
if (size != null) {
_updateAspectRatio(size);
}
});
}
}
@override
void dispose() {
widget.controller.stopPreview();
widget.controller.removeWidgetListener(_widgetListener);
widget.controller.removeEventsListener(_eventsListener);
super.dispose();
}
@override
Widget build(BuildContext context) {
return _textureId == ApiVideoLiveStreamController.kUninitializedTextureId
? Container()
: _buildPreview(context);
}
Widget _buildPreview(BuildContext context) {
return NativeDeviceOrientationReader(builder: (context) {
final orientation = NativeDeviceOrientationReader.orientation(context);
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return Stack(alignment: Alignment.center, children: [
_buildFittedPreview(constraints, orientation),
_buildFittedOverlay(constraints, orientation)
]);
});
});
}
Widget _buildFittedPreview(
BoxConstraints constraints, NativeDeviceOrientation orientation) {
final orientedSize = _size.orientate(orientation);
// See https://github.com/flutter/flutter/issues/17287
return SizedBox(
width: constraints.maxWidth,
height: constraints.maxHeight,
child: FittedBox(
fit: widget.fit,
clipBehavior: Clip.hardEdge,
child: Center(
child: SizedBox(
width: orientedSize.width,
height: orientedSize.height,
child: _wrapInRotatedBox(
orientation: orientation,
child: widget.controller.buildPreview())))));
}
Widget _buildFittedOverlay(
BoxConstraints constraints, NativeDeviceOrientation orientation) {
final orientedSize = _size.orientate(orientation);
final fittedSize =
applyBoxFit(widget.fit, orientedSize, constraints.biggest);
return SizedBox(
width: fittedSize.destination.width,
height: fittedSize.destination.height,
child: widget.child ?? Container());
}
Widget _wrapInRotatedBox(
{required NativeDeviceOrientation orientation, required Widget child}) {
if (defaultTargetPlatform != TargetPlatform.android) {
return child;
}
return RotatedBox(
quarterTurns: orientation.getQuarterTurns(),
child: child,
);
}
void _updateAspectRatio(Size newSize) async {
final double newAspectRatio = newSize.aspectRatio;
if ((newAspectRatio != _aspectRatio) || (newSize != _size)) {
if (mounted) {
setState(() {
_size = newSize;
_aspectRatio = newAspectRatio;
});
}
}
}
}
extension OrientationHelper on NativeDeviceOrientation {
/// Returns true if the orientation is portrait.
bool isLandscape() {
return [
NativeDeviceOrientation.landscapeLeft,
NativeDeviceOrientation.landscapeRight
].contains(this);
}
/// Returns the number of clockwise quarter turns the orientation is rotated
int getQuarterTurns() {
Map<NativeDeviceOrientation, int> turns = {
NativeDeviceOrientation.unknown: 0,
NativeDeviceOrientation.portraitUp: 0,
NativeDeviceOrientation.landscapeRight: 1,
NativeDeviceOrientation.portraitDown: 2,
NativeDeviceOrientation.landscapeLeft: 3,
};
return turns[this]!;
}
}
extension OrientedSize on Size {
/// Returns the size with width and height swapped if [orientation] is portrait.
Size orientate(NativeDeviceOrientation orientation) {
if (orientation.isLandscape()) {
return Size(width, height);
} else {
return Size(height, width);
}
}
}
@@ -0,0 +1,335 @@
import 'dart:async';
import 'package:apivideo_live_stream/apivideo_live_stream.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:meta/meta.dart';
import 'apivideo_live_stream_platform_interface.dart';
import 'types.dart';
ApiVideoLiveStreamPlatform get _platform {
return ApiVideoLiveStreamPlatform.instance;
}
/// Controller of the live streaming
class ApiVideoLiveStreamController {
final VideoConfig _initialVideoConfig;
final AudioConfig _initialAudioConfig;
final CameraPosition _initialCameraPosition;
static const int kUninitializedTextureId = -1;
int _textureId = kUninitializedTextureId;
/// This is just exposed for testing. Do not use it.
@internal
int get textureId => _textureId;
bool _isInitialized = false;
/// Gets the current state of the video player.
bool get isInitialized => _isInitialized;
/// Events
StreamSubscription<dynamic>? _eventSubscription;
List<ApiVideoLiveStreamEventsListener> _eventsListeners = [];
List<ApiVideoLiveStreamWidgetListener> _widgetListeners = [];
/// Creates a new [ApiVideoLiveStreamController] instance.
ApiVideoLiveStreamController(
{required AudioConfig initialAudioConfig,
required VideoConfig initialVideoConfig,
CameraPosition initialCameraPosition = CameraPosition.back,
VoidCallback? onConnectionSuccess,
Function(String)? onConnectionFailed,
VoidCallback? onDisconnection,
Function(Exception)? onError})
: _initialVideoConfig = initialVideoConfig,
_initialAudioConfig = initialAudioConfig,
_initialCameraPosition = initialCameraPosition {
_eventsListeners.add(ApiVideoLiveStreamEventsListener(
onConnectionSuccess: onConnectionSuccess,
onConnectionFailed: onConnectionFailed,
onDisconnection: onDisconnection,
onError: onError));
}
ApiVideoLiveStreamController.fromListener(
{required AudioConfig initialAudioConfig,
required VideoConfig initialVideoConfig,
CameraPosition initialCameraPosition = CameraPosition.back,
ApiVideoLiveStreamEventsListener? listener})
: _initialVideoConfig = initialVideoConfig,
_initialAudioConfig = initialAudioConfig,
_initialCameraPosition = initialCameraPosition {
if (listener != null) {
_eventsListeners.add(listener);
}
}
/// Creates a new live stream instance with initial audio and video configurations.
Future<void> initialize() async {
_textureId = await _platform.initialize() ?? kUninitializedTextureId;
_eventSubscription = _platform
.liveStreamingEventsFor(_textureId)
.listen(_eventListener, onError: _errorListener);
for (var listener in [..._widgetListeners]) {
if (listener.onTextureReady != null) {
listener.onTextureReady!();
}
}
await setCameraPosition(_initialCameraPosition);
await setVideoConfig(_initialVideoConfig);
await setAudioConfig(_initialAudioConfig);
await startPreview();
_isInitialized = true;
return;
}
/// Disposes the live stream instance.
Future<void> dispose() async {
await _eventSubscription?.cancel();
_eventsListeners.clear();
_widgetListeners.clear();
await _platform.dispose();
return;
}
/// Sets new video parameters.
///
/// Do not call when in live or when preview is running.
Future<void> setVideoConfig(VideoConfig videoConfig) {
return _platform.setVideoConfig(videoConfig);
}
/// Sets new audio parameters.
///
/// Do not call when in live or when preview is running.
Future<void> setAudioConfig(AudioConfig audioConfig) {
return _platform.setAudioConfig(audioConfig);
}
/// Starts the live stream to the specified "[url]/[streamKey]".
Future<void> startStreaming(
{required String streamKey,
String url = "rtmp://broadcast.api.video/s/"}) async {
return _platform.startStreaming(streamKey: streamKey, url: url);
}
/// Stops the live stream.
Future<void> stopStreaming() {
return _platform.stopStreaming();
}
/// Starts the camera preview.
///
/// The purpose of this method is to be called when application is sent
/// to foreground.
Future<void> startPreview() {
return _platform.startPreview();
}
/// Stops the camera preview.
///
/// The purpose of this method is to be called when application is sent
/// to background.
Future<void> stopPreview() {
return _platform.stopPreview();
}
/// Same as [stopStreaming] and [stopPreview]
Future<void> stop() async {
await stopStreaming();
await stopPreview();
}
/// Gets if live stream is streaming or not.
Future<bool> get isStreaming {
return _platform.getIsStreaming();
}
/// Changes current back/front camera to front/back camera
Future<void> switchCamera() async {
final cameraPosition = await this.cameraPosition;
if (cameraPosition == CameraPosition.back) {
return setCameraPosition(CameraPosition.front);
} else {
return setCameraPosition(CameraPosition.back);
}
}
/// Gets the current camera position
Future<CameraPosition> get cameraPosition {
return _platform.getCameraPosition();
}
/// Sets the current camera position
Future<void> setCameraPosition(CameraPosition position) {
return _platform.setCameraPosition(position);
}
/// Lists back cameras exposed by Android CameraManager.
Future<List<ApiVideoBackCamera>> getBackCameras() async {
final cameras = await _platform.getBackCameras();
return cameras
.map(ApiVideoBackCamera.fromJson)
.where((camera) => camera.cameraId.isNotEmpty)
.toList(growable: false);
}
/// Selects a concrete camera id. Android-only extension.
Future<void> setCameraId(String cameraId) {
return _platform.setCameraId(cameraId);
}
/// Toggle mutes/unmutes from the microphone. See [isMuted] and [setIsMuted].
Future<void> toggleMute() async {
final isMuted = await this.isMuted;
await setIsMuted(!isMuted);
}
/// Gets if live stream is muted or not.
Future<bool> get isMuted {
return _platform.getIsMuted();
}
/// Mutes/unmutes the microphone.
Future<void> setIsMuted(bool isMuted) {
return _platform.setIsMuted(isMuted);
}
Future<Size?> get videoSize {
return _platform.getVideoSize();
}
/// Builds the preview widget.
@internal
Widget buildPreview() {
return Texture(textureId: textureId);
}
void addEventsListener(ApiVideoLiveStreamEventsListener listener) {
_eventsListeners.add(listener);
}
void removeEventsListener(ApiVideoLiveStreamEventsListener listener) {
_eventsListeners.remove(listener);
}
/// This is exposed for internal use only. Do not use it.
@internal
void addWidgetListener(ApiVideoLiveStreamWidgetListener listener) {
_widgetListeners.add(listener);
}
/// This is exposed for internal use only. Do not use it.
@internal
void removeWidgetListener(ApiVideoLiveStreamWidgetListener listener) {
_widgetListeners.remove(listener);
}
void _errorListener(Object obj) {
final PlatformException e = obj as PlatformException;
for (var listener in [..._eventsListeners]) {
if (listener.onError != null) {
listener.onError!(e);
}
}
}
void _eventListener(LiveStreamingEvent event) {
switch (event.type) {
case LiveStreamingEventType.connected:
for (var listener in [..._eventsListeners]) {
if (listener.onConnectionSuccess != null) {
listener.onConnectionSuccess!();
}
}
break;
case LiveStreamingEventType.disconnected:
for (var listener in [..._eventsListeners]) {
if (listener.onDisconnection != null) {
listener.onDisconnection!();
}
}
break;
case LiveStreamingEventType.connectionFailed:
for (var listener in [..._eventsListeners]) {
if (listener.onConnectionFailed != null) {
listener.onConnectionFailed!(event.data as String);
}
}
break;
case LiveStreamingEventType.videoSizeChanged:
for (var listener in [..._eventsListeners]) {
if (listener.onVideoSizeChanged != null) {
listener.onVideoSizeChanged!(event.data as Size);
}
}
break;
case LiveStreamingEventType.unknown:
// Nothing to do
break;
}
}
}
class ApiVideoBackCamera {
const ApiVideoBackCamera({
required this.cameraId,
required this.minFocalLength,
required this.sensorWidth,
required this.sensorHeight,
required this.horizontalFov,
});
final String cameraId;
final double minFocalLength;
final double sensorWidth;
final double sensorHeight;
final double horizontalFov;
factory ApiVideoBackCamera.fromJson(Map<String, dynamic> json) {
return ApiVideoBackCamera(
cameraId: json['cameraId'] as String? ?? '',
minFocalLength: (json['minFocalLength'] as num?)?.toDouble() ?? 0,
sensorWidth: (json['sensorWidth'] as num?)?.toDouble() ?? 0,
sensorHeight: (json['sensorHeight'] as num?)?.toDouble() ?? 0,
horizontalFov: (json['horizontalFov'] as num?)?.toDouble() ?? 0,
);
}
}
class ApiVideoLiveStreamEventsListener {
/// Gets notified when the connection is successful
final VoidCallback? onConnectionSuccess;
/// Gets notified when the connection failed
final Function(String)? onConnectionFailed;
/// Gets notified when the device has been disconnected
final VoidCallback? onDisconnection;
/// Gets notified when the video size has changed. Mostly designed to update Widget aspect ratio.
final Function(Size)? onVideoSizeChanged;
/// Gets notified when an error occurs
final Function(Exception)? onError;
ApiVideoLiveStreamEventsListener(
{this.onConnectionSuccess,
this.onConnectionFailed,
this.onDisconnection,
this.onVideoSizeChanged,
this.onError});
}
class ApiVideoLiveStreamWidgetListener {
final VoidCallback? onTextureReady;
ApiVideoLiveStreamWidgetListener({this.onTextureReady});
}
@@ -0,0 +1,155 @@
import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'apivideo_live_stream_platform_interface.dart';
import 'types.dart';
/// Controller of the live streaming
class ApiVideoMobileLiveStreamPlatform extends ApiVideoLiveStreamPlatform {
final MethodChannel _channel =
const MethodChannel('video.api.livestream/controller');
/// Registers this class as the default instance of [PathProviderPlatform].
static void registerWith() {
ApiVideoLiveStreamPlatform.instance = ApiVideoMobileLiveStreamPlatform();
}
@override
Future<int?> initialize() async {
final Map<String, dynamic>? reply =
await _channel.invokeMapMethod<String, dynamic>('create');
return reply!['textureId']! as int;
}
@override
Future<void> dispose() {
return _channel.invokeMapMethod<String, dynamic>('dispose');
}
@override
Future<void> setVideoConfig(VideoConfig videoConfig) {
return _channel.invokeMethod('setVideoConfig', videoConfig.toJson());
}
@override
Future<void> setAudioConfig(AudioConfig audioConfig) {
return _channel.invokeMethod('setAudioConfig', audioConfig.toJson());
}
@override
Future<void> startStreaming(
{required String streamKey, required String url}) {
return _channel.invokeMethod('startStreaming', <String, dynamic>{
'streamKey': streamKey,
'url': url,
});
}
@override
Future<void> stopStreaming() {
return _channel.invokeMethod('stopStreaming');
}
@override
Future<void> startPreview() {
return _channel.invokeMethod('startPreview');
}
@override
Future<void> stopPreview() {
return _channel.invokeMethod('stopPreview');
}
@override
Future<bool> getIsStreaming() async {
final Map<dynamic, dynamic> reply =
await _channel.invokeMethod('getIsStreaming') as Map;
return reply['isStreaming'] as bool;
}
@override
Future<void> setCameraPosition(CameraPosition cameraPosition) {
return _channel.invokeMethod('setCameraPosition',
<String, dynamic>{'position': cameraPosition.toJson()});
}
@override
Future<List<Map<String, dynamic>>> getBackCameras() async {
final List<dynamic> reply =
await _channel.invokeMethod('getBackCameras') as List<dynamic>;
return reply
.whereType<Map<dynamic, dynamic>>()
.map((item) => Map<String, dynamic>.from(item))
.toList(growable: false);
}
@override
Future<void> setCameraId(String cameraId) {
return _channel.invokeMethod(
'setCameraId',
<String, dynamic>{'cameraId': cameraId},
);
}
@override
Future<CameraPosition> getCameraPosition() async {
final Map<dynamic, dynamic> reply =
await _channel.invokeMethod('getCameraPosition') as Map;
return CameraPosition.fromJson(reply['position'] as String);
}
@override
Future<void> setIsMuted(bool isMuted) {
return _channel
.invokeMethod('setIsMuted', <String, dynamic>{'isMuted': isMuted});
}
@override
Future<bool> getIsMuted() async {
final Map<dynamic, dynamic> reply =
await _channel.invokeMethod('getIsMuted') as Map;
return reply['isMuted'] as bool;
}
@override
Future<Size?> getVideoSize() async {
final Map<dynamic, dynamic> reply =
await _channel.invokeMethod('getVideoSize') as Map;
if (reply.containsKey("width") && reply.containsKey("height")) {
return Size(reply["width"] as double, reply["height"] as double);
} else {
return null;
}
}
/// Builds the preview widget.
@override
Widget buildPreview(int textureId) {
return Texture(textureId: textureId);
}
@override
Stream<LiveStreamingEvent> liveStreamingEventsFor(int textureId) {
return EventChannel('video.api.livestream/events')
.receiveBroadcastStream()
.map((dynamic map) {
final Map<dynamic, dynamic> event = map as Map<dynamic, dynamic>;
switch (event['type']) {
case 'connected':
return LiveStreamingEvent(type: LiveStreamingEventType.connected);
case 'disconnected':
return LiveStreamingEvent(type: LiveStreamingEventType.disconnected);
case 'connectionFailed':
return LiveStreamingEvent(
type: LiveStreamingEventType.connectionFailed,
data: event['message']);
case 'videoSizeChanged':
return LiveStreamingEvent(
type: LiveStreamingEventType.videoSizeChanged,
data: Size(event['width'] as double, event['height'] as double));
default:
return LiveStreamingEvent(type: LiveStreamingEventType.unknown);
}
});
}
}
@@ -0,0 +1,132 @@
import 'package:flutter/widgets.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';
import 'types.dart';
abstract class ApiVideoLiveStreamPlatform extends PlatformInterface {
/// Constructs a ApiVideoPlayerPlatform.
ApiVideoLiveStreamPlatform() : super(token: _token);
static final Object _token = Object();
static ApiVideoLiveStreamPlatform _instance = _PlatformImplementation();
/// The default instance of [ApiVideoLiveStreamPlatform] to use.
///
/// Defaults to [_PlatformImplementation].
static ApiVideoLiveStreamPlatform get instance => _instance;
/// Platform-specific implementations should set this with their own
/// platform-specific class that extends [ApiVideoLiveStreamPlatform] when
/// they register themselves.
static set instance(ApiVideoLiveStreamPlatform instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
/// Creates a new live stream instance
Future<int?> initialize() {
throw UnimplementedError('initialize() has not been implemented.');
}
/// Disposes the live stream instance
Future<void> dispose() {
throw UnimplementedError('dispose() has not been implemented.');
}
Future<void> setVideoConfig(VideoConfig videoConfig) {
throw UnimplementedError('setVideoConfig() has not been implemented.');
}
Future<void> setAudioConfig(AudioConfig audioConfig) {
throw UnimplementedError('setAudioConfig() has not been implemented.');
}
Future<void> startStreaming(
{required String streamKey, required String url}) {
throw UnimplementedError('startStreaming() has not been implemented.');
}
Future<void> stopStreaming() {
throw UnimplementedError('stopStreaming() has not been implemented.');
}
Future<void> startPreview() {
throw UnimplementedError('startPreview() has not been implemented.');
}
Future<void> stopPreview() {
throw UnimplementedError('stopPreview() has not been implemented.');
}
Future<bool> getIsStreaming() {
throw UnimplementedError('getIsStreaming() has not been implemented.');
}
Future<CameraPosition> getCameraPosition() {
throw UnimplementedError('getCameraPosition() has not been implemented.');
}
Future<void> setCameraPosition(CameraPosition cameraPosition) {
throw UnimplementedError('setCameraPosition() has not been implemented.');
}
Future<List<Map<String, dynamic>>> getBackCameras() {
throw UnimplementedError('getBackCameras() has not been implemented.');
}
Future<void> setCameraId(String cameraId) {
throw UnimplementedError('setCameraId() has not been implemented.');
}
Future<bool> getIsMuted() {
throw UnimplementedError('getIsMuted() has not been implemented.');
}
Future<void> setIsMuted(bool isMuted) {
throw UnimplementedError('setIsMuted() has not been implemented.');
}
Future<Size?> getVideoSize() {
throw UnimplementedError('getVideoSize() has not been implemented.');
}
/// Returns a Stream of [LiveStreamingEvent]s.
Stream<LiveStreamingEvent> liveStreamingEventsFor(int textureId) {
throw UnimplementedError(
'liveStreamingEventsFor() has not been implemented.');
}
Widget buildPreview(int textureId) {
throw UnimplementedError('buildPreview() has not been implemented.');
}
}
class _PlatformImplementation extends ApiVideoLiveStreamPlatform {}
class LiveStreamingEvent {
/// Adds optional parameters here if needed
final Object? data;
/// The [LiveStreamingEventType]
final LiveStreamingEventType type;
LiveStreamingEvent({required this.type, this.data});
}
enum LiveStreamingEventType {
/// The live streaming is connected.
connected,
/// The live streaming has just been disconnected.
disconnected,
/// The connection to the server failed.
connectionFailed,
/// The video size has changed.
videoSizeChanged,
/// Unknown event
unknown
}
@@ -0,0 +1,6 @@
export 'types/audio_config.dart';
export 'types/camera_position.dart';
export 'types/channel.dart';
export 'types/resolution.dart';
export 'types/sample_rate.dart';
export 'types/video_config.dart';
@@ -0,0 +1,48 @@
import 'package:json_annotation/json_annotation.dart';
import 'channel.dart';
import 'sample_rate.dart';
part 'audio_config.g.dart';
/// Live streaming audio configuration.
@JsonSerializable()
class AudioConfig {
/// The video bitrate in bps
int bitrate;
/// The number of audio channels
/// Only available on Android
Channel channel;
/// The sample rate of the audio capture
/// Only available on Android
SampleRate sampleRate;
/// Enable the echo cancellation
/// Only available on Android
bool enableEchoCanceler;
/// Enable the noise suppressor
/// Only available on Android
bool enableNoiseSuppressor;
/// Creates a new [AudioConfig] instance.
///
/// [sampleRate] is only supported on Android.
/// [channel] is only supported on Android.
AudioConfig(
{this.bitrate = 128000,
this.channel = Channel.stereo,
this.sampleRate = SampleRate.kHz_44_1,
this.enableEchoCanceler = true,
this.enableNoiseSuppressor = true})
: assert(bitrate > 0);
/// Creates a [AudioConfig] from a [json] map.
factory AudioConfig.fromJson(Map<String, dynamic> json) =>
_$AudioConfigFromJson(json);
/// Creates a json map from a [AudioConfig].
Map<String, dynamic> toJson() => _$AudioConfigToJson(this);
}
@@ -0,0 +1,38 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'audio_config.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
AudioConfig _$AudioConfigFromJson(Map<String, dynamic> json) => AudioConfig(
bitrate: json['bitrate'] as int? ?? 128000,
channel: $enumDecodeNullable(_$ChannelEnumMap, json['channel']) ??
Channel.stereo,
sampleRate:
$enumDecodeNullable(_$SampleRateEnumMap, json['sampleRate']) ??
SampleRate.kHz_44_1,
enableEchoCanceler: json['enableEchoCanceler'] as bool? ?? true,
enableNoiseSuppressor: json['enableNoiseSuppressor'] as bool? ?? true,
);
Map<String, dynamic> _$AudioConfigToJson(AudioConfig instance) =>
<String, dynamic>{
'bitrate': instance.bitrate,
'channel': _$ChannelEnumMap[instance.channel]!,
'sampleRate': _$SampleRateEnumMap[instance.sampleRate]!,
'enableEchoCanceler': instance.enableEchoCanceler,
'enableNoiseSuppressor': instance.enableNoiseSuppressor,
};
const _$ChannelEnumMap = {
Channel.stereo: 'stereo',
Channel.mono: 'mono',
};
const _$SampleRateEnumMap = {
SampleRate.kHz_11: 11025,
SampleRate.kHz_22: 22050,
SampleRate.kHz_44_1: 44100,
};
@@ -0,0 +1,15 @@
/// Camera facing direction
enum CameraPosition {
/// Front camera
front,
/// Back camera
back,
/// Other camera (external for example)
other;
String toJson() => name;
static CameraPosition fromJson(String json) => values.byName(json);
}
@@ -0,0 +1,12 @@
import 'package:json_annotation/json_annotation.dart';
/// Audio channel
enum Channel {
/// Stereo (2 channels)
@JsonValue("stereo")
stereo,
/// Mono (1 channel)
@JsonValue("mono")
mono,
}
@@ -0,0 +1,31 @@
import 'dart:ui';
import 'package:json_annotation/json_annotation.dart';
/// Enumeration for camera resolution
/// Only 16/9 resolutions are supported.
enum Resolution {
/// 426x240
@JsonValue("240p")
RESOLUTION_240(size: Size(426, 240)),
/// 640x360
@JsonValue("360p")
RESOLUTION_360(size: Size(640, 360)),
/// 854x480
@JsonValue("480p")
RESOLUTION_480(size: Size(854, 480)),
/// 1280x720
@JsonValue("720p")
RESOLUTION_720(size: Size(1280, 720)),
/// 1920x1080
@JsonValue("1080p")
RESOLUTION_1080(size: Size(1920, 1080));
const Resolution({required this.size});
final Size size;
}
@@ -0,0 +1,18 @@
import 'package:json_annotation/json_annotation.dart';
/// Enumeration for supported RTMP sample rate
@JsonEnum(valueField: 'value')
enum SampleRate {
/// 11025 Hz
kHz_11(value: 11025),
/// 22050 Hz
kHz_22(value: 22050),
/// 44100 Hz
kHz_44_1(value: 44100);
const SampleRate({required this.value});
final int value;
}
@@ -0,0 +1,55 @@
import 'package:json_annotation/json_annotation.dart';
import 'resolution.dart';
part 'video_config.g.dart';
/// Live streaming video configuration.
@JsonSerializable()
class VideoConfig {
/// The video bitrate in bps
int bitrate;
/// The live streaming video resolution
Resolution resolution;
/// The video frame rate in fps
int fps;
/// Creates a [VideoConfig] instance
VideoConfig(
{required this.bitrate,
this.resolution = Resolution.RESOLUTION_720,
this.fps = 30})
: assert(bitrate > 0),
assert(fps > 0);
/// Creates a [VideoConfig] instance where bitrate is set according to the given [resolution].
VideoConfig.withDefaultBitrate(
{this.resolution = Resolution.RESOLUTION_720, this.fps = 30})
: assert(fps > 0),
bitrate = _getDefaultBitrate(resolution);
/// Creates a [VideoConfig] from a [json] map.
factory VideoConfig.fromJson(Map<String, dynamic> json) =>
_$VideoConfigFromJson(json);
/// Creates a json map from a [VideoConfig].
Map<String, dynamic> toJson() => _$VideoConfigToJson(this);
/// Returns the default bitrate for the given [resolution].
static int _getDefaultBitrate(Resolution resolution) {
switch (resolution) {
case Resolution.RESOLUTION_240:
return 800000;
case Resolution.RESOLUTION_360:
return 1000000;
case Resolution.RESOLUTION_480:
return 1300000;
case Resolution.RESOLUTION_720:
return 2000000;
case Resolution.RESOLUTION_1080:
return 3500000;
}
}
}
@@ -0,0 +1,30 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'video_config.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
VideoConfig _$VideoConfigFromJson(Map<String, dynamic> json) => VideoConfig(
bitrate: json['bitrate'] as int,
resolution:
$enumDecodeNullable(_$ResolutionEnumMap, json['resolution']) ??
Resolution.RESOLUTION_720,
fps: json['fps'] as int? ?? 30,
);
Map<String, dynamic> _$VideoConfigToJson(VideoConfig instance) =>
<String, dynamic>{
'bitrate': instance.bitrate,
'resolution': _$ResolutionEnumMap[instance.resolution]!,
'fps': instance.fps,
};
const _$ResolutionEnumMap = {
Resolution.RESOLUTION_240: '240p',
Resolution.RESOLUTION_360: '360p',
Resolution.RESOLUTION_480: '480p',
Resolution.RESOLUTION_720: '720p',
Resolution.RESOLUTION_1080: '1080p',
};
+74
View File
@@ -0,0 +1,74 @@
name: apivideo_live_stream
description: Flutter RTMP live stream client for your audio/video application. Made with ♥ by api.video.
version: 1.2.0
repository: https://github.com/apivideo/api.video-flutter-live-stream
issue_tracker: https://github.com/apivideo/api.video-flutter-live-stream/issues
homepage: https://api.video
environment:
sdk: ">=2.17.1 <4.0.0"
flutter: ">=2.5.0"
dependencies:
flutter:
sdk: flutter
json_annotation: ^4.8.1
native_device_orientation: ^1.2.1
plugin_platform_interface: ^2.1.6
meta: ^1.9.0
dev_dependencies:
flutter_test:
sdk: flutter
build_runner: ^2.4.6
json_serializable: ^6.7.1
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter.
flutter:
# This section identifies this Flutter project as a plugin project.
# The 'pluginClass' and Android 'package' identifiers should not ordinarily
# be modified. They are used by the tooling to maintain consistency when
# adding or updating assets for this project.
plugin:
platforms:
android:
dartPluginClass: ApiVideoMobileLiveStreamPlatform
package: video.api.flutter.livestream
pluginClass: ApiVideoLiveStreamPlugin
ios:
dartPluginClass: ApiVideoMobileLiveStreamPlatform
pluginClass: ApiVideoLiveStreamPlugin
# To add assets to your plugin package, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
#
# For details regarding assets in packages, see
# https://flutter.dev/assets-and-images/#from-packages
#
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/assets-and-images/#resolution-aware.
# To add custom fonts to your plugin package, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts in packages, see
# https://flutter.dev/custom-fonts/#from-packages