From 7238d6ac736a9eda47dc4664c04e65f1c127a91d Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sat, 14 Mar 2020 19:44:01 +0800 Subject: [PATCH 01/69] Changes for golang server. --- lib/src/basic_sample/loopback_sample.dart | 2 ++ lib/src/call_sample/signaling.dart | 12 ++++++++---- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/lib/src/basic_sample/loopback_sample.dart b/lib/src/basic_sample/loopback_sample.dart index 32702bd..993f080 100644 --- a/lib/src/basic_sample/loopback_sample.dart +++ b/lib/src/basic_sample/loopback_sample.dart @@ -151,6 +151,8 @@ class _MyAppState extends State { //change for loopback. description.type = 'answer'; _peerConnection.setRemoteDescription(description); + + _localStream.getAudioTracks()[0].setMicrophoneMute(false); } catch (e) { print(e.toString()); } diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 11ef011..307b9e9 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -220,7 +220,6 @@ class Signaling { break; case 'bye': { - var from = data['from']; var to = data['to']; var sessionId = data['session_id']; print('bye: ' + sessionId); @@ -259,7 +258,7 @@ class Signaling { } void connect() async { - var url = 'wss://$_host:$_port'; + var url = 'wss://$_host:$_port/ws'; _socket = SimpleWebSocket(url); print('connect to $url'); @@ -321,6 +320,7 @@ class Signaling { pc.onIceCandidate = (candidate) { _send('candidate', { 'to': id, + 'from': _selfId, 'candidate': { 'sdpMLineIndex': candidate.sdpMlineIndex, 'sdpMid': candidate.sdpMid, @@ -375,6 +375,7 @@ class Signaling { pc.setLocalDescription(s); _send('offer', { 'to': id, + 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, 'session_id': this._sessionId, 'media': media, @@ -391,6 +392,7 @@ class Signaling { pc.setLocalDescription(s); _send('answer', { 'to': id, + 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, 'session_id': this._sessionId, }); @@ -400,8 +402,10 @@ class Signaling { } _send(event, data) { - data['type'] = event; + var request = new Map(); + request["type"] = event; + request["data"] = data; JsonEncoder encoder = new JsonEncoder(); - _socket.send(encoder.convert(data)); + _socket.send(encoder.convert(request)); } } From 5c8b48566155fb6445e7323bce2974d07b12624a Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sat, 14 Mar 2020 22:41:11 +0800 Subject: [PATCH 02/69] Add getTurnCredential. --- lib/src/call_sample/signaling.dart | 40 ++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 307b9e9..a88d32c 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -1,5 +1,6 @@ import 'dart:convert'; import 'dart:async'; +import 'dart:io'; import 'package:flutter_webrtc/webrtc.dart'; import 'random_string.dart'; @@ -30,6 +31,8 @@ typedef void DataChannelMessageCallback( typedef void DataChannelCallback(RTCDataChannel dc); class Signaling { + JsonEncoder _encoder = new JsonEncoder(); + JsonDecoder _decoder = new JsonDecoder(); String _selfId = randomNumeric(6); SimpleWebSocket _socket; var _sessionId; @@ -38,6 +41,7 @@ class Signaling { var _peerConnections = new Map(); var _dataChannels = new Map(); var _remoteCandidates = []; + var _turnCredential; MediaStream _localStream; List _remoteStreams; @@ -100,6 +104,17 @@ class Signaling { if (_socket != null) _socket.close(); } + getTurnCredential(String host) async { + var httpClient = new HttpClient(); + var uri = new Uri.http('$host', '/api/turn', + {'service': 'turn', 'username': 'flutter-webrtc'}); + var request = await httpClient.getUrl(uri); + var response = await request.close(); + var responseBody = await response.transform(Utf8Decoder()).join(); + Map data = _decoder.convert(responseBody); + return data; + } + void switchCamera() { if (_localStream != null) { _localStream.getVideoTracks()[0].switchCamera(); @@ -263,6 +278,28 @@ class Signaling { print('connect to $url'); + if (_turnCredential == null) { + try { + _turnCredential = await getTurnCredential(_host); + /*{ + "username": "1584195784:mbzrxpgjys", + "password": "isyl6FF6nqMTB9/ig5MrMRUXqZg", + "ttl": 86400, + "uris": ["turn:127.0.0.1:19302?transport=udp"] + } + */ + _iceServers = { + 'iceServers': [ + { + 'url': _turnCredential['uris'][0], + 'username': _turnCredential['username'], + 'credential': _turnCredential['password'] + }, + ] + }; + } catch (e) {} + } + _socket.onOpen = () { print('onOpen'); this?.onStateChange(SignalingState.ConnectionOpen); @@ -405,7 +442,6 @@ class Signaling { var request = new Map(); request["type"] = event; request["data"] = data; - JsonEncoder encoder = new JsonEncoder(); - _socket.send(encoder.convert(request)); + _socket.send(_encoder.convert(request)); } } From ff4a8118d46c831eb5ee972900f652b337b9a014 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sun, 15 Mar 2020 00:02:17 +0800 Subject: [PATCH 03/69] Add turn relay support for web. --- lib/main.dart | 26 +++++++++++++----------- lib/src/call_sample/signaling.dart | 21 ++++++------------- lib/src/utils/key_value_store.dart | 16 --------------- lib/src/utils/key_value_store_web.dart | 28 -------------------------- lib/src/utils/turn.dart | 19 +++++++++++++++++ lib/src/utils/turn_web.dart | 13 ++++++++++++ lib/src/utils/websocket.dart | 17 ++++++++-------- lib/src/utils/websocket_web.dart | 8 +++++--- pubspec.yaml | 3 ++- 9 files changed, 67 insertions(+), 84 deletions(-) delete mode 100644 lib/src/utils/key_value_store.dart delete mode 100644 lib/src/utils/key_value_store_web.dart create mode 100644 lib/src/utils/turn.dart create mode 100644 lib/src/utils/turn_web.dart diff --git a/lib/main.dart b/lib/main.dart index d51bb5e..6fddb5f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,7 +1,8 @@ -import 'package:flutter/material.dart'; -import 'src/utils/key_value_store.dart' - if (dart.library.js) 'src/utils/key_value_store_web.dart'; import 'dart:core'; + +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + import 'src/basic_sample/basic_sample.dart'; import 'src/call_sample/call_sample.dart'; import 'src/call_sample/data_channel_sample.dart'; @@ -21,8 +22,9 @@ enum DialogDemoAction { class _MyAppState extends State { List items; - String _serverAddress = ''; - KeyValueStore keyValueStore = KeyValueStore(); + String _server = ''; + SharedPreferences _prefs; + bool _datachannel = false; @override initState() { @@ -60,9 +62,9 @@ class _MyAppState extends State { } _initData() async { - await keyValueStore.init(); + _prefs = await SharedPreferences.getInstance(); setState(() { - _serverAddress = keyValueStore.getString('server') ?? 'demo.cloudwebrtc.com'; + _server = _prefs.getString('server') ?? 'demo.cloudwebrtc.com'; }); } @@ -74,13 +76,13 @@ class _MyAppState extends State { // The value passed to Navigator.pop() or null. if (value != null) { if (value == DialogDemoAction.connect) { - keyValueStore.setString('server', _serverAddress); + _prefs.setString('server', _server); Navigator.push( context, MaterialPageRoute( builder: (BuildContext context) => _datachannel - ? DataChannelSample(ip: _serverAddress) - : CallSample(ip: _serverAddress))); + ? DataChannelSample(ip: _server) + : CallSample(ip: _server))); } } }); @@ -94,11 +96,11 @@ class _MyAppState extends State { content: TextField( onChanged: (String text) { setState(() { - _serverAddress = text; + _server = text; }); }, decoration: InputDecoration( - hintText: _serverAddress, + hintText: _server, ), textAlign: TextAlign.center, ), diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index a88d32c..76a19f5 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -1,13 +1,15 @@ import 'dart:convert'; import 'dart:async'; -import 'dart:io'; import 'package:flutter_webrtc/webrtc.dart'; + import 'random_string.dart'; import '../utils/device_info.dart' if (dart.library.js) '../utils/device_info_web.dart'; import '../utils/websocket.dart' if (dart.library.js) '../utils/websocket_web.dart'; +import '../utils/turn.dart' + if (dart.library.js) '../utils/turn_web.dart'; enum SignalingState { CallStateNew, @@ -37,7 +39,7 @@ class Signaling { SimpleWebSocket _socket; var _sessionId; var _host; - var _port = 4443; + var _port = 8086; var _peerConnections = new Map(); var _dataChannels = new Map(); var _remoteCandidates = []; @@ -104,17 +106,6 @@ class Signaling { if (_socket != null) _socket.close(); } - getTurnCredential(String host) async { - var httpClient = new HttpClient(); - var uri = new Uri.http('$host', '/api/turn', - {'service': 'turn', 'username': 'flutter-webrtc'}); - var request = await httpClient.getUrl(uri); - var response = await request.close(); - var responseBody = await response.transform(Utf8Decoder()).join(); - Map data = _decoder.convert(responseBody); - return data; - } - void switchCamera() { if (_localStream != null) { _localStream.getVideoTracks()[0].switchCamera(); @@ -273,14 +264,14 @@ class Signaling { } void connect() async { - var url = 'wss://$_host:$_port/ws'; + var url = 'https://$_host:$_port/ws'; _socket = SimpleWebSocket(url); print('connect to $url'); if (_turnCredential == null) { try { - _turnCredential = await getTurnCredential(_host); + _turnCredential = await getTurnCredential(_host, _port); /*{ "username": "1584195784:mbzrxpgjys", "password": "isyl6FF6nqMTB9/ig5MrMRUXqZg", diff --git a/lib/src/utils/key_value_store.dart b/lib/src/utils/key_value_store.dart deleted file mode 100644 index 56e5eb5..0000000 --- a/lib/src/utils/key_value_store.dart +++ /dev/null @@ -1,16 +0,0 @@ -import 'dart:async'; -import 'package:shared_preferences/shared_preferences.dart'; - -class KeyValueStore { - KeyValueStore(); - SharedPreferences _preferences; - - init() async { - _preferences = await SharedPreferences.getInstance(); - } - - String getString(String key) => _preferences.getString(key); - - Future setString(String key, String value) => - _preferences.setString(key, value); -} diff --git a/lib/src/utils/key_value_store_web.dart b/lib/src/utils/key_value_store_web.dart deleted file mode 100644 index 0fc445a..0000000 --- a/lib/src/utils/key_value_store_web.dart +++ /dev/null @@ -1,28 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; -import 'dart:html'; - -class KeyValueStore { - KeyValueStore(); - Storage _storage; - - init() async { - _storage = window.localStorage; - } - - String getString(String key) => _storage[key]; - - Future setString(String key, String value) => _setValue(key, value); - - Future _setValue(String key, dynamic value) { - if (value is String) { - _storage[key] = value; - } else if (value is bool || value is double || value is int) { - _storage[key] = value.toString(); - } else if (value is List) { - _storage[key] = json.encode(value); - } - - return Future.value(true); - } -} diff --git a/lib/src/utils/turn.dart b/lib/src/utils/turn.dart new file mode 100644 index 0000000..0d4a00f --- /dev/null +++ b/lib/src/utils/turn.dart @@ -0,0 +1,19 @@ +import 'dart:convert'; +import 'dart:async'; +import 'dart:io'; + +Future getTurnCredential(String host, int port) async { + HttpClient client = HttpClient(context: SecurityContext()); + client.badCertificateCallback = + (X509Certificate cert, String host, int port) { + print('getTurnCredential: Allow self-signed certificate => $host:$port. '); + return true; + }; + var url = 'https://$host:$port/api/turn?service=turn&username=flutter-webrtc'; + var request = await client.getUrl(Uri.parse(url)); + var response = await request.close(); + var responseBody = await response.transform(Utf8Decoder()).join(); + print('getTurnCredential:response => $responseBody.'); + Map data = JsonDecoder().convert(responseBody); + return data; + } diff --git a/lib/src/utils/turn_web.dart b/lib/src/utils/turn_web.dart new file mode 100644 index 0000000..63c16e9 --- /dev/null +++ b/lib/src/utils/turn_web.dart @@ -0,0 +1,13 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; + +Future getTurnCredential(String host, int port) async { + var url = 'https://$host:$port/api/turn?service=turn&username=flutter-webrtc'; + final res = await http.get(url); + if (res.statusCode == 200) { + var data = json.decode(res.body); + print('getTurnCredential:response => $data.'); + return data; + } + return {}; + } \ No newline at end of file diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index cd49115..4cd39f1 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -17,8 +17,8 @@ class SimpleWebSocket { connect() async { try { - _socket = await WebSocket.connect(_url); - //socket = await _connectForSelfSignedCert(_host, _port); + //_socket = await WebSocket.connect(_url); + _socket = await _connectForSelfSignedCert(_url); this?.onOpen(); _socket.listen((data) { this?.onMessage(data); @@ -38,23 +38,22 @@ class SimpleWebSocket { } close() { - _socket.close(); + if (_socket != null) + _socket.close(); } - Future _connectForSelfSignedCert(String host, int port) async { + Future _connectForSelfSignedCert(url) async { try { Random r = new Random(); String key = base64.encode(List.generate(8, (_) => r.nextInt(255))); - SecurityContext securityContext = new SecurityContext(); - HttpClient client = HttpClient(context: securityContext); + HttpClient client = HttpClient(context: SecurityContext()); client.badCertificateCallback = (X509Certificate cert, String host, int port) { - print('Allow self-signed certificate => $host:$port. '); + print('SimpleWebSocket: Allow self-signed certificate => $host:$port. '); return true; }; - HttpClientRequest request = await client.getUrl( - Uri.parse('https://$host:$port/ws')); // form the correct url here + HttpClientRequest request = await client.getUrl(Uri.parse(url)); // form the correct url here request.headers.add('Connection', 'Upgrade'); request.headers.add('Upgrade', 'websocket'); request.headers.add( diff --git a/lib/src/utils/websocket_web.dart b/lib/src/utils/websocket_web.dart index f7ecdc5..e33cf17 100644 --- a/lib/src/utils/websocket_web.dart +++ b/lib/src/utils/websocket_web.dart @@ -11,7 +11,9 @@ class SimpleWebSocket { OnMessageCallback onMessage; OnCloseCallback onClose; - SimpleWebSocket(this._url); + SimpleWebSocket(this._url) { + _url = _url.replaceAll('https:', 'wss:'); + } connect() async { try { @@ -28,7 +30,7 @@ class SimpleWebSocket { this?.onClose(e.code, e.reason); }); } catch (e) { - this?.onClose(e.code, e.reason); + this?.onClose(500, e.toString()); } } @@ -42,6 +44,6 @@ class SimpleWebSocket { } close() { - _socket.close(); + if (_socket != null) _socket.close(); } } diff --git a/pubspec.yaml b/pubspec.yaml index d82dbab..29e959b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,9 +19,10 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 - flutter_webrtc: ^0.2.2 + flutter_webrtc: ^0.2.6 shared_preferences: shared_preferences_macos: + shared_preferences_web: # Required for MediaRecorder example path_provider: From b896df87f5785a051d6fa9e1459062070e6b523b Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sun, 15 Mar 2020 00:11:12 +0800 Subject: [PATCH 04/69] Add http to pubspec.yaml. --- pubspec.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/pubspec.yaml b/pubspec.yaml index 29e959b..76f3edb 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -23,6 +23,7 @@ dependencies: shared_preferences: shared_preferences_macos: shared_preferences_web: + http: ^0.12.0+4 # Required for MediaRecorder example path_provider: From 35f1a3d153cd60c110950ae97e784683601f127a Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sun, 15 Mar 2020 00:41:32 +0800 Subject: [PATCH 05/69] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index c701b00..e3bcf7a 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,8 @@ # flutter-webrtc-demo Flutter WebRTC plugin Demo + +Online Demo: https://demo.cloudwebrtc.com:8086/ + ## Usage - `git clone https://github.com/cloudwebrtc/flutter-webrtc-demo` - `cd flutter-webrtc-demo` From bde7e64e1ddf6721b3662bc9d6c0b6dd045b7ed3 Mon Sep 17 00:00:00 2001 From: 18871002288 <18871002288@163.com> Date: Sun, 31 May 2020 08:58:21 +0800 Subject: [PATCH 06/69] Remove new key word --- lib/main.dart | 20 ++++---- lib/src/basic_sample/basic_sample.dart | 24 +++++----- lib/src/basic_sample/data_channel_sample.dart | 18 +++---- .../basic_sample/get_user_media_sample.dart | 24 +++++----- lib/src/basic_sample/loopback_sample.dart | 42 ++++++++-------- lib/src/call_sample/call_sample.dart | 48 +++++++++---------- lib/src/call_sample/data_channel_sample.dart | 20 ++++---- lib/src/call_sample/settings.dart | 10 ++-- 8 files changed, 103 insertions(+), 103 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 6fddb5f..7d42a73 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -46,12 +46,12 @@ class _MyAppState extends State { @override Widget build(BuildContext context) { - return new MaterialApp( - home: new Scaffold( - appBar: new AppBar( - title: new Text('Flutter-WebRTC example'), + return MaterialApp( + home: Scaffold( + appBar: AppBar( + title: Text('Flutter-WebRTC example'), ), - body: new ListView.builder( + body: ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: items.length, @@ -91,7 +91,7 @@ class _MyAppState extends State { _showAddressDialog(context) { showDemoDialog( context: context, - child: new AlertDialog( + child: AlertDialog( title: const Text('Enter server address:'), content: TextField( onChanged: (String text) { @@ -105,12 +105,12 @@ class _MyAppState extends State { textAlign: TextAlign.center, ), actions: [ - new FlatButton( + FlatButton( child: const Text('CANCEL'), onPressed: () { Navigator.pop(context, DialogDemoAction.cancel); }), - new FlatButton( + FlatButton( child: const Text('CONNECT'), onPressed: () { Navigator.pop(context, DialogDemoAction.connect); @@ -126,8 +126,8 @@ class _MyAppState extends State { push: (BuildContext context) { Navigator.push( context, - new MaterialPageRoute( - builder: (BuildContext context) => new BasicSample())); + MaterialPageRoute( + builder: (BuildContext context) => BasicSample())); }), RouteItem( title: 'P2P Call Sample', diff --git a/lib/src/basic_sample/basic_sample.dart b/lib/src/basic_sample/basic_sample.dart index 4a3fe1d..0f73a56 100644 --- a/lib/src/basic_sample/basic_sample.dart +++ b/lib/src/basic_sample/basic_sample.dart @@ -13,35 +13,35 @@ final List items = [ push: (BuildContext context) { Navigator.push( context, - new MaterialPageRoute( - builder: (BuildContext context) => new GetUserMediaSample())); + MaterialPageRoute( + builder: (BuildContext context) => GetUserMediaSample())); }), RouteItem( title: 'LoopBack Sample', push: (BuildContext context) { Navigator.push( context, - new MaterialPageRoute( - builder: (BuildContext context) => new LoopBackSample())); + MaterialPageRoute( + builder: (BuildContext context) => LoopBackSample())); }), RouteItem( title: 'DataChannel Test', push: (BuildContext context) { Navigator.push( context, - new MaterialPageRoute( - builder: (BuildContext context) => new DataChannelSample())); + MaterialPageRoute( + builder: (BuildContext context) => DataChannelSample())); }), ]; class BasicSample extends StatefulWidget { static String tag = 'basic_sample'; @override - _BasicSampleState createState() => new _BasicSampleState(); + _BasicSampleState createState() => _BasicSampleState(); } class _BasicSampleState extends State { - GlobalKey _formKey = new GlobalKey(); + GlobalKey _formKey = GlobalKey(); @override initState() { super.initState(); @@ -65,11 +65,11 @@ class _BasicSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Basic API Tests'), + return Scaffold( + appBar: AppBar( + title: Text('Basic API Tests'), ), - body: new ListView.builder( + body: ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: items.length, diff --git a/lib/src/basic_sample/data_channel_sample.dart b/lib/src/basic_sample/data_channel_sample.dart index 69eaddf..8fe83c1 100644 --- a/lib/src/basic_sample/data_channel_sample.dart +++ b/lib/src/basic_sample/data_channel_sample.dart @@ -7,7 +7,7 @@ class DataChannelSample extends StatefulWidget { static String tag = 'data_channel_sample'; @override - _DataChannelSampleState createState() => new _DataChannelSampleState(); + _DataChannelSampleState createState() => _DataChannelSampleState(); } class _DataChannelSampleState extends State { @@ -135,23 +135,23 @@ class _DataChannelSampleState extends State { @override Widget build(BuildContext context) { return - new Scaffold( - appBar: new AppBar( - title: new Text('Data Channel Test'), + Scaffold( + appBar: AppBar( + title: Text('Data Channel Test'), ), - body: new OrientationBuilder( + body: OrientationBuilder( builder: (context, orientation) { - return new Center( - child: new Container( + return Center( + child: Container( child: _inCalling? Text(_sdp) : Text('data channel test'), ), ); }, ), - floatingActionButton: new FloatingActionButton( + floatingActionButton: FloatingActionButton( onPressed: _inCalling ? _hangUp : _makeCall, tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), + child: Icon(_inCalling ? Icons.call_end : Icons.phone), ), ); diff --git a/lib/src/basic_sample/get_user_media_sample.dart b/lib/src/basic_sample/get_user_media_sample.dart index 156c9b9..fa8d08f 100644 --- a/lib/src/basic_sample/get_user_media_sample.dart +++ b/lib/src/basic_sample/get_user_media_sample.dart @@ -9,12 +9,12 @@ class GetUserMediaSample extends StatefulWidget { static String tag = 'get_usermedia_sample'; @override - _GetUserMediaSampleState createState() => new _GetUserMediaSampleState(); + _GetUserMediaSampleState createState() => _GetUserMediaSampleState(); } class _GetUserMediaSampleState extends State { MediaStream _localStream; - final _localRenderer = new RTCVideoRenderer(); + final _localRenderer = RTCVideoRenderer(); bool _inCalling = false; @override @@ -80,27 +80,27 @@ class _GetUserMediaSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('GetUserMedia API Test'), + return Scaffold( + appBar: AppBar( + title: Text('GetUserMedia API Test'), ), - body: new OrientationBuilder( + body: OrientationBuilder( builder: (context, orientation) { - return new Center( - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), + return Center( + child: Container( + margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, child: RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), + decoration: BoxDecoration(color: Colors.black54), ), ); }, ), - floatingActionButton: new FloatingActionButton( + floatingActionButton: FloatingActionButton( onPressed: _inCalling ? _hangUp : _makeCall, tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), + child: Icon(_inCalling ? Icons.call_end : Icons.phone), ), ); } diff --git a/lib/src/basic_sample/loopback_sample.dart b/lib/src/basic_sample/loopback_sample.dart index 993f080..44a6a71 100644 --- a/lib/src/basic_sample/loopback_sample.dart +++ b/lib/src/basic_sample/loopback_sample.dart @@ -9,14 +9,14 @@ class LoopBackSample extends StatefulWidget { static String tag = 'loopback_sample'; @override - _MyAppState createState() => new _MyAppState(); + _MyAppState createState() => _MyAppState(); } class _MyAppState extends State { MediaStream _localStream; RTCPeerConnection _peerConnection; - final _localRenderer = new RTCVideoRenderer(); - final _remoteRenderer = new RTCVideoRenderer(); + final _localRenderer = RTCVideoRenderer(); + final _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; Timer _timer; @@ -184,38 +184,38 @@ class _MyAppState extends State { Widget build(BuildContext context) { return new Scaffold( - appBar: new AppBar( - title: new Text('LoopBack example'), + appBar: AppBar( + title: Text('LoopBack example'), ), - body: new OrientationBuilder( + body: OrientationBuilder( builder: (context, orientation) { - return new Center( - child: new Container( - decoration: new BoxDecoration(color: Colors.white), - child: new Stack( + return Center( + child: Container( + decoration: BoxDecoration(color: Colors.white), + child: Stack( children: [ - new Align( + Align( alignment: orientation == Orientation.portrait ? const FractionalOffset(0.5, 0.1) : const FractionalOffset(0.0, 0.5), - child: new Container( + child: Container( margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: 320.0, height: 240.0, - child: new RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_localRenderer), + decoration: BoxDecoration(color: Colors.black54), ), ), - new Align( + Align( alignment: orientation == Orientation.portrait ? const FractionalOffset(0.5, 0.9) : const FractionalOffset(1.0, 0.5), - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), + child: Container( + margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: 320.0, height: 240.0, - child: new RTCVideoView(_remoteRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_remoteRenderer), + decoration: BoxDecoration(color: Colors.black54), ), ), ], @@ -224,10 +224,10 @@ class _MyAppState extends State { ); }, ), - floatingActionButton: new FloatingActionButton( + floatingActionButton: FloatingActionButton( onPressed: _inCalling ? _hangUp : _makeCall, tooltip: _inCalling ? 'Hangup' : 'Call', - child: new Icon(_inCalling ? Icons.call_end : Icons.phone), + child: Icon(_inCalling ? Icons.call_end : Icons.phone), ), ); diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 273807b..9f7be86 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -11,15 +11,15 @@ class CallSample extends StatefulWidget { CallSample({Key key, @required this.ip}) : super(key: key); @override - _CallSampleState createState() => new _CallSampleState(serverIP: ip); + _CallSampleState createState() => _CallSampleState(serverIP: ip); } class _CallSampleState extends State { Signaling _signaling; List _peers; var _selfId; - RTCVideoRenderer _localRenderer = new RTCVideoRenderer(); - RTCVideoRenderer _remoteRenderer = new RTCVideoRenderer(); + RTCVideoRenderer _localRenderer = RTCVideoRenderer(); + RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; final String serverIP; @@ -47,7 +47,7 @@ class _CallSampleState extends State { void _connect() async { if (_signaling == null) { - _signaling = new Signaling(serverIP)..connect(); + _signaling = Signaling(serverIP)..connect(); _signaling.onStateChange = (SignalingState state) { switch (state) { @@ -120,9 +120,9 @@ class _CallSampleState extends State { ? peer['name'] + '[Your self]' : peer['name'] + '[' + peer['user_agent'] + ']'), onTap: null, - trailing: new SizedBox( + trailing: SizedBox( width: 100.0, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( @@ -144,9 +144,9 @@ class _CallSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('P2P Call Sample'), + return Scaffold( + appBar: AppBar( + title: Text('P2P Call Sample'), actions: [ IconButton( icon: const Icon(Icons.settings), @@ -157,9 +157,9 @@ class _CallSampleState extends State { ), floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: _inCalling - ? new SizedBox( + ? SizedBox( width: 200.0, - child: new Row( + child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FloatingActionButton( @@ -169,7 +169,7 @@ class _CallSampleState extends State { FloatingActionButton( onPressed: _hangUp, tooltip: 'Hangup', - child: new Icon(Icons.call_end), + child: Icon(Icons.call_end), backgroundColor: Colors.pink, ), FloatingActionButton( @@ -180,35 +180,35 @@ class _CallSampleState extends State { : null, body: _inCalling ? OrientationBuilder(builder: (context, orientation) { - return new Container( - child: new Stack(children: [ - new Positioned( + return Container( + child: Stack(children: [ + Positioned( left: 0.0, right: 0.0, top: 0.0, bottom: 0.0, - child: new Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), + child: Container( + margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), width: MediaQuery.of(context).size.width, height: MediaQuery.of(context).size.height, - child: new RTCVideoView(_remoteRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_remoteRenderer), + decoration: BoxDecoration(color: Colors.black54), )), - new Positioned( + Positioned( left: 20.0, top: 20.0, - child: new Container( + child: Container( width: orientation == Orientation.portrait ? 90.0 : 120.0, height: orientation == Orientation.portrait ? 120.0 : 90.0, - child: new RTCVideoView(_localRenderer), - decoration: new BoxDecoration(color: Colors.black54), + child: RTCVideoView(_localRenderer), + decoration: BoxDecoration(color: Colors.black54), ), ), ]), ); }) - : new ListView.builder( + : ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: (_peers != null ? _peers.length : 0), diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 0a354c2..d81e781 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -14,7 +14,7 @@ class DataChannelSample extends StatefulWidget { DataChannelSample({Key key, @required this.ip}) : super(key: key); @override - _DataChannelSampleState createState() => new _DataChannelSampleState(serverIP: ip); + _DataChannelSampleState createState() => _DataChannelSampleState(serverIP: ip); } class _DataChannelSampleState extends State { @@ -45,7 +45,7 @@ class _DataChannelSampleState extends State { void _connect() async { if (_signaling == null) { - _signaling = new Signaling(serverIP) + _signaling = Signaling(serverIP) ..connect(); _signaling.onDataChannelMessage = (dc, RTCDataChannelMessage data){ @@ -70,7 +70,7 @@ class _DataChannelSampleState extends State { this.setState(() { _inCalling = true; }); - _timer = new Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); + _timer = Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); break; } case SignalingState.CallStateBye: @@ -142,9 +142,9 @@ class _DataChannelSampleState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Data Channel Sample'), + return Scaffold( + appBar: AppBar( + title: Text('Data Channel Sample'), actions: [ IconButton( icon: const Icon(Icons.settings), @@ -157,14 +157,14 @@ class _DataChannelSampleState extends State { ? FloatingActionButton( onPressed: _hangUp, tooltip: 'Hangup', - child: new Icon(Icons.call_end), + child: Icon(Icons.call_end), ) : null, - body: _inCalling? new Center( - child: new Container( + body: _inCalling? Center( + child: Container( child: Text('Recevied => ' + _text), ), - ) : new ListView.builder( + ) : ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: (_peers != null ? _peers.length : 0), diff --git a/lib/src/call_sample/settings.dart b/lib/src/call_sample/settings.dart index a964836..37c6831 100644 --- a/lib/src/call_sample/settings.dart +++ b/lib/src/call_sample/settings.dart @@ -22,13 +22,13 @@ class _CallSettingsState extends State { @override Widget build(BuildContext context) { - return new Scaffold( - appBar: new AppBar( - title: new Text('Settings'), + return Scaffold( + appBar: AppBar( + title: Text('Settings'), ), - body: new OrientationBuilder( + body: OrientationBuilder( builder: (context, orientation) { - return new Center( + return Center( child: Text("settings") ); }, From c2279b615e65f5445bdefa7e64f5baf510e6585a Mon Sep 17 00:00:00 2001 From: mitch ross Date: Sun, 5 Jul 2020 17:31:27 -0400 Subject: [PATCH 07/69] add gitignore --- .gitignore | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..65aa46d --- /dev/null +++ b/.gitignore @@ -0,0 +1,70 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# Visual Studio Code related +.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.packages +.pub-cache/ +.pub/ +/build/ + +# Android related +**/android/**/gradle-wrapper.jar +**/android/.gradle +**/android/captures/ +**/android/gradlew +**/android/gradlew.bat +**/android/local.properties +**/android/**/GeneratedPluginRegistrant.java + +# iOS/XCode related +**/ios/**/*.mode1v3 +**/ios/**/*.mode2v3 +**/ios/**/*.moved-aside +**/ios/**/*.pbxuser +**/ios/**/*.perspectivev3 +**/ios/**/*sync/ +**/ios/**/.sconsign.dblite +**/ios/**/.tags* +**/ios/**/.vagrant/ +**/ios/**/DerivedData/ +**/ios/**/Icon? +**/ios/**/Pods/ +**/ios/**/.symlinks/ +**/ios/**/profile +**/ios/**/xcuserdata +**/ios/.generated/ +**/ios/Flutter/App.framework +**/ios/Flutter/Flutter.framework +**/ios/Flutter/Generated.xcconfig +**/ios/Flutter/app.flx +**/ios/Flutter/app.zip +**/ios/Flutter/flutter_assets/ +**/ios/ServiceDefinitions.json +**/ios/Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!**/ios/**/default.mode1v3 +!**/ios/**/default.mode2v3 +!**/ios/**/default.pbxuser +!**/ios/**/default.perspectivev3 +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages \ No newline at end of file From b9a7befa82b3d6e8686e48398c07b90afeb434fe Mon Sep 17 00:00:00 2001 From: mitch ross Date: Sun, 5 Jul 2020 17:39:55 -0400 Subject: [PATCH 08/69] Make Android Build Again --- .gitignore | 5 +- .../plugins/GeneratedPluginRegistrant.java | 2 + android/build.gradle | 2 +- .../gradle/wrapper/gradle-wrapper.properties | 6 + ios/Runner/GeneratedPluginRegistrant.h | 3 + ios/Runner/GeneratedPluginRegistrant.m | 19 +- pubspec.lock | 278 ++++++++++++++++++ pubspec.yaml | 10 +- 8 files changed, 317 insertions(+), 8 deletions(-) create mode 100644 android/gradle/wrapper/gradle-wrapper.properties create mode 100644 pubspec.lock diff --git a/.gitignore b/.gitignore index 65aa46d..fb82ae0 100644 --- a/.gitignore +++ b/.gitignore @@ -67,4 +67,7 @@ !**/ios/**/default.mode2v3 !**/ios/**/default.pbxuser !**/ios/**/default.perspectivev3 -!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages \ No newline at end of file +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +.flutter-plugins-dependencies + +ios/Flutter/flutter_export_environment.sh diff --git a/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java b/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java index f0810df..85444bd 100644 --- a/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java +++ b/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java @@ -2,6 +2,7 @@ import io.flutter.plugin.common.PluginRegistry; import com.cloudwebrtc.webrtc.FlutterWebRTCPlugin; +import io.flutter.plugins.pathprovider.PathProviderPlugin; import io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin; /** @@ -13,6 +14,7 @@ public static void registerWith(PluginRegistry registry) { return; } FlutterWebRTCPlugin.registerWith(registry.registrarFor("com.cloudwebrtc.webrtc.FlutterWebRTCPlugin")); + PathProviderPlugin.registerWith(registry.registrarFor("io.flutter.plugins.pathprovider.PathProviderPlugin")); SharedPreferencesPlugin.registerWith(registry.registrarFor("io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")); } diff --git a/android/build.gradle b/android/build.gradle index d4225c7..cd23eff 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -5,7 +5,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.1.2' + classpath 'com.android.tools.build:gradle:4.0.0' } } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..39202e2 --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Sun Jul 05 17:31:51 EDT 2020 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip diff --git a/ios/Runner/GeneratedPluginRegistrant.h b/ios/Runner/GeneratedPluginRegistrant.h index 3b700eb..ed9a5c6 100644 --- a/ios/Runner/GeneratedPluginRegistrant.h +++ b/ios/Runner/GeneratedPluginRegistrant.h @@ -7,8 +7,11 @@ #import +NS_ASSUME_NONNULL_BEGIN + @interface GeneratedPluginRegistrant : NSObject + (void)registerWithRegistry:(NSObject*)registry; @end +NS_ASSUME_NONNULL_END #endif /* GeneratedPluginRegistrant_h */ diff --git a/ios/Runner/GeneratedPluginRegistrant.m b/ios/Runner/GeneratedPluginRegistrant.m index c200173..8331b4a 100644 --- a/ios/Runner/GeneratedPluginRegistrant.m +++ b/ios/Runner/GeneratedPluginRegistrant.m @@ -3,13 +3,30 @@ // #import "GeneratedPluginRegistrant.h" + +#if __has_include() #import -#import +#else +@import flutter_webrtc; +#endif + +#if __has_include() +#import +#else +@import path_provider; +#endif + +#if __has_include() +#import +#else +@import shared_preferences; +#endif @implementation GeneratedPluginRegistrant + (void)registerWithRegistry:(NSObject*)registry { [FlutterWebRTCPlugin registerWithRegistrar:[registry registrarForPlugin:@"FlutterWebRTCPlugin"]]; + [FLTPathProviderPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTPathProviderPlugin"]]; [FLTSharedPreferencesPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTSharedPreferencesPlugin"]]; } diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..d14a732 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,278 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + charcode: + dependency: transitive + description: + name: charcode + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.3" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.14.12" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.3" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + file: + dependency: transitive + description: + name: file + url: "https://pub.dartlang.org" + source: hosted + version: "5.2.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_webrtc: + dependency: "direct main" + description: + name: flutter_webrtc + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.8" + http: + dependency: "direct main" + description: + name: http + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.1" + http_parser: + dependency: transitive + description: + name: http_parser + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.4" + intl: + dependency: transitive + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.16.1" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.6" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.8" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + url: "https://pub.dartlang.org" + source: hosted + version: "1.6.11" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.1+2" + path_provider_macos: + dependency: "direct main" + description: + name: path_provider_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.4+3" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + pedantic: + dependency: transitive + description: + name: pedantic + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.0" + platform: + dependency: transitive + description: + name: platform + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.1" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + process: + dependency: transitive + description: + name: process + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.13" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.7+3" + shared_preferences_macos: + dependency: "direct main" + description: + name: shared_preferences_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.1+10" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.4" + shared_preferences_web: + dependency: "direct main" + description: + name: shared_preferences_web + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.2+7" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.3" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.5" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.16" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.6" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.8" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.0" +sdks: + dart: ">=2.7.0 <3.0.0" + flutter: ">=1.12.13+hotfix.5 <2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 76f3edb..7a1e38d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -7,10 +7,10 @@ description: A new Flutter application. # Both the version and the builder number may be overridden in flutter # build by specifying --build-name and --build-number, respectively. # Read more about versioning at semver.org. -version: 1.0.0+1 +version: 1.0.1 environment: - sdk: ">=2.2.0 <3.0.0" + sdk: ">=2.6.0 <3.0.0" dependencies: flutter: @@ -18,12 +18,12 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 - flutter_webrtc: ^0.2.6 + cupertino_icons: ^0.1.3 + flutter_webrtc: ^0.2.8 shared_preferences: shared_preferences_macos: shared_preferences_web: - http: ^0.12.0+4 + http: ^0.12.1 # Required for MediaRecorder example path_provider: From d01bb37f24ed402d80fd09b20bd75be7a3689959 Mon Sep 17 00:00:00 2001 From: lumec <55417562+lumec@users.noreply.github.com> Date: Tue, 4 Aug 2020 16:49:42 -0500 Subject: [PATCH 09/69] Add scrollview for SDP anatomy --- lib/src/basic_sample/data_channel_sample.dart | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/src/basic_sample/data_channel_sample.dart b/lib/src/basic_sample/data_channel_sample.dart index 8fe83c1..5c97d68 100644 --- a/lib/src/basic_sample/data_channel_sample.dart +++ b/lib/src/basic_sample/data_channel_sample.dart @@ -142,7 +142,8 @@ class _DataChannelSampleState extends State { body: OrientationBuilder( builder: (context, orientation) { return Center( - child: Container( + child: SingleChildScrollView( + scrollDirection: Axis.vertical, child: _inCalling? Text(_sdp) : Text('data channel test'), ), ); From 920c8ff8f189b1ebc1c45cfeee798a171ea16724 Mon Sep 17 00:00:00 2001 From: lumec <55417562+lumec@users.noreply.github.com> Date: Tue, 4 Aug 2020 10:42:24 -0500 Subject: [PATCH 10/69] Fix spelling --- lib/src/call_sample/signaling.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 76a19f5..9c7a124 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -302,7 +302,7 @@ class Signaling { }; _socket.onMessage = (message) { - print('Recivied data: ' + message); + print('Received data: ' + message); JsonDecoder decoder = new JsonDecoder(); this.onMessage(decoder.convert(message)); }; From 2b37859f9118a69544656dc0a0beb1bdfa4d40ff Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sat, 5 Sep 2020 17:03:04 +0800 Subject: [PATCH 11/69] Upgrade flutter-webrtc to 0.3.0. --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 76f3edb..e538fa3 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 - flutter_webrtc: ^0.2.6 + flutter_webrtc: ^0.3.0 shared_preferences: shared_preferences_macos: shared_preferences_web: From 095c179b594ef52e2545017b965eaeb6c85fc090 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sat, 12 Sep 2020 15:52:30 +0800 Subject: [PATCH 12/69] Remove basic sample and upgrade flutter-webrtc to 0.3.2. --- lib/generated_plugin_registrant.dart | 16 ++ lib/main.dart | 10 - lib/src/basic_sample/basic_sample.dart | 80 ------ lib/src/basic_sample/data_channel_sample.dart | 160 ------------ .../basic_sample/get_user_media_sample.dart | 107 -------- lib/src/basic_sample/loopback_sample.dart | 235 ------------------ lib/src/call_sample/call_sample.dart | 2 +- lib/src/call_sample/data_channel_sample.dart | 44 ++-- lib/src/call_sample/signaling.dart | 9 +- pubspec.yaml | 2 +- 10 files changed, 47 insertions(+), 618 deletions(-) create mode 100644 lib/generated_plugin_registrant.dart delete mode 100644 lib/src/basic_sample/basic_sample.dart delete mode 100644 lib/src/basic_sample/data_channel_sample.dart delete mode 100644 lib/src/basic_sample/get_user_media_sample.dart delete mode 100644 lib/src/basic_sample/loopback_sample.dart diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart new file mode 100644 index 0000000..9f6808e --- /dev/null +++ b/lib/generated_plugin_registrant.dart @@ -0,0 +1,16 @@ +// +// Generated file. Do not edit. +// + +// ignore: unused_import +import 'dart:ui'; + +import 'package:shared_preferences_web/shared_preferences_web.dart'; + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +// ignore: public_member_api_docs +void registerPlugins(PluginRegistry registry) { + SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); + registry.registerMessageHandler(); +} diff --git a/lib/main.dart b/lib/main.dart index 7d42a73..94fdced 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -3,7 +3,6 @@ import 'dart:core'; import 'package:flutter/material.dart'; import 'package:shared_preferences/shared_preferences.dart'; -import 'src/basic_sample/basic_sample.dart'; import 'src/call_sample/call_sample.dart'; import 'src/call_sample/data_channel_sample.dart'; import 'src/route_item.dart'; @@ -120,15 +119,6 @@ class _MyAppState extends State { _initItems() { items = [ - RouteItem( - title: 'Basic API Tests', - subtitle: 'Basic API Tests.', - push: (BuildContext context) { - Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => BasicSample())); - }), RouteItem( title: 'P2P Call Sample', subtitle: 'P2P Call Sample.', diff --git a/lib/src/basic_sample/basic_sample.dart b/lib/src/basic_sample/basic_sample.dart deleted file mode 100644 index 0f73a56..0000000 --- a/lib/src/basic_sample/basic_sample.dart +++ /dev/null @@ -1,80 +0,0 @@ -import 'package:flutter/material.dart'; -import 'dart:core'; -import 'loopback_sample.dart'; -import 'get_user_media_sample.dart'; -import 'data_channel_sample.dart'; -import '../route_item.dart'; - -typedef void RouteCallback(BuildContext context); - -final List items = [ - RouteItem( - title: 'GetUserMedia Test', - push: (BuildContext context) { - Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => GetUserMediaSample())); - }), - RouteItem( - title: 'LoopBack Sample', - push: (BuildContext context) { - Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => LoopBackSample())); - }), - RouteItem( - title: 'DataChannel Test', - push: (BuildContext context) { - Navigator.push( - context, - MaterialPageRoute( - builder: (BuildContext context) => DataChannelSample())); - }), -]; - -class BasicSample extends StatefulWidget { - static String tag = 'basic_sample'; - @override - _BasicSampleState createState() => _BasicSampleState(); -} - -class _BasicSampleState extends State { - GlobalKey _formKey = GlobalKey(); - @override - initState() { - super.initState(); - } - - @override - deactivate() { - super.deactivate(); - } - - _buildRow(context, item) { - return ListBody(children: [ - ListTile( - title: Text(item.title), - onTap: () => item.push(context), - trailing: Icon(Icons.arrow_right), - ), - Divider() - ]); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('Basic API Tests'), - ), - body: ListView.builder( - shrinkWrap: true, - padding: const EdgeInsets.all(0.0), - itemCount: items.length, - itemBuilder: (context, i) { - return _buildRow(context, items[i]); - })); - } -} diff --git a/lib/src/basic_sample/data_channel_sample.dart b/lib/src/basic_sample/data_channel_sample.dart deleted file mode 100644 index 5c97d68..0000000 --- a/lib/src/basic_sample/data_channel_sample.dart +++ /dev/null @@ -1,160 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; - -class DataChannelSample extends StatefulWidget { - - static String tag = 'data_channel_sample'; - - @override - _DataChannelSampleState createState() => _DataChannelSampleState(); -} - -class _DataChannelSampleState extends State { - RTCPeerConnection _peerConnection; - bool _inCalling = false; - - RTCDataChannelInit _dataChannelDict = null; - RTCDataChannel _dataChannel; - - String _sdp; - - @override - initState() { - super.initState(); - } - - _onSignalingState(RTCSignalingState state) { - print(state); - } - - _onIceGatheringState(RTCIceGatheringState state) { - print(state); - } - - _onIceConnectionState(RTCIceConnectionState state) { - print(state); - } - - _onCandidate(RTCIceCandidate candidate) { - print('onCandidate: ' + candidate.candidate); - _peerConnection.addCandidate(candidate); - setState(() { - _sdp += '\n'; - _sdp += candidate.candidate; - }); - } - - _onRenegotiationNeeded() { - print('RenegotiationNeeded'); - } - - _onDataChannel(RTCDataChannel dataChannel) { - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - - Map configuration = { - "iceServers": [ - {"url": "stun:stun.l.google.com:19302"}, - ] - }; - - final Map offer_sdp_constraints = { - "mandatory": { - "OfferToReceiveAudio": false, - "OfferToReceiveVideo": false, - }, - "optional": [], - }; - - final Map loopback_constraints = { - "mandatory": {}, - "optional": [ - {"DtlsSrtpKeyAgreement": true }, - ], - }; - - if (_peerConnection != null) return; - - try { - - _peerConnection = - await createPeerConnection(configuration, loopback_constraints); - - _peerConnection.onSignalingState = _onSignalingState; - _peerConnection.onIceGatheringState = _onIceGatheringState; - _peerConnection.onIceConnectionState = _onIceConnectionState; - _peerConnection.onIceCandidate = _onCandidate; - _peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded; - - _dataChannelDict = new RTCDataChannelInit(); - _dataChannelDict.id = 1; - _dataChannelDict.ordered = true; - _dataChannelDict.maxRetransmitTime = -1; - _dataChannelDict.maxRetransmits = -1; - _dataChannelDict.protocol = "sctp"; - _dataChannelDict.negotiated = false; - - _dataChannel = await _peerConnection.createDataChannel('dataChannel', _dataChannelDict); - _peerConnection.onDataChannel = _onDataChannel; - - RTCSessionDescription description = - await _peerConnection.createOffer(offer_sdp_constraints); - print(description.sdp); - _peerConnection.setLocalDescription(description); - - _sdp = description.sdp; - //change for loopback. - //description.type = 'answer'; - //_peerConnection.setRemoteDescription(description); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _dataChannel.close(); - await _peerConnection.close(); - _peerConnection = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return - Scaffold( - appBar: AppBar( - title: Text('Data Channel Test'), - ), - body: OrientationBuilder( - builder: (context, orientation) { - return Center( - child: SingleChildScrollView( - scrollDirection: Axis.vertical, - child: _inCalling? Text(_sdp) : Text('data channel test'), - ), - ); - }, - ), - floatingActionButton: FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - - } -} diff --git a/lib/src/basic_sample/get_user_media_sample.dart b/lib/src/basic_sample/get_user_media_sample.dart deleted file mode 100644 index fa8d08f..0000000 --- a/lib/src/basic_sample/get_user_media_sample.dart +++ /dev/null @@ -1,107 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; - -/** - * getUserMedia sample - */ -class GetUserMediaSample extends StatefulWidget { - static String tag = 'get_usermedia_sample'; - - @override - _GetUserMediaSampleState createState() => _GetUserMediaSampleState(); -} - -class _GetUserMediaSampleState extends State { - MediaStream _localStream; - final _localRenderer = RTCVideoRenderer(); - bool _inCalling = false; - - @override - initState() { - super.initState(); - initRenderers(); - } - - @override - deactivate() { - super.deactivate(); - if (_inCalling) { - _hangUp(); - } - _localRenderer.dispose(); - } - - initRenderers() async { - await _localRenderer.initialize(); - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - final Map mediaConstraints = { - "audio": true, - "video": { - "mandatory": { - "minWidth":'640', // Provide your own width, height and frame rate here - "minHeight": '480', - "minFrameRate": '30', - }, - "facingMode": "user", - "optional": [], - } - }; - - try { - navigator.getUserMedia(mediaConstraints).then((stream){ - _localStream = stream; - _localRenderer.srcObject = _localStream; - }); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _localStream.dispose(); - _localRenderer.srcObject = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return Scaffold( - appBar: AppBar( - title: Text('GetUserMedia API Test'), - ), - body: OrientationBuilder( - builder: (context, orientation) { - return Center( - child: Container( - margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: MediaQuery.of(context).size.width, - height: MediaQuery.of(context).size.height, - child: RTCVideoView(_localRenderer), - decoration: BoxDecoration(color: Colors.black54), - ), - ); - }, - ), - floatingActionButton: FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - } -} diff --git a/lib/src/basic_sample/loopback_sample.dart b/lib/src/basic_sample/loopback_sample.dart deleted file mode 100644 index 44a6a71..0000000 --- a/lib/src/basic_sample/loopback_sample.dart +++ /dev/null @@ -1,235 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_webrtc/webrtc.dart'; -import 'dart:core'; -import 'dart:async'; - - -class LoopBackSample extends StatefulWidget { - - static String tag = 'loopback_sample'; - - @override - _MyAppState createState() => _MyAppState(); -} - -class _MyAppState extends State { - MediaStream _localStream; - RTCPeerConnection _peerConnection; - final _localRenderer = RTCVideoRenderer(); - final _remoteRenderer = RTCVideoRenderer(); - bool _inCalling = false; - Timer _timer; - - @override - initState() { - super.initState(); - initRenderers(); - } - - @override - deactivate() { - super.deactivate(); - if (_inCalling) { - _hangUp(); - } - _localRenderer.dispose(); - _remoteRenderer.dispose(); - } - - initRenderers() async { - await _localRenderer.initialize(); - await _remoteRenderer.initialize(); - } - - void handleStatsReport(Timer timer) async { - if (_peerConnection != null) { - List reports = await _peerConnection.getStats(); - reports.forEach((report) { - print("report => { "); - print(" id: " + report.id + ","); - print(" type: " + report.type + ","); - print(" timestamp: ${report.timestamp},"); - print(" values => {"); - report.values.forEach((key, value) { - print(" " + key + " : " + value + ", "); - }); - print(" }"); - print("}"); - }); - } - } - - _onSignalingState(RTCSignalingState state) { - print(state); - } - - _onIceGatheringState(RTCIceGatheringState state) { - print(state); - } - - _onIceConnectionState(RTCIceConnectionState state) { - print(state); - } - - _onAddStream(MediaStream stream) { - print('addStream: ' + stream.id); - _remoteRenderer.srcObject = stream; - } - - _onRemoveStream(MediaStream stream) { - _remoteRenderer.srcObject = null; - } - - _onCandidate(RTCIceCandidate candidate) { - print('onCandidate: ' + candidate.candidate); - _peerConnection.addCandidate(candidate); - } - - _onRenegotiationNeeded() { - print('RenegotiationNeeded'); - } - - // Platform messages are asynchronous, so we initialize in an async method. - _makeCall() async { - final Map mediaConstraints = { - "audio": true, - "video": { - "mandatory": { - "minWidth": - '640', // Provide your own width, height and frame rate here - "minHeight": '480', - "minFrameRate": '30', - }, - "facingMode": "user", - "optional": [], - } - }; - - Map configuration = { - "iceServers": [ - {"url": "stun:stun.l.google.com:19302"}, - ] - }; - - final Map offer_sdp_constraints = { - "mandatory": { - "OfferToReceiveAudio": true, - "OfferToReceiveVideo": true, - }, - "optional": [], - }; - - final Map loopback_constraints = { - "mandatory": {}, - "optional": [ - {"DtlsSrtpKeyAgreement": false}, - ], - }; - - if (_peerConnection != null) return; - - try { - _localStream = await navigator.getUserMedia(mediaConstraints); - _localRenderer.srcObject = _localStream; - - _peerConnection = - await createPeerConnection(configuration, loopback_constraints); - - _peerConnection.onSignalingState = _onSignalingState; - _peerConnection.onIceGatheringState = _onIceGatheringState; - _peerConnection.onIceConnectionState = _onIceConnectionState; - _peerConnection.onAddStream = _onAddStream; - _peerConnection.onRemoveStream = _onRemoveStream; - _peerConnection.onIceCandidate = _onCandidate; - _peerConnection.onRenegotiationNeeded = _onRenegotiationNeeded; - - _peerConnection.addStream(_localStream); - RTCSessionDescription description = - await _peerConnection.createOffer(offer_sdp_constraints); - print(description.sdp); - _peerConnection.setLocalDescription(description); - //change for loopback. - description.type = 'answer'; - _peerConnection.setRemoteDescription(description); - - _localStream.getAudioTracks()[0].setMicrophoneMute(false); - } catch (e) { - print(e.toString()); - } - if (!mounted) return; - - _timer = new Timer.periodic(Duration(seconds: 1), handleStatsReport); - - setState(() { - _inCalling = true; - }); - } - - _hangUp() async { - try { - await _localStream.dispose(); - await _peerConnection.close(); - _peerConnection = null; - _localRenderer.srcObject = null; - _remoteRenderer.srcObject = null; - } catch (e) { - print(e.toString()); - } - setState(() { - _inCalling = false; - }); - } - - @override - Widget build(BuildContext context) { - return - new Scaffold( - appBar: AppBar( - title: Text('LoopBack example'), - ), - body: OrientationBuilder( - builder: (context, orientation) { - return Center( - child: Container( - decoration: BoxDecoration(color: Colors.white), - child: Stack( - children: [ - Align( - alignment: orientation == Orientation.portrait - ? const FractionalOffset(0.5, 0.1) - : const FractionalOffset(0.0, 0.5), - child: Container( - margin: new EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: 320.0, - height: 240.0, - child: RTCVideoView(_localRenderer), - decoration: BoxDecoration(color: Colors.black54), - ), - ), - Align( - alignment: orientation == Orientation.portrait - ? const FractionalOffset(0.5, 0.9) - : const FractionalOffset(1.0, 0.5), - child: Container( - margin: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0), - width: 320.0, - height: 240.0, - child: RTCVideoView(_remoteRenderer), - decoration: BoxDecoration(color: Colors.black54), - ), - ), - ], - ), - ), - ); - }, - ), - floatingActionButton: FloatingActionButton( - onPressed: _inCalling ? _hangUp : _makeCall, - tooltip: _inCalling ? 'Hangup' : 'Call', - child: Icon(_inCalling ? Icons.call_end : Icons.phone), - ), - ); - - } -} diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 9f7be86..2707a1e 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -1,7 +1,7 @@ import 'package:flutter/material.dart'; import 'dart:core'; import 'signaling.dart'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; class CallSample extends StatefulWidget { static String tag = 'call_sample'; diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index d81e781..b10ee1a 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -1,10 +1,9 @@ import 'package:flutter/material.dart'; -import 'dart:io'; import 'dart:core'; import 'dart:async'; import 'dart:typed_data'; import 'signaling.dart'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; class DataChannelSample extends StatefulWidget { static String tag = 'call_sample'; @@ -14,7 +13,8 @@ class DataChannelSample extends StatefulWidget { DataChannelSample({Key key, @required this.ip}) : super(key: key); @override - _DataChannelSampleState createState() => _DataChannelSampleState(serverIP: ip); + _DataChannelSampleState createState() => + _DataChannelSampleState(serverIP: ip); } class _DataChannelSampleState extends State { @@ -38,28 +38,26 @@ class _DataChannelSampleState extends State { deactivate() { super.deactivate(); if (_signaling != null) _signaling.close(); - if(_timer != null){ + if (_timer != null) { _timer.cancel(); } } void _connect() async { if (_signaling == null) { - _signaling = Signaling(serverIP) - ..connect(); + _signaling = Signaling(serverIP)..connect(); - _signaling.onDataChannelMessage = (dc, RTCDataChannelMessage data){ + _signaling.onDataChannelMessage = (dc, RTCDataChannelMessage data) { setState(() { - if(data.isBinary) { + if (data.isBinary) { print('Got binary [' + data.binary.toString() + ']'); - } - else{ + } else { _text = data.text; } }); }; - _signaling.onDataChannel = (channel){ + _signaling.onDataChannel = (channel) { _dataChannel = channel; }; @@ -70,7 +68,8 @@ class _DataChannelSampleState extends State { this.setState(() { _inCalling = true; }); - _timer = Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); + _timer = + Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); break; } case SignalingState.CallStateBye: @@ -78,7 +77,7 @@ class _DataChannelSampleState extends State { this.setState(() { _inCalling = false; }); - if(_timer != null){ + if (_timer != null) { _timer.cancel(); _timer = null; } @@ -106,9 +105,14 @@ class _DataChannelSampleState extends State { } _handleDataChannelTest(Timer timer) async { - if(_dataChannel != null){ - String text = 'Say hello ' + timer.tick.toString() + ' times, from [' + _selfId + ']'; - _dataChannel.send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); + if (_dataChannel != null) { + String text = 'Say hello ' + + timer.tick.toString() + + ' times, from [' + + _selfId + + ']'; + _dataChannel + .send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); _dataChannel.send(RTCDataChannelMessage(text)); } } @@ -160,11 +164,13 @@ class _DataChannelSampleState extends State { child: Icon(Icons.call_end), ) : null, - body: _inCalling? Center( + body: _inCalling + ? Center( child: Container( - child: Text('Recevied => ' + _text), + child: Text('Recevied => ' + _text), ), - ) : ListView.builder( + ) + : ListView.builder( shrinkWrap: true, padding: const EdgeInsets.all(0.0), itemCount: (_peers != null ? _peers.length : 0), diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 9c7a124..73a62c7 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -1,6 +1,6 @@ import 'dart:convert'; import 'dart:async'; -import 'package:flutter_webrtc/webrtc.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; import 'random_string.dart'; @@ -8,8 +8,7 @@ import '../utils/device_info.dart' if (dart.library.js) '../utils/device_info_web.dart'; import '../utils/websocket.dart' if (dart.library.js) '../utils/websocket_web.dart'; -import '../utils/turn.dart' - if (dart.library.js) '../utils/turn_web.dart'; +import '../utils/turn.dart' if (dart.library.js) '../utils/turn_web.dart'; enum SignalingState { CallStateNew, @@ -333,8 +332,8 @@ class Signaling { }; MediaStream stream = user_screen - ? await navigator.getDisplayMedia(mediaConstraints) - : await navigator.getUserMedia(mediaConstraints); + ? await MediaDevices.getDisplayMedia(mediaConstraints) + : await MediaDevices.getUserMedia(mediaConstraints); if (this.onLocalStream != null) { this.onLocalStream(stream); } diff --git a/pubspec.yaml b/pubspec.yaml index e538fa3..ced4880 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^0.1.2 - flutter_webrtc: ^0.3.0 + flutter_webrtc: ^0.3.2 shared_preferences: shared_preferences_macos: shared_preferences_web: From eb57e9b869467846917a79428f708a839e2a1cb2 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 14 Sep 2020 14:06:23 +0000 Subject: [PATCH 13/69] Add renovate.json --- renovate.json | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 renovate.json diff --git a/renovate.json b/renovate.json new file mode 100644 index 0000000..f45d8f1 --- /dev/null +++ b/renovate.json @@ -0,0 +1,5 @@ +{ + "extends": [ + "config:base" + ] +} From 44148ded027a69dfaef3faefdcd262aa15863e1a Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 14 Sep 2020 14:11:12 +0000 Subject: [PATCH 14/69] Update dependency cupertino_icons to v1 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index ced4880..78636f0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -18,7 +18,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. - cupertino_icons: ^0.1.2 + cupertino_icons: ^1.0.0 flutter_webrtc: ^0.3.2 shared_preferences: shared_preferences_macos: From 9f3a762ea398fdaedc12d80549ba5562b539ae3b Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 14 Oct 2020 00:42:12 +0000 Subject: [PATCH 15/69] Update dependency flutter_webrtc to ^0.4.0 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 78636f0..c557c5f 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.3.2 + flutter_webrtc: ^0.4.0 shared_preferences: shared_preferences_macos: shared_preferences_web: From 13833e897a7adc0c778bf410bcd2149f9ef3f2e5 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Wed, 14 Oct 2020 01:10:15 +0000 Subject: [PATCH 16/69] Update dependency gradle to v6.6.1 --- android/gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 39202e2..69897b2 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.1.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip From 8ada749baeeeb828df5eec8b48985e9f43f8cfaf Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Thu, 22 Oct 2020 01:54:16 +0800 Subject: [PATCH 17/69] Delete generated_plugin_registrant.dart --- lib/generated_plugin_registrant.dart | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 lib/generated_plugin_registrant.dart diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart deleted file mode 100644 index 9f6808e..0000000 --- a/lib/generated_plugin_registrant.dart +++ /dev/null @@ -1,16 +0,0 @@ -// -// Generated file. Do not edit. -// - -// ignore: unused_import -import 'dart:ui'; - -import 'package:shared_preferences_web/shared_preferences_web.dart'; - -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -// ignore: public_member_api_docs -void registerPlugins(PluginRegistry registry) { - SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); - registry.registerMessageHandler(); -} From 4ff2b93be711a6796364b92f36bac112176105f5 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 3 Nov 2020 05:45:26 +0000 Subject: [PATCH 18/69] Update actions/checkout action to v2 --- .github/workflows/flutter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/flutter.yml b/.github/workflows/flutter.yml index 166d257..c0438d2 100644 --- a/.github/workflows/flutter.yml +++ b/.github/workflows/flutter.yml @@ -16,7 +16,7 @@ jobs: os: [ubuntu-latest] # os: [ubuntu-latest, windows-latest, macos-latest] steps: - - uses: actions/checkout@v1 + - uses: actions/checkout@v2 - uses: actions/setup-java@v1 with: java-version: '12.x' From 4702c8faeada80a305ba25ac2a542c694f5f18a9 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sun, 15 Nov 2020 16:41:09 +0800 Subject: [PATCH 19/69] update. --- android/app/build.gradle | 2 +- lib/generated_plugin_registrant.dart | 16 ++++++++ lib/src/call_sample/call_sample.dart | 2 +- lib/src/call_sample/signaling.dart | 55 +++++++++++++--------------- 4 files changed, 44 insertions(+), 31 deletions(-) create mode 100644 lib/generated_plugin_registrant.dart diff --git a/android/app/build.gradle b/android/app/build.gradle index 4543909..57cc757 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -34,7 +34,7 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.cloudwebrtc.flutterwebrtcdemo" - minSdkVersion 18 + minSdkVersion 21 targetSdkVersion 28 versionCode flutterVersionCode.toInteger() versionName flutterVersionName diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart new file mode 100644 index 0000000..9f6808e --- /dev/null +++ b/lib/generated_plugin_registrant.dart @@ -0,0 +1,16 @@ +// +// Generated file. Do not edit. +// + +// ignore: unused_import +import 'dart:ui'; + +import 'package:shared_preferences_web/shared_preferences_web.dart'; + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +// ignore: public_member_api_docs +void registerPlugins(PluginRegistry registry) { + SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); + registry.registerMessageHandler(); +} diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 2707a1e..2170996 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -201,7 +201,7 @@ class _CallSampleState extends State { width: orientation == Orientation.portrait ? 90.0 : 120.0, height: orientation == Orientation.portrait ? 120.0 : 90.0, - child: RTCVideoView(_localRenderer), + child: RTCVideoView(_localRenderer, mirror: true), decoration: BoxDecoration(color: Colors.black54), ), ), diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 73a62c7..4b4e9e9 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -33,7 +33,6 @@ typedef void DataChannelCallback(RTCDataChannel dc); class Signaling { JsonEncoder _encoder = new JsonEncoder(); - JsonDecoder _decoder = new JsonDecoder(); String _selfId = randomNumeric(6); SimpleWebSocket _socket; var _sessionId; @@ -45,7 +44,7 @@ class Signaling { var _turnCredential; MediaStream _localStream; - List _remoteStreams; + List _remoteStreams = []; SignalingStateCallback onStateChange; StreamStateCallback onLocalStream; StreamStateCallback onAddRemoteStream; @@ -114,9 +113,7 @@ class Signaling { void invite(String peer_id, String media, use_screen) { this._sessionId = this._selfId + '-' + peer_id; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateNew); - } + this.onStateChange?.call(SignalingState.CallStateNew); _createPeerConnection(peer_id, media, use_screen).then((pc) { _peerConnections[peer_id] = pc; @@ -158,9 +155,7 @@ class Signaling { var sessionId = data['session_id']; this._sessionId = sessionId; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateNew); - } + onStateChange?.call(SignalingState.CallStateNew); var pc = await _createPeerConnection(id, media, false); _peerConnections[id] = pc; @@ -218,9 +213,7 @@ class Signaling { pc.close(); } this._sessionId = null; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateBye); - } + this.onStateChange?.call(SignalingState.CallStateBye); } break; case 'bye': @@ -247,9 +240,7 @@ class Signaling { } this._sessionId = null; - if (this.onStateChange != null) { - this.onStateChange(SignalingState.CallStateBye); - } + onStateChange?.call(SignalingState.CallStateBye); } break; case 'keepalive': @@ -308,9 +299,7 @@ class Signaling { _socket.onClose = (int code, String reason) { print('Closed by server [$code => $reason]!'); - if (this.onStateChange != null) { - this.onStateChange(SignalingState.ConnectionClosed); - } + onStateChange?.call(SignalingState.ConnectionClosed); }; await _socket.connect(); @@ -332,11 +321,9 @@ class Signaling { }; MediaStream stream = user_screen - ? await MediaDevices.getDisplayMedia(mediaConstraints) - : await MediaDevices.getUserMedia(mediaConstraints); - if (this.onLocalStream != null) { - this.onLocalStream(stream); - } + ? await navigator.mediaDevices.getDisplayMedia(mediaConstraints) + : await navigator.mediaDevices.getUserMedia(mediaConstraints); + onLocalStream?.call(stream); return stream; } @@ -345,6 +332,10 @@ class Signaling { RTCPeerConnection pc = await createPeerConnection(_iceServers, _config); if (media != 'data') pc.addStream(_localStream); pc.onIceCandidate = (candidate) { + if (candidate == null) { + print('onIceCandidate: complete!'); + return; + } _send('candidate', { 'to': id, 'from': _selfId, @@ -360,12 +351,20 @@ class Signaling { pc.onIceConnectionState = (state) {}; pc.onAddStream = (stream) { - if (this.onAddRemoteStream != null) this.onAddRemoteStream(stream); - //_remoteStreams.add(stream); + onAddRemoteStream?.call(stream); + _remoteStreams.add(stream); }; + /* unified-plan + pc.onTrack = (event) { + if (event.track.kind == 'video') { + onAddRemoteStream?.call(event.streams[0]); + } + }; + */ + pc.onRemoveStream = (stream) { - if (this.onRemoveRemoteStream != null) this.onRemoveRemoteStream(stream); + this.onRemoveRemoteStream?.call(stream); _remoteStreams.removeWhere((it) { return (it.id == stream.id); }); @@ -381,12 +380,10 @@ class Signaling { _addDataChannel(id, RTCDataChannel channel) { channel.onDataChannelState = (e) {}; channel.onMessage = (RTCDataChannelMessage data) { - if (this.onDataChannelMessage != null) - this.onDataChannelMessage(channel, data); + this.onDataChannelMessage?.call(channel, data); }; _dataChannels[id] = channel; - - if (this.onDataChannel != null) this.onDataChannel(channel); + onDataChannel?.call(channel); } _createDataChannel(id, RTCPeerConnection pc, {label: 'fileTransfer'}) async { From b4d7196bcac01886b68a12e8f13f4e6b959fd8da Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sun, 15 Nov 2020 23:30:30 +0800 Subject: [PATCH 20/69] Add unified-plan/simulcast example. --- lib/src/call_sample/signaling.dart | 60 ++++++++++++++++++++++++------ 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 4b4e9e9..1c45092 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -71,7 +71,7 @@ class Signaling { 'mandatory': {}, 'optional': [ {'DtlsSrtpKeyAgreement': true}, - ], + ] }; final Map _constraints = { @@ -327,10 +327,48 @@ class Signaling { return stream; } - _createPeerConnection(id, media, user_screen) async { - if (media != 'data') _localStream = await createStream(media, user_screen); - RTCPeerConnection pc = await createPeerConnection(_iceServers, _config); - if (media != 'data') pc.addStream(_localStream); + _createPeerConnection(String id, String media, bool screenSharing) async { + if (media != 'data') + _localStream = await createStream(media, screenSharing); + RTCPeerConnection pc = await createPeerConnection({ + ..._iceServers, + ...{'sdpSemantics': 'unified-plan'} + }, _config); + if (media != 'data') { + _localStream + .getTracks() + .forEach((track) => pc.addTrack(track, _localStream)); + + /* Unified-Plan: Simuclast + await pc.addTransceiver( + track: _localStream.getAudioTracks()[0], + init: RTCRtpTransceiverInit( + direction: TransceiverDirection.SendOnly, streams: [_localStream]), + ); + + await pc.addTransceiver( + track: _localStream.getVideoTracks()[0], + init: RTCRtpTransceiverInit( + direction: TransceiverDirection.SendOnly, + streams: [ + _localStream + ], + sendEncodings: [ + RTCRtpEncoding(rid: 'f'), + RTCRtpEncoding( + rid: 'h', + scaleResolutionDownBy: 2.0, + maxBitrateBps: 150000, + ), + RTCRtpEncoding( + rid: 'q', + scaleResolutionDownBy: 4.0, + maxBitrateBps: 100000, + ), + ]), + ); + */ + } pc.onIceCandidate = (candidate) { if (candidate == null) { print('onIceCandidate: complete!'); @@ -350,18 +388,17 @@ class Signaling { pc.onIceConnectionState = (state) {}; - pc.onAddStream = (stream) { - onAddRemoteStream?.call(stream); - _remoteStreams.add(stream); - }; + //pc.onAddStream = (stream) { + // onAddRemoteStream?.call(stream); + // _remoteStreams.add(stream); + //}; - /* unified-plan + // Unified-Plan pc.onTrack = (event) { if (event.track.kind == 'video') { onAddRemoteStream?.call(event.streams[0]); } }; - */ pc.onRemoveStream = (stream) { this.onRemoveRemoteStream?.call(stream); @@ -373,7 +410,6 @@ class Signaling { pc.onDataChannel = (channel) { _addDataChannel(id, channel); }; - return pc; } From 1e02a2d7a7e755ecd3723708e8349302ad778ac6 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sun, 15 Nov 2020 23:30:44 +0800 Subject: [PATCH 21/69] Bump flutter-webrtc version to 0.5.0. --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 6e26159..85e4a25 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.4.0 + flutter_webrtc: ^0.5.0 shared_preferences: shared_preferences_macos: shared_preferences_web: From 57c586821d885c6d69da9e73fb8ca2738168ba6d Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sun, 15 Nov 2020 23:31:42 +0800 Subject: [PATCH 22/69] Delete generated_plugin_registrant.dart --- lib/generated_plugin_registrant.dart | 16 ---------------- 1 file changed, 16 deletions(-) delete mode 100644 lib/generated_plugin_registrant.dart diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart deleted file mode 100644 index 9f6808e..0000000 --- a/lib/generated_plugin_registrant.dart +++ /dev/null @@ -1,16 +0,0 @@ -// -// Generated file. Do not edit. -// - -// ignore: unused_import -import 'dart:ui'; - -import 'package:shared_preferences_web/shared_preferences_web.dart'; - -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -// ignore: public_member_api_docs -void registerPlugins(PluginRegistry registry) { - SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); - registry.registerMessageHandler(); -} From a2e641363edeb6a80eb83a0ef137397550a2e6ae Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Wed, 18 Nov 2020 15:39:22 +0800 Subject: [PATCH 23/69] update. --- lib/src/call_sample/call_sample.dart | 4 +- lib/src/call_sample/signaling.dart | 54 ++++-- pubspec.lock | 278 --------------------------- pubspec.yaml | 2 +- 4 files changed, 42 insertions(+), 296 deletions(-) delete mode 100644 pubspec.lock diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 2170996..efcceb7 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -110,7 +110,9 @@ class _CallSampleState extends State { _signaling.switchCamera(); } - _muteMic() {} + _muteMic() { + _signaling.muteMic(); + } _buildRow(context, peer) { var self = (peer['id'] == _selfId); diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 1c45092..a3463c5 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -110,17 +110,24 @@ class Signaling { } } - void invite(String peer_id, String media, use_screen) { - this._sessionId = this._selfId + '-' + peer_id; + void muteMic() { + if (_localStream != null) { + bool enabled = _localStream.getAudioTracks()[0].enabled; + _localStream.getAudioTracks()[0].enabled = !enabled; + } + } + + void invite(String peerId, String media, bool useScreen) { + this._sessionId = this._selfId + '-' + peerId; this.onStateChange?.call(SignalingState.CallStateNew); - _createPeerConnection(peer_id, media, use_screen).then((pc) { - _peerConnections[peer_id] = pc; + _createPeerConnection(peerId, media, useScreen).then((pc) { + _peerConnections[peerId] = pc; if (media == 'data') { - _createDataChannel(peer_id, pc); + _createDataChannel(peerId, pc); } - _createOffer(peer_id, pc, media); + _createOffer(peerId, pc, media); }); } @@ -339,7 +346,8 @@ class Signaling { .getTracks() .forEach((track) => pc.addTrack(track, _localStream)); - /* Unified-Plan: Simuclast + // Unified-Plan: Simuclast + /* await pc.addTransceiver( track: _localStream.getAudioTracks()[0], init: RTCRtpTransceiverInit( @@ -354,19 +362,32 @@ class Signaling { _localStream ], sendEncodings: [ - RTCRtpEncoding(rid: 'f'), + RTCRtpEncoding(rid: 'f', active: true), RTCRtpEncoding( rid: 'h', + active: true, scaleResolutionDownBy: 2.0, - maxBitrateBps: 150000, + maxBitrate: 150000, ), RTCRtpEncoding( rid: 'q', + active: true, scaleResolutionDownBy: 4.0, - maxBitrateBps: 100000, + maxBitrate: 100000, ), ]), - ); + );*/ + /* + var sender = pc.getSenders().find(s => s.track.kind == "video"); + var parameters = sender.getParameters(); + if(!parameters) + parameters = {}; + parameters.encodings = [ + { rid: "h", active: true, maxBitrate: 900000 }, + { rid: "m", active: true, maxBitrate: 300000, scaleResolutionDownBy: 2 }, + { rid: "l", active: true, maxBitrate: 100000, scaleResolutionDownBy: 4 } + ]; + sender.setParameters(parameters); */ } pc.onIceCandidate = (candidate) { @@ -423,15 +444,16 @@ class Signaling { } _createDataChannel(id, RTCPeerConnection pc, {label: 'fileTransfer'}) async { - RTCDataChannelInit dataChannelDict = new RTCDataChannelInit(); + RTCDataChannelInit dataChannelDict = new RTCDataChannelInit() + ..maxRetransmits = 30; RTCDataChannel channel = await pc.createDataChannel(label, dataChannelDict); _addDataChannel(id, channel); } _createOffer(String id, RTCPeerConnection pc, String media) async { try { - RTCSessionDescription s = await pc - .createOffer(media == 'data' ? _dc_constraints : _constraints); + RTCSessionDescription s = + await pc.createOffer(media == 'data' ? _dc_constraints : {}); pc.setLocalDescription(s); _send('offer', { 'to': id, @@ -447,8 +469,8 @@ class Signaling { _createAnswer(String id, RTCPeerConnection pc, media) async { try { - RTCSessionDescription s = await pc - .createAnswer(media == 'data' ? _dc_constraints : _constraints); + RTCSessionDescription s = + await pc.createAnswer(media == 'data' ? _dc_constraints : {}); pc.setLocalDescription(s); _send('answer', { 'to': id, diff --git a/pubspec.lock b/pubspec.lock deleted file mode 100644 index d14a732..0000000 --- a/pubspec.lock +++ /dev/null @@ -1,278 +0,0 @@ -# Generated by pub -# See https://dart.dev/tools/pub/glossary#lockfile -packages: - async: - dependency: transitive - description: - name: async - url: "https://pub.dartlang.org" - source: hosted - version: "2.4.1" - boolean_selector: - dependency: transitive - description: - name: boolean_selector - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" - charcode: - dependency: transitive - description: - name: charcode - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.3" - clock: - dependency: transitive - description: - name: clock - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.1" - collection: - dependency: transitive - description: - name: collection - url: "https://pub.dartlang.org" - source: hosted - version: "1.14.12" - cupertino_icons: - dependency: "direct main" - description: - name: cupertino_icons - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.3" - fake_async: - dependency: transitive - description: - name: fake_async - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - file: - dependency: transitive - description: - name: file - url: "https://pub.dartlang.org" - source: hosted - version: "5.2.1" - flutter: - dependency: "direct main" - description: flutter - source: sdk - version: "0.0.0" - flutter_test: - dependency: "direct dev" - description: flutter - source: sdk - version: "0.0.0" - flutter_web_plugins: - dependency: transitive - description: flutter - source: sdk - version: "0.0.0" - flutter_webrtc: - dependency: "direct main" - description: - name: flutter_webrtc - url: "https://pub.dartlang.org" - source: hosted - version: "0.2.8" - http: - dependency: "direct main" - description: - name: http - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.1" - http_parser: - dependency: transitive - description: - name: http_parser - url: "https://pub.dartlang.org" - source: hosted - version: "3.1.4" - intl: - dependency: transitive - description: - name: intl - url: "https://pub.dartlang.org" - source: hosted - version: "0.16.1" - matcher: - dependency: transitive - description: - name: matcher - url: "https://pub.dartlang.org" - source: hosted - version: "0.12.6" - meta: - dependency: transitive - description: - name: meta - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.8" - path: - dependency: transitive - description: - name: path - url: "https://pub.dartlang.org" - source: hosted - version: "1.7.0" - path_provider: - dependency: "direct main" - description: - name: path_provider - url: "https://pub.dartlang.org" - source: hosted - version: "1.6.11" - path_provider_linux: - dependency: transitive - description: - name: path_provider_linux - url: "https://pub.dartlang.org" - source: hosted - version: "0.0.1+2" - path_provider_macos: - dependency: "direct main" - description: - name: path_provider_macos - url: "https://pub.dartlang.org" - source: hosted - version: "0.0.4+3" - path_provider_platform_interface: - dependency: transitive - description: - name: path_provider_platform_interface - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.2" - pedantic: - dependency: transitive - description: - name: pedantic - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.0" - platform: - dependency: transitive - description: - name: platform - url: "https://pub.dartlang.org" - source: hosted - version: "2.2.1" - plugin_platform_interface: - dependency: transitive - description: - name: plugin_platform_interface - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.2" - process: - dependency: transitive - description: - name: process - url: "https://pub.dartlang.org" - source: hosted - version: "3.0.13" - shared_preferences: - dependency: "direct main" - description: - name: shared_preferences - url: "https://pub.dartlang.org" - source: hosted - version: "0.5.7+3" - shared_preferences_macos: - dependency: "direct main" - description: - name: shared_preferences_macos - url: "https://pub.dartlang.org" - source: hosted - version: "0.0.1+10" - shared_preferences_platform_interface: - dependency: transitive - description: - name: shared_preferences_platform_interface - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.4" - shared_preferences_web: - dependency: "direct main" - description: - name: shared_preferences_web - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.2+7" - sky_engine: - dependency: transitive - description: flutter - source: sdk - version: "0.0.99" - source_span: - dependency: transitive - description: - name: source_span - url: "https://pub.dartlang.org" - source: hosted - version: "1.7.0" - stack_trace: - dependency: transitive - description: - name: stack_trace - url: "https://pub.dartlang.org" - source: hosted - version: "1.9.3" - stream_channel: - dependency: transitive - description: - name: stream_channel - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.0" - string_scanner: - dependency: transitive - description: - name: string_scanner - url: "https://pub.dartlang.org" - source: hosted - version: "1.0.5" - term_glyph: - dependency: transitive - description: - name: term_glyph - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.0" - test_api: - dependency: transitive - description: - name: test_api - url: "https://pub.dartlang.org" - source: hosted - version: "0.2.16" - typed_data: - dependency: transitive - description: - name: typed_data - url: "https://pub.dartlang.org" - source: hosted - version: "1.1.6" - vector_math: - dependency: transitive - description: - name: vector_math - url: "https://pub.dartlang.org" - source: hosted - version: "2.0.8" - xdg_directories: - dependency: transitive - description: - name: xdg_directories - url: "https://pub.dartlang.org" - source: hosted - version: "0.1.0" -sdks: - dart: ">=2.7.0 <3.0.0" - flutter: ">=1.12.13+hotfix.5 <2.0.0" diff --git a/pubspec.yaml b/pubspec.yaml index 85e4a25..353884b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.0 + flutter_webrtc: ^0.5.0+1 shared_preferences: shared_preferences_macos: shared_preferences_web: From a3e5f20d06e32416b191bb192d6c24d2197f25f1 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Wed, 18 Nov 2020 15:44:39 +0800 Subject: [PATCH 24/69] update. --- lib/generated_plugin_registrant.dart | 16 ++++++++++++++++ lib/src/call_sample/call_sample.dart | 4 ++-- lib/src/call_sample/signaling.dart | 18 +++++------------- lib/src/utils/device_info_web.dart | 1 + lib/src/utils/websocket.dart | 10 ++++++---- pubspec.yaml | 2 +- test/widget_test.dart | 1 - 7 files changed, 31 insertions(+), 21 deletions(-) create mode 100644 lib/generated_plugin_registrant.dart diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart new file mode 100644 index 0000000..9f6808e --- /dev/null +++ b/lib/generated_plugin_registrant.dart @@ -0,0 +1,16 @@ +// +// Generated file. Do not edit. +// + +// ignore: unused_import +import 'dart:ui'; + +import 'package:shared_preferences_web/shared_preferences_web.dart'; + +import 'package:flutter_web_plugins/flutter_web_plugins.dart'; + +// ignore: public_member_api_docs +void registerPlugins(PluginRegistry registry) { + SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); + registry.registerMessageHandler(); +} diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index efcceb7..f5d42b3 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -94,9 +94,9 @@ class _CallSampleState extends State { } } - _invitePeer(context, peerId, use_screen) async { + _invitePeer(BuildContext context, String peerId, bool useScreen) async { if (_signaling != null && peerId != _selfId) { - _signaling.invite(peerId, 'video', use_screen); + _signaling.invite(peerId, 'video', useScreen); } } diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index a3463c5..9406c0e 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -74,15 +74,7 @@ class Signaling { ] }; - final Map _constraints = { - 'mandatory': { - 'OfferToReceiveAudio': true, - 'OfferToReceiveVideo': true, - }, - 'optional': [], - }; - - final Map _dc_constraints = { + final Map _dcConstraints = { 'mandatory': { 'OfferToReceiveAudio': false, 'OfferToReceiveVideo': false, @@ -312,7 +304,7 @@ class Signaling { await _socket.connect(); } - Future createStream(media, user_screen) async { + Future createStream(String media, bool userScreen) async { final Map mediaConstraints = { 'audio': true, 'video': { @@ -327,7 +319,7 @@ class Signaling { } }; - MediaStream stream = user_screen + MediaStream stream = userScreen ? await navigator.mediaDevices.getDisplayMedia(mediaConstraints) : await navigator.mediaDevices.getUserMedia(mediaConstraints); onLocalStream?.call(stream); @@ -453,7 +445,7 @@ class Signaling { _createOffer(String id, RTCPeerConnection pc, String media) async { try { RTCSessionDescription s = - await pc.createOffer(media == 'data' ? _dc_constraints : {}); + await pc.createOffer(media == 'data' ? _dcConstraints : {}); pc.setLocalDescription(s); _send('offer', { 'to': id, @@ -470,7 +462,7 @@ class Signaling { _createAnswer(String id, RTCPeerConnection pc, media) async { try { RTCSessionDescription s = - await pc.createAnswer(media == 'data' ? _dc_constraints : {}); + await pc.createAnswer(media == 'data' ? _dcConstraints : {}); pc.setLocalDescription(s); _send('answer', { 'to': id, diff --git a/lib/src/utils/device_info_web.dart b/lib/src/utils/device_info_web.dart index 0899668..8dbeba2 100644 --- a/lib/src/utils/device_info_web.dart +++ b/lib/src/utils/device_info_web.dart @@ -1,3 +1,4 @@ +// ignore: avoid_web_libraries_in_flutter import 'dart:html' as HTML; class DeviceInfo { diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index 4cd39f1..f44011d 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -38,8 +38,7 @@ class SimpleWebSocket { } close() { - if (_socket != null) - _socket.close(); + if (_socket != null) _socket.close(); } Future _connectForSelfSignedCert(url) async { @@ -49,11 +48,13 @@ class SimpleWebSocket { HttpClient client = HttpClient(context: SecurityContext()); client.badCertificateCallback = (X509Certificate cert, String host, int port) { - print('SimpleWebSocket: Allow self-signed certificate => $host:$port. '); + print( + 'SimpleWebSocket: Allow self-signed certificate => $host:$port. '); return true; }; - HttpClientRequest request = await client.getUrl(Uri.parse(url)); // form the correct url here + HttpClientRequest request = + await client.getUrl(Uri.parse(url)); // form the correct url here request.headers.add('Connection', 'Upgrade'); request.headers.add('Upgrade', 'websocket'); request.headers.add( @@ -61,6 +62,7 @@ class SimpleWebSocket { request.headers.add('Sec-WebSocket-Key', key.toLowerCase()); HttpClientResponse response = await request.close(); + // ignore: close_sinks Socket socket = await response.detachSocket(); var webSocket = WebSocket.fromUpgradedSocket( socket, diff --git a/pubspec.yaml b/pubspec.yaml index 353884b..85e4a25 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.0+1 + flutter_webrtc: ^0.5.0 shared_preferences: shared_preferences_macos: shared_preferences_web: diff --git a/test/widget_test.dart b/test/widget_test.dart index 93e3022..1fcb865 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -4,7 +4,6 @@ // find child widgets in the widget tree, read text, and verify that the values of widget properties // are correct. -import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:flutter_webrtc_demo/main.dart'; From 98b62494fe4273fd0d5ec52e8b4be161bde933f4 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Wed, 18 Nov 2020 15:53:38 +0800 Subject: [PATCH 25/69] update. --- lib/src/call_sample/call_sample.dart | 1 + lib/src/call_sample/data_channel_sample.dart | 1 + lib/src/call_sample/signaling.dart | 2 +- lib/src/utils/websocket_web.dart | 1 + 4 files changed, 4 insertions(+), 1 deletion(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index f5d42b3..50b6a68 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -23,6 +23,7 @@ class _CallSampleState extends State { bool _inCalling = false; final String serverIP; + // ignore: unused_element _CallSampleState({Key key, @required this.serverIP}); @override diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index b10ee1a..7774887 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -26,6 +26,7 @@ class _DataChannelSampleState extends State { RTCDataChannel _dataChannel; Timer _timer; var _text = ''; + // ignore: unused_element _DataChannelSampleState({Key key, @required this.serverIP}); @override diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 9406c0e..1172470 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -271,7 +271,7 @@ class Signaling { _iceServers = { 'iceServers': [ { - 'url': _turnCredential['uris'][0], + 'urls': _turnCredential['uris'][0], 'username': _turnCredential['username'], 'credential': _turnCredential['password'] }, diff --git a/lib/src/utils/websocket_web.dart b/lib/src/utils/websocket_web.dart index e33cf17..5af44ca 100644 --- a/lib/src/utils/websocket_web.dart +++ b/lib/src/utils/websocket_web.dart @@ -1,3 +1,4 @@ +// ignore: avoid_web_libraries_in_flutter import 'dart:html'; typedef void OnMessageCallback(dynamic msg); From ea278352097bef4266c6716d7a33e60a9af95396 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Fri, 20 Nov 2020 07:19:04 +0800 Subject: [PATCH 26/69] update. --- lib/src/call_sample/call_sample.dart | 6 +- lib/src/call_sample/data_channel_sample.dart | 6 +- lib/src/call_sample/signaling.dart | 78 +++++++++----------- lib/src/utils/websocket.dart | 8 +- lib/src/utils/websocket_web.dart | 12 +-- pubspec.yaml | 2 +- 6 files changed, 52 insertions(+), 60 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 50b6a68..5cd85ec 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -53,12 +53,12 @@ class _CallSampleState extends State { _signaling.onStateChange = (SignalingState state) { switch (state) { case SignalingState.CallStateNew: - this.setState(() { + setState(() { _inCalling = true; }); break; case SignalingState.CallStateBye: - this.setState(() { + setState(() { _localRenderer.srcObject = null; _remoteRenderer.srcObject = null; _inCalling = false; @@ -75,7 +75,7 @@ class _CallSampleState extends State { }; _signaling.onPeersUpdate = ((event) { - this.setState(() { + setState(() { _selfId = event['self']; _peers = event['peers']; }); diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 7774887..056794b 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -66,7 +66,7 @@ class _DataChannelSampleState extends State { switch (state) { case SignalingState.CallStateNew: { - this.setState(() { + setState(() { _inCalling = true; }); _timer = @@ -75,7 +75,7 @@ class _DataChannelSampleState extends State { } case SignalingState.CallStateBye: { - this.setState(() { + setState(() { _inCalling = false; }); if (_timer != null) { @@ -97,7 +97,7 @@ class _DataChannelSampleState extends State { }; _signaling.onPeersUpdate = ((event) { - this.setState(() { + setState(() { _selfId = event['self']; _peers = event['peers']; }); diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 1172470..6408c0c 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -45,6 +45,7 @@ class Signaling { MediaStream _localStream; List _remoteStreams = []; + SignalingStateCallback onStateChange; StreamStateCallback onLocalStream; StreamStateCallback onAddRemoteStream; @@ -63,7 +64,7 @@ class Signaling { 'username': 'change_to_real_user', 'credential': 'change_to_real_secret' }, - */ + */ ] }; @@ -82,7 +83,7 @@ class Signaling { 'optional': [], }; - Signaling(this._host); + Signaling(_host); close() { if (_localStream != null) { @@ -110,9 +111,9 @@ class Signaling { } void invite(String peerId, String media, bool useScreen) { - this._sessionId = this._selfId + '-' + peerId; + _sessionId = _selfId + '-' + peerId; - this.onStateChange?.call(SignalingState.CallStateNew); + onStateChange?.call(SignalingState.CallStateNew); _createPeerConnection(peerId, media, useScreen).then((pc) { _peerConnections[peerId] = pc; @@ -125,8 +126,8 @@ class Signaling { void bye() { _send('bye', { - 'session_id': this._sessionId, - 'from': this._selfId, + 'session_id': _sessionId, + 'from': _selfId, }); } @@ -138,11 +139,11 @@ class Signaling { case 'peers': { List peers = data; - if (this.onPeersUpdate != null) { + if (onPeersUpdate != null) { Map event = new Map(); event['self'] = _selfId; event['peers'] = peers; - this.onPeersUpdate(event); + onPeersUpdate?.call(event); } } break; @@ -152,7 +153,7 @@ class Signaling { var description = data['description']; var media = data['media']; var sessionId = data['session_id']; - this._sessionId = sessionId; + _sessionId = sessionId; onStateChange?.call(SignalingState.CallStateNew); @@ -161,7 +162,7 @@ class Signaling { await pc.setRemoteDescription(new RTCSessionDescription( description['sdp'], description['type'])); await _createAnswer(id, pc, media); - if (this._remoteCandidates.length > 0) { + if (_remoteCandidates.length > 0) { _remoteCandidates.forEach((candidate) async { await pc.addCandidate(candidate); }); @@ -202,17 +203,11 @@ class Signaling { var id = data; var pc = _peerConnections.remove(id); _dataChannels.remove(id); - - if (_localStream != null) { - _localStream.dispose(); - _localStream = null; - } - - if (pc != null) { - pc.close(); - } - this._sessionId = null; - this.onStateChange?.call(SignalingState.CallStateBye); + _localStream?.dispose(); + _localStream = null; + pc?.close(); + _sessionId = null; + onStateChange?.call(SignalingState.CallStateBye); } break; case 'bye': @@ -221,24 +216,18 @@ class Signaling { var sessionId = data['session_id']; print('bye: ' + sessionId); - if (_localStream != null) { - _localStream.dispose(); - _localStream = null; - } + _localStream?.dispose(); + _localStream = null; var pc = _peerConnections[to]; - if (pc != null) { - pc.close(); - _peerConnections.remove(to); - } + pc?.close(); + _peerConnections.remove(to); var dc = _dataChannels[to]; - if (dc != null) { - dc.close(); - _dataChannels.remove(to); - } + dc?.close(); + _dataChannels.remove(to); - this._sessionId = null; + _sessionId = null; onStateChange?.call(SignalingState.CallStateBye); } break; @@ -282,7 +271,7 @@ class Signaling { _socket.onOpen = () { print('onOpen'); - this?.onStateChange(SignalingState.ConnectionOpen); + onStateChange?.call(SignalingState.ConnectionOpen); _send('new', { 'name': DeviceInfo.label, 'id': _selfId, @@ -293,7 +282,7 @@ class Signaling { _socket.onMessage = (message) { print('Received data: ' + message); JsonDecoder decoder = new JsonDecoder(); - this.onMessage(decoder.convert(message)); + onMessage(decoder.convert(message)); }; _socket.onClose = (int code, String reason) { @@ -329,6 +318,7 @@ class Signaling { _createPeerConnection(String id, String media, bool screenSharing) async { if (media != 'data') _localStream = await createStream(media, screenSharing); + print(_iceServers); RTCPeerConnection pc = await createPeerConnection({ ..._iceServers, ...{'sdpSemantics': 'unified-plan'} @@ -336,7 +326,7 @@ class Signaling { if (media != 'data') { _localStream .getTracks() - .forEach((track) => pc.addTrack(track, _localStream)); + .forEach((track) async => await pc.addTrack(track, _localStream)); // Unified-Plan: Simuclast /* @@ -395,7 +385,7 @@ class Signaling { 'sdpMid': candidate.sdpMid, 'candidate': candidate.candidate, }, - 'session_id': this._sessionId, + 'session_id': _sessionId, }); }; @@ -414,7 +404,7 @@ class Signaling { }; pc.onRemoveStream = (stream) { - this.onRemoveRemoteStream?.call(stream); + onRemoveRemoteStream?.call(stream); _remoteStreams.removeWhere((it) { return (it.id == stream.id); }); @@ -429,7 +419,7 @@ class Signaling { _addDataChannel(id, RTCDataChannel channel) { channel.onDataChannelState = (e) {}; channel.onMessage = (RTCDataChannelMessage data) { - this.onDataChannelMessage?.call(channel, data); + onDataChannelMessage?.call(channel, data); }; _dataChannels[id] = channel; onDataChannel?.call(channel); @@ -446,12 +436,12 @@ class Signaling { try { RTCSessionDescription s = await pc.createOffer(media == 'data' ? _dcConstraints : {}); - pc.setLocalDescription(s); + await pc.setLocalDescription(s); _send('offer', { 'to': id, 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': this._sessionId, + 'session_id': _sessionId, 'media': media, }); } catch (e) { @@ -463,12 +453,12 @@ class Signaling { try { RTCSessionDescription s = await pc.createAnswer(media == 'data' ? _dcConstraints : {}); - pc.setLocalDescription(s); + await pc.setLocalDescription(s); _send('answer', { 'to': id, 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': this._sessionId, + 'session_id': _sessionId, }); } catch (e) { print(e.toString()); diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index f44011d..75684e0 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -19,14 +19,14 @@ class SimpleWebSocket { try { //_socket = await WebSocket.connect(_url); _socket = await _connectForSelfSignedCert(_url); - this?.onOpen(); + onOpen?.call(); _socket.listen((data) { - this?.onMessage(data); + onMessage?.call(data); }, onDone: () { - this?.onClose(_socket.closeCode, _socket.closeReason); + onClose?.call(_socket.closeCode, _socket.closeReason); }); } catch (e) { - this.onClose(500, e.toString()); + onClose?.call(500, e.toString()); } } diff --git a/lib/src/utils/websocket_web.dart b/lib/src/utils/websocket_web.dart index 5af44ca..e2108be 100644 --- a/lib/src/utils/websocket_web.dart +++ b/lib/src/utils/websocket_web.dart @@ -20,18 +20,18 @@ class SimpleWebSocket { try { _socket = WebSocket(_url); _socket.onOpen.listen((e) { - this?.onOpen(); + onOpen?.call(); }); _socket.onMessage.listen((e) { - this?.onMessage(e.data); + onMessage?.call(e.data); }); _socket.onClose.listen((e) { - this?.onClose(e.code, e.reason); + onClose?.call(e.code, e.reason); }); } catch (e) { - this?.onClose(500, e.toString()); + onClose?.call(500, e.toString()); } } @@ -45,6 +45,8 @@ class SimpleWebSocket { } close() { - if (_socket != null) _socket.close(); + if (_socket != null) { + _socket.close(); + } } } diff --git a/pubspec.yaml b/pubspec.yaml index 85e4a25..801f18b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -19,7 +19,7 @@ dependencies: # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.0 + flutter_webrtc: ^0.5.2 shared_preferences: shared_preferences_macos: shared_preferences_web: From 787e1369a427c3bfb42ff08ad02d542e51a56af6 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 26 Nov 2020 16:19:18 +0800 Subject: [PATCH 27/69] Migrate to embedding v2. --- android/app/src/main/AndroidManifest.xml | 6 +- .../flutterwebrtcdemo/MainActivity.java | 9 +-- .../plugins/GeneratedPluginRegistrant.java | 31 ++++----- pubspec.yaml | 64 ++----------------- 4 files changed, 21 insertions(+), 89 deletions(-) diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index a29bb70..c9e7a48 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -22,11 +22,13 @@ additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> + =2.6.0 <3.0.0" + sdk: ">=2.2.2 <3.0.0" dependencies: flutter: sdk: flutter - # The following adds the Cupertino Icons font to your application. - # Use with the CupertinoIcons class for iOS style icons. cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.2 - shared_preferences: - shared_preferences_macos: - shared_preferences_web: + flutter_webrtc: ^0.5.7 + shared_preferences: ^0.5.12 http: ^0.12.1 - - # Required for MediaRecorder example - path_provider: - path_provider_macos: + path_provider: ^1.6.24 dev_dependencies: flutter_test: sdk: flutter - -# For information on the generic Dart part of this file, see the -# following page: https://www.dartlang.org/tools/pub/pubspec - -# The following section is specific to Flutter. flutter: - - # The following line ensures that the Material Icons font is - # included with your application, so that you can use the icons in - # the material Icons class. - uses-material-design: true - - # To add assets to your application, add an assets section, like this: - # assets: - # - images/a_dot_burr.jpeg - # - images/a_dot_ham.jpeg - - # An image asset can refer to one or more resolution-specific "variants", see - # https://flutter.io/assets-and-images/#resolution-aware. - - # For details regarding adding assets from package dependencies, see - # https://flutter.io/assets-and-images/#from-packages - - # To add custom fonts to your application, 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 from package dependencies, - # see https://flutter.io/custom-fonts/#from-packages + uses-material-design: true \ No newline at end of file From f63e1cd7e1341f31b0511ff4a5065d0536aff5f6 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 26 Nov 2020 16:21:38 +0800 Subject: [PATCH 28/69] Refactoring call signaling. --- lib/main.dart | 9 +- lib/src/call_sample/call_sample.dart | 47 ++-- lib/src/call_sample/data_channel_sample.dart | 47 ++-- lib/src/call_sample/signaling.dart | 244 +++++++++++-------- 4 files changed, 198 insertions(+), 149 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 94fdced..f59c5ae 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -23,8 +23,9 @@ class _MyAppState extends State { List items; String _server = ''; SharedPreferences _prefs; - bool _datachannel = false; + + String get server => _server ?? 'demo.cloudwebrtc.com'; @override initState() { super.initState(); @@ -63,7 +64,7 @@ class _MyAppState extends State { _initData() async { _prefs = await SharedPreferences.getInstance(); setState(() { - _server = _prefs.getString('server') ?? 'demo.cloudwebrtc.com'; + _server = _prefs.getString('server'); }); } @@ -80,8 +81,8 @@ class _MyAppState extends State { context, MaterialPageRoute( builder: (BuildContext context) => _datachannel - ? DataChannelSample(ip: _server) - : CallSample(ip: _server))); + ? DataChannelSample(host: _server) + : CallSample(host: _server))); } } }); diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 5cd85ec..5405948 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -6,12 +6,12 @@ import 'package:flutter_webrtc/flutter_webrtc.dart'; class CallSample extends StatefulWidget { static String tag = 'call_sample'; - final String ip; + final String host; - CallSample({Key key, @required this.ip}) : super(key: key); + CallSample({Key key, @required this.host}) : super(key: key); @override - _CallSampleState createState() => _CallSampleState(serverIP: ip); + _CallSampleState createState() => _CallSampleState(); } class _CallSampleState extends State { @@ -21,10 +21,10 @@ class _CallSampleState extends State { RTCVideoRenderer _localRenderer = RTCVideoRenderer(); RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; - final String serverIP; + Session _session; // ignore: unused_element - _CallSampleState({Key key, @required this.serverIP}); + _CallSampleState({Key key}); @override initState() { @@ -48,29 +48,36 @@ class _CallSampleState extends State { void _connect() async { if (_signaling == null) { - _signaling = Signaling(serverIP)..connect(); + _signaling = Signaling(widget.host)..connect(); - _signaling.onStateChange = (SignalingState state) { + _signaling.onSignalingStateChange = (SignalingState state) { switch (state) { - case SignalingState.CallStateNew: + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; + + _signaling.onCallStateChange = (Session session, CallState state) { + switch (state) { + case CallState.CallStateNew: setState(() { + _session = session; _inCalling = true; }); break; - case SignalingState.CallStateBye: + case CallState.CallStateBye: setState(() { _localRenderer.srcObject = null; _remoteRenderer.srcObject = null; _inCalling = false; + _session = null; }); break; - case SignalingState.CallStateInvite: - case SignalingState.CallStateConnected: - case SignalingState.CallStateRinging: - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; + case CallState.CallStateInvite: + case CallState.CallStateConnected: + case CallState.CallStateRinging: } }; @@ -81,15 +88,15 @@ class _CallSampleState extends State { }); }); - _signaling.onLocalStream = ((stream) { + _signaling.onLocalStream = ((_, stream) { _localRenderer.srcObject = stream; }); - _signaling.onAddRemoteStream = ((stream) { + _signaling.onAddRemoteStream = ((_, stream) { _remoteRenderer.srcObject = stream; }); - _signaling.onRemoveRemoteStream = ((stream) { + _signaling.onRemoveRemoteStream = ((_, stream) { _remoteRenderer.srcObject = null; }); } @@ -103,7 +110,7 @@ class _CallSampleState extends State { _hangUp() { if (_signaling != null) { - _signaling.bye(); + _signaling.bye(_session.sid); } } diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 056794b..0dfda30 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -8,13 +8,12 @@ import 'package:flutter_webrtc/flutter_webrtc.dart'; class DataChannelSample extends StatefulWidget { static String tag = 'call_sample'; - final String ip; + final String host; - DataChannelSample({Key key, @required this.ip}) : super(key: key); + DataChannelSample({Key key, @required this.host}) : super(key: key); @override - _DataChannelSampleState createState() => - _DataChannelSampleState(serverIP: ip); + _DataChannelSampleState createState() => _DataChannelSampleState(); } class _DataChannelSampleState extends State { @@ -22,12 +21,12 @@ class _DataChannelSampleState extends State { List _peers; var _selfId; bool _inCalling = false; - final String serverIP; RTCDataChannel _dataChannel; + Session _session; Timer _timer; var _text = ''; // ignore: unused_element - _DataChannelSampleState({Key key, @required this.serverIP}); + _DataChannelSampleState({Key key}); @override initState() { @@ -46,9 +45,9 @@ class _DataChannelSampleState extends State { void _connect() async { if (_signaling == null) { - _signaling = Signaling(serverIP)..connect(); + _signaling = Signaling(widget.host)..connect(); - _signaling.onDataChannelMessage = (dc, RTCDataChannelMessage data) { + _signaling.onDataChannelMessage = (_, dc, RTCDataChannelMessage data) { setState(() { if (data.isBinary) { print('Got binary [' + data.binary.toString() + ']'); @@ -58,22 +57,32 @@ class _DataChannelSampleState extends State { }); }; - _signaling.onDataChannel = (channel) { + _signaling.onDataChannel = (_, channel) { _dataChannel = channel; }; - _signaling.onStateChange = (SignalingState state) { + _signaling.onSignalingStateChange = (SignalingState state) { switch (state) { - case SignalingState.CallStateNew: + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; + + _signaling.onCallStateChange = (Session session, CallState state) { + switch (state) { + case CallState.CallStateNew: { setState(() { + _session = session; _inCalling = true; }); _timer = Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); break; } - case SignalingState.CallStateBye: + case CallState.CallStateBye: { setState(() { _inCalling = false; @@ -83,16 +92,14 @@ class _DataChannelSampleState extends State { _timer = null; } _dataChannel = null; + _inCalling = false; + _session = null; _text = ''; break; } - case SignalingState.CallStateInvite: - case SignalingState.CallStateConnected: - case SignalingState.CallStateRinging: - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; + case CallState.CallStateInvite: + case CallState.CallStateConnected: + case CallState.CallStateRinging: } }; @@ -126,7 +133,7 @@ class _DataChannelSampleState extends State { _hangUp() { if (_signaling != null) { - _signaling.bye(); + _signaling.bye(_session.sid); } } diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 6408c0c..7ee8696 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -11,42 +11,53 @@ import '../utils/websocket.dart' import '../utils/turn.dart' if (dart.library.js) '../utils/turn_web.dart'; enum SignalingState { + ConnectionOpen, + ConnectionClosed, + ConnectionError, +} + +enum CallState { CallStateNew, CallStateRinging, CallStateInvite, CallStateConnected, CallStateBye, - ConnectionOpen, - ConnectionClosed, - ConnectionError, } /* * callbacks for Signaling API. */ typedef void SignalingStateCallback(SignalingState state); -typedef void StreamStateCallback(MediaStream stream); +typedef void CallStateCallback(Session session, CallState state); +typedef void StreamStateCallback(Session session, MediaStream stream); typedef void OtherEventCallback(dynamic event); typedef void DataChannelMessageCallback( - RTCDataChannel dc, RTCDataChannelMessage data); -typedef void DataChannelCallback(RTCDataChannel dc); + Session session, RTCDataChannel dc, RTCDataChannelMessage data); +typedef void DataChannelCallback(Session session, RTCDataChannel dc); + +class Session { + Session({this.sid, this.pid}); + String pid; + String sid; + RTCPeerConnection pc; + RTCDataChannel dc; + List remoteCandidates = []; +} class Signaling { JsonEncoder _encoder = new JsonEncoder(); String _selfId = randomNumeric(6); SimpleWebSocket _socket; - var _sessionId; var _host; var _port = 8086; - var _peerConnections = new Map(); - var _dataChannels = new Map(); - var _remoteCandidates = []; var _turnCredential; + Map _sessions = {}; MediaStream _localStream; List _remoteStreams = []; - SignalingStateCallback onStateChange; + SignalingStateCallback onSignalingStateChange; + CallStateCallback onCallStateChange; StreamStateCallback onLocalStream; StreamStateCallback onAddRemoteStream; StreamStateCallback onRemoveRemoteStream; @@ -83,17 +94,21 @@ class Signaling { 'optional': [], }; - Signaling(_host); + Signaling(this._host); - close() { + close() async { if (_localStream != null) { - _localStream.dispose(); + _localStream.getTracks().forEach((element) async { + await element.dispose(); + }); + await _localStream.dispose(); _localStream = null; } - _peerConnections.forEach((key, pc) { - pc.close(); + _sessions.forEach((key, sess) async { + await sess.pc.close(); }); + _sessions.clear(); if (_socket != null) _socket.close(); } @@ -110,25 +125,28 @@ class Signaling { } } - void invite(String peerId, String media, bool useScreen) { - _sessionId = _selfId + '-' + peerId; - - onStateChange?.call(SignalingState.CallStateNew); - - _createPeerConnection(peerId, media, useScreen).then((pc) { - _peerConnections[peerId] = pc; - if (media == 'data') { - _createDataChannel(peerId, pc); - } - _createOffer(peerId, pc, media); - }); + void invite(String peerId, String media, bool useScreen) async { + var sessionId = _selfId + '-' + peerId; + Session session = await _createSession( + peerId: peerId, + sessionId: sessionId, + media: media, + screenSharing: useScreen); + _sessions[sessionId] = session; + if (media == 'data') { + _createDataChannel(session); + } + _createOffer(session, media); + onCallStateChange?.call(session, CallState.CallStateNew); } - void bye() { + void bye(String sessionId) { _send('bye', { - 'session_id': _sessionId, + 'session_id': sessionId, 'from': _selfId, }); + + _stopSession(_sessions[sessionId]); } void onMessage(message) async { @@ -149,86 +167,71 @@ class Signaling { break; case 'offer': { - var id = data['from']; + var peerId = data['from']; var description = data['description']; var media = data['media']; var sessionId = data['session_id']; - _sessionId = sessionId; - - onStateChange?.call(SignalingState.CallStateNew); - - var pc = await _createPeerConnection(id, media, false); - _peerConnections[id] = pc; - await pc.setRemoteDescription(new RTCSessionDescription( + var session = _sessions[sessionId]; + var newSession = await _createSession( + session: session, + peerId: peerId, + sessionId: sessionId, + media: media, + screenSharing: false); + _sessions[sessionId] = newSession; + await newSession.pc.setRemoteDescription(new RTCSessionDescription( description['sdp'], description['type'])); - await _createAnswer(id, pc, media); - if (_remoteCandidates.length > 0) { - _remoteCandidates.forEach((candidate) async { - await pc.addCandidate(candidate); + await _createAnswer(newSession, media); + if (newSession.remoteCandidates.length > 0) { + newSession.remoteCandidates.forEach((candidate) async { + await newSession.pc.addCandidate(candidate); }); - _remoteCandidates.clear(); + newSession.remoteCandidates.clear(); } + onCallStateChange?.call(newSession, CallState.CallStateNew); } break; case 'answer': { - var id = data['from']; var description = data['description']; - - var pc = _peerConnections[id]; - if (pc != null) { - await pc.setRemoteDescription(new RTCSessionDescription( - description['sdp'], description['type'])); - } + var sessionId = data['session_id']; + var session = _sessions[sessionId]; + session?.pc?.setRemoteDescription(new RTCSessionDescription( + description['sdp'], description['type'])); } break; case 'candidate': { - var id = data['from']; + var peerId = data['from']; var candidateMap = data['candidate']; - var pc = _peerConnections[id]; + var sessionId = data['session_id']; + var session = _sessions[sessionId]; RTCIceCandidate candidate = new RTCIceCandidate( candidateMap['candidate'], candidateMap['sdpMid'], candidateMap['sdpMLineIndex']); - if (pc != null) { - await pc.addCandidate(candidate); + + if (session != null) { + await session.pc.addCandidate(candidate); } else { - _remoteCandidates.add(candidate); + _sessions[sessionId] = Session(pid: peerId, sid: sessionId) + ..remoteCandidates.add(candidate); } } break; case 'leave': { - var id = data; - var pc = _peerConnections.remove(id); - _dataChannels.remove(id); - _localStream?.dispose(); - _localStream = null; - pc?.close(); - _sessionId = null; - onStateChange?.call(SignalingState.CallStateBye); + var peerId = data as String; + _cleanSession(peerId); } break; case 'bye': { - var to = data['to']; var sessionId = data['session_id']; print('bye: ' + sessionId); - - _localStream?.dispose(); - _localStream = null; - - var pc = _peerConnections[to]; - pc?.close(); - _peerConnections.remove(to); - - var dc = _dataChannels[to]; - dc?.close(); - _dataChannels.remove(to); - - _sessionId = null; - onStateChange?.call(SignalingState.CallStateBye); + var session = _sessions.remove(sessionId); + onCallStateChange?.call(session, CallState.CallStateBye); + _stopSession(session); } break; case 'keepalive': @@ -271,7 +274,7 @@ class Signaling { _socket.onOpen = () { print('onOpen'); - onStateChange?.call(SignalingState.ConnectionOpen); + onSignalingStateChange?.call(SignalingState.ConnectionOpen); _send('new', { 'name': DeviceInfo.label, 'id': _selfId, @@ -287,7 +290,7 @@ class Signaling { _socket.onClose = (int code, String reason) { print('Closed by server [$code => $reason]!'); - onStateChange?.call(SignalingState.ConnectionClosed); + onSignalingStateChange?.call(SignalingState.ConnectionClosed); }; await _socket.connect(); @@ -311,11 +314,17 @@ class Signaling { MediaStream stream = userScreen ? await navigator.mediaDevices.getDisplayMedia(mediaConstraints) : await navigator.mediaDevices.getUserMedia(mediaConstraints); - onLocalStream?.call(stream); + onLocalStream?.call(null, stream); return stream; } - _createPeerConnection(String id, String media, bool screenSharing) async { + _createSession( + {Session session, + String peerId, + String sessionId, + String media, + bool screenSharing}) async { + var newSession = session ?? Session(sid: sessionId, pid: peerId); if (media != 'data') _localStream = await createStream(media, screenSharing); print(_iceServers); @@ -378,14 +387,14 @@ class Signaling { return; } _send('candidate', { - 'to': id, + 'to': peerId, 'from': _selfId, 'candidate': { 'sdpMLineIndex': candidate.sdpMlineIndex, 'sdpMid': candidate.sdpMid, 'candidate': candidate.candidate, }, - 'session_id': _sessionId, + 'session_id': sessionId, }); }; @@ -399,49 +408,52 @@ class Signaling { // Unified-Plan pc.onTrack = (event) { if (event.track.kind == 'video') { - onAddRemoteStream?.call(event.streams[0]); + onAddRemoteStream?.call(newSession, event.streams[0]); } }; pc.onRemoveStream = (stream) { - onRemoveRemoteStream?.call(stream); + onRemoveRemoteStream?.call(newSession, stream); _remoteStreams.removeWhere((it) { return (it.id == stream.id); }); }; pc.onDataChannel = (channel) { - _addDataChannel(id, channel); + _addDataChannel(newSession, channel); }; - return pc; + + newSession.pc = pc; + return newSession; } - _addDataChannel(id, RTCDataChannel channel) { + _addDataChannel(Session session, RTCDataChannel channel) { channel.onDataChannelState = (e) {}; channel.onMessage = (RTCDataChannelMessage data) { - onDataChannelMessage?.call(channel, data); + onDataChannelMessage?.call(session, channel, data); }; - _dataChannels[id] = channel; - onDataChannel?.call(channel); + session.dc = channel; + onDataChannel?.call(session, channel); } - _createDataChannel(id, RTCPeerConnection pc, {label: 'fileTransfer'}) async { + _createDataChannel(Session session, {label: 'fileTransfer'}) async { RTCDataChannelInit dataChannelDict = new RTCDataChannelInit() ..maxRetransmits = 30; - RTCDataChannel channel = await pc.createDataChannel(label, dataChannelDict); - _addDataChannel(id, channel); + RTCDataChannel channel = + await session.pc.createDataChannel(label, dataChannelDict); + _addDataChannel(session, channel); } - _createOffer(String id, RTCPeerConnection pc, String media) async { + _createOffer(Session session, String media) async { try { RTCSessionDescription s = - await pc.createOffer(media == 'data' ? _dcConstraints : {}); - await pc.setLocalDescription(s); + await session.pc.createOffer(media == 'data' ? _dcConstraints : {}); + await session.pc.setLocalDescription(s); _send('offer', { - 'to': id, + 'to': session.pid, 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': _sessionId, + 'session_id': session.sid, 'media': media, }); } catch (e) { @@ -449,16 +461,16 @@ class Signaling { } } - _createAnswer(String id, RTCPeerConnection pc, media) async { + _createAnswer(Session session, String media) async { try { RTCSessionDescription s = - await pc.createAnswer(media == 'data' ? _dcConstraints : {}); - await pc.setLocalDescription(s); + await session.pc.createAnswer(media == 'data' ? _dcConstraints : {}); + await session.pc.setLocalDescription(s); _send('answer', { - 'to': id, + 'to': session.pid, 'from': _selfId, 'description': {'sdp': s.sdp, 'type': s.type}, - 'session_id': _sessionId, + 'session_id': session.sid, }); } catch (e) { print(e.toString()); @@ -471,4 +483,26 @@ class Signaling { request["data"] = data; _socket.send(_encoder.convert(request)); } + + _cleanSession(String peerId) { + var session; + _sessions.removeWhere((String key, Session session) { + var ids = key.split('-'); + return peerId == ids[0] || peerId == ids[1]; + }); + if (session != null) { + onCallStateChange?.call(session, CallState.CallStateBye); + } + } + + void _stopSession(Session session) async { + _localStream?.getTracks()?.forEach((element) async { + await element.dispose(); + }); + await _localStream?.dispose(); + _localStream = null; + + await session?.pc?.close(); + await session?.dc?.close(); + } } From 47e9155948da97004b45e6b4c6d9f157a32c7ab0 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 26 Nov 2020 16:31:22 +0800 Subject: [PATCH 29/69] update. --- lib/main.dart | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index f59c5ae..b7934e3 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -23,9 +23,8 @@ class _MyAppState extends State { List items; String _server = ''; SharedPreferences _prefs; - bool _datachannel = false; - String get server => _server ?? 'demo.cloudwebrtc.com'; + bool _datachannel = false; @override initState() { super.initState(); @@ -64,7 +63,7 @@ class _MyAppState extends State { _initData() async { _prefs = await SharedPreferences.getInstance(); setState(() { - _server = _prefs.getString('server'); + _server = _prefs.getString('server') ?? 'demo.cloudwebrtc.com'; }); } From 542793152c431ef12ef7d8f19a116438bef9687b Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Fri, 27 Nov 2020 09:29:33 +0800 Subject: [PATCH 30/69] Optimize signaling. --- lib/src/call_sample/random_string.dart | 12 ++-- lib/src/call_sample/settings.dart | 7 +- lib/src/call_sample/signaling.dart | 92 ++++++++++++++------------ 3 files changed, 58 insertions(+), 53 deletions(-) diff --git a/lib/src/call_sample/random_string.dart b/lib/src/call_sample/random_string.dart index 2e45184..73c2f08 100644 --- a/lib/src/call_sample/random_string.dart +++ b/lib/src/call_sample/random_string.dart @@ -32,8 +32,8 @@ const UPPER_ALPHA_END = 90; /// Generates a random integer where [from] <= [to]. int randomBetween(int from, int to) { - if (from > to) throw new Exception('$from cannot be > $to'); - var rand = new Random(); + if (from > to) throw Exception('$from cannot be > $to'); + var rand = Random(); return ((to - from) * rand.nextDouble()).toInt() + from; } @@ -41,8 +41,8 @@ int randomBetween(int from, int to) { /// between ascii [from] to [to]. /// Defaults to characters of ascii '!' to '~'. String randomString(int length, {int from: ASCII_START, int to: ASCII_END}) { - return new String.fromCharCodes( - new List.generate(length, (index) => randomBetween(from, to))); + return String.fromCharCodes( + List.generate(length, (index) => randomBetween(from, to))); } /// Generates a random string of [length] with only numeric characters. @@ -71,7 +71,7 @@ String randomAlphaNumeric(int length) { /// Merge [a] with [b] and scramble characters. String randomMerge(String a, String b) { - var mergedCodeUnits = new List.from("$a$b".codeUnits); + var mergedCodeUnits = List.from("$a$b".codeUnits); mergedCodeUnits.shuffle(); - return new String.fromCharCodes(mergedCodeUnits); + return String.fromCharCodes(mergedCodeUnits); }*/ diff --git a/lib/src/call_sample/settings.dart b/lib/src/call_sample/settings.dart index 37c6831..fe9c953 100644 --- a/lib/src/call_sample/settings.dart +++ b/lib/src/call_sample/settings.dart @@ -5,7 +5,7 @@ class CallSettings extends StatefulWidget { static String tag = 'call_settings'; @override - _CallSettingsState createState() => new _CallSettingsState(); + _CallSettingsState createState() => _CallSettingsState(); } class _CallSettingsState extends State { @@ -17,7 +17,6 @@ class _CallSettingsState extends State { @override deactivate() { super.deactivate(); - } @override @@ -28,9 +27,7 @@ class _CallSettingsState extends State { ), body: OrientationBuilder( builder: (context, orientation) { - return Center( - child: Text("settings") - ); + return Center(child: Text("settings")); }, ), ); diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 7ee8696..904c507 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -45,14 +45,16 @@ class Session { } class Signaling { - JsonEncoder _encoder = new JsonEncoder(); + Signaling(this._host); + + JsonEncoder _encoder = JsonEncoder(); + JsonDecoder _decoder = JsonDecoder(); String _selfId = randomNumeric(6); SimpleWebSocket _socket; var _host; var _port = 8086; var _turnCredential; Map _sessions = {}; - MediaStream _localStream; List _remoteStreams = []; @@ -94,21 +96,8 @@ class Signaling { 'optional': [], }; - Signaling(this._host); - close() async { - if (_localStream != null) { - _localStream.getTracks().forEach((element) async { - await element.dispose(); - }); - await _localStream.dispose(); - _localStream = null; - } - - _sessions.forEach((key, sess) async { - await sess.pc.close(); - }); - _sessions.clear(); + await _cleanSessions(); if (_socket != null) _socket.close(); } @@ -146,7 +135,7 @@ class Signaling { 'from': _selfId, }); - _stopSession(_sessions[sessionId]); + _closeSession(_sessions[sessionId]); } void onMessage(message) async { @@ -158,7 +147,7 @@ class Signaling { { List peers = data; if (onPeersUpdate != null) { - Map event = new Map(); + Map event = Map(); event['self'] = _selfId; event['peers'] = peers; onPeersUpdate?.call(event); @@ -179,8 +168,8 @@ class Signaling { media: media, screenSharing: false); _sessions[sessionId] = newSession; - await newSession.pc.setRemoteDescription(new RTCSessionDescription( - description['sdp'], description['type'])); + await newSession.pc.setRemoteDescription( + RTCSessionDescription(description['sdp'], description['type'])); await _createAnswer(newSession, media); if (newSession.remoteCandidates.length > 0) { newSession.remoteCandidates.forEach((candidate) async { @@ -196,8 +185,8 @@ class Signaling { var description = data['description']; var sessionId = data['session_id']; var session = _sessions[sessionId]; - session?.pc?.setRemoteDescription(new RTCSessionDescription( - description['sdp'], description['type'])); + session?.pc?.setRemoteDescription( + RTCSessionDescription(description['sdp'], description['type'])); } break; case 'candidate': @@ -206,13 +195,15 @@ class Signaling { var candidateMap = data['candidate']; var sessionId = data['session_id']; var session = _sessions[sessionId]; - RTCIceCandidate candidate = new RTCIceCandidate( - candidateMap['candidate'], - candidateMap['sdpMid'], - candidateMap['sdpMLineIndex']); + RTCIceCandidate candidate = RTCIceCandidate(candidateMap['candidate'], + candidateMap['sdpMid'], candidateMap['sdpMLineIndex']); if (session != null) { - await session.pc.addCandidate(candidate); + if (session.pc != null) { + await session.pc.addCandidate(candidate); + } else { + session.remoteCandidates.add(candidate); + } } else { _sessions[sessionId] = Session(pid: peerId, sid: sessionId) ..remoteCandidates.add(candidate); @@ -222,7 +213,7 @@ class Signaling { case 'leave': { var peerId = data as String; - _cleanSession(peerId); + _closeSessionByPeerId(peerId); } break; case 'bye': @@ -231,7 +222,7 @@ class Signaling { print('bye: ' + sessionId); var session = _sessions.remove(sessionId); onCallStateChange?.call(session, CallState.CallStateBye); - _stopSession(session); + _closeSession(session); } break; case 'keepalive': @@ -244,7 +235,7 @@ class Signaling { } } - void connect() async { + Future connect() async { var url = 'https://$_host:$_port/ws'; _socket = SimpleWebSocket(url); @@ -284,8 +275,7 @@ class Signaling { _socket.onMessage = (message) { print('Received data: ' + message); - JsonDecoder decoder = new JsonDecoder(); - onMessage(decoder.convert(message)); + onMessage(_decoder.convert(message)); }; _socket.onClose = (int code, String reason) { @@ -318,7 +308,7 @@ class Signaling { return stream; } - _createSession( + Future _createSession( {Session session, String peerId, String sessionId, @@ -427,7 +417,7 @@ class Signaling { return newSession; } - _addDataChannel(Session session, RTCDataChannel channel) { + void _addDataChannel(Session session, RTCDataChannel channel) { channel.onDataChannelState = (e) {}; channel.onMessage = (RTCDataChannelMessage data) { onDataChannelMessage?.call(session, channel, data); @@ -436,15 +426,16 @@ class Signaling { onDataChannel?.call(session, channel); } - _createDataChannel(Session session, {label: 'fileTransfer'}) async { - RTCDataChannelInit dataChannelDict = new RTCDataChannelInit() + Future _createDataChannel(Session session, + {label: 'fileTransfer'}) async { + RTCDataChannelInit dataChannelDict = RTCDataChannelInit() ..maxRetransmits = 30; RTCDataChannel channel = await session.pc.createDataChannel(label, dataChannelDict); _addDataChannel(session, channel); } - _createOffer(Session session, String media) async { + Future _createOffer(Session session, String media) async { try { RTCSessionDescription s = await session.pc.createOffer(media == 'data' ? _dcConstraints : {}); @@ -461,7 +452,7 @@ class Signaling { } } - _createAnswer(Session session, String media) async { + Future _createAnswer(Session session, String media) async { try { RTCSessionDescription s = await session.pc.createAnswer(media == 'data' ? _dcConstraints : {}); @@ -478,24 +469,41 @@ class Signaling { } _send(event, data) { - var request = new Map(); + var request = Map(); request["type"] = event; request["data"] = data; _socket.send(_encoder.convert(request)); } - _cleanSession(String peerId) { + Future _cleanSessions() async { + if (_localStream != null) { + _localStream.getTracks().forEach((element) async { + await element.dispose(); + }); + await _localStream.dispose(); + _localStream = null; + } + _sessions.forEach((key, sess) async { + await sess?.pc?.close(); + await sess?.dc?.close(); + }); + _sessions.clear(); + } + + void _closeSessionByPeerId(String peerId) { var session; - _sessions.removeWhere((String key, Session session) { + _sessions.removeWhere((String key, Session sess) { var ids = key.split('-'); + session = sess; return peerId == ids[0] || peerId == ids[1]; }); if (session != null) { + _closeSession(session); onCallStateChange?.call(session, CallState.CallStateBye); } } - void _stopSession(Session session) async { + Future _closeSession(Session session) async { _localStream?.getTracks()?.forEach((element) async { await element.dispose(); }); From 69fe49faedc56ce0e58ccce9aaf7e1df37d3c3df Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Fri, 22 Jan 2021 14:44:01 +0000 Subject: [PATCH 31/69] Update dependency gradle to v6.8.1 --- android/gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 69897b2..f839b8d 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-all.zip From 54771c5317fcd3a04481e0866fbb67ebe6c16256 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Fri, 29 Jan 2021 10:06:27 +0800 Subject: [PATCH 32/69] Add windows support. --- lib/generated_plugin_registrant.dart | 16 -- pubspec.yaml | 4 +- windows/.gitignore | 17 ++ windows/CMakeLists.txt | 95 +++++++ windows/flutter/CMakeLists.txt | 101 ++++++++ .../flutter/generated_plugin_registrant.cc | 12 + windows/flutter/generated_plugin_registrant.h | 13 + windows/flutter/generated_plugins.cmake | 16 ++ windows/runner/CMakeLists.txt | 18 ++ windows/runner/Runner.rc | 121 +++++++++ windows/runner/flutter_window.cpp | 64 +++++ windows/runner/flutter_window.h | 39 +++ windows/runner/main.cpp | 42 +++ windows/runner/resource.h | 16 ++ windows/runner/resources/app_icon.ico | Bin 0 -> 33772 bytes windows/runner/run_loop.cpp | 66 +++++ windows/runner/run_loop.h | 40 +++ windows/runner/runner.exe.manifest | 20 ++ windows/runner/utils.cpp | 64 +++++ windows/runner/utils.h | 19 ++ windows/runner/win32_window.cpp | 245 ++++++++++++++++++ windows/runner/win32_window.h | 98 +++++++ 22 files changed, 1108 insertions(+), 18 deletions(-) delete mode 100644 lib/generated_plugin_registrant.dart create mode 100644 windows/.gitignore create mode 100644 windows/CMakeLists.txt create mode 100644 windows/flutter/CMakeLists.txt create mode 100644 windows/flutter/generated_plugin_registrant.cc create mode 100644 windows/flutter/generated_plugin_registrant.h create mode 100644 windows/flutter/generated_plugins.cmake create mode 100644 windows/runner/CMakeLists.txt create mode 100644 windows/runner/Runner.rc create mode 100644 windows/runner/flutter_window.cpp create mode 100644 windows/runner/flutter_window.h create mode 100644 windows/runner/main.cpp create mode 100644 windows/runner/resource.h create mode 100644 windows/runner/resources/app_icon.ico create mode 100644 windows/runner/run_loop.cpp create mode 100644 windows/runner/run_loop.h create mode 100644 windows/runner/runner.exe.manifest create mode 100644 windows/runner/utils.cpp create mode 100644 windows/runner/utils.h create mode 100644 windows/runner/win32_window.cpp create mode 100644 windows/runner/win32_window.h diff --git a/lib/generated_plugin_registrant.dart b/lib/generated_plugin_registrant.dart deleted file mode 100644 index 9f6808e..0000000 --- a/lib/generated_plugin_registrant.dart +++ /dev/null @@ -1,16 +0,0 @@ -// -// Generated file. Do not edit. -// - -// ignore: unused_import -import 'dart:ui'; - -import 'package:shared_preferences_web/shared_preferences_web.dart'; - -import 'package:flutter_web_plugins/flutter_web_plugins.dart'; - -// ignore: public_member_api_docs -void registerPlugins(PluginRegistry registry) { - SharedPreferencesPlugin.registerWith(registry.registrarFor(SharedPreferencesPlugin)); - registry.registerMessageHandler(); -} diff --git a/pubspec.yaml b/pubspec.yaml index 24b888e..13dc535 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -10,7 +10,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.7 + flutter_webrtc: ^0.5.8 shared_preferences: ^0.5.12 http: ^0.12.1 path_provider: ^1.6.24 @@ -20,4 +20,4 @@ dev_dependencies: sdk: flutter flutter: - uses-material-design: true \ No newline at end of file + uses-material-design: true diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100644 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100644 index 0000000..69533fb --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,95 @@ +cmake_minimum_required(VERSION 3.15) +project(flutter_webrtc_demo LANGUAGES CXX) + +set(BINARY_NAME "flutter_webrtc_demo") + +cmake_policy(SET CMP0063 NEW) + +set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") + +# Configure build options. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() + +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") + +# Flutter library and tool build rules. +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100644 index 0000000..c7a8c76 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,101 @@ +cmake_minimum_required(VERSION 3.15) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100644 index 0000000..60a2e52 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,12 @@ +// +// Generated file. Do not edit. +// + +#include "generated_plugin_registrant.h" + +#include + +void RegisterPlugins(flutter::PluginRegistry* registry) { + FlutterWebRTCPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("FlutterWebRTCPlugin")); +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100644 index 0000000..9846246 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,13 @@ +// +// Generated file. Do not edit. +// + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100644 index 0000000..345025b --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,16 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST + flutter_webrtc +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100644 index 0000000..977e38b --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,18 @@ +cmake_minimum_required(VERSION 3.15) +project(runner LANGUAGES CXX) + +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "run_loop.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) +apply_standard_settings(${BINARY_NAME}) +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100644 index 0000000..b24b959 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#ifdef FLUTTER_BUILD_NUMBER +#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER +#else +#define VERSION_AS_NUMBER 1,0,0 +#endif + +#ifdef FLUTTER_BUILD_NAME +#define VERSION_AS_STRING #FLUTTER_BUILD_NAME +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "com.cloudwebrtc" "\0" + VALUE "FileDescription", "A new Flutter project." "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "flutter_webrtc_demo" "\0" + VALUE "LegalCopyright", "Copyright (C) 2021 com.cloudwebrtc. All rights reserved." "\0" + VALUE "OriginalFilename", "flutter_webrtc_demo.exe" "\0" + VALUE "ProductName", "flutter_webrtc_demo" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100644 index 0000000..c422723 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,64 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project) + : run_loop_(run_loop), project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + run_loop_->RegisterFlutterInstance(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + run_loop_->UnregisterFlutterInstance(flutter_controller_->engine()); + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opporutunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100644 index 0000000..b663ddd --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,39 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "run_loop.h" +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow driven by the |run_loop|, hosting a + // Flutter view running |project|. + explicit FlutterWindow(RunLoop* run_loop, + const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The run loop driving events for this window. + RunLoop* run_loop_; + + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100644 index 0000000..ec13ebc --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,42 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "run_loop.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + RunLoop run_loop; + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(&run_loop, project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"flutter_webrtc_demo", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + run_loop.Run(); + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100644 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100644 index 0000000000000000000000000000000000000000..c04e20caf6370ebb9253ad831cc31de4a9c965f6 GIT binary patch literal 33772 zcmeHQc|26z|35SKE&G-*mXah&B~fFkXr)DEO&hIfqby^T&>|8^_Ub8Vp#`BLl3lbZ zvPO!8k!2X>cg~Elr=IVxo~J*a`+9wR=A83c-k-DFd(XM&UI1VKCqM@V;DDtJ09WB} zRaHKiW(GT00brH|0EeTeKVbpbGZg?nK6-j827q-+NFM34gXjqWxJ*a#{b_apGN<-L_m3#8Z26atkEn& ze87Bvv^6vVmM+p+cQ~{u%=NJF>#(d;8{7Q{^rWKWNtf14H}>#&y7$lqmY6xmZryI& z($uy?c5-+cPnt2%)R&(KIWEXww>Cnz{OUpT>W$CbO$h1= z#4BPMkFG1Y)x}Ui+WXr?Z!w!t_hjRq8qTaWpu}FH{MsHlU{>;08goVLm{V<&`itk~ zE_Ys=D(hjiy+5=?=$HGii=Y5)jMe9|wWoD_K07(}edAxh`~LBorOJ!Cf@f{_gNCC| z%{*04ViE!#>@hc1t5bb+NO>ncf@@Dv01K!NxH$3Eg1%)|wLyMDF8^d44lV!_Sr}iEWefOaL z8f?ud3Q%Sen39u|%00W<#!E=-RpGa+H8}{ulxVl4mwpjaU+%2pzmi{3HM)%8vb*~-M9rPUAfGCSos8GUXp02|o~0BTV2l#`>>aFV&_P$ejS;nGwSVP8 zMbOaG7<7eKD>c12VdGH;?2@q7535sa7MN*L@&!m?L`ASG%boY7(&L5imY#EQ$KrBB z4@_tfP5m50(T--qv1BJcD&aiH#b-QC>8#7Fx@3yXlonJI#aEIi=8&ChiVpc#N=5le zM*?rDIdcpawoc5kizv$GEjnveyrp3sY>+5_R5;>`>erS%JolimF=A^EIsAK zsPoVyyUHCgf0aYr&alx`<)eb6Be$m&`JYSuBu=p8j%QlNNp$-5C{b4#RubPb|CAIS zGE=9OFLP7?Hgc{?k45)84biT0k&-C6C%Q}aI~q<(7BL`C#<6HyxaR%!dFx7*o^laG z=!GBF^cwK$IA(sn9y6>60Rw{mYRYkp%$jH z*xQM~+bp)G$_RhtFPYx2HTsWk80+p(uqv9@I9)y{b$7NK53rYL$ezbmRjdXS?V}fj zWxX_feWoLFNm3MG7pMUuFPs$qrQWO9!l2B(SIuy2}S|lHNbHzoE+M2|Zxhjq9+Ws8c{*}x^VAib7SbxJ*Q3EnY5lgI9 z=U^f3IW6T=TWaVj+2N%K3<%Un;CF(wUp`TC&Y|ZjyFu6co^uqDDB#EP?DV5v_dw~E zIRK*BoY9y-G_ToU2V_XCX4nJ32~`czdjT!zwme zGgJ0nOk3U4@IE5JwtM}pwimLjk{ln^*4HMU%Fl4~n(cnsLB}Ja-jUM>xIB%aY;Nq8 z)Fp8dv1tkqKanv<68o@cN|%thj$+f;zGSO7H#b+eMAV8xH$hLggtt?O?;oYEgbq@= zV(u9bbd12^%;?nyk6&$GPI%|+<_mEpJGNfl*`!KV;VfmZWw{n{rnZ51?}FDh8we_L z8OI9nE31skDqJ5Oa_ybn7|5@ui>aC`s34p4ZEu6-s!%{uU45$Zd1=p$^^dZBh zu<*pDDPLW+c>iWO$&Z_*{VSQKg7=YEpS3PssPn1U!lSm6eZIho*{@&20e4Y_lRklKDTUCKI%o4Pc<|G^Xgu$J^Q|B87U;`c1zGwf^-zH*VQ^x+i^OUWE0yd z;{FJq)2w!%`x7yg@>uGFFf-XJl4H`YtUG%0slGKOlXV`q?RP>AEWg#x!b{0RicxGhS!3$p7 zij;{gm!_u@D4$Ox%>>bPtLJ> zwKtYz?T_DR1jN>DkkfGU^<#6sGz|~p*I{y`aZ>^Di#TC|Z!7j_O1=Wo8thuit?WxR zh9_S>kw^{V^|g}HRUF=dcq>?q(pHxw!8rx4dC6vbQVmIhmICF#zU!HkHpQ>9S%Uo( zMw{eC+`&pb=GZRou|3;Po1}m46H6NGd$t<2mQh}kaK-WFfmj_66_17BX0|j-E2fe3Jat}ijpc53 zJV$$;PC<5aW`{*^Z6e5##^`Ed#a0nwJDT#Qq~^e8^JTA=z^Kl>La|(UQ!bI@#ge{Dzz@61p-I)kc2?ZxFt^QQ}f%ldLjO*GPj(5)V9IyuUakJX=~GnTgZ4$5!3E=V#t`yOG4U z(gphZB6u2zsj=qNFLYShhg$}lNpO`P9xOSnO*$@@UdMYES*{jJVj|9z-}F^riksLK zbsU+4-{281P9e2UjY6tse^&a)WM1MFw;p#_dHhWI7p&U*9TR0zKdVuQed%6{otTsq z$f~S!;wg#Bd9kez=Br{m|66Wv z#g1xMup<0)H;c2ZO6su_ii&m8j&+jJz4iKnGZ&wxoQX|5a>v&_e#6WA!MB_4asTxLRGQCC5cI(em z%$ZfeqP>!*q5kU>a+BO&ln=4Jm>Ef(QE8o&RgLkk%2}4Tf}U%IFP&uS7}&|Q-)`5< z+e>;s#4cJ-z%&-^&!xsYx777Wt(wZY9(3(avmr|gRe4cD+a8&!LY`1^T?7x{E<=kdY9NYw>A;FtTvQ=Y&1M%lyZPl$ss1oY^Sl8we}n}Aob#6 zl4jERwnt9BlSoWb@3HxYgga(752Vu6Y)k4yk9u~Kw>cA5&LHcrvn1Y-HoIuFWg~}4 zEw4bR`mXZQIyOAzo)FYqg?$5W<;^+XX%Uz61{-L6@eP|lLH%|w?g=rFc;OvEW;^qh z&iYXGhVt(G-q<+_j}CTbPS_=K>RKN0&;dubh0NxJyDOHFF;<1k!{k#7b{|Qok9hac z;gHz}6>H6C6RnB`Tt#oaSrX0p-j-oRJ;_WvS-qS--P*8}V943RT6kou-G=A+7QPGQ z!ze^UGxtW3FC0$|(lY9^L!Lx^?Q8cny(rR`es5U;-xBhphF%_WNu|aO<+e9%6LuZq zt(0PoagJG<%hyuf;te}n+qIl_Ej;czWdc{LX^pS>77s9t*2b4s5dvP_!L^3cwlc)E!(!kGrg~FescVT zZCLeua3f4;d;Tk4iXzt}g}O@nlK3?_o91_~@UMIl?@77Qc$IAlLE95#Z=TES>2E%z zxUKpK{_HvGF;5%Q7n&vA?`{%8ohlYT_?(3A$cZSi)MvIJygXD}TS-3UwyUxGLGiJP znblO~G|*uA^|ac8E-w#}uBtg|s_~s&t>-g0X%zIZ@;o_wNMr_;{KDg^O=rg`fhDZu zFp(VKd1Edj%F zWHPl+)FGj%J1BO3bOHVfH^3d1F{)*PL&sRX`~(-Zy3&9UQX)Z;c51tvaI2E*E7!)q zcz|{vpK7bjxix(k&6=OEIBJC!9lTkUbgg?4-yE{9+pFS)$Ar@vrIf`D0Bnsed(Cf? zObt2CJ>BKOl>q8PyFO6w)+6Iz`LW%T5^R`U_NIW0r1dWv6OY=TVF?N=EfA(k(~7VBW(S;Tu5m4Lg8emDG-(mOSSs=M9Q&N8jc^Y4&9RqIsk(yO_P(mcCr}rCs%1MW1VBrn=0-oQN(Xj!k%iKV zb%ricBF3G4S1;+8lzg5PbZ|$Se$)I=PwiK=cDpHYdov2QO1_a-*dL4KUi|g&oh>(* zq$<`dQ^fat`+VW?m)?_KLn&mp^-@d=&7yGDt<=XwZZC=1scwxO2^RRI7n@g-1o8ps z)&+et_~)vr8aIF1VY1Qrq~Xe``KJrQSnAZ{CSq3yP;V*JC;mmCT6oRLSs7=GA?@6g zUooM}@tKtx(^|aKK8vbaHlUQqwE0}>j&~YlN3H#vKGm@u)xxS?n9XrOWUfCRa< z`20Fld2f&;gg7zpo{Adh+mqNntMc-D$N^yWZAZRI+u1T1zWHPxk{+?vcS1D>08>@6 zLhE@`gt1Y9mAK6Z4p|u(5I%EkfU7rKFSM=E4?VG9tI;a*@?6!ey{lzN5=Y-!$WFSe z&2dtO>^0@V4WRc#L&P%R(?@KfSblMS+N+?xUN$u3K4Ys%OmEh+tq}fnU}i>6YHM?< zlnL2gl~sF!j!Y4E;j3eIU-lfa`RsOL*Tt<%EFC0gPzoHfNWAfKFIKZN8}w~(Yi~=q z>=VNLO2|CjkxP}RkutxjV#4fWYR1KNrPYq5ha9Wl+u>ipsk*I(HS@iLnmGH9MFlTU zaFZ*KSR0px>o+pL7BbhB2EC1%PJ{67_ z#kY&#O4@P=OV#-79y_W>Gv2dxL*@G7%LksNSqgId9v;2xJ zrh8uR!F-eU$NMx@S*+sk=C~Dxr9Qn7TfWnTupuHKuQ$;gGiBcU>GF5sWx(~4IP3`f zWE;YFO*?jGwYh%C3X<>RKHC-DZ!*r;cIr}GLOno^3U4tFSSoJp%oHPiSa%nh=Zgn% z14+8v@ygy0>UgEN1bczD6wK45%M>psM)y^)IfG*>3ItX|TzV*0i%@>L(VN!zdKb8S?Qf7BhjNpziA zR}?={-eu>9JDcl*R=OP9B8N$IcCETXah9SUDhr{yrld{G;PnCWRsPD7!eOOFBTWUQ=LrA_~)mFf&!zJX!Oc-_=kT<}m|K52 z)M=G#;p;Rdb@~h5D{q^K;^fX-m5V}L%!wVC2iZ1uu401Ll}#rocTeK|7FAeBRhNdQ zCc2d^aQnQp=MpOmak60N$OgS}a;p(l9CL`o4r(e-nN}mQ?M&isv-P&d$!8|1D1I(3-z!wi zTgoo)*Mv`gC?~bm?S|@}I|m-E2yqPEvYybiD5azInexpK8?9q*$9Yy9-t%5jU8~ym zgZDx>!@ujQ=|HJnwp^wv-FdD{RtzO9SnyfB{mH_(c!jHL*$>0o-(h(eqe*ZwF6Lvu z{7rkk%PEqaA>o+f{H02tzZ@TWy&su?VNw43! z-X+rN`6llvpUms3ZiSt)JMeztB~>9{J8SPmYs&qohxdYFi!ra8KR$35Zp9oR)eFC4 zE;P31#3V)n`w$fZ|4X-|%MX`xZDM~gJyl2W;O$H25*=+1S#%|53>|LyH za@yh+;325%Gq3;J&a)?%7X%t@WXcWL*BaaR*7UEZad4I8iDt7^R_Fd`XeUo256;sAo2F!HcIQKk;h})QxEsPE5BcKc7WyerTchgKmrfRX z!x#H_%cL#B9TWAqkA4I$R^8{%do3Y*&(;WFmJ zU7Dih{t1<{($VtJRl9|&EB?|cJ)xse!;}>6mSO$o5XIx@V|AA8ZcoD88ZM?C*;{|f zZVmf94_l1OmaICt`2sTyG!$^UeTHx9YuUP!omj(r|7zpm5475|yXI=rR>>fteLI+| z)MoiGho0oEt=*J(;?VY0QzwCqw@cVm?d7Y!z0A@u#H?sCJ*ecvyhj& z-F77lO;SH^dmf?L>3i>?Z*U}Em4ZYV_CjgfvzYsRZ+1B!Uo6H6mbS<-FFL`ytqvb& zE7+)2ahv-~dz(Hs+f})z{*4|{)b=2!RZK;PWwOnO=hG7xG`JU5>bAvUbdYd_CjvtHBHgtGdlO+s^9ca^Bv3`t@VRX2_AD$Ckg36OcQRF zXD6QtGfHdw*hx~V(MV-;;ZZF#dJ-piEF+s27z4X1qi5$!o~xBnvf=uopcn7ftfsZc zy@(PuOk`4GL_n(H9(E2)VUjqRCk9kR?w)v@xO6Jm_Mx})&WGEl=GS0#)0FAq^J*o! zAClhvoTsNP*-b~rN{8Yym3g{01}Ep^^Omf=SKqvN?{Q*C4HNNAcrowIa^mf+3PRy! z*_G-|3i8a;+q;iP@~Of_$(vtFkB8yOyWt2*K)vAn9El>=D;A$CEx6b*XF@4y_6M+2 zpeW`RHoI_p(B{%(&jTHI->hmNmZjHUj<@;7w0mx3&koy!2$@cfX{sN19Y}euYJFn& z1?)+?HCkD0MRI$~uB2UWri})0bru_B;klFdwsLc!ne4YUE;t41JqfG# zZJq6%vbsdx!wYeE<~?>o4V`A3?lN%MnKQ`z=uUivQN^vzJ|C;sdQ37Qn?;lpzg})y z)_2~rUdH}zNwX;Tp0tJ78+&I=IwOQ-fl30R79O8@?Ub8IIA(6I`yHn%lARVL`%b8+ z4$8D-|MZZWxc_)vu6@VZN!HsI$*2NOV&uMxBNzIbRgy%ob_ zhwEH{J9r$!dEix9XM7n&c{S(h>nGm?el;gaX0@|QnzFD@bne`el^CO$yXC?BDJ|Qg z+y$GRoR`?ST1z^e*>;!IS@5Ovb7*RlN>BV_UC!7E_F;N#ky%1J{+iixp(dUJj93aK zzHNN>R-oN7>kykHClPnoPTIj7zc6KM(Pnlb(|s??)SMb)4!sMHU^-ntJwY5Big7xv zb1Ew`Xj;|D2kzGja*C$eS44(d&RMU~c_Y14V9_TLTz0J#uHlsx`S6{nhsA0dWZ#cG zJ?`fO50E>*X4TQLv#nl%3GOk*UkAgt=IY+u0LNXqeln3Z zv$~&Li`ZJOKkFuS)dJRA>)b_Da%Q~axwA_8zNK{BH{#}#m}zGcuckz}riDE-z_Ms> zR8-EqAMcfyGJCtvTpaUVQtajhUS%c@Yj}&6Zz;-M7MZzqv3kA7{SuW$oW#=0az2wQ zg-WG@Vb4|D`pl~Il54N7Hmsauc_ne-a!o5#j3WaBBh@Wuefb!QJIOn5;d)%A#s+5% zuD$H=VNux9bE-}1&bcYGZ+>1Fo;3Z@e&zX^n!?JK*adSbONm$XW9z;Q^L>9U!}Toj2WdafJ%oL#h|yWWwyAGxzfrAWdDTtaKl zK4`5tDpPg5>z$MNv=X0LZ0d6l%D{(D8oT@+w0?ce$DZ6pv>{1&Ok67Ix1 zH}3=IEhPJEhItCC8E=`T`N5(k?G=B4+xzZ?<4!~ ze~z6Wk9!CHTI(0rLJ4{JU?E-puc;xusR?>G?;4vt;q~iI9=kDL=z0Rr%O$vU`30X$ zDZRFyZ`(omOy@u|i6h;wtJlP;+}$|Ak|k2dea7n?U1*$T!sXqqOjq^NxLPMmk~&qI zYg0W?yK8T(6+Ea+$YyspKK?kP$+B`~t3^Pib_`!6xCs32!i@pqXfFV6PmBIR<-QW= zN8L{pt0Vap0x`Gzn#E@zh@H)0FfVfA_Iu4fjYZ+umO1LXIbVc$pY+E234u)ttcrl$ z>s92z4vT%n6cMb>=XT6;l0+9e(|CZG)$@C7t7Z7Ez@a)h)!hyuV&B5K%%)P5?Lk|C zZZSVzdXp{@OXSP0hoU-gF8s8Um(#xzjP2Vem zec#-^JqTa&Y#QJ>-FBxd7tf`XB6e^JPUgagB8iBSEps;92KG`!#mvVcPQ5yNC-GEG zTiHEDYfH+0O15}r^+ z#jxj=@x8iNHWALe!P3R67TwmhItn**0JwnzSV2O&KE8KcT+0hWH^OPD1pwiuyx=b@ zNf5Jh0{9X)8;~Es)$t@%(3!OnbY+`@?i{mGX7Yy}8T_*0a6g;kaFPq;*=px5EhO{Cp%1kI<0?*|h8v!6WnO3cCJRF2-CRrU3JiLJnj@6;L)!0kWYAc_}F{2P))3HmCrz zQ&N&gE70;`!6*eJ4^1IR{f6j4(-l&X!tjHxkbHA^Zhrnhr9g{exN|xrS`5Pq=#Xf& zG%P=#ra-TyVFfgW%cZo5OSIwFL9WtXAlFOa+ubmI5t*3=g#Y zF%;70p5;{ZeFL}&}yOY1N1*Q;*<(kTB!7vM$QokF)yr2FlIU@$Ph58$Bz z0J?xQG=MlS4L6jA22eS42g|9*9pX@$#*sUeM(z+t?hr@r5J&D1rx}2pW&m*_`VDCW zUYY@v-;bAO0HqoAgbbiGGC<=ryf96}3pouhy3XJrX+!!u*O_>Si38V{uJmQ&USptX zKp#l(?>%^7;2%h(q@YWS#9;a!JhKlkR#Vd)ERILlgu!Hr@jA@V;sk4BJ-H#p*4EqC zDGjC*tl=@3Oi6)Bn^QwFpul18fpkbpg0+peH$xyPBqb%`$OUhPKyWb32o7clB*9Z< zN=i~NLjavrLtwgJ01bufP+>p-jR2I95|TpmKpQL2!oV>g(4RvS2pK4*ou%m(h6r3A zX#s&`9LU1ZG&;{CkOK!4fLDTnBys`M!vuz>Q&9OZ0hGQl!~!jSDg|~s*w52opC{sB ze|Cf2luD(*G13LcOAGA!s2FjSK8&IE5#W%J25w!vM0^VyQM!t)inj&RTiJ!wXzFgz z3^IqzB7I0L$llljsGq})thBy9UOyjtFO_*hYM_sgcMk>44jeH0V1FDyELc{S1F-;A zS;T^k^~4biG&V*Irq}O;e}j$$+E_#G?HKIn05iP3j|87TkGK~SqG!-KBg5+mN(aLm z8ybhIM`%C19UX$H$KY6JgXbY$0AT%rEpHC;u`rQ$Y=rxUdsc5*Kvc8jaYaO$^)cI6){P6K0r)I6DY4Wr4&B zLQUBraey#0HV|&c4v7PVo3n$zHj99(TZO^3?Ly%C4nYvJTL9eLBLHsM3WKKD>5!B` zQ=BsR3aR6PD(Fa>327E2HAu5TM~Wusc!)>~(gM)+3~m;92Jd;FnSib=M5d6;;5{%R zb4V7DEJ0V!CP-F*oU?gkc>ksUtAYP&V4ND5J>J2^jt*vcFflQWCrB&fLdT%O59PVJ zhid#toR=FNgD!q3&r8#wEBr`!wzvQu5zX?Q>nlSJ4i@WC*CN*-xU66F^V5crWevQ9gsq$I@z1o(a=k7LL~ z7m_~`o;_Ozha1$8Q}{WBehvAlO4EL60y5}8GDrZ< zXh&F}71JbW2A~8KfEWj&UWV#4+Z4p`b{uAj4&WC zha`}X@3~+Iz^WRlOHU&KngK>#j}+_o@LdBC1H-`gT+krWX3-;!)6?{FBp~%20a}FL zFP9%Emqcwa#(`=G>BBZ0qZDQhmZKJg_g8<=bBFKWr!dyg(YkpE+|R*SGpDVU!+VlU zFC54^DLv}`qa%49T>nNiA9Q7Ips#!Xx90tCU2gvK`(F+GPcL=J^>No{)~we#o@&mUb6c$ zCc*<|NJBk-#+{j9xkQ&ujB zI~`#kN~7W!f*-}wkG~Ld!JqZ@tK}eeSnsS5J1fMFXm|`LJx&}5`@dK3W^7#Wnm+_P zBZkp&j1fa2Y=eIjJ0}gh85jt43kaIXXv?xmo@eHrka!Z|vQv12HN#+!I5E z`(fbuW>gFiJL|uXJ!vKt#z3e3HlVdboH7;e#i3(2<)Fg-I@BR!qY#eof3MFZ&*Y@l zI|KJf&ge@p2Dq09Vu$$Qxb7!}{m-iRk@!)%KL)txi3;~Z4Pb}u@GsW;ELiWeG9V51 znX#}B&4Y2E7-H=OpNE@q{%hFLxwIpBF2t{vPREa8_{linXT;#1vMRWjOzLOP$-hf( z>=?$0;~~PnkqY;~K{EM6Vo-T(0K{A0}VUGmu*hR z{tw3hvBN%N3G3Yw`X5Te+F{J`(3w1s3-+1EbnFQKcrgrX1Jqvs@ADGe%M0s$EbK$$ zK)=y=upBc6SjGYAACCcI=Y*6Fi8_jgwZlLxD26fnQfJmb8^gHRN5(TemhX@0e=vr> zg`W}6U>x6VhoA3DqsGGD9uL1DhB3!OXO=k}59TqD@(0Nb{)Ut_luTioK_>7wjc!5C zIr@w}b`Fez3)0wQfKl&bae7;PcTA7%?f2xucM0G)wt_KO!Ewx>F~;=BI0j=Fb4>pp zv}0R^xM4eti~+^+gE$6b81p(kwzuDti(-K9bc|?+pJEl@H+jSYuxZQV8rl8 zjp@M{#%qItIUFN~KcO9Hed*`$5A-2~pAo~K&<-Q+`9`$CK>rzqAI4w~$F%vs9s{~x zg4BP%Gy*@m?;D6=SRX?888Q6peF@_4Z->8wAH~Cn!R$|Hhq2cIzFYqT_+cDourHbY z0qroxJnrZ4Gh+Ay+F`_c%+KRT>y3qw{)89?=hJ@=KO=@ep)aBJ$c!JHfBMJpsP*3G za7|)VJJ8B;4?n{~ldJF7%jmb`-ftIvNd~ekoufG(`K(3=LNc;HBY& z(lp#q8XAD#cIf}k49zX_i`*fO+#!zKA&%T3j@%)R+#yag067CU%yUEe47>wzGU8^` z1EXFT^@I!{J!F8!X?S6ph8J=gUi5tl93*W>7}_uR<2N2~e}FaG?}KPyugQ=-OGEZs z!GBoyYY+H*ANn4?Z)X4l+7H%`17i5~zRlRIX?t)6_eu=g2Q`3WBhxSUeea+M-S?RL zX9oBGKn%a!H+*hx4d2(I!gsi+@SQK%<{X22M~2tMulJoa)0*+z9=-YO+;DFEm5eE1U9b^B(Z}2^9!Qk`!A$wUE z7$Ar5?NRg2&G!AZqnmE64eh^Anss3i!{}%6@Et+4rr!=}!SBF8eZ2*J3ujCWbl;3; z48H~goPSv(8X61fKKdpP!Z7$88NL^Z?j`!^*I?-P4X^pMxyWz~@$(UeAcTSDd(`vO z{~rc;9|GfMJcApU3k}22a!&)k4{CU!e_ny^Y3cO;tOvOMKEyWz!vG(Kp*;hB?d|R3`2X~=5a6#^o5@qn?J-bI8Ppip{-yG z!k|VcGsq!jF~}7DMr49Wap-s&>o=U^T0!Lcy}!(bhtYsPQy z4|EJe{12QL#=c(suQ89Mhw9<`bui%nx7Nep`C&*M3~vMEACmcRYYRGtANq$F%zh&V zc)cEVeHz*Z1N)L7k-(k3np#{GcDh2Q@ya0YHl*n7fl*ZPAsbU-a94MYYtA#&!c`xGIaV;yzsmrjfieTEtqB_WgZp2*NplHx=$O{M~2#i_vJ{ps-NgK zQsxKK_CBM2PP_je+Xft`(vYfXXgIUr{=PA=7a8`2EHk)Ym2QKIforz# tySWtj{oF3N9@_;i*Fv5S)9x^z=nlWP>jpp-9)52ZmLVA=i*%6g{{fxOO~wEK literal 0 HcmV?d00001 diff --git a/windows/runner/run_loop.cpp b/windows/runner/run_loop.cpp new file mode 100644 index 0000000..2d6636a --- /dev/null +++ b/windows/runner/run_loop.cpp @@ -0,0 +1,66 @@ +#include "run_loop.h" + +#include + +#include + +RunLoop::RunLoop() {} + +RunLoop::~RunLoop() {} + +void RunLoop::Run() { + bool keep_running = true; + TimePoint next_flutter_event_time = TimePoint::clock::now(); + while (keep_running) { + std::chrono::nanoseconds wait_duration = + std::max(std::chrono::nanoseconds(0), + next_flutter_event_time - TimePoint::clock::now()); + ::MsgWaitForMultipleObjects( + 0, nullptr, FALSE, static_cast(wait_duration.count() / 1000), + QS_ALLINPUT); + bool processed_events = false; + MSG message; + // All pending Windows messages must be processed; MsgWaitForMultipleObjects + // won't return again for items left in the queue after PeekMessage. + while (::PeekMessage(&message, nullptr, 0, 0, PM_REMOVE)) { + processed_events = true; + if (message.message == WM_QUIT) { + keep_running = false; + break; + } + ::TranslateMessage(&message); + ::DispatchMessage(&message); + // Allow Flutter to process messages each time a Windows message is + // processed, to prevent starvation. + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + // If the PeekMessage loop didn't run, process Flutter messages. + if (!processed_events) { + next_flutter_event_time = + std::min(next_flutter_event_time, ProcessFlutterMessages()); + } + } +} + +void RunLoop::RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.insert(flutter_instance); +} + +void RunLoop::UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance) { + flutter_instances_.erase(flutter_instance); +} + +RunLoop::TimePoint RunLoop::ProcessFlutterMessages() { + TimePoint next_event_time = TimePoint::max(); + for (auto instance : flutter_instances_) { + std::chrono::nanoseconds wait_duration = instance->ProcessMessages(); + if (wait_duration != std::chrono::nanoseconds::max()) { + next_event_time = + std::min(next_event_time, TimePoint::clock::now() + wait_duration); + } + } + return next_event_time; +} diff --git a/windows/runner/run_loop.h b/windows/runner/run_loop.h new file mode 100644 index 0000000..000d362 --- /dev/null +++ b/windows/runner/run_loop.h @@ -0,0 +1,40 @@ +#ifndef RUNNER_RUN_LOOP_H_ +#define RUNNER_RUN_LOOP_H_ + +#include + +#include +#include + +// A runloop that will service events for Flutter instances as well +// as native messages. +class RunLoop { + public: + RunLoop(); + ~RunLoop(); + + // Prevent copying + RunLoop(RunLoop const&) = delete; + RunLoop& operator=(RunLoop const&) = delete; + + // Runs the run loop until the application quits. + void Run(); + + // Registers the given Flutter instance for event servicing. + void RegisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + // Unregisters the given Flutter instance from event servicing. + void UnregisterFlutterInstance( + flutter::FlutterEngine* flutter_instance); + + private: + using TimePoint = std::chrono::steady_clock::time_point; + + // Processes all currently pending messages for registered Flutter instances. + TimePoint ProcessFlutterMessages(); + + std::set flutter_instances_; +}; + +#endif // RUNNER_RUN_LOOP_H_ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100644 index 0000000..c977c4a --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100644 index 0000000..d19bdbb --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + if (target_length == 0) { + return std::string(); + } + std::string utf8_string; + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100644 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100644 index 0000000..c10f08d --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100644 index 0000000..17ba431 --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_ From 6129876a52b3d9326f6b126e4940c1567ebb6675 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Fri, 29 Jan 2021 10:25:46 +0800 Subject: [PATCH 33/69] Fix issue for windows. i --- lib/src/call_sample/signaling.dart | 41 ++++++++++++++++++------------ windows/flutter/CMakeLists.txt | 1 + 2 files changed, 26 insertions(+), 16 deletions(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 904c507..e526e57 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -67,6 +67,9 @@ class Signaling { DataChannelMessageCallback onDataChannelMessage; DataChannelCallback onDataChannel; + String get sdpSemantics => + WebRTC.platformIsWindows ? 'plan-b' : 'unified-plan'; + Map _iceServers = { 'iceServers': [ {'url': 'stun:stun.l.google.com:19302'}, @@ -320,12 +323,30 @@ class Signaling { print(_iceServers); RTCPeerConnection pc = await createPeerConnection({ ..._iceServers, - ...{'sdpSemantics': 'unified-plan'} + ...{'sdpSemantics': sdpSemantics} }, _config); if (media != 'data') { - _localStream - .getTracks() - .forEach((track) async => await pc.addTrack(track, _localStream)); + switch (sdpSemantics) { + case 'plan-b': + pc.onAddStream = (MediaStream stream) { + onAddRemoteStream?.call(newSession, stream); + _remoteStreams.add(stream); + }; + await pc.addStream(_localStream); + break; + case 'unified-plan': + + // Unified-Plan + pc.onTrack = (event) { + if (event.track.kind == 'video') { + onAddRemoteStream?.call(newSession, event.streams[0]); + } + }; + _localStream.getTracks().forEach((track) { + pc.addTrack(track, _localStream); + }); + break; + } // Unified-Plan: Simuclast /* @@ -390,18 +411,6 @@ class Signaling { pc.onIceConnectionState = (state) {}; - //pc.onAddStream = (stream) { - // onAddRemoteStream?.call(stream); - // _remoteStreams.add(stream); - //}; - - // Unified-Plan - pc.onTrack = (event) { - if (event.track.kind == 'video') { - onAddRemoteStream?.call(newSession, event.streams[0]); - } - }; - pc.onRemoveStream = (stream) { onRemoveRemoteStream?.call(newSession, stream); _remoteStreams.removeWhere((it) { diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt index c7a8c76..744f08a 100644 --- a/windows/flutter/CMakeLists.txt +++ b/windows/flutter/CMakeLists.txt @@ -91,6 +91,7 @@ add_custom_command( ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" windows-x64 $ + VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" From 780bbba68c154fd3a81f7d7fa55617a72986c54a Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Sun, 7 Feb 2021 12:19:23 +0800 Subject: [PATCH 34/69] Install stalebot. --- .github/stale.yml | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 .github/stale.yml diff --git a/.github/stale.yml b/.github/stale.yml new file mode 100644 index 0000000..dc90e5a --- /dev/null +++ b/.github/stale.yml @@ -0,0 +1,17 @@ +# Number of days of inactivity before an issue becomes stale +daysUntilStale: 60 +# Number of days of inactivity before a stale issue is closed +daysUntilClose: 7 +# Issues with these labels will never be considered stale +exemptLabels: + - pinned + - security +# Label to use when marking an issue as stale +staleLabel: wontfix +# Comment to post when marking an issue as stale. Set to `false` to disable +markComment: > + This issue has been automatically marked as stale because it has not had + recent activity. It will be closed if no further activity occurs. Thank you + for your contributions. +# Comment to post when closing a stale issue. Set to `false` to disable +closeComment: false From 9c654f7adecf02c70f3b6646cfcece11e43c201e Mon Sep 17 00:00:00 2001 From: Ham3D Date: Mon, 8 Feb 2021 12:07:27 +0330 Subject: [PATCH 35/69] Change the deprecated switch camera method --- lib/src/call_sample/signaling.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index e526e57..287bf2f 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -106,7 +106,7 @@ class Signaling { void switchCamera() { if (_localStream != null) { - _localStream.getVideoTracks()[0].switchCamera(); + Helper.switchCamera(_localStream.getVideoTracks()[0]); } } From 66ec6a18409eca5d4cdfdcf81e829b962e624b9e Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 22 Feb 2021 17:08:26 +0000 Subject: [PATCH 36/69] Update dependency gradle to v6.8.3 --- android/gradle/wrapper/gradle-wrapper.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index f839b8d..05f3529 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.1-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-all.zip From cd5e2b85180905f498949bd08ff5b9251dd07400 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Mon, 22 Feb 2021 22:37:48 +0000 Subject: [PATCH 37/69] Update dependency path_provider to v2 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 13dc535..bf139b1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -13,7 +13,7 @@ dependencies: flutter_webrtc: ^0.5.8 shared_preferences: ^0.5.12 http: ^0.12.1 - path_provider: ^1.6.24 + path_provider: ^2.0.0 dev_dependencies: flutter_test: From 4a66c95489e77193a9822f82a43e312be326f648 Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 23 Feb 2021 01:08:51 +0000 Subject: [PATCH 38/69] Update dependency shared_preferences to v2 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 13dc535..88889a0 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: cupertino_icons: ^1.0.0 flutter_webrtc: ^0.5.8 - shared_preferences: ^0.5.12 + shared_preferences: ^2.0.0 http: ^0.12.1 path_provider: ^1.6.24 From cc9c5dee0c5a78512898ba5f99bcb0160ff10b9c Mon Sep 17 00:00:00 2001 From: Renovate Bot Date: Tue, 23 Feb 2021 04:22:03 +0000 Subject: [PATCH 39/69] Update dependency http to ^0.13.0 --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 88889a0..9936f2a 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -12,7 +12,7 @@ dependencies: cupertino_icons: ^1.0.0 flutter_webrtc: ^0.5.8 shared_preferences: ^2.0.0 - http: ^0.12.1 + http: ^0.13.0 path_provider: ^1.6.24 dev_dependencies: From db8bffd43578857eb7723be10e53a271c0e79016 Mon Sep 17 00:00:00 2001 From: ColleSerre Date: Tue, 23 Mar 2021 19:08:10 +0100 Subject: [PATCH 40/69] http.get takes a uri as an argument but was served an unparsed string --- lib/src/utils/turn_web.dart | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/src/utils/turn_web.dart b/lib/src/utils/turn_web.dart index 63c16e9..bf2ea7a 100644 --- a/lib/src/utils/turn_web.dart +++ b/lib/src/utils/turn_web.dart @@ -3,11 +3,11 @@ import 'package:http/http.dart' as http; Future getTurnCredential(String host, int port) async { var url = 'https://$host:$port/api/turn?service=turn&username=flutter-webrtc'; - final res = await http.get(url); - if (res.statusCode == 200) { - var data = json.decode(res.body); - print('getTurnCredential:response => $data.'); - return data; - } - return {}; - } \ No newline at end of file + final res = await http.get(Uri.parse(url)); + if (res.statusCode == 200) { + var data = json.decode(res.body); + print('getTurnCredential:response => $data.'); + return data; + } + return {}; +} From 07c0ecd11a1b52209d46579430e8ac9b0d792b58 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Wed, 5 May 2021 19:26:14 +0800 Subject: [PATCH 41/69] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index e3bcf7a..96c8d11 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ # flutter-webrtc-demo + [![slack](https://img.shields.io/badge/join-us%20on%20slack-gray.svg?longCache=true&logo=slack&colorB=brightgreen)](https://join.slack.com/t/flutterwebrtc/shared_invite/zt-q83o7y1s-FExGLWEvtkPKM8ku_F8cEQ) + Flutter WebRTC plugin Demo Online Demo: https://demo.cloudwebrtc.com:8086/ From fbe19ba592a2c76725e8e1b4ec43bea39cb7c442 Mon Sep 17 00:00:00 2001 From: milochen0418 Date: Tue, 11 May 2021 16:06:38 +0800 Subject: [PATCH 42/69] re-generate Podfile to fit lastest version for XCode, Mac, flutter and cocoapod --- ios/Podfile | 77 ++++++++++------------------------------------------- 1 file changed, 14 insertions(+), 63 deletions(-) diff --git a/ios/Podfile b/ios/Podfile index 2a3a960..41d619a 100644 --- a/ios/Podfile +++ b/ios/Podfile @@ -10,78 +10,29 @@ project 'Runner', { 'Release' => :release, } -def parse_KV_file(file, separator='=') - file_abs_path = File.expand_path(file) - if !File.exists? file_abs_path - return []; +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" end - generated_key_values = {} - skip_line_start_symbols = ["#", "/"] - File.foreach(file_abs_path) do |line| - next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ } - plugin = line.split(pattern=separator) - if plugin.length == 2 - podname = plugin[0].strip() - path = plugin[1].strip() - podpath = File.expand_path("#{path}", file_abs_path) - generated_key_values[podname] = podpath - else - puts "Invalid plugin specification: #{line}" - end - end - generated_key_values -end - -target 'Runner' do - # Flutter Pod - - copied_flutter_dir = File.join(__dir__, 'Flutter') - copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework') - copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec') - unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path) - # Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet. - # That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration. - # CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist. - generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig') - unless File.exist?(generated_xcode_build_settings_path) - raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first" - end - generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path) - cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR']; - - unless File.exist?(copied_framework_path) - FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir) - end - unless File.exist?(copied_podspec_path) - FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir) - end + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end - # Keep pod path relative so it can be checked into Podfile.lock. - pod 'Flutter', :path => 'Flutter' +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) - # Plugin Pods +flutter_ios_podfile_setup - # Prepare symlinks folder. We use symlinks to avoid having Podfile.lock - # referring to absolute paths on developers' machines. - system('rm -rf .symlinks') - system('mkdir -p .symlinks/plugins') - plugin_pods = parse_KV_file('../.flutter-plugins') - plugin_pods.each do |name, path| - symlink = File.join('.symlinks', 'plugins', name) - File.symlink(path, symlink) - pod name, :path => File.join(symlink, 'ios') - end +target 'Runner' do + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) end -# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system. -install! 'cocoapods', :disable_input_output_paths => true - post_install do |installer| installer.pods_project.targets.each do |target| - target.build_configurations.each do |config| - config.build_settings['ENABLE_BITCODE'] = 'NO' - end + flutter_additional_ios_build_settings(target) end end From 64cd6df69fc0cc544067e5f102d0e74bfd3a30eb Mon Sep 17 00:00:00 2001 From: Carlo Grisetti Date: Mon, 30 Aug 2021 01:28:24 +0200 Subject: [PATCH 43/69] Convert onIceCandidate to async and introduce a delay Convert onIceCandidate to async and introduce a delay --- lib/src/call_sample/signaling.dart | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 287bf2f..e998454 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -392,21 +392,27 @@ class Signaling { sender.setParameters(parameters); */ } - pc.onIceCandidate = (candidate) { + pc.onIceCandidate = (candidate) async { if (candidate == null) { print('onIceCandidate: complete!'); return; } - _send('candidate', { - 'to': peerId, - 'from': _selfId, - 'candidate': { - 'sdpMLineIndex': candidate.sdpMlineIndex, - 'sdpMid': candidate.sdpMid, - 'candidate': candidate.candidate, - }, - 'session_id': sessionId, - }); + // This delay is needed to allow enough time to try an ICE candidate + // before skipping to the next one. 1 second is just an heuristic value + // and should be thoroughly tested in your own environment. + await Future.delayed( + const Duration(seconds: 1), + () => _send('candidate', { + 'to': peerId, + 'from': _selfId, + 'candidate': { + 'sdpMLineIndex': candidate.sdpMlineIndex, + 'sdpMid': candidate.sdpMid, + 'candidate': candidate.candidate, + }, + 'session_id': sessionId, + }) + ); }; pc.onIceConnectionState = (state) {}; From 33f168f3bdfb1269794ed6f9a02901b15a751f1e Mon Sep 17 00:00:00 2001 From: Carlo Grisetti Date: Mon, 30 Aug 2021 09:47:27 +0200 Subject: [PATCH 44/69] Set a different greyed out icon to easily identify self when testing --- lib/src/call_sample/call_sample.dart | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 5405948..7031692 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -136,12 +136,24 @@ class _CallSampleState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: const Icon(Icons.videocam), + icon: Icon(self + ? Icons.close + : Icons.videocam, + color: self + ? Colors.grey + : Colors.black + ), onPressed: () => _invitePeer(context, peer['id'], false), tooltip: 'Video calling', ), IconButton( - icon: const Icon(Icons.screen_share), + icon: Icon(self + ? Icons.close + : Icons.screen_share, + color: self + ? Colors.grey + : Colors.black + ), onPressed: () => _invitePeer(context, peer['id'], true), tooltip: 'Screen sharing', ) From af736180a1fd9ab37d2403b736c6f1459a7d0c89 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Mon, 30 Aug 2021 16:34:38 +0800 Subject: [PATCH 45/69] feat: null safety. --- .gitignore | 1 + lib/main.dart | 9 +- lib/src/call_sample/call_sample.dart | 139 +++++++-------- lib/src/call_sample/data_channel_sample.dart | 168 +++++++++--------- lib/src/call_sample/signaling.dart | 170 +++++++++---------- lib/src/route_item.dart | 8 +- lib/src/utils/websocket.dart | 10 +- lib/src/utils/websocket_web.dart | 10 +- pubspec.yaml | 15 +- 9 files changed, 243 insertions(+), 287 deletions(-) diff --git a/.gitignore b/.gitignore index fb82ae0..bbe6700 100644 --- a/.gitignore +++ b/.gitignore @@ -71,3 +71,4 @@ .flutter-plugins-dependencies ios/Flutter/flutter_export_environment.sh +lib/generated_plugin_registrant.dart \ No newline at end of file diff --git a/lib/main.dart b/lib/main.dart index b7934e3..208d1dd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,9 +20,9 @@ enum DialogDemoAction { } class _MyAppState extends State { - List items; + List items = []; String _server = ''; - SharedPreferences _prefs; + late SharedPreferences _prefs; bool _datachannel = false; @override @@ -67,11 +67,12 @@ class _MyAppState extends State { }); } - void showDemoDialog({BuildContext context, Widget child}) { + void showDemoDialog( + {required BuildContext context, required Widget child}) { showDialog( context: context, builder: (BuildContext context) => child, - ).then((T value) { + ).then((T? value) { // The value passed to Navigator.pop() or null. if (value != null) { if (value == DialogDemoAction.connect) { diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 7031692..3bb7936 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -5,26 +5,24 @@ import 'package:flutter_webrtc/flutter_webrtc.dart'; class CallSample extends StatefulWidget { static String tag = 'call_sample'; - final String host; - - CallSample({Key key, @required this.host}) : super(key: key); + CallSample({required this.host}); @override _CallSampleState createState() => _CallSampleState(); } class _CallSampleState extends State { - Signaling _signaling; - List _peers; - var _selfId; + Signaling? _signaling; + List _peers = []; + String? _selfId; RTCVideoRenderer _localRenderer = RTCVideoRenderer(); RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; - Session _session; + Session? _session; // ignore: unused_element - _CallSampleState({Key key}); + _CallSampleState(); @override initState() { @@ -41,85 +39,82 @@ class _CallSampleState extends State { @override deactivate() { super.deactivate(); - if (_signaling != null) _signaling.close(); + _signaling?.close(); _localRenderer.dispose(); _remoteRenderer.dispose(); } void _connect() async { - if (_signaling == null) { - _signaling = Signaling(widget.host)..connect(); - - _signaling.onSignalingStateChange = (SignalingState state) { - switch (state) { - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; - } - }; - - _signaling.onCallStateChange = (Session session, CallState state) { - switch (state) { - case CallState.CallStateNew: - setState(() { - _session = session; - _inCalling = true; - }); - break; - case CallState.CallStateBye: - setState(() { - _localRenderer.srcObject = null; - _remoteRenderer.srcObject = null; - _inCalling = false; - _session = null; - }); - break; - case CallState.CallStateInvite: - case CallState.CallStateConnected: - case CallState.CallStateRinging: - } - }; - - _signaling.onPeersUpdate = ((event) { - setState(() { - _selfId = event['self']; - _peers = event['peers']; - }); + _signaling ??= Signaling(widget.host)..connect(); + _signaling?.onSignalingStateChange = (SignalingState state) { + switch (state) { + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; + + _signaling?.onCallStateChange = (Session session, CallState state) { + switch (state) { + case CallState.CallStateNew: + setState(() { + _session = session; + _inCalling = true; + }); + break; + case CallState.CallStateBye: + setState(() { + _localRenderer.srcObject = null; + _remoteRenderer.srcObject = null; + _inCalling = false; + _session = null; + }); + break; + case CallState.CallStateInvite: + case CallState.CallStateConnected: + case CallState.CallStateRinging: + } + }; + + _signaling?.onPeersUpdate = ((event) { + setState(() { + _selfId = event['self']; + _peers = event['peers']; }); + }); - _signaling.onLocalStream = ((_, stream) { - _localRenderer.srcObject = stream; - }); + _signaling?.onLocalStream = ((stream) { + _localRenderer.srcObject = stream; + }); - _signaling.onAddRemoteStream = ((_, stream) { - _remoteRenderer.srcObject = stream; - }); + _signaling?.onAddRemoteStream = ((_, stream) { + _remoteRenderer.srcObject = stream; + }); - _signaling.onRemoveRemoteStream = ((_, stream) { - _remoteRenderer.srcObject = null; - }); - } + _signaling?.onRemoveRemoteStream = ((_, stream) { + _remoteRenderer.srcObject = null; + }); } _invitePeer(BuildContext context, String peerId, bool useScreen) async { if (_signaling != null && peerId != _selfId) { - _signaling.invite(peerId, 'video', useScreen); + _signaling?.invite(peerId, 'video', useScreen); } } _hangUp() { - if (_signaling != null) { - _signaling.bye(_session.sid); + if (_session != null) { + _signaling?.bye(_session!.sid); } } _switchCamera() { - _signaling.switchCamera(); + _signaling?.switchCamera(); } _muteMic() { - _signaling.muteMic(); + _signaling?.muteMic(); } _buildRow(context, peer) { @@ -136,24 +131,14 @@ class _CallSampleState extends State { mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ IconButton( - icon: Icon(self - ? Icons.close - : Icons.videocam, - color: self - ? Colors.grey - : Colors.black - ), + icon: Icon(self ? Icons.close : Icons.videocam, + color: self ? Colors.grey : Colors.black), onPressed: () => _invitePeer(context, peer['id'], false), tooltip: 'Video calling', ), IconButton( - icon: Icon(self - ? Icons.close - : Icons.screen_share, - color: self - ? Colors.grey - : Colors.black - ), + icon: Icon(self ? Icons.close : Icons.screen_share, + color: self ? Colors.grey : Colors.black), onPressed: () => _invitePeer(context, peer['id'], true), tooltip: 'Screen sharing', ) diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 0dfda30..c589c2c 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -7,26 +7,24 @@ import 'package:flutter_webrtc/flutter_webrtc.dart'; class DataChannelSample extends StatefulWidget { static String tag = 'call_sample'; - final String host; - - DataChannelSample({Key key, @required this.host}) : super(key: key); + DataChannelSample({required this.host}); @override _DataChannelSampleState createState() => _DataChannelSampleState(); } class _DataChannelSampleState extends State { - Signaling _signaling; - List _peers; - var _selfId; + Signaling? _signaling; + List _peers = []; + String? _selfId; bool _inCalling = false; - RTCDataChannel _dataChannel; - Session _session; - Timer _timer; + RTCDataChannel? _dataChannel; + Session? _session; + Timer? _timer; var _text = ''; // ignore: unused_element - _DataChannelSampleState({Key key}); + _DataChannelSampleState(); @override initState() { @@ -37,104 +35,90 @@ class _DataChannelSampleState extends State { @override deactivate() { super.deactivate(); - if (_signaling != null) _signaling.close(); - if (_timer != null) { - _timer.cancel(); - } + _signaling?.close(); + _timer?.cancel(); } void _connect() async { - if (_signaling == null) { - _signaling = Signaling(widget.host)..connect(); - - _signaling.onDataChannelMessage = (_, dc, RTCDataChannelMessage data) { - setState(() { - if (data.isBinary) { - print('Got binary [' + data.binary.toString() + ']'); - } else { - _text = data.text; - } - }); - }; - - _signaling.onDataChannel = (_, channel) { - _dataChannel = channel; - }; - - _signaling.onSignalingStateChange = (SignalingState state) { - switch (state) { - case SignalingState.ConnectionClosed: - case SignalingState.ConnectionError: - case SignalingState.ConnectionOpen: - break; + _signaling ??= Signaling(widget.host)..connect(); + + _signaling?.onDataChannelMessage = (_, dc, RTCDataChannelMessage data) { + setState(() { + if (data.isBinary) { + print('Got binary [' + data.binary.toString() + ']'); + } else { + _text = data.text; } - }; - - _signaling.onCallStateChange = (Session session, CallState state) { - switch (state) { - case CallState.CallStateNew: - { - setState(() { - _session = session; - _inCalling = true; - }); - _timer = - Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); - break; - } - case CallState.CallStateBye: - { - setState(() { - _inCalling = false; - }); - if (_timer != null) { - _timer.cancel(); - _timer = null; - } - _dataChannel = null; + }); + }; + + _signaling?.onDataChannel = (_, channel) { + _dataChannel = channel; + }; + + _signaling?.onSignalingStateChange = (SignalingState state) { + switch (state) { + case SignalingState.ConnectionClosed: + case SignalingState.ConnectionError: + case SignalingState.ConnectionOpen: + break; + } + }; + + _signaling?.onCallStateChange = (Session session, CallState state) { + switch (state) { + case CallState.CallStateNew: + { + setState(() { + _session = session; + _inCalling = true; + }); + _timer = + Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); + break; + } + case CallState.CallStateBye: + { + setState(() { _inCalling = false; - _session = null; - _text = ''; - break; - } - case CallState.CallStateInvite: - case CallState.CallStateConnected: - case CallState.CallStateRinging: - } - }; - - _signaling.onPeersUpdate = ((event) { - setState(() { - _selfId = event['self']; - _peers = event['peers']; - }); + }); + _timer?.cancel(); + _dataChannel = null; + _inCalling = false; + _session = null; + _text = ''; + break; + } + case CallState.CallStateInvite: + case CallState.CallStateConnected: + case CallState.CallStateRinging: + } + }; + + _signaling?.onPeersUpdate = ((event) { + setState(() { + _selfId = event['self']; + _peers = event['peers']; }); - } + }); } _handleDataChannelTest(Timer timer) async { - if (_dataChannel != null) { - String text = 'Say hello ' + - timer.tick.toString() + - ' times, from [' + - _selfId + - ']'; - _dataChannel - .send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); - _dataChannel.send(RTCDataChannelMessage(text)); - } + String text = + 'Say hello ' + timer.tick.toString() + ' times, from [$_selfId]'; + _dataChannel + ?.send(RTCDataChannelMessage.fromBinary(Uint8List(timer.tick + 1))); + _dataChannel?.send(RTCDataChannelMessage(text)); } _invitePeer(context, peerId) async { - if (_signaling != null && peerId != _selfId) { - _signaling.invite(peerId, 'data', false); + if (peerId != _selfId) { + _signaling?.invite(peerId, 'data', false); } } _hangUp() { - if (_signaling != null) { - _signaling.bye(_session.sid); - } + _signaling?.bye(_session!.sid); } _buildRow(context, peer) { diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index e998454..7feada4 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -24,23 +24,12 @@ enum CallState { CallStateBye, } -/* - * callbacks for Signaling API. - */ -typedef void SignalingStateCallback(SignalingState state); -typedef void CallStateCallback(Session session, CallState state); -typedef void StreamStateCallback(Session session, MediaStream stream); -typedef void OtherEventCallback(dynamic event); -typedef void DataChannelMessageCallback( - Session session, RTCDataChannel dc, RTCDataChannelMessage data); -typedef void DataChannelCallback(Session session, RTCDataChannel dc); - class Session { - Session({this.sid, this.pid}); + Session({required this.sid, required this.pid}); String pid; String sid; - RTCPeerConnection pc; - RTCDataChannel dc; + RTCPeerConnection? pc; + RTCDataChannel? dc; List remoteCandidates = []; } @@ -50,22 +39,23 @@ class Signaling { JsonEncoder _encoder = JsonEncoder(); JsonDecoder _decoder = JsonDecoder(); String _selfId = randomNumeric(6); - SimpleWebSocket _socket; + SimpleWebSocket? _socket; var _host; var _port = 8086; var _turnCredential; Map _sessions = {}; - MediaStream _localStream; + MediaStream? _localStream; List _remoteStreams = []; - SignalingStateCallback onSignalingStateChange; - CallStateCallback onCallStateChange; - StreamStateCallback onLocalStream; - StreamStateCallback onAddRemoteStream; - StreamStateCallback onRemoveRemoteStream; - OtherEventCallback onPeersUpdate; - DataChannelMessageCallback onDataChannelMessage; - DataChannelCallback onDataChannel; + Function(SignalingState state)? onSignalingStateChange; + Function(Session session, CallState state)? onCallStateChange; + Function(MediaStream stream)? onLocalStream; + Function(Session session, MediaStream stream)? onAddRemoteStream; + Function(Session session, MediaStream stream)? onRemoveRemoteStream; + Function(dynamic event)? onPeersUpdate; + Function(Session session, RTCDataChannel dc, RTCDataChannelMessage data)? + onDataChannelMessage; + Function(Session session, RTCDataChannel dc)? onDataChannel; String get sdpSemantics => WebRTC.platformIsWindows ? 'plan-b' : 'unified-plan'; @@ -101,25 +91,25 @@ class Signaling { close() async { await _cleanSessions(); - if (_socket != null) _socket.close(); + _socket?.close(); } void switchCamera() { if (_localStream != null) { - Helper.switchCamera(_localStream.getVideoTracks()[0]); + Helper.switchCamera(_localStream!.getVideoTracks()[0]); } } void muteMic() { if (_localStream != null) { - bool enabled = _localStream.getAudioTracks()[0].enabled; - _localStream.getAudioTracks()[0].enabled = !enabled; + bool enabled = _localStream!.getAudioTracks()[0].enabled; + _localStream!.getAudioTracks()[0].enabled = !enabled; } } void invite(String peerId, String media, bool useScreen) async { var sessionId = _selfId + '-' + peerId; - Session session = await _createSession( + Session session = await _createSession(null, peerId: peerId, sessionId: sessionId, media: media, @@ -137,8 +127,10 @@ class Signaling { 'session_id': sessionId, 'from': _selfId, }); - - _closeSession(_sessions[sessionId]); + var sess = _sessions[sessionId]; + if (sess != null) { + _closeSession(sess); + } } void onMessage(message) async { @@ -164,19 +156,18 @@ class Signaling { var media = data['media']; var sessionId = data['session_id']; var session = _sessions[sessionId]; - var newSession = await _createSession( - session: session, + var newSession = await _createSession(session, peerId: peerId, sessionId: sessionId, media: media, screenSharing: false); _sessions[sessionId] = newSession; - await newSession.pc.setRemoteDescription( + await newSession.pc?.setRemoteDescription( RTCSessionDescription(description['sdp'], description['type'])); await _createAnswer(newSession, media); if (newSession.remoteCandidates.length > 0) { newSession.remoteCandidates.forEach((candidate) async { - await newSession.pc.addCandidate(candidate); + await newSession.pc?.addCandidate(candidate); }); newSession.remoteCandidates.clear(); } @@ -203,7 +194,7 @@ class Signaling { if (session != null) { if (session.pc != null) { - await session.pc.addCandidate(candidate); + await session.pc?.addCandidate(candidate); } else { session.remoteCandidates.add(candidate); } @@ -224,8 +215,10 @@ class Signaling { var sessionId = data['session_id']; print('bye: ' + sessionId); var session = _sessions.remove(sessionId); - onCallStateChange?.call(session, CallState.CallStateBye); - _closeSession(session); + if (session != null) { + onCallStateChange?.call(session, CallState.CallStateBye); + _closeSession(session); + } } break; case 'keepalive': @@ -266,7 +259,7 @@ class Signaling { } catch (e) {} } - _socket.onOpen = () { + _socket?.onOpen = () { print('onOpen'); onSignalingStateChange?.call(SignalingState.ConnectionOpen); _send('new', { @@ -276,47 +269,48 @@ class Signaling { }); }; - _socket.onMessage = (message) { + _socket?.onMessage = (message) { print('Received data: ' + message); onMessage(_decoder.convert(message)); }; - _socket.onClose = (int code, String reason) { + _socket?.onClose = (int code, String reason) { print('Closed by server [$code => $reason]!'); onSignalingStateChange?.call(SignalingState.ConnectionClosed); }; - await _socket.connect(); + await _socket?.connect(); } Future createStream(String media, bool userScreen) async { final Map mediaConstraints = { - 'audio': true, - 'video': { - 'mandatory': { - 'minWidth': - '640', // Provide your own width, height and frame rate here - 'minHeight': '480', - 'minFrameRate': '30', - }, - 'facingMode': 'user', - 'optional': [], - } + 'audio': userScreen ? false : true, + 'video': userScreen + ? true + : { + 'mandatory': { + 'minWidth': + '640', // Provide your own width, height and frame rate here + 'minHeight': '480', + 'minFrameRate': '30', + }, + 'facingMode': 'user', + 'optional': [], + } }; MediaStream stream = userScreen ? await navigator.mediaDevices.getDisplayMedia(mediaConstraints) : await navigator.mediaDevices.getUserMedia(mediaConstraints); - onLocalStream?.call(null, stream); + onLocalStream?.call(stream); return stream; } - Future _createSession( - {Session session, - String peerId, - String sessionId, - String media, - bool screenSharing}) async { + Future _createSession(Session? session, + {required String peerId, + required String sessionId, + required String media, + required bool screenSharing}) async { var newSession = session ?? Session(sid: sessionId, pid: peerId); if (media != 'data') _localStream = await createStream(media, screenSharing); @@ -332,18 +326,17 @@ class Signaling { onAddRemoteStream?.call(newSession, stream); _remoteStreams.add(stream); }; - await pc.addStream(_localStream); + await pc.addStream(_localStream!); break; case 'unified-plan': - // Unified-Plan pc.onTrack = (event) { if (event.track.kind == 'video') { onAddRemoteStream?.call(newSession, event.streams[0]); } }; - _localStream.getTracks().forEach((track) { - pc.addTrack(track, _localStream); + _localStream!.getTracks().forEach((track) { + pc.addTrack(track, _localStream!); }); break; } @@ -403,16 +396,15 @@ class Signaling { await Future.delayed( const Duration(seconds: 1), () => _send('candidate', { - 'to': peerId, - 'from': _selfId, - 'candidate': { - 'sdpMLineIndex': candidate.sdpMlineIndex, - 'sdpMid': candidate.sdpMid, - 'candidate': candidate.candidate, - }, - 'session_id': sessionId, - }) - ); + 'to': peerId, + 'from': _selfId, + 'candidate': { + 'sdpMLineIndex': candidate.sdpMlineIndex, + 'sdpMid': candidate.sdpMid, + 'candidate': candidate.candidate, + }, + 'session_id': sessionId, + })); }; pc.onIceConnectionState = (state) {}; @@ -446,15 +438,15 @@ class Signaling { RTCDataChannelInit dataChannelDict = RTCDataChannelInit() ..maxRetransmits = 30; RTCDataChannel channel = - await session.pc.createDataChannel(label, dataChannelDict); + await session.pc!.createDataChannel(label, dataChannelDict); _addDataChannel(session, channel); } Future _createOffer(Session session, String media) async { try { RTCSessionDescription s = - await session.pc.createOffer(media == 'data' ? _dcConstraints : {}); - await session.pc.setLocalDescription(s); + await session.pc!.createOffer(media == 'data' ? _dcConstraints : {}); + await session.pc!.setLocalDescription(s); _send('offer', { 'to': session.pid, 'from': _selfId, @@ -470,8 +462,8 @@ class Signaling { Future _createAnswer(Session session, String media) async { try { RTCSessionDescription s = - await session.pc.createAnswer(media == 'data' ? _dcConstraints : {}); - await session.pc.setLocalDescription(s); + await session.pc!.createAnswer(media == 'data' ? _dcConstraints : {}); + await session.pc!.setLocalDescription(s); _send('answer', { 'to': session.pid, 'from': _selfId, @@ -487,20 +479,20 @@ class Signaling { var request = Map(); request["type"] = event; request["data"] = data; - _socket.send(_encoder.convert(request)); + _socket?.send(_encoder.convert(request)); } Future _cleanSessions() async { if (_localStream != null) { - _localStream.getTracks().forEach((element) async { - await element.dispose(); + _localStream!.getTracks().forEach((element) async { + await element.stop(); }); - await _localStream.dispose(); + await _localStream!.dispose(); _localStream = null; } _sessions.forEach((key, sess) async { - await sess?.pc?.close(); - await sess?.dc?.close(); + await sess.pc?.close(); + await sess.dc?.close(); }); _sessions.clear(); } @@ -519,13 +511,13 @@ class Signaling { } Future _closeSession(Session session) async { - _localStream?.getTracks()?.forEach((element) async { - await element.dispose(); + _localStream?.getTracks().forEach((element) async { + await element.stop(); }); await _localStream?.dispose(); _localStream = null; - await session?.pc?.close(); - await session?.dc?.close(); + await session.pc?.close(); + await session.dc?.close(); } } diff --git a/lib/src/route_item.dart b/lib/src/route_item.dart index 78427b1..a7a46d9 100644 --- a/lib/src/route_item.dart +++ b/lib/src/route_item.dart @@ -5,12 +5,12 @@ typedef void RouteCallback(BuildContext context); class RouteItem { RouteItem({ - @required this.title, - @required this.subtitle, - @required this.push, + required this.title, + required this.subtitle, + required this.push, }); final String title; final String subtitle; final RouteCallback push; -} \ No newline at end of file +} diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index 75684e0..33347a0 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -3,16 +3,12 @@ import 'dart:math'; import 'dart:convert'; import 'dart:async'; -typedef void OnMessageCallback(dynamic msg); -typedef void OnCloseCallback(int code, String reason); -typedef void OnOpenCallback(); - class SimpleWebSocket { String _url; var _socket; - OnOpenCallback onOpen; - OnMessageCallback onMessage; - OnCloseCallback onClose; + Function()? onOpen; + Function(dynamic msg)? onMessage; + Function(int code, String reaso)? onClose; SimpleWebSocket(this._url); connect() async { diff --git a/lib/src/utils/websocket_web.dart b/lib/src/utils/websocket_web.dart index e2108be..94c9546 100644 --- a/lib/src/utils/websocket_web.dart +++ b/lib/src/utils/websocket_web.dart @@ -1,16 +1,12 @@ // ignore: avoid_web_libraries_in_flutter import 'dart:html'; -typedef void OnMessageCallback(dynamic msg); -typedef void OnCloseCallback(int code, String reason); -typedef void OnOpenCallback(); - class SimpleWebSocket { String _url; var _socket; - OnOpenCallback onOpen; - OnMessageCallback onMessage; - OnCloseCallback onClose; + Function()? onOpen; + Function(dynamic msg)? onMessage; + Function(int code, String reason)? onClose; SimpleWebSocket(this._url) { _url = _url.replaceAll('https:', 'wss:'); diff --git a/pubspec.yaml b/pubspec.yaml index d4b7d69..278d5bd 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,19 +1,20 @@ name: flutter_webrtc_demo description: A new Flutter application. -version: 1.0.1 +version: 1.2.0 environment: - sdk: ">=2.2.2 <3.0.0" + sdk: '>=2.12.0 <3.0.0' + flutter: '>=1.22.0' dependencies: flutter: sdk: flutter - cupertino_icons: ^1.0.0 - flutter_webrtc: ^0.5.8 - shared_preferences: ^2.0.0 - http: ^0.13.0 - path_provider: ^2.0.0 + cupertino_icons: ^1.0.3 + flutter_webrtc: ^0.6.5 + shared_preferences: ^2.0.7 + http: ^0.13.3 + path_provider: ^2.0.2 dev_dependencies: flutter_test: From b2a495d8888fa84da9c8eba164cb2c8d46988a44 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Mon, 30 Aug 2021 16:52:50 +0800 Subject: [PATCH 46/69] update device label. --- lib/src/call_sample/call_sample.dart | 9 +++++---- lib/src/call_sample/data_channel_sample.dart | 9 +++++---- lib/src/utils/device_info.dart | 6 +++++- lib/src/utils/device_info_web.dart | 7 +++++-- 4 files changed, 20 insertions(+), 11 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 3bb7936..6207c85 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -122,8 +122,8 @@ class _CallSampleState extends State { return ListBody(children: [ ListTile( title: Text(self - ? peer['name'] + '[Your self]' - : peer['name'] + '[' + peer['user_agent'] + ']'), + ? peer['name'] + ', ID: ${peer['id']} ' + ' [Your self]' + : peer['name'] + ', ID: ${peer['id']} '), onTap: null, trailing: SizedBox( width: 100.0, @@ -143,7 +143,7 @@ class _CallSampleState extends State { tooltip: 'Screen sharing', ) ])), - subtitle: Text('id: ' + peer['id']), + subtitle: Text('[' + peer['user_agent'] + ']'), ), Divider() ]); @@ -153,7 +153,8 @@ class _CallSampleState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('P2P Call Sample'), + title: Text('P2P Call Sample' + + (_selfId != null ? ' [Your ID ($_selfId)] ' : '')), actions: [ IconButton( icon: const Icon(Icons.settings), diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index c589c2c..601729c 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -126,11 +126,11 @@ class _DataChannelSampleState extends State { return ListBody(children: [ ListTile( title: Text(self - ? peer['name'] + '[Your self]' - : peer['name'] + '[' + peer['user_agent'] + ']'), + ? peer['name'] + ', ID: ${peer['id']} ' + ' [Your self]' + : peer['name'] + ', ID: ${peer['id']} '), onTap: () => _invitePeer(context, peer['id']), trailing: Icon(Icons.sms), - subtitle: Text('id: ' + peer['id']), + subtitle: Text('[' + peer['user_agent'] + ']'), ), Divider() ]); @@ -140,7 +140,8 @@ class _DataChannelSampleState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text('Data Channel Sample'), + title: Text('Data Channel Sample' + + (_selfId != null ? ' [Your ID ($_selfId)] ' : '')), actions: [ IconButton( icon: const Icon(Icons.settings), diff --git a/lib/src/utils/device_info.dart b/lib/src/utils/device_info.dart index 21617f4..e89ab5b 100644 --- a/lib/src/utils/device_info.dart +++ b/lib/src/utils/device_info.dart @@ -2,7 +2,11 @@ import 'dart:io'; class DeviceInfo { static String get label { - return Platform.localHostname + '(' + Platform.operatingSystem + ")"; + return 'Flutter ' + + Platform.operatingSystem + + '(' + + Platform.localHostname + + ")"; } static String get userAgent { diff --git a/lib/src/utils/device_info_web.dart b/lib/src/utils/device_info_web.dart index 8dbeba2..ca0a396 100644 --- a/lib/src/utils/device_info_web.dart +++ b/lib/src/utils/device_info_web.dart @@ -3,10 +3,13 @@ import 'dart:html' as HTML; class DeviceInfo { static String get label { - return 'Flutter Web ( ' + HTML.window.navigator.userAgent + ' )'; + return 'Flutter Web'; } static String get userAgent { - return 'flutter-webrtc/web-plugin 0.0.1'; + return 'flutter-webrtc/web-plugin 0.0.1 ' + + ' ( ' + + HTML.window.navigator.userAgent + + ' )'; } } From e43d209618f1add375fb3cee6b27d4be749c6c62 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Mon, 30 Aug 2021 17:06:48 +0800 Subject: [PATCH 47/69] Update flutter.yml --- .github/workflows/flutter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/flutter.yml b/.github/workflows/flutter.yml index c0438d2..d6ea4a3 100644 --- a/.github/workflows/flutter.yml +++ b/.github/workflows/flutter.yml @@ -22,7 +22,7 @@ jobs: java-version: '12.x' - uses: subosito/flutter-action@v1 with: - flutter-version: '1.7.8+hotfix.4' + flutter-version: '2.0.5' channel: 'stable' - run: flutter packages get - run: flutter test From 070ab82673eb37e28c82bbfdf5e1aeba4fc6f2ab Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 21 Oct 2021 14:18:03 +0800 Subject: [PATCH 48/69] bump version for flutter-webrtc. --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 278d5bd..5c02e51 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.6.5 + flutter_webrtc: ^0.7.0+hotfix.1 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From da0c8248749e90a1966685e893b081dd83d8f35e Mon Sep 17 00:00:00 2001 From: baihua <> Date: Sun, 27 Mar 2022 21:04:35 +0800 Subject: [PATCH 49/69] Add accept and reject call example --- lib/src/call_sample/call_sample.dart | 92 +++++++++++++++++++++++++++- lib/src/call_sample/signaling.dart | 27 +++++++- lib/src/utils/websocket.dart | 2 +- 3 files changed, 115 insertions(+), 6 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 6207c85..9f6cc0d 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -21,6 +21,8 @@ class _CallSampleState extends State { bool _inCalling = false; Session? _session; + bool _waitAccept = false; + // ignore: unused_element _CallSampleState(); @@ -55,15 +57,31 @@ class _CallSampleState extends State { } }; - _signaling?.onCallStateChange = (Session session, CallState state) { + _signaling?.onCallStateChange = (Session session, CallState state) async { switch (state) { case CallState.CallStateNew: setState(() { _session = session; - _inCalling = true; }); break; + case CallState.CallStateRinging: + bool? accept = await _showAcceptDialog(); + if (accept!) { + _accept(); + setState(() { + _inCalling = true; + }); + } + else { + _reject(); + } + break; case CallState.CallStateBye: + if (_waitAccept) { + print('peer reject'); + _waitAccept = false; + Navigator.of(context).pop(false); + } setState(() { _localRenderer.srcObject = null; _remoteRenderer.srcObject = null; @@ -72,7 +90,19 @@ class _CallSampleState extends State { }); break; case CallState.CallStateInvite: + _waitAccept = true; + _showInvateDialog(); + break; case CallState.CallStateConnected: + if (_waitAccept) { + _waitAccept = false; + Navigator.of(context).pop(false); + } + setState(() { + _inCalling = true; + }); + + break; case CallState.CallStateRinging: } }; @@ -97,12 +127,70 @@ class _CallSampleState extends State { }); } + Future _showAcceptDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("accept?"), + actions: [ + TextButton( + child: Text("reject"), + onPressed: () => Navigator.of(context).pop(false), + ), + TextButton( + child: Text("accept"), + onPressed: () { + Navigator.of(context).pop(true); + }, + ), + ], + ); + }, + ); + } + + Future _showInvateDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("waiting"), + actions: [ + TextButton( + child: Text("cancel"), + onPressed: () { + Navigator.of(context).pop(false); + _hangUp(); + }, + + ), + ], + ); + }, + ); + } + _invitePeer(BuildContext context, String peerId, bool useScreen) async { if (_signaling != null && peerId != _selfId) { _signaling?.invite(peerId, 'video', useScreen); } } + _accept() { + if (_session != null) { + _signaling?.accept(_session!.sid); + } + } + + _reject() { + if (_session != null) { + _signaling?.reject(_session!.sid); + } + } + _hangUp() { if (_session != null) { _signaling?.bye(_session!.sid); diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 7feada4..8fe84a2 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -120,6 +120,7 @@ class Signaling { } _createOffer(session, media); onCallStateChange?.call(session, CallState.CallStateNew); + onCallStateChange?.call(session, CallState.CallStateInvite); } void bye(String sessionId) { @@ -133,6 +134,22 @@ class Signaling { } } + void accept(String sessionId) { + var session = _sessions[sessionId]; + if (session == null) { + return; + } + _createAnswer(session, 'video'); + } + + void reject(String sessionId) { + var session = _sessions[sessionId]; + if (session == null) { + return; + } + bye(session.sid); + } + void onMessage(message) async { Map mapData = message; var data = mapData['data']; @@ -164,7 +181,8 @@ class Signaling { _sessions[sessionId] = newSession; await newSession.pc?.setRemoteDescription( RTCSessionDescription(description['sdp'], description['type'])); - await _createAnswer(newSession, media); + // await _createAnswer(newSession, media); + if (newSession.remoteCandidates.length > 0) { newSession.remoteCandidates.forEach((candidate) async { await newSession.pc?.addCandidate(candidate); @@ -172,6 +190,8 @@ class Signaling { newSession.remoteCandidates.clear(); } onCallStateChange?.call(newSession, CallState.CallStateNew); + + onCallStateChange?.call(newSession, CallState.CallStateRinging); } break; case 'answer': @@ -181,6 +201,7 @@ class Signaling { var session = _sessions[sessionId]; session?.pc?.setRemoteDescription( RTCSessionDescription(description['sdp'], description['type'])); + onCallStateChange?.call(session!, CallState.CallStateConnected); } break; case 'candidate': @@ -274,7 +295,7 @@ class Signaling { onMessage(_decoder.convert(message)); }; - _socket?.onClose = (int code, String reason) { + _socket?.onClose = (int? code, String? reason) { print('Closed by server [$code => $reason]!'); onSignalingStateChange?.call(SignalingState.ConnectionClosed); }; @@ -399,7 +420,7 @@ class Signaling { 'to': peerId, 'from': _selfId, 'candidate': { - 'sdpMLineIndex': candidate.sdpMlineIndex, + 'sdpMLineIndex': candidate.sdpMLineIndex, 'sdpMid': candidate.sdpMid, 'candidate': candidate.candidate, }, diff --git a/lib/src/utils/websocket.dart b/lib/src/utils/websocket.dart index 33347a0..c6ebffc 100644 --- a/lib/src/utils/websocket.dart +++ b/lib/src/utils/websocket.dart @@ -8,7 +8,7 @@ class SimpleWebSocket { var _socket; Function()? onOpen; Function(dynamic msg)? onMessage; - Function(int code, String reaso)? onClose; + Function(int? code, String? reaso)? onClose; SimpleWebSocket(this._url); connect() async { From 7206a98a222cfe493f2f95be93708529da3f75d2 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Mon, 28 Mar 2022 11:15:44 +0800 Subject: [PATCH 50/69] chore: bump version for flutter_webrtc. --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 5c02e51..a8f880d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.7.0+hotfix.1 + flutter_webrtc: ^0.8.3 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From 5aa6608224cdf96bb0edebf7aedbae5a99aaca6e Mon Sep 17 00:00:00 2001 From: Mayur Mahajan <47064215+MayurSMahajan@users.noreply.github.com> Date: Tue, 28 Jun 2022 10:04:39 +0530 Subject: [PATCH 51/69] Update main.dart --- lib/main.dart | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/main.dart b/lib/main.dart index 208d1dd..ed3df9f 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -105,12 +105,12 @@ class _MyAppState extends State { textAlign: TextAlign.center, ), actions: [ - FlatButton( + TextButton( child: const Text('CANCEL'), onPressed: () { Navigator.pop(context, DialogDemoAction.cancel); }), - FlatButton( + TextButton( child: const Text('CONNECT'), onPressed: () { Navigator.pop(context, DialogDemoAction.connect); From 23296915a7e2c656d7b63ad37e38b7f85df70a91 Mon Sep 17 00:00:00 2001 From: "duanweiwei1982@gmail.com" Date: Sun, 17 Jul 2022 03:58:04 +0800 Subject: [PATCH 52/69] screen sharing. --- lib/src/call_sample/call_sample.dart | 64 ++++- lib/src/call_sample/signaling.dart | 43 +++- lib/src/widgets/screen_select_dialog.dart | 284 ++++++++++++++++++++++ pubspec.yaml | 2 +- 4 files changed, 374 insertions(+), 19 deletions(-) create mode 100644 lib/src/widgets/screen_select_dialog.dart diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 9f6cc0d..9d2982d 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'dart:core'; +import '../widgets/screen_select_dialog.dart'; import 'signaling.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; @@ -71,8 +72,7 @@ class _CallSampleState extends State { setState(() { _inCalling = true; }); - } - else { + } else { _reject(); } break; @@ -135,15 +135,19 @@ class _CallSampleState extends State { title: Text("title"), content: Text("accept?"), actions: [ - TextButton( - child: Text("reject"), + MaterialButton( + child: Text( + 'Reject', + style: TextStyle(color: Colors.red), + ), onPressed: () => Navigator.of(context).pop(false), ), - TextButton( - child: Text("accept"), - onPressed: () { - Navigator.of(context).pop(true); - }, + MaterialButton( + child: Text( + 'Accept', + style: TextStyle(color: Colors.green), + ), + onPressed: () => Navigator.of(context).pop(true), ), ], ); @@ -164,8 +168,7 @@ class _CallSampleState extends State { onPressed: () { Navigator.of(context).pop(false); _hangUp(); - }, - + }, ), ], ); @@ -201,6 +204,36 @@ class _CallSampleState extends State { _signaling?.switchCamera(); } + Future selectScreenSourceDialog(BuildContext context) async { + final source = await showDialog( + context: context, + builder: (context) => ScreenSelectDialog(), + ); + if (source != null) { + try { + var stream = + await navigator.mediaDevices.getDisplayMedia({ + 'video': { + 'deviceId': {'exact': source.id}, + 'mandatory': {'frameRate': 30.0} + } + }); + stream.getVideoTracks()[0].onEnded = () { + print( + 'By adding a listener on onEnded you can: 1) catch stop video sharing on Web'); + }; + _signaling?.switchToScreenSharing(stream); + } catch (e) { + print(e); + } + //await _makeCall(source); + } + } + + _switchScreenSharing() { + //_signaling?.switchToScreenSharing(); + } + _muteMic() { _signaling?.muteMic(); } @@ -254,14 +287,20 @@ class _CallSampleState extends State { floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, floatingActionButton: _inCalling ? SizedBox( - width: 200.0, + width: 240.0, child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ FloatingActionButton( child: const Icon(Icons.switch_camera), + tooltip: 'Camera', onPressed: _switchCamera, ), + FloatingActionButton( + child: const Icon(Icons.desktop_mac), + tooltip: 'Screen Sharing', + onPressed: () => selectScreenSourceDialog(context), + ), FloatingActionButton( onPressed: _hangUp, tooltip: 'Hangup', @@ -270,6 +309,7 @@ class _CallSampleState extends State { ), FloatingActionButton( child: const Icon(Icons.mic_off), + tooltip: 'Mute Mic', onPressed: _muteMic, ) ])) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 8fe84a2..2a5dd6e 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -24,6 +24,11 @@ enum CallState { CallStateBye, } +enum VideoSource { + Camera, + Screen, +} + class Session { Session({required this.sid, required this.pid}); String pid; @@ -46,6 +51,8 @@ class Signaling { Map _sessions = {}; MediaStream? _localStream; List _remoteStreams = []; + List _senders = []; + VideoSource videoSource = VideoSource.Camera; Function(SignalingState state)? onSignalingStateChange; Function(Session session, CallState state)? onCallStateChange; @@ -57,8 +64,7 @@ class Signaling { onDataChannelMessage; Function(Session session, RTCDataChannel dc)? onDataChannel; - String get sdpSemantics => - WebRTC.platformIsWindows ? 'plan-b' : 'unified-plan'; + String get sdpSemantics => 'unified-plan'; Map _iceServers = { 'iceServers': [ @@ -96,10 +102,36 @@ class Signaling { void switchCamera() { if (_localStream != null) { - Helper.switchCamera(_localStream!.getVideoTracks()[0]); + if (videoSource != VideoSource.Camera) { + switchVideoSource(source: VideoSource.Camera); + _senders.forEach((sender) { + if (sender.track!.kind == 'video') { + sender.replaceTrack(_localStream!.getVideoTracks()[0]); + } + }); + videoSource = VideoSource.Camera; + onLocalStream?.call(_localStream!); + } else { + Helper.switchCamera(_localStream!.getVideoTracks()[0]); + } } } + void switchToScreenSharing(MediaStream stream) { + if (_localStream != null && videoSource != VideoSource.Screen) { + switchVideoSource(source: VideoSource.Screen); + _senders.forEach((sender) { + if (sender.track!.kind == 'video') { + sender.replaceTrack(stream.getVideoTracks()[0]); + } + }); + onLocalStream?.call(stream); + videoSource = VideoSource.Screen; + } + } + + void switchVideoSource({VideoSource source = VideoSource.Camera}) {} + void muteMic() { if (_localStream != null) { bool enabled = _localStream!.getAudioTracks()[0].enabled; @@ -190,7 +222,6 @@ class Signaling { newSession.remoteCandidates.clear(); } onCallStateChange?.call(newSession, CallState.CallStateNew); - onCallStateChange?.call(newSession, CallState.CallStateRinging); } break; @@ -356,8 +387,8 @@ class Signaling { onAddRemoteStream?.call(newSession, event.streams[0]); } }; - _localStream!.getTracks().forEach((track) { - pc.addTrack(track, _localStream!); + _localStream!.getTracks().forEach((track) async { + _senders.add(await pc.addTrack(track, _localStream!)); }); break; } diff --git a/lib/src/widgets/screen_select_dialog.dart b/lib/src/widgets/screen_select_dialog.dart new file mode 100644 index 0000000..1697944 --- /dev/null +++ b/lib/src/widgets/screen_select_dialog.dart @@ -0,0 +1,284 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; + +// ignore: must_be_immutable +class ScreenSelectDialog extends Dialog { + ScreenSelectDialog() { + Future.delayed(Duration(milliseconds: 100), () { + _getSources(); + _timer = Timer.periodic(Duration(milliseconds: 2000), (timer) { + _getSources(); + }); + }); + } + List _sources = []; + SourceType _sourceType = SourceType.Screen; + DesktopCapturerSource? _selected_source; + StateSetter? _stateSetter; + Timer? _timer; + + void _pop(context) { + _timer?.cancel(); + Navigator.pop(context, _selected_source); + } + + Future _getSources() async { + try { + var sources = await desktopCapturer.getSources(types: [_sourceType]); + sources.forEach((element) { + print( + 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); + }); + _stateSetter?.call(() { + _sources = sources; + }); + return; + } catch (e) { + print(e.toString()); + } + } + + @override + Widget build(BuildContext context) { + return Material( + type: MaterialType.transparency, + child: Center( + child: Container( + width: 640, + height: 560, + color: Colors.white, + child: Column( + children: [ + Padding( + padding: EdgeInsets.all(10), + child: Stack( + children: [ + Align( + alignment: Alignment.topLeft, + child: Text( + 'Choose what to share', + style: TextStyle(fontSize: 16, color: Colors.black87), + ), + ), + Align( + alignment: Alignment.topRight, + child: InkWell( + child: Icon(Icons.close), + onTap: () => _pop(context), + ), + ), + ], + ), + ), + Expanded( + flex: 1, + child: Container( + width: double.infinity, + padding: EdgeInsets.all(10), + child: StatefulBuilder( + builder: (context, setState) { + _stateSetter = setState; + return DefaultTabController( + length: 2, + child: Column( + children: [ + Container( + constraints: BoxConstraints.expand(height: 24), + child: TabBar( + onTap: (value) => Future.delayed( + Duration(milliseconds: 300), () { + _sourceType = value == 0 + ? SourceType.Screen + : SourceType.Window; + _getSources(); + }), + tabs: [ + Tab( + child: Text( + 'Entrire Screen', + style: TextStyle(color: Colors.black54), + )), + Tab( + child: Text( + 'Window', + style: TextStyle(color: Colors.black54), + )), + ]), + ), + SizedBox( + height: 2, + ), + Expanded( + child: Container( + child: TabBarView(children: [ + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 2, + children: _sources + .where((element) => + element.type == + SourceType.Screen) + .map((e) => Column( + children: [ + Expanded( + child: Container( + decoration: (_selected_source != + null && + _selected_source! + .id == + e.id) + ? BoxDecoration( + border: Border.all( + width: 2, + color: Colors + .blueAccent)) + : null, + child: InkWell( + onTap: () { + print( + 'Selected screen id => ${e.id}'); + setState(() { + _selected_source = + e; + }); + }, + child: + e.thumbnail != null + ? Image.memory( + e.thumbnail!, + scale: 1.0, + repeat: ImageRepeat + .noRepeat, + ) + : Container(), + ), + )), + Text( + e.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: (_selected_source != + null && + _selected_source! + .id == + e.id) + ? FontWeight.bold + : FontWeight + .normal), + ), + ], + )) + .toList(), + ), + )), + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 3, + children: _sources + .where((element) => + element.type == + SourceType.Window) + .map((e) => Column( + children: [ + Expanded( + child: Container( + decoration: (_selected_source != + null && + _selected_source! + .id == + e.id) + ? BoxDecoration( + border: Border.all( + width: 2, + color: Colors + .blueAccent)) + : null, + child: InkWell( + onTap: () { + print( + 'Selected window id => ${e.id}'); + setState(() { + _selected_source = + e; + }); + }, + child: + e.thumbnail != null + ? Image.memory( + e.thumbnail!, + scale: 1.0, + repeat: ImageRepeat + .noRepeat, + ) + : Container(), + ), + )), + Text( + e.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: (_selected_source != + null && + _selected_source! + .id == + e.id) + ? FontWeight.bold + : FontWeight + .normal), + ), + ], + )) + .toList(), + ), + )), + ]), + ), + ) + ], + ), + ); + }, + ), + ), + ), + Container( + width: double.infinity, + child: ButtonBar( + children: [ + MaterialButton( + child: Text( + 'Cancel', + style: TextStyle(color: Colors.black54), + ), + onPressed: () { + _pop(context); + }, + ), + MaterialButton( + color: Theme.of(context).primaryColor, + child: Text( + 'Share', + ), + onPressed: () { + _pop(context); + }, + ), + ], + ), + ), + ], + ), + )), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index a8f880d..6b2a06b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.8.3 + flutter_webrtc: ^0.8.12 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From 14e8b588b80bd95298bc2d8cabdaed71d86cb67e Mon Sep 17 00:00:00 2001 From: Jun Huh Date: Wed, 20 Jul 2022 07:26:16 +0200 Subject: [PATCH 53/69] Fix remote peer video is blank https://github.com/flutter-webrtc/flutter-webrtc-demo/issues/118 --- lib/src/call_sample/call_sample.dart | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index 9f6cc0d..ee3b5f5 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -116,10 +116,12 @@ class _CallSampleState extends State { _signaling?.onLocalStream = ((stream) { _localRenderer.srcObject = stream; + setState(() {}); }); _signaling?.onAddRemoteStream = ((_, stream) { _remoteRenderer.srcObject = stream; + setState(() {}); }); _signaling?.onRemoveRemoteStream = ((_, stream) { From 0d29d55fed76ab75d45eaa4472a6ed15c45bcc86 Mon Sep 17 00:00:00 2001 From: "duanweiwei1982@gmail.com" Date: Wed, 27 Jul 2022 09:29:50 +0800 Subject: [PATCH 54/69] chore: fix bugs. --- lib/src/call_sample/call_sample.dart | 55 ++++++----- lib/src/call_sample/signaling.dart | 16 ++-- lib/src/widgets/screen_select_dialog.dart | 111 +++++++++++++++------- pubspec.yaml | 6 +- 4 files changed, 119 insertions(+), 69 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index e36aa5c..2c875a7 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -207,33 +207,38 @@ class _CallSampleState extends State { } Future selectScreenSourceDialog(BuildContext context) async { - final source = await showDialog( - context: context, - builder: (context) => ScreenSelectDialog(), - ); - if (source != null) { - try { - var stream = - await navigator.mediaDevices.getDisplayMedia({ - 'video': { - 'deviceId': {'exact': source.id}, - 'mandatory': {'frameRate': 30.0} - } - }); - stream.getVideoTracks()[0].onEnded = () { - print( - 'By adding a listener on onEnded you can: 1) catch stop video sharing on Web'); - }; - _signaling?.switchToScreenSharing(stream); - } catch (e) { - print(e); + MediaStream? screenStream; + if (WebRTC.platformIsDesktop) { + final source = await showDialog( + context: context, + builder: (context) => ScreenSelectDialog(), + ); + if (source != null) { + try { + var stream = + await navigator.mediaDevices.getDisplayMedia({ + 'video': { + 'deviceId': {'exact': source.id}, + 'mandatory': {'frameRate': 30.0} + } + }); + stream.getVideoTracks()[0].onEnded = () { + print( + 'By adding a listener on onEnded you can: 1) catch stop video sharing on Web'); + }; + screenStream = stream; + } catch (e) { + print(e); + } } - //await _makeCall(source); + } else if (WebRTC.platformIsWeb) { + screenStream = + await navigator.mediaDevices.getDisplayMedia({ + 'audio': false, + 'video': true, + }); } - } - - _switchScreenSharing() { - //_signaling?.switchToScreenSharing(); + if (screenStream != null) _signaling?.switchToScreenSharing(screenStream); } _muteMic() { diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 2a5dd6e..14599ae 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -52,7 +52,7 @@ class Signaling { MediaStream? _localStream; List _remoteStreams = []; List _senders = []; - VideoSource videoSource = VideoSource.Camera; + VideoSource _videoSource = VideoSource.Camera; Function(SignalingState state)? onSignalingStateChange; Function(Session session, CallState state)? onCallStateChange; @@ -102,14 +102,13 @@ class Signaling { void switchCamera() { if (_localStream != null) { - if (videoSource != VideoSource.Camera) { - switchVideoSource(source: VideoSource.Camera); + if (_videoSource != VideoSource.Camera) { _senders.forEach((sender) { if (sender.track!.kind == 'video') { sender.replaceTrack(_localStream!.getVideoTracks()[0]); } }); - videoSource = VideoSource.Camera; + _videoSource = VideoSource.Camera; onLocalStream?.call(_localStream!); } else { Helper.switchCamera(_localStream!.getVideoTracks()[0]); @@ -118,20 +117,17 @@ class Signaling { } void switchToScreenSharing(MediaStream stream) { - if (_localStream != null && videoSource != VideoSource.Screen) { - switchVideoSource(source: VideoSource.Screen); + if (_localStream != null && _videoSource != VideoSource.Screen) { _senders.forEach((sender) { if (sender.track!.kind == 'video') { sender.replaceTrack(stream.getVideoTracks()[0]); } }); onLocalStream?.call(stream); - videoSource = VideoSource.Screen; + _videoSource = VideoSource.Screen; } } - void switchVideoSource({VideoSource source = VideoSource.Camera}) {} - void muteMic() { if (_localStream != null) { bool enabled = _localStream!.getAudioTracks()[0].enabled; @@ -571,5 +567,7 @@ class Signaling { await session.pc?.close(); await session.dc?.close(); + _senders.clear(); + _videoSource = VideoSource.Camera; } } diff --git a/lib/src/widgets/screen_select_dialog.dart b/lib/src/widgets/screen_select_dialog.dart index 1697944..496c9b0 100644 --- a/lib/src/widgets/screen_select_dialog.dart +++ b/lib/src/widgets/screen_select_dialog.dart @@ -8,22 +8,51 @@ class ScreenSelectDialog extends Dialog { ScreenSelectDialog() { Future.delayed(Duration(milliseconds: 100), () { _getSources(); - _timer = Timer.periodic(Duration(milliseconds: 2000), (timer) { - _getSources(); - }); }); + _subscriptions.add(desktopCapturer.onAdded.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); + + _subscriptions.add(desktopCapturer.onRemoved.stream.listen((source) { + _sources.remove(source.id); + _stateSetter?.call(() {}); + })); + + _subscriptions.add(desktopCapturer.onNameChanged.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); + + _subscriptions + .add(desktopCapturer.onThumbnailChanged.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); } - List _sources = []; + final Map _sources = {}; SourceType _sourceType = SourceType.Screen; DesktopCapturerSource? _selected_source; + final List> _subscriptions = []; StateSetter? _stateSetter; Timer? _timer; - void _pop(context) { + void _ok(context) async { _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); Navigator.pop(context, _selected_source); } + void _cancel(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, null); + } + Future _getSources() async { try { var sources = await desktopCapturer.getSources(types: [_sourceType]); @@ -32,7 +61,13 @@ class ScreenSelectDialog extends Dialog { 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); }); _stateSetter?.call(() { - _sources = sources; + sources.forEach((element) { + _sources[element.id] = element; + }); + }); + _timer?.cancel(); + _timer = Timer.periodic(Duration(seconds: 3), (timer) { + desktopCapturer.updateSources(types: [_sourceType]); }); return; } catch (e) { @@ -66,7 +101,7 @@ class ScreenSelectDialog extends Dialog { alignment: Alignment.topRight, child: InkWell( child: Icon(Icons.close), - onTap: () => _pop(context), + onTap: () => _cancel(context), ), ), ], @@ -97,7 +132,7 @@ class ScreenSelectDialog extends Dialog { tabs: [ Tab( child: Text( - 'Entrire Screen', + 'Entire Screen', style: TextStyle(color: Colors.black54), )), Tab( @@ -119,9 +154,9 @@ class ScreenSelectDialog extends Dialog { child: GridView.count( crossAxisSpacing: 8, crossAxisCount: 2, - children: _sources + children: _sources.entries .where((element) => - element.type == + element.value.type == SourceType.Screen) .map((e) => Column( children: [ @@ -131,7 +166,7 @@ class ScreenSelectDialog extends Dialog { null && _selected_source! .id == - e.id) + e.value.id) ? BoxDecoration( border: Border.all( width: 2, @@ -141,16 +176,18 @@ class ScreenSelectDialog extends Dialog { child: InkWell( onTap: () { print( - 'Selected screen id => ${e.id}'); + 'Selected screen id => ${e.value.id}'); setState(() { _selected_source = - e; + e.value; }); }, child: - e.thumbnail != null + e.value.thumbnail != + null ? Image.memory( - e.thumbnail!, + e.value + .thumbnail!, scale: 1.0, repeat: ImageRepeat .noRepeat, @@ -159,7 +196,7 @@ class ScreenSelectDialog extends Dialog { ), )), Text( - e.name, + e.value.name, style: TextStyle( fontSize: 12, color: Colors.black87, @@ -167,7 +204,8 @@ class ScreenSelectDialog extends Dialog { null && _selected_source! .id == - e.id) + e.value + .id) ? FontWeight.bold : FontWeight .normal), @@ -183,9 +221,9 @@ class ScreenSelectDialog extends Dialog { child: GridView.count( crossAxisSpacing: 8, crossAxisCount: 3, - children: _sources + children: _sources.entries .where((element) => - element.type == + element.value.type == SourceType.Window) .map((e) => Column( children: [ @@ -195,7 +233,7 @@ class ScreenSelectDialog extends Dialog { null && _selected_source! .id == - e.id) + e.value.id) ? BoxDecoration( border: Border.all( width: 2, @@ -205,25 +243,29 @@ class ScreenSelectDialog extends Dialog { child: InkWell( onTap: () { print( - 'Selected window id => ${e.id}'); + 'Selected window id => ${e.value.id}'); setState(() { _selected_source = - e; + e.value; }); }, - child: - e.thumbnail != null - ? Image.memory( - e.thumbnail!, - scale: 1.0, - repeat: ImageRepeat + child: e + .value + .thumbnail! + .isNotEmpty + ? Image.memory( + e.value + .thumbnail!, + scale: 1.0, + repeat: + ImageRepeat .noRepeat, - ) - : Container(), + ) + : Container(), ), )), Text( - e.name, + e.value.name, style: TextStyle( fontSize: 12, color: Colors.black87, @@ -231,7 +273,8 @@ class ScreenSelectDialog extends Dialog { null && _selected_source! .id == - e.id) + e.value + .id) ? FontWeight.bold : FontWeight .normal), @@ -261,7 +304,7 @@ class ScreenSelectDialog extends Dialog { style: TextStyle(color: Colors.black54), ), onPressed: () { - _pop(context); + _cancel(context); }, ), MaterialButton( @@ -270,7 +313,7 @@ class ScreenSelectDialog extends Dialog { 'Share', ), onPressed: () { - _pop(context); + _ok(context); }, ), ], diff --git a/pubspec.yaml b/pubspec.yaml index 6b2a06b..e43dae6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,11 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.8.12 + flutter_webrtc: + git: + url: https://github.com/flutter-webrtc/flutter-webrtc.git + ref: feat/screen-capture-event-listener-for-win + shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From 198ccba6f5909e23fe8eaef27d8a64db4f08da24 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Sun, 31 Jul 2022 22:53:35 +0800 Subject: [PATCH 55/69] update. --- android/app/build.gradle | 1 + pubspec.yaml | 6 +----- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 57cc757..568b1ac 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -26,6 +26,7 @@ apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" android { compileSdkVersion 28 + ndkVersion "21.4.7075529" lintOptions { disable 'InvalidPackage' diff --git a/pubspec.yaml b/pubspec.yaml index e43dae6..e6e3ac6 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,11 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: - git: - url: https://github.com/flutter-webrtc/flutter-webrtc.git - ref: feat/screen-capture-event-listener-for-win - + flutter_webrtc: ^0.9.0 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From ad0dd2838d862d14cdb5c8bb19af007ecdbe24e2 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Fri, 23 Sep 2022 17:55:19 +0800 Subject: [PATCH 56/69] bump version for flutter-webrtc. --- lib/src/call_sample/call_sample.dart | 14 +- lib/src/call_sample/data_channel_sample.dart | 6 +- lib/src/call_sample/signaling.dart | 47 ++- lib/src/utils/screen_select_dialog.dart | 307 +++++++++++++++++++ pubspec.yaml | 2 +- 5 files changed, 353 insertions(+), 23 deletions(-) create mode 100644 lib/src/utils/screen_select_dialog.dart diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index ee3b5f5..ff20912 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -20,7 +20,7 @@ class _CallSampleState extends State { RTCVideoRenderer _remoteRenderer = RTCVideoRenderer(); bool _inCalling = false; Session? _session; - + DesktopCapturerSource? selected_source_; bool _waitAccept = false; // ignore: unused_element @@ -30,7 +30,7 @@ class _CallSampleState extends State { initState() { super.initState(); initRenderers(); - _connect(); + _connect(context); } initRenderers() async { @@ -46,8 +46,8 @@ class _CallSampleState extends State { _remoteRenderer.dispose(); } - void _connect() async { - _signaling ??= Signaling(widget.host)..connect(); + void _connect(BuildContext context) async { + _signaling ??= Signaling(widget.host, context)..connect(); _signaling?.onSignalingStateChange = (SignalingState state) { switch (state) { case SignalingState.ConnectionClosed: @@ -71,8 +71,7 @@ class _CallSampleState extends State { setState(() { _inCalling = true; }); - } - else { + } else { _reject(); } break; @@ -166,8 +165,7 @@ class _CallSampleState extends State { onPressed: () { Navigator.of(context).pop(false); _hangUp(); - }, - + }, ), ], ); diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index 601729c..aaca560 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -29,7 +29,7 @@ class _DataChannelSampleState extends State { @override initState() { super.initState(); - _connect(); + _connect(context); } @override @@ -39,8 +39,8 @@ class _DataChannelSampleState extends State { _timer?.cancel(); } - void _connect() async { - _signaling ??= Signaling(widget.host)..connect(); + void _connect(BuildContext context) async { + _signaling ??= Signaling(widget.host, context)..connect(); _signaling?.onDataChannelMessage = (_, dc, RTCDataChannelMessage data) { setState(() { diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 8fe84a2..078b42e 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -1,7 +1,9 @@ import 'dart:convert'; import 'dart:async'; +import 'package:flutter/material.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; +import '../utils/screen_select_dialog.dart'; import 'random_string.dart'; import '../utils/device_info.dart' @@ -34,12 +36,13 @@ class Session { } class Signaling { - Signaling(this._host); + Signaling(this._host, this._context); JsonEncoder _encoder = JsonEncoder(); JsonDecoder _decoder = JsonDecoder(); String _selfId = randomNumeric(6); SimpleWebSocket? _socket; + BuildContext? _context; var _host; var _port = 8086; var _turnCredential; @@ -303,7 +306,8 @@ class Signaling { await _socket?.connect(); } - Future createStream(String media, bool userScreen) async { + Future createStream(String media, bool userScreen, + {BuildContext? context}) async { final Map mediaConstraints = { 'audio': userScreen ? false : true, 'video': userScreen @@ -319,22 +323,43 @@ class Signaling { 'optional': [], } }; + late MediaStream stream; + if (userScreen) { + if (WebRTC.platformIsDesktop) { + final source = await showDialog( + context: context!, + builder: (context) => ScreenSelectDialog(), + ); + stream = await navigator.mediaDevices.getDisplayMedia({ + 'video': source == null + ? true + : { + 'deviceId': {'exact': source.id}, + 'mandatory': {'frameRate': 30.0} + } + }); + } else { + stream = await navigator.mediaDevices.getDisplayMedia(mediaConstraints); + } + } else { + stream = await navigator.mediaDevices.getUserMedia(mediaConstraints); + } - MediaStream stream = userScreen - ? await navigator.mediaDevices.getDisplayMedia(mediaConstraints) - : await navigator.mediaDevices.getUserMedia(mediaConstraints); onLocalStream?.call(stream); return stream; } - Future _createSession(Session? session, - {required String peerId, - required String sessionId, - required String media, - required bool screenSharing}) async { + Future _createSession( + Session? session, { + required String peerId, + required String sessionId, + required String media, + required bool screenSharing, + }) async { var newSession = session ?? Session(sid: sessionId, pid: peerId); if (media != 'data') - _localStream = await createStream(media, screenSharing); + _localStream = + await createStream(media, screenSharing, context: _context); print(_iceServers); RTCPeerConnection pc = await createPeerConnection({ ..._iceServers, diff --git a/lib/src/utils/screen_select_dialog.dart b/lib/src/utils/screen_select_dialog.dart new file mode 100644 index 0000000..45a4f2a --- /dev/null +++ b/lib/src/utils/screen_select_dialog.dart @@ -0,0 +1,307 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_webrtc/flutter_webrtc.dart'; + +class ThumbnailWidget extends StatefulWidget { + const ThumbnailWidget( + {Key? key, + required this.source, + required this.selected, + required this.onTap}) + : super(key: key); + final DesktopCapturerSource source; + final bool selected; + final Function(DesktopCapturerSource) onTap; + + @override + _ThumbnailWidgetState createState() => _ThumbnailWidgetState(); +} + +class _ThumbnailWidgetState extends State { + final List _subscriptions = []; + + @override + void initState() { + super.initState(); + _subscriptions.add(widget.source.onThumbnailChanged.stream.listen((event) { + setState(() {}); + })); + _subscriptions.add(widget.source.onNameChanged.stream.listen((event) { + setState(() {}); + })); + } + + @override + void deactivate() { + _subscriptions.forEach((element) { + element.cancel(); + }); + super.deactivate(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Expanded( + child: Container( + decoration: widget.selected + ? BoxDecoration( + border: Border.all(width: 2, color: Colors.blueAccent)) + : null, + child: InkWell( + onTap: () { + print('Selected source id => ${widget.source.id}'); + widget.onTap(widget.source); + }, + child: widget.source.thumbnail != null + ? Image.memory( + widget.source.thumbnail!, + gaplessPlayback: true, + alignment: Alignment.center, + ) + : Container(), + ), + )), + Text( + widget.source.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: + widget.selected ? FontWeight.bold : FontWeight.normal), + ), + ], + ); + } +} + +// ignore: must_be_immutable +class ScreenSelectDialog extends Dialog { + ScreenSelectDialog() { + Future.delayed(Duration(milliseconds: 100), () { + _getSources(); + }); + _subscriptions.add(desktopCapturer.onAdded.stream.listen((source) { + _sources[source.id] = source; + _stateSetter?.call(() {}); + })); + + _subscriptions.add(desktopCapturer.onRemoved.stream.listen((source) { + _sources.remove(source.id); + _stateSetter?.call(() {}); + })); + + _subscriptions + .add(desktopCapturer.onThumbnailChanged.stream.listen((source) { + _stateSetter?.call(() {}); + })); + } + final Map _sources = {}; + SourceType _sourceType = SourceType.Screen; + DesktopCapturerSource? _selected_source; + final List> _subscriptions = []; + StateSetter? _stateSetter; + Timer? _timer; + + void _ok(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, _selected_source); + } + + void _cancel(context) async { + _timer?.cancel(); + _subscriptions.forEach((element) { + element.cancel(); + }); + Navigator.pop(context, null); + } + + Future _getSources() async { + try { + var sources = await desktopCapturer.getSources(types: [_sourceType]); + sources.forEach((element) { + print( + 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); + }); + _timer?.cancel(); + _timer = Timer.periodic(Duration(seconds: 3), (timer) { + desktopCapturer.updateSources(types: [_sourceType]); + }); + _sources.clear(); + sources.forEach((element) { + _sources[element.id] = element; + }); + _stateSetter?.call(() {}); + return; + } catch (e) { + print(e.toString()); + } + } + + @override + Widget build(BuildContext context) { + return Material( + type: MaterialType.transparency, + child: Center( + child: Container( + width: 640, + height: 560, + color: Colors.white, + child: Column( + children: [ + Padding( + padding: EdgeInsets.all(10), + child: Stack( + children: [ + Align( + alignment: Alignment.topLeft, + child: Text( + 'Choose what to share', + style: TextStyle(fontSize: 16, color: Colors.black87), + ), + ), + Align( + alignment: Alignment.topRight, + child: InkWell( + child: Icon(Icons.close), + onTap: () => _cancel(context), + ), + ), + ], + ), + ), + Expanded( + flex: 1, + child: Container( + width: double.infinity, + padding: EdgeInsets.all(10), + child: StatefulBuilder( + builder: (context, setState) { + _stateSetter = setState; + return DefaultTabController( + length: 2, + child: Column( + children: [ + Container( + constraints: BoxConstraints.expand(height: 24), + child: TabBar( + onTap: (value) => Future.delayed( + Duration(milliseconds: 300), () { + _sourceType = value == 0 + ? SourceType.Screen + : SourceType.Window; + _getSources(); + }), + tabs: [ + Tab( + child: Text( + 'Entire Screen', + style: TextStyle(color: Colors.black54), + )), + Tab( + child: Text( + 'Window', + style: TextStyle(color: Colors.black54), + )), + ]), + ), + SizedBox( + height: 2, + ), + Expanded( + child: Container( + child: TabBarView(children: [ + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 2, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Screen) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + Align( + alignment: Alignment.center, + child: Container( + child: GridView.count( + crossAxisSpacing: 8, + crossAxisCount: 3, + children: _sources.entries + .where((element) => + element.value.type == + SourceType.Window) + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, + )) + .toList(), + ), + )), + ]), + ), + ) + ], + ), + ); + }, + ), + ), + ), + Container( + width: double.infinity, + child: ButtonBar( + children: [ + MaterialButton( + child: Text( + 'Cancel', + style: TextStyle(color: Colors.black54), + ), + onPressed: () { + _cancel(context); + }, + ), + MaterialButton( + color: Theme.of(context).primaryColor, + child: Text( + 'Share', + ), + onPressed: () { + _ok(context); + }, + ), + ], + ), + ), + ], + ), + )), + ); + } +} diff --git a/pubspec.yaml b/pubspec.yaml index a8f880d..22aac78 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.8.3 + flutter_webrtc: ^0.9.7 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From 53880d61db78ecf3b7b34799e0b429303618983b Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Fri, 23 Sep 2022 18:02:37 +0800 Subject: [PATCH 57/69] Update pubspec.yaml --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 22aac78..87a8009 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -3,7 +3,7 @@ description: A new Flutter application. version: 1.2.0 environment: - sdk: '>=2.12.0 <3.0.0' + sdk: '>=2.15.0 <3.0.0' flutter: '>=1.22.0' dependencies: From 8df9f40b67ee46c2b8c8d69bf15d83366ca576d9 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Fri, 23 Sep 2022 18:16:29 +0800 Subject: [PATCH 58/69] Update flutter.yml --- .github/workflows/flutter.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/flutter.yml b/.github/workflows/flutter.yml index d6ea4a3..3b9b3ae 100644 --- a/.github/workflows/flutter.yml +++ b/.github/workflows/flutter.yml @@ -22,7 +22,7 @@ jobs: java-version: '12.x' - uses: subosito/flutter-action@v1 with: - flutter-version: '2.0.5' + flutter-version: '3.3.2' channel: 'stable' - run: flutter packages get - run: flutter test From 3136076a2bf85f74f5d327244bd7c2ba5441ad83 Mon Sep 17 00:00:00 2001 From: Jeesang Kim Date: Fri, 23 Sep 2022 21:24:52 +0900 Subject: [PATCH 59/69] remove ignored dependencies --- .../plugins/GeneratedPluginRegistrant.java | 20 ----------- ios/Runner/GeneratedPluginRegistrant.h | 17 ---------- ios/Runner/GeneratedPluginRegistrant.m | 33 ------------------- 3 files changed, 70 deletions(-) delete mode 100644 android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java delete mode 100644 ios/Runner/GeneratedPluginRegistrant.h delete mode 100644 ios/Runner/GeneratedPluginRegistrant.m diff --git a/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java b/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java deleted file mode 100644 index c18798d..0000000 --- a/android/app/src/main/java/io/flutter/plugins/GeneratedPluginRegistrant.java +++ /dev/null @@ -1,20 +0,0 @@ -package io.flutter.plugins; - -import androidx.annotation.Keep; -import androidx.annotation.NonNull; - -import io.flutter.embedding.engine.FlutterEngine; - -/** - * Generated file. Do not edit. - * This file is generated by the Flutter tool based on the - * plugins that support the Android platform. - */ -@Keep -public final class GeneratedPluginRegistrant { - public static void registerWith(@NonNull FlutterEngine flutterEngine) { - flutterEngine.getPlugins().add(new com.cloudwebrtc.webrtc.FlutterWebRTCPlugin()); - flutterEngine.getPlugins().add(new io.flutter.plugins.pathprovider.PathProviderPlugin()); - flutterEngine.getPlugins().add(new io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin()); - } -} diff --git a/ios/Runner/GeneratedPluginRegistrant.h b/ios/Runner/GeneratedPluginRegistrant.h deleted file mode 100644 index ed9a5c6..0000000 --- a/ios/Runner/GeneratedPluginRegistrant.h +++ /dev/null @@ -1,17 +0,0 @@ -// -// Generated file. Do not edit. -// - -#ifndef GeneratedPluginRegistrant_h -#define GeneratedPluginRegistrant_h - -#import - -NS_ASSUME_NONNULL_BEGIN - -@interface GeneratedPluginRegistrant : NSObject -+ (void)registerWithRegistry:(NSObject*)registry; -@end - -NS_ASSUME_NONNULL_END -#endif /* GeneratedPluginRegistrant_h */ diff --git a/ios/Runner/GeneratedPluginRegistrant.m b/ios/Runner/GeneratedPluginRegistrant.m deleted file mode 100644 index 8331b4a..0000000 --- a/ios/Runner/GeneratedPluginRegistrant.m +++ /dev/null @@ -1,33 +0,0 @@ -// -// Generated file. Do not edit. -// - -#import "GeneratedPluginRegistrant.h" - -#if __has_include() -#import -#else -@import flutter_webrtc; -#endif - -#if __has_include() -#import -#else -@import path_provider; -#endif - -#if __has_include() -#import -#else -@import shared_preferences; -#endif - -@implementation GeneratedPluginRegistrant - -+ (void)registerWithRegistry:(NSObject*)registry { - [FlutterWebRTCPlugin registerWithRegistrar:[registry registrarForPlugin:@"FlutterWebRTCPlugin"]]; - [FLTPathProviderPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTPathProviderPlugin"]]; - [FLTSharedPreferencesPlugin registerWithRegistrar:[registry registrarForPlugin:@"FLTSharedPreferencesPlugin"]]; -} - -@end From 0cc2747f49bf9a2f0c0c70458648f05c1a9a528e Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 20 Oct 2022 17:36:58 +0800 Subject: [PATCH 60/69] update. --- lib/src/widgets/screen_select_dialog.dart | 218 ++++++++++------------ 1 file changed, 99 insertions(+), 119 deletions(-) diff --git a/lib/src/widgets/screen_select_dialog.dart b/lib/src/widgets/screen_select_dialog.dart index 496c9b0..45a4f2a 100644 --- a/lib/src/widgets/screen_select_dialog.dart +++ b/lib/src/widgets/screen_select_dialog.dart @@ -3,6 +3,80 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_webrtc/flutter_webrtc.dart'; +class ThumbnailWidget extends StatefulWidget { + const ThumbnailWidget( + {Key? key, + required this.source, + required this.selected, + required this.onTap}) + : super(key: key); + final DesktopCapturerSource source; + final bool selected; + final Function(DesktopCapturerSource) onTap; + + @override + _ThumbnailWidgetState createState() => _ThumbnailWidgetState(); +} + +class _ThumbnailWidgetState extends State { + final List _subscriptions = []; + + @override + void initState() { + super.initState(); + _subscriptions.add(widget.source.onThumbnailChanged.stream.listen((event) { + setState(() {}); + })); + _subscriptions.add(widget.source.onNameChanged.stream.listen((event) { + setState(() {}); + })); + } + + @override + void deactivate() { + _subscriptions.forEach((element) { + element.cancel(); + }); + super.deactivate(); + } + + @override + Widget build(BuildContext context) { + return Column( + children: [ + Expanded( + child: Container( + decoration: widget.selected + ? BoxDecoration( + border: Border.all(width: 2, color: Colors.blueAccent)) + : null, + child: InkWell( + onTap: () { + print('Selected source id => ${widget.source.id}'); + widget.onTap(widget.source); + }, + child: widget.source.thumbnail != null + ? Image.memory( + widget.source.thumbnail!, + gaplessPlayback: true, + alignment: Alignment.center, + ) + : Container(), + ), + )), + Text( + widget.source.name, + style: TextStyle( + fontSize: 12, + color: Colors.black87, + fontWeight: + widget.selected ? FontWeight.bold : FontWeight.normal), + ), + ], + ); + } +} + // ignore: must_be_immutable class ScreenSelectDialog extends Dialog { ScreenSelectDialog() { @@ -19,14 +93,8 @@ class ScreenSelectDialog extends Dialog { _stateSetter?.call(() {}); })); - _subscriptions.add(desktopCapturer.onNameChanged.stream.listen((source) { - _sources[source.id] = source; - _stateSetter?.call(() {}); - })); - _subscriptions .add(desktopCapturer.onThumbnailChanged.stream.listen((source) { - _sources[source.id] = source; _stateSetter?.call(() {}); })); } @@ -60,15 +128,15 @@ class ScreenSelectDialog extends Dialog { print( 'name: ${element.name}, id: ${element.id}, type: ${element.type}'); }); - _stateSetter?.call(() { - sources.forEach((element) { - _sources[element.id] = element; - }); - }); _timer?.cancel(); _timer = Timer.periodic(Duration(seconds: 3), (timer) { desktopCapturer.updateSources(types: [_sourceType]); }); + _sources.clear(); + sources.forEach((element) { + _sources[element.id] = element; + }); + _stateSetter?.call(() {}); return; } catch (e) { print(e.toString()); @@ -158,59 +226,16 @@ class ScreenSelectDialog extends Dialog { .where((element) => element.value.type == SourceType.Screen) - .map((e) => Column( - children: [ - Expanded( - child: Container( - decoration: (_selected_source != - null && - _selected_source! - .id == - e.value.id) - ? BoxDecoration( - border: Border.all( - width: 2, - color: Colors - .blueAccent)) - : null, - child: InkWell( - onTap: () { - print( - 'Selected screen id => ${e.value.id}'); - setState(() { - _selected_source = - e.value; - }); - }, - child: - e.value.thumbnail != - null - ? Image.memory( - e.value - .thumbnail!, - scale: 1.0, - repeat: ImageRepeat - .noRepeat, - ) - : Container(), - ), - )), - Text( - e.value.name, - style: TextStyle( - fontSize: 12, - color: Colors.black87, - fontWeight: (_selected_source != - null && - _selected_source! - .id == - e.value - .id) - ? FontWeight.bold - : FontWeight - .normal), - ), - ], + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, )) .toList(), ), @@ -225,61 +250,16 @@ class ScreenSelectDialog extends Dialog { .where((element) => element.value.type == SourceType.Window) - .map((e) => Column( - children: [ - Expanded( - child: Container( - decoration: (_selected_source != - null && - _selected_source! - .id == - e.value.id) - ? BoxDecoration( - border: Border.all( - width: 2, - color: Colors - .blueAccent)) - : null, - child: InkWell( - onTap: () { - print( - 'Selected window id => ${e.value.id}'); - setState(() { - _selected_source = - e.value; - }); - }, - child: e - .value - .thumbnail! - .isNotEmpty - ? Image.memory( - e.value - .thumbnail!, - scale: 1.0, - repeat: - ImageRepeat - .noRepeat, - ) - : Container(), - ), - )), - Text( - e.value.name, - style: TextStyle( - fontSize: 12, - color: Colors.black87, - fontWeight: (_selected_source != - null && - _selected_source! - .id == - e.value - .id) - ? FontWeight.bold - : FontWeight - .normal), - ), - ], + .map((e) => ThumbnailWidget( + onTap: (source) { + setState(() { + _selected_source = source; + }); + }, + source: e.value, + selected: + _selected_source?.id == + e.value.id, )) .toList(), ), From 48b6c64be4a560e6ea84e0a62c6f5ef93cd898e6 Mon Sep 17 00:00:00 2001 From: cloudwebrtc Date: Thu, 20 Oct 2022 22:14:38 +0800 Subject: [PATCH 61/69] change profile-level-id to fix issue for screen sharing on macOS. --- lib/src/call_sample/signaling.dart | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index 14599ae..ff59b7c 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -494,7 +494,7 @@ class Signaling { try { RTCSessionDescription s = await session.pc!.createOffer(media == 'data' ? _dcConstraints : {}); - await session.pc!.setLocalDescription(s); + await session.pc!.setLocalDescription(_fixSdp(s)); _send('offer', { 'to': session.pid, 'from': _selfId, @@ -507,11 +507,18 @@ class Signaling { } } + RTCSessionDescription _fixSdp(RTCSessionDescription s) { + var sdp = s.sdp; + s.sdp = + sdp!.replaceAll('profile-level-id=640c1f', 'profile-level-id=42e032'); + return s; + } + Future _createAnswer(Session session, String media) async { try { RTCSessionDescription s = await session.pc!.createAnswer(media == 'data' ? _dcConstraints : {}); - await session.pc!.setLocalDescription(s); + await session.pc!.setLocalDescription(_fixSdp(s)); _send('answer', { 'to': session.pid, 'from': _selfId, From 420495f55ff6345d8e28d622dbc77d1cab09d327 Mon Sep 17 00:00:00 2001 From: "duanweiwei1982@gmail.com" Date: Thu, 20 Oct 2022 22:38:11 +0800 Subject: [PATCH 62/69] bump version for flutter-webrtc. --- pubspec.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index e6e3ac6..360f7d8 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.9.0 + flutter_webrtc: ^0.9.11 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 From 830b81ee31a0d4c374fb80048d81c65fd54f298e Mon Sep 17 00:00:00 2001 From: xiaowei guan Date: Fri, 24 Mar 2023 09:16:45 +0800 Subject: [PATCH 63/69] Fix data channel not work issue Need set local description when recevie offer event. copy code from call_sample.dart --- lib/src/call_sample/call_sample.dart | 2 +- lib/src/call_sample/data_channel_sample.dart | 123 ++++++++++++++++--- lib/src/call_sample/signaling.dart | 4 +- 3 files changed, 106 insertions(+), 23 deletions(-) diff --git a/lib/src/call_sample/call_sample.dart b/lib/src/call_sample/call_sample.dart index d0a289b..fac35f2 100644 --- a/lib/src/call_sample/call_sample.dart +++ b/lib/src/call_sample/call_sample.dart @@ -186,7 +186,7 @@ class _CallSampleState extends State { _accept() { if (_session != null) { - _signaling?.accept(_session!.sid); + _signaling?.accept(_session!.sid, 'video'); } } diff --git a/lib/src/call_sample/data_channel_sample.dart b/lib/src/call_sample/data_channel_sample.dart index aaca560..e9bb883 100644 --- a/lib/src/call_sample/data_channel_sample.dart +++ b/lib/src/call_sample/data_channel_sample.dart @@ -25,6 +25,7 @@ class _DataChannelSampleState extends State { var _text = ''; // ignore: unused_element _DataChannelSampleState(); + bool _waitAccept = false; @override initState() { @@ -39,6 +40,55 @@ class _DataChannelSampleState extends State { _timer?.cancel(); } + Future _showAcceptDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("accept?"), + actions: [ + MaterialButton( + child: Text( + 'Reject', + style: TextStyle(color: Colors.red), + ), + onPressed: () => Navigator.of(context).pop(false), + ), + MaterialButton( + child: Text( + 'Accept', + style: TextStyle(color: Colors.green), + ), + onPressed: () => Navigator.of(context).pop(true), + ), + ], + ); + }, + ); + } + + Future _showInvateDialog() { + return showDialog( + context: context, + builder: (context) { + return AlertDialog( + title: Text("title"), + content: Text("waiting"), + actions: [ + TextButton( + child: Text("cancel"), + onPressed: () { + Navigator.of(context).pop(false); + _hangUp(); + }, + ), + ], + ); + }, + ); + } + void _connect(BuildContext context) async { _signaling ??= Signaling(widget.host, context)..connect(); @@ -65,33 +115,54 @@ class _DataChannelSampleState extends State { } }; - _signaling?.onCallStateChange = (Session session, CallState state) { + _signaling?.onCallStateChange = (Session session, CallState state) async { switch (state) { case CallState.CallStateNew: - { - setState(() { - _session = session; - _inCalling = true; - }); - _timer = - Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); - break; - } + setState(() { + _session = session; + }); + _timer = Timer.periodic(Duration(seconds: 1), _handleDataChannelTest); + break; case CallState.CallStateBye: - { - setState(() { - _inCalling = false; - }); - _timer?.cancel(); - _dataChannel = null; - _inCalling = false; - _session = null; - _text = ''; - break; + if (_waitAccept) { + print('peer reject'); + _waitAccept = false; + Navigator.of(context).pop(false); } + setState(() { + _inCalling = false; + }); + _timer?.cancel(); + _dataChannel = null; + _inCalling = false; + _session = null; + _text = ''; + break; case CallState.CallStateInvite: + _waitAccept = true; + _showInvateDialog(); + break; case CallState.CallStateConnected: + if (_waitAccept) { + _waitAccept = false; + Navigator.of(context).pop(false); + } + setState(() { + _inCalling = true; + }); + break; case CallState.CallStateRinging: + bool? accept = await _showAcceptDialog(); + if (accept!) { + _accept(); + setState(() { + _inCalling = true; + }); + } else { + _reject(); + } + + break; } }; @@ -117,6 +188,18 @@ class _DataChannelSampleState extends State { } } + _accept() { + if (_session != null) { + _signaling?.accept(_session!.sid, 'data'); + } + } + + _reject() { + if (_session != null) { + _signaling?.reject(_session!.sid); + } + } + _hangUp() { _signaling?.bye(_session!.sid); } diff --git a/lib/src/call_sample/signaling.dart b/lib/src/call_sample/signaling.dart index f375889..abbaf6b 100644 --- a/lib/src/call_sample/signaling.dart +++ b/lib/src/call_sample/signaling.dart @@ -165,12 +165,12 @@ class Signaling { } } - void accept(String sessionId) { + void accept(String sessionId, String media) { var session = _sessions[sessionId]; if (session == null) { return; } - _createAnswer(session, 'video'); + _createAnswer(session, media); } void reject(String sessionId) { From be08af744905d2341cebe6bba860000168034895 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Wed, 13 Sep 2023 21:30:48 +0800 Subject: [PATCH 64/69] Create deploy-web.yaml --- .github/workflows/deploy-web.yaml | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 .github/workflows/deploy-web.yaml diff --git a/.github/workflows/deploy-web.yaml b/.github/workflows/deploy-web.yaml new file mode 100644 index 0000000..622814c --- /dev/null +++ b/.github/workflows/deploy-web.yaml @@ -0,0 +1,31 @@ +name: deploy web on github-page +on: + push: + branches: + - master +jobs: + build: + name: Build Web + env: + my_secret: ${{secrets.commit_secret}} + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - uses: subosito/flutter-action@v1 + with: + channel: "stable" + - run: flutter config --enable-web + - run: flutter clean + - run: flutter pub get + - run: flutter build web --release --web-renderer html --base-href /flutter-webrtc-demo/ + - run: | + cd build/web + git init + git config --global user.email duanweiwei1982@gmail.com + git config --global user.name cloudwebrtc + git status + git remote add origin https://${{secrets.commit_secret}}@github.com/flutter-webrtc/flutter-webrtc-demo.git + git checkout -b gh-pages + git add --all + git commit -m "update" + git push origin gh-pages -f From 5261c7d9d082249b2dc011b2d6a2cf76aa39d004 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Wed, 13 Sep 2023 21:34:26 +0800 Subject: [PATCH 65/69] Update index.html --- web/index.html | 1 + 1 file changed, 1 insertion(+) diff --git a/web/index.html b/web/index.html index 3940fd7..550e257 100644 --- a/web/index.html +++ b/web/index.html @@ -3,6 +3,7 @@ Codestin Search App + From e9d5906e3b9346a82a9d4e57eb06e48595c86316 Mon Sep 17 00:00:00 2001 From: CloudWebRTC Date: Wed, 13 Sep 2023 21:40:31 +0800 Subject: [PATCH 66/69] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 96c8d11..49790fe 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Flutter WebRTC plugin Demo -Online Demo: https://demo.cloudwebrtc.com:8086/ +Online Demo: https://flutter-webrtc.github.io/flutter-webrtc-demo/ ## Usage - `git clone https://github.com/cloudwebrtc/flutter-webrtc-demo` From f1c564d4f0bac24de71548cd05925a5322317d83 Mon Sep 17 00:00:00 2001 From: Vladislav Komelkov Date: Fri, 7 Feb 2025 15:01:56 +0200 Subject: [PATCH 67/69] chore:test --- pubspec.yaml | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pubspec.yaml b/pubspec.yaml index b1c4a07..8ab9867 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -22,3 +22,5 @@ dev_dependencies: flutter: uses-material-design: true + +# test \ No newline at end of file From 13e0c81efff0c7e05e6841fe026336656a43e3ba Mon Sep 17 00:00:00 2001 From: Vladislav Komelkov Date: Fri, 7 Feb 2025 15:07:14 +0200 Subject: [PATCH 68/69] update(android): migrate to new android AGP dsl --- android/app/build.gradle | 32 ++++++++----------- android/app/src/main/AndroidManifest.xml | 1 + android/build.gradle | 12 +------ .../gradle/wrapper/gradle-wrapper.properties | 2 +- android/settings.gradle | 32 +++++++++++++------ 5 files changed, 38 insertions(+), 41 deletions(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index 568b1ac..f30d743 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -1,3 +1,9 @@ +plugins { + id "com.android.application" + id "kotlin-android" + id "dev.flutter.flutter-gradle-plugin" +} + def localProperties = new Properties() def localPropertiesFile = rootProject.file('local.properties') if (localPropertiesFile.exists()) { @@ -6,11 +12,6 @@ if (localPropertiesFile.exists()) { } } -def flutterRoot = localProperties.getProperty('flutter.sdk') -if (flutterRoot == null) { - throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") -} - def flutterVersionCode = localProperties.getProperty('flutter.versionCode') if (flutterVersionCode == null) { flutterVersionCode = '1' @@ -21,12 +22,11 @@ if (flutterVersionName == null) { flutterVersionName = '1.0' } -apply plugin: 'com.android.application' -apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" - android { - compileSdkVersion 28 - ndkVersion "21.4.7075529" + namespace "com.cloudwebrtc.flutterwebrtcdemo" + compileSdkVersion flutter.compileSdkVersion + ndkVersion flutter.ndkVersion + lintOptions { disable 'InvalidPackage' @@ -35,8 +35,8 @@ android { defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.cloudwebrtc.flutterwebrtcdemo" - minSdkVersion 21 - targetSdkVersion 28 + minSdkVersion 23 + targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" @@ -52,8 +52,6 @@ android { // TODO: Add your own signing config for the release build. // Signing with the debug keys for now, so `flutter run --release` works. signingConfig signingConfigs.debug - useProguard true - proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } } packagingOptions { @@ -65,8 +63,4 @@ flutter { source '../..' } -dependencies { - testImplementation 'junit:junit:4.12' - androidTestImplementation 'com.android.support.test:runner:1.0.2' - androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2' -} +dependencies {} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index c9e7a48..97c9635 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -29,6 +29,7 @@ android:value="2" /> plugins.load(reader) } + includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") + + repositories { + google() + mavenCentral() + gradlePluginPortal() + } } -plugins.each { name, path -> - def pluginDirectory = flutterProjectRoot.resolve(path).resolve('android').toFile() - include ":$name" - project(":$name").projectDir = pluginDirectory +plugins { + id "dev.flutter.flutter-plugin-loader" version "1.0.0" + id "com.android.application" version '8.1.1' apply false + id "org.jetbrains.kotlin.android" version "2.0.0" apply false } + +include ":app" + From 94099d590b2d9300cc861e8e3c7a4329085a6c8f Mon Sep 17 00:00:00 2001 From: Vladislav Komelkov Date: Fri, 7 Feb 2025 15:07:45 +0200 Subject: [PATCH 69/69] update(webrtc): bump webrtc 0.12.8 --- pubspec.lock | 442 +++++++++++++++++++++++++++++++++++++++++++++++++++ pubspec.yaml | 6 +- 2 files changed, 444 insertions(+), 4 deletions(-) create mode 100644 pubspec.lock diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..494646b --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,442 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: a1ace0a119f20aabc852d165077c036cd864315bd99b7eaa10a60100341941bf + url: "https://pub.dev" + source: hosted + version: "1.19.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + dart_webrtc: + dependency: transitive + description: + name: dart_webrtc + sha256: e65506edb452148220efab53d8d2f8bb9d827bd8bcd53cf3a3e6df70b27f3d86 + url: "https://pub.dev" + source: hosted + version: "1.4.10" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6" + url: "https://pub.dev" + source: hosted + version: "2.1.3" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + flutter_webrtc: + dependency: "direct main" + description: + name: flutter_webrtc + sha256: e917067abeef2400e6a7a03db53a6e1418551e54809f18ab80447ac323eb77e4 + url: "https://pub.dev" + source: hosted + version: "0.12.8" + http: + dependency: "direct main" + description: + name: http + sha256: "5895291c13fa8a3bd82e76d5627f69e0d85ca6a30dcac95c4ea19a5d555879c2" + url: "https://pub.dev" + source: hosted + version: "0.13.6" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571" + url: "https://pub.dev" + source: hosted + version: "4.1.2" + js: + dependency: transitive + description: + name: js + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf + url: "https://pub.dev" + source: hosted + version: "0.7.1" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "7bb2830ebd849694d1ec25bf1f44582d6ac531a57a365a803a6034ff751d2d06" + url: "https://pub.dev" + source: hosted + version: "10.0.7" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: "9491a714cca3667b60b5c420da8217e6de0d1ba7a5ec322fab01758f6998f379" + url: "https://pub.dev" + source: hosted + version: "3.0.8" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: "6ba465d5d76e67ddf503e1161d1f4a6bc42306f9d66ca1e8f079a47290fb06d3" + url: "https://pub.dev" + source: hosted + version: "3.0.1" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: f7142bb1154231d7ea5f96bc7bde4bda2a0945d2806bb11670e30b850d56bdec + url: "https://pub.dev" + source: hosted + version: "0.11.1" + meta: + dependency: transitive + description: + name: meta + sha256: bdb68674043280c3428e9ec998512fb681678676b3c54e773629ffe74419f8c7 + url: "https://pub.dev" + source: hosted + version: "1.15.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + path_provider: + dependency: "direct main" + description: + name: path_provider + sha256: "50c5dd5b6e1aaf6fb3a78b33f6aa3afca52bf903a8a5298f53101fdaee55bbcd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + path_provider_android: + dependency: transitive + description: + name: path_provider_android + sha256: "4adf4fd5423ec60a29506c76581bc05854c55e3a0b72d35bb28d661c9686edf2" + url: "https://pub.dev" + source: hosted + version: "2.2.15" + path_provider_foundation: + dependency: transitive + description: + name: path_provider_foundation + sha256: "4843174df4d288f5e29185bd6e72a6fbdf5a4a4602717eed565497429f179942" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + sha256: f7a1fe3a634fe7734c8d3f2766ad746ae2a2884abe22e241a8b301bf5cac3279 + url: "https://pub.dev" + source: hosted + version: "2.2.1" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + sha256: "88f5779f72ba699763fa3a3b06aa4bf6de76c8e5de842cf6f29e2e06476c2334" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7 + url: "https://pub.dev" + source: hosted + version: "2.3.0" + platform: + dependency: transitive + description: + name: platform + sha256: "5d6b1b0036a5f331ebc77c850ebc8506cbc1e9416c27e59b439f917a902a4984" + url: "https://pub.dev" + source: hosted + version: "3.1.6" + platform_detect: + dependency: transitive + description: + name: platform_detect + sha256: a62f99417fc4fa2d099ce0ccdbb1bd3977920f2a64292c326271f049d4bc3a4f + url: "https://pub.dev" + source: hosted + version: "2.1.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "7b3cfbf654f3edd0c6298ecd5be782ce997ddf0e00531b9464b55245185bbbbd" + url: "https://pub.dev" + source: hosted + version: "2.1.5" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "688ee90fbfb6989c980254a56cb26ebe9bb30a3a2dff439a78894211f73de67a" + url: "https://pub.dev" + source: hosted + version: "2.5.1" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "650584dcc0a39856f369782874e562efd002a9c94aec032412c9eb81419cce1f" + url: "https://pub.dev" + source: hosted + version: "2.4.4" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "6a52cfcdaeac77cad8c97b539ff688ccfc458c007b4db12be584fbe5c0e49e03" + url: "https://pub.dev" + source: hosted + version: "2.5.4" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + sha256: "57cbf196c486bc2cf1f02b85784932c6094376284b3ad5779d1b1c6c6a816b80" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: d2ca4132d3946fec2184261726b355836a82c33d7d5b67af32692aff18a4684e + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "9f47fd3630d76be3ab26f0ee06d213679aa425996925ff3feffdec504931c377" + url: "https://pub.dev" + source: hosted + version: "1.12.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "688af5ed3402a4bde5b3a6c15fd768dbf2621a614950b17f04626c431ab3c4c3" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: "69fe30f3a8b04a0be0c15ae6490fc859a78ef4c43ae2dd5e8a623d45bfcf9225" + url: "https://pub.dev" + source: hosted + version: "3.3.0+3" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "664d3a9a64782fcdeb83ce9c6b39e78fd2971d4e37827b9b06c3aa1edc5e760c" + url: "https://pub.dev" + source: hosted + version: "0.7.3" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006 + url: "https://pub.dev" + source: hosted + version: "1.4.0" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: f6be3ed8bd01289b34d679c2b62226f63c0e69f9fd2e50a6b3c1c729a961041b + url: "https://pub.dev" + source: hosted + version: "14.3.0" + web: + dependency: transitive + description: + name: web + sha256: cd3543bd5798f6ad290ea73d210f423502e71900302dde696f8bff84bf89a1cb + url: "https://pub.dev" + source: hosted + version: "1.1.0" + webrtc_interface: + dependency: transitive + description: + name: webrtc_interface + sha256: "10fc6dc0ac16f909f5e434c18902415211d759313c87261f1e4ec5b4f6a04c26" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15" + url: "https://pub.dev" + source: hosted + version: "1.1.0" +sdks: + dart: ">=3.5.0 <4.0.0" + flutter: ">=3.24.0" diff --git a/pubspec.yaml b/pubspec.yaml index 8ab9867..d27c17b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -11,7 +11,7 @@ dependencies: sdk: flutter cupertino_icons: ^1.0.3 - flutter_webrtc: ^0.9.11 + flutter_webrtc: ^0.12.8 shared_preferences: ^2.0.7 http: ^0.13.3 path_provider: ^2.0.2 @@ -21,6 +21,4 @@ dev_dependencies: sdk: flutter flutter: - uses-material-design: true - -# test \ No newline at end of file + uses-material-design: true \ No newline at end of file