From 2f0fd5dd3001f54b63afdd0e5a01bd1d6b893d58 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Thu, 16 Jul 2026 17:39:09 +0800 Subject: [PATCH 01/18] FFI initialize and create --- .../lib/src/messages.g.dart | 453 ++++++++++++------ .../lib/src/video_player_tizen.dart | 89 +++- .../tizen/src/media_player.cc | 40 +- .../tizen/src/messages.h | 22 + .../tizen/src/video_player_tizen_plugin.cc | 283 ++++++++++- 5 files changed, 697 insertions(+), 190 deletions(-) diff --git a/packages/video_player_videohole/lib/src/messages.g.dart b/packages/video_player_videohole/lib/src/messages.g.dart index aefd72f53..52b8af5f4 100644 --- a/packages/video_player_videohole/lib/src/messages.g.dart +++ b/packages/video_player_videohole/lib/src/messages.g.dart @@ -3,47 +3,39 @@ // ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import import 'dart:async'; +import 'dart:ffi' as ffi; +import 'package:ffi/ffi.dart' show calloc; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; +import 'dart:convert' show utf8, jsonEncode; -import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer; +import 'package:flutter/foundation.dart' + show ReadBuffer, WriteBuffer, debugPrint; import 'package:flutter/services.dart'; class PlayerMessage { - PlayerMessage({ - required this.playerId, - }); + PlayerMessage({required this.playerId}); int playerId; Object encode() { - return [ - playerId, - ]; + return [playerId]; } static PlayerMessage decode(Object result) { result as List; - return PlayerMessage( - playerId: result[0]! as int, - ); + return PlayerMessage(playerId: result[0]! as int); } } class LoopingMessage { - LoopingMessage({ - required this.playerId, - required this.isLooping, - }); + LoopingMessage({required this.playerId, required this.isLooping}); int playerId; bool isLooping; Object encode() { - return [ - playerId, - isLooping, - ]; + return [playerId, isLooping]; } static LoopingMessage decode(Object result) { @@ -56,20 +48,14 @@ class LoopingMessage { } class VolumeMessage { - VolumeMessage({ - required this.playerId, - required this.volume, - }); + VolumeMessage({required this.playerId, required this.volume}); int playerId; double volume; Object encode() { - return [ - playerId, - volume, - ]; + return [playerId, volume]; } static VolumeMessage decode(Object result) { @@ -82,20 +68,14 @@ class VolumeMessage { } class PlaybackSpeedMessage { - PlaybackSpeedMessage({ - required this.playerId, - required this.speed, - }); + PlaybackSpeedMessage({required this.playerId, required this.speed}); int playerId; double speed; Object encode() { - return [ - playerId, - speed, - ]; + return [playerId, speed]; } static PlaybackSpeedMessage decode(Object result) { @@ -108,20 +88,14 @@ class PlaybackSpeedMessage { } class TrackMessage { - TrackMessage({ - required this.playerId, - required this.tracks, - }); + TrackMessage({required this.playerId, required this.tracks}); int playerId; List?> tracks; Object encode() { - return [ - playerId, - tracks, - ]; + return [playerId, tracks]; } static TrackMessage decode(Object result) { @@ -134,20 +108,14 @@ class TrackMessage { } class TrackTypeMessage { - TrackTypeMessage({ - required this.playerId, - required this.trackType, - }); + TrackTypeMessage({required this.playerId, required this.trackType}); int playerId; String trackType; Object encode() { - return [ - playerId, - trackType, - ]; + return [playerId, trackType]; } static TrackTypeMessage decode(Object result) { @@ -173,11 +141,7 @@ class SelectedTracksMessage { String trackType; Object encode() { - return [ - playerId, - trackId, - trackType, - ]; + return [playerId, trackId, trackType]; } static SelectedTracksMessage decode(Object result) { @@ -191,20 +155,14 @@ class SelectedTracksMessage { } class PositionMessage { - PositionMessage({ - required this.playerId, - required this.position, - }); + PositionMessage({required this.playerId, required this.position}); int playerId; int position; Object encode() { - return [ - playerId, - position, - ]; + return [playerId, position]; } static PositionMessage decode(Object result) { @@ -271,23 +229,17 @@ class CreateMessage { } class MixWithOthersMessage { - MixWithOthersMessage({ - required this.mixWithOthers, - }); + MixWithOthersMessage({required this.mixWithOthers}); bool mixWithOthers; Object encode() { - return [ - mixWithOthers, - ]; + return [mixWithOthers]; } static MixWithOthersMessage decode(Object result) { result as List; - return MixWithOthersMessage( - mixWithOthers: result[0]! as bool, - ); + return MixWithOthersMessage(mixWithOthers: result[0]! as bool); } } @@ -311,13 +263,7 @@ class GeometryMessage { int height; Object encode() { - return [ - playerId, - x, - y, - width, - height, - ]; + return [playerId, x, y, width, height]; } static GeometryMessage decode(Object result) { @@ -333,20 +279,14 @@ class GeometryMessage { } class DurationMessage { - DurationMessage({ - required this.playerId, - this.durationRange, - }); + DurationMessage({required this.playerId, this.durationRange}); int playerId; List? durationRange; Object encode() { - return [ - playerId, - durationRange, - ]; + return [playerId, durationRange]; } static DurationMessage decode(Object result) { @@ -359,20 +299,14 @@ class DurationMessage { } class RotationMessage { - RotationMessage({ - required this.playerId, - required this.rotation, - }); + RotationMessage({required this.playerId, required this.rotation}); int playerId; int rotation; Object encode() { - return [ - playerId, - rotation, - ]; + return [playerId, rotation]; } static RotationMessage decode(Object result) { @@ -484,9 +418,10 @@ class VideoPlayerVideoholeApi { Future initialize() async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.initialize', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.initialize', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send(null) as List?; if (replyList == null) { throw PlatformException( @@ -506,9 +441,10 @@ class VideoPlayerVideoholeApi { Future create(CreateMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.create', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.create', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -534,9 +470,10 @@ class VideoPlayerVideoholeApi { Future dispose(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.dispose', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.dispose', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -557,9 +494,10 @@ class VideoPlayerVideoholeApi { Future setLooping(LoopingMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setLooping', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setLooping', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -580,9 +518,10 @@ class VideoPlayerVideoholeApi { Future setVolume(VolumeMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setVolume', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setVolume', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -603,9 +542,10 @@ class VideoPlayerVideoholeApi { Future setPlaybackSpeed(PlaybackSpeedMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setPlaybackSpeed', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setPlaybackSpeed', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -626,9 +566,10 @@ class VideoPlayerVideoholeApi { Future play(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.play', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.play', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -649,9 +590,10 @@ class VideoPlayerVideoholeApi { Future setDeactivate(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDeactivate', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDeactivate', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -677,9 +619,10 @@ class VideoPlayerVideoholeApi { Future setActivate(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setActivate', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setActivate', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -705,9 +648,10 @@ class VideoPlayerVideoholeApi { Future track(TrackTypeMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.track', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.track', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -733,9 +677,10 @@ class VideoPlayerVideoholeApi { Future setTrackSelection(SelectedTracksMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setTrackSelection', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setTrackSelection', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -761,9 +706,10 @@ class VideoPlayerVideoholeApi { Future position(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.position', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.position', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -789,9 +735,10 @@ class VideoPlayerVideoholeApi { Future seekTo(PositionMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.seekTo', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.seekTo', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -812,9 +759,10 @@ class VideoPlayerVideoholeApi { Future pause(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.pause', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.pause', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -835,9 +783,10 @@ class VideoPlayerVideoholeApi { Future setMixWithOthers(MixWithOthersMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setMixWithOthers', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setMixWithOthers', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -858,9 +807,10 @@ class VideoPlayerVideoholeApi { Future setDisplayGeometry(GeometryMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayGeometry', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayGeometry', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -881,9 +831,10 @@ class VideoPlayerVideoholeApi { Future duration(PlayerMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.duration', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.duration', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -909,9 +860,10 @@ class VideoPlayerVideoholeApi { Future suspend(int arg_playerId) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.suspend', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.suspend', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_playerId]) as List?; if (replyList == null) { @@ -931,11 +883,15 @@ class VideoPlayerVideoholeApi { } Future restore( - int arg_playerId, CreateMessage? arg_msg, int arg_resumeTime) async { + int arg_playerId, + CreateMessage? arg_msg, + int arg_resumeTime, + ) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.restore', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.restore', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_playerId, arg_msg, arg_resumeTime]) as List?; @@ -957,9 +913,10 @@ class VideoPlayerVideoholeApi { Future setDisplayRotate(RotationMessage arg_msg) async { final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayRotate', - codec, - binaryMessenger: _binaryMessenger); + 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayRotate', + codec, + binaryMessenger: _binaryMessenger, + ); final List? replyList = await channel.send([arg_msg]) as List?; if (replyList == null) { @@ -983,3 +940,187 @@ class VideoPlayerVideoholeApi { } } } + +// ===== FFI Section - Gradual Migration ===== + +// FFI type definitions +typedef _FFIInitializeNative = ffi.Int32 Function(); +typedef _FFIInitializeDart = int Function(); + +// FFI type definitions with JSON parameters for complex data +typedef _FFICreateNative = ffi.Int64 Function( + ffi.Pointer, // uri + ffi.Pointer, // asset + ffi.Pointer, // package_name + ffi.Pointer, // format_hint + ffi.Pointer, // http_headers_json + ffi.Pointer, // drm_configs_json + ffi.Pointer, // player_options_json +); +typedef _FFICreateDart = int Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, +); + +// Helper functions for FFI string conversion +ffi.Pointer _toPointer(String? str) { + if (str == null) return ffi.nullptr; + final units = utf8.encode(str); + final result = calloc.allocate(units.length + 1); + final Uint8List nativeString = result.asTypedList(units.length + 1); + nativeString.setAll(0, units); + nativeString[units.length] = 0; // null terminator + return result.cast(); +} + +void _freePointer(ffi.Pointer ptr) { + if (ptr != ffi.nullptr) { + calloc.free(ptr); + } +} + +/// FFI Bindings for video_player_tizen +class VideoPlayerFFIBindings { + static VideoPlayerFFIBindings? _instance; + ffi.DynamicLibrary? _lib; + + late int Function() _ffiInitialize; + late int Function( + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer, + ffi.Pointer) _ffiCreate; + + static VideoPlayerFFIBindings get instance { + _instance ??= VideoPlayerFFIBindings._(); + return _instance!; + } + + VideoPlayerFFIBindings._(); + + /// Load the native library - must be called before using FFI functions + void load() { + if (_lib != null) return; + + try { + // On Tizen, the plugin is statically linked, so we use process() to access + // symbols from the main executable + _lib = ffi.DynamicLibrary.process(); + + _ffiInitialize = _lib! + .lookup>('ffi_initialize') + .asFunction<_FFIInitializeDart>(); + + _ffiCreate = _lib! + .lookup>('ffi_create') + .asFunction<_FFICreateDart>(); + + debugPrint('FFI bindings loaded successfully'); + } catch (e) { + debugPrint('Failed to load FFI bindings: $e'); + rethrow; + } + } + + bool get isLoaded => _lib != null; + + /// FFI initialize function + int ffiInitialize() { + if (!isLoaded) { + throw StateError('FFI bindings not loaded. Call load() first.'); + } + return _ffiInitialize(); + } + + /// FFI create function with JSON parameters for complex data + int ffiCreate({ + String? uri, + String? asset, + String? packageName, + String? formatHint, + Map? httpHeaders, + Map? drmConfigs, + Map? playerOptions, + }) { + if (!isLoaded) { + throw StateError('FFI bindings not loaded. Call load() first.'); + } + + // Convert Maps to JSON strings + String? httpHeadersJson = + httpHeaders != null ? jsonEncode(httpHeaders) : null; + String? drmConfigsJson = drmConfigs != null ? jsonEncode(drmConfigs) : null; + String? playerOptionsJson = + playerOptions != null ? jsonEncode(playerOptions) : null; + + final uriPtr = _toPointer(uri); + final assetPtr = _toPointer(asset); + final packagePtr = _toPointer(packageName); + final formatHintPtr = _toPointer(formatHint); + final httpHeadersPtr = _toPointer(httpHeadersJson); + final drmConfigsPtr = _toPointer(drmConfigsJson); + final playerOptionsPtr = _toPointer(playerOptionsJson); + + try { + return _ffiCreate( + uriPtr, + assetPtr, + packagePtr, + formatHintPtr, + httpHeadersPtr, + drmConfigsPtr, + playerOptionsPtr, + ); + } finally { + _freePointer(uriPtr); + _freePointer(assetPtr); + _freePointer(packagePtr); + _freePointer(formatHintPtr); + _freePointer(httpHeadersPtr); + _freePointer(drmConfigsPtr); + _freePointer(playerOptionsPtr); + } + } +} + +// Top-level FFI functions for easy access +Future ffiInitialize() async { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings.ffiInitialize(); +} + +/// FFI create function - returns player_id or -1 on error +Future ffiCreate({ + String? uri, + String? asset, + String? packageName, + String? formatHint, + Map? httpHeaders, + Map? drmConfigs, + Map? playerOptions, +}) async { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings.ffiCreate( + uri: uri, + asset: asset, + packageName: packageName, + formatHint: formatHint, + httpHeaders: httpHeaders, + drmConfigs: drmConfigs, + playerOptions: playerOptions, + ); +} diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index a6f482751..4e0909d24 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -12,14 +12,26 @@ import '../video_player_platform_interface.dart'; import 'messages.g.dart'; import 'tracks.dart'; -/// An implementation of [VideoPlayerPlatform] that uses the -/// Pigeon-generated [VideoPlayerVideoholeApi]. +/// An implementation of [VideoPlayerPlatform] that uses FFI for initialization +/// and Platform Channel (Pigeon) for other methods (gradual migration). class VideoPlayerTizen extends VideoPlayerPlatform { final VideoPlayerVideoholeApi _api = VideoPlayerVideoholeApi(); @override - Future init() { - return _api.initialize(); + Future init() async { + // Use FFI for initialization (gradual migration from Platform Channel) + try { + final result = await ffiInitialize(); + if (result != 0) { + throw Exception('FFI initialize failed with code: $result'); + } + print('********FFI initialize succeeded**********'); + } catch (e) { + print( + '***********FFI initialize failed, falling back to Platform Channel: $e**********'); + // Fallback to Platform Channel if FFI fails + return _api.initialize(); + } } @override @@ -29,26 +41,59 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future create(DataSource dataSource) async { - final CreateMessage message = CreateMessage(); + // Use FFI for create (gradual migration from Platform Channel) + try { + int playerId; - switch (dataSource.sourceType) { - case DataSourceType.asset: - message.asset = dataSource.asset; - message.packageName = dataSource.package; - case DataSourceType.network: - message.uri = dataSource.uri; - message.formatHint = _videoFormatStringMap[dataSource.formatHint]; - message.httpHeaders = dataSource.httpHeaders; - message.drmConfigs = dataSource.drmConfigs?.toMap(); - message.playerOptions = dataSource.playerOptions; - case DataSourceType.file: - message.uri = dataSource.uri; - case DataSourceType.contentUri: - message.uri = dataSource.uri; - } + switch (dataSource.sourceType) { + case DataSourceType.asset: + playerId = await ffiCreate( + asset: dataSource.asset, + packageName: dataSource.package, + ); + case DataSourceType.network: + playerId = await ffiCreate( + uri: dataSource.uri, + formatHint: _videoFormatStringMap[dataSource.formatHint], + httpHeaders: dataSource.httpHeaders, + drmConfigs: dataSource.drmConfigs?.toMap(), + playerOptions: dataSource.playerOptions, + ); + case DataSourceType.file: + case DataSourceType.contentUri: + playerId = await ffiCreate(uri: dataSource.uri); + } + + if (playerId < 0) { + throw Exception('FFI create failed with code: $playerId'); + } + print( + '*************FFI create succeeded with player_id: $playerId*******'); + return playerId; + } catch (e) { + print( + '*************FFI create failed, falling back to Platform Channel: $e****'); + // Fallback to Platform Channel if FFI fails + final CreateMessage message = CreateMessage(); + + switch (dataSource.sourceType) { + case DataSourceType.asset: + message.asset = dataSource.asset; + message.packageName = dataSource.package; + case DataSourceType.network: + message.uri = dataSource.uri; + message.formatHint = _videoFormatStringMap[dataSource.formatHint]; + message.httpHeaders = dataSource.httpHeaders; + message.drmConfigs = dataSource.drmConfigs?.toMap(); + message.playerOptions = dataSource.playerOptions; + case DataSourceType.file: + case DataSourceType.contentUri: + message.uri = dataSource.uri; + } - final PlayerMessage response = await _api.create(message); - return response.playerId; + final PlayerMessage response = await _api.create(message); + return response.playerId; + } } @override diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 1cfefa0c1..98962e574 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -102,15 +102,30 @@ int64_t MediaPlayer::Create(const std::string &uri, } } - int64_t drm_type = - flutter_common::GetValue(create_message.drm_configs(), "drmType", 0); - std::string license_server_url = flutter_common::GetValue( - create_message.drm_configs(), "licenseServerUrl", std::string()); - if (drm_type != 0) { - if (!SetDrm(uri, drm_type, license_server_url)) { - LOG_ERROR("[MediaPlayer] Failed to set drm."); - return -1; + auto drm_configs_ptr = create_message.drm_configs(); + if (drm_configs_ptr != nullptr) { + LOG_INFO("[MediaPlayer] drm_configs is present."); + + // Must use 0LL (int64_t literal) instead of 0 (int literal) for proper type + // matching + int64_t drm_type = + flutter_common::GetValue(drm_configs_ptr, "drmType", 0LL); + std::string license_server_url = flutter_common::GetValue( + drm_configs_ptr, "licenseServerUrl", std::string()); + + LOG_INFO("[MediaPlayer] drm_type=%lld, license_server_url=%s", + static_cast(drm_type), license_server_url.c_str()); + + if (drm_type != 0) { + if (!SetDrm(uri, drm_type, license_server_url)) { + LOG_ERROR("[MediaPlayer] Failed to set drm."); + return -1; + } + } else { + LOG_INFO("[MediaPlayer] drm_type is 0, skipping SetDrm."); } + } else { + LOG_INFO("[MediaPlayer] drm_configs is NOT present (null)."); } if (!SetDisplay()) { @@ -592,6 +607,7 @@ bool MediaPlayer::SetTrackSelection(int32_t track_id, std::string track_type) { bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, const std::string &license_server_url) { drm_manager_ = std::make_unique(); + if (!drm_manager_->CreateDrmSession(drm_type, false)) { LOG_ERROR("[MediaPlayer] Failed to create drm session."); return false; @@ -622,7 +638,7 @@ bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, ret = media_player_proxy_->player_set_drm_init_data_cb( player_, OnDrmUpdatePsshData, this); if (ret != PLAYER_ERROR_NONE) { - LOG_ERROR("[MediaPlayer] player_set_drm_init_complete_cb failed : %s.", + LOG_ERROR("[MediaPlayer] player_set_drm_init_data_cb failed : %s.", get_error_message(ret)); return false; } @@ -630,15 +646,17 @@ bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, if (license_server_url.empty()) { bool success = drm_manager_->SetChallenge(uri, binary_messenger_); if (!success) { - LOG_ERROR("[MediaPlayer] Failed to set challenge."); + LOG_ERROR("[MediaPlayer] Failed to set challenge via licenseCallback."); return false; } } else { if (!drm_manager_->SetChallenge(uri, license_server_url)) { - LOG_ERROR("[MediaPlayer] Failed to set challenge."); + LOG_ERROR("[MediaPlayer] Failed to set challenge via licenseServerUrl."); return false; } } + + LOG_INFO("[MediaPlayer] SetDrm completed successfully."); return true; } diff --git a/packages/video_player_videohole/tizen/src/messages.h b/packages/video_player_videohole/tizen/src/messages.h index 0e92690a4..793334fa2 100644 --- a/packages/video_player_videohole/tizen/src/messages.h +++ b/packages/video_player_videohole/tizen/src/messages.h @@ -447,4 +447,26 @@ class VideoPlayerVideoholeApi { VideoPlayerVideoholeApi() = default; }; } // namespace video_player_videohole_tizen + +// FFI exports for gradual migration +#ifdef __cplusplus +extern "C" { +#endif + +// FFI initialization +int ffi_initialize(); + +// FFI create - returns player_id or -1 on error +// Parameters: uri, asset, package_name, format_hint, http_headers_json, +// drm_configs_json, player_options_json (all const char*) +// Returns: int64_t player_id (negative value indicates error) +int64_t ffi_create(const char* uri, const char* asset, const char* package_name, + const char* format_hint, const char* http_headers_json, + const char* drm_configs_json, + const char* player_options_json); + +#ifdef __cplusplus +} // extern "C" +#endif + #endif // PIGEON_MESSAGES_H_ diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 50c3c076b..02deed936 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -9,9 +9,11 @@ #include #include +#include #include #include #include +#include #include #include @@ -29,6 +31,9 @@ class VideoPlayerTizenPlugin : public flutter::Plugin, FlutterDesktopPluginRegistrarRef registrar_ref, flutter::PluginRegistrar *plugin_registrar); + // Get singleton instance for FFI access + static VideoPlayerTizenPlugin *GetInstance() { return instance_; } + VideoPlayerTizenPlugin(FlutterDesktopPluginRegistrarRef registrar_ref, flutter::PluginRegistrar *plugin_registrar); virtual ~VideoPlayerTizenPlugin(); @@ -56,7 +61,7 @@ class VideoPlayerTizenPlugin : public flutter::Plugin, std::optional SetDisplayGeometry( const GeometryMessage &msg) override; std::optional Suspend(int64_t player_id) override; - std::optional Restore(int64_t palyer_id, + std::optional Restore(int64_t player_id, const CreateMessage *msg, int64_t resume_time) override; ErrorOr SetDisplayRotate(const RotationMessage &msg) override; @@ -82,6 +87,7 @@ class VideoPlayerTizenPlugin : public flutter::Plugin, VideoPlayerOptions options_; static inline std::map> players_; + static VideoPlayerTizenPlugin *instance_; }; void VideoPlayerTizenPlugin::RegisterWithRegistrar( @@ -96,6 +102,7 @@ VideoPlayerTizenPlugin::VideoPlayerTizenPlugin( FlutterDesktopPluginRegistrarRef registrar_ref, flutter::PluginRegistrar *plugin_registrar) : registrar_ref_(registrar_ref), plugin_registrar_(plugin_registrar) { + instance_ = this; // Set singleton instance for FFI access VideoPlayerVideoholeApi::SetUp(plugin_registrar->messenger(), this); } @@ -342,6 +349,280 @@ ErrorOr VideoPlayerTizenPlugin::SetDisplayRotate( } // namespace video_player_videohole_tizen +// Static instance definition +namespace video_player_videohole_tizen { +VideoPlayerTizenPlugin *VideoPlayerTizenPlugin::instance_ = nullptr; +} // namespace video_player_videohole_tizen + +// FFI exports for gradual migration +extern "C" { + +int ffi_initialize() { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->Initialize(); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + +// Helper function to parse simple JSON-like string to flutter::EncodableMap +// Format: {"key1":"value1","key2":"value2"} +static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { + flutter::EncodableMap result; + if (json_str.empty() || json_str == "{}") { + return result; + } + + // Simple parser for flat key-value pairs + std::string content = json_str; + // Remove outer braces + if (content.front() == '{') content = content.substr(1); + if (content.back() == '}') content.pop_back(); + + // Parse key-value pairs + size_t pos = 0; + while (pos < content.length()) { + // Skip whitespace and commas + while (pos < content.length() && + (isspace(content[pos]) || content[pos] == ',')) { + pos++; + } + if (pos >= content.length()) break; + + // Find key + if (content[pos] != '"') break; + pos++; // skip opening quote + size_t key_start = pos; + while (pos < content.length() && content[pos] != '"') pos++; + std::string key = content.substr(key_start, pos - key_start); + pos++; // skip closing quote + + // Skip colon and whitespace + while (pos < content.length() && + (isspace(content[pos]) || content[pos] == ':')) { + pos++; + } + if (pos >= content.length()) break; + + // Find value + std::string value; + if (content[pos] == '"') { + // String value + pos++; // skip opening quote + size_t val_start = pos; + while (pos < content.length() && content[pos] != '"') pos++; + value = content.substr(val_start, pos - val_start); + pos++; // skip closing quote + result[flutter::EncodableValue(key)] = flutter::EncodableValue(value); + } else if (content[pos] == '{') { + // Nested object - skip for now, treat as empty map + int brace_count = 1; + pos++; + while (pos < content.length() && brace_count > 0) { + if (content[pos] == '{') + brace_count++; + else if (content[pos] == '}') + brace_count--; + pos++; + } + result[flutter::EncodableValue(key)] = flutter::EncodableMap(); + } else { + // Number or boolean + size_t val_start = pos; + while (pos < content.length() && content[pos] != ',' && + content[pos] != '}') { + pos++; + } + value = content.substr(val_start, pos - val_start); + // Trim whitespace + while (!value.empty() && isspace(value.back())) value.pop_back(); + + if (value == "true") { + result[flutter::EncodableValue(key)] = flutter::EncodableValue(true); + } else if (value == "false") { + result[flutter::EncodableValue(key)] = flutter::EncodableValue(false); + } else { + // Try as number + try { + if (value.find('.') != std::string::npos) { + result[flutter::EncodableValue(key)] = + flutter::EncodableValue(std::stod(value)); + } else { + result[flutter::EncodableValue(key)] = + flutter::EncodableValue(std::stoll(value)); + } + } catch (...) { + result[flutter::EncodableValue(key)] = flutter::EncodableValue(value); + } + } + } + } + + return result; +} + +// Helper function to parse JSON for drm_configs +// Format: {"drmType":1,"licenseServerUrl":"http://..."} +// Note: prebufferMode is not currently supported by DrmConfigs class +// +// Dart DrmType enum: none=0, playready=1, widevine=2 +// DrmManager::DrmType enum: DRM_TYPE_NONE=0, DRM_TYPE_PLAYREADAY=1, +// DRM_TYPE_WIDEVINECDM=2 The enum values are the same, no mapping needed + +static void ParseDrmConfigs(const std::string &json_str, int64_t &drm_type, + std::string &license_server_url) { + drm_type = 0; + license_server_url.clear(); + + if (json_str.empty() || json_str == "{}") { + return; + } + + // Simple extraction + size_t pos; + + // Extract drmType + pos = json_str.find("\"drmType\""); + if (pos != std::string::npos) { + pos = json_str.find(':', pos); + if (pos != std::string::npos) { + pos++; + while (pos < json_str.length() && + (isspace(json_str[pos]) || json_str[pos] == ':')) + pos++; + + // Skip any leading quotes (shouldn't be there for numbers, but just in + // case) + while (pos < json_str.length() && + (json_str[pos] == '"' || isspace(json_str[pos]))) + pos++; + + size_t end = pos; + while (end < json_str.length() && json_str[end] != ',' && + json_str[end] != '}' && json_str[end] != '"') + end++; + std::string val = json_str.substr(pos, end - pos); + + // Trim trailing whitespace and quotes + while (!val.empty() && (val.back() == '"' || isspace(val.back()))) + val.pop_back(); + + try { + drm_type = std::stoll(val); + } catch (const std::exception &e) { + // Fallback: try direct comparison + if (val == "1") { + drm_type = 1; // PlayReady + } else if (val == "2") { + drm_type = 2; // Widevine + } + } + } + } + + // Extract licenseServerUrl - handle both string and null values + pos = json_str.find("\"licenseServerUrl\""); + if (pos != std::string::npos) { + pos = json_str.find(':', pos); + if (pos != std::string::npos) { + pos++; + while (pos < json_str.length() && + (isspace(json_str[pos]) || json_str[pos] == ':')) + pos++; + + // Check for null value + if (pos < json_str.length() && json_str.substr(pos, 4) == "null") { + license_server_url.clear(); + } else if (pos < json_str.length() && json_str[pos] == '"') { + // String value + pos++; + size_t end = pos; + while (end < json_str.length() && json_str[end] != '"') end++; + license_server_url = json_str.substr(pos, end - pos); + } + } + } +} + +int64_t ffi_create(const char *uri, const char *asset, const char *package_name, + const char *format_hint, const char *http_headers_json, + const char *drm_configs_json, + const char *player_options_json) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Build CreateMessage from FFI parameters + video_player_videohole_tizen::CreateMessage msg; + + // Set basic fields + if (uri != nullptr && strlen(uri) > 0) { + msg.set_uri(std::string(uri)); + } + if (asset != nullptr && strlen(asset) > 0) { + msg.set_asset(std::string(asset)); + } + if (package_name != nullptr && strlen(package_name) > 0) { + msg.set_package_name(std::string(package_name)); + } + if (format_hint != nullptr && strlen(format_hint) > 0) { + msg.set_format_hint(std::string(format_hint)); + } + + // Parse http_headers JSON + if (http_headers_json != nullptr && strlen(http_headers_json) > 0) { + flutter::EncodableMap headers = + ParseJsonMap(std::string(http_headers_json)); + if (!headers.empty()) { + msg.set_http_headers(headers); + } + } + + // Parse drm_configs JSON + if (drm_configs_json != nullptr && strlen(drm_configs_json) > 0) { + int64_t drm_type = 0; + std::string license_url; + ParseDrmConfigs(std::string(drm_configs_json), drm_type, license_url); + + flutter::EncodableMap drm_map; + drm_map[flutter::EncodableValue("drmType")] = + flutter::EncodableValue(drm_type); + if (!license_url.empty()) { + drm_map[flutter::EncodableValue("licenseServerUrl")] = + flutter::EncodableValue(license_url); + } + msg.set_drm_configs(drm_map); + } + + // Parse player_options JSON + if (player_options_json != nullptr && strlen(player_options_json) > 0) { + flutter::EncodableMap options = + ParseJsonMap(std::string(player_options_json)); + if (!options.empty()) { + msg.set_player_options(options); + } + } + + // Use the plugin's Create method which handles asset resolution and player + // creation + auto result = plugin->Create(msg); + if (result.has_error()) { + return -1; + } + return result.value().player_id(); +} + +} // extern "C" + void VideoPlayerTizenPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar) { video_player_videohole_tizen::VideoPlayerTizenPlugin::RegisterWithRegistrar( From 19c4bd1e39a0b6580314cbca0d312e3fd7578f9b Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Fri, 17 Jul 2026 16:30:16 +0800 Subject: [PATCH 02/18] Migration of methods other than (de)activate --- .../lib/src/messages.g.dart | 475 +++++++++++++-- .../lib/src/video_player_tizen.dart | 346 ++++++++--- .../tizen/src/messages.h | 10 +- .../tizen/src/video_player_tizen_plugin.cc | 572 ++++++++++++++---- 4 files changed, 1138 insertions(+), 265 deletions(-) diff --git a/packages/video_player_videohole/lib/src/messages.g.dart b/packages/video_player_videohole/lib/src/messages.g.dart index 52b8af5f4..6c590951b 100644 --- a/packages/video_player_videohole/lib/src/messages.g.dart +++ b/packages/video_player_videohole/lib/src/messages.g.dart @@ -6,7 +6,7 @@ import 'dart:async'; import 'dart:ffi' as ffi; import 'package:ffi/ffi.dart' show calloc; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; -import 'dart:convert' show utf8, jsonEncode; +import 'dart:convert' show utf8, jsonEncode, jsonDecode; import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer, debugPrint; @@ -947,25 +947,63 @@ class VideoPlayerVideoholeApi { typedef _FFIInitializeNative = ffi.Int32 Function(); typedef _FFIInitializeDart = int Function(); -// FFI type definitions with JSON parameters for complex data -typedef _FFICreateNative = ffi.Int64 Function( - ffi.Pointer, // uri - ffi.Pointer, // asset - ffi.Pointer, // package_name - ffi.Pointer, // format_hint - ffi.Pointer, // http_headers_json - ffi.Pointer, // drm_configs_json - ffi.Pointer, // player_options_json -); -typedef _FFICreateDart = int Function( - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, -); +// FFI type definitions - create takes a single JSON string for all parameters +// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} +typedef _FFICreateNative = ffi.Int64 Function(ffi.Pointer); +typedef _FFICreateDart = int Function(ffi.Pointer); + +// FFI type definitions for additional methods +typedef _FFIDisposeNative = ffi.Int32 Function(ffi.Int64); +typedef _FFIDisposeDart = int Function(int); + +typedef _FFIPlayNative = ffi.Int32 Function(ffi.Int64); +typedef _FFIPlayDart = int Function(int); + +typedef _FFIPauseNative = ffi.Int32 Function(ffi.Int64); +typedef _FFIPauseDart = int Function(int); + +typedef _FFISeekToNative = ffi.Int32 Function(ffi.Int64, ffi.Int64); +typedef _FFISeekToDart = int Function(int, int); + +typedef _FFIGetPositionNative = ffi.Int64 Function(ffi.Int64); +typedef _FFIGetPositionDart = int Function(int); + +typedef _FFIGetDurationNative = ffi.Pointer Function(ffi.Int64); +typedef _FFIGetDurationDart = ffi.Pointer Function(int); + +typedef _FFISetVolumeNative = ffi.Int32 Function(ffi.Int64, ffi.Double); +typedef _FFISetVolumeDart = int Function(int, double); + +typedef _FFISetPlaybackSpeedNative = ffi.Int32 Function(ffi.Int64, ffi.Double); +typedef _FFISetPlaybackSpeedDart = int Function(int, double); + +typedef _FFISetLoopingNative = ffi.Int32 Function(ffi.Int64, ffi.Bool); +typedef _FFISetLoopingDart = int Function(int, bool); + +typedef _FFIGetTrackInfoNative = ffi.Pointer Function( + ffi.Int64, ffi.Pointer); +typedef _FFIGetTrackInfoDart = ffi.Pointer Function( + int, ffi.Pointer); + +typedef _FFISetTrackSelectionNative = ffi.Int32 Function( + ffi.Int64, ffi.Int64, ffi.Pointer); +typedef _FFISetTrackSelectionDart = int Function( + int, int, ffi.Pointer); + +typedef _FFISetDisplayGeometryNative = ffi.Int32 Function( + ffi.Int64, ffi.Int32, ffi.Int32, ffi.Int32, ffi.Int32); +typedef _FFISetDisplayGeometryDart = int Function(int, int, int, int, int); + +typedef _FFISetDisplayRotateNative = ffi.Int32 Function(ffi.Int64, ffi.Int32); +typedef _FFISetDisplayRotateDart = int Function(int, int); + +typedef _FFISuspendNative = ffi.Int32 Function(ffi.Int64); +typedef _FFISuspendDart = int Function(int); + +typedef _FFIRestoreNative = ffi.Int32 Function( + ffi.Int64, ffi.Pointer, ffi.Int64); +typedef _FFIRestoreDart = int Function(int, ffi.Pointer, int); // Helper functions for FFI string conversion ffi.Pointer _toPointer(String? str) { @@ -990,14 +1028,24 @@ class VideoPlayerFFIBindings { ffi.DynamicLibrary? _lib; late int Function() _ffiInitialize; - late int Function( - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer, - ffi.Pointer) _ffiCreate; + late int Function(ffi.Pointer) _ffiCreate; + + late int Function(int) _ffiDispose; + late int Function(int) _ffiPlay; + late int Function(int) _ffiPause; + late int Function(int, int) _ffiSeekTo; + late int Function(int) _ffiGetPosition; + late ffi.Pointer Function(int) _ffiGetDuration; + late int Function(int, double) _ffiSetVolume; + late int Function(int, double) _ffiSetPlaybackSpeed; + late int Function(int, bool) _ffiSetLooping; + late ffi.Pointer Function(int, ffi.Pointer) + _ffiGetTrackInfo; + late int Function(int, int, ffi.Pointer) _ffiSetTrackSelection; + late int Function(int, int, int, int, int) _ffiSetDisplayGeometry; + late int Function(int, int) _ffiSetDisplayRotate; + late int Function(int) _ffiSuspend; + late int Function(int, ffi.Pointer, int) _ffiRestore; static VideoPlayerFFIBindings get instance { _instance ??= VideoPlayerFFIBindings._(); @@ -1023,6 +1071,71 @@ class VideoPlayerFFIBindings { .lookup>('ffi_create') .asFunction<_FFICreateDart>(); + _ffiDispose = _lib! + .lookup>('ffi_dispose') + .asFunction<_FFIDisposeDart>(); + + _ffiPlay = _lib! + .lookup>('ffi_play') + .asFunction<_FFIPlayDart>(); + + _ffiPause = _lib! + .lookup>('ffi_pause') + .asFunction<_FFIPauseDart>(); + + _ffiSeekTo = _lib! + .lookup>('ffi_seek_to') + .asFunction<_FFISeekToDart>(); + + _ffiGetPosition = _lib! + .lookup>('ffi_get_position') + .asFunction<_FFIGetPositionDart>(); + + _ffiGetDuration = _lib! + .lookup>('ffi_get_duration') + .asFunction<_FFIGetDurationDart>(); + + _ffiSetVolume = _lib! + .lookup>('ffi_set_volume') + .asFunction<_FFISetVolumeDart>(); + + _ffiSetPlaybackSpeed = _lib! + .lookup>( + 'ffi_set_playback_speed') + .asFunction<_FFISetPlaybackSpeedDart>(); + + _ffiSetLooping = _lib! + .lookup>('ffi_set_looping') + .asFunction<_FFISetLoopingDart>(); + + _ffiGetTrackInfo = _lib! + .lookup>( + 'ffi_get_track_info') + .asFunction<_FFIGetTrackInfoDart>(); + + _ffiSetTrackSelection = _lib! + .lookup>( + 'ffi_set_track_selection') + .asFunction<_FFISetTrackSelectionDart>(); + + _ffiSetDisplayGeometry = _lib! + .lookup>( + 'ffi_set_display_geometry') + .asFunction<_FFISetDisplayGeometryDart>(); + + _ffiSetDisplayRotate = _lib! + .lookup>( + 'ffi_set_display_rotate') + .asFunction<_FFISetDisplayRotateDart>(); + + _ffiSuspend = _lib! + .lookup>('ffi_suspend') + .asFunction<_FFISuspendDart>(); + + _ffiRestore = _lib! + .lookup>('ffi_restore') + .asFunction<_FFIRestoreDart>(); + debugPrint('FFI bindings loaded successfully'); } catch (e) { debugPrint('Failed to load FFI bindings: $e'); @@ -1040,7 +1153,9 @@ class VideoPlayerFFIBindings { return _ffiInitialize(); } - /// FFI create function with JSON parameters for complex data + /// FFI create function - takes a single JSON string for all parameters + /// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", + /// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} int ffiCreate({ String? uri, String? asset, @@ -1054,45 +1169,114 @@ class VideoPlayerFFIBindings { throw StateError('FFI bindings not loaded. Call load() first.'); } - // Convert Maps to JSON strings - String? httpHeadersJson = - httpHeaders != null ? jsonEncode(httpHeaders) : null; - String? drmConfigsJson = drmConfigs != null ? jsonEncode(drmConfigs) : null; - String? playerOptionsJson = - playerOptions != null ? jsonEncode(playerOptions) : null; - - final uriPtr = _toPointer(uri); - final assetPtr = _toPointer(asset); - final packagePtr = _toPointer(packageName); - final formatHintPtr = _toPointer(formatHint); - final httpHeadersPtr = _toPointer(httpHeadersJson); - final drmConfigsPtr = _toPointer(drmConfigsJson); - final playerOptionsPtr = _toPointer(playerOptionsJson); + // Build JSON string from individual parameters (same as restore pattern) + final Map jsonMap = {}; + if (uri != null && uri.isNotEmpty) jsonMap['uri'] = uri; + if (asset != null && asset.isNotEmpty) jsonMap['asset'] = asset; + if (packageName != null && packageName.isNotEmpty) + jsonMap['packageName'] = packageName; + if (formatHint != null && formatHint.isNotEmpty) + jsonMap['formatHint'] = formatHint; + if (httpHeaders != null && httpHeaders.isNotEmpty) + jsonMap['httpHeaders'] = httpHeaders; + if (drmConfigs != null && drmConfigs.isNotEmpty) + jsonMap['drmConfigs'] = drmConfigs; + if (playerOptions != null && playerOptions.isNotEmpty) + jsonMap['playerOptions'] = playerOptions; + + final String jsonString = jsonEncode(jsonMap); + final jsonPtr = _toPointer(jsonString); try { - return _ffiCreate( - uriPtr, - assetPtr, - packagePtr, - formatHintPtr, - httpHeadersPtr, - drmConfigsPtr, - playerOptionsPtr, - ); + return _ffiCreate(jsonPtr); } finally { - _freePointer(uriPtr); - _freePointer(assetPtr); - _freePointer(packagePtr); - _freePointer(formatHintPtr); - _freePointer(httpHeadersPtr); - _freePointer(drmConfigsPtr); - _freePointer(playerOptionsPtr); + _freePointer(jsonPtr); } } } -// Top-level FFI functions for easy access -Future ffiInitialize() async { +// FFI API for video_player_tizen - mirrors VideoPlayerVideoholeApi structure +// Note: All methods are synchronous for better performance +class VideoPlayerFFIApi { + int initialize() { + return ffiInitialize(); + } + + int create({ + String? uri, + String? asset, + String? packageName, + String? formatHint, + Map? httpHeaders, + Map? drmConfigs, + Map? playerOptions, + }) { + return ffiCreate( + uri: uri, + asset: asset, + packageName: packageName, + formatHint: formatHint, + httpHeaders: httpHeaders, + drmConfigs: drmConfigs, + playerOptions: playerOptions, + ); + } + + int dispose(int playerId) { + return ffiDispose(playerId); + } + + int play(int playerId) { + return ffiPlay(playerId); + } + + int pause(int playerId) { + return ffiPause(playerId); + } + + int seekTo(int playerId, int positionMs) { + return ffiSeekTo(playerId, positionMs); + } + + int getPosition(int playerId) { + return ffiGetPosition(playerId); + } + + DurationMessage duration(int playerId) { + return ffiGetDuration(playerId); + } + + int setVolume(int playerId, double volume) { + return ffiSetVolume(playerId, volume); + } + + int setPlaybackSpeed(int playerId, double speed) { + return ffiSetPlaybackSpeed(playerId, speed); + } + + int setLooping(int playerId, bool isLooping) { + return ffiSetLooping(playerId, isLooping); + } + + int setDisplayGeometry(int playerId, int x, int y, int width, int height) { + return ffiSetDisplayGeometry(playerId, x, y, width, height); + } + + int setDisplayRotate(int playerId, int rotation) { + return ffiSetDisplayRotate(playerId, rotation); + } + + int suspend(int playerId) { + return ffiSuspend(playerId); + } + + int restore(int playerId, String? createMessageJson, int resumeTime) { + return ffiRestore(playerId, createMessageJson, resumeTime); + } +} + +// Top-level FFI functions for easy access (synchronous) +int ffiInitialize() { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { bindings.load(); @@ -1101,7 +1285,7 @@ Future ffiInitialize() async { } /// FFI create function - returns player_id or -1 on error -Future ffiCreate({ +int ffiCreate({ String? uri, String? asset, String? packageName, @@ -1109,7 +1293,7 @@ Future ffiCreate({ Map? httpHeaders, Map? drmConfigs, Map? playerOptions, -}) async { +}) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { bindings.load(); @@ -1124,3 +1308,168 @@ Future ffiCreate({ playerOptions: playerOptions, ); } + +/// FFI dispose function - releases player resources +/// Returns: 0 on success, -1 on error +int ffiDispose(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiDispose(playerId); +} + +/// FFI play function - starts or resumes playback +/// Returns: 0 on success, -1 on error +int ffiPlay(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiPlay(playerId); +} + +/// FFI pause function - pauses playback +/// Returns: 0 on success, -1 on error +int ffiPause(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiPause(playerId); +} + +/// FFI seek_to function - seeks to a specific position (in milliseconds) +/// Returns: 0 on success, -1 on error +int ffiSeekTo(int playerId, int positionMs) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSeekTo(playerId, positionMs); +} + +/// FFI get_position function - gets current playback position in milliseconds +/// Returns: position in milliseconds (>= 0) on success, -1 on error +int ffiGetPosition(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiGetPosition(playerId); +} + +/// FFI get_duration function - gets video duration range in milliseconds +/// Returns: DurationMessage with durationRange on success +/// For live streams, start may be non-zero +/// Note: The C++ function returns a strdup-allocated string that we must free +DurationMessage ffiGetDuration(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final ptr = bindings._ffiGetDuration(playerId); + if (ptr == ffi.nullptr) { + throw Exception('FFI getDuration failed - returned null pointer'); + } + try { + // Convert C string to Dart string by finding null terminator + final bytes = ptr.cast(); + int length = 0; + while (bytes[length] != 0) { + length++; + } + final jsonString = utf8.decode(bytes.asTypedList(length)); + if (jsonString == '-1') { + throw Exception('FFI getDuration failed'); + } + final Map jsonMap = jsonDecode(jsonString); + return DurationMessage( + playerId: playerId, + durationRange: [ + jsonMap['start'] as int, + jsonMap['end'] as int, + ], + ); + } finally { + // Free the strdup-allocated memory to prevent memory leak + calloc.free(ptr); + } +} + +/// FFI set_volume function - sets playback volume (0.0 to 1.0) +/// Returns: 0 on success, -1 on error +int ffiSetVolume(int playerId, double volume) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetVolume(playerId, volume); +} + +/// FFI set_playback_speed function - sets playback speed +/// Returns: 0 on success, -1 on error +int ffiSetPlaybackSpeed(int playerId, double speed) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetPlaybackSpeed(playerId, speed); +} + +/// FFI set_looping function - enables or disables looping +/// Returns: 0 on success, -1 on error +int ffiSetLooping(int playerId, bool isLooping) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetLooping(playerId, isLooping); +} + +/// FFI set_display_geometry function - sets the display geometry (ROI) +/// Returns: 0 on success, -1 on error +int ffiSetDisplayGeometry(int playerId, int x, int y, int width, int height) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDisplayGeometry(playerId, x, y, width, height); +} + +/// FFI set_display_rotate function - sets display rotation +/// Returns: 0 on success, -1 on error +int ffiSetDisplayRotate(int playerId, int rotation) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDisplayRotate(playerId, rotation); +} + +/// FFI suspend function - suspends the player +/// Returns: 0 on success, -1 on error +int ffiSuspend(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSuspend(playerId); +} + +/// FFI restore function - restores a suspended player +/// Returns: 0 on success, -1 on error +/// createMessageJson: JSON string of CreateMessage or null/empty for using saved state from Suspend +int ffiRestore(int playerId, String? createMessageJson, int resumeTime) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + // Pass JSON string to C++ for parsing + final createMessagePtr = _toPointer(createMessageJson); + try { + return bindings._ffiRestore(playerId, createMessagePtr, resumeTime); + } finally { + _freePointer(createMessagePtr); + } +} diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index 4e0909d24..c73bb6ebe 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -4,7 +4,9 @@ // found in the LICENSE file. import 'dart:async'; +import 'dart:convert'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -12,47 +14,62 @@ import '../video_player_platform_interface.dart'; import 'messages.g.dart'; import 'tracks.dart'; -/// An implementation of [VideoPlayerPlatform] that uses FFI for initialization -/// and Platform Channel (Pigeon) for other methods (gradual migration). +/// An implementation of [VideoPlayerPlatform] that uses FFI for all methods. class VideoPlayerTizen extends VideoPlayerPlatform { final VideoPlayerVideoholeApi _api = VideoPlayerVideoholeApi(); + final VideoPlayerFFIApi _ffiApi = VideoPlayerFFIApi(); @override Future init() async { - // Use FFI for initialization (gradual migration from Platform Channel) + // Use FFI for initialization (synchronous call) try { - final result = await ffiInitialize(); + final int result = _ffiApi.initialize(); if (result != 0) { throw Exception('FFI initialize failed with code: $result'); } - print('********FFI initialize succeeded**********'); } catch (e) { - print( - '***********FFI initialize failed, falling back to Platform Channel: $e**********'); + debugPrint('FFI initialize failed, falling back to Platform Channel: $e'); // Fallback to Platform Channel if FFI fails return _api.initialize(); } } @override - Future dispose(int playerId) { - return _api.dispose(PlayerMessage(playerId: playerId)); + Future dispose(int playerId) async { + // Use FFI for dispose (synchronous call) + try { + final int result = _ffiApi.dispose(playerId); + // Don't throw on error - just log and return + // The player may already be disposed or in an invalid state + if (result != 0) { + return; + } + } catch (e) { + debugPrint('FFI dispose failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + // But don't throw - just silently return to avoid crash + try { + return _api.dispose(PlayerMessage(playerId: playerId)); + } catch (fallbackError) { + // Silently ignore - player is likely already disposed + } + } } @override Future create(DataSource dataSource) async { - // Use FFI for create (gradual migration from Platform Channel) + // Use FFI for create (synchronous call) try { int playerId; switch (dataSource.sourceType) { case DataSourceType.asset: - playerId = await ffiCreate( + playerId = _ffiApi.create( asset: dataSource.asset, packageName: dataSource.package, ); case DataSourceType.network: - playerId = await ffiCreate( + playerId = _ffiApi.create( uri: dataSource.uri, formatHint: _videoFormatStringMap[dataSource.formatHint], httpHeaders: dataSource.httpHeaders, @@ -61,18 +78,15 @@ class VideoPlayerTizen extends VideoPlayerPlatform { ); case DataSourceType.file: case DataSourceType.contentUri: - playerId = await ffiCreate(uri: dataSource.uri); + playerId = _ffiApi.create(uri: dataSource.uri); } if (playerId < 0) { throw Exception('FFI create failed with code: $playerId'); } - print( - '*************FFI create succeeded with player_id: $playerId*******'); return playerId; } catch (e) { - print( - '*************FFI create failed, falling back to Platform Channel: $e****'); + debugPrint('FFI create failed, falling back to Platform Channel: $e'); // Fallback to Platform Channel if FFI fails final CreateMessage message = CreateMessage(); @@ -97,51 +111,107 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } @override - Future setLooping(int playerId, bool looping) { - return _api.setLooping( - LoopingMessage(playerId: playerId, isLooping: looping), - ); + Future setLooping(int playerId, bool looping) async { + // Use FFI for setLooping (synchronous call) + try { + final int result = _ffiApi.setLooping(playerId, looping); + if (result != 0) { + throw Exception('FFI setLooping failed with code: $result'); + } + } catch (e) { + debugPrint('FFI setLooping failed, falling back to Platform Channel: $e'); + return _api.setLooping( + LoopingMessage(playerId: playerId, isLooping: looping), + ); + } } @override - Future play(int playerId) { - return _api.play(PlayerMessage(playerId: playerId)); + Future play(int playerId) async { + // Use FFI for play (synchronous call) + try { + final int result = _ffiApi.play(playerId); + if (result != 0) { + throw Exception('FFI play failed with code: $result'); + } + } catch (e) { + debugPrint('FFI play failed, falling back to Platform Channel: $e'); + return _api.play(PlayerMessage(playerId: playerId)); + } } @override Future setActivate(int playerId) { + // Note: FFI version not implemented yet, use Platform Channel return _api.setActivate(PlayerMessage(playerId: playerId)); } @override Future setDeactivate(int playerId) { + // Note: FFI version not implemented yet, use Platform Channel return _api.setDeactivate(PlayerMessage(playerId: playerId)); } @override - Future pause(int playerId) { - return _api.pause(PlayerMessage(playerId: playerId)); + Future pause(int playerId) async { + // Use FFI for pause (synchronous call) + try { + final int result = _ffiApi.pause(playerId); + if (result != 0) { + throw Exception('FFI pause failed with code: $result'); + } + } catch (e) { + debugPrint('FFI pause failed, falling back to Platform Channel: $e'); + return _api.pause(PlayerMessage(playerId: playerId)); + } } @override - Future setVolume(int playerId, double volume) { - return _api.setVolume(VolumeMessage(playerId: playerId, volume: volume)); + Future setVolume(int playerId, double volume) async { + // Use FFI for setVolume (synchronous call) + try { + final int result = _ffiApi.setVolume(playerId, volume); + if (result != 0) { + throw Exception('FFI setVolume failed with code: $result'); + } + } catch (e) { + debugPrint('FFI setVolume failed, falling back to Platform Channel: $e'); + return _api.setVolume(VolumeMessage(playerId: playerId, volume: volume)); + } } @override - Future setPlaybackSpeed(int playerId, double speed) { + Future setPlaybackSpeed(int playerId, double speed) async { + // Use FFI for setPlaybackSpeed (synchronous call) assert(speed > 0); - - return _api.setPlaybackSpeed( - PlaybackSpeedMessage(playerId: playerId, speed: speed), - ); + try { + final int result = _ffiApi.setPlaybackSpeed(playerId, speed); + if (result != 0) { + throw Exception('FFI setPlaybackSpeed failed with code: $result'); + } + } catch (e) { + debugPrint( + 'FFI setPlaybackSpeed failed, falling back to Platform Channel: $e'); + return _api.setPlaybackSpeed( + PlaybackSpeedMessage(playerId: playerId, speed: speed), + ); + } } @override - Future seekTo(int playerId, Duration position) { - return _api.seekTo( - PositionMessage(playerId: playerId, position: position.inMilliseconds), - ); + Future seekTo(int playerId, Duration position) async { + // Use FFI for seekTo (synchronous call) + try { + final int result = _ffiApi.seekTo(playerId, position.inMilliseconds); + if (result != 0) { + throw Exception('FFI seekTo failed with code: $result'); + } + } catch (e) { + debugPrint('FFI seekTo failed, falling back to Platform Channel: $e'); + return _api.seekTo( + PositionMessage(playerId: playerId, position: position.inMilliseconds), + ); + } } @override @@ -226,21 +296,45 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future getDuration(int playerId) async { - final DurationMessage message = await _api.duration( - PlayerMessage(playerId: playerId), - ); - return DurationRange( - Duration(milliseconds: message.durationRange?[0] ?? 0), - Duration(milliseconds: message.durationRange?[1] ?? 0), - ); + // Use FFI for getDuration (synchronous call) + try { + final DurationMessage message = _ffiApi.duration(playerId); + return DurationRange( + Duration(milliseconds: message.durationRange?[0] ?? 0), + Duration(milliseconds: message.durationRange?[1] ?? 0), + ); + } catch (e) { + debugPrint( + 'FFI getDuration failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + final DurationMessage message = await _api.duration( + PlayerMessage(playerId: playerId), + ); + return DurationRange( + Duration(milliseconds: message.durationRange?[0] ?? 0), + Duration(milliseconds: message.durationRange?[1] ?? 0), + ); + } } @override Future getPosition(int playerId) async { - final PositionMessage response = await _api.position( - PlayerMessage(playerId: playerId), - ); - return Duration(milliseconds: response.position); + // Use FFI for getPosition (synchronous call) + try { + final int positionMs = _ffiApi.getPosition(playerId); + if (positionMs < 0) { + throw Exception('FFI getPosition failed with code: $positionMs'); + } + return Duration(milliseconds: positionMs); + } catch (e) { + debugPrint( + 'FFI getPosition failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + final PositionMessage response = await _api.position( + PlayerMessage(playerId: playerId), + ); + return Duration(milliseconds: response.position); + } } @override @@ -318,21 +412,43 @@ class VideoPlayerTizen extends VideoPlayerPlatform { int y, int width, int height, - ) { - return _api.setDisplayGeometry( - GeometryMessage( - playerId: playerId, - x: x, - y: y, - width: width, - height: height, - ), - ); + ) async { + // Use FFI for setDisplayGeometry (synchronous call) + try { + final int result = + _ffiApi.setDisplayGeometry(playerId, x, y, width, height); + if (result != 0) { + throw Exception('FFI setDisplayGeometry failed with code: $result'); + } + } catch (e) { + debugPrint( + 'FFI setDisplayGeometry failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + return _api.setDisplayGeometry( + GeometryMessage( + playerId: playerId, + x: x, + y: y, + width: width, + height: height, + ), + ); + } } @override - Future suspend(int playerId) { - return _api.suspend(playerId); + Future suspend(int playerId) async { + // Use FFI for suspend (synchronous call) + try { + final int result = _ffiApi.suspend(playerId); + if (result != 0) { + throw Exception('FFI suspend failed with code: $result'); + } + } catch (e) { + debugPrint('FFI suspend failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + return _api.suspend(playerId); + } } @override @@ -340,35 +456,101 @@ class VideoPlayerTizen extends VideoPlayerPlatform { int playerId, { DataSource? dataSource, int resumeTime = -1, - }) { - final CreateMessage message = CreateMessage(); + }) async { + // Use FFI for restore (synchronous call) + try { + // Build JSON string from dataSource (same pattern as create) + String? createMessageJson; + if (dataSource != null) { + final Map jsonMap = {}; + + switch (dataSource.sourceType) { + case DataSourceType.asset: + if (dataSource.asset != null && dataSource.asset!.isNotEmpty) { + jsonMap['asset'] = dataSource.asset; + } + if (dataSource.package != null && dataSource.package!.isNotEmpty) { + jsonMap['packageName'] = dataSource.package; + } + case DataSourceType.network: + if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { + jsonMap['uri'] = dataSource.uri; + } + if (dataSource.formatHint != null) { + jsonMap['formatHint'] = + _videoFormatStringMap[dataSource.formatHint]; + } + if (dataSource.httpHeaders.isNotEmpty) { + jsonMap['httpHeaders'] = dataSource.httpHeaders; + } + if (dataSource.drmConfigs != null) { + jsonMap['drmConfigs'] = dataSource.drmConfigs!.toMap(); + } + if (dataSource.playerOptions != null && + dataSource.playerOptions!.isNotEmpty) { + jsonMap['playerOptions'] = dataSource.playerOptions; + } + case DataSourceType.file: + case DataSourceType.contentUri: + if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { + jsonMap['uri'] = dataSource.uri; + } + } + + createMessageJson = jsonEncode(jsonMap); + } - if (dataSource != null) { - switch (dataSource.sourceType) { - case DataSourceType.asset: - message.asset = dataSource.asset; - message.packageName = dataSource.package; - case DataSourceType.network: - message.uri = dataSource.uri; - message.formatHint = _videoFormatStringMap[dataSource.formatHint]; - message.httpHeaders = dataSource.httpHeaders; - message.drmConfigs = dataSource.drmConfigs?.toMap(); - message.playerOptions = dataSource.playerOptions; - case DataSourceType.file: - message.uri = dataSource.uri; - case DataSourceType.contentUri: - message.uri = dataSource.uri; + final int result = + _ffiApi.restore(playerId, createMessageJson, resumeTime); + if (result != 0) { + // FFI restore failed, but don't throw - just log and return + // The player may still be in a valid state + return; + } + } catch (e) { + debugPrint('FFI restore failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + final CreateMessage message = CreateMessage(); + + if (dataSource != null) { + switch (dataSource.sourceType) { + case DataSourceType.asset: + message.asset = dataSource.asset; + message.packageName = dataSource.package; + case DataSourceType.network: + message.uri = dataSource.uri; + message.formatHint = _videoFormatStringMap[dataSource.formatHint]; + message.httpHeaders = dataSource.httpHeaders; + message.drmConfigs = dataSource.drmConfigs?.toMap(); + message.playerOptions = dataSource.playerOptions; + case DataSourceType.file: + message.uri = dataSource.uri; + case DataSourceType.contentUri: + message.uri = dataSource.uri; + } } - } - return _api.restore(playerId, message, resumeTime); + return _api.restore(playerId, message, resumeTime); + } } @override - Future setDisplayRotate(int playerId, DisplayRotation rotation) { - return _api.setDisplayRotate( - RotationMessage(playerId: playerId, rotation: rotation.index), - ); + Future setDisplayRotate(int playerId, DisplayRotation rotation) async { + // Use FFI for setDisplayRotate (synchronous call) + try { + final int result = _ffiApi.setDisplayRotate(playerId, rotation.index); + if (result != 0) { + throw Exception('FFI setDisplayRotate failed with code: $result'); + } + return true; + } catch (e) { + debugPrint( + 'FFI setDisplayRotate failed, falling back to Platform Channel: $e'); + // Fallback to Platform Channel if FFI fails + return _api.setDisplayRotate( + RotationMessage(playerId: playerId, rotation: rotation.index), + ); + } } EventChannel _eventChannelFor(int playerId) { diff --git a/packages/video_player_videohole/tizen/src/messages.h b/packages/video_player_videohole/tizen/src/messages.h index 793334fa2..13435e6aa 100644 --- a/packages/video_player_videohole/tizen/src/messages.h +++ b/packages/video_player_videohole/tizen/src/messages.h @@ -457,13 +457,11 @@ extern "C" { int ffi_initialize(); // FFI create - returns player_id or -1 on error -// Parameters: uri, asset, package_name, format_hint, http_headers_json, -// drm_configs_json, player_options_json (all const char*) +// Parameters: create_message_json - JSON string containing all create parameters +// Format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} // Returns: int64_t player_id (negative value indicates error) -int64_t ffi_create(const char* uri, const char* asset, const char* package_name, - const char* format_hint, const char* http_headers_json, - const char* drm_configs_json, - const char* player_options_json); +int64_t ffi_create(const char* create_message_json); #ifdef __cplusplus } // extern "C" diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 02deed936..50e04d084 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -12,10 +12,12 @@ #include #include #include +#include #include #include #include #include +#include #include "media_player.h" #include "messages.h" @@ -468,157 +470,499 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { return result; } -// Helper function to parse JSON for drm_configs -// Format: {"drmType":1,"licenseServerUrl":"http://..."} -// Note: prebufferMode is not currently supported by DrmConfigs class -// -// Dart DrmType enum: none=0, playready=1, widevine=2 -// DrmManager::DrmType enum: DRM_TYPE_NONE=0, DRM_TYPE_PLAYREADAY=1, -// DRM_TYPE_WIDEVINECDM=2 The enum values are the same, no mapping needed +// Helper function to extract a string value from JSON by key +// Returns true if the key was found and value was extracted +static bool ExtractStringValue(const std::string &json_str, + const std::string &key, + std::string &out_value) { + std::string search_key = "\"" + key + "\""; + size_t pos = json_str.find(search_key); + if (pos == std::string::npos) return false; + + pos = json_str.find(':', pos); + if (pos == std::string::npos) return false; + + pos++; + while (pos < json_str.length() && (isspace(json_str[pos]) || json_str[pos] == ':')) pos++; + if (pos >= json_str.length() || json_str[pos] != '"') return false; + + pos++; // skip opening quote + size_t end = pos; + while (end < json_str.length() && json_str[end] != '"') end++; + + out_value = json_str.substr(pos, end - pos); + return true; +} -static void ParseDrmConfigs(const std::string &json_str, int64_t &drm_type, - std::string &license_server_url) { - drm_type = 0; - license_server_url.clear(); +// Helper function to extract a nested object from JSON by key +// Returns the nested object JSON string (including braces) or empty string if not found +static std::string ExtractObjectValue(const std::string &json_str, + const std::string &key) { + std::string search_key = "\"" + key + "\""; + size_t pos = json_str.find(search_key); + if (pos == std::string::npos) return ""; + + pos = json_str.find(':', pos); + if (pos == std::string::npos) return ""; + + pos++; + while (pos < json_str.length() && isspace(json_str[pos])) pos++; + if (pos >= json_str.length() || json_str[pos] != '{') return ""; + + int brace_count = 1; + size_t start = pos; + pos++; + while (pos < json_str.length() && brace_count > 0) { + if (json_str[pos] == '{') brace_count++; + else if (json_str[pos] == '}') brace_count--; + pos++; + } + return json_str.substr(start, pos - start); +} +// Unified function to parse CreateMessage from JSON string +// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} +static video_player_videohole_tizen::CreateMessage ParseCreateMessage( + const std::string &json_str) { + video_player_videohole_tizen::CreateMessage msg; + if (json_str.empty() || json_str == "{}") { - return; + return msg; + } + + // Extract string fields using helper function + std::string value; + if (ExtractStringValue(json_str, "uri", value)) { + msg.set_uri(value); + } + if (ExtractStringValue(json_str, "asset", value)) { + msg.set_asset(value); + } + if (ExtractStringValue(json_str, "packageName", value)) { + msg.set_package_name(value); + } + if (ExtractStringValue(json_str, "formatHint", value)) { + msg.set_format_hint(value); + } + + // Extract nested object fields using helper function + std::string nested_json; + + // httpHeaders + nested_json = ExtractObjectValue(json_str, "httpHeaders"); + if (!nested_json.empty()) { + flutter::EncodableMap headers = ParseJsonMap(nested_json); + if (!headers.empty()) { + msg.set_http_headers(headers); + } + } + + // playerOptions + nested_json = ExtractObjectValue(json_str, "playerOptions"); + if (!nested_json.empty()) { + flutter::EncodableMap options = ParseJsonMap(nested_json); + if (!options.empty()) { + msg.set_player_options(options); + } + } + + // drmConfigs (special handling for drmType and licenseServerUrl) + nested_json = ExtractObjectValue(json_str, "drmConfigs"); + if (!nested_json.empty()) { + int64_t drm_type = 0; + std::string license_url; + + // Extract drmType (number value) + size_t drm_pos = nested_json.find("\"drmType\""); + if (drm_pos != std::string::npos) { + drm_pos = nested_json.find(':', drm_pos); + if (drm_pos != std::string::npos) { + drm_pos++; + while (drm_pos < nested_json.length() && (isspace(nested_json[drm_pos]) || nested_json[drm_pos] == ':')) drm_pos++; + size_t end = drm_pos; + while (end < nested_json.length() && nested_json[end] != ',' && nested_json[end] != '}' && nested_json[end] != '"') end++; + std::string val = nested_json.substr(drm_pos, end - drm_pos); + while (!val.empty() && (val.back() == '"' || isspace(val.back()))) val.pop_back(); + try { + drm_type = std::stoll(val); + } catch (...) { + if (val == "1") drm_type = 1; + else if (val == "2") drm_type = 2; + } + } + } + + // Extract licenseServerUrl using helper function + ExtractStringValue(nested_json, "licenseServerUrl", license_url); + + flutter::EncodableMap drm_map; + drm_map[flutter::EncodableValue("drmType")] = flutter::EncodableValue(drm_type); + if (!license_url.empty()) { + drm_map[flutter::EncodableValue("licenseServerUrl")] = flutter::EncodableValue(license_url); + } + msg.set_drm_configs(drm_map); } + + return msg; +} - // Simple extraction - size_t pos; +// FFI create function - takes a single JSON string for all create parameters +// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} +// Returns: player_id on success, -1 on error +int64_t ffi_create(const char *create_message_json) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } - // Extract drmType - pos = json_str.find("\"drmType\""); - if (pos != std::string::npos) { - pos = json_str.find(':', pos); - if (pos != std::string::npos) { - pos++; - while (pos < json_str.length() && - (isspace(json_str[pos]) || json_str[pos] == ':')) - pos++; + video_player_videohole_tizen::CreateMessage msg; + if (create_message_json != nullptr && strlen(create_message_json) > 0) { + msg = ParseCreateMessage(std::string(create_message_json)); + } + + auto result = plugin->Create(msg); + if (result.has_error()) { + return -1; + } + return result.value().player_id(); +} - // Skip any leading quotes (shouldn't be there for numbers, but just in - // case) - while (pos < json_str.length() && - (json_str[pos] == '"' || isspace(json_str[pos]))) - pos++; +// FFI dispose function - releases player resources +// Returns: 0 on success, -1 on error +// Safe to call multiple times with same player_id +int ffi_dispose(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Check if player exists before trying to dispose + // This prevents crash when dispose is called multiple times + auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + if (player == nullptr) { + // Player already disposed or never existed - return success silently + return 0; + } + + auto result = plugin->Dispose( + video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + +// FFI play function - starts or resumes playback +// Returns: 0 on success, -1 on error +// Note: Checks if player exists before calling to avoid crash on disposed player +int ffi_play(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Check if player exists before calling - avoid crash on disposed player + auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + if (player == nullptr) { + return -1; // Player already disposed or never existed + } + + auto result = + plugin->Play(video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} - size_t end = pos; - while (end < json_str.length() && json_str[end] != ',' && - json_str[end] != '}' && json_str[end] != '"') - end++; - std::string val = json_str.substr(pos, end - pos); - - // Trim trailing whitespace and quotes - while (!val.empty() && (val.back() == '"' || isspace(val.back()))) - val.pop_back(); - - try { - drm_type = std::stoll(val); - } catch (const std::exception &e) { - // Fallback: try direct comparison - if (val == "1") { - drm_type = 1; // PlayReady - } else if (val == "2") { - drm_type = 2; // Widevine +// FFI pause function - pauses playback +// Returns: 0 on success, -1 on error +// Note: Checks if player exists before calling to avoid crash on disposed player +int ffi_pause(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Check if player exists before calling - avoid crash on disposed player + auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + if (player == nullptr) { + return -1; // Player already disposed or never existed + } + + auto result = + plugin->Pause(video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + +// FFI seek_to function - seeks to a specific position (in milliseconds) +// Returns: 0 on success, -1 on error +// Note: This is a fire-and-forget operation. The seek completion is notified +// through the event channel, not through return value. +int ffi_seek_to(int64_t player_id, int64_t position_ms) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Call SeekTo asynchronously - the result will be notified through event channel + // We don't block here to avoid freezing the UI thread + plugin->SeekTo( + video_player_videohole_tizen::PositionMessage(player_id, position_ms), + [](std::optional result) { + // Callback is invoked when seek completes + // The event channel will notify Flutter about the seek completion + if (result.has_value()) { + // Log error but don't block - Flutter will handle it through events } - } - } + }); + + // Return immediately to allow UI to refresh + return 0; // Success (actual result will be notified through event channel) +} + +// FFI get_position function - gets current playback position in milliseconds +// Returns: position in milliseconds (>= 0) on success, -1 on error +// Note: Checks if player exists before calling to avoid crash on disposed player +int64_t ffi_get_position(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized } - // Extract licenseServerUrl - handle both string and null values - pos = json_str.find("\"licenseServerUrl\""); - if (pos != std::string::npos) { - pos = json_str.find(':', pos); - if (pos != std::string::npos) { - pos++; - while (pos < json_str.length() && - (isspace(json_str[pos]) || json_str[pos] == ':')) - pos++; + // Check if player exists before calling - avoid crash on disposed player + auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + if (player == nullptr) { + return -1; // Player already disposed or never existed + } - // Check for null value - if (pos < json_str.length() && json_str.substr(pos, 4) == "null") { - license_server_url.clear(); - } else if (pos < json_str.length() && json_str[pos] == '"') { - // String value - pos++; - size_t end = pos; - while (end < json_str.length() && json_str[end] != '"') end++; - license_server_url = json_str.substr(pos, end - pos); - } - } + auto result = + plugin->Position(video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_error()) { + return -1; + } + return result.value().position(); +} + +// FFI get_duration function - gets video duration range in milliseconds +// Returns: JSON string with start and end values, or "-1" on error +// Format: {"start": , "end": } +// For live streams, start may be non-zero (e.g., {"start": 1000, "end": 5000}) +// Note: Returns a malloc-allocated string that the caller must free +const char* ffi_get_duration(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return strdup("-1"); // Plugin not initialized + } + + auto result = + plugin->Duration(video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_error()) { + return strdup("-1"); + } + + // Return both start and end of duration range as JSON + // Use strdup to allocate memory that persists after this function returns + // The Dart caller is responsible for freeing this memory + const auto& duration_range = result.value().duration_range(); + std::string duration_json; + if (duration_range && duration_range->size() >= 2) { + int64_t start = (*duration_range)[0].IsNull() ? 0 : + std::get((*duration_range)[0]); + int64_t end = (*duration_range)[1].IsNull() ? 0 : + std::get((*duration_range)[1]); + duration_json = "{\"start\":" + std::to_string(start) + + ",\"end\":" + std::to_string(end) + "}"; + } else { + duration_json = "{\"start\":0,\"end\":0}"; } + return strdup(duration_json.c_str()); } -int64_t ffi_create(const char *uri, const char *asset, const char *package_name, - const char *format_hint, const char *http_headers_json, - const char *drm_configs_json, - const char *player_options_json) { +// FFI set_volume function - sets playback volume (0.0 to 1.0) +// Returns: 0 on success, -1 on error +int ffi_set_volume(int64_t player_id, double volume) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { return -1; // Plugin not initialized } - // Build CreateMessage from FFI parameters - video_player_videohole_tizen::CreateMessage msg; + auto result = plugin->SetVolume( + video_player_videohole_tizen::VolumeMessage(player_id, volume)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} - // Set basic fields - if (uri != nullptr && strlen(uri) > 0) { - msg.set_uri(std::string(uri)); +// FFI set_playback_speed function - sets playback speed +// Returns: 0 on success, -1 on error +int ffi_set_playback_speed(int64_t player_id, double speed) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized } - if (asset != nullptr && strlen(asset) > 0) { - msg.set_asset(std::string(asset)); + + auto result = plugin->SetPlaybackSpeed( + video_player_videohole_tizen::PlaybackSpeedMessage(player_id, speed)); + if (result.has_value()) { + // Error occurred + return -1; } - if (package_name != nullptr && strlen(package_name) > 0) { - msg.set_package_name(std::string(package_name)); + return 0; // Success +} + +// FFI set_looping function - enables or disables looping +// Returns: 0 on success, -1 on error +int ffi_set_looping(int64_t player_id, bool is_looping) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized } - if (format_hint != nullptr && strlen(format_hint) > 0) { - msg.set_format_hint(std::string(format_hint)); + + auto result = plugin->SetLooping( + video_player_videohole_tizen::LoopingMessage(player_id, is_looping)); + if (result.has_value()) { + // Error occurred + return -1; } + return 0; // Success +} - // Parse http_headers JSON - if (http_headers_json != nullptr && strlen(http_headers_json) > 0) { - flutter::EncodableMap headers = - ParseJsonMap(std::string(http_headers_json)); - if (!headers.empty()) { - msg.set_http_headers(headers); - } +// FFI get_track_info function - gets track information for a specific track type +// Returns: JSON string of track info on success, nullptr on error +// Note: Returns a malloc-allocated string that the caller must free +const char* ffi_get_track_info(int64_t player_id, const char* track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return nullptr; } - // Parse drm_configs JSON - if (drm_configs_json != nullptr && strlen(drm_configs_json) > 0) { - int64_t drm_type = 0; - std::string license_url; - ParseDrmConfigs(std::string(drm_configs_json), drm_type, license_url); + auto result = plugin->Track( + video_player_videohole_tizen::TrackTypeMessage(player_id, std::string(track_type))); + if (result.has_error()) { + return nullptr; + } - flutter::EncodableMap drm_map; - drm_map[flutter::EncodableValue("drmType")] = - flutter::EncodableValue(drm_type); - if (!license_url.empty()) { - drm_map[flutter::EncodableValue("licenseServerUrl")] = - flutter::EncodableValue(license_url); - } - msg.set_drm_configs(drm_map); + // Convert TrackMessage to JSON string + // Use strdup to allocate memory that persists after this function returns + // The Dart caller is responsible for freeing this memory + std::string track_info_json = "{\"playerId\":" + std::to_string(result.value().player_id()) + + ",\"tracks\":[]}"; + return strdup(track_info_json.c_str()); +} + +// FFI set_track_selection function - sets the selected track +// Returns: 0 on success, -1 on error +int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return -1; // Plugin not initialized } - // Parse player_options JSON - if (player_options_json != nullptr && strlen(player_options_json) > 0) { - flutter::EncodableMap options = - ParseJsonMap(std::string(player_options_json)); - if (!options.empty()) { - msg.set_player_options(options); - } + auto result = plugin->SetTrackSelection( + video_player_videohole_tizen::SelectedTracksMessage(player_id, track_id, std::string(track_type))); + if (result.has_error()) { + return -1; } + return result.value() ? 0 : -1; +} - // Use the plugin's Create method which handles asset resolution and player - // creation - auto result = plugin->Create(msg); +// FFI set_display_geometry function - sets the display geometry (ROI) +// Returns: 0 on success, -1 on error +int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetDisplayGeometry( + video_player_videohole_tizen::GeometryMessage(player_id, x, y, width, height)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + +// FFI set_display_rotate function - sets display rotation +// Returns: 0 on success, -1 on error +int ffi_set_display_rotate(int64_t player_id, int32_t rotation) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetDisplayRotate( + video_player_videohole_tizen::RotationMessage(player_id, rotation)); if (result.has_error()) { return -1; } - return result.value().player_id(); + return result.value() ? 0 : -1; +} + +// FFI suspend function - suspends the player +// Returns: 0 on success, -1 on error +int ffi_suspend(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->Suspend(player_id); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + +// FFI restore function - restores a suspended player +// create_message_json: JSON string of CreateMessage or empty/null for using saved state +// Returns: 0 on success, -1 on error +int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resume_time) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + // Use unified ParseCreateMessage function to parse JSON + video_player_videohole_tizen::CreateMessage msg; + if (create_message_json != nullptr && strlen(create_message_json) > 0) { + msg = ParseCreateMessage(std::string(create_message_json)); + } + + auto result = plugin->Restore(player_id, &msg, resume_time); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success } } // extern "C" From 51571e3f75e4c34c8b555fb78005df7c20ca8922 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Mon, 20 Jul 2026 15:32:44 +0800 Subject: [PATCH 03/18] remove BasicMessageChannel and VideoPlayerVideoholeApi --- .../lib/src/messages.g.dart | 135 +++++ .../lib/src/video_player_tizen.dart | 484 +++++++----------- .../tizen/src/drm_manager.cc | 11 +- .../tizen/src/drm_manager.h | 1 + .../tizen/src/media_player.cc | 26 +- .../tizen/src/messages.cc | 7 +- .../tizen/src/messages.h | 76 ++- .../tizen/src/video_player_tizen_plugin.cc | 216 +++++--- 8 files changed, 573 insertions(+), 383 deletions(-) diff --git a/packages/video_player_videohole/lib/src/messages.g.dart b/packages/video_player_videohole/lib/src/messages.g.dart index 6c590951b..47ca219e1 100644 --- a/packages/video_player_videohole/lib/src/messages.g.dart +++ b/packages/video_player_videohole/lib/src/messages.g.dart @@ -998,6 +998,15 @@ typedef _FFISetDisplayGeometryDart = int Function(int, int, int, int, int); typedef _FFISetDisplayRotateNative = ffi.Int32 Function(ffi.Int64, ffi.Int32); typedef _FFISetDisplayRotateDart = int Function(int, int); +typedef _FFISetActivateNative = ffi.Int32 Function(ffi.Int64); +typedef _FFISetActivateDart = int Function(int); + +typedef _FFISetDeactivateNative = ffi.Int32 Function(ffi.Int64); +typedef _FFISetDeactivateDart = int Function(int); + +typedef _FFISetMixWithOthersNative = ffi.Int32 Function(ffi.Bool); +typedef _FFISetMixWithOthersDart = int Function(bool); + typedef _FFISuspendNative = ffi.Int32 Function(ffi.Int64); typedef _FFISuspendDart = int Function(int); @@ -1046,6 +1055,9 @@ class VideoPlayerFFIBindings { late int Function(int, int) _ffiSetDisplayRotate; late int Function(int) _ffiSuspend; late int Function(int, ffi.Pointer, int) _ffiRestore; + late int Function(int) _ffiSetActivate; + late int Function(int) _ffiSetDeactivate; + late int Function(bool) _ffiSetMixWithOthers; static VideoPlayerFFIBindings get instance { _instance ??= VideoPlayerFFIBindings._(); @@ -1136,6 +1148,30 @@ class VideoPlayerFFIBindings { .lookup>('ffi_restore') .asFunction<_FFIRestoreDart>(); + _ffiSetActivate = _lib! + .lookup>('ffi_set_activate') + .asFunction<_FFISetActivateDart>(); + + _ffiSetDeactivate = _lib! + .lookup>( + 'ffi_set_deactivate') + .asFunction<_FFISetDeactivateDart>(); + + _ffiGetTrackInfo = _lib! + .lookup>( + 'ffi_get_track_info') + .asFunction<_FFIGetTrackInfoDart>(); + + _ffiSetTrackSelection = _lib! + .lookup>( + 'ffi_set_track_selection') + .asFunction<_FFISetTrackSelectionDart>(); + + _ffiSetMixWithOthers = _lib! + .lookup>( + 'ffi_set_mix_with_others') + .asFunction<_FFISetMixWithOthersDart>(); + debugPrint('FFI bindings loaded successfully'); } catch (e) { debugPrint('Failed to load FFI bindings: $e'); @@ -1273,6 +1309,26 @@ class VideoPlayerFFIApi { int restore(int playerId, String? createMessageJson, int resumeTime) { return ffiRestore(playerId, createMessageJson, resumeTime); } + + int setActivate(int playerId) { + return ffiSetActivate(playerId); + } + + int setDeactivate(int playerId) { + return ffiSetDeactivate(playerId); + } + + String getTrackInfo(int playerId, String trackType) { + return ffiGetTrackInfo(playerId, trackType); + } + + int setTrackSelection(int playerId, int trackId, String trackType) { + return ffiSetTrackSelection(playerId, trackId, trackType); + } + + int setMixWithOthers(bool mixWithOthers) { + return ffiSetMixWithOthers(mixWithOthers); + } } // Top-level FFI functions for easy access (synchronous) @@ -1473,3 +1529,82 @@ int ffiRestore(int playerId, String? createMessageJson, int resumeTime) { _freePointer(createMessagePtr); } } + +/// FFI set_activate function - activates the player +/// Returns: 0 on success, -1 on error +int ffiSetActivate(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetActivate(playerId); +} + +/// FFI set_deactivate function - deactivates the player +/// Returns: 0 on success, -1 on error +int ffiSetDeactivate(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDeactivate(playerId); +} + +/// FFI get_track_info function - gets track info as JSON string +/// Returns: JSON string containing track information +String ffiGetTrackInfo(int playerId, String trackType) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final trackTypePtr = _toPointer(trackType); + ffi.Pointer? ptr; + try { + ptr = bindings._ffiGetTrackInfo(playerId, trackTypePtr); + if (ptr == ffi.nullptr) { + throw Exception('FFI getTrackInfo failed - returned null pointer'); + } + // Convert C string to Dart string by finding null terminator + final bytes = ptr.cast(); + int length = 0; + while (bytes[length] != 0) { + length++; + } + final jsonString = utf8.decode(bytes.asTypedList(length)); + if (jsonString == '-1') { + throw Exception('FFI getTrackInfo failed'); + } + return jsonString; + } finally { + // Free the strdup-allocated memory to prevent memory leak + if (ptr != null) { + calloc.free(ptr); + } + _freePointer(trackTypePtr); + } +} + +/// FFI set_track_selection function - sets the track selection +/// Returns: 0 on success, -1 on error +int ffiSetTrackSelection(int playerId, int trackId, String trackType) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final trackTypePtr = _toPointer(trackType); + try { + return bindings._ffiSetTrackSelection(playerId, trackId, trackTypePtr); + } finally { + _freePointer(trackTypePtr); + } +} + +/// FFI set_mix_with_others function - sets mix with others +/// Returns: 0 on success, -1 on error +int ffiSetMixWithOthers(bool mixWithOthers) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetMixWithOthers(mixWithOthers); +} diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index c73bb6ebe..f7db1dbd0 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -6,7 +6,6 @@ import 'dart:async'; import 'dart:convert'; -import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; @@ -16,167 +15,111 @@ import 'tracks.dart'; /// An implementation of [VideoPlayerPlatform] that uses FFI for all methods. class VideoPlayerTizen extends VideoPlayerPlatform { - final VideoPlayerVideoholeApi _api = VideoPlayerVideoholeApi(); final VideoPlayerFFIApi _ffiApi = VideoPlayerFFIApi(); @override Future init() async { // Use FFI for initialization (synchronous call) - try { - final int result = _ffiApi.initialize(); - if (result != 0) { - throw Exception('FFI initialize failed with code: $result'); - } - } catch (e) { - debugPrint('FFI initialize failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - return _api.initialize(); + final int result = _ffiApi.initialize(); + if (result != 0) { + throw Exception('FFI initialize failed with code: $result'); } } @override Future dispose(int playerId) async { // Use FFI for dispose (synchronous call) - try { - final int result = _ffiApi.dispose(playerId); - // Don't throw on error - just log and return - // The player may already be disposed or in an invalid state - if (result != 0) { - return; - } - } catch (e) { - debugPrint('FFI dispose failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - // But don't throw - just silently return to avoid crash - try { - return _api.dispose(PlayerMessage(playerId: playerId)); - } catch (fallbackError) { - // Silently ignore - player is likely already disposed - } + final int result = _ffiApi.dispose(playerId); + // Don't throw on error - just return + // The player may already be disposed or in an invalid state + if (result != 0) { + return; } } @override Future create(DataSource dataSource) async { // Use FFI for create (synchronous call) - try { - int playerId; - - switch (dataSource.sourceType) { - case DataSourceType.asset: - playerId = _ffiApi.create( - asset: dataSource.asset, - packageName: dataSource.package, - ); - case DataSourceType.network: - playerId = _ffiApi.create( - uri: dataSource.uri, - formatHint: _videoFormatStringMap[dataSource.formatHint], - httpHeaders: dataSource.httpHeaders, - drmConfigs: dataSource.drmConfigs?.toMap(), - playerOptions: dataSource.playerOptions, - ); - case DataSourceType.file: - case DataSourceType.contentUri: - playerId = _ffiApi.create(uri: dataSource.uri); - } - - if (playerId < 0) { - throw Exception('FFI create failed with code: $playerId'); - } - return playerId; - } catch (e) { - debugPrint('FFI create failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - final CreateMessage message = CreateMessage(); - - switch (dataSource.sourceType) { - case DataSourceType.asset: - message.asset = dataSource.asset; - message.packageName = dataSource.package; - case DataSourceType.network: - message.uri = dataSource.uri; - message.formatHint = _videoFormatStringMap[dataSource.formatHint]; - message.httpHeaders = dataSource.httpHeaders; - message.drmConfigs = dataSource.drmConfigs?.toMap(); - message.playerOptions = dataSource.playerOptions; - case DataSourceType.file: - case DataSourceType.contentUri: - message.uri = dataSource.uri; - } + int playerId; + + switch (dataSource.sourceType) { + case DataSourceType.asset: + playerId = _ffiApi.create( + asset: dataSource.asset, + packageName: dataSource.package, + ); + case DataSourceType.network: + playerId = _ffiApi.create( + uri: dataSource.uri, + formatHint: _videoFormatStringMap[dataSource.formatHint], + httpHeaders: dataSource.httpHeaders, + drmConfigs: dataSource.drmConfigs?.toMap(), + playerOptions: dataSource.playerOptions, + ); + case DataSourceType.file: + case DataSourceType.contentUri: + playerId = _ffiApi.create(uri: dataSource.uri); + } - final PlayerMessage response = await _api.create(message); - return response.playerId; + if (playerId < 0) { + throw Exception('FFI create failed with code: $playerId'); } + return playerId; } @override Future setLooping(int playerId, bool looping) async { // Use FFI for setLooping (synchronous call) - try { - final int result = _ffiApi.setLooping(playerId, looping); - if (result != 0) { - throw Exception('FFI setLooping failed with code: $result'); - } - } catch (e) { - debugPrint('FFI setLooping failed, falling back to Platform Channel: $e'); - return _api.setLooping( - LoopingMessage(playerId: playerId, isLooping: looping), - ); + final int result = _ffiApi.setLooping(playerId, looping); + if (result != 0) { + throw Exception('FFI setLooping failed with code: $result'); } } @override Future play(int playerId) async { // Use FFI for play (synchronous call) - try { - final int result = _ffiApi.play(playerId); - if (result != 0) { - throw Exception('FFI play failed with code: $result'); - } - } catch (e) { - debugPrint('FFI play failed, falling back to Platform Channel: $e'); - return _api.play(PlayerMessage(playerId: playerId)); + final int result = _ffiApi.play(playerId); + if (result != 0) { + throw Exception('FFI play failed with code: $result'); } } @override - Future setActivate(int playerId) { - // Note: FFI version not implemented yet, use Platform Channel - return _api.setActivate(PlayerMessage(playerId: playerId)); + Future setActivate(int playerId) async { + // Use FFI for setActivate (synchronous call) + final int result = _ffiApi.setActivate(playerId); + if (result != 0) { + throw Exception('FFI setActivate failed with code: $result'); + } + return true; } @override - Future setDeactivate(int playerId) { - // Note: FFI version not implemented yet, use Platform Channel - return _api.setDeactivate(PlayerMessage(playerId: playerId)); + Future setDeactivate(int playerId) async { + // Use FFI for setDeactivate (synchronous call) + final int result = _ffiApi.setDeactivate(playerId); + if (result != 0) { + throw Exception('FFI setDeactivate failed with code: $result'); + } + return true; } @override Future pause(int playerId) async { // Use FFI for pause (synchronous call) - try { - final int result = _ffiApi.pause(playerId); - if (result != 0) { - throw Exception('FFI pause failed with code: $result'); - } - } catch (e) { - debugPrint('FFI pause failed, falling back to Platform Channel: $e'); - return _api.pause(PlayerMessage(playerId: playerId)); + final int result = _ffiApi.pause(playerId); + if (result != 0) { + throw Exception('FFI pause failed with code: $result'); } } @override Future setVolume(int playerId, double volume) async { // Use FFI for setVolume (synchronous call) - try { - final int result = _ffiApi.setVolume(playerId, volume); - if (result != 0) { - throw Exception('FFI setVolume failed with code: $result'); - } - } catch (e) { - debugPrint('FFI setVolume failed, falling back to Platform Channel: $e'); - return _api.setVolume(VolumeMessage(playerId: playerId, volume: volume)); + final int result = _ffiApi.setVolume(playerId, volume); + if (result != 0) { + throw Exception('FFI setVolume failed with code: $result'); } } @@ -184,48 +127,36 @@ class VideoPlayerTizen extends VideoPlayerPlatform { Future setPlaybackSpeed(int playerId, double speed) async { // Use FFI for setPlaybackSpeed (synchronous call) assert(speed > 0); - try { - final int result = _ffiApi.setPlaybackSpeed(playerId, speed); - if (result != 0) { - throw Exception('FFI setPlaybackSpeed failed with code: $result'); - } - } catch (e) { - debugPrint( - 'FFI setPlaybackSpeed failed, falling back to Platform Channel: $e'); - return _api.setPlaybackSpeed( - PlaybackSpeedMessage(playerId: playerId, speed: speed), - ); + final int result = _ffiApi.setPlaybackSpeed(playerId, speed); + if (result != 0) { + throw Exception('FFI setPlaybackSpeed failed with code: $result'); } } @override Future seekTo(int playerId, Duration position) async { // Use FFI for seekTo (synchronous call) - try { - final int result = _ffiApi.seekTo(playerId, position.inMilliseconds); - if (result != 0) { - throw Exception('FFI seekTo failed with code: $result'); - } - } catch (e) { - debugPrint('FFI seekTo failed, falling back to Platform Channel: $e'); - return _api.seekTo( - PositionMessage(playerId: playerId, position: position.inMilliseconds), - ); + final int result = _ffiApi.seekTo(playerId, position.inMilliseconds); + if (result != 0) { + throw Exception('FFI seekTo failed with code: $result'); } } @override Future> getVideoTracks(int playerId) async { - final TrackMessage response = await _api.track( - TrackTypeMessage(playerId: playerId, trackType: TrackType.video.name), - ); + // Use FFI for getTrackInfo (synchronous call) + // C++ returns: {"playerId": , "tracks": [{...}, ...]} + final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'video'); + final Map responseJson = + jsonDecode(jsonResponse) as Map; + final List tracksJson = responseJson['tracks'] as List; final List videoTracks = []; - for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final int bitrate = trackMap['bitrate']! as int; - final int width = trackMap['width']! as int; - final int height = trackMap['height']! as int; + for (final dynamic trackMap in tracksJson) { + final int trackId = trackMap['trackId'] as int; + final int bitrate = trackMap['bitrate'] as int; + final int width = trackMap['width'] as int; + final int height = trackMap['height'] as int; videoTracks.add( VideoTrack( @@ -242,16 +173,19 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future> getAudioTracks(int playerId) async { - final TrackMessage response = await _api.track( - TrackTypeMessage(playerId: playerId, trackType: TrackType.audio.name), - ); + // Use FFI for getTrackInfo (synchronous call) + // C++ returns: {"playerId": , "tracks": [{...}, ...]} + final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'audio'); + final Map responseJson = + jsonDecode(jsonResponse) as Map; + final List tracksJson = responseJson['tracks'] as List; final List audioTracks = []; - for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String language = trackMap['language']! as String; - final int channel = trackMap['channel']! as int; - final int bitrate = trackMap['bitrate']! as int; + for (final dynamic trackMap in tracksJson) { + final int trackId = trackMap['trackId'] as int; + final String language = trackMap['language'] as String; + final int channel = trackMap['channel'] as int; + final int bitrate = trackMap['bitrate'] as int; audioTracks.add( AudioTrack( @@ -268,14 +202,17 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future> getTextTracks(int playerId) async { - final TrackMessage response = await _api.track( - TrackTypeMessage(playerId: playerId, trackType: TrackType.text.name), - ); + // Use FFI for getTrackInfo (synchronous call) + // C++ returns: {"playerId": , "tracks": [{...}, ...]} + final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'text'); + final Map responseJson = + jsonDecode(jsonResponse) as Map; + final List tracksJson = responseJson['tracks'] as List; final List textTracks = []; - for (final Map? trackMap in response.tracks) { - final int trackId = trackMap!['trackId']! as int; - final String language = trackMap['language']! as String; + for (final dynamic trackMap in tracksJson) { + final int trackId = trackMap['trackId'] as int; + final String language = trackMap['language'] as String; textTracks.add(TextTrack(trackId: trackId, language: language)); } @@ -284,57 +221,37 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } @override - Future setTrackSelection(int playerId, Track track) { - return _api.setTrackSelection( - SelectedTracksMessage( - playerId: playerId, - trackId: track.trackId, - trackType: track.trackType.name, - ), + Future setTrackSelection(int playerId, Track track) async { + // Use FFI for setTrackSelection (synchronous call) + final int result = _ffiApi.setTrackSelection( + playerId, + track.trackId, + track.trackType.name, ); + if (result != 0) { + throw Exception('FFI setTrackSelection failed with code: $result'); + } + return true; } @override Future getDuration(int playerId) async { // Use FFI for getDuration (synchronous call) - try { - final DurationMessage message = _ffiApi.duration(playerId); - return DurationRange( - Duration(milliseconds: message.durationRange?[0] ?? 0), - Duration(milliseconds: message.durationRange?[1] ?? 0), - ); - } catch (e) { - debugPrint( - 'FFI getDuration failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - final DurationMessage message = await _api.duration( - PlayerMessage(playerId: playerId), - ); - return DurationRange( - Duration(milliseconds: message.durationRange?[0] ?? 0), - Duration(milliseconds: message.durationRange?[1] ?? 0), - ); - } + final DurationMessage message = _ffiApi.duration(playerId); + return DurationRange( + Duration(milliseconds: message.durationRange?[0] ?? 0), + Duration(milliseconds: message.durationRange?[1] ?? 0), + ); } @override Future getPosition(int playerId) async { // Use FFI for getPosition (synchronous call) - try { - final int positionMs = _ffiApi.getPosition(playerId); - if (positionMs < 0) { - throw Exception('FFI getPosition failed with code: $positionMs'); - } - return Duration(milliseconds: positionMs); - } catch (e) { - debugPrint( - 'FFI getPosition failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - final PositionMessage response = await _api.position( - PlayerMessage(playerId: playerId), - ); - return Duration(milliseconds: response.position); + final int positionMs = _ffiApi.getPosition(playerId); + if (positionMs < 0) { + throw Exception('FFI getPosition failed with code: $positionMs'); } + return Duration(milliseconds: positionMs); } @override @@ -399,10 +316,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } @override - Future setMixWithOthers(bool mixWithOthers) { - return _api.setMixWithOthers( - MixWithOthersMessage(mixWithOthers: mixWithOthers), - ); + Future setMixWithOthers(bool mixWithOthers) async { + // Use FFI for setMixWithOthers (synchronous call) + final int result = _ffiApi.setMixWithOthers(mixWithOthers); + if (result != 0) { + throw Exception('FFI setMixWithOthers failed with code: $result'); + } } @override @@ -414,40 +333,19 @@ class VideoPlayerTizen extends VideoPlayerPlatform { int height, ) async { // Use FFI for setDisplayGeometry (synchronous call) - try { - final int result = - _ffiApi.setDisplayGeometry(playerId, x, y, width, height); - if (result != 0) { - throw Exception('FFI setDisplayGeometry failed with code: $result'); - } - } catch (e) { - debugPrint( - 'FFI setDisplayGeometry failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - return _api.setDisplayGeometry( - GeometryMessage( - playerId: playerId, - x: x, - y: y, - width: width, - height: height, - ), - ); + final int result = + _ffiApi.setDisplayGeometry(playerId, x, y, width, height); + if (result != 0) { + throw Exception('FFI setDisplayGeometry failed with code: $result'); } } @override Future suspend(int playerId) async { // Use FFI for suspend (synchronous call) - try { - final int result = _ffiApi.suspend(playerId); - if (result != 0) { - throw Exception('FFI suspend failed with code: $result'); - } - } catch (e) { - debugPrint('FFI suspend failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - return _api.suspend(playerId); + final int result = _ffiApi.suspend(playerId); + if (result != 0) { + throw Exception('FFI suspend failed with code: $result'); } } @@ -458,99 +356,63 @@ class VideoPlayerTizen extends VideoPlayerPlatform { int resumeTime = -1, }) async { // Use FFI for restore (synchronous call) - try { - // Build JSON string from dataSource (same pattern as create) - String? createMessageJson; - if (dataSource != null) { - final Map jsonMap = {}; - - switch (dataSource.sourceType) { - case DataSourceType.asset: - if (dataSource.asset != null && dataSource.asset!.isNotEmpty) { - jsonMap['asset'] = dataSource.asset; - } - if (dataSource.package != null && dataSource.package!.isNotEmpty) { - jsonMap['packageName'] = dataSource.package; - } - case DataSourceType.network: - if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { - jsonMap['uri'] = dataSource.uri; - } - if (dataSource.formatHint != null) { - jsonMap['formatHint'] = - _videoFormatStringMap[dataSource.formatHint]; - } - if (dataSource.httpHeaders.isNotEmpty) { - jsonMap['httpHeaders'] = dataSource.httpHeaders; - } - if (dataSource.drmConfigs != null) { - jsonMap['drmConfigs'] = dataSource.drmConfigs!.toMap(); - } - if (dataSource.playerOptions != null && - dataSource.playerOptions!.isNotEmpty) { - jsonMap['playerOptions'] = dataSource.playerOptions; - } - case DataSourceType.file: - case DataSourceType.contentUri: - if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { - jsonMap['uri'] = dataSource.uri; - } - } - - createMessageJson = jsonEncode(jsonMap); - } + // Build JSON string from dataSource (same pattern as create) + String? createMessageJson; + if (dataSource != null) { + final Map jsonMap = {}; - final int result = - _ffiApi.restore(playerId, createMessageJson, resumeTime); - if (result != 0) { - // FFI restore failed, but don't throw - just log and return - // The player may still be in a valid state - return; - } - } catch (e) { - debugPrint('FFI restore failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - final CreateMessage message = CreateMessage(); - - if (dataSource != null) { - switch (dataSource.sourceType) { - case DataSourceType.asset: - message.asset = dataSource.asset; - message.packageName = dataSource.package; - case DataSourceType.network: - message.uri = dataSource.uri; - message.formatHint = _videoFormatStringMap[dataSource.formatHint]; - message.httpHeaders = dataSource.httpHeaders; - message.drmConfigs = dataSource.drmConfigs?.toMap(); - message.playerOptions = dataSource.playerOptions; - case DataSourceType.file: - message.uri = dataSource.uri; - case DataSourceType.contentUri: - message.uri = dataSource.uri; - } + switch (dataSource.sourceType) { + case DataSourceType.asset: + if (dataSource.asset != null && dataSource.asset!.isNotEmpty) { + jsonMap['asset'] = dataSource.asset; + } + if (dataSource.package != null && dataSource.package!.isNotEmpty) { + jsonMap['packageName'] = dataSource.package; + } + case DataSourceType.network: + if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { + jsonMap['uri'] = dataSource.uri; + } + if (dataSource.formatHint != null) { + jsonMap['formatHint'] = + _videoFormatStringMap[dataSource.formatHint]; + } + if (dataSource.httpHeaders.isNotEmpty) { + jsonMap['httpHeaders'] = dataSource.httpHeaders; + } + if (dataSource.drmConfigs != null) { + jsonMap['drmConfigs'] = dataSource.drmConfigs!.toMap(); + } + if (dataSource.playerOptions != null && + dataSource.playerOptions!.isNotEmpty) { + jsonMap['playerOptions'] = dataSource.playerOptions; + } + case DataSourceType.file: + case DataSourceType.contentUri: + if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { + jsonMap['uri'] = dataSource.uri; + } } - return _api.restore(playerId, message, resumeTime); + createMessageJson = jsonEncode(jsonMap); + } + + final int result = _ffiApi.restore(playerId, createMessageJson, resumeTime); + if (result != 0) { + // FFI restore failed, but don't throw - just return + // The player may still be in a valid state + return; } } @override Future setDisplayRotate(int playerId, DisplayRotation rotation) async { // Use FFI for setDisplayRotate (synchronous call) - try { - final int result = _ffiApi.setDisplayRotate(playerId, rotation.index); - if (result != 0) { - throw Exception('FFI setDisplayRotate failed with code: $result'); - } - return true; - } catch (e) { - debugPrint( - 'FFI setDisplayRotate failed, falling back to Platform Channel: $e'); - // Fallback to Platform Channel if FFI fails - return _api.setDisplayRotate( - RotationMessage(playerId: playerId, rotation: rotation.index), - ); + final int result = _ffiApi.setDisplayRotate(playerId, rotation.index); + if (result != 0) { + throw Exception('FFI setDisplayRotate failed with code: $result'); } + return true; } EventChannel _eventChannelFor(int playerId) { diff --git a/packages/video_player_videohole/tizen/src/drm_manager.cc b/packages/video_player_videohole/tizen/src/drm_manager.cc index 3547b6cbd..56af62eac 100644 --- a/packages/video_player_videohole/tizen/src/drm_manager.cc +++ b/packages/video_player_videohole/tizen/src/drm_manager.cc @@ -116,7 +116,7 @@ bool DrmManager::SetChallenge(const std::string &media_url, return DM_ERROR_NONE == SetChallenge(media_url); } -void DrmManager::ReleaseDrmSession() { +void DrmManager::StopDrmSession() { if (drm_session_ == nullptr) { LOG_ERROR("[DrmManager] Already released."); return; @@ -138,8 +138,15 @@ void DrmManager::ReleaseDrmSession() { LOG_ERROR("[DrmManager] Fail to set finalize to drm session: %s", get_error_message(ret)); } +} + +void DrmManager::ReleaseDrmSession() { + if (drm_session_ == nullptr) { + LOG_ERROR("[DrmManager] Already released."); + return; + } - ret = DMGRReleaseDRMSession(drm_session_); + int ret = DMGRReleaseDRMSession(drm_session_); if (ret != DM_ERROR_NONE) { LOG_ERROR("[DrmManager] Fail to release drm session: %s", get_error_message(ret)); diff --git a/packages/video_player_videohole/tizen/src/drm_manager.h b/packages/video_player_videohole/tizen/src/drm_manager.h index 3c820a0a0..5881e54b6 100644 --- a/packages/video_player_videohole/tizen/src/drm_manager.h +++ b/packages/video_player_videohole/tizen/src/drm_manager.h @@ -34,6 +34,7 @@ class DrmManager { unsigned char *pssh_data, void *user_data); int UpdatePsshData(const void *data, int length); void ReleaseDrmSession(); + void StopDrmSession(); private: struct DataForLicenseProcess { diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 98962e574..e0607e230 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -48,6 +48,9 @@ MediaPlayer::MediaPlayer(flutter::BinaryMessenger *messenger, MediaPlayer::~MediaPlayer() { if (player_) { + if (drm_manager_) { + drm_manager_->StopDrmSession(); + } player_stop(player_); player_unprepare(player_); player_unset_buffering_cb(player_); @@ -219,7 +222,9 @@ bool MediaPlayer::Play() { player_state_e state = PLAYER_STATE_NONE; int ret = player_get_state(player_, &state); if (ret != PLAYER_ERROR_NONE) { - LOG_ERROR("[MediaPlayer] Unable to get player state."); + LOG_ERROR("[MediaPlayer] Unable to get player state: %s.", + get_error_message(ret)); + return false; } if (state == PLAYER_STATE_NONE || state == PLAYER_STATE_IDLE) { LOG_ERROR("[MediaPlayer] Player not ready."); @@ -473,7 +478,9 @@ flutter::EncodableList MediaPlayer::GetTrackInfo(std::string track_type) { get_error_message(ret)); return {}; } + if (track_count <= 0) { + LOG_INFO("[MediaPlayer] No tracks found for type=%d", type); return {}; } @@ -680,6 +687,10 @@ bool MediaPlayer::StopAndDestroy() { return true; } + if (drm_manager_) { + drm_manager_->StopDrmSession(); + } + if (player_stop(player_) != PLAYER_ERROR_NONE) { LOG_ERROR("[MediaPlayer] Player fail to stop."); return false; @@ -730,6 +741,19 @@ bool MediaPlayer::Suspend() { "[MediaPlayer] Saved current player state: %d, playing time: %llu ms", pre_state_, pre_playing_time_); + // For DRM content, always do full destroy/recreate on suspend/restore + // to avoid player_start() timeout issues with invalid display surface + if (drm_manager_ != nullptr) { + LOG_INFO( + "[MediaPlayer] DRM content detected, doing full destroy on suspend"); + if (!StopAndDestroy()) { + LOG_ERROR("[MediaPlayer] DRM content StopAndDestroy fail."); + return false; + } + LOG_INFO("[MediaPlayer] DRM content suspend done successfully."); + return true; + } + if (IsLive()) { pre_playing_time_ = 0; if (!StopAndDestroy()) { diff --git a/packages/video_player_videohole/tizen/src/messages.cc b/packages/video_player_videohole/tizen/src/messages.cc index 486eacf43..5e1eb0a9c 100644 --- a/packages/video_player_videohole/tizen/src/messages.cc +++ b/packages/video_player_videohole/tizen/src/messages.cc @@ -744,10 +744,13 @@ const flutter::StandardMessageCodec& VideoPlayerVideoholeApi::GetCodec() { &VideoPlayerVideoholeApiCodecSerializer::GetInstance()); } -// Sets up an instance of `VideoPlayerVideoholeApi` to handle messages through -// the `binary_messenger`. +// VideoPlayerVideoholeApi::SetUp() removed - all methods migrated to FFI +// This function is no longer needed void VideoPlayerVideoholeApi::SetUp(flutter::BinaryMessenger* binary_messenger, VideoPlayerVideoholeApi* api) { + // No-op: all methods migrated to FFI + (void)binary_messenger; + (void)api; { auto channel = std::make_unique>( binary_messenger, diff --git a/packages/video_player_videohole/tizen/src/messages.h b/packages/video_player_videohole/tizen/src/messages.h index 13435e6aa..e94dcb379 100644 --- a/packages/video_player_videohole/tizen/src/messages.h +++ b/packages/video_player_videohole/tizen/src/messages.h @@ -458,11 +458,83 @@ int ffi_initialize(); // FFI create - returns player_id or -1 on error // Parameters: create_message_json - JSON string containing all create parameters -// Format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} // Returns: int64_t player_id (negative value indicates error) int64_t ffi_create(const char* create_message_json); +// FFI dispose - releases player resources +// Returns: 0 on success, -1 on error +int ffi_dispose(int64_t player_id); + +// FFI play - starts or resumes playback +// Returns: 0 on success, -1 on error +int ffi_play(int64_t player_id); + +// FFI pause - pauses playback +// Returns: 0 on success, -1 on error +int ffi_pause(int64_t player_id); + +// FFI seek_to - seeks to a specific position (in milliseconds) +// Returns: 0 on success, -1 on error +int ffi_seek_to(int64_t player_id, int64_t position_ms); + +// FFI get_position - gets current playback position in milliseconds +// Returns: position in milliseconds (>= 0) on success, -1 on error +int64_t ffi_get_position(int64_t player_id); + +// FFI get_duration - gets video duration range in milliseconds +// Returns: JSON string with start and end values, or "-1" on error +// Note: Returns a malloc-allocated string that the caller must free +const char* ffi_get_duration(int64_t player_id); + +// FFI set_volume - sets playback volume (0.0 to 1.0) +// Returns: 0 on success, -1 on error +int ffi_set_volume(int64_t player_id, double volume); + +// FFI set_playback_speed - sets playback speed +// Returns: 0 on success, -1 on error +int ffi_set_playback_speed(int64_t player_id, double speed); + +// FFI set_looping - enables or disables looping +// Returns: 0 on success, -1 on error +int ffi_set_looping(int64_t player_id, bool is_looping); + +// FFI get_track_info - gets track information for a specific track type +// Returns: JSON string of track info on success, nullptr on error +// Note: Returns a malloc-allocated string that the caller must free +const char* ffi_get_track_info(int64_t player_id, const char* track_type); + +// FFI set_track_selection - sets the selected track +// Returns: 0 on success, -1 on error +int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type); + +// FFI set_display_geometry - sets the display geometry (ROI) +// Returns: 0 on success, -1 on error +int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height); + +// FFI set_display_rotate - sets display rotation +// Returns: 0 on success, -1 on error +int ffi_set_display_rotate(int64_t player_id, int32_t rotation); + +// FFI suspend - suspends the player +// Returns: 0 on success, -1 on error +int ffi_suspend(int64_t player_id); + +// FFI restore - restores a suspended player +// Returns: 0 on success, -1 on error +int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resume_time); + +// FFI set_activate - activates the player +// Returns: 0 on success, -1 on error +int ffi_set_activate(int64_t player_id); + +// FFI set_deactivate - deactivates the player +// Returns: 0 on success, -1 on error +int ffi_set_deactivate(int64_t player_id); + +// FFI set_mix_with_others - sets whether to mix audio with other players +// Returns: 0 on success, -1 on error +int ffi_set_mix_with_others(bool mix_with_others); + #ifdef __cplusplus } // extern "C" #endif diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 50e04d084..84c278980 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -20,14 +20,12 @@ #include #include "media_player.h" -#include "messages.h" #include "video_player.h" #include "video_player_options.h" namespace video_player_videohole_tizen { -class VideoPlayerTizenPlugin : public flutter::Plugin, - public VideoPlayerVideoholeApi { +class VideoPlayerTizenPlugin : public flutter::Plugin { public: static void RegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar_ref, @@ -40,33 +38,33 @@ class VideoPlayerTizenPlugin : public flutter::Plugin, flutter::PluginRegistrar *plugin_registrar); virtual ~VideoPlayerTizenPlugin(); - std::optional Initialize() override; - ErrorOr Create(const CreateMessage &msg) override; - std::optional Dispose(const PlayerMessage &msg) override; - ErrorOr Duration(const PlayerMessage &msg) override; - std::optional SetLooping(const LoopingMessage &msg) override; - std::optional SetVolume(const VolumeMessage &msg) override; + std::optional Initialize(); + ErrorOr Create(const CreateMessage &msg); + std::optional Dispose(const PlayerMessage &msg); + ErrorOr Duration(const PlayerMessage &msg); + std::optional SetLooping(const LoopingMessage &msg); + std::optional SetVolume(const VolumeMessage &msg); std::optional SetPlaybackSpeed( - const PlaybackSpeedMessage &msg) override; - ErrorOr Track(const TrackTypeMessage &msg) override; - ErrorOr SetTrackSelection(const SelectedTracksMessage &msg) override; - std::optional Play(const PlayerMessage &msg) override; - ErrorOr SetDeactivate(const PlayerMessage &msg) override; - ErrorOr SetActivate(const PlayerMessage &msg) override; - ErrorOr Position(const PlayerMessage &msg) override; + const PlaybackSpeedMessage &msg); + ErrorOr Track(const TrackTypeMessage &msg); + ErrorOr SetTrackSelection(const SelectedTracksMessage &msg); + std::optional Play(const PlayerMessage &msg); + ErrorOr SetDeactivate(const PlayerMessage &msg); + ErrorOr SetActivate(const PlayerMessage &msg); + ErrorOr Position(const PlayerMessage &msg); void SeekTo( const PositionMessage &msg, - std::function reply)> result) override; - std::optional Pause(const PlayerMessage &msg) override; + std::function reply)> result); + std::optional Pause(const PlayerMessage &msg); std::optional SetMixWithOthers( - const MixWithOthersMessage &msg) override; + const MixWithOthersMessage &msg); std::optional SetDisplayGeometry( - const GeometryMessage &msg) override; - std::optional Suspend(int64_t player_id) override; + const GeometryMessage &msg); + std::optional Suspend(int64_t player_id); std::optional Restore(int64_t player_id, const CreateMessage *msg, - int64_t resume_time) override; - ErrorOr SetDisplayRotate(const RotationMessage &msg) override; + int64_t resume_time); + ErrorOr SetDisplayRotate(const RotationMessage &msg); static VideoPlayer *FindPlayerById(int64_t player_id) { auto iter = players_.find(player_id); @@ -105,7 +103,7 @@ VideoPlayerTizenPlugin::VideoPlayerTizenPlugin( flutter::PluginRegistrar *plugin_registrar) : registrar_ref_(registrar_ref), plugin_registrar_(plugin_registrar) { instance_ = this; // Set singleton instance for FFI access - VideoPlayerVideoholeApi::SetUp(plugin_registrar->messenger(), this); + // VideoPlayerVideoholeApi removed - all methods migrated to FFI } VideoPlayerTizenPlugin::~VideoPlayerTizenPlugin() { DisposeAllPlayers(); } @@ -848,47 +846,6 @@ int ffi_set_looping(int64_t player_id, bool is_looping) { return 0; // Success } -// FFI get_track_info function - gets track information for a specific track type -// Returns: JSON string of track info on success, nullptr on error -// Note: Returns a malloc-allocated string that the caller must free -const char* ffi_get_track_info(int64_t player_id, const char* track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return nullptr; - } - - auto result = plugin->Track( - video_player_videohole_tizen::TrackTypeMessage(player_id, std::string(track_type))); - if (result.has_error()) { - return nullptr; - } - - // Convert TrackMessage to JSON string - // Use strdup to allocate memory that persists after this function returns - // The Dart caller is responsible for freeing this memory - std::string track_info_json = "{\"playerId\":" + std::to_string(result.value().player_id()) + - ",\"tracks\":[]}"; - return strdup(track_info_json.c_str()); -} - -// FFI set_track_selection function - sets the selected track -// Returns: 0 on success, -1 on error -int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return -1; // Plugin not initialized - } - - auto result = plugin->SetTrackSelection( - video_player_videohole_tizen::SelectedTracksMessage(player_id, track_id, std::string(track_type))); - if (result.has_error()) { - return -1; - } - return result.value() ? 0 : -1; -} - // FFI set_display_geometry function - sets the display geometry (ROI) // Returns: 0 on success, -1 on error int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height) { @@ -965,6 +922,135 @@ int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resu return 0; // Success } +// FFI set_activate function - activates the player +// Returns: 0 on success, -1 on error +int ffi_set_activate(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetActivate( + video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_error()) { + return -1; + } + return result.value() ? 0 : -1; +} + +// FFI set_deactivate function - deactivates the player +// Returns: 0 on success, -1 on error +int ffi_set_deactivate(int64_t player_id) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetDeactivate( + video_player_videohole_tizen::PlayerMessage(player_id)); + if (result.has_error()) { + return -1; + } + return result.value() ? 0 : -1; +} + +// FFI get_track_info function - gets track information for a specific track type +// Returns: JSON string of track info on success, nullptr on error +// Format: {"playerId": , "tracks": [{"trackId": , ...}, ...]} +// Note: Returns a malloc-allocated string that the caller must free +const char* ffi_get_track_info(int64_t player_id, const char* track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return nullptr; + } + + auto result = plugin->Track( + video_player_videohole_tizen::TrackTypeMessage(player_id, std::string(track_type))); + if (result.has_error()) { + return nullptr; + } + + // Convert TrackMessage to JSON string + // Use strdup to allocate memory that persists after this function returns + // The Dart caller is responsible for freeing this memory + std::string track_info_json = "{\"playerId\":" + std::to_string(result.value().player_id()) + + ",\"tracks\":["; + + const auto& tracks = result.value().tracks(); + for (size_t i = 0; i < tracks.size(); ++i) { + if (i > 0) track_info_json += ","; + + const auto& track_map = std::get(tracks[i]); + track_info_json += "{"; + + bool first = true; + for (const auto& [key, value] : track_map) { + if (!first) track_info_json += ","; + first = false; + + const std::string* key_str = std::get_if(&key); + if (!key_str) continue; + + track_info_json += "\"" + *key_str + "\":"; + + if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += "\"" + std::get(value) + "\""; + } else if (std::holds_alternative(value)) { + track_info_json += std::get(value) ? "true" : "false"; + } + } + + track_info_json += "}"; + } + + track_info_json += "]}"; + return strdup(track_info_json.c_str()); +} + +// FFI set_track_selection function - sets the selected track +// Returns: 0 on success, -1 on error +int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetTrackSelection( + video_player_videohole_tizen::SelectedTracksMessage(player_id, track_id, std::string(track_type))); + if (result.has_error()) { + return -1; + } + return result.value() ? 0 : -1; +} + +// FFI set_mix_with_others function - sets whether to mix audio with other players +// Returns: 0 on success, -1 on error +int ffi_set_mix_with_others(bool mix_with_others) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; // Plugin not initialized + } + + auto result = plugin->SetMixWithOthers( + video_player_videohole_tizen::MixWithOthersMessage(mix_with_others)); + if (result.has_value()) { + // Error occurred + return -1; + } + return 0; // Success +} + } // extern "C" void VideoPlayerTizenPluginRegisterWithRegistrar( From 643a04dfd7df2db4c83f1fe2fc782bf3efd2cf94 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Tue, 21 Jul 2026 09:49:27 +0800 Subject: [PATCH 04/18] code format --- .../lib/src/video_player_tizen.dart | 23 +- .../tizen/src/messages.h | 14 +- .../tizen/src/video_player_tizen_plugin.cc | 229 ++++++++++-------- 3 files changed, 150 insertions(+), 116 deletions(-) diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index f7db1dbd0..6e622da3b 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -153,10 +153,11 @@ class VideoPlayerTizen extends VideoPlayerPlatform { final List videoTracks = []; for (final dynamic trackMap in tracksJson) { - final int trackId = trackMap['trackId'] as int; - final int bitrate = trackMap['bitrate'] as int; - final int width = trackMap['width'] as int; - final int height = trackMap['height'] as int; + final Map track = trackMap as Map; + final int trackId = track['trackId'] as int; + final int bitrate = track['bitrate'] as int; + final int width = track['width'] as int; + final int height = track['height'] as int; videoTracks.add( VideoTrack( @@ -182,10 +183,11 @@ class VideoPlayerTizen extends VideoPlayerPlatform { final List audioTracks = []; for (final dynamic trackMap in tracksJson) { - final int trackId = trackMap['trackId'] as int; - final String language = trackMap['language'] as String; - final int channel = trackMap['channel'] as int; - final int bitrate = trackMap['bitrate'] as int; + final Map track = trackMap as Map; + final int trackId = track['trackId'] as int; + final String language = track['language'] as String; + final int channel = track['channel'] as int; + final int bitrate = track['bitrate'] as int; audioTracks.add( AudioTrack( @@ -211,8 +213,9 @@ class VideoPlayerTizen extends VideoPlayerPlatform { final List textTracks = []; for (final dynamic trackMap in tracksJson) { - final int trackId = trackMap['trackId'] as int; - final String language = trackMap['language'] as String; + final Map track = trackMap as Map; + final int trackId = track['trackId'] as int; + final String language = track['language'] as String; textTracks.add(TextTrack(trackId: trackId, language: language)); } diff --git a/packages/video_player_videohole/tizen/src/messages.h b/packages/video_player_videohole/tizen/src/messages.h index e94dcb379..c1fa8fe6c 100644 --- a/packages/video_player_videohole/tizen/src/messages.h +++ b/packages/video_player_videohole/tizen/src/messages.h @@ -456,9 +456,8 @@ extern "C" { // FFI initialization int ffi_initialize(); -// FFI create - returns player_id or -1 on error -// Parameters: create_message_json - JSON string containing all create parameters -// Returns: int64_t player_id (negative value indicates error) +// FFI create - returns player_id or -1 on error. +// Parameters: JSON string containing all create parameters. int64_t ffi_create(const char* create_message_json); // FFI dispose - releases player resources @@ -505,11 +504,13 @@ const char* ffi_get_track_info(int64_t player_id, const char* track_type); // FFI set_track_selection - sets the selected track // Returns: 0 on success, -1 on error -int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type); +int ffi_set_track_selection(int64_t player_id, int64_t track_id, + const char* track_type); // FFI set_display_geometry - sets the display geometry (ROI) // Returns: 0 on success, -1 on error -int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height); +int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, + int32_t width, int32_t height); // FFI set_display_rotate - sets display rotation // Returns: 0 on success, -1 on error @@ -521,7 +522,8 @@ int ffi_suspend(int64_t player_id); // FFI restore - restores a suspended player // Returns: 0 on success, -1 on error -int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resume_time); +int ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time); // FFI set_activate - activates the player // Returns: 0 on success, -1 on error diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 84c278980..52f29409a 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -14,10 +14,10 @@ #include #include #include +#include #include #include #include -#include #include "media_player.h" #include "video_player.h" @@ -44,22 +44,18 @@ class VideoPlayerTizenPlugin : public flutter::Plugin { ErrorOr Duration(const PlayerMessage &msg); std::optional SetLooping(const LoopingMessage &msg); std::optional SetVolume(const VolumeMessage &msg); - std::optional SetPlaybackSpeed( - const PlaybackSpeedMessage &msg); + std::optional SetPlaybackSpeed(const PlaybackSpeedMessage &msg); ErrorOr Track(const TrackTypeMessage &msg); ErrorOr SetTrackSelection(const SelectedTracksMessage &msg); std::optional Play(const PlayerMessage &msg); ErrorOr SetDeactivate(const PlayerMessage &msg); ErrorOr SetActivate(const PlayerMessage &msg); ErrorOr Position(const PlayerMessage &msg); - void SeekTo( - const PositionMessage &msg, - std::function reply)> result); + void SeekTo(const PositionMessage &msg, + std::function reply)> result); std::optional Pause(const PlayerMessage &msg); - std::optional SetMixWithOthers( - const MixWithOthersMessage &msg); - std::optional SetDisplayGeometry( - const GeometryMessage &msg); + std::optional SetMixWithOthers(const MixWithOthersMessage &msg); + std::optional SetDisplayGeometry(const GeometryMessage &msg); std::optional Suspend(int64_t player_id); std::optional Restore(int64_t player_id, const CreateMessage *msg, @@ -470,65 +466,69 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { // Helper function to extract a string value from JSON by key // Returns true if the key was found and value was extracted -static bool ExtractStringValue(const std::string &json_str, - const std::string &key, - std::string &out_value) { +static bool ExtractStringValue(const std::string &json_str, + const std::string &key, std::string &out_value) { std::string search_key = "\"" + key + "\""; size_t pos = json_str.find(search_key); if (pos == std::string::npos) return false; - + pos = json_str.find(':', pos); if (pos == std::string::npos) return false; - + pos++; - while (pos < json_str.length() && (isspace(json_str[pos]) || json_str[pos] == ':')) pos++; + while (pos < json_str.length() && + (isspace(json_str[pos]) || json_str[pos] == ':')) + pos++; if (pos >= json_str.length() || json_str[pos] != '"') return false; - + pos++; // skip opening quote size_t end = pos; while (end < json_str.length() && json_str[end] != '"') end++; - + out_value = json_str.substr(pos, end - pos); return true; } -// Helper function to extract a nested object from JSON by key -// Returns the nested object JSON string (including braces) or empty string if not found -static std::string ExtractObjectValue(const std::string &json_str, - const std::string &key) { +// Helper function to extract a nested object from JSON by key. +// Returns the nested object JSON string or empty string if not found. +static std::string ExtractObjectValue(const std::string &json_str, + const std::string &key) { std::string search_key = "\"" + key + "\""; size_t pos = json_str.find(search_key); if (pos == std::string::npos) return ""; - + pos = json_str.find(':', pos); if (pos == std::string::npos) return ""; - + pos++; while (pos < json_str.length() && isspace(json_str[pos])) pos++; if (pos >= json_str.length() || json_str[pos] != '{') return ""; - + int brace_count = 1; size_t start = pos; pos++; while (pos < json_str.length() && brace_count > 0) { - if (json_str[pos] == '{') brace_count++; - else if (json_str[pos] == '}') brace_count--; + if (json_str[pos] == '{') + brace_count++; + else if (json_str[pos] == '}') + brace_count--; pos++; } return json_str.substr(start, pos - start); } // Unified function to parse CreateMessage from JSON string -// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} +// JSON format: +// {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} static video_player_videohole_tizen::CreateMessage ParseCreateMessage( const std::string &json_str) { video_player_videohole_tizen::CreateMessage msg; - + if (json_str.empty() || json_str == "{}") { return msg; } - + // Extract string fields using helper function std::string value; if (ExtractStringValue(json_str, "uri", value)) { @@ -543,10 +543,10 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( if (ExtractStringValue(json_str, "formatHint", value)) { msg.set_format_hint(value); } - + // Extract nested object fields using helper function std::string nested_json; - + // httpHeaders nested_json = ExtractObjectValue(json_str, "httpHeaders"); if (!nested_json.empty()) { @@ -555,7 +555,7 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( msg.set_http_headers(headers); } } - + // playerOptions nested_json = ExtractObjectValue(json_str, "playerOptions"); if (!nested_json.empty()) { @@ -564,50 +564,60 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( msg.set_player_options(options); } } - + // drmConfigs (special handling for drmType and licenseServerUrl) nested_json = ExtractObjectValue(json_str, "drmConfigs"); if (!nested_json.empty()) { int64_t drm_type = 0; std::string license_url; - + // Extract drmType (number value) size_t drm_pos = nested_json.find("\"drmType\""); if (drm_pos != std::string::npos) { drm_pos = nested_json.find(':', drm_pos); if (drm_pos != std::string::npos) { drm_pos++; - while (drm_pos < nested_json.length() && (isspace(nested_json[drm_pos]) || nested_json[drm_pos] == ':')) drm_pos++; + while (drm_pos < nested_json.length() && + (isspace(nested_json[drm_pos]) || nested_json[drm_pos] == ':')) + drm_pos++; size_t end = drm_pos; - while (end < nested_json.length() && nested_json[end] != ',' && nested_json[end] != '}' && nested_json[end] != '"') end++; + while (end < nested_json.length() && nested_json[end] != ',' && + nested_json[end] != '}' && nested_json[end] != '"') + end++; std::string val = nested_json.substr(drm_pos, end - drm_pos); - while (!val.empty() && (val.back() == '"' || isspace(val.back()))) val.pop_back(); + while (!val.empty() && (val.back() == '"' || isspace(val.back()))) + val.pop_back(); try { drm_type = std::stoll(val); } catch (...) { - if (val == "1") drm_type = 1; - else if (val == "2") drm_type = 2; + if (val == "1") + drm_type = 1; + else if (val == "2") + drm_type = 2; } } } - + // Extract licenseServerUrl using helper function ExtractStringValue(nested_json, "licenseServerUrl", license_url); - + flutter::EncodableMap drm_map; - drm_map[flutter::EncodableValue("drmType")] = flutter::EncodableValue(drm_type); + drm_map[flutter::EncodableValue("drmType")] = + flutter::EncodableValue(drm_type); if (!license_url.empty()) { - drm_map[flutter::EncodableValue("licenseServerUrl")] = flutter::EncodableValue(license_url); + drm_map[flutter::EncodableValue("licenseServerUrl")] = + flutter::EncodableValue(license_url); } msg.set_drm_configs(drm_map); } - + return msg; } // FFI create function - takes a single JSON string for all create parameters -// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} +// JSON format: +// {"uri":"...","asset":"...","packageName":"...","formatHint":"...", +// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}}. // Returns: player_id on success, -1 on error int64_t ffi_create(const char *create_message_json) { auto *plugin = @@ -620,7 +630,7 @@ int64_t ffi_create(const char *create_message_json) { if (create_message_json != nullptr && strlen(create_message_json) > 0) { msg = ParseCreateMessage(std::string(create_message_json)); } - + auto result = plugin->Create(msg); if (result.has_error()) { return -1; @@ -640,14 +650,16 @@ int ffi_dispose(int64_t player_id) { // Check if player exists before trying to dispose // This prevents crash when dispose is called multiple times - auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + auto player = + video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( + player_id); if (player == nullptr) { // Player already disposed or never existed - return success silently return 0; } - auto result = plugin->Dispose( - video_player_videohole_tizen::PlayerMessage(player_id)); + auto result = + plugin->Dispose(video_player_videohole_tizen::PlayerMessage(player_id)); if (result.has_value()) { // Error occurred return -1; @@ -657,7 +669,8 @@ int ffi_dispose(int64_t player_id) { // FFI play function - starts or resumes playback // Returns: 0 on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed player +// Note: Checks if player exists before calling to avoid crash on disposed +// player int ffi_play(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); @@ -666,7 +679,9 @@ int ffi_play(int64_t player_id) { } // Check if player exists before calling - avoid crash on disposed player - auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + auto player = + video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( + player_id); if (player == nullptr) { return -1; // Player already disposed or never existed } @@ -682,7 +697,8 @@ int ffi_play(int64_t player_id) { // FFI pause function - pauses playback // Returns: 0 on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed player +// Note: Checks if player exists before calling to avoid crash on disposed +// player int ffi_pause(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); @@ -691,7 +707,9 @@ int ffi_pause(int64_t player_id) { } // Check if player exists before calling - avoid crash on disposed player - auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + auto player = + video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( + player_id); if (player == nullptr) { return -1; // Player already disposed or never existed } @@ -716,8 +734,8 @@ int ffi_seek_to(int64_t player_id, int64_t position_ms) { return -1; // Plugin not initialized } - // Call SeekTo asynchronously - the result will be notified through event channel - // We don't block here to avoid freezing the UI thread + // Call SeekTo asynchronously - the result will be notified through event + // channel. We don't block here to avoid freezing the UI thread plugin->SeekTo( video_player_videohole_tizen::PositionMessage(player_id, position_ms), [](std::optional result) { @@ -734,7 +752,8 @@ int ffi_seek_to(int64_t player_id, int64_t position_ms) { // FFI get_position function - gets current playback position in milliseconds // Returns: position in milliseconds (>= 0) on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed player +// Note: Checks if player exists before calling to avoid crash on disposed +// player int64_t ffi_get_position(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); @@ -743,7 +762,9 @@ int64_t ffi_get_position(int64_t player_id) { } // Check if player exists before calling - avoid crash on disposed player - auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById(player_id); + auto player = + video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( + player_id); if (player == nullptr) { return -1; // Player already disposed or never existed } @@ -761,7 +782,7 @@ int64_t ffi_get_position(int64_t player_id) { // Format: {"start": , "end": } // For live streams, start may be non-zero (e.g., {"start": 1000, "end": 5000}) // Note: Returns a malloc-allocated string that the caller must free -const char* ffi_get_duration(int64_t player_id) { +const char *ffi_get_duration(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { @@ -773,18 +794,20 @@ const char* ffi_get_duration(int64_t player_id) { if (result.has_error()) { return strdup("-1"); } - + // Return both start and end of duration range as JSON // Use strdup to allocate memory that persists after this function returns // The Dart caller is responsible for freeing this memory - const auto& duration_range = result.value().duration_range(); + const auto &duration_range = result.value().duration_range(); std::string duration_json; if (duration_range && duration_range->size() >= 2) { - int64_t start = (*duration_range)[0].IsNull() ? 0 : - std::get((*duration_range)[0]); - int64_t end = (*duration_range)[1].IsNull() ? 0 : - std::get((*duration_range)[1]); - duration_json = "{\"start\":" + std::to_string(start) + + int64_t start = (*duration_range)[0].IsNull() + ? 0 + : std::get((*duration_range)[0]); + int64_t end = (*duration_range)[1].IsNull() + ? 0 + : std::get((*duration_range)[1]); + duration_json = "{\"start\":" + std::to_string(start) + ",\"end\":" + std::to_string(end) + "}"; } else { duration_json = "{\"start\":0,\"end\":0}"; @@ -848,15 +871,17 @@ int ffi_set_looping(int64_t player_id, bool is_looping) { // FFI set_display_geometry function - sets the display geometry (ROI) // Returns: 0 on success, -1 on error -int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height) { +int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, + int32_t width, int32_t height) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { return -1; // Plugin not initialized } - auto result = plugin->SetDisplayGeometry( - video_player_videohole_tizen::GeometryMessage(player_id, x, y, width, height)); + auto result = + plugin->SetDisplayGeometry(video_player_videohole_tizen::GeometryMessage( + player_id, x, y, width, height)); if (result.has_value()) { // Error occurred return -1; @@ -899,9 +924,10 @@ int ffi_suspend(int64_t player_id) { } // FFI restore function - restores a suspended player -// create_message_json: JSON string of CreateMessage or empty/null for using saved state -// Returns: 0 on success, -1 on error -int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resume_time) { +// create_message_json: JSON string of CreateMessage or empty/null for using +// saved state. Returns: 0 on success, -1 on error +int ffi_restore(int64_t player_id, const char *create_message_json, + int64_t resume_time) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { @@ -913,7 +939,7 @@ int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resu if (create_message_json != nullptr && strlen(create_message_json) > 0) { msg = ParseCreateMessage(std::string(create_message_json)); } - + auto result = plugin->Restore(player_id, &msg, resume_time); if (result.has_value()) { // Error occurred @@ -956,19 +982,19 @@ int ffi_set_deactivate(int64_t player_id) { return result.value() ? 0 : -1; } -// FFI get_track_info function - gets track information for a specific track type -// Returns: JSON string of track info on success, nullptr on error -// Format: {"playerId": , "tracks": [{"trackId": , ...}, ...]} -// Note: Returns a malloc-allocated string that the caller must free -const char* ffi_get_track_info(int64_t player_id, const char* track_type) { +// FFI get_track_info function - gets track information for a specific track +// type. Returns: JSON string of track info on success, nullptr on error. +// Format: {"playerId": , "tracks": [{"trackId": , ...}, ...]}. +// Note: Returns a malloc-allocated string that the caller must free. +const char *ffi_get_track_info(int64_t player_id, const char *track_type) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr || track_type == nullptr) { return nullptr; } - auto result = plugin->Track( - video_player_videohole_tizen::TrackTypeMessage(player_id, std::string(track_type))); + auto result = plugin->Track(video_player_videohole_tizen::TrackTypeMessage( + player_id, std::string(track_type))); if (result.has_error()) { return nullptr; } @@ -976,26 +1002,27 @@ const char* ffi_get_track_info(int64_t player_id, const char* track_type) { // Convert TrackMessage to JSON string // Use strdup to allocate memory that persists after this function returns // The Dart caller is responsible for freeing this memory - std::string track_info_json = "{\"playerId\":" + std::to_string(result.value().player_id()) + - ",\"tracks\":["; - - const auto& tracks = result.value().tracks(); + std::string track_info_json = + "{\"playerId\":" + std::to_string(result.value().player_id()) + + ",\"tracks\":["; + + const auto &tracks = result.value().tracks(); for (size_t i = 0; i < tracks.size(); ++i) { if (i > 0) track_info_json += ","; - - const auto& track_map = std::get(tracks[i]); + + const auto &track_map = std::get(tracks[i]); track_info_json += "{"; - + bool first = true; - for (const auto& [key, value] : track_map) { + for (const auto &[key, value] : track_map) { if (!first) track_info_json += ","; first = false; - - const std::string* key_str = std::get_if(&key); + + const std::string *key_str = std::get_if(&key); if (!key_str) continue; - + track_info_json += "\"" + *key_str + "\":"; - + if (std::holds_alternative(value)) { track_info_json += std::to_string(std::get(value)); } else if (std::holds_alternative(value)) { @@ -1008,17 +1035,18 @@ const char* ffi_get_track_info(int64_t player_id, const char* track_type) { track_info_json += std::get(value) ? "true" : "false"; } } - + track_info_json += "}"; } - + track_info_json += "]}"; return strdup(track_info_json.c_str()); } // FFI set_track_selection function - sets the selected track // Returns: 0 on success, -1 on error -int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* track_type) { +int ffi_set_track_selection(int64_t player_id, int64_t track_id, + const char *track_type) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr || track_type == nullptr) { @@ -1026,15 +1054,16 @@ int ffi_set_track_selection(int64_t player_id, int64_t track_id, const char* tra } auto result = plugin->SetTrackSelection( - video_player_videohole_tizen::SelectedTracksMessage(player_id, track_id, std::string(track_type))); + video_player_videohole_tizen::SelectedTracksMessage( + player_id, track_id, std::string(track_type))); if (result.has_error()) { return -1; } return result.value() ? 0 : -1; } -// FFI set_mix_with_others function - sets whether to mix audio with other players -// Returns: 0 on success, -1 on error +// FFI set_mix_with_others function - sets whether to mix audio with other +// players. Returns: 0 on success, -1 on error int ffi_set_mix_with_others(bool mix_with_others) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); From 1815a221deea16b4d30f9189214809e33e512315 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 22 Jul 2026 13:03:12 +0800 Subject: [PATCH 05/18] replace EventChannel with ffi --- .../lib/src/messages.g.dart | 126 ++++++++ .../lib/src/video_player_tizen.dart | 206 ++++++++---- .../lib/video_player_platform_interface.dart | 11 + .../tizen/src/media_player.cc | 48 ++- .../tizen/src/video_player.cc | 300 +++++++++++++----- .../tizen/src/video_player.h | 36 ++- .../tizen/src/video_player_tizen_plugin.cc | 78 ++++- 7 files changed, 655 insertions(+), 150 deletions(-) diff --git a/packages/video_player_videohole/lib/src/messages.g.dart b/packages/video_player_videohole/lib/src/messages.g.dart index 47ca219e1..7979e7798 100644 --- a/packages/video_player_videohole/lib/src/messages.g.dart +++ b/packages/video_player_videohole/lib/src/messages.g.dart @@ -4,6 +4,8 @@ import 'dart:async'; import 'dart:ffi' as ffi; +import 'dart:ffi' show NativeCallable; +import 'dart:isolate' show RawReceivePort, ReceivePort, SendPort; import 'package:ffi/ffi.dart' show calloc; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'dart:convert' show utf8, jsonEncode, jsonDecode; @@ -1608,3 +1610,127 @@ int ffiSetMixWithOthers(bool mixWithOthers) { } return bindings._ffiSetMixWithOthers(mixWithOthers); } + +// ===== FFI Event Port Section - Using Dart_PostCObject_DL ===== + +/// FFI initialize_api_dl function - initializes Dart API DL +/// This must be called before using Dart_PostCObject_DL +typedef _FFIInitializeApiDlNative = ffi.Int32 Function(ffi.Pointer); +typedef _FFIInitializeApiDlDart = int Function(ffi.Pointer); + +ffi.Pointer>? + _ffiInitializeApiDlPtr; +bool _apiDlInitialized = false; + +/// Initialize the Dart API DL for FFI event notifications +/// This must be called before registering the event port +void ffiInitializeApiDL() { + if (_apiDlInitialized) return; + + final lib = VideoPlayerFFIBindings.instance._lib; + if (lib == null) return; + + try { + _ffiInitializeApiDlPtr = + lib.lookup>( + 'ffi_initialize_api_dl'); + + if (_ffiInitializeApiDlPtr != null) { + // Pass NativeApi.initializeApiDLData to the native side + _ffiInitializeApiDlPtr! + .cast>() + .asFunction)>()( + ffi.NativeApi.initializeApiDLData); + _apiDlInitialized = true; + debugPrint('Dart API DL initialized successfully'); + } + } catch (e) { + debugPrint('Failed to initialize Dart API DL: $e'); + } +} + +/// Extension to get the native port number from RawReceivePort +extension RawReceivePortNativePort on RawReceivePort { + /// Returns the native port number that can be used with Dart_PostCObject_DL + int get nativePort => _rawReceivePortNativePort(this); +} + +/// Extension to get the native port number from ReceivePort +extension ReceivePortNativePort on ReceivePort { + /// Returns the native port number that can be used with Dart_PostCObject_DL + int get nativePort => _receivePortNativePort(this); +} + +// External function to get native port from RawReceivePort +// This uses the private _RawReceivePortImpl class internals +@pragma('vm:never-inline') +int _rawReceivePortNativePort(RawReceivePort port) { + // Access the sendPort's nativePort through the port's internal field + // RawReceivePort has a sendPort property that exposes nativePort + return port.sendPort.nativePort; +} + +// External function to get native port from ReceivePort +@pragma('vm:never-inline') +int _receivePortNativePort(ReceivePort port) { + // Access the sendPort's nativePort through the port's internal field + return port.sendPort.nativePort; +} + +/// FFI register_event_port function - registers Dart port for event notifications +/// The port is used with Dart_PostCObject_DL to send events to Dart isolate +typedef _FFIRegisterEventPortNative = ffi.Void Function(ffi.Int64); +typedef _FFIRegisterEventPortDart = void Function(int); + +/// FFI unregister_event_port function - unregisters the Dart port +typedef _FFIUnregisterEventPortNative = ffi.Void Function(); +typedef _FFIUnregisterEventPortDart = void Function(); + +// Global static variables for FFI event port bindings +ffi.Pointer>? + _ffiRegisterEventPortPtr; +ffi.Pointer>? + _ffiUnregisterEventPortPtr; +bool _eventPortLoaded = false; + +void _loadEventPortBindings(ffi.DynamicLibrary? lib) { + if (lib == null || _eventPortLoaded) return; + + try { + _ffiRegisterEventPortPtr = + lib.lookup>( + 'ffi_register_event_port'); + + _ffiUnregisterEventPortPtr = + lib.lookup>( + 'ffi_unregister_event_port'); + + _eventPortLoaded = true; + debugPrint('FFI event port bindings loaded successfully'); + } catch (e) { + debugPrint('Failed to load FFI event port bindings: $e'); + } +} + +/// Register FFI event port for event notifications using Dart_PostCObject_DL +/// This function is exported for use in video_player_tizen.dart +void ffiRegisterEventPort(int port) { + if (!_eventPortLoaded) { + _loadEventPortBindings(VideoPlayerFFIBindings.instance._lib); + } + if (_eventPortLoaded && _ffiRegisterEventPortPtr != null) { + _ffiRegisterEventPortPtr! + .cast>() + .asFunction()(port); + } +} + +/// Unregister FFI event port +/// This function is exported for use in video_player_tizen.dart +void ffiUnregisterEventPort() { + if (_eventPortLoaded && _ffiUnregisterEventPortPtr != null) { + _ffiUnregisterEventPortPtr! + .cast>() + .asFunction()(); + } +} diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index 6e622da3b..eb49992cd 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -5,8 +5,8 @@ import 'dart:async'; import 'dart:convert'; +import 'dart:isolate' show RawReceivePort, ReceivePort; -import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import '../video_player_platform_interface.dart'; @@ -15,6 +15,9 @@ import 'tracks.dart'; /// An implementation of [VideoPlayerPlatform] that uses FFI for all methods. class VideoPlayerTizen extends VideoPlayerPlatform { + /// Create a new VideoPlayerTizen instance. + VideoPlayerTizen() : super(); + final VideoPlayerFFIApi _ffiApi = VideoPlayerFFIApi(); @override @@ -28,6 +31,13 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future dispose(int playerId) async { + // Close the StreamController for this player + final StreamController? controller = + _eventControllers.remove(playerId); + if (controller != null && !controller.isClosed) { + await controller.close(); + } + // Use FFI for dispose (synchronous call) final int result = _ffiApi.dispose(playerId); // Don't throw on error - just return @@ -39,6 +49,10 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future create(DataSource dataSource) async { + // Ensure the event port is registered before creating the player + // This is important because events may be sent immediately after creation + _ensureEventPortRegistered(); + // Use FFI for create (synchronous call) int playerId; @@ -67,6 +81,45 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return playerId; } + /// Ensure the event port is registered before any events are sent + void _ensureEventPortRegistered() { + if (_eventPort == null) { + // Initialize Dart API DL before using Dart_PostCObject_DL + ffiInitializeApiDL(); + + _eventPort = RawReceivePort(); + + // Listen to FFI events and route them to the appropriate StreamController + _eventPort!.handler = (dynamic message) { + try { + // Message format from C++: [player_id, event_json_string] + if (message is List && message.length == 2) { + final int receivingPlayerId = message[0] as int; + final String eventJson = message[1] as String; + + // Parse JSON to Map + final Map eventMap = + jsonDecode(eventJson) as Map; + + // Route to the correct StreamController + final StreamController? controller = + _eventControllers[receivingPlayerId]; + if (controller != null && !controller.isClosed) { + controller.add(_parseVideoEventFromMap(eventMap)); + } + } + } catch (e, stackTrace) { + // Log error but don't crash + debugPrint('Error processing FFI event: $e\n$stackTrace'); + } + }; + + // Register the port with C++ side using FFI + ffiRegisterEventPort(_eventPort!.nativePort); + debugPrint('Event port registered: ${_eventPort!.nativePort}'); + } + } + @override Future setLooping(int playerId, bool looping) async { // Use FFI for setLooping (synchronous call) @@ -257,60 +310,105 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return Duration(milliseconds: positionMs); } + // Static RawReceivePort for FFI event notifications + static RawReceivePort? _eventPort; + + // Map of playerId to StreamController for broadcasting events + final Map> _eventControllers = + >{}; + @override Stream videoEventsFor(int playerId) { - return _eventChannelFor(playerId).receiveBroadcastStream().map(( - dynamic event, - ) { - final Map map = event as Map; - switch (map['event']) { - case 'initialized': - case 'restored': - final List? durationVal = map['duration'] as List?; - VideoEventType videoEventType; - if (map['event'] == 'initialized') { - videoEventType = VideoEventType.initialized; - } else { - videoEventType = VideoEventType.restored; + // Initialize the RawReceivePort once for all players + if (_eventPort == null) { + _eventPort = RawReceivePort(); + + // Listen to FFI events and route them to the appropriate StreamController + _eventPort!.handler = (dynamic message) { + try { + // Message format from C++: [player_id, event_json_string] + if (message is List && message.length == 2) { + final int receivingPlayerId = message[0] as int; + final String eventJson = message[1] as String; + + // Parse JSON to Map + final Map eventMap = + jsonDecode(eventJson) as Map; + + // Route to the correct StreamController + final StreamController? controller = + _eventControllers[receivingPlayerId]; + if (controller != null && !controller.isClosed) { + controller.add(_parseVideoEventFromMap(eventMap)); + } } - return VideoEvent( - eventType: videoEventType, - duration: DurationRange( - Duration(milliseconds: durationVal?[0] as int), - Duration(milliseconds: durationVal?[1] as int), - ), - size: Size( - (map['width'] as num?)?.toDouble() ?? 0.0, - (map['height'] as num?)?.toDouble() ?? 0.0, - ), - ); - case 'completed': - return VideoEvent(eventType: VideoEventType.completed); - case 'bufferingUpdate': - final int value = map['value']! as int; - - return VideoEvent( - buffered: value, - eventType: VideoEventType.bufferingUpdate, - ); - case 'bufferingStart': - return VideoEvent(eventType: VideoEventType.bufferingStart); - case 'bufferingEnd': - return VideoEvent(eventType: VideoEventType.bufferingEnd); - case 'subtitleUpdate': - return VideoEvent( - eventType: VideoEventType.subtitleUpdate, - text: map['text']! as String, - ); - case 'isPlayingStateUpdate': - return VideoEvent( - eventType: VideoEventType.isPlayingStateUpdate, - isPlaying: map['isPlaying']! as bool, - ); - default: - return VideoEvent(eventType: VideoEventType.unknown); - } - }); + } catch (e, stackTrace) { + // Log error but don't crash + debugPrint('Error processing FFI event: $e\n$stackTrace'); + } + }; + + // Register the port with C++ side using FFI + // Use NativePort extension to get the raw port number from RawReceivePort + ffiRegisterEventPort(_eventPort!.nativePort); + } + + // Return the stream for this specific player + return _eventControllers + .putIfAbsent( + playerId, + () => StreamController.broadcast(), + ) + .stream; + } + + VideoEvent _parseVideoEventFromMap(Map map) { + switch (map['event']) { + case 'initialized': + case 'restored': + final List? durationVal = map['duration'] as List?; + VideoEventType videoEventType; + if (map['event'] == 'initialized') { + videoEventType = VideoEventType.initialized; + } else { + videoEventType = VideoEventType.restored; + } + return VideoEvent( + eventType: videoEventType, + duration: DurationRange( + Duration(milliseconds: durationVal?[0] as int? ?? 0), + Duration(milliseconds: durationVal?[1] as int? ?? 0), + ), + size: Size( + (map['width'] as num?)?.toDouble() ?? 0.0, + (map['height'] as num?)?.toDouble() ?? 0.0, + ), + ); + case 'completed': + return VideoEvent(eventType: VideoEventType.completed); + case 'bufferingUpdate': + final int value = map['value']! as int; + return VideoEvent( + buffered: value, + eventType: VideoEventType.bufferingUpdate, + ); + case 'bufferingStart': + return VideoEvent(eventType: VideoEventType.bufferingStart); + case 'bufferingEnd': + return VideoEvent(eventType: VideoEventType.bufferingEnd); + case 'subtitleUpdate': + return VideoEvent( + eventType: VideoEventType.subtitleUpdate, + text: map['text']! as String, + ); + case 'isPlayingStateUpdate': + return VideoEvent( + eventType: VideoEventType.isPlayingStateUpdate, + isPlaying: map['isPlaying']! as bool, + ); + default: + return VideoEvent(eventType: VideoEventType.unknown); + } } @override @@ -418,10 +516,6 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return true; } - EventChannel _eventChannelFor(int playerId) { - return EventChannel('tizen/video_player/video_events_$playerId'); - } - static const Map _videoFormatStringMap = { VideoFormat.ss: 'ss', diff --git a/packages/video_player_videohole/lib/video_player_platform_interface.dart b/packages/video_player_videohole/lib/video_player_platform_interface.dart index 9412ed433..68b127015 100644 --- a/packages/video_player_videohole/lib/video_player_platform_interface.dart +++ b/packages/video_player_videohole/lib/video_player_platform_interface.dart @@ -29,8 +29,19 @@ abstract class VideoPlayerPlatform extends PlatformInterface { /// The default instance of [VideoPlayerPlatform] to use. /// /// Defaults to [VideoPlayerTizen]. + /// + /// The [binaryMessenger] argument is used for communicating with the + /// platform-side EventChannel for event notifications. static VideoPlayerPlatform get instance => _instance; + /// Sets the default instance of [VideoPlayerPlatform] to use. + /// + /// This should be called by platform-specific code to initialize + /// the platform interface. + static void setupInstance() { + _instance = VideoPlayerTizen(); + } + /// Platform-specific plugins should override this with their own /// platform-specific class that extends [VideoPlayerPlatform] when they /// register themselves. diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index e0607e230..523c21f04 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -44,6 +44,7 @@ MediaPlayer::MediaPlayer(flutter::BinaryMessenger *messenger, : VideoPlayer(messenger, flutter_view) { media_player_proxy_ = std::make_unique(); device_proxy_ = std::make_unique(); + // ecore_wl2_window_proxy_ is already created in VideoPlayer constructor } MediaPlayer::~MediaPlayer() { @@ -66,6 +67,9 @@ MediaPlayer::~MediaPlayer() { } } +// Static counter for generating unique player IDs +static int64_t player_id_counter = 1; + int64_t MediaPlayer::Create(const std::string &uri, const CreateMessage &create_message) { LOG_INFO("[MediaPlayer] uri: %s.", uri.c_str()); @@ -74,6 +78,11 @@ int64_t MediaPlayer::Create(const std::string &uri, LOG_ERROR("[MediaPlayer] The uri must not be empty."); return -1; } + + // Assign a unique player ID (this was previously done in SetUpEventChannel) + player_id_ = player_id_counter++; + LOG_INFO("[MediaPlayer] Assigned player_id_: %lld", + static_cast(player_id_)); url_ = uri; create_message_ = create_message; @@ -195,12 +204,13 @@ int64_t MediaPlayer::Create(const std::string &uri, return -1; } - return SetUpEventChannel(); + // Return player_id_ which was already set in constructor + return player_id_; } void MediaPlayer::Dispose() { LOG_INFO("[MediaPlayer] Disposing."); - ClearUpEventChannel(); + // EventChannel has been removed, no cleanup needed } void MediaPlayer::SetDisplayRoi(int32_t x, int32_t y, int32_t width, @@ -391,6 +401,8 @@ bool MediaPlayer::SetDisplay() { return false; } + LOG_INFO("[MediaPlayer] Got native window handle: %p", native_window); + int x = 0, y = 0, width = 0, height = 0; ecore_wl2_window_proxy_->ecore_wl2_window_geometry_get(native_window, &x, &y, &width, &height); @@ -408,6 +420,8 @@ bool MediaPlayer::SetDisplay() { get_error_message(ret)); return false; } + + LOG_INFO("[MediaPlayer] Display set successfully."); return true; } @@ -834,7 +848,12 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, if (pre_state_ == PLAYER_STATE_PLAYING) { if (!Play()) { LOG_ERROR("[MediaPlayer] Player play failed."); - return false; + // return false; + if (player_ && !StopAndDestroy()) { + LOG_ERROR("[MediaPlayer] Player StopAndDestroy fail."); + return false; + } + return RestorePlayer(restore_message, resume_time); } } break; @@ -895,8 +914,27 @@ bool MediaPlayer::SetDisplayRotate(int64_t rotation) { } void MediaPlayer::OnRestoreCompleted() { - if (pre_playing_time_ <= 0 || - !SeekTo(pre_playing_time_, [this]() { SendRestored(); })) { + LOG_INFO( + "[MediaPlayer] OnRestoreCompleted called. pre_state_=%d, " + "pre_playing_time_=%llu", + pre_state_, pre_playing_time_); + + // First, seek to the saved position + if (pre_playing_time_ <= 0 || !SeekTo(pre_playing_time_, [this]() { + // After seek completed, restore the playing state if it was playing + // before suspend + if (pre_state_ == PLAYER_STATE_PLAYING) { + LOG_INFO("[MediaPlayer] Restoring to PLAYING state after seek."); + Play(); + } + SendRestored(); + })) { + // If seek failed or not needed, still restore playing state if it was + // playing + if (pre_state_ == PLAYER_STATE_PLAYING) { + LOG_INFO("[MediaPlayer] Restoring to PLAYING state (no seek needed)."); + Play(); + } SendRestored(); } } diff --git a/packages/video_player_videohole/tizen/src/video_player.cc b/packages/video_player_videohole/tizen/src/video_player.cc index 724011822..f6c644dec 100644 --- a/packages/video_player_videohole/tizen/src/video_player.cc +++ b/packages/video_player_videohole/tizen/src/video_player.cc @@ -4,18 +4,197 @@ #include "video_player.h" -#include -#include +#include #include "log.h" +// For Dart_Port and Dart_PostCObject_DL +#include + namespace video_player_videohole_tizen { static int64_t player_index = 1; -VideoPlayer::VideoPlayer(flutter::BinaryMessenger *messenger, +// Static FFI event callback - shared across all VideoPlayer instances +static DartPortEventCallback g_ffi_event_callback = nullptr; +static std::mutex g_ffi_callback_mutex; + +// Dart Port for FFI event notifications using Dart_PostCObject_DL +// Defined here (extern declared in video_player.h) +int64_t g_dart_port = -1; +std::mutex g_dart_port_mutex; + +void RegisterDartPort(int64_t port) { + std::lock_guard lock(g_dart_port_mutex); + g_dart_port = port; +} + +int64_t GetDartPort() { + std::lock_guard lock(g_dart_port_mutex); + return g_dart_port; +} + +void PostEventToDart(int64_t player_id, const std::string& event_json) { + std::lock_guard lock(g_dart_port_mutex); + if (g_dart_port < 0) { + LOG_INFO("[VideoPlayer] Dart port not registered yet."); + return; + } + + LOG_INFO( + "[VideoPlayer] Posting event to Dart: player_id=%lld, event=%s, " + "port=%lld", + static_cast(player_id), event_json.c_str(), + static_cast(g_dart_port)); + + // Message format: [player_id, event_json] + // This matches what Dart side expects + Dart_CObject player_id_obj; + player_id_obj.type = Dart_CObject_kInt64; + player_id_obj.value.as_int64 = player_id; + + // Dart_PostCObject_DL takes ownership of the string on success + char* json_copy = strdup(event_json.c_str()); + Dart_CObject event_json_obj; + event_json_obj.type = Dart_CObject_kString; + event_json_obj.value.as_string = json_copy; + + // Array elements (must be pointers) + Dart_CObject* array_elements[2]; + array_elements[0] = &player_id_obj; + array_elements[1] = &event_json_obj; + + // The message array + Dart_CObject message; + message.type = Dart_CObject_kArray; + message.value.as_array.length = 2; + message.value.as_array.values = array_elements; + + LOG_INFO("[VideoPlayer] Calling Dart_PostCObject_DL..."); + + bool result = Dart_PostCObject_DL(g_dart_port, &message); + LOG_INFO("[VideoPlayer] Dart_PostCObject_DL result: %d", result ? 1 : 0); + + if (!result) { + LOG_ERROR("[VideoPlayer] Failed to post event to Dart. Freeing json_copy."); + free(json_copy); + } + // On success, Dart takes ownership of json_copy +} + +void VideoPlayer::RegisterFFIEventCallback(DartPortEventCallback callback) { + std::lock_guard lock(g_ffi_callback_mutex); + g_ffi_event_callback = std::move(callback); +} + +DartPortEventCallback VideoPlayer::GetFFIEventCallback() { + std::lock_guard lock(g_ffi_callback_mutex); + return g_ffi_event_callback; +} + +// Helper function to convert EncodableValue to JSON string +static std::string EncodableValueToJson(const flutter::EncodableValue& value); + +static std::string EncodableMapToJson(const flutter::EncodableMap& map) { + std::ostringstream oss; + oss << "{"; + bool first = true; + for (const auto& [key, val] : map) { + if (!first) oss << ","; + first = false; + + // Key + if (std::holds_alternative(key)) { + oss << "\"" << std::get(key) << "\":"; + } else if (std::holds_alternative(key)) { + oss << std::get(key) << ":"; + } else if (std::holds_alternative(key)) { + oss << std::get(key) << ":"; + } + + // Value + oss << EncodableValueToJson(val); + } + oss << "}"; + return oss.str(); +} + +static std::string EncodableListToJson(const flutter::EncodableList& list) { + std::ostringstream oss; + oss << "["; + for (size_t i = 0; i < list.size(); ++i) { + if (i > 0) oss << ","; + oss << EncodableValueToJson(list[i]); + } + oss << "]"; + return oss.str(); +} + +static std::string EncodableValueToJson(const flutter::EncodableValue& value) { + // Use holds_alternative with try-catch to safely check types + // This avoids static_assert errors and bad_variant_access exceptions + try { + if (std::holds_alternative(value)) { + return std::get(value) ? "true" : "false"; + } + if (std::holds_alternative(value)) { + return std::to_string(std::get(value)); + } + if (std::holds_alternative(value)) { + return std::to_string(std::get(value)); + } + if (std::holds_alternative(value)) { + return std::to_string(std::get(value)); + } + if (std::holds_alternative(value)) { + std::ostringstream oss; + oss << "\"" << std::get(value) << "\""; + return oss.str(); + } + if (std::holds_alternative>(value)) { + return "[]"; + } + if (std::holds_alternative>(value)) { + return "[]"; + } + if (std::holds_alternative>(value)) { + return "[]"; + } + if (std::holds_alternative>(value)) { + return "[]"; + } + if (std::holds_alternative(value)) { + return EncodableListToJson(std::get(value)); + } + if (std::holds_alternative(value)) { + return EncodableMapToJson(std::get(value)); + } + if (std::holds_alternative>(value)) { + return "[]"; + } + // Default for null/monostate or any unknown type + return "null"; + } catch (const std::bad_variant_access& e) { + return "null"; + } +} + +// Convert event to JSON and call FFI callback if registered +static void NotifyFFIEventCallback(int64_t player_id, + const flutter::EncodableValue& event_value) { + DartPortEventCallback callback = VideoPlayer::GetFFIEventCallback(); + if (callback) { + std::string event_json = EncodableValueToJson(event_value); + // Pass strdup-allocated string to callback + callback(player_id, strdup(event_json.c_str())); + } +} + +VideoPlayer::VideoPlayer(flutter::BinaryMessenger* messenger, FlutterDesktopViewRef flutter_view) - : ecore_wl2_window_proxy_(std::make_unique()), + : player_id_(-1), // Initialize player_id_ to -1 (will be set in + // SetUpEventChannel) + ecore_wl2_window_proxy_(std::make_unique()), binary_messenger_(messenger), flutter_view_(flutter_view) { // Initialize GMainContext and event dispatch state @@ -41,62 +220,31 @@ VideoPlayer::~VideoPlayer() { main_context_.reset(); } -void VideoPlayer::ClearUpEventChannel() { - is_initialized_ = false; - { - std::lock_guard lock(queue_mutex_); - event_sink_ = nullptr; - } - if (event_channel_) { - event_channel_->SetStreamHandler(nullptr); - } -} - -int64_t VideoPlayer::SetUpEventChannel() { - int64_t player_id = player_index++; - std::string channel_name = - "tizen/video_player/video_events_" + std::to_string(player_id); - auto channel = - std::make_unique>( - binary_messenger_, channel_name, - &flutter::StandardMethodCodec::GetInstance()); - auto handler = std::make_unique< - flutter::StreamHandlerFunctions>( - [&](const flutter::EncodableValue *arguments, - std::unique_ptr> &&events) - -> std::unique_ptr> { - event_sink_ = std::move(events); - if (IsReady()) { - SendInitialized(); - } else { - LOG_INFO("[VideoPlayer] Player is not ready."); - } - return nullptr; - }, - [&](const flutter::EncodableValue *arguments) - -> std::unique_ptr> { - event_sink_ = nullptr; - return nullptr; - }); - channel->SetStreamHandler(std::move(handler)); - event_channel_ = std::move(channel); - return player_id; -} - void VideoPlayer::ExecuteSinkEvents() { std::lock_guard lock(queue_mutex_); + + // Process regular events using FFI only while (!encodable_event_queue_.empty()) { - if (event_sink_) { - event_sink_->Success(encodable_event_queue_.front()); - } + const flutter::EncodableValue& event = encodable_event_queue_.front(); + + // Send to FFI using Dart_PostCObject_DL + std::string event_json = EncodableValueToJson(event); + PostEventToDart(player_id_, event_json); + encodable_event_queue_.pop(); } + // Process error events via FFI while (!error_event_queue_.empty()) { - if (event_sink_) { - event_sink_->Error(error_event_queue_.front().first, - error_event_queue_.front().second); - } + const auto& error = error_event_queue_.front(); + // Send error event via FFI + flutter::EncodableMap error_map = { + {flutter::EncodableValue("event"), flutter::EncodableValue("error")}, + {flutter::EncodableValue("code"), flutter::EncodableValue(error.first)}, + {flutter::EncodableValue("message"), + flutter::EncodableValue(error.second)}, + }; + PushEvent(flutter::EncodableValue(error_map)); error_event_queue_.pop(); } } @@ -111,14 +259,14 @@ void VideoPlayer::ScheduleSendPendingEvents() { return; } - auto *state = new std::shared_ptr(event_dispatch_state_); + auto* state = new std::shared_ptr(event_dispatch_state_); - GSource *source = g_idle_source_new(); + GSource* source = g_idle_source_new(); g_source_set_callback( source, [](gpointer data) -> gboolean { - auto state = static_cast *>(data); - VideoPlayer *player = nullptr; + auto state = static_cast*>(data); + VideoPlayer* player = nullptr; { std::lock_guard lock((*state)->mutex); if (!(*state)->disposed && (*state)->player) { @@ -133,7 +281,7 @@ void VideoPlayer::ScheduleSendPendingEvents() { }, state, [](gpointer data) { - delete static_cast *>(data); + delete static_cast*>(data); }); event_dispatch_state_->pending_source_id = @@ -144,17 +292,18 @@ void VideoPlayer::ScheduleSendPendingEvents() { void VideoPlayer::PushEvent(flutter::EncodableValue encodable_value) { { std::lock_guard lock(queue_mutex_); - if (!event_sink_) { - LOG_ERROR("[VideoPlayer] event sink is nullptr."); - return; - } + // Always add event to queue, even if event_sink_ is nullptr + // FFI callback doesn't require event_sink_ to be set encodable_event_queue_.push(encodable_value); } ScheduleSendPendingEvents(); } void VideoPlayer::SendInitialized() { - if (!is_initialized_ && event_sink_) { + // Always send initialized event via FFI + if (!is_initialized_) { + LOG_INFO("[VideoPlayer] SendInitialized called."); + int32_t width = 0, height = 0; GetVideoSize(&width, &height); is_initialized_ = true; @@ -170,7 +319,10 @@ void VideoPlayer::SendInitialized() { {flutter::EncodableValue("width"), flutter::EncodableValue(width)}, {flutter::EncodableValue("height"), flutter::EncodableValue(height)}, }; + LOG_INFO("[VideoPlayer] Pushing initialized event to FFI"); PushEvent(flutter::EncodableValue(result)); + } else { + LOG_INFO("[VideoPlayer] SendInitialized skipped - already initialized"); } } @@ -200,7 +352,7 @@ void VideoPlayer::SendBufferingEnd() { } void VideoPlayer::SendSubtitleUpdate(int32_t duration, - const std::string &text) { + const std::string& text) { flutter::EncodableMap result = { {flutter::EncodableValue("event"), flutter::EncodableValue("subtitleUpdate")}, @@ -218,6 +370,7 @@ void VideoPlayer::SendPlayCompleted() { } void VideoPlayer::SendIsPlayingState(bool is_playing) { + LOG_INFO("***********SendIsPlayingState start***************"); flutter::EncodableMap result = { {flutter::EncodableValue("event"), flutter::EncodableValue("isPlayingStateUpdate")}, @@ -225,10 +378,11 @@ void VideoPlayer::SendIsPlayingState(bool is_playing) { flutter::EncodableValue(is_playing)}, }; PushEvent(flutter::EncodableValue(result)); + LOG_INFO("***********SendIsPlayingState end***************"); } void VideoPlayer::SendRestored() { - if (is_restored_ && event_sink_) { + if (is_restored_) { is_restored_ = false; int32_t width = 0, height = 0; GetVideoSize(&width, &height); @@ -248,20 +402,14 @@ void VideoPlayer::SendRestored() { } } -void VideoPlayer::SendError(const std::string &error_code, - const std::string &error_message) { - { - std::lock_guard lock(queue_mutex_); - if (!event_sink_) { - LOG_ERROR("[VideoPlayer] event sink is nullptr."); - return; - } - error_event_queue_.push(std::make_pair(error_code, error_message)); - } +void VideoPlayer::SendError(const std::string& error_code, + const std::string& error_message) { + std::lock_guard lock(queue_mutex_); + error_event_queue_.push(std::make_pair(error_code, error_message)); ScheduleSendPendingEvents(); } -void *VideoPlayer::GetWindowHandle() { +void* VideoPlayer::GetWindowHandle() { return FlutterDesktopViewGetNativeHandle(flutter_view_); } diff --git a/packages/video_player_videohole/tizen/src/video_player.h b/packages/video_player_videohole/tizen/src/video_player.h index 92a311197..3862484b3 100644 --- a/packages/video_player_videohole/tizen/src/video_player.h +++ b/packages/video_player_videohole/tizen/src/video_player.h @@ -6,25 +6,53 @@ #define FLUTTER_PLUGIN_VIDEO_PLAYER_H_ #include -#include #include #include +#include +#include #include #include #include #include #include +// Dart API for sending messages from native code to Dart isolate +#include + #include "ecore_wl2_window_proxy.h" #include "messages.h" namespace video_player_videohole_tizen { +// FFI event callback using Dart_Port - sends message to Dart isolate +// Parameters: player_id, event_json string +using DartPortEventCallback = + std::function; + +// Static FFI event callback - shared across all VideoPlayer instances +extern DartPortEventCallback g_dart_port_callback; +extern int64_t g_dart_port; +extern std::mutex g_dart_port_mutex; + +// Register Dart port for FFI event notifications +void RegisterDartPort(int64_t port); +int64_t GetDartPort(); + +// Post event to Dart using Dart_PostCObject_DL +void PostEventToDart(int64_t player_id, const std::string &event_json); + class VideoPlayer { public: using SeekCompletedCallback = std::function; + // Static method to register FFI event callback (legacy, kept for + // compatibility) + static void RegisterFFIEventCallback(DartPortEventCallback callback); + + // Static method to get current FFI event callback (legacy) + static DartPortEventCallback GetFFIEventCallback(); + explicit VideoPlayer(flutter::BinaryMessenger *messenger, FlutterDesktopViewRef flutter_view); VideoPlayer(const VideoPlayer &) = delete; @@ -58,8 +86,6 @@ class VideoPlayer { protected: virtual void GetVideoSize(int32_t *width, int32_t *height) = 0; void *GetWindowHandle(); - int64_t SetUpEventChannel(); - void ClearUpEventChannel(); void SendInitialized(); void SendBufferingStart(); void SendBufferingUpdate(int32_t value); @@ -71,6 +97,7 @@ class VideoPlayer { void SendError(const std::string &error_code, const std::string &error_message); + int64_t player_id_; // Store player ID for FFI event callback std::mutex queue_mutex_; std::unique_ptr ecore_wl2_window_proxy_ = nullptr; flutter::BinaryMessenger *binary_messenger_; @@ -102,9 +129,6 @@ class VideoPlayer { std::queue encodable_event_queue_; std::queue> error_event_queue_; - std::unique_ptr> - event_channel_; - std::unique_ptr> event_sink_; }; } // namespace video_player_videohole_tizen diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 52f29409a..81b73e546 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -350,9 +350,24 @@ namespace video_player_videohole_tizen { VideoPlayerTizenPlugin *VideoPlayerTizenPlugin::instance_ = nullptr; } // namespace video_player_videohole_tizen -// FFI exports for gradual migration +// C interface for plugin registration (required by C# +// GeneratedPluginRegistrant) and FFI exports for gradual migration extern "C" { +void VideoPlayerTizenPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar_ref) { + // Get the plugin registrar from the manager using the template method + auto *plugin_registrar = + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar_ref); + + // Create and register the plugin + auto plugin = + std::make_unique( + registrar_ref, plugin_registrar); + plugin_registrar->AddPlugin(std::move(plugin)); +} + int ffi_initialize() { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); @@ -1080,11 +1095,60 @@ int ffi_set_mix_with_others(bool mix_with_others) { return 0; // Success } -} // extern "C" +// FFI event callback function pointer type - matches the C++ type +// Parameters: player_id, event_json (malloc-allocated string, caller must free) +typedef void (*FFIEventCallbackFunc)(int64_t player_id, const char *event_json); + +// FFI register_event_callback function - registers callback for event +// notifications The callback will be invoked on the main thread via +// g_idle_source event_json is a malloc-allocated string that the callback must +// free +void ffi_register_event_callback(FFIEventCallbackFunc callback) { + if (callback == nullptr) { + // Clear the callback + video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback( + nullptr); + return; + } -void VideoPlayerTizenPluginRegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar) { - video_player_videohole_tizen::VideoPlayerTizenPlugin::RegisterWithRegistrar( - registrar, flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar)); + // Wrap the C function pointer in a std::function + video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback( + [callback](int64_t player_id, const char *event_json) { + callback(player_id, event_json); + }); +} + +// FFI unregister_event_callback function - unregisters the event callback +void ffi_unregister_event_callback() { + video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback(nullptr); +} + +// Global variable to store Dart_InitializeApiDL data +static bool g_dart_api_dl_initialized = false; + +// FFI initialize_api_dl function - initializes Dart API DL +// This must be called before using Dart_PostCObject_DL +// data: The initializeApiDLData from Dart's NativeApi +void ffi_initialize_api_dl(void *data) { + if (!g_dart_api_dl_initialized) { + if (Dart_InitializeApiDL(data) == 0) { + g_dart_api_dl_initialized = true; + } + } } + +// FFI register_event_port function - registers Dart port for event +// notifications The port is used with Dart_PostCObject_DL to send events to +// Dart isolate port: The nativePort from Dart's ReceivePort.sendPort +void ffi_register_event_port(int64_t port) { + // Ensure Dart API DL is initialized before using Dart_PostCObject_DL + // Note: This assumes Dart side has already called ffi_initialize_api_dl + video_player_videohole_tizen::RegisterDartPort(port); +} + +// FFI unregister_event_port function - unregisters the Dart port +void ffi_unregister_event_port() { + video_player_videohole_tizen::RegisterDartPort(-1); +} + +} // extern "C" From 93de4a23b5113ea3170d31ea9ce156d4e13cee7d Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 22 Jul 2026 13:30:34 +0800 Subject: [PATCH 06/18] fixed dart analyze issue --- packages/video_player_videohole/lib/src/video_player_tizen.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index eb49992cd..946140ab7 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -5,7 +5,7 @@ import 'dart:async'; import 'dart:convert'; -import 'dart:isolate' show RawReceivePort, ReceivePort; +import 'dart:isolate' show RawReceivePort; import 'package:flutter/widgets.dart'; From 3a558d657e714cf846e9b86512abcc29462fa7b5 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 22 Jul 2026 17:03:42 +0800 Subject: [PATCH 07/18] Code refactoring --- .../{messages.g.dart => ffi_messages.g.dart} | 761 +-------- .../lib/src/video_player_tizen.dart | 2 +- .../tizen/src/ffi_messages.h | 359 ++++ .../tizen/src/media_player.cc | 40 +- .../tizen/src/messages.cc | 1479 ----------------- .../tizen/src/messages.h | 544 ------ .../tizen/src/video_player.cc | 10 +- .../tizen/src/video_player.h | 2 +- .../tizen/src/video_player_tizen_plugin.cc | 450 ++--- 9 files changed, 564 insertions(+), 3083 deletions(-) rename packages/video_player_videohole/lib/src/{messages.g.dart => ffi_messages.g.dart} (50%) create mode 100644 packages/video_player_videohole/tizen/src/ffi_messages.h delete mode 100644 packages/video_player_videohole/tizen/src/messages.cc delete mode 100644 packages/video_player_videohole/tizen/src/messages.h diff --git a/packages/video_player_videohole/lib/src/messages.g.dart b/packages/video_player_videohole/lib/src/ffi_messages.g.dart similarity index 50% rename from packages/video_player_videohole/lib/src/messages.g.dart rename to packages/video_player_videohole/lib/src/ffi_messages.g.dart index 7979e7798..ec445583d 100644 --- a/packages/video_player_videohole/lib/src/messages.g.dart +++ b/packages/video_player_videohole/lib/src/ffi_messages.g.dart @@ -1,11 +1,13 @@ -// Autogenerated from Pigeon (v10.1.6), do not edit directly. -// See also: https://pub.dev/packages/pigeon -// ignore_for_file: public_member_api_docs, non_constant_identifier_names, avoid_as, unused_import, unnecessary_parenthesis, prefer_null_aware_operators, omit_local_variable_types, unused_shown_name, unnecessary_import +// Copyright 2023 Samsung Electronics Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// FFI API for video_player_tizen - manually maintained +// This file contains FFI bindings and message types for synchronous native calls -import 'dart:async'; import 'dart:ffi' as ffi; import 'dart:ffi' show NativeCallable; -import 'dart:isolate' show RawReceivePort, ReceivePort, SendPort; +import 'dart:isolate' show RawReceivePort, ReceivePort; import 'package:ffi/ffi.dart' show calloc; import 'dart:typed_data' show Float64List, Int32List, Int64List, Uint8List; import 'dart:convert' show utf8, jsonEncode, jsonDecode; @@ -14,6 +16,8 @@ import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer, debugPrint; import 'package:flutter/services.dart'; +// ===== Message Types ===== + class PlayerMessage { PlayerMessage({required this.playerId}); @@ -33,7 +37,6 @@ class LoopingMessage { LoopingMessage({required this.playerId, required this.isLooping}); int playerId; - bool isLooping; Object encode() { @@ -53,7 +56,6 @@ class VolumeMessage { VolumeMessage({required this.playerId, required this.volume}); int playerId; - double volume; Object encode() { @@ -73,7 +75,6 @@ class PlaybackSpeedMessage { PlaybackSpeedMessage({required this.playerId, required this.speed}); int playerId; - double speed; Object encode() { @@ -93,7 +94,6 @@ class TrackMessage { TrackMessage({required this.playerId, required this.tracks}); int playerId; - List?> tracks; Object encode() { @@ -113,7 +113,6 @@ class TrackTypeMessage { TrackTypeMessage({required this.playerId, required this.trackType}); int playerId; - String trackType; Object encode() { @@ -137,9 +136,7 @@ class SelectedTracksMessage { }); int playerId; - int trackId; - String trackType; Object encode() { @@ -160,7 +157,6 @@ class PositionMessage { PositionMessage({required this.playerId, required this.position}); int playerId; - int position; Object encode() { @@ -188,17 +184,11 @@ class CreateMessage { }); String? asset; - String? uri; - String? packageName; - String? formatHint; - Map? httpHeaders; - Map? drmConfigs; - Map? playerOptions; Object encode() { @@ -255,13 +245,9 @@ class GeometryMessage { }); int playerId; - int x; - int y; - int width; - int height; Object encode() { @@ -284,7 +270,6 @@ class DurationMessage { DurationMessage({required this.playerId, this.durationRange}); int playerId; - List? durationRange; Object encode() { @@ -304,7 +289,6 @@ class RotationMessage { RotationMessage({required this.playerId, required this.rotation}); int playerId; - int rotation; Object encode() { @@ -320,642 +304,14 @@ class RotationMessage { } } -class _VideoPlayerVideoholeApiCodec extends StandardMessageCodec { - const _VideoPlayerVideoholeApiCodec(); - @override - void writeValue(WriteBuffer buffer, Object? value) { - if (value is CreateMessage) { - buffer.putUint8(128); - writeValue(buffer, value.encode()); - } else if (value is CreateMessage) { - buffer.putUint8(129); - writeValue(buffer, value.encode()); - } else if (value is DurationMessage) { - buffer.putUint8(130); - writeValue(buffer, value.encode()); - } else if (value is GeometryMessage) { - buffer.putUint8(131); - writeValue(buffer, value.encode()); - } else if (value is LoopingMessage) { - buffer.putUint8(132); - writeValue(buffer, value.encode()); - } else if (value is MixWithOthersMessage) { - buffer.putUint8(133); - writeValue(buffer, value.encode()); - } else if (value is PlaybackSpeedMessage) { - buffer.putUint8(134); - writeValue(buffer, value.encode()); - } else if (value is PlayerMessage) { - buffer.putUint8(135); - writeValue(buffer, value.encode()); - } else if (value is PositionMessage) { - buffer.putUint8(136); - writeValue(buffer, value.encode()); - } else if (value is RotationMessage) { - buffer.putUint8(137); - writeValue(buffer, value.encode()); - } else if (value is SelectedTracksMessage) { - buffer.putUint8(138); - writeValue(buffer, value.encode()); - } else if (value is TrackMessage) { - buffer.putUint8(139); - writeValue(buffer, value.encode()); - } else if (value is TrackTypeMessage) { - buffer.putUint8(140); - writeValue(buffer, value.encode()); - } else if (value is VolumeMessage) { - buffer.putUint8(141); - writeValue(buffer, value.encode()); - } else { - super.writeValue(buffer, value); - } - } - - @override - Object? readValueOfType(int type, ReadBuffer buffer) { - switch (type) { - case 128: - return CreateMessage.decode(readValue(buffer)!); - case 129: - return CreateMessage.decode(readValue(buffer)!); - case 130: - return DurationMessage.decode(readValue(buffer)!); - case 131: - return GeometryMessage.decode(readValue(buffer)!); - case 132: - return LoopingMessage.decode(readValue(buffer)!); - case 133: - return MixWithOthersMessage.decode(readValue(buffer)!); - case 134: - return PlaybackSpeedMessage.decode(readValue(buffer)!); - case 135: - return PlayerMessage.decode(readValue(buffer)!); - case 136: - return PositionMessage.decode(readValue(buffer)!); - case 137: - return RotationMessage.decode(readValue(buffer)!); - case 138: - return SelectedTracksMessage.decode(readValue(buffer)!); - case 139: - return TrackMessage.decode(readValue(buffer)!); - case 140: - return TrackTypeMessage.decode(readValue(buffer)!); - case 141: - return VolumeMessage.decode(readValue(buffer)!); - default: - return super.readValueOfType(type, buffer); - } - } -} - -class VideoPlayerVideoholeApi { - /// Constructor for [VideoPlayerVideoholeApi]. The [binaryMessenger] named argument is - /// available for dependency injection. If it is left null, the default - /// BinaryMessenger will be used which routes to the host platform. - VideoPlayerVideoholeApi({BinaryMessenger? binaryMessenger}) - : _binaryMessenger = binaryMessenger; - final BinaryMessenger? _binaryMessenger; - - static const MessageCodec codec = _VideoPlayerVideoholeApiCodec(); - - Future initialize() async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.initialize', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = await channel.send(null) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future create(CreateMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.create', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as PlayerMessage?)!; - } - } - - Future dispose(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.dispose', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setLooping(LoopingMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setLooping', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setVolume(VolumeMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setVolume', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setPlaybackSpeed(PlaybackSpeedMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setPlaybackSpeed', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future play(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.play', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setDeactivate(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDeactivate', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as bool?)!; - } - } - - Future setActivate(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setActivate', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as bool?)!; - } - } - - Future track(TrackTypeMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.track', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as TrackMessage?)!; - } - } - - Future setTrackSelection(SelectedTracksMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setTrackSelection', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as bool?)!; - } - } - - Future position(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.position', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as PositionMessage?)!; - } - } - - Future seekTo(PositionMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.seekTo', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future pause(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.pause', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setMixWithOthers(MixWithOthersMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setMixWithOthers', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setDisplayGeometry(GeometryMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayGeometry', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future duration(PlayerMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.duration', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as DurationMessage?)!; - } - } - - Future suspend(int arg_playerId) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.suspend', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_playerId]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future restore( - int arg_playerId, - CreateMessage? arg_msg, - int arg_resumeTime, - ) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.restore', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_playerId, arg_msg, arg_resumeTime]) - as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else { - return; - } - } - - Future setDisplayRotate(RotationMessage arg_msg) async { - final BasicMessageChannel channel = BasicMessageChannel( - 'dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi.setDisplayRotate', - codec, - binaryMessenger: _binaryMessenger, - ); - final List? replyList = - await channel.send([arg_msg]) as List?; - if (replyList == null) { - throw PlatformException( - code: 'channel-error', - message: 'Unable to establish connection on channel.', - ); - } else if (replyList.length > 1) { - throw PlatformException( - code: replyList[0]! as String, - message: replyList[1] as String?, - details: replyList[2], - ); - } else if (replyList[0] == null) { - throw PlatformException( - code: 'null-error', - message: 'Host platform returned null value for non-null return value.', - ); - } else { - return (replyList[0] as bool?)!; - } - } -} - -// ===== FFI Section - Gradual Migration ===== +// ===== FFI Type Definitions ===== -// FFI type definitions typedef _FFIInitializeNative = ffi.Int32 Function(); typedef _FFIInitializeDart = int Function(); -// FFI type definitions - create takes a single JSON string for all parameters -// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} typedef _FFICreateNative = ffi.Int64 Function(ffi.Pointer); typedef _FFICreateDart = int Function(ffi.Pointer); -// FFI type definitions for additional methods typedef _FFIDisposeNative = ffi.Int32 Function(ffi.Int64); typedef _FFIDisposeDart = int Function(int); @@ -1016,7 +372,8 @@ typedef _FFIRestoreNative = ffi.Int32 Function( ffi.Int64, ffi.Pointer, ffi.Int64); typedef _FFIRestoreDart = int Function(int, ffi.Pointer, int); -// Helper functions for FFI string conversion +// ===== Helper Functions ===== + ffi.Pointer _toPointer(String? str) { if (str == null) return ffi.nullptr; final units = utf8.encode(str); @@ -1033,7 +390,8 @@ void _freePointer(ffi.Pointer ptr) { } } -/// FFI Bindings for video_player_tizen +// ===== FFI Bindings ===== + class VideoPlayerFFIBindings { static VideoPlayerFFIBindings? _instance; ffi.DynamicLibrary? _lib; @@ -1159,16 +517,6 @@ class VideoPlayerFFIBindings { 'ffi_set_deactivate') .asFunction<_FFISetDeactivateDart>(); - _ffiGetTrackInfo = _lib! - .lookup>( - 'ffi_get_track_info') - .asFunction<_FFIGetTrackInfoDart>(); - - _ffiSetTrackSelection = _lib! - .lookup>( - 'ffi_set_track_selection') - .asFunction<_FFISetTrackSelectionDart>(); - _ffiSetMixWithOthers = _lib! .lookup>( 'ffi_set_mix_with_others') @@ -1192,8 +540,6 @@ class VideoPlayerFFIBindings { } /// FFI create function - takes a single JSON string for all parameters - /// JSON format: {"uri":"...","asset":"...","packageName":"...","formatHint":"...", - /// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} int ffiCreate({ String? uri, String? asset, @@ -1207,7 +553,7 @@ class VideoPlayerFFIBindings { throw StateError('FFI bindings not loaded. Call load() first.'); } - // Build JSON string from individual parameters (same as restore pattern) + // Build JSON string from individual parameters final Map jsonMap = {}; if (uri != null && uri.isNotEmpty) jsonMap['uri'] = uri; if (asset != null && asset.isNotEmpty) jsonMap['asset'] = asset; @@ -1233,8 +579,8 @@ class VideoPlayerFFIBindings { } } -// FFI API for video_player_tizen - mirrors VideoPlayerVideoholeApi structure -// Note: All methods are synchronous for better performance +// ===== FFI API Class ===== + class VideoPlayerFFIApi { int initialize() { return ffiInitialize(); @@ -1333,7 +679,8 @@ class VideoPlayerFFIApi { } } -// Top-level FFI functions for easy access (synchronous) +// ===== Top-level FFI Functions ===== + int ffiInitialize() { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1342,7 +689,6 @@ int ffiInitialize() { return bindings.ffiInitialize(); } -/// FFI create function - returns player_id or -1 on error int ffiCreate({ String? uri, String? asset, @@ -1367,8 +713,6 @@ int ffiCreate({ ); } -/// FFI dispose function - releases player resources -/// Returns: 0 on success, -1 on error int ffiDispose(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1377,8 +721,6 @@ int ffiDispose(int playerId) { return bindings._ffiDispose(playerId); } -/// FFI play function - starts or resumes playback -/// Returns: 0 on success, -1 on error int ffiPlay(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1387,8 +729,6 @@ int ffiPlay(int playerId) { return bindings._ffiPlay(playerId); } -/// FFI pause function - pauses playback -/// Returns: 0 on success, -1 on error int ffiPause(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1397,8 +737,6 @@ int ffiPause(int playerId) { return bindings._ffiPause(playerId); } -/// FFI seek_to function - seeks to a specific position (in milliseconds) -/// Returns: 0 on success, -1 on error int ffiSeekTo(int playerId, int positionMs) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1407,8 +745,6 @@ int ffiSeekTo(int playerId, int positionMs) { return bindings._ffiSeekTo(playerId, positionMs); } -/// FFI get_position function - gets current playback position in milliseconds -/// Returns: position in milliseconds (>= 0) on success, -1 on error int ffiGetPosition(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1417,10 +753,6 @@ int ffiGetPosition(int playerId) { return bindings._ffiGetPosition(playerId); } -/// FFI get_duration function - gets video duration range in milliseconds -/// Returns: DurationMessage with durationRange on success -/// For live streams, start may be non-zero -/// Note: The C++ function returns a strdup-allocated string that we must free DurationMessage ffiGetDuration(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1431,7 +763,6 @@ DurationMessage ffiGetDuration(int playerId) { throw Exception('FFI getDuration failed - returned null pointer'); } try { - // Convert C string to Dart string by finding null terminator final bytes = ptr.cast(); int length = 0; while (bytes[length] != 0) { @@ -1450,13 +781,10 @@ DurationMessage ffiGetDuration(int playerId) { ], ); } finally { - // Free the strdup-allocated memory to prevent memory leak calloc.free(ptr); } } -/// FFI set_volume function - sets playback volume (0.0 to 1.0) -/// Returns: 0 on success, -1 on error int ffiSetVolume(int playerId, double volume) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1465,8 +793,6 @@ int ffiSetVolume(int playerId, double volume) { return bindings._ffiSetVolume(playerId, volume); } -/// FFI set_playback_speed function - sets playback speed -/// Returns: 0 on success, -1 on error int ffiSetPlaybackSpeed(int playerId, double speed) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1475,8 +801,6 @@ int ffiSetPlaybackSpeed(int playerId, double speed) { return bindings._ffiSetPlaybackSpeed(playerId, speed); } -/// FFI set_looping function - enables or disables looping -/// Returns: 0 on success, -1 on error int ffiSetLooping(int playerId, bool isLooping) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1485,8 +809,6 @@ int ffiSetLooping(int playerId, bool isLooping) { return bindings._ffiSetLooping(playerId, isLooping); } -/// FFI set_display_geometry function - sets the display geometry (ROI) -/// Returns: 0 on success, -1 on error int ffiSetDisplayGeometry(int playerId, int x, int y, int width, int height) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1495,8 +817,6 @@ int ffiSetDisplayGeometry(int playerId, int x, int y, int width, int height) { return bindings._ffiSetDisplayGeometry(playerId, x, y, width, height); } -/// FFI set_display_rotate function - sets display rotation -/// Returns: 0 on success, -1 on error int ffiSetDisplayRotate(int playerId, int rotation) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1505,8 +825,6 @@ int ffiSetDisplayRotate(int playerId, int rotation) { return bindings._ffiSetDisplayRotate(playerId, rotation); } -/// FFI suspend function - suspends the player -/// Returns: 0 on success, -1 on error int ffiSuspend(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1515,15 +833,11 @@ int ffiSuspend(int playerId) { return bindings._ffiSuspend(playerId); } -/// FFI restore function - restores a suspended player -/// Returns: 0 on success, -1 on error -/// createMessageJson: JSON string of CreateMessage or null/empty for using saved state from Suspend int ffiRestore(int playerId, String? createMessageJson, int resumeTime) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { bindings.load(); } - // Pass JSON string to C++ for parsing final createMessagePtr = _toPointer(createMessageJson); try { return bindings._ffiRestore(playerId, createMessagePtr, resumeTime); @@ -1532,8 +846,6 @@ int ffiRestore(int playerId, String? createMessageJson, int resumeTime) { } } -/// FFI set_activate function - activates the player -/// Returns: 0 on success, -1 on error int ffiSetActivate(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1542,8 +854,6 @@ int ffiSetActivate(int playerId) { return bindings._ffiSetActivate(playerId); } -/// FFI set_deactivate function - deactivates the player -/// Returns: 0 on success, -1 on error int ffiSetDeactivate(int playerId) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1552,8 +862,6 @@ int ffiSetDeactivate(int playerId) { return bindings._ffiSetDeactivate(playerId); } -/// FFI get_track_info function - gets track info as JSON string -/// Returns: JSON string containing track information String ffiGetTrackInfo(int playerId, String trackType) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1566,7 +874,6 @@ String ffiGetTrackInfo(int playerId, String trackType) { if (ptr == ffi.nullptr) { throw Exception('FFI getTrackInfo failed - returned null pointer'); } - // Convert C string to Dart string by finding null terminator final bytes = ptr.cast(); int length = 0; while (bytes[length] != 0) { @@ -1578,16 +885,13 @@ String ffiGetTrackInfo(int playerId, String trackType) { } return jsonString; } finally { - // Free the strdup-allocated memory to prevent memory leak if (ptr != null) { - calloc.free(ptr); + calloc.free(ptr.cast()); } _freePointer(trackTypePtr); } } -/// FFI set_track_selection function - sets the track selection -/// Returns: 0 on success, -1 on error int ffiSetTrackSelection(int playerId, int trackId, String trackType) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1601,8 +905,6 @@ int ffiSetTrackSelection(int playerId, int trackId, String trackType) { } } -/// FFI set_mix_with_others function - sets mix with others -/// Returns: 0 on success, -1 on error int ffiSetMixWithOthers(bool mixWithOthers) { final bindings = VideoPlayerFFIBindings.instance; if (!bindings.isLoaded) { @@ -1613,8 +915,6 @@ int ffiSetMixWithOthers(bool mixWithOthers) { // ===== FFI Event Port Section - Using Dart_PostCObject_DL ===== -/// FFI initialize_api_dl function - initializes Dart API DL -/// This must be called before using Dart_PostCObject_DL typedef _FFIInitializeApiDlNative = ffi.Int32 Function(ffi.Pointer); typedef _FFIInitializeApiDlDart = int Function(ffi.Pointer); @@ -1622,8 +922,6 @@ ffi.Pointer>? _ffiInitializeApiDlPtr; bool _apiDlInitialized = false; -/// Initialize the Dart API DL for FFI event notifications -/// This must be called before registering the event port void ffiInitializeApiDL() { if (_apiDlInitialized) return; @@ -1636,7 +934,6 @@ void ffiInitializeApiDL() { 'ffi_initialize_api_dl'); if (_ffiInitializeApiDlPtr != null) { - // Pass NativeApi.initializeApiDLData to the native side _ffiInitializeApiDlPtr! .cast>() .asFunction)>()( @@ -1649,44 +946,30 @@ void ffiInitializeApiDL() { } } -/// Extension to get the native port number from RawReceivePort extension RawReceivePortNativePort on RawReceivePort { - /// Returns the native port number that can be used with Dart_PostCObject_DL int get nativePort => _rawReceivePortNativePort(this); } -/// Extension to get the native port number from ReceivePort extension ReceivePortNativePort on ReceivePort { - /// Returns the native port number that can be used with Dart_PostCObject_DL int get nativePort => _receivePortNativePort(this); } -// External function to get native port from RawReceivePort -// This uses the private _RawReceivePortImpl class internals @pragma('vm:never-inline') int _rawReceivePortNativePort(RawReceivePort port) { - // Access the sendPort's nativePort through the port's internal field - // RawReceivePort has a sendPort property that exposes nativePort return port.sendPort.nativePort; } -// External function to get native port from ReceivePort @pragma('vm:never-inline') int _receivePortNativePort(ReceivePort port) { - // Access the sendPort's nativePort through the port's internal field return port.sendPort.nativePort; } -/// FFI register_event_port function - registers Dart port for event notifications -/// The port is used with Dart_PostCObject_DL to send events to Dart isolate typedef _FFIRegisterEventPortNative = ffi.Void Function(ffi.Int64); typedef _FFIRegisterEventPortDart = void Function(int); -/// FFI unregister_event_port function - unregisters the Dart port typedef _FFIUnregisterEventPortNative = ffi.Void Function(); typedef _FFIUnregisterEventPortDart = void Function(); -// Global static variables for FFI event port bindings ffi.Pointer>? _ffiRegisterEventPortPtr; ffi.Pointer>? @@ -1712,8 +995,6 @@ void _loadEventPortBindings(ffi.DynamicLibrary? lib) { } } -/// Register FFI event port for event notifications using Dart_PostCObject_DL -/// This function is exported for use in video_player_tizen.dart void ffiRegisterEventPort(int port) { if (!_eventPortLoaded) { _loadEventPortBindings(VideoPlayerFFIBindings.instance._lib); @@ -1725,8 +1006,6 @@ void ffiRegisterEventPort(int port) { } } -/// Unregister FFI event port -/// This function is exported for use in video_player_tizen.dart void ffiUnregisterEventPort() { if (_eventPortLoaded && _ffiUnregisterEventPortPtr != null) { _ffiUnregisterEventPortPtr! diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index 946140ab7..eeee95335 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -10,7 +10,7 @@ import 'dart:isolate' show RawReceivePort; import 'package:flutter/widgets.dart'; import '../video_player_platform_interface.dart'; -import 'messages.g.dart'; +import 'ffi_messages.g.dart'; import 'tracks.dart'; /// An implementation of [VideoPlayerPlatform] that uses FFI for all methods. diff --git a/packages/video_player_videohole/tizen/src/ffi_messages.h b/packages/video_player_videohole/tizen/src/ffi_messages.h new file mode 100644 index 000000000..171423ffb --- /dev/null +++ b/packages/video_player_videohole/tizen/src/ffi_messages.h @@ -0,0 +1,359 @@ +// Copyright 2023 Samsung Electronics Co., Ltd. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +// FFI API header for video_player_tizen +// This file contains all FFI function declarations and message types + +#ifndef FFI_MESSAGES_H_ +#define FFI_MESSAGES_H_ + +#include +#include + +#include +#include +#include +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +// ===== FFI function declarations ===== + +int ffi_initialize(); +int64_t ffi_create(const char* create_message_json); +int ffi_dispose(int64_t player_id); +int ffi_play(int64_t player_id); +int ffi_pause(int64_t player_id); +int ffi_seek_to(int64_t player_id, int64_t position_ms); +int64_t ffi_get_position(int64_t player_id); +const char* ffi_get_duration(int64_t player_id); +int ffi_set_volume(int64_t player_id, double volume); +int ffi_set_playback_speed(int64_t player_id, double speed); +int ffi_set_looping(int64_t player_id, bool is_looping); +const char* ffi_get_track_info(int64_t player_id, const char* track_type); +int ffi_set_track_selection(int64_t player_id, int64_t track_id, + const char* track_type); +int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, + int32_t width, int32_t height); +int ffi_set_display_rotate(int64_t player_id, int32_t rotation); +int ffi_suspend(int64_t player_id); +int ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time); +int ffi_set_activate(int64_t player_id); +int ffi_set_deactivate(int64_t player_id); +int ffi_set_mix_with_others(bool mix_with_others); + +// FFI event port functions +int ffi_initialize_api_dl(void* data); +void ffi_register_event_port(int64_t port); +void ffi_unregister_event_port(); + +#ifdef __cplusplus +} // extern "C" + +// ===== Message types for C++ usage ===== + +namespace video_player_videohole_tizen { + +// Error type +class FlutterError { + public: + explicit FlutterError(const std::string& code) : code_(code) {} + explicit FlutterError(const std::string& code, const std::string& message) + : code_(code), message_(message) {} + explicit FlutterError(const std::string& code, const std::string& message, + const flutter::EncodableValue& details) + : code_(code), message_(message), details_(details) {} + + const std::string& code() const { return code_; } + const std::string& message() const { return message_; } + const flutter::EncodableValue& details() const { return details_; } + + private: + std::string code_; + std::string message_; + flutter::EncodableValue details_; +}; + +// ErrorOr template type +template +class ErrorOr { + public: + ErrorOr(const T& rhs) : v_(rhs) {} + ErrorOr(const T&& rhs) : v_(std::move(rhs)) {} + ErrorOr(const FlutterError& rhs) : v_(rhs) {} + ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} + + bool has_error() const { return std::holds_alternative(v_); } + const T& value() const { return std::get(v_); }; + const FlutterError& error() const { return std::get(v_); }; + + private: + friend class VideoPlayerVideoholeApi; + ErrorOr() = default; + T TakeValue() && { return std::get(std::move(v_)); } + + std::variant v_; +}; + +// PlayerMessage - player identifier +class PlayerMessage { + public: + explicit PlayerMessage(int64_t id) : player_id_(id) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + private: + int64_t player_id_; +}; + +// LoopingMessage - looping state +class LoopingMessage { + public: + LoopingMessage(int64_t id, bool looping) + : player_id_(id), is_looping_(looping) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + bool is_looping() const { return is_looping_; } + void set_is_looping(bool value) { is_looping_ = value; } + + private: + int64_t player_id_; + bool is_looping_; +}; + +// VolumeMessage - volume level +class VolumeMessage { + public: + VolumeMessage(int64_t id, double vol) : player_id_(id), volume_(vol) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + double volume() const { return volume_; } + void set_volume(double value) { volume_ = value; } + + private: + int64_t player_id_; + double volume_; +}; + +// PlaybackSpeedMessage - playback speed +class PlaybackSpeedMessage { + public: + PlaybackSpeedMessage(int64_t id, double speed) + : player_id_(id), speed_(speed) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + double speed() const { return speed_; } + void set_speed(double value) { speed_ = value; } + + private: + int64_t player_id_; + double speed_; +}; + +// TrackMessage - track information +class TrackMessage { + public: + TrackMessage(int64_t id, const flutter::EncodableList& tracks) + : player_id_(id), tracks_(tracks) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + const flutter::EncodableList& tracks() const { return tracks_; } + void set_tracks(const flutter::EncodableList& value) { tracks_ = value; } + + private: + int64_t player_id_; + flutter::EncodableList tracks_; +}; + +// TrackTypeMessage - track type identifier +class TrackTypeMessage { + public: + TrackTypeMessage(int64_t id, const std::string& type) + : player_id_(id), track_type_(type) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + const std::string& track_type() const { return track_type_; } + void set_track_type(const std::string& value) { track_type_ = value; } + + private: + int64_t player_id_; + std::string track_type_; +}; + +// SelectedTracksMessage - selected track info +class SelectedTracksMessage { + public: + SelectedTracksMessage(int64_t id, int64_t track_id, const std::string& type) + : player_id_(id), track_id_(track_id), track_type_(type) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + int64_t track_id() const { return track_id_; } + void set_track_id(int64_t value) { track_id_ = value; } + + const std::string& track_type() const { return track_type_; } + void set_track_type(const std::string& value) { track_type_ = value; } + + private: + int64_t player_id_; + int64_t track_id_; + std::string track_type_; +}; + +// PositionMessage - playback position +class PositionMessage { + public: + PositionMessage(int64_t id, int64_t pos) : player_id_(id), position_(pos) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + int64_t position() const { return position_; } + void set_position(int64_t value) { position_ = value; } + + private: + int64_t player_id_; + int64_t position_; +}; + +// DurationMessage - duration range +class DurationMessage { + public: + explicit DurationMessage(int64_t id) : player_id_(id) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + const std::optional& duration_range() const { + return duration_range_; + } + void set_duration_range(const flutter::EncodableList& value) { + duration_range_ = value; + } + + private: + int64_t player_id_; + std::optional duration_range_; +}; + +// GeometryMessage - display geometry (ROI) +class GeometryMessage { + public: + GeometryMessage(int64_t id, int32_t x, int32_t y, int32_t w, int32_t h) + : player_id_(id), x_(x), y_(y), width_(w), height_(h) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + int32_t x() const { return x_; } + void set_x(int32_t value) { x_ = value; } + + int32_t y() const { return y_; } + void set_y(int32_t value) { y_ = value; } + + int32_t width() const { return width_; } + void set_width(int32_t value) { width_ = value; } + + int32_t height() const { return height_; } + void set_height(int32_t value) { height_ = value; } + + private: + int64_t player_id_; + int32_t x_, y_, width_, height_; +}; + +// RotationMessage - display rotation +class RotationMessage { + public: + RotationMessage(int64_t id, int32_t r) : player_id_(id), rotation_(r) {} + + int64_t player_id() const { return player_id_; } + void set_player_id(int64_t value) { player_id_ = value; } + + int32_t rotation() const { return rotation_; } + void set_rotation(int32_t value) { rotation_ = value; } + + private: + int64_t player_id_; + int32_t rotation_; +}; + +// MixWithOthersMessage - mix with others setting +class MixWithOthersMessage { + public: + explicit MixWithOthersMessage(bool m) : mix_with_others_(m) {} + + bool mix_with_others() const { return mix_with_others_; } + void set_mix_with_others(bool value) { mix_with_others_ = value; } + + private: + bool mix_with_others_; +}; + +// CreateMessage - player creation parameters +class CreateMessage { + public: + CreateMessage() = default; + + const std::optional& asset() const { return asset_; } + void set_asset(const std::string& value) { asset_ = value; } + + const std::optional& uri() const { return uri_; } + void set_uri(const std::string& value) { uri_ = value; } + + const std::optional& package_name() const { + return package_name_; + } + void set_package_name(const std::string& value) { package_name_ = value; } + + const std::optional& format_hint() const { return format_hint_; } + void set_format_hint(const std::string& value) { format_hint_ = value; } + + const flutter::EncodableMap& http_headers() const { return http_headers_; } + void set_http_headers(const flutter::EncodableMap& value) { + http_headers_ = value; + } + + const flutter::EncodableMap& drm_configs() const { return drm_configs_; } + void set_drm_configs(const flutter::EncodableMap& value) { + drm_configs_ = value; + } + + const flutter::EncodableMap& player_options() const { + return player_options_; + } + void set_player_options(const flutter::EncodableMap& value) { + player_options_ = value; + } + + private: + std::optional asset_; + std::optional uri_; + std::optional package_name_; + std::optional format_hint_; + flutter::EncodableMap http_headers_; + flutter::EncodableMap drm_configs_; + flutter::EncodableMap player_options_; +}; + +} // namespace video_player_videohole_tizen + +#endif // __cplusplus +#endif // FFI_MESSAGES_H_ diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 523c21f04..91f2fbcf8 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -93,8 +93,13 @@ int64_t MediaPlayer::Create(const std::string &uri, return -1; } - std::string cookie = flutter_common::GetValue(create_message.http_headers(), - "Cookie", std::string()); + const auto &http_headers = create_message.http_headers(); + auto cookie_it = http_headers.find(flutter::EncodableValue("Cookie")); + std::string cookie; + if (cookie_it != http_headers.end() && + std::holds_alternative(cookie_it->second)) { + cookie = std::get(cookie_it->second); + } if (!cookie.empty()) { int ret = player_set_streaming_cookie(player_, cookie.c_str(), cookie.size()); @@ -103,8 +108,12 @@ int64_t MediaPlayer::Create(const std::string &uri, get_error_message(ret)); } } - std::string user_agent = flutter_common::GetValue( - create_message.http_headers(), "User-Agent", std::string()); + auto user_agent_it = http_headers.find(flutter::EncodableValue("User-Agent")); + std::string user_agent; + if (user_agent_it != http_headers.end() && + std::holds_alternative(user_agent_it->second)) { + user_agent = std::get(user_agent_it->second); + } if (!user_agent.empty()) { int ret = player_set_streaming_user_agent(player_, user_agent.c_str(), user_agent.size()); @@ -114,16 +123,23 @@ int64_t MediaPlayer::Create(const std::string &uri, } } - auto drm_configs_ptr = create_message.drm_configs(); - if (drm_configs_ptr != nullptr) { + const auto &drm_configs = create_message.drm_configs(); + if (!drm_configs.empty()) { LOG_INFO("[MediaPlayer] drm_configs is present."); - // Must use 0LL (int64_t literal) instead of 0 (int literal) for proper type - // matching - int64_t drm_type = - flutter_common::GetValue(drm_configs_ptr, "drmType", 0LL); - std::string license_server_url = flutter_common::GetValue( - drm_configs_ptr, "licenseServerUrl", std::string()); + int64_t drm_type = 0; + std::string license_server_url; + auto drm_type_it = drm_configs.find(flutter::EncodableValue("drmType")); + if (drm_type_it != drm_configs.end() && + std::holds_alternative(drm_type_it->second)) { + drm_type = std::get(drm_type_it->second); + } + auto license_it = + drm_configs.find(flutter::EncodableValue("licenseServerUrl")); + if (license_it != drm_configs.end() && + std::holds_alternative(license_it->second)) { + license_server_url = std::get(license_it->second); + } LOG_INFO("[MediaPlayer] drm_type=%lld, license_server_url=%s", static_cast(drm_type), license_server_url.c_str()); diff --git a/packages/video_player_videohole/tizen/src/messages.cc b/packages/video_player_videohole/tizen/src/messages.cc deleted file mode 100644 index 5e1eb0a9c..000000000 --- a/packages/video_player_videohole/tizen/src/messages.cc +++ /dev/null @@ -1,1479 +0,0 @@ -// Autogenerated from Pigeon (v10.1.6), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#undef _HAS_EXCEPTIONS - -#include "messages.h" - -#include -#include -#include -#include - -#include -#include -#include - -namespace video_player_videohole_tizen { -using flutter::BasicMessageChannel; -using flutter::CustomEncodableValue; -using flutter::EncodableList; -using flutter::EncodableMap; -using flutter::EncodableValue; - -// PlayerMessage - -PlayerMessage::PlayerMessage(int64_t player_id) : player_id_(player_id) {} - -int64_t PlayerMessage::player_id() const { return player_id_; } - -void PlayerMessage::set_player_id(int64_t value_arg) { player_id_ = value_arg; } - -EncodableList PlayerMessage::ToEncodableList() const { - EncodableList list; - list.reserve(1); - list.push_back(EncodableValue(player_id_)); - return list; -} - -PlayerMessage PlayerMessage::FromEncodableList(const EncodableList& list) { - PlayerMessage decoded(list[0].LongValue()); - return decoded; -} - -// LoopingMessage - -LoopingMessage::LoopingMessage(int64_t player_id, bool is_looping) - : player_id_(player_id), is_looping_(is_looping) {} - -int64_t LoopingMessage::player_id() const { return player_id_; } - -void LoopingMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -bool LoopingMessage::is_looping() const { return is_looping_; } - -void LoopingMessage::set_is_looping(bool value_arg) { is_looping_ = value_arg; } - -EncodableList LoopingMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(is_looping_)); - return list; -} - -LoopingMessage LoopingMessage::FromEncodableList(const EncodableList& list) { - LoopingMessage decoded(list[0].LongValue(), std::get(list[1])); - return decoded; -} - -// VolumeMessage - -VolumeMessage::VolumeMessage(int64_t player_id, double volume) - : player_id_(player_id), volume_(volume) {} - -int64_t VolumeMessage::player_id() const { return player_id_; } - -void VolumeMessage::set_player_id(int64_t value_arg) { player_id_ = value_arg; } - -double VolumeMessage::volume() const { return volume_; } - -void VolumeMessage::set_volume(double value_arg) { volume_ = value_arg; } - -EncodableList VolumeMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(volume_)); - return list; -} - -VolumeMessage VolumeMessage::FromEncodableList(const EncodableList& list) { - VolumeMessage decoded(list[0].LongValue(), std::get(list[1])); - return decoded; -} - -// PlaybackSpeedMessage - -PlaybackSpeedMessage::PlaybackSpeedMessage(int64_t player_id, double speed) - : player_id_(player_id), speed_(speed) {} - -int64_t PlaybackSpeedMessage::player_id() const { return player_id_; } - -void PlaybackSpeedMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -double PlaybackSpeedMessage::speed() const { return speed_; } - -void PlaybackSpeedMessage::set_speed(double value_arg) { speed_ = value_arg; } - -EncodableList PlaybackSpeedMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(speed_)); - return list; -} - -PlaybackSpeedMessage PlaybackSpeedMessage::FromEncodableList( - const EncodableList& list) { - PlaybackSpeedMessage decoded(list[0].LongValue(), std::get(list[1])); - return decoded; -} - -// TrackMessage - -TrackMessage::TrackMessage(int64_t player_id, const EncodableList& tracks) - : player_id_(player_id), tracks_(tracks) {} - -int64_t TrackMessage::player_id() const { return player_id_; } - -void TrackMessage::set_player_id(int64_t value_arg) { player_id_ = value_arg; } - -const EncodableList& TrackMessage::tracks() const { return tracks_; } - -void TrackMessage::set_tracks(const EncodableList& value_arg) { - tracks_ = value_arg; -} - -EncodableList TrackMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(tracks_)); - return list; -} - -TrackMessage TrackMessage::FromEncodableList(const EncodableList& list) { - TrackMessage decoded(list[0].LongValue(), std::get(list[1])); - return decoded; -} - -// TrackTypeMessage - -TrackTypeMessage::TrackTypeMessage(int64_t player_id, - const std::string& track_type) - : player_id_(player_id), track_type_(track_type) {} - -int64_t TrackTypeMessage::player_id() const { return player_id_; } - -void TrackTypeMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -const std::string& TrackTypeMessage::track_type() const { return track_type_; } - -void TrackTypeMessage::set_track_type(std::string_view value_arg) { - track_type_ = value_arg; -} - -EncodableList TrackTypeMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(track_type_)); - return list; -} - -TrackTypeMessage TrackTypeMessage::FromEncodableList( - const EncodableList& list) { - TrackTypeMessage decoded(list[0].LongValue(), std::get(list[1])); - return decoded; -} - -// SelectedTracksMessage - -SelectedTracksMessage::SelectedTracksMessage(int64_t player_id, - int64_t track_id, - const std::string& track_type) - : player_id_(player_id), track_id_(track_id), track_type_(track_type) {} - -int64_t SelectedTracksMessage::player_id() const { return player_id_; } - -void SelectedTracksMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -int64_t SelectedTracksMessage::track_id() const { return track_id_; } - -void SelectedTracksMessage::set_track_id(int64_t value_arg) { - track_id_ = value_arg; -} - -const std::string& SelectedTracksMessage::track_type() const { - return track_type_; -} - -void SelectedTracksMessage::set_track_type(std::string_view value_arg) { - track_type_ = value_arg; -} - -EncodableList SelectedTracksMessage::ToEncodableList() const { - EncodableList list; - list.reserve(3); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(track_id_)); - list.push_back(EncodableValue(track_type_)); - return list; -} - -SelectedTracksMessage SelectedTracksMessage::FromEncodableList( - const EncodableList& list) { - SelectedTracksMessage decoded(list[0].LongValue(), list[1].LongValue(), - std::get(list[2])); - return decoded; -} - -// PositionMessage - -PositionMessage::PositionMessage(int64_t player_id, int64_t position) - : player_id_(player_id), position_(position) {} - -int64_t PositionMessage::player_id() const { return player_id_; } - -void PositionMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -int64_t PositionMessage::position() const { return position_; } - -void PositionMessage::set_position(int64_t value_arg) { position_ = value_arg; } - -EncodableList PositionMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(position_)); - return list; -} - -PositionMessage PositionMessage::FromEncodableList(const EncodableList& list) { - PositionMessage decoded(list[0].LongValue(), list[1].LongValue()); - return decoded; -} - -// CreateMessage - -CreateMessage::CreateMessage() {} - -CreateMessage::CreateMessage(const std::string* asset, const std::string* uri, - const std::string* package_name, - const std::string* format_hint, - const EncodableMap* http_headers, - const EncodableMap* drm_configs, - const EncodableMap* player_options) - : asset_(asset ? std::optional(*asset) : std::nullopt), - uri_(uri ? std::optional(*uri) : std::nullopt), - package_name_(package_name ? std::optional(*package_name) - : std::nullopt), - format_hint_(format_hint ? std::optional(*format_hint) - : std::nullopt), - http_headers_(http_headers ? std::optional(*http_headers) - : std::nullopt), - drm_configs_(drm_configs ? std::optional(*drm_configs) - : std::nullopt), - player_options_(player_options - ? std::optional(*player_options) - : std::nullopt) {} - -const std::string* CreateMessage::asset() const { - return asset_ ? &(*asset_) : nullptr; -} - -void CreateMessage::set_asset(const std::string_view* value_arg) { - asset_ = value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_asset(std::string_view value_arg) { - asset_ = value_arg; -} - -const std::string* CreateMessage::uri() const { - return uri_ ? &(*uri_) : nullptr; -} - -void CreateMessage::set_uri(const std::string_view* value_arg) { - uri_ = value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_uri(std::string_view value_arg) { uri_ = value_arg; } - -const std::string* CreateMessage::package_name() const { - return package_name_ ? &(*package_name_) : nullptr; -} - -void CreateMessage::set_package_name(const std::string_view* value_arg) { - package_name_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_package_name(std::string_view value_arg) { - package_name_ = value_arg; -} - -const std::string* CreateMessage::format_hint() const { - return format_hint_ ? &(*format_hint_) : nullptr; -} - -void CreateMessage::set_format_hint(const std::string_view* value_arg) { - format_hint_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_format_hint(std::string_view value_arg) { - format_hint_ = value_arg; -} - -const EncodableMap* CreateMessage::http_headers() const { - return http_headers_ ? &(*http_headers_) : nullptr; -} - -void CreateMessage::set_http_headers(const EncodableMap* value_arg) { - http_headers_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_http_headers(const EncodableMap& value_arg) { - http_headers_ = value_arg; -} - -const EncodableMap* CreateMessage::drm_configs() const { - return drm_configs_ ? &(*drm_configs_) : nullptr; -} - -void CreateMessage::set_drm_configs(const EncodableMap* value_arg) { - drm_configs_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_drm_configs(const EncodableMap& value_arg) { - drm_configs_ = value_arg; -} - -const EncodableMap* CreateMessage::player_options() const { - return player_options_ ? &(*player_options_) : nullptr; -} - -void CreateMessage::set_player_options(const EncodableMap* value_arg) { - player_options_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void CreateMessage::set_player_options(const EncodableMap& value_arg) { - player_options_ = value_arg; -} - -EncodableList CreateMessage::ToEncodableList() const { - EncodableList list; - list.reserve(7); - list.push_back(asset_ ? EncodableValue(*asset_) : EncodableValue()); - list.push_back(uri_ ? EncodableValue(*uri_) : EncodableValue()); - list.push_back(package_name_ ? EncodableValue(*package_name_) - : EncodableValue()); - list.push_back(format_hint_ ? EncodableValue(*format_hint_) - : EncodableValue()); - list.push_back(http_headers_ ? EncodableValue(*http_headers_) - : EncodableValue()); - list.push_back(drm_configs_ ? EncodableValue(*drm_configs_) - : EncodableValue()); - list.push_back(player_options_ ? EncodableValue(*player_options_) - : EncodableValue()); - return list; -} - -CreateMessage CreateMessage::FromEncodableList(const EncodableList& list) { - CreateMessage decoded; - auto& encodable_asset = list[0]; - if (!encodable_asset.IsNull()) { - decoded.set_asset(std::get(encodable_asset)); - } - auto& encodable_uri = list[1]; - if (!encodable_uri.IsNull()) { - decoded.set_uri(std::get(encodable_uri)); - } - auto& encodable_package_name = list[2]; - if (!encodable_package_name.IsNull()) { - decoded.set_package_name(std::get(encodable_package_name)); - } - auto& encodable_format_hint = list[3]; - if (!encodable_format_hint.IsNull()) { - decoded.set_format_hint(std::get(encodable_format_hint)); - } - auto& encodable_http_headers = list[4]; - if (!encodable_http_headers.IsNull()) { - decoded.set_http_headers(std::get(encodable_http_headers)); - } - auto& encodable_drm_configs = list[5]; - if (!encodable_drm_configs.IsNull()) { - decoded.set_drm_configs(std::get(encodable_drm_configs)); - } - auto& encodable_player_options = list[6]; - if (!encodable_player_options.IsNull()) { - decoded.set_player_options( - std::get(encodable_player_options)); - } - return decoded; -} - -// MixWithOthersMessage - -MixWithOthersMessage::MixWithOthersMessage(bool mix_with_others) - : mix_with_others_(mix_with_others) {} - -bool MixWithOthersMessage::mix_with_others() const { return mix_with_others_; } - -void MixWithOthersMessage::set_mix_with_others(bool value_arg) { - mix_with_others_ = value_arg; -} - -EncodableList MixWithOthersMessage::ToEncodableList() const { - EncodableList list; - list.reserve(1); - list.push_back(EncodableValue(mix_with_others_)); - return list; -} - -MixWithOthersMessage MixWithOthersMessage::FromEncodableList( - const EncodableList& list) { - MixWithOthersMessage decoded(std::get(list[0])); - return decoded; -} - -// GeometryMessage - -GeometryMessage::GeometryMessage(int64_t player_id, int64_t x, int64_t y, - int64_t width, int64_t height) - : player_id_(player_id), x_(x), y_(y), width_(width), height_(height) {} - -int64_t GeometryMessage::player_id() const { return player_id_; } - -void GeometryMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -int64_t GeometryMessage::x() const { return x_; } - -void GeometryMessage::set_x(int64_t value_arg) { x_ = value_arg; } - -int64_t GeometryMessage::y() const { return y_; } - -void GeometryMessage::set_y(int64_t value_arg) { y_ = value_arg; } - -int64_t GeometryMessage::width() const { return width_; } - -void GeometryMessage::set_width(int64_t value_arg) { width_ = value_arg; } - -int64_t GeometryMessage::height() const { return height_; } - -void GeometryMessage::set_height(int64_t value_arg) { height_ = value_arg; } - -EncodableList GeometryMessage::ToEncodableList() const { - EncodableList list; - list.reserve(5); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(x_)); - list.push_back(EncodableValue(y_)); - list.push_back(EncodableValue(width_)); - list.push_back(EncodableValue(height_)); - return list; -} - -GeometryMessage GeometryMessage::FromEncodableList(const EncodableList& list) { - GeometryMessage decoded(list[0].LongValue(), list[1].LongValue(), - list[2].LongValue(), list[3].LongValue(), - list[4].LongValue()); - return decoded; -} - -// DurationMessage - -DurationMessage::DurationMessage(int64_t player_id) : player_id_(player_id) {} - -DurationMessage::DurationMessage(int64_t player_id, - const EncodableList* duration_range) - : player_id_(player_id), - duration_range_(duration_range - ? std::optional(*duration_range) - : std::nullopt) {} - -int64_t DurationMessage::player_id() const { return player_id_; } - -void DurationMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -const EncodableList* DurationMessage::duration_range() const { - return duration_range_ ? &(*duration_range_) : nullptr; -} - -void DurationMessage::set_duration_range(const EncodableList* value_arg) { - duration_range_ = - value_arg ? std::optional(*value_arg) : std::nullopt; -} - -void DurationMessage::set_duration_range(const EncodableList& value_arg) { - duration_range_ = value_arg; -} - -EncodableList DurationMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(duration_range_ ? EncodableValue(*duration_range_) - : EncodableValue()); - return list; -} - -DurationMessage DurationMessage::FromEncodableList(const EncodableList& list) { - DurationMessage decoded(list[0].LongValue()); - auto& encodable_duration_range = list[1]; - if (!encodable_duration_range.IsNull()) { - decoded.set_duration_range( - std::get(encodable_duration_range)); - } - return decoded; -} - -// RotationMessage - -RotationMessage::RotationMessage(int64_t player_id, int64_t rotation) - : player_id_(player_id), rotation_(rotation) {} - -int64_t RotationMessage::player_id() const { return player_id_; } - -void RotationMessage::set_player_id(int64_t value_arg) { - player_id_ = value_arg; -} - -int64_t RotationMessage::rotation() const { return rotation_; } - -void RotationMessage::set_rotation(int64_t value_arg) { rotation_ = value_arg; } - -EncodableList RotationMessage::ToEncodableList() const { - EncodableList list; - list.reserve(2); - list.push_back(EncodableValue(player_id_)); - list.push_back(EncodableValue(rotation_)); - return list; -} - -RotationMessage RotationMessage::FromEncodableList(const EncodableList& list) { - RotationMessage decoded(list[0].LongValue(), list[1].LongValue()); - return decoded; -} - -VideoPlayerVideoholeApiCodecSerializer:: - VideoPlayerVideoholeApiCodecSerializer() {} - -EncodableValue VideoPlayerVideoholeApiCodecSerializer::ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const { - switch (type) { - case 128: - return CustomEncodableValue(CreateMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 129: - return CustomEncodableValue(CreateMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 130: - return CustomEncodableValue(DurationMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 131: - return CustomEncodableValue(GeometryMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 132: - return CustomEncodableValue(LoopingMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 133: - return CustomEncodableValue(MixWithOthersMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 134: - return CustomEncodableValue(PlaybackSpeedMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 135: - return CustomEncodableValue(PlayerMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 136: - return CustomEncodableValue(PositionMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 137: - return CustomEncodableValue(RotationMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 138: - return CustomEncodableValue(SelectedTracksMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 139: - return CustomEncodableValue(TrackMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 140: - return CustomEncodableValue(TrackTypeMessage::FromEncodableList( - std::get(ReadValue(stream)))); - case 141: - return CustomEncodableValue(VolumeMessage::FromEncodableList( - std::get(ReadValue(stream)))); - default: - return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); - } -} - -void VideoPlayerVideoholeApiCodecSerializer::WriteValue( - const EncodableValue& value, flutter::ByteStreamWriter* stream) const { - if (const CustomEncodableValue* custom_value = - std::get_if(&value)) { - if (custom_value->type() == typeid(CreateMessage)) { - stream->WriteByte(128); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(CreateMessage)) { - stream->WriteByte(129); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(DurationMessage)) { - stream->WriteByte(130); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(GeometryMessage)) { - stream->WriteByte(131); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(LoopingMessage)) { - stream->WriteByte(132); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(MixWithOthersMessage)) { - stream->WriteByte(133); - WriteValue( - EncodableValue(std::any_cast(*custom_value) - .ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(PlaybackSpeedMessage)) { - stream->WriteByte(134); - WriteValue( - EncodableValue(std::any_cast(*custom_value) - .ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(PlayerMessage)) { - stream->WriteByte(135); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(PositionMessage)) { - stream->WriteByte(136); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(RotationMessage)) { - stream->WriteByte(137); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(SelectedTracksMessage)) { - stream->WriteByte(138); - WriteValue( - EncodableValue(std::any_cast(*custom_value) - .ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(TrackMessage)) { - stream->WriteByte(139); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(TrackTypeMessage)) { - stream->WriteByte(140); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - if (custom_value->type() == typeid(VolumeMessage)) { - stream->WriteByte(141); - WriteValue( - EncodableValue( - std::any_cast(*custom_value).ToEncodableList()), - stream); - return; - } - } - flutter::StandardCodecSerializer::WriteValue(value, stream); -} - -/// The codec used by VideoPlayerVideoholeApi. -const flutter::StandardMessageCodec& VideoPlayerVideoholeApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance( - &VideoPlayerVideoholeApiCodecSerializer::GetInstance()); -} - -// VideoPlayerVideoholeApi::SetUp() removed - all methods migrated to FFI -// This function is no longer needed -void VideoPlayerVideoholeApi::SetUp(flutter::BinaryMessenger* binary_messenger, - VideoPlayerVideoholeApi* api) { - // No-op: all methods migrated to FFI - (void)binary_messenger; - (void)api; - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "initialize", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - std::optional output = api->Initialize(); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "create", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->Create(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back( - CustomEncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "dispose", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = api->Dispose(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setLooping", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = api->SetLooping(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setVolume", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = api->SetVolume(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setPlaybackSpeed", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = - api->SetPlaybackSpeed(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "play", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = api->Play(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setDeactivate", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->SetDeactivate(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setActivate", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->SetActivate(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "track", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->Track(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back( - CustomEncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setTrackSelection", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->SetTrackSelection(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "position", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->Position(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back( - CustomEncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "seekTo", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - api->SeekTo(msg_arg, - [reply](std::optional&& output) { - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - }); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "pause", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = api->Pause(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setMixWithOthers", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = - api->SetMixWithOthers(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setDisplayGeometry", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - std::optional output = - api->SetDisplayGeometry(msg_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "duration", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->Duration(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back( - CustomEncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "suspend", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_player_id_arg = args.at(0); - if (encodable_player_id_arg.IsNull()) { - reply(WrapError("player_id_arg unexpectedly null.")); - return; - } - const int64_t player_id_arg = encodable_player_id_arg.LongValue(); - std::optional output = api->Suspend(player_id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "restore", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_player_id_arg = args.at(0); - if (encodable_player_id_arg.IsNull()) { - reply(WrapError("player_id_arg unexpectedly null.")); - return; - } - const int64_t player_id_arg = encodable_player_id_arg.LongValue(); - const auto& encodable_msg_arg = args.at(1); - const auto* msg_arg = &(std::any_cast( - std::get(encodable_msg_arg))); - const auto& encodable_resume_time_arg = args.at(2); - if (encodable_resume_time_arg.IsNull()) { - reply(WrapError("resume_time_arg unexpectedly null.")); - return; - } - const int64_t resume_time_arg = - encodable_resume_time_arg.LongValue(); - std::optional output = - api->Restore(player_id_arg, msg_arg, resume_time_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue()); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } - { - auto channel = std::make_unique>( - binary_messenger, - "dev.flutter.pigeon.video_player_videohole.VideoPlayerVideoholeApi." - "setDisplayRotate", - &GetCodec()); - if (api != nullptr) { - channel->SetMessageHandler( - [api](const EncodableValue& message, - const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_msg_arg = args.at(0); - if (encodable_msg_arg.IsNull()) { - reply(WrapError("msg_arg unexpectedly null.")); - return; - } - const auto& msg_arg = std::any_cast( - std::get(encodable_msg_arg)); - ErrorOr output = api->SetDisplayRotate(msg_arg); - if (output.has_error()) { - reply(WrapError(output.error())); - return; - } - EncodableList wrapped; - wrapped.push_back(EncodableValue(std::move(output).TakeValue())); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel->SetMessageHandler(nullptr); - } - } -} - -EncodableValue VideoPlayerVideoholeApi::WrapError( - std::string_view error_message) { - return EncodableValue( - EncodableList{EncodableValue(std::string(error_message)), - EncodableValue("Error"), EncodableValue()}); -} - -EncodableValue VideoPlayerVideoholeApi::WrapError(const FlutterError& error) { - return EncodableValue(EncodableList{EncodableValue(error.code()), - EncodableValue(error.message()), - error.details()}); -} - -} // namespace video_player_videohole_tizen diff --git a/packages/video_player_videohole/tizen/src/messages.h b/packages/video_player_videohole/tizen/src/messages.h deleted file mode 100644 index c1fa8fe6c..000000000 --- a/packages/video_player_videohole/tizen/src/messages.h +++ /dev/null @@ -1,544 +0,0 @@ -// Autogenerated from Pigeon (v10.1.6), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#ifndef PIGEON_MESSAGES_H_ -#define PIGEON_MESSAGES_H_ -#include -#include -#include -#include - -#include -#include -#include - -namespace video_player_videohole_tizen { - -// Generated class from Pigeon. - -class FlutterError { - public: - explicit FlutterError(const std::string& code) : code_(code) {} - explicit FlutterError(const std::string& code, const std::string& message) - : code_(code), message_(message) {} - explicit FlutterError(const std::string& code, const std::string& message, - const flutter::EncodableValue& details) - : code_(code), message_(message), details_(details) {} - - const std::string& code() const { return code_; } - const std::string& message() const { return message_; } - const flutter::EncodableValue& details() const { return details_; } - - private: - std::string code_; - std::string message_; - flutter::EncodableValue details_; -}; - -template -class ErrorOr { - public: - ErrorOr(const T& rhs) : v_(rhs) {} - ErrorOr(const T&& rhs) : v_(std::move(rhs)) {} - ErrorOr(const FlutterError& rhs) : v_(rhs) {} - ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} - - bool has_error() const { return std::holds_alternative(v_); } - const T& value() const { return std::get(v_); }; - const FlutterError& error() const { return std::get(v_); }; - - private: - friend class VideoPlayerVideoholeApi; - ErrorOr() = default; - T TakeValue() && { return std::get(std::move(v_)); } - - std::variant v_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class PlayerMessage { - public: - // Constructs an object setting all fields. - explicit PlayerMessage(int64_t player_id); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - private: - static PlayerMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class LoopingMessage { - public: - // Constructs an object setting all fields. - explicit LoopingMessage(int64_t player_id, bool is_looping); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - bool is_looping() const; - void set_is_looping(bool value_arg); - - private: - static LoopingMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - bool is_looping_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class VolumeMessage { - public: - // Constructs an object setting all fields. - explicit VolumeMessage(int64_t player_id, double volume); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - double volume() const; - void set_volume(double value_arg); - - private: - static VolumeMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - double volume_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class PlaybackSpeedMessage { - public: - // Constructs an object setting all fields. - explicit PlaybackSpeedMessage(int64_t player_id, double speed); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - double speed() const; - void set_speed(double value_arg); - - private: - static PlaybackSpeedMessage FromEncodableList( - const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - double speed_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class TrackMessage { - public: - // Constructs an object setting all fields. - explicit TrackMessage(int64_t player_id, - const flutter::EncodableList& tracks); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - const flutter::EncodableList& tracks() const; - void set_tracks(const flutter::EncodableList& value_arg); - - private: - static TrackMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - flutter::EncodableList tracks_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class TrackTypeMessage { - public: - // Constructs an object setting all fields. - explicit TrackTypeMessage(int64_t player_id, const std::string& track_type); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - const std::string& track_type() const; - void set_track_type(std::string_view value_arg); - - private: - static TrackTypeMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - std::string track_type_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class SelectedTracksMessage { - public: - // Constructs an object setting all fields. - explicit SelectedTracksMessage(int64_t player_id, int64_t track_id, - const std::string& track_type); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - int64_t track_id() const; - void set_track_id(int64_t value_arg); - - const std::string& track_type() const; - void set_track_type(std::string_view value_arg); - - private: - static SelectedTracksMessage FromEncodableList( - const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - int64_t track_id_; - std::string track_type_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class PositionMessage { - public: - // Constructs an object setting all fields. - explicit PositionMessage(int64_t player_id, int64_t position); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - int64_t position() const; - void set_position(int64_t value_arg); - - private: - static PositionMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - int64_t position_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class CreateMessage { - public: - // Constructs an object setting all non-nullable fields. - CreateMessage(); - - // Constructs an object setting all fields. - explicit CreateMessage(const std::string* asset, const std::string* uri, - const std::string* package_name, - const std::string* format_hint, - const flutter::EncodableMap* http_headers, - const flutter::EncodableMap* drm_configs, - const flutter::EncodableMap* player_options); - - const std::string* asset() const; - void set_asset(const std::string_view* value_arg); - void set_asset(std::string_view value_arg); - - const std::string* uri() const; - void set_uri(const std::string_view* value_arg); - void set_uri(std::string_view value_arg); - - const std::string* package_name() const; - void set_package_name(const std::string_view* value_arg); - void set_package_name(std::string_view value_arg); - - const std::string* format_hint() const; - void set_format_hint(const std::string_view* value_arg); - void set_format_hint(std::string_view value_arg); - - const flutter::EncodableMap* http_headers() const; - void set_http_headers(const flutter::EncodableMap* value_arg); - void set_http_headers(const flutter::EncodableMap& value_arg); - - const flutter::EncodableMap* drm_configs() const; - void set_drm_configs(const flutter::EncodableMap* value_arg); - void set_drm_configs(const flutter::EncodableMap& value_arg); - - const flutter::EncodableMap* player_options() const; - void set_player_options(const flutter::EncodableMap* value_arg); - void set_player_options(const flutter::EncodableMap& value_arg); - - private: - static CreateMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - std::optional asset_; - std::optional uri_; - std::optional package_name_; - std::optional format_hint_; - std::optional http_headers_; - std::optional drm_configs_; - std::optional player_options_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class MixWithOthersMessage { - public: - // Constructs an object setting all fields. - explicit MixWithOthersMessage(bool mix_with_others); - - bool mix_with_others() const; - void set_mix_with_others(bool value_arg); - - private: - static MixWithOthersMessage FromEncodableList( - const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - bool mix_with_others_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class GeometryMessage { - public: - // Constructs an object setting all fields. - explicit GeometryMessage(int64_t player_id, int64_t x, int64_t y, - int64_t width, int64_t height); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - int64_t x() const; - void set_x(int64_t value_arg); - - int64_t y() const; - void set_y(int64_t value_arg); - - int64_t width() const; - void set_width(int64_t value_arg); - - int64_t height() const; - void set_height(int64_t value_arg); - - private: - static GeometryMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - int64_t x_; - int64_t y_; - int64_t width_; - int64_t height_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class DurationMessage { - public: - // Constructs an object setting all non-nullable fields. - explicit DurationMessage(int64_t player_id); - - // Constructs an object setting all fields. - explicit DurationMessage(int64_t player_id, - const flutter::EncodableList* duration_range); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - const flutter::EncodableList* duration_range() const; - void set_duration_range(const flutter::EncodableList* value_arg); - void set_duration_range(const flutter::EncodableList& value_arg); - - private: - static DurationMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - std::optional duration_range_; -}; - -// Generated class from Pigeon that represents data sent in messages. -class RotationMessage { - public: - // Constructs an object setting all fields. - explicit RotationMessage(int64_t player_id, int64_t rotation); - - int64_t player_id() const; - void set_player_id(int64_t value_arg); - - int64_t rotation() const; - void set_rotation(int64_t value_arg); - - private: - static RotationMessage FromEncodableList(const flutter::EncodableList& list); - flutter::EncodableList ToEncodableList() const; - friend class VideoPlayerVideoholeApi; - friend class VideoPlayerVideoholeApiCodecSerializer; - int64_t player_id_; - int64_t rotation_; -}; - -class VideoPlayerVideoholeApiCodecSerializer - : public flutter::StandardCodecSerializer { - public: - VideoPlayerVideoholeApiCodecSerializer(); - inline static VideoPlayerVideoholeApiCodecSerializer& GetInstance() { - static VideoPlayerVideoholeApiCodecSerializer sInstance; - return sInstance; - } - - void WriteValue(const flutter::EncodableValue& value, - flutter::ByteStreamWriter* stream) const override; - - protected: - flutter::EncodableValue ReadValueOfType( - uint8_t type, flutter::ByteStreamReader* stream) const override; -}; - -// Generated interface from Pigeon that represents a handler of messages from -// Flutter. -class VideoPlayerVideoholeApi { - public: - VideoPlayerVideoholeApi(const VideoPlayerVideoholeApi&) = delete; - VideoPlayerVideoholeApi& operator=(const VideoPlayerVideoholeApi&) = delete; - virtual ~VideoPlayerVideoholeApi() {} - virtual std::optional Initialize() = 0; - virtual ErrorOr Create(const CreateMessage& msg) = 0; - virtual std::optional Dispose(const PlayerMessage& msg) = 0; - virtual std::optional SetLooping(const LoopingMessage& msg) = 0; - virtual std::optional SetVolume(const VolumeMessage& msg) = 0; - virtual std::optional SetPlaybackSpeed( - const PlaybackSpeedMessage& msg) = 0; - virtual std::optional Play(const PlayerMessage& msg) = 0; - virtual ErrorOr SetDeactivate(const PlayerMessage& msg) = 0; - virtual ErrorOr SetActivate(const PlayerMessage& msg) = 0; - virtual ErrorOr Track(const TrackTypeMessage& msg) = 0; - virtual ErrorOr SetTrackSelection(const SelectedTracksMessage& msg) = 0; - virtual ErrorOr Position(const PlayerMessage& msg) = 0; - virtual void SeekTo( - const PositionMessage& msg, - std::function reply)> result) = 0; - virtual std::optional Pause(const PlayerMessage& msg) = 0; - virtual std::optional SetMixWithOthers( - const MixWithOthersMessage& msg) = 0; - virtual std::optional SetDisplayGeometry( - const GeometryMessage& msg) = 0; - virtual ErrorOr Duration(const PlayerMessage& msg) = 0; - virtual std::optional Suspend(int64_t player_id) = 0; - virtual std::optional Restore(int64_t player_id, - const CreateMessage* msg, - int64_t resume_time) = 0; - virtual ErrorOr SetDisplayRotate(const RotationMessage& msg) = 0; - - // The codec used by VideoPlayerVideoholeApi. - static const flutter::StandardMessageCodec& GetCodec(); - // Sets up an instance of `VideoPlayerVideoholeApi` to handle messages through - // the `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, - VideoPlayerVideoholeApi* api); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); - - protected: - VideoPlayerVideoholeApi() = default; -}; -} // namespace video_player_videohole_tizen - -// FFI exports for gradual migration -#ifdef __cplusplus -extern "C" { -#endif - -// FFI initialization -int ffi_initialize(); - -// FFI create - returns player_id or -1 on error. -// Parameters: JSON string containing all create parameters. -int64_t ffi_create(const char* create_message_json); - -// FFI dispose - releases player resources -// Returns: 0 on success, -1 on error -int ffi_dispose(int64_t player_id); - -// FFI play - starts or resumes playback -// Returns: 0 on success, -1 on error -int ffi_play(int64_t player_id); - -// FFI pause - pauses playback -// Returns: 0 on success, -1 on error -int ffi_pause(int64_t player_id); - -// FFI seek_to - seeks to a specific position (in milliseconds) -// Returns: 0 on success, -1 on error -int ffi_seek_to(int64_t player_id, int64_t position_ms); - -// FFI get_position - gets current playback position in milliseconds -// Returns: position in milliseconds (>= 0) on success, -1 on error -int64_t ffi_get_position(int64_t player_id); - -// FFI get_duration - gets video duration range in milliseconds -// Returns: JSON string with start and end values, or "-1" on error -// Note: Returns a malloc-allocated string that the caller must free -const char* ffi_get_duration(int64_t player_id); - -// FFI set_volume - sets playback volume (0.0 to 1.0) -// Returns: 0 on success, -1 on error -int ffi_set_volume(int64_t player_id, double volume); - -// FFI set_playback_speed - sets playback speed -// Returns: 0 on success, -1 on error -int ffi_set_playback_speed(int64_t player_id, double speed); - -// FFI set_looping - enables or disables looping -// Returns: 0 on success, -1 on error -int ffi_set_looping(int64_t player_id, bool is_looping); - -// FFI get_track_info - gets track information for a specific track type -// Returns: JSON string of track info on success, nullptr on error -// Note: Returns a malloc-allocated string that the caller must free -const char* ffi_get_track_info(int64_t player_id, const char* track_type); - -// FFI set_track_selection - sets the selected track -// Returns: 0 on success, -1 on error -int ffi_set_track_selection(int64_t player_id, int64_t track_id, - const char* track_type); - -// FFI set_display_geometry - sets the display geometry (ROI) -// Returns: 0 on success, -1 on error -int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, - int32_t width, int32_t height); - -// FFI set_display_rotate - sets display rotation -// Returns: 0 on success, -1 on error -int ffi_set_display_rotate(int64_t player_id, int32_t rotation); - -// FFI suspend - suspends the player -// Returns: 0 on success, -1 on error -int ffi_suspend(int64_t player_id); - -// FFI restore - restores a suspended player -// Returns: 0 on success, -1 on error -int ffi_restore(int64_t player_id, const char* create_message_json, - int64_t resume_time); - -// FFI set_activate - activates the player -// Returns: 0 on success, -1 on error -int ffi_set_activate(int64_t player_id); - -// FFI set_deactivate - deactivates the player -// Returns: 0 on success, -1 on error -int ffi_set_deactivate(int64_t player_id); - -// FFI set_mix_with_others - sets whether to mix audio with other players -// Returns: 0 on success, -1 on error -int ffi_set_mix_with_others(bool mix_with_others); - -#ifdef __cplusplus -} // extern "C" -#endif - -#endif // PIGEON_MESSAGES_H_ diff --git a/packages/video_player_videohole/tizen/src/video_player.cc b/packages/video_player_videohole/tizen/src/video_player.cc index f6c644dec..57150c366 100644 --- a/packages/video_player_videohole/tizen/src/video_player.cc +++ b/packages/video_player_videohole/tizen/src/video_player.cc @@ -192,8 +192,7 @@ static void NotifyFFIEventCallback(int64_t player_id, VideoPlayer::VideoPlayer(flutter::BinaryMessenger* messenger, FlutterDesktopViewRef flutter_view) - : player_id_(-1), // Initialize player_id_ to -1 (will be set in - // SetUpEventChannel) + : player_id_(-1), // Will be set in SetUpEventChannel. ecore_wl2_window_proxy_(std::make_unique()), binary_messenger_(messenger), flutter_view_(flutter_view) { @@ -223,7 +222,6 @@ VideoPlayer::~VideoPlayer() { void VideoPlayer::ExecuteSinkEvents() { std::lock_guard lock(queue_mutex_); - // Process regular events using FFI only while (!encodable_event_queue_.empty()) { const flutter::EncodableValue& event = encodable_event_queue_.front(); @@ -234,7 +232,6 @@ void VideoPlayer::ExecuteSinkEvents() { encodable_event_queue_.pop(); } - // Process error events via FFI while (!error_event_queue_.empty()) { const auto& error = error_event_queue_.front(); // Send error event via FFI @@ -292,15 +289,12 @@ void VideoPlayer::ScheduleSendPendingEvents() { void VideoPlayer::PushEvent(flutter::EncodableValue encodable_value) { { std::lock_guard lock(queue_mutex_); - // Always add event to queue, even if event_sink_ is nullptr - // FFI callback doesn't require event_sink_ to be set encodable_event_queue_.push(encodable_value); } ScheduleSendPendingEvents(); } void VideoPlayer::SendInitialized() { - // Always send initialized event via FFI if (!is_initialized_) { LOG_INFO("[VideoPlayer] SendInitialized called."); @@ -370,7 +364,6 @@ void VideoPlayer::SendPlayCompleted() { } void VideoPlayer::SendIsPlayingState(bool is_playing) { - LOG_INFO("***********SendIsPlayingState start***************"); flutter::EncodableMap result = { {flutter::EncodableValue("event"), flutter::EncodableValue("isPlayingStateUpdate")}, @@ -378,7 +371,6 @@ void VideoPlayer::SendIsPlayingState(bool is_playing) { flutter::EncodableValue(is_playing)}, }; PushEvent(flutter::EncodableValue(result)); - LOG_INFO("***********SendIsPlayingState end***************"); } void VideoPlayer::SendRestored() { diff --git a/packages/video_player_videohole/tizen/src/video_player.h b/packages/video_player_videohole/tizen/src/video_player.h index 3862484b3..a3909ab13 100644 --- a/packages/video_player_videohole/tizen/src/video_player.h +++ b/packages/video_player_videohole/tizen/src/video_player.h @@ -21,7 +21,7 @@ #include #include "ecore_wl2_window_proxy.h" -#include "messages.h" +#include "ffi_messages.h" namespace video_player_videohole_tizen { diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 81b73e546..37cc9da00 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -5,7 +5,6 @@ #include "video_player_tizen_plugin.h" #include -#include #include #include @@ -19,6 +18,7 @@ #include #include +#include "ffi_messages.h" #include "media_player.h" #include "video_player.h" #include "video_player_options.h" @@ -86,6 +86,9 @@ class VideoPlayerTizenPlugin : public flutter::Plugin { static VideoPlayerTizenPlugin *instance_; }; +// Static instance definition +VideoPlayerTizenPlugin *VideoPlayerTizenPlugin::instance_ = nullptr; + void VideoPlayerTizenPlugin::RegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar_ref, flutter::PluginRegistrar *plugin_registrar) { @@ -99,7 +102,6 @@ VideoPlayerTizenPlugin::VideoPlayerTizenPlugin( flutter::PluginRegistrar *plugin_registrar) : registrar_ref_(registrar_ref), plugin_registrar_(plugin_registrar) { instance_ = this; // Set singleton instance for FFI access - // VideoPlayerVideoholeApi removed - all methods migrated to FFI } VideoPlayerTizenPlugin::~VideoPlayerTizenPlugin() { DisposeAllPlayers(); } @@ -321,6 +323,7 @@ std::optional VideoPlayerTizenPlugin::Suspend(int64_t player_id) { } return std::nullopt; } + std::optional VideoPlayerTizenPlugin::Restore( int64_t player_id, const CreateMessage *msg, int64_t resume_time) { VideoPlayer *player = FindPlayerById(player_id); @@ -345,95 +348,53 @@ ErrorOr VideoPlayerTizenPlugin::SetDisplayRotate( } // namespace video_player_videohole_tizen -// Static instance definition -namespace video_player_videohole_tizen { -VideoPlayerTizenPlugin *VideoPlayerTizenPlugin::instance_ = nullptr; -} // namespace video_player_videohole_tizen - -// C interface for plugin registration (required by C# -// GeneratedPluginRegistrant) and FFI exports for gradual migration -extern "C" { - -void VideoPlayerTizenPluginRegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar_ref) { - // Get the plugin registrar from the manager using the template method - auto *plugin_registrar = - flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar_ref); - - // Create and register the plugin - auto plugin = - std::make_unique( - registrar_ref, plugin_registrar); - plugin_registrar->AddPlugin(std::move(plugin)); -} +// ===== FFI Implementation ===== -int ffi_initialize() { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; // Plugin not initialized - } - - auto result = plugin->Initialize(); - if (result.has_value()) { - // Error occurred - return -1; - } - return 0; // Success -} +#include +#include +#include // Helper function to parse simple JSON-like string to flutter::EncodableMap -// Format: {"key1":"value1","key2":"value2"} static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { flutter::EncodableMap result; if (json_str.empty() || json_str == "{}") { return result; } - // Simple parser for flat key-value pairs std::string content = json_str; - // Remove outer braces if (content.front() == '{') content = content.substr(1); if (content.back() == '}') content.pop_back(); - // Parse key-value pairs size_t pos = 0; while (pos < content.length()) { - // Skip whitespace and commas while (pos < content.length() && (isspace(content[pos]) || content[pos] == ',')) { pos++; } if (pos >= content.length()) break; - // Find key if (content[pos] != '"') break; - pos++; // skip opening quote + pos++; size_t key_start = pos; while (pos < content.length() && content[pos] != '"') pos++; std::string key = content.substr(key_start, pos - key_start); - pos++; // skip closing quote + pos++; - // Skip colon and whitespace while (pos < content.length() && (isspace(content[pos]) || content[pos] == ':')) { pos++; } if (pos >= content.length()) break; - // Find value std::string value; if (content[pos] == '"') { - // String value - pos++; // skip opening quote + pos++; size_t val_start = pos; while (pos < content.length() && content[pos] != '"') pos++; value = content.substr(val_start, pos - val_start); - pos++; // skip closing quote + pos++; result[flutter::EncodableValue(key)] = flutter::EncodableValue(value); } else if (content[pos] == '{') { - // Nested object - skip for now, treat as empty map int brace_count = 1; pos++; while (pos < content.length() && brace_count > 0) { @@ -445,14 +406,12 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { } result[flutter::EncodableValue(key)] = flutter::EncodableMap(); } else { - // Number or boolean size_t val_start = pos; while (pos < content.length() && content[pos] != ',' && content[pos] != '}') { pos++; } value = content.substr(val_start, pos - val_start); - // Trim whitespace while (!value.empty() && isspace(value.back())) value.pop_back(); if (value == "true") { @@ -460,7 +419,6 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { } else if (value == "false") { result[flutter::EncodableValue(key)] = flutter::EncodableValue(false); } else { - // Try as number try { if (value.find('.') != std::string::npos) { result[flutter::EncodableValue(key)] = @@ -480,7 +438,6 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { } // Helper function to extract a string value from JSON by key -// Returns true if the key was found and value was extracted static bool ExtractStringValue(const std::string &json_str, const std::string &key, std::string &out_value) { std::string search_key = "\"" + key + "\""; @@ -496,7 +453,7 @@ static bool ExtractStringValue(const std::string &json_str, pos++; if (pos >= json_str.length() || json_str[pos] != '"') return false; - pos++; // skip opening quote + pos++; size_t end = pos; while (end < json_str.length() && json_str[end] != '"') end++; @@ -504,8 +461,7 @@ static bool ExtractStringValue(const std::string &json_str, return true; } -// Helper function to extract a nested object from JSON by key. -// Returns the nested object JSON string or empty string if not found. +// Helper function to extract a nested object from JSON by key static std::string ExtractObjectValue(const std::string &json_str, const std::string &key) { std::string search_key = "\"" + key + "\""; @@ -533,9 +489,6 @@ static std::string ExtractObjectValue(const std::string &json_str, } // Unified function to parse CreateMessage from JSON string -// JSON format: -// {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}} static video_player_videohole_tizen::CreateMessage ParseCreateMessage( const std::string &json_str) { video_player_videohole_tizen::CreateMessage msg; @@ -544,7 +497,6 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( return msg; } - // Extract string fields using helper function std::string value; if (ExtractStringValue(json_str, "uri", value)) { msg.set_uri(value); @@ -559,10 +511,8 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( msg.set_format_hint(value); } - // Extract nested object fields using helper function std::string nested_json; - // httpHeaders nested_json = ExtractObjectValue(json_str, "httpHeaders"); if (!nested_json.empty()) { flutter::EncodableMap headers = ParseJsonMap(nested_json); @@ -571,7 +521,6 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( } } - // playerOptions nested_json = ExtractObjectValue(json_str, "playerOptions"); if (!nested_json.empty()) { flutter::EncodableMap options = ParseJsonMap(nested_json); @@ -580,13 +529,11 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( } } - // drmConfigs (special handling for drmType and licenseServerUrl) nested_json = ExtractObjectValue(json_str, "drmConfigs"); if (!nested_json.empty()) { int64_t drm_type = 0; std::string license_url; - // Extract drmType (number value) size_t drm_pos = nested_json.find("\"drmType\""); if (drm_pos != std::string::npos) { drm_pos = nested_json.find(':', drm_pos); @@ -613,7 +560,6 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( } } - // Extract licenseServerUrl using helper function ExtractStringValue(nested_json, "licenseServerUrl", license_url); flutter::EncodableMap drm_map; @@ -629,16 +575,41 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( return msg; } -// FFI create function - takes a single JSON string for all create parameters -// JSON format: -// {"uri":"...","asset":"...","packageName":"...","formatHint":"...", -// "httpHeaders":{...},"drmConfigs":{...},"playerOptions":{...}}. -// Returns: player_id on success, -1 on error +// C interface for plugin registration (required by C# +// GeneratedPluginRegistrant) and FFI exports +extern "C" { + +void VideoPlayerTizenPluginRegisterWithRegistrar( + FlutterDesktopPluginRegistrarRef registrar_ref) { + auto *plugin_registrar = + flutter::PluginRegistrarManager::GetInstance() + ->GetRegistrar(registrar_ref); + + auto plugin = + std::make_unique( + registrar_ref, plugin_registrar); + plugin_registrar->AddPlugin(std::move(plugin)); +} + +int ffi_initialize() { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr) { + return -1; + } + + auto result = plugin->Initialize(); + if (result.has_value()) { + return -1; + } + return 0; +} + int64_t ffi_create(const char *create_message_json) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } video_player_videohole_tizen::CreateMessage msg; @@ -653,135 +624,102 @@ int64_t ffi_create(const char *create_message_json) { return result.value().player_id(); } -// FFI dispose function - releases player resources -// Returns: 0 on success, -1 on error -// Safe to call multiple times with same player_id int ffi_dispose(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Check if player exists before trying to dispose - // This prevents crash when dispose is called multiple times auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( player_id); if (player == nullptr) { - // Player already disposed or never existed - return success silently return 0; } auto result = plugin->Dispose(video_player_videohole_tizen::PlayerMessage(player_id)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI play function - starts or resumes playback -// Returns: 0 on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed -// player int ffi_play(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Check if player exists before calling - avoid crash on disposed player auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( player_id); if (player == nullptr) { - return -1; // Player already disposed or never existed + return -1; } auto result = plugin->Play(video_player_videohole_tizen::PlayerMessage(player_id)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI pause function - pauses playback -// Returns: 0 on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed -// player int ffi_pause(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Check if player exists before calling - avoid crash on disposed player auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( player_id); if (player == nullptr) { - return -1; // Player already disposed or never existed + return -1; } auto result = plugin->Pause(video_player_videohole_tizen::PlayerMessage(player_id)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI seek_to function - seeks to a specific position (in milliseconds) -// Returns: 0 on success, -1 on error -// Note: This is a fire-and-forget operation. The seek completion is notified -// through the event channel, not through return value. int ffi_seek_to(int64_t player_id, int64_t position_ms) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Call SeekTo asynchronously - the result will be notified through event - // channel. We don't block here to avoid freezing the UI thread plugin->SeekTo( video_player_videohole_tizen::PositionMessage(player_id, position_ms), [](std::optional result) { - // Callback is invoked when seek completes - // The event channel will notify Flutter about the seek completion if (result.has_value()) { - // Log error but don't block - Flutter will handle it through events + // Error handling through events } }); - // Return immediately to allow UI to refresh - return 0; // Success (actual result will be notified through event channel) + return 0; } -// FFI get_position function - gets current playback position in milliseconds -// Returns: position in milliseconds (>= 0) on success, -1 on error -// Note: Checks if player exists before calling to avoid crash on disposed -// player int64_t ffi_get_position(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Check if player exists before calling - avoid crash on disposed player auto player = video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( player_id); if (player == nullptr) { - return -1; // Player already disposed or never existed + return -1; } auto result = @@ -792,16 +730,11 @@ int64_t ffi_get_position(int64_t player_id) { return result.value().position(); } -// FFI get_duration function - gets video duration range in milliseconds -// Returns: JSON string with start and end values, or "-1" on error -// Format: {"start": , "end": } -// For live streams, start may be non-zero (e.g., {"start": 1000, "end": 5000}) -// Note: Returns a malloc-allocated string that the caller must free const char *ffi_get_duration(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return strdup("-1"); // Plugin not initialized + return strdup("-1"); } auto result = @@ -810,9 +743,6 @@ const char *ffi_get_duration(int64_t player_id) { return strdup("-1"); } - // Return both start and end of duration range as JSON - // Use strdup to allocate memory that persists after this function returns - // The Dart caller is responsible for freeing this memory const auto &duration_range = result.value().duration_range(); std::string duration_json; if (duration_range && duration_range->size() >= 2) { @@ -830,87 +760,144 @@ const char *ffi_get_duration(int64_t player_id) { return strdup(duration_json.c_str()); } -// FFI set_volume function - sets playback volume (0.0 to 1.0) -// Returns: 0 on success, -1 on error int ffi_set_volume(int64_t player_id, double volume) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetVolume( video_player_videohole_tizen::VolumeMessage(player_id, volume)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI set_playback_speed function - sets playback speed -// Returns: 0 on success, -1 on error int ffi_set_playback_speed(int64_t player_id, double speed) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetPlaybackSpeed( video_player_videohole_tizen::PlaybackSpeedMessage(player_id, speed)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI set_looping function - enables or disables looping -// Returns: 0 on success, -1 on error int ffi_set_looping(int64_t player_id, bool is_looping) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetLooping( - video_player_videohole_tizen::LoopingMessage(player_id, is_looping)); + video_player_videohole_tizen::LoopingMessage(player_id, is_looping != 0)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; +} + +const char *ffi_get_track_info(int64_t player_id, const char *track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return nullptr; + } + + auto result = plugin->Track(video_player_videohole_tizen::TrackTypeMessage( + player_id, std::string(track_type))); + if (result.has_error()) { + return nullptr; + } + + std::string track_info_json = + "{\"playerId\":" + std::to_string(result.value().player_id()) + + ",\"tracks\":["; + + const auto &tracks = result.value().tracks(); + for (size_t i = 0; i < tracks.size(); ++i) { + if (i > 0) track_info_json += ","; + + const auto &track_map = std::get(tracks[i]); + track_info_json += "{"; + + bool first = true; + for (const auto &[key, value] : track_map) { + if (!first) track_info_json += ","; + first = false; + + const std::string *key_str = std::get_if(&key); + if (!key_str) continue; + + track_info_json += "\"" + *key_str + "\":"; + + if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += std::to_string(std::get(value)); + } else if (std::holds_alternative(value)) { + track_info_json += "\"" + std::get(value) + "\""; + } else if (std::holds_alternative(value)) { + track_info_json += std::get(value) ? "true" : "false"; + } + } + + track_info_json += "}"; + } + + track_info_json += "]}"; + return strdup(track_info_json.c_str()); +} + +int ffi_set_track_selection(int64_t player_id, int64_t track_id, + const char *track_type) { + auto *plugin = + video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); + if (plugin == nullptr || track_type == nullptr) { + return -1; + } + + auto result = plugin->SetTrackSelection( + video_player_videohole_tizen::SelectedTracksMessage( + player_id, track_id, std::string(track_type))); + if (result.has_error()) { + return -1; + } + return result.value() ? 0 : -1; } -// FFI set_display_geometry function - sets the display geometry (ROI) -// Returns: 0 on success, -1 on error int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetDisplayGeometry(video_player_videohole_tizen::GeometryMessage( player_id, x, y, width, height)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI set_display_rotate function - sets display rotation -// Returns: 0 on success, -1 on error int ffi_set_display_rotate(int64_t player_id, int32_t rotation) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetDisplayRotate( @@ -921,35 +908,28 @@ int ffi_set_display_rotate(int64_t player_id, int32_t rotation) { return result.value() ? 0 : -1; } -// FFI suspend function - suspends the player -// Returns: 0 on success, -1 on error int ffi_suspend(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->Suspend(player_id); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI restore function - restores a suspended player -// create_message_json: JSON string of CreateMessage or empty/null for using -// saved state. Returns: 0 on success, -1 on error int ffi_restore(int64_t player_id, const char *create_message_json, int64_t resume_time) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } - // Use unified ParseCreateMessage function to parse JSON video_player_videohole_tizen::CreateMessage msg; if (create_message_json != nullptr && strlen(create_message_json) > 0) { msg = ParseCreateMessage(std::string(create_message_json)); @@ -957,19 +937,16 @@ int ffi_restore(int64_t player_id, const char *create_message_json, auto result = plugin->Restore(player_id, &msg, resume_time); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success + return 0; } -// FFI set_activate function - activates the player -// Returns: 0 on success, -1 on error int ffi_set_activate(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetActivate( @@ -980,13 +957,11 @@ int ffi_set_activate(int64_t player_id) { return result.value() ? 0 : -1; } -// FFI set_deactivate function - deactivates the player -// Returns: 0 on success, -1 on error int ffi_set_deactivate(int64_t player_id) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetDeactivate( @@ -997,156 +972,39 @@ int ffi_set_deactivate(int64_t player_id) { return result.value() ? 0 : -1; } -// FFI get_track_info function - gets track information for a specific track -// type. Returns: JSON string of track info on success, nullptr on error. -// Format: {"playerId": , "tracks": [{"trackId": , ...}, ...]}. -// Note: Returns a malloc-allocated string that the caller must free. -const char *ffi_get_track_info(int64_t player_id, const char *track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return nullptr; - } - - auto result = plugin->Track(video_player_videohole_tizen::TrackTypeMessage( - player_id, std::string(track_type))); - if (result.has_error()) { - return nullptr; - } - - // Convert TrackMessage to JSON string - // Use strdup to allocate memory that persists after this function returns - // The Dart caller is responsible for freeing this memory - std::string track_info_json = - "{\"playerId\":" + std::to_string(result.value().player_id()) + - ",\"tracks\":["; - - const auto &tracks = result.value().tracks(); - for (size_t i = 0; i < tracks.size(); ++i) { - if (i > 0) track_info_json += ","; - - const auto &track_map = std::get(tracks[i]); - track_info_json += "{"; - - bool first = true; - for (const auto &[key, value] : track_map) { - if (!first) track_info_json += ","; - first = false; - - const std::string *key_str = std::get_if(&key); - if (!key_str) continue; - - track_info_json += "\"" + *key_str + "\":"; - - if (std::holds_alternative(value)) { - track_info_json += std::to_string(std::get(value)); - } else if (std::holds_alternative(value)) { - track_info_json += std::to_string(std::get(value)); - } else if (std::holds_alternative(value)) { - track_info_json += std::to_string(std::get(value)); - } else if (std::holds_alternative(value)) { - track_info_json += "\"" + std::get(value) + "\""; - } else if (std::holds_alternative(value)) { - track_info_json += std::get(value) ? "true" : "false"; - } - } - - track_info_json += "}"; - } - - track_info_json += "]}"; - return strdup(track_info_json.c_str()); -} - -// FFI set_track_selection function - sets the selected track -// Returns: 0 on success, -1 on error -int ffi_set_track_selection(int64_t player_id, int64_t track_id, - const char *track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return -1; // Plugin not initialized - } - - auto result = plugin->SetTrackSelection( - video_player_videohole_tizen::SelectedTracksMessage( - player_id, track_id, std::string(track_type))); - if (result.has_error()) { - return -1; - } - return result.value() ? 0 : -1; -} - -// FFI set_mix_with_others function - sets whether to mix audio with other -// players. Returns: 0 on success, -1 on error int ffi_set_mix_with_others(bool mix_with_others) { auto *plugin = video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); if (plugin == nullptr) { - return -1; // Plugin not initialized + return -1; } auto result = plugin->SetMixWithOthers( video_player_videohole_tizen::MixWithOthersMessage(mix_with_others)); if (result.has_value()) { - // Error occurred return -1; } - return 0; // Success -} - -// FFI event callback function pointer type - matches the C++ type -// Parameters: player_id, event_json (malloc-allocated string, caller must free) -typedef void (*FFIEventCallbackFunc)(int64_t player_id, const char *event_json); - -// FFI register_event_callback function - registers callback for event -// notifications The callback will be invoked on the main thread via -// g_idle_source event_json is a malloc-allocated string that the callback must -// free -void ffi_register_event_callback(FFIEventCallbackFunc callback) { - if (callback == nullptr) { - // Clear the callback - video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback( - nullptr); - return; - } - - // Wrap the C function pointer in a std::function - video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback( - [callback](int64_t player_id, const char *event_json) { - callback(player_id, event_json); - }); + return 0; } -// FFI unregister_event_callback function - unregisters the event callback -void ffi_unregister_event_callback() { - video_player_videohole_tizen::VideoPlayer::RegisterFFIEventCallback(nullptr); -} - -// Global variable to store Dart_InitializeApiDL data +// FFI event port functions static bool g_dart_api_dl_initialized = false; -// FFI initialize_api_dl function - initializes Dart API DL -// This must be called before using Dart_PostCObject_DL -// data: The initializeApiDLData from Dart's NativeApi -void ffi_initialize_api_dl(void *data) { +int ffi_initialize_api_dl(void *data) { if (!g_dart_api_dl_initialized) { if (Dart_InitializeApiDL(data) == 0) { g_dart_api_dl_initialized = true; + return 0; } + return -1; } + return 0; } -// FFI register_event_port function - registers Dart port for event -// notifications The port is used with Dart_PostCObject_DL to send events to -// Dart isolate port: The nativePort from Dart's ReceivePort.sendPort void ffi_register_event_port(int64_t port) { - // Ensure Dart API DL is initialized before using Dart_PostCObject_DL - // Note: This assumes Dart side has already called ffi_initialize_api_dl video_player_videohole_tizen::RegisterDartPort(port); } -// FFI unregister_event_port function - unregisters the Dart port void ffi_unregister_event_port() { video_player_videohole_tizen::RegisterDartPort(-1); } From 46dee32a86becfb5eb931d09d222742bcbe77875 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 22 Jul 2026 18:47:43 +0800 Subject: [PATCH 08/18] Ensure minimal changes --- .../tizen/src/media_player.cc | 99 +++---------------- .../tizen/src/video_player.cc | 6 -- .../tizen/src/video_player.h | 13 ++- 3 files changed, 22 insertions(+), 96 deletions(-) diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 91f2fbcf8..31eeb517a 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -44,7 +44,6 @@ MediaPlayer::MediaPlayer(flutter::BinaryMessenger *messenger, : VideoPlayer(messenger, flutter_view) { media_player_proxy_ = std::make_unique(); device_proxy_ = std::make_unique(); - // ecore_wl2_window_proxy_ is already created in VideoPlayer constructor } MediaPlayer::~MediaPlayer() { @@ -79,10 +78,7 @@ int64_t MediaPlayer::Create(const std::string &uri, return -1; } - // Assign a unique player ID (this was previously done in SetUpEventChannel) player_id_ = player_id_counter++; - LOG_INFO("[MediaPlayer] Assigned player_id_: %lld", - static_cast(player_id_)); url_ = uri; create_message_ = create_message; @@ -93,13 +89,8 @@ int64_t MediaPlayer::Create(const std::string &uri, return -1; } - const auto &http_headers = create_message.http_headers(); - auto cookie_it = http_headers.find(flutter::EncodableValue("Cookie")); - std::string cookie; - if (cookie_it != http_headers.end() && - std::holds_alternative(cookie_it->second)) { - cookie = std::get(cookie_it->second); - } + std::string cookie = flutter_common::GetValue(&create_message.http_headers(), + "Cookie", std::string()); if (!cookie.empty()) { int ret = player_set_streaming_cookie(player_, cookie.c_str(), cookie.size()); @@ -108,12 +99,8 @@ int64_t MediaPlayer::Create(const std::string &uri, get_error_message(ret)); } } - auto user_agent_it = http_headers.find(flutter::EncodableValue("User-Agent")); - std::string user_agent; - if (user_agent_it != http_headers.end() && - std::holds_alternative(user_agent_it->second)) { - user_agent = std::get(user_agent_it->second); - } + std::string user_agent = flutter_common::GetValue( + &create_message.http_headers(), "User-Agent", std::string()); if (!user_agent.empty()) { int ret = player_set_streaming_user_agent(player_, user_agent.c_str(), user_agent.size()); @@ -123,37 +110,15 @@ int64_t MediaPlayer::Create(const std::string &uri, } } - const auto &drm_configs = create_message.drm_configs(); - if (!drm_configs.empty()) { - LOG_INFO("[MediaPlayer] drm_configs is present."); - - int64_t drm_type = 0; - std::string license_server_url; - auto drm_type_it = drm_configs.find(flutter::EncodableValue("drmType")); - if (drm_type_it != drm_configs.end() && - std::holds_alternative(drm_type_it->second)) { - drm_type = std::get(drm_type_it->second); - } - auto license_it = - drm_configs.find(flutter::EncodableValue("licenseServerUrl")); - if (license_it != drm_configs.end() && - std::holds_alternative(license_it->second)) { - license_server_url = std::get(license_it->second); - } - - LOG_INFO("[MediaPlayer] drm_type=%lld, license_server_url=%s", - static_cast(drm_type), license_server_url.c_str()); - - if (drm_type != 0) { - if (!SetDrm(uri, drm_type, license_server_url)) { - LOG_ERROR("[MediaPlayer] Failed to set drm."); - return -1; - } - } else { - LOG_INFO("[MediaPlayer] drm_type is 0, skipping SetDrm."); + int64_t drm_type = flutter_common::GetValue(&create_message.drm_configs(), + "drmType", (int64_t)0); + std::string license_server_url = flutter_common::GetValue( + &create_message.drm_configs(), "licenseServerUrl", std::string()); + if (drm_type != 0) { + if (!SetDrm(uri, drm_type, license_server_url)) { + LOG_ERROR("[MediaPlayer] Failed to set drm."); + return -1; } - } else { - LOG_INFO("[MediaPlayer] drm_configs is NOT present (null)."); } if (!SetDisplay()) { @@ -220,7 +185,6 @@ int64_t MediaPlayer::Create(const std::string &uri, return -1; } - // Return player_id_ which was already set in constructor return player_id_; } @@ -417,8 +381,6 @@ bool MediaPlayer::SetDisplay() { return false; } - LOG_INFO("[MediaPlayer] Got native window handle: %p", native_window); - int x = 0, y = 0, width = 0, height = 0; ecore_wl2_window_proxy_->ecore_wl2_window_geometry_get(native_window, &x, &y, &width, &height); @@ -437,7 +399,6 @@ bool MediaPlayer::SetDisplay() { return false; } - LOG_INFO("[MediaPlayer] Display set successfully."); return true; } @@ -644,7 +605,6 @@ bool MediaPlayer::SetTrackSelection(int32_t track_id, std::string track_type) { bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, const std::string &license_server_url) { drm_manager_ = std::make_unique(); - if (!drm_manager_->CreateDrmSession(drm_type, false)) { LOG_ERROR("[MediaPlayer] Failed to create drm session."); return false; @@ -683,17 +643,16 @@ bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, if (license_server_url.empty()) { bool success = drm_manager_->SetChallenge(uri, binary_messenger_); if (!success) { - LOG_ERROR("[MediaPlayer] Failed to set challenge via licenseCallback."); + LOG_ERROR("[MediaPlayer] Failed to set challenge."); return false; } } else { if (!drm_manager_->SetChallenge(uri, license_server_url)) { - LOG_ERROR("[MediaPlayer] Failed to set challenge via licenseServerUrl."); + LOG_ERROR("[MediaPlayer] Failed to set challenge."); return false; } } - LOG_INFO("[MediaPlayer] SetDrm completed successfully."); return true; } @@ -771,19 +730,6 @@ bool MediaPlayer::Suspend() { "[MediaPlayer] Saved current player state: %d, playing time: %llu ms", pre_state_, pre_playing_time_); - // For DRM content, always do full destroy/recreate on suspend/restore - // to avoid player_start() timeout issues with invalid display surface - if (drm_manager_ != nullptr) { - LOG_INFO( - "[MediaPlayer] DRM content detected, doing full destroy on suspend"); - if (!StopAndDestroy()) { - LOG_ERROR("[MediaPlayer] DRM content StopAndDestroy fail."); - return false; - } - LOG_INFO("[MediaPlayer] DRM content suspend done successfully."); - return true; - } - if (IsLive()) { pre_playing_time_ = 0; if (!StopAndDestroy()) { @@ -864,12 +810,7 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, if (pre_state_ == PLAYER_STATE_PLAYING) { if (!Play()) { LOG_ERROR("[MediaPlayer] Player play failed."); - // return false; - if (player_ && !StopAndDestroy()) { - LOG_ERROR("[MediaPlayer] Player StopAndDestroy fail."); - return false; - } - return RestorePlayer(restore_message, resume_time); + return false; } } break; @@ -935,22 +876,14 @@ void MediaPlayer::OnRestoreCompleted() { "pre_playing_time_=%llu", pre_state_, pre_playing_time_); - // First, seek to the saved position if (pre_playing_time_ <= 0 || !SeekTo(pre_playing_time_, [this]() { - // After seek completed, restore the playing state if it was playing - // before suspend if (pre_state_ == PLAYER_STATE_PLAYING) { LOG_INFO("[MediaPlayer] Restoring to PLAYING state after seek."); Play(); } SendRestored(); })) { - // If seek failed or not needed, still restore playing state if it was - // playing - if (pre_state_ == PLAYER_STATE_PLAYING) { - LOG_INFO("[MediaPlayer] Restoring to PLAYING state (no seek needed)."); - Play(); - } + if (pre_state_ == PLAYER_STATE_PLAYING) Play(); SendRestored(); } } diff --git a/packages/video_player_videohole/tizen/src/video_player.cc b/packages/video_player_videohole/tizen/src/video_player.cc index 57150c366..6f14329be 100644 --- a/packages/video_player_videohole/tizen/src/video_player.cc +++ b/packages/video_player_videohole/tizen/src/video_player.cc @@ -221,7 +221,6 @@ VideoPlayer::~VideoPlayer() { void VideoPlayer::ExecuteSinkEvents() { std::lock_guard lock(queue_mutex_); - while (!encodable_event_queue_.empty()) { const flutter::EncodableValue& event = encodable_event_queue_.front(); @@ -296,8 +295,6 @@ void VideoPlayer::PushEvent(flutter::EncodableValue encodable_value) { void VideoPlayer::SendInitialized() { if (!is_initialized_) { - LOG_INFO("[VideoPlayer] SendInitialized called."); - int32_t width = 0, height = 0; GetVideoSize(&width, &height); is_initialized_ = true; @@ -313,10 +310,7 @@ void VideoPlayer::SendInitialized() { {flutter::EncodableValue("width"), flutter::EncodableValue(width)}, {flutter::EncodableValue("height"), flutter::EncodableValue(height)}, }; - LOG_INFO("[VideoPlayer] Pushing initialized event to FFI"); PushEvent(flutter::EncodableValue(result)); - } else { - LOG_INFO("[VideoPlayer] SendInitialized skipped - already initialized"); } } diff --git a/packages/video_player_videohole/tizen/src/video_player.h b/packages/video_player_videohole/tizen/src/video_player.h index a3909ab13..52ced8832 100644 --- a/packages/video_player_videohole/tizen/src/video_player.h +++ b/packages/video_player_videohole/tizen/src/video_player.h @@ -25,21 +25,20 @@ namespace video_player_videohole_tizen { -// FFI event callback using Dart_Port - sends message to Dart isolate -// Parameters: player_id, event_json string +// FFI event callback using Dart_Port - sends message to Dart isolate. using DartPortEventCallback = std::function; -// Static FFI event callback - shared across all VideoPlayer instances +// Static FFI event callback - shared across all VideoPlayer instances. extern DartPortEventCallback g_dart_port_callback; extern int64_t g_dart_port; extern std::mutex g_dart_port_mutex; -// Register Dart port for FFI event notifications +// Register Dart port for FFI event notifications. void RegisterDartPort(int64_t port); int64_t GetDartPort(); -// Post event to Dart using Dart_PostCObject_DL +// Post event to Dart using Dart_PostCObject_DL. void PostEventToDart(int64_t player_id, const std::string &event_json); class VideoPlayer { @@ -47,10 +46,10 @@ class VideoPlayer { using SeekCompletedCallback = std::function; // Static method to register FFI event callback (legacy, kept for - // compatibility) + // compatibility). static void RegisterFFIEventCallback(DartPortEventCallback callback); - // Static method to get current FFI event callback (legacy) + // Static method to get current FFI event callback (legacy). static DartPortEventCallback GetFFIEventCallback(); explicit VideoPlayer(flutter::BinaryMessenger *messenger, From 7efc2520e4000cfaedc3ffc0b553f962d1fa3a25 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Thu, 23 Jul 2026 17:07:34 +0800 Subject: [PATCH 09/18] remove VideoPlayerTizenPlugin --- .../tizen/src/media_player.cc | 37 +- .../tizen/src/video_player_tizen_plugin.cc | 749 ++++-------------- 2 files changed, 184 insertions(+), 602 deletions(-) diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 31eeb517a..82bbcff53 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -5,6 +5,7 @@ #include "media_player.h" #include +#include #include @@ -375,6 +376,7 @@ bool MediaPlayer::IsReady() { } bool MediaPlayer::SetDisplay() { + LOG_INFO("***********SetDisplay start**************"); void *native_window = GetWindowHandle(); if (!native_window) { LOG_ERROR("[MediaPlayer] Could not get a native window handle."); @@ -398,7 +400,7 @@ bool MediaPlayer::SetDisplay() { get_error_message(ret)); return false; } - + LOG_INFO("***********SetDisplay end**************"); return true; } @@ -652,7 +654,6 @@ bool MediaPlayer::SetDrm(const std::string &uri, int drm_type, return false; } } - return true; } @@ -753,13 +754,14 @@ bool MediaPlayer::Suspend() { LOG_INFO("[MediaPlayer] Player state is not standby: %d, do nothing.", res); } - if (player_state == PLAYER_STATE_IDLE) { + if (player_state == PLAYER_STATE_IDLE || player_state == PLAYER_STATE_READY) { if (!StopAndDestroy()) { LOG_ERROR("[MediaPlayer] Player StopAndDestroy fail."); return false; } LOG_INFO("[MediaPlayer] Player called in IDLE state, so stop the player."); - } else if (player_state != PLAYER_STATE_PAUSED) { + } else if (player_state == PLAYER_STATE_PLAYING) { + // 只有当前是 PLAYING 时才调用 pause,并保存 pre_state_ 为 PLAYING LOG_INFO("[MediaPlayer] Player calling pause from suspend."); if (!Pause()) { LOG_ERROR( @@ -808,10 +810,13 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, break; case PLAYER_STATE_PAUSED: if (pre_state_ == PLAYER_STATE_PLAYING) { - if (!Play()) { - LOG_ERROR("[MediaPlayer] Player play failed."); - return false; - } + // 不尝试 Play(),直接重建 player + // 因为 Play() 可能会阻塞很长时间(甚至卡死) + // 而且最终也会 fallback 到 RestorePlayer + LOG_INFO( + "[MediaPlayer] Restore: skipping Play(), calling RestorePlayer " + "directly."); + return RestorePlayer(restore_message, resume_time); } break; case PLAYER_STATE_PLAYING: @@ -819,11 +824,10 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, // restore more than once, just ignore. break; default: - LOG_INFO( - "[MediaPlayer] Unhandled state, dont know how to process, just " - "return " - "false."); - return false; + LOG_ERROR( + "[MediaPlayer] Restore: unhandled state=%d, calling RestorePlayer.", + player_state); + return RestorePlayer(restore_message, resume_time); } return true; } @@ -832,6 +836,13 @@ bool MediaPlayer::RestorePlayer(const CreateMessage *restore_message, int64_t resume_time) { LOG_INFO("[MediaPlayer] RestorePlayer is called."); + // 先清理旧的 player,避免状态冲突导致卡死 + if (player_ && !StopAndDestroy()) { + LOG_ERROR("[MediaPlayer] RestorePlayer: StopAndDestroy failed."); + return false; + } + LOG_INFO("[MediaPlayer] RestorePlayer: old player cleaned up."); + if (restore_message->uri()) { LOG_INFO("[MediaPlayer] Player previous url: %s", url_.c_str()); LOG_INFO("[MediaPlayer] Player new url: %s", diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 37cc9da00..2078fce08 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -11,8 +11,8 @@ #include #include #include +#include #include -#include #include #include #include @@ -25,337 +25,28 @@ namespace video_player_videohole_tizen { -class VideoPlayerTizenPlugin : public flutter::Plugin { - public: - static void RegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar_ref, - flutter::PluginRegistrar *plugin_registrar); - - // Get singleton instance for FFI access - static VideoPlayerTizenPlugin *GetInstance() { return instance_; } - - VideoPlayerTizenPlugin(FlutterDesktopPluginRegistrarRef registrar_ref, - flutter::PluginRegistrar *plugin_registrar); - virtual ~VideoPlayerTizenPlugin(); - - std::optional Initialize(); - ErrorOr Create(const CreateMessage &msg); - std::optional Dispose(const PlayerMessage &msg); - ErrorOr Duration(const PlayerMessage &msg); - std::optional SetLooping(const LoopingMessage &msg); - std::optional SetVolume(const VolumeMessage &msg); - std::optional SetPlaybackSpeed(const PlaybackSpeedMessage &msg); - ErrorOr Track(const TrackTypeMessage &msg); - ErrorOr SetTrackSelection(const SelectedTracksMessage &msg); - std::optional Play(const PlayerMessage &msg); - ErrorOr SetDeactivate(const PlayerMessage &msg); - ErrorOr SetActivate(const PlayerMessage &msg); - ErrorOr Position(const PlayerMessage &msg); - void SeekTo(const PositionMessage &msg, - std::function reply)> result); - std::optional Pause(const PlayerMessage &msg); - std::optional SetMixWithOthers(const MixWithOthersMessage &msg); - std::optional SetDisplayGeometry(const GeometryMessage &msg); - std::optional Suspend(int64_t player_id); - std::optional Restore(int64_t player_id, - const CreateMessage *msg, - int64_t resume_time); - ErrorOr SetDisplayRotate(const RotationMessage &msg); - - static VideoPlayer *FindPlayerById(int64_t player_id) { - auto iter = players_.find(player_id); - if (iter != players_.end()) { - return iter->second.get(); - } - return nullptr; - } - - private: - void DisposeAllPlayers(); - void ParseFromCreateMessage(const CreateMessage &msg, std::string &uri, - int64_t &drm_type, - std::string &license_server_url, - bool &prebuffer_mode, - flutter::EncodableMap &http_headers); - - FlutterDesktopPluginRegistrarRef registrar_ref_; - flutter::PluginRegistrar *plugin_registrar_; - VideoPlayerOptions options_; - - static inline std::map> players_; - static VideoPlayerTizenPlugin *instance_; -}; - -// Static instance definition -VideoPlayerTizenPlugin *VideoPlayerTizenPlugin::instance_ = nullptr; - -void VideoPlayerTizenPlugin::RegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar_ref, - flutter::PluginRegistrar *plugin_registrar) { - auto plugin = - std::make_unique(registrar_ref, plugin_registrar); - plugin_registrar->AddPlugin(std::move(plugin)); -} - -VideoPlayerTizenPlugin::VideoPlayerTizenPlugin( - FlutterDesktopPluginRegistrarRef registrar_ref, - flutter::PluginRegistrar *plugin_registrar) - : registrar_ref_(registrar_ref), plugin_registrar_(plugin_registrar) { - instance_ = this; // Set singleton instance for FFI access -} - -VideoPlayerTizenPlugin::~VideoPlayerTizenPlugin() { DisposeAllPlayers(); } - -void VideoPlayerTizenPlugin::DisposeAllPlayers() { - for (const auto &[id, player] : players_) { - player->Dispose(); - } - players_.clear(); -} - -std::optional VideoPlayerTizenPlugin::Initialize() { - DisposeAllPlayers(); - return std::nullopt; -} - -ErrorOr VideoPlayerTizenPlugin::Create( - const CreateMessage &msg) { - if (!FlutterDesktopPluginRegistrarGetView(registrar_ref_)) { - return FlutterError("Operation failed", "Could not get a Flutter view."); - } - std::string uri; - - if (msg.asset() && !msg.asset()->empty()) { - char *res_path = app_get_resource_path(); - if (res_path) { - uri = uri + res_path + "flutter_assets/" + *msg.asset(); - free(res_path); - } else { - return FlutterError("Internal error", "Failed to get resource path."); - } - } else if (msg.uri() && !msg.uri()->empty()) { - uri = *msg.uri(); - } else { - return FlutterError("Invalid argument", "Either asset or uri must be set."); - } - - auto player = std::make_unique( - plugin_registrar_->messenger(), - FlutterDesktopPluginRegistrarGetView(registrar_ref_)); - int64_t player_id = player->Create(uri, msg); - if (player_id == -1) { - return FlutterError("Operation failed", "Failed to create a player."); - } - players_[player_id] = std::move(player); - PlayerMessage result(player_id); - return result; -} - -ErrorOr VideoPlayerTizenPlugin::Duration( - const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found."); - } - DurationMessage result(msg.player_id()); - auto duration_pair = player->GetDuration(); - flutter::EncodableList duration_range{ - flutter::EncodableValue(duration_pair.first), - flutter::EncodableValue(duration_pair.second)}; - result.set_duration_range(duration_range); - return result; -} - -std::optional VideoPlayerTizenPlugin::Dispose( - const PlayerMessage &msg) { - auto iter = players_.find(msg.player_id()); - if (iter != players_.end()) { - iter->second->Dispose(); - players_.erase(iter); - } - return std::nullopt; -} - -std::optional VideoPlayerTizenPlugin::SetLooping( - const LoopingMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->SetLooping(msg.is_looping())) { - return FlutterError("SetLooping", "Player set looping failed"); - } - return std::nullopt; -} +// ===== Global State ===== +// Player registry - manages all player instances using shared_ptr for thread safety +static std::map> g_players; +static std::shared_mutex g_players_mutex; // Read-write lock for better concurrency -std::optional VideoPlayerTizenPlugin::SetVolume( - const VolumeMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->SetVolume(msg.volume())) { - return FlutterError("SetVolume", "Player set volume failed"); - } - return std::nullopt; -} +// Global resources needed for player creation +static FlutterDesktopPluginRegistrarRef g_registrar_ref = nullptr; +static flutter::PluginRegistrar* g_plugin_registrar = nullptr; +static VideoPlayerOptions g_options; -std::optional VideoPlayerTizenPlugin::SetPlaybackSpeed( - const PlaybackSpeedMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->SetPlaybackSpeed(msg.speed())) { - return FlutterError("SetPlaybackSpeed", "Player set playback speed failed"); +// Helper function to get player by ID (returns shared_ptr, caller holds reference) +static std::shared_ptr GetPlayer(int64_t player_id) { + std::shared_lock lock(g_players_mutex); // Read lock + auto iter = g_players.find(player_id); + if (iter != g_players.end()) { + return iter->second; // Copy shared_ptr, reference count +1 } - return std::nullopt; + return nullptr; } -ErrorOr VideoPlayerTizenPlugin::Track( - const TrackTypeMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - - TrackMessage result(msg.player_id(), player->GetTrackInfo(msg.track_type())); - return result; -} - -ErrorOr VideoPlayerTizenPlugin::SetTrackSelection( - const SelectedTracksMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - return player->SetTrackSelection(msg.track_id(), msg.track_type()); -} - -std::optional VideoPlayerTizenPlugin::Play( - const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->Play()) { - return FlutterError("Play", "Player play failed"); - } - return std::nullopt; -} - -ErrorOr VideoPlayerTizenPlugin::SetDeactivate(const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - return player->Deactivate(); -} - -ErrorOr VideoPlayerTizenPlugin::SetActivate(const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - return player->Activate(); -} - -std::optional VideoPlayerTizenPlugin::Pause( - const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->Pause()) { - return FlutterError("Pause", "Player pause failed"); - } - return std::nullopt; -} - -ErrorOr VideoPlayerTizenPlugin::Position( - const PlayerMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - PositionMessage result(msg.player_id(), player->GetPosition()); - return result; -} - -void VideoPlayerTizenPlugin::SeekTo( - const PositionMessage &msg, - std::function reply)> result) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - result(FlutterError("Invalid argument", "Player not found")); - return; - } - if (!player->SeekTo(msg.position(), - [result]() -> void { result(std::nullopt); })) { - result(FlutterError("SeekTo", "Player seek to failed")); - } -} - -std::optional VideoPlayerTizenPlugin::SetDisplayGeometry( - const GeometryMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - player->SetDisplayRoi(msg.x(), msg.y(), msg.width(), msg.height()); - return std::nullopt; -} - -std::optional VideoPlayerTizenPlugin::SetMixWithOthers( - const MixWithOthersMessage &msg) { - options_.SetMixWithOthers(msg.mix_with_others()); - return std::nullopt; -} - -std::optional VideoPlayerTizenPlugin::Suspend(int64_t player_id) { - VideoPlayer *player = FindPlayerById(player_id); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - if (!player->Suspend()) { - return FlutterError("Operation failed", "Player suspend error"); - } - return std::nullopt; -} - -std::optional VideoPlayerTizenPlugin::Restore( - int64_t player_id, const CreateMessage *msg, int64_t resume_time) { - VideoPlayer *player = FindPlayerById(player_id); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - - if (!player->Restore(msg, resume_time)) { - return FlutterError("Operation failed", "Player restore error"); - } - return std::nullopt; -} - -ErrorOr VideoPlayerTizenPlugin::SetDisplayRotate( - const RotationMessage &msg) { - VideoPlayer *player = FindPlayerById(msg.player_id()); - if (!player) { - return FlutterError("Invalid argument", "Player not found"); - } - return player->SetDisplayRotate(msg.rotation()); -} - -} // namespace video_player_videohole_tizen - -// ===== FFI Implementation ===== - -#include -#include -#include - // Helper function to parse simple JSON-like string to flutter::EncodableMap -static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { +static flutter::EncodableMap ParseJsonMap(const std::string& json_str) { flutter::EncodableMap result; if (json_str.empty() || json_str == "{}") { return result; @@ -438,8 +129,8 @@ static flutter::EncodableMap ParseJsonMap(const std::string &json_str) { } // Helper function to extract a string value from JSON by key -static bool ExtractStringValue(const std::string &json_str, - const std::string &key, std::string &out_value) { +static bool ExtractStringValue(const std::string& json_str, + const std::string& key, std::string& out_value) { std::string search_key = "\"" + key + "\""; size_t pos = json_str.find(search_key); if (pos == std::string::npos) return false; @@ -462,8 +153,8 @@ static bool ExtractStringValue(const std::string &json_str, } // Helper function to extract a nested object from JSON by key -static std::string ExtractObjectValue(const std::string &json_str, - const std::string &key) { +static std::string ExtractObjectValue(const std::string& json_str, + const std::string& key) { std::string search_key = "\"" + key + "\""; size_t pos = json_str.find(search_key); if (pos == std::string::npos) return ""; @@ -490,7 +181,11 @@ static std::string ExtractObjectValue(const std::string &json_str, // Unified function to parse CreateMessage from JSON string static video_player_videohole_tizen::CreateMessage ParseCreateMessage( - const std::string &json_str) { + const std::string& json_str) { + using video_player_videohole_tizen::CreateMessage; + using flutter::EncodableMap; + using flutter::EncodableValue; + video_player_videohole_tizen::CreateMessage msg; if (json_str.empty() || json_str == "{}") { @@ -575,266 +270,196 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( return msg; } -// C interface for plugin registration (required by C# -// GeneratedPluginRegistrant) and FFI exports +// ===== C interface for plugin registration ===== + extern "C" { void VideoPlayerTizenPluginRegisterWithRegistrar( FlutterDesktopPluginRegistrarRef registrar_ref) { - auto *plugin_registrar = + auto* plugin_registrar = flutter::PluginRegistrarManager::GetInstance() ->GetRegistrar(registrar_ref); - auto plugin = - std::make_unique( - registrar_ref, plugin_registrar); - plugin_registrar->AddPlugin(std::move(plugin)); + // Store global references for FFI functions + g_registrar_ref = registrar_ref; + g_plugin_registrar = plugin_registrar; } +} // extern "C" + +} // namespace video_player_videohole_tizen + +// ===== FFI Implementation ===== + +#include +#include +#include + +using video_player_videohole_tizen::CreateMessage; +using video_player_videohole_tizen::GetPlayer; +using video_player_videohole_tizen::g_dart_port; +using video_player_videohole_tizen::g_dart_port_mutex; +using video_player_videohole_tizen::g_options; +using video_player_videohole_tizen::g_plugin_registrar; +using video_player_videohole_tizen::g_players; +using video_player_videohole_tizen::g_players_mutex; +using video_player_videohole_tizen::g_registrar_ref; +using video_player_videohole_tizen::ParseCreateMessage; +using video_player_videohole_tizen::VideoPlayer; + +extern "C" { + int ffi_initialize() { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } + std::unique_lock lock(g_players_mutex); + g_players.clear(); + return 0; +} - auto result = plugin->Initialize(); - if (result.has_value()) { +int64_t ffi_create(const char* create_message_json) { + if (g_registrar_ref == nullptr || g_plugin_registrar == nullptr) { return -1; } - return 0; -} -int64_t ffi_create(const char *create_message_json) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { + FlutterDesktopViewRef view = FlutterDesktopPluginRegistrarGetView(g_registrar_ref); + if (!view) { return -1; } - video_player_videohole_tizen::CreateMessage msg; + CreateMessage msg; if (create_message_json != nullptr && strlen(create_message_json) > 0) { msg = ParseCreateMessage(std::string(create_message_json)); } - auto result = plugin->Create(msg); - if (result.has_error()) { + std::string uri; + if (msg.asset() && !msg.asset()->empty()) { + char* res_path = app_get_resource_path(); + if (res_path) { + uri = uri + res_path + "flutter_assets/" + *msg.asset(); + free(res_path); + } else { + return -1; + } + } else if (msg.uri() && !msg.uri()->empty()) { + uri = *msg.uri(); + } else { return -1; } - return result.value().player_id(); -} -int ffi_dispose(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { + auto player = std::make_unique( + g_plugin_registrar->messenger(), view); + int64_t player_id = player->Create(uri, msg); + if (player_id == -1) { return -1; } - auto player = - video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( - player_id); - if (player == nullptr) { - return 0; - } + std::unique_lock lock(g_players_mutex); + g_players[player_id] = std::move(player); + return player_id; +} - auto result = - plugin->Dispose(video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_value()) { - return -1; +int ffi_dispose(int64_t player_id) { + std::unique_lock lock(g_players_mutex); + auto iter = g_players.find(player_id); + if (iter != g_players.end()) { + iter->second->Dispose(); + g_players.erase(iter); } return 0; } int ffi_play(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto player = - video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( - player_id); - if (player == nullptr) { - return -1; - } - - auto result = - plugin->Play(video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->Play() ? 0 : -1; } int ffi_pause(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto player = - video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( - player_id); - if (player == nullptr) { - return -1; - } - - auto result = - plugin->Pause(video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->Pause() ? 0 : -1; } int ffi_seek_to(int64_t player_id, int64_t position_ms) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - - plugin->SeekTo( - video_player_videohole_tizen::PositionMessage(player_id, position_ms), - [](std::optional result) { - if (result.has_value()) { - // Error handling through events - } - }); - + player->SeekTo(position_ms, []() -> void { + // Seek completed callback - events are sent via FFI event port + }); return 0; } int64_t ffi_get_position(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto player = - video_player_videohole_tizen::VideoPlayerTizenPlugin::FindPlayerById( - player_id); - if (player == nullptr) { - return -1; - } - - auto result = - plugin->Position(video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_error()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return result.value().position(); + return player->GetPosition(); } -const char *ffi_get_duration(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return strdup("-1"); - } - - auto result = - plugin->Duration(video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_error()) { +const char* ffi_get_duration(int64_t player_id) { + auto player = GetPlayer(player_id); + if (!player) { return strdup("-1"); } - const auto &duration_range = result.value().duration_range(); - std::string duration_json; - if (duration_range && duration_range->size() >= 2) { - int64_t start = (*duration_range)[0].IsNull() - ? 0 - : std::get((*duration_range)[0]); - int64_t end = (*duration_range)[1].IsNull() - ? 0 - : std::get((*duration_range)[1]); - duration_json = "{\"start\":" + std::to_string(start) + - ",\"end\":" + std::to_string(end) + "}"; - } else { - duration_json = "{\"start\":0,\"end\":0}"; - } + auto duration_pair = player->GetDuration(); + std::string duration_json = "{\"start\":" + std::to_string(duration_pair.first) + + ",\"end\":" + std::to_string(duration_pair.second) + "}"; return strdup(duration_json.c_str()); } int ffi_set_volume(int64_t player_id, double volume) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetVolume( - video_player_videohole_tizen::VolumeMessage(player_id, volume)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->SetVolume(volume) ? 0 : -1; } int ffi_set_playback_speed(int64_t player_id, double speed) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetPlaybackSpeed( - video_player_videohole_tizen::PlaybackSpeedMessage(player_id, speed)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->SetPlaybackSpeed(speed) ? 0 : -1; } int ffi_set_looping(int64_t player_id, bool is_looping) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetLooping( - video_player_videohole_tizen::LoopingMessage(player_id, is_looping != 0)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->SetLooping(is_looping) ? 0 : -1; } -const char *ffi_get_track_info(int64_t player_id, const char *track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return nullptr; - } - - auto result = plugin->Track(video_player_videohole_tizen::TrackTypeMessage( - player_id, std::string(track_type))); - if (result.has_error()) { +const char* ffi_get_track_info(int64_t player_id, const char* track_type) { + auto player = GetPlayer(player_id); + if (!player || track_type == nullptr) { return nullptr; } - std::string track_info_json = - "{\"playerId\":" + std::to_string(result.value().player_id()) + - ",\"tracks\":["; + auto tracks = player->GetTrackInfo(std::string(track_type)); + std::string track_info_json = "{\"playerId\":" + std::to_string(player_id) + + ",\"tracks\":["; - const auto &tracks = result.value().tracks(); for (size_t i = 0; i < tracks.size(); ++i) { if (i > 0) track_info_json += ","; - const auto &track_map = std::get(tracks[i]); + const auto& track_map = std::get(tracks[i]); track_info_json += "{"; bool first = true; - for (const auto &[key, value] : track_map) { + for (const auto& [key, value] : track_map) { if (!first) track_info_json += ","; first = false; - const std::string *key_str = std::get_if(&key); + const std::string* key_str = std::get_if(&key); if (!key_str) continue; track_info_json += "\"" + *key_str + "\":"; @@ -860,137 +485,81 @@ const char *ffi_get_track_info(int64_t player_id, const char *track_type) { } int ffi_set_track_selection(int64_t player_id, int64_t track_id, - const char *track_type) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr || track_type == nullptr) { - return -1; - } - - auto result = plugin->SetTrackSelection( - video_player_videohole_tizen::SelectedTracksMessage( - player_id, track_id, std::string(track_type))); - if (result.has_error()) { + const char* track_type) { + auto player = GetPlayer(player_id); + if (!player || track_type == nullptr) { return -1; } - return result.value() ? 0 : -1; + return player->SetTrackSelection(track_id, std::string(track_type)) ? 0 : -1; } int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = - plugin->SetDisplayGeometry(video_player_videohole_tizen::GeometryMessage( - player_id, x, y, width, height)); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } + player->SetDisplayRoi(x, y, width, height); return 0; } int ffi_set_display_rotate(int64_t player_id, int32_t rotation) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetDisplayRotate( - video_player_videohole_tizen::RotationMessage(player_id, rotation)); - if (result.has_error()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return result.value() ? 0 : -1; + return player->SetDisplayRotate(rotation) ? 0 : -1; } int ffi_suspend(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->Suspend(player_id); - if (result.has_value()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return 0; + return player->Suspend() ? 0 : -1; } -int ffi_restore(int64_t player_id, const char *create_message_json, +int ffi_restore(int64_t player_id, const char* create_message_json, int64_t resume_time) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - video_player_videohole_tizen::CreateMessage msg; + CreateMessage msg; if (create_message_json != nullptr && strlen(create_message_json) > 0) { msg = ParseCreateMessage(std::string(create_message_json)); } - auto result = plugin->Restore(player_id, &msg, resume_time); - if (result.has_value()) { - return -1; - } - return 0; + return player->Restore(&msg, resume_time) ? 0 : -1; } int ffi_set_activate(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetActivate( - video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_error()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return result.value() ? 0 : -1; + return player->Activate() ? 0 : -1; } int ffi_set_deactivate(int64_t player_id) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetDeactivate( - video_player_videohole_tizen::PlayerMessage(player_id)); - if (result.has_error()) { + auto player = GetPlayer(player_id); + if (!player) { return -1; } - return result.value() ? 0 : -1; + return player->Deactivate() ? 0 : -1; } int ffi_set_mix_with_others(bool mix_with_others) { - auto *plugin = - video_player_videohole_tizen::VideoPlayerTizenPlugin::GetInstance(); - if (plugin == nullptr) { - return -1; - } - - auto result = plugin->SetMixWithOthers( - video_player_videohole_tizen::MixWithOthersMessage(mix_with_others)); - if (result.has_value()) { - return -1; - } + g_options.SetMixWithOthers(mix_with_others); return 0; } // FFI event port functions +// Note: g_dart_port and g_dart_port_mutex are declared in video_player.h static bool g_dart_api_dl_initialized = false; -int ffi_initialize_api_dl(void *data) { +int ffi_initialize_api_dl(void* data) { if (!g_dart_api_dl_initialized) { if (Dart_InitializeApiDL(data) == 0) { g_dart_api_dl_initialized = true; @@ -1002,11 +571,13 @@ int ffi_initialize_api_dl(void *data) { } void ffi_register_event_port(int64_t port) { - video_player_videohole_tizen::RegisterDartPort(port); + std::lock_guard lock(g_dart_port_mutex); + g_dart_port = port; } void ffi_unregister_event_port() { - video_player_videohole_tizen::RegisterDartPort(-1); + std::lock_guard lock(g_dart_port_mutex); + g_dart_port = 0; } } // extern "C" From c6c0570fecdf287fa0d8e07037027f0d892e2b7f Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Thu, 23 Jul 2026 17:09:17 +0800 Subject: [PATCH 10/18] code format --- .../tizen/src/video_player_tizen_plugin.cc | 27 +++++++++++-------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 2078fce08..5d9f552bb 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -26,16 +26,19 @@ namespace video_player_videohole_tizen { // ===== Global State ===== -// Player registry - manages all player instances using shared_ptr for thread safety +// Player registry - manages all player instances using shared_ptr for thread +// safety static std::map> g_players; -static std::shared_mutex g_players_mutex; // Read-write lock for better concurrency +static std::shared_mutex + g_players_mutex; // Read-write lock for better concurrency // Global resources needed for player creation static FlutterDesktopPluginRegistrarRef g_registrar_ref = nullptr; static flutter::PluginRegistrar* g_plugin_registrar = nullptr; static VideoPlayerOptions g_options; -// Helper function to get player by ID (returns shared_ptr, caller holds reference) +// Helper function to get player by ID (returns shared_ptr, caller holds +// reference) static std::shared_ptr GetPlayer(int64_t player_id) { std::shared_lock lock(g_players_mutex); // Read lock auto iter = g_players.find(player_id); @@ -182,9 +185,9 @@ static std::string ExtractObjectValue(const std::string& json_str, // Unified function to parse CreateMessage from JSON string static video_player_videohole_tizen::CreateMessage ParseCreateMessage( const std::string& json_str) { - using video_player_videohole_tizen::CreateMessage; using flutter::EncodableMap; using flutter::EncodableValue; + using video_player_videohole_tizen::CreateMessage; video_player_videohole_tizen::CreateMessage msg; @@ -296,14 +299,14 @@ void VideoPlayerTizenPluginRegisterWithRegistrar( #include using video_player_videohole_tizen::CreateMessage; -using video_player_videohole_tizen::GetPlayer; using video_player_videohole_tizen::g_dart_port; using video_player_videohole_tizen::g_dart_port_mutex; using video_player_videohole_tizen::g_options; -using video_player_videohole_tizen::g_plugin_registrar; using video_player_videohole_tizen::g_players; using video_player_videohole_tizen::g_players_mutex; +using video_player_videohole_tizen::g_plugin_registrar; using video_player_videohole_tizen::g_registrar_ref; +using video_player_videohole_tizen::GetPlayer; using video_player_videohole_tizen::ParseCreateMessage; using video_player_videohole_tizen::VideoPlayer; @@ -320,7 +323,8 @@ int64_t ffi_create(const char* create_message_json) { return -1; } - FlutterDesktopViewRef view = FlutterDesktopPluginRegistrarGetView(g_registrar_ref); + FlutterDesktopViewRef view = + FlutterDesktopPluginRegistrarGetView(g_registrar_ref); if (!view) { return -1; } @@ -409,8 +413,9 @@ const char* ffi_get_duration(int64_t player_id) { } auto duration_pair = player->GetDuration(); - std::string duration_json = "{\"start\":" + std::to_string(duration_pair.first) + - ",\"end\":" + std::to_string(duration_pair.second) + "}"; + std::string duration_json = + "{\"start\":" + std::to_string(duration_pair.first) + + ",\"end\":" + std::to_string(duration_pair.second) + "}"; return strdup(duration_json.c_str()); } @@ -445,8 +450,8 @@ const char* ffi_get_track_info(int64_t player_id, const char* track_type) { } auto tracks = player->GetTrackInfo(std::string(track_type)); - std::string track_info_json = "{\"playerId\":" + std::to_string(player_id) + - ",\"tracks\":["; + std::string track_info_json = + "{\"playerId\":" + std::to_string(player_id) + ",\"tracks\":["; for (size_t i = 0; i < tracks.size(); ++i) { if (i > 0) track_info_json += ","; From 29d58da17ba349369d80319871c4283a4f7fd29c Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Tue, 28 Jul 2026 18:12:08 +0800 Subject: [PATCH 11/18] fixed UI not refreshing issue and code structure updated --- .../lib/src/ffi_messages.g.dart | 770 +++++------------- .../lib/src/video_player_tizen.dart | 183 ++--- .../lib/video_player.dart | 30 +- .../lib/video_player_platform_interface.dart | 14 +- .../tizen/src/ffi_messages.h | 254 +----- .../tizen/src/media_player.cc | 63 +- .../tizen/src/media_player.h | 7 +- .../tizen/src/video_player.cc | 22 +- .../tizen/src/video_player.h | 8 +- .../tizen/src/video_player_tizen_plugin.cc | 23 +- 10 files changed, 381 insertions(+), 993 deletions(-) diff --git a/packages/video_player_videohole/lib/src/ffi_messages.g.dart b/packages/video_player_videohole/lib/src/ffi_messages.g.dart index ec445583d..55a5e1240 100644 --- a/packages/video_player_videohole/lib/src/ffi_messages.g.dart +++ b/packages/video_player_videohole/lib/src/ffi_messages.g.dart @@ -16,158 +16,29 @@ import 'package:flutter/foundation.dart' show ReadBuffer, WriteBuffer, debugPrint; import 'package:flutter/services.dart'; -// ===== Message Types ===== - -class PlayerMessage { - PlayerMessage({required this.playerId}); - - int playerId; - - Object encode() { - return [playerId]; - } - - static PlayerMessage decode(Object result) { - result as List; - return PlayerMessage(playerId: result[0]! as int); - } -} - -class LoopingMessage { - LoopingMessage({required this.playerId, required this.isLooping}); - - int playerId; - bool isLooping; - - Object encode() { - return [playerId, isLooping]; - } - - static LoopingMessage decode(Object result) { - result as List; - return LoopingMessage( - playerId: result[0]! as int, - isLooping: result[1]! as bool, - ); - } -} - -class VolumeMessage { - VolumeMessage({required this.playerId, required this.volume}); - - int playerId; - double volume; - - Object encode() { - return [playerId, volume]; - } - - static VolumeMessage decode(Object result) { - result as List; - return VolumeMessage( - playerId: result[0]! as int, - volume: result[1]! as double, - ); - } -} - -class PlaybackSpeedMessage { - PlaybackSpeedMessage({required this.playerId, required this.speed}); - - int playerId; - double speed; - - Object encode() { - return [playerId, speed]; - } - - static PlaybackSpeedMessage decode(Object result) { - result as List; - return PlaybackSpeedMessage( - playerId: result[0]! as int, - speed: result[1]! as double, - ); - } -} - class TrackMessage { TrackMessage({required this.playerId, required this.tracks}); int playerId; List?> tracks; - Object encode() { - return [playerId, tracks]; + /// Convert to JSON string for FFI call + String toJson() { + final Map jsonMap = { + 'playerId': playerId, + 'tracks': tracks, + }; + return jsonEncode(jsonMap); } - static TrackMessage decode(Object result) { - result as List; + /// Create from JSON string + static TrackMessage fromJson(String jsonString) { + final Map jsonMap = jsonDecode(jsonString); return TrackMessage( - playerId: result[0]! as int, - tracks: (result[1] as List?)!.cast?>(), - ); - } -} - -class TrackTypeMessage { - TrackTypeMessage({required this.playerId, required this.trackType}); - - int playerId; - String trackType; - - Object encode() { - return [playerId, trackType]; - } - - static TrackTypeMessage decode(Object result) { - result as List; - return TrackTypeMessage( - playerId: result[0]! as int, - trackType: result[1]! as String, - ); - } -} - -class SelectedTracksMessage { - SelectedTracksMessage({ - required this.playerId, - required this.trackId, - required this.trackType, - }); - - int playerId; - int trackId; - String trackType; - - Object encode() { - return [playerId, trackId, trackType]; - } - - static SelectedTracksMessage decode(Object result) { - result as List; - return SelectedTracksMessage( - playerId: result[0]! as int, - trackId: result[1]! as int, - trackType: result[2]! as String, - ); - } -} - -class PositionMessage { - PositionMessage({required this.playerId, required this.position}); - - int playerId; - int position; - - Object encode() { - return [playerId, position]; - } - - static PositionMessage decode(Object result) { - result as List; - return PositionMessage( - playerId: result[0]! as int, - position: result[1]! as int, + playerId: jsonMap['playerId'] as int, + tracks: (jsonMap['tracks'] as List) + .map((e) => (e as Map).cast()) + .toList(), ); } } @@ -191,77 +62,36 @@ class CreateMessage { Map? drmConfigs; Map? playerOptions; - Object encode() { - return [ - asset, - uri, - packageName, - formatHint, - httpHeaders, - drmConfigs, - playerOptions, - ]; + /// Convert to JSON string for FFI call + String toJson() { + final Map jsonMap = {}; + if (asset != null && asset!.isNotEmpty) jsonMap['asset'] = asset; + if (uri != null && uri!.isNotEmpty) jsonMap['uri'] = uri; + if (packageName != null && packageName!.isNotEmpty) + jsonMap['packageName'] = packageName; + if (formatHint != null && formatHint!.isNotEmpty) + jsonMap['formatHint'] = formatHint; + if (httpHeaders != null && httpHeaders!.isNotEmpty) + jsonMap['httpHeaders'] = httpHeaders; + if (drmConfigs != null && drmConfigs!.isNotEmpty) + jsonMap['drmConfigs'] = drmConfigs; + if (playerOptions != null && playerOptions!.isNotEmpty) + jsonMap['playerOptions'] = playerOptions; + return jsonEncode(jsonMap); } - static CreateMessage decode(Object result) { - result as List; + /// Create from JSON string + static CreateMessage fromJson(String jsonString) { + final Map jsonMap = jsonDecode(jsonString); return CreateMessage( - asset: result[0] as String?, - uri: result[1] as String?, - packageName: result[2] as String?, - formatHint: result[3] as String?, - httpHeaders: - (result[4] as Map?)?.cast(), - drmConfigs: - (result[5] as Map?)?.cast(), + asset: jsonMap['asset'] as String?, + uri: jsonMap['uri'] as String?, + packageName: jsonMap['packageName'] as String?, + formatHint: jsonMap['formatHint'] as String?, + httpHeaders: (jsonMap['httpHeaders'] as Map?)?.cast(), + drmConfigs: (jsonMap['drmConfigs'] as Map?)?.cast(), playerOptions: - (result[6] as Map?)?.cast(), - ); - } -} - -class MixWithOthersMessage { - MixWithOthersMessage({required this.mixWithOthers}); - - bool mixWithOthers; - - Object encode() { - return [mixWithOthers]; - } - - static MixWithOthersMessage decode(Object result) { - result as List; - return MixWithOthersMessage(mixWithOthers: result[0]! as bool); - } -} - -class GeometryMessage { - GeometryMessage({ - required this.playerId, - required this.x, - required this.y, - required this.width, - required this.height, - }); - - int playerId; - int x; - int y; - int width; - int height; - - Object encode() { - return [playerId, x, y, width, height]; - } - - static GeometryMessage decode(Object result) { - result as List; - return GeometryMessage( - playerId: result[0]! as int, - x: result[1]! as int, - y: result[2]! as int, - width: result[3]! as int, - height: result[4]! as int, + (jsonMap['playerOptions'] as Map?)?.cast(), ); } } @@ -272,34 +102,24 @@ class DurationMessage { int playerId; List? durationRange; - Object encode() { - return [playerId, durationRange]; + /// Convert to JSON string for FFI call + String toJson() { + final Map jsonMap = { + 'playerId': playerId, + if (durationRange != null) 'durationRange': durationRange, + }; + return jsonEncode(jsonMap); } - static DurationMessage decode(Object result) { - result as List; + /// Create from JSON string + /// C++ returns: {"playerId": , "durationRange": [, ]} + static DurationMessage fromJson(String jsonString) { + final Map jsonMap = jsonDecode(jsonString); return DurationMessage( - playerId: result[0]! as int, - durationRange: (result[1] as List?)?.cast(), - ); - } -} - -class RotationMessage { - RotationMessage({required this.playerId, required this.rotation}); - - int playerId; - int rotation; - - Object encode() { - return [playerId, rotation]; - } - - static RotationMessage decode(Object result) { - result as List; - return RotationMessage( - playerId: result[0]! as int, - rotation: result[1]! as int, + playerId: jsonMap['playerId'] as int, + durationRange: (jsonMap['durationRange'] as List?) + ?.map((e) => (e as num).toInt()) + .toList(), ); } } @@ -368,7 +188,7 @@ typedef _FFISetMixWithOthersDart = int Function(bool); typedef _FFISuspendNative = ffi.Int32 Function(ffi.Int64); typedef _FFISuspendDart = int Function(int); -typedef _FFIRestoreNative = ffi.Int32 Function( +typedef _FFIRestoreNative = ffi.Int64 Function( ffi.Int64, ffi.Pointer, ffi.Int64); typedef _FFIRestoreDart = int Function(int, ffi.Pointer, int); @@ -530,387 +350,229 @@ class VideoPlayerFFIBindings { } bool get isLoaded => _lib != null; +} - /// FFI initialize function - int ffiInitialize() { - if (!isLoaded) { - throw StateError('FFI bindings not loaded. Call load() first.'); - } - return _ffiInitialize(); - } - - /// FFI create function - takes a single JSON string for all parameters - int ffiCreate({ - String? uri, - String? asset, - String? packageName, - String? formatHint, - Map? httpHeaders, - Map? drmConfigs, - Map? playerOptions, - }) { - if (!isLoaded) { - throw StateError('FFI bindings not loaded. Call load() first.'); - } +// ===== FFI API Class ===== - // Build JSON string from individual parameters - final Map jsonMap = {}; - if (uri != null && uri.isNotEmpty) jsonMap['uri'] = uri; - if (asset != null && asset.isNotEmpty) jsonMap['asset'] = asset; - if (packageName != null && packageName.isNotEmpty) - jsonMap['packageName'] = packageName; - if (formatHint != null && formatHint.isNotEmpty) - jsonMap['formatHint'] = formatHint; - if (httpHeaders != null && httpHeaders.isNotEmpty) - jsonMap['httpHeaders'] = httpHeaders; - if (drmConfigs != null && drmConfigs.isNotEmpty) - jsonMap['drmConfigs'] = drmConfigs; - if (playerOptions != null && playerOptions.isNotEmpty) - jsonMap['playerOptions'] = playerOptions; +class VideoPlayerVideoholeFFIApi { + /// Initialize the FFI bindings + int initialize() { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiInitialize(); + } - final String jsonString = jsonEncode(jsonMap); + /// Create using CreateMessage object + int create(CreateMessage message) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final String jsonString = message.toJson(); final jsonPtr = _toPointer(jsonString); - try { - return _ffiCreate(jsonPtr); + return bindings._ffiCreate(jsonPtr); } finally { _freePointer(jsonPtr); } } -} - -// ===== FFI API Class ===== -class VideoPlayerFFIApi { - int initialize() { - return ffiInitialize(); - } - - int create({ - String? uri, - String? asset, - String? packageName, - String? formatHint, - Map? httpHeaders, - Map? drmConfigs, - Map? playerOptions, - }) { - return ffiCreate( - uri: uri, - asset: asset, - packageName: packageName, - formatHint: formatHint, - httpHeaders: httpHeaders, - drmConfigs: drmConfigs, - playerOptions: playerOptions, - ); + /// Restore using CreateMessage object + int restore(int playerId, CreateMessage? message, int resumeTime) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final String? jsonString = message?.toJson(); + final createMessagePtr = _toPointer(jsonString); + try { + return bindings._ffiRestore(playerId, createMessagePtr, resumeTime); + } finally { + _freePointer(createMessagePtr); + } } int dispose(int playerId) { - return ffiDispose(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiDispose(playerId); } int play(int playerId) { - return ffiPlay(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiPlay(playerId); } int pause(int playerId) { - return ffiPause(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiPause(playerId); } int seekTo(int playerId, int positionMs) { - return ffiSeekTo(playerId, positionMs); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSeekTo(playerId, positionMs); } int getPosition(int playerId) { - return ffiGetPosition(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiGetPosition(playerId); } DurationMessage duration(int playerId) { - return ffiGetDuration(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final ptr = bindings._ffiGetDuration(playerId); + if (ptr == ffi.nullptr) { + throw Exception('FFI getDuration failed - returned null pointer'); + } + try { + final bytes = ptr.cast(); + int length = 0; + while (bytes[length] != 0) { + length++; + } + final jsonString = utf8.decode(bytes.asTypedList(length)); + if (jsonString == '-1') { + throw Exception('FFI getDuration failed'); + } + return DurationMessage.fromJson(jsonString); + } finally { + calloc.free(ptr); + } } int setVolume(int playerId, double volume) { - return ffiSetVolume(playerId, volume); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetVolume(playerId, volume); } int setPlaybackSpeed(int playerId, double speed) { - return ffiSetPlaybackSpeed(playerId, speed); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetPlaybackSpeed(playerId, speed); } int setLooping(int playerId, bool isLooping) { - return ffiSetLooping(playerId, isLooping); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetLooping(playerId, isLooping); } int setDisplayGeometry(int playerId, int x, int y, int width, int height) { - return ffiSetDisplayGeometry(playerId, x, y, width, height); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDisplayGeometry(playerId, x, y, width, height); } int setDisplayRotate(int playerId, int rotation) { - return ffiSetDisplayRotate(playerId, rotation); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDisplayRotate(playerId, rotation); } int suspend(int playerId) { - return ffiSuspend(playerId); - } - - int restore(int playerId, String? createMessageJson, int resumeTime) { - return ffiRestore(playerId, createMessageJson, resumeTime); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSuspend(playerId); } int setActivate(int playerId) { - return ffiSetActivate(playerId); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetActivate(playerId); } int setDeactivate(int playerId) { - return ffiSetDeactivate(playerId); - } - - String getTrackInfo(int playerId, String trackType) { - return ffiGetTrackInfo(playerId, trackType); - } - - int setTrackSelection(int playerId, int trackId, String trackType) { - return ffiSetTrackSelection(playerId, trackId, trackType); - } - - int setMixWithOthers(bool mixWithOthers) { - return ffiSetMixWithOthers(mixWithOthers); - } -} - -// ===== Top-level FFI Functions ===== - -int ffiInitialize() { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings.ffiInitialize(); -} - -int ffiCreate({ - String? uri, - String? asset, - String? packageName, - String? formatHint, - Map? httpHeaders, - Map? drmConfigs, - Map? playerOptions, -}) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings.ffiCreate( - uri: uri, - asset: asset, - packageName: packageName, - formatHint: formatHint, - httpHeaders: httpHeaders, - drmConfigs: drmConfigs, - playerOptions: playerOptions, - ); -} - -int ffiDispose(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiDispose(playerId); -} - -int ffiPlay(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiPlay(playerId); -} - -int ffiPause(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetDeactivate(playerId); } - return bindings._ffiPause(playerId); -} -int ffiSeekTo(int playerId, int positionMs) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSeekTo(playerId, positionMs); -} - -int ffiGetPosition(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiGetPosition(playerId); -} - -DurationMessage ffiGetDuration(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - final ptr = bindings._ffiGetDuration(playerId); - if (ptr == ffi.nullptr) { - throw Exception('FFI getDuration failed - returned null pointer'); - } - try { - final bytes = ptr.cast(); - int length = 0; - while (bytes[length] != 0) { - length++; + TrackMessage getTrackInfo(int playerId, String trackType) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); } - final jsonString = utf8.decode(bytes.asTypedList(length)); - if (jsonString == '-1') { - throw Exception('FFI getDuration failed'); + final trackTypePtr = _toPointer(trackType); + ffi.Pointer? ptr; + try { + ptr = bindings._ffiGetTrackInfo(playerId, trackTypePtr); + if (ptr == ffi.nullptr) { + throw Exception('FFI getTrackInfo failed - returned null pointer'); + } + final bytes = ptr.cast(); + int length = 0; + while (bytes[length] != 0) { + length++; + } + final jsonString = utf8.decode(bytes.asTypedList(length)); + if (jsonString == '-1') { + throw Exception('FFI getTrackInfo failed'); + } + return TrackMessage.fromJson(jsonString); + } finally { + if (ptr != null) { + calloc.free(ptr.cast()); + } + _freePointer(trackTypePtr); } - final Map jsonMap = jsonDecode(jsonString); - return DurationMessage( - playerId: playerId, - durationRange: [ - jsonMap['start'] as int, - jsonMap['end'] as int, - ], - ); - } finally { - calloc.free(ptr); - } -} - -int ffiSetVolume(int playerId, double volume) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetVolume(playerId, volume); -} - -int ffiSetPlaybackSpeed(int playerId, double speed) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetPlaybackSpeed(playerId, speed); -} - -int ffiSetLooping(int playerId, bool isLooping) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetLooping(playerId, isLooping); -} - -int ffiSetDisplayGeometry(int playerId, int x, int y, int width, int height) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetDisplayGeometry(playerId, x, y, width, height); -} - -int ffiSetDisplayRotate(int playerId, int rotation) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetDisplayRotate(playerId, rotation); -} - -int ffiSuspend(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); } - return bindings._ffiSuspend(playerId); -} - -int ffiRestore(int playerId, String? createMessageJson, int resumeTime) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - final createMessagePtr = _toPointer(createMessageJson); - try { - return bindings._ffiRestore(playerId, createMessagePtr, resumeTime); - } finally { - _freePointer(createMessagePtr); - } -} - -int ffiSetActivate(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetActivate(playerId); -} -int ffiSetDeactivate(int playerId) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - return bindings._ffiSetDeactivate(playerId); -} - -String ffiGetTrackInfo(int playerId, String trackType) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - final trackTypePtr = _toPointer(trackType); - ffi.Pointer? ptr; - try { - ptr = bindings._ffiGetTrackInfo(playerId, trackTypePtr); - if (ptr == ffi.nullptr) { - throw Exception('FFI getTrackInfo failed - returned null pointer'); - } - final bytes = ptr.cast(); - int length = 0; - while (bytes[length] != 0) { - length++; - } - final jsonString = utf8.decode(bytes.asTypedList(length)); - if (jsonString == '-1') { - throw Exception('FFI getTrackInfo failed'); + int setTrackSelection(int playerId, int trackId, String trackType) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); } - return jsonString; - } finally { - if (ptr != null) { - calloc.free(ptr.cast()); + final trackTypePtr = _toPointer(trackType); + try { + return bindings._ffiSetTrackSelection(playerId, trackId, trackTypePtr); + } finally { + _freePointer(trackTypePtr); } - _freePointer(trackTypePtr); - } -} - -int ffiSetTrackSelection(int playerId, int trackId, String trackType) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); - } - final trackTypePtr = _toPointer(trackType); - try { - return bindings._ffiSetTrackSelection(playerId, trackId, trackTypePtr); - } finally { - _freePointer(trackTypePtr); } -} -int ffiSetMixWithOthers(bool mixWithOthers) { - final bindings = VideoPlayerFFIBindings.instance; - if (!bindings.isLoaded) { - bindings.load(); + int setMixWithOthers(bool mixWithOthers) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + return bindings._ffiSetMixWithOthers(mixWithOthers); } - return bindings._ffiSetMixWithOthers(mixWithOthers); } // ===== FFI Event Port Section - Using Dart_PostCObject_DL ===== diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index eeee95335..b027c410a 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -18,7 +18,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { /// Create a new VideoPlayerTizen instance. VideoPlayerTizen() : super(); - final VideoPlayerFFIApi _ffiApi = VideoPlayerFFIApi(); + final VideoPlayerVideoholeFFIApi _ffiApi = VideoPlayerVideoholeFFIApi(); @override Future init() async { @@ -53,28 +53,26 @@ class VideoPlayerTizen extends VideoPlayerPlatform { // This is important because events may be sent immediately after creation _ensureEventPortRegistered(); - // Use FFI for create (synchronous call) - int playerId; + // Use CreateMessage class for FFI create (synchronous call) + final CreateMessage message = CreateMessage(); switch (dataSource.sourceType) { case DataSourceType.asset: - playerId = _ffiApi.create( - asset: dataSource.asset, - packageName: dataSource.package, - ); + message.asset = dataSource.asset; + message.packageName = dataSource.package; case DataSourceType.network: - playerId = _ffiApi.create( - uri: dataSource.uri, - formatHint: _videoFormatStringMap[dataSource.formatHint], - httpHeaders: dataSource.httpHeaders, - drmConfigs: dataSource.drmConfigs?.toMap(), - playerOptions: dataSource.playerOptions, - ); + message.uri = dataSource.uri; + message.formatHint = _videoFormatStringMap[dataSource.formatHint]; + message.httpHeaders = dataSource.httpHeaders; + message.drmConfigs = dataSource.drmConfigs?.toMap(); + message.playerOptions = dataSource.playerOptions; case DataSourceType.file: case DataSourceType.contentUri: - playerId = _ffiApi.create(uri: dataSource.uri); + message.uri = dataSource.uri; } + final int playerId = _ffiApi.create(message); + if (playerId < 0) { throw Exception('FFI create failed with code: $playerId'); } @@ -105,7 +103,8 @@ class VideoPlayerTizen extends VideoPlayerPlatform { final StreamController? controller = _eventControllers[receivingPlayerId]; if (controller != null && !controller.isClosed) { - controller.add(_parseVideoEventFromMap(eventMap)); + final VideoEvent videoEvent = _parseVideoEventFromMap(eventMap); + controller.add(videoEvent); } } } catch (e, stackTrace) { @@ -197,20 +196,14 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future> getVideoTracks(int playerId) async { - // Use FFI for getTrackInfo (synchronous call) - // C++ returns: {"playerId": , "tracks": [{...}, ...]} - final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'video'); - final Map responseJson = - jsonDecode(jsonResponse) as Map; - final List tracksJson = responseJson['tracks'] as List; + final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'video'); final List videoTracks = []; - for (final dynamic trackMap in tracksJson) { - final Map track = trackMap as Map; - final int trackId = track['trackId'] as int; - final int bitrate = track['bitrate'] as int; - final int width = track['width'] as int; - final int height = track['height'] as int; + for (final Map? trackMap in message.tracks) { + final int trackId = trackMap!['trackId']! as int; + final int bitrate = trackMap['bitrate']! as int; + final int width = trackMap['width']! as int; + final int height = trackMap['height']! as int; videoTracks.add( VideoTrack( @@ -227,20 +220,14 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future> getAudioTracks(int playerId) async { - // Use FFI for getTrackInfo (synchronous call) - // C++ returns: {"playerId": , "tracks": [{...}, ...]} - final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'audio'); - final Map responseJson = - jsonDecode(jsonResponse) as Map; - final List tracksJson = responseJson['tracks'] as List; + final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'audio'); final List audioTracks = []; - for (final dynamic trackMap in tracksJson) { - final Map track = trackMap as Map; - final int trackId = track['trackId'] as int; - final String language = track['language'] as String; - final int channel = track['channel'] as int; - final int bitrate = track['bitrate'] as int; + for (final Map? trackMap in message.tracks) { + final int trackId = trackMap!['trackId']! as int; + final String language = trackMap['language']! as String; + final int channel = trackMap['channel']! as int; + final int bitrate = trackMap['bitrate']! as int; audioTracks.add( AudioTrack( @@ -257,18 +244,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future> getTextTracks(int playerId) async { - // Use FFI for getTrackInfo (synchronous call) - // C++ returns: {"playerId": , "tracks": [{...}, ...]} - final String jsonResponse = _ffiApi.getTrackInfo(playerId, 'text'); - final Map responseJson = - jsonDecode(jsonResponse) as Map; - final List tracksJson = responseJson['tracks'] as List; + final TrackMessage message = _ffiApi.getTrackInfo(playerId, 'text'); final List textTracks = []; - for (final dynamic trackMap in tracksJson) { - final Map track = trackMap as Map; - final int trackId = track['trackId'] as int; - final String language = track['language'] as String; + for (final Map? trackMap in message.tracks) { + final int trackId = trackMap!['trackId']! as int; + final String language = trackMap['language']! as String; textTracks.add(TextTrack(trackId: trackId, language: language)); } @@ -319,39 +300,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Stream videoEventsFor(int playerId) { - // Initialize the RawReceivePort once for all players - if (_eventPort == null) { - _eventPort = RawReceivePort(); - - // Listen to FFI events and route them to the appropriate StreamController - _eventPort!.handler = (dynamic message) { - try { - // Message format from C++: [player_id, event_json_string] - if (message is List && message.length == 2) { - final int receivingPlayerId = message[0] as int; - final String eventJson = message[1] as String; - - // Parse JSON to Map - final Map eventMap = - jsonDecode(eventJson) as Map; - - // Route to the correct StreamController - final StreamController? controller = - _eventControllers[receivingPlayerId]; - if (controller != null && !controller.isClosed) { - controller.add(_parseVideoEventFromMap(eventMap)); - } - } - } catch (e, stackTrace) { - // Log error but don't crash - debugPrint('Error processing FFI event: $e\n$stackTrace'); - } - }; - - // Register the port with C++ side using FFI - // Use NativePort extension to get the raw port number from RawReceivePort - ffiRegisterEventPort(_eventPort!.nativePort); - } + _ensureEventPortRegistered(); // Return the stream for this specific player return _eventControllers @@ -451,59 +400,53 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } @override - Future restore( + Future restore( int playerId, { DataSource? dataSource, int resumeTime = -1, }) async { // Use FFI for restore (synchronous call) - // Build JSON string from dataSource (same pattern as create) - String? createMessageJson; + // Use CreateMessage class (JSON conversion handled internally) + CreateMessage? message; if (dataSource != null) { - final Map jsonMap = {}; + message = CreateMessage(); switch (dataSource.sourceType) { case DataSourceType.asset: - if (dataSource.asset != null && dataSource.asset!.isNotEmpty) { - jsonMap['asset'] = dataSource.asset; - } - if (dataSource.package != null && dataSource.package!.isNotEmpty) { - jsonMap['packageName'] = dataSource.package; - } + message.asset = dataSource.asset; + message.packageName = dataSource.package; case DataSourceType.network: - if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { - jsonMap['uri'] = dataSource.uri; - } - if (dataSource.formatHint != null) { - jsonMap['formatHint'] = - _videoFormatStringMap[dataSource.formatHint]; - } - if (dataSource.httpHeaders.isNotEmpty) { - jsonMap['httpHeaders'] = dataSource.httpHeaders; - } - if (dataSource.drmConfigs != null) { - jsonMap['drmConfigs'] = dataSource.drmConfigs!.toMap(); - } - if (dataSource.playerOptions != null && - dataSource.playerOptions!.isNotEmpty) { - jsonMap['playerOptions'] = dataSource.playerOptions; - } + message.uri = dataSource.uri; + message.formatHint = _videoFormatStringMap[dataSource.formatHint]; + message.httpHeaders = dataSource.httpHeaders; + message.drmConfigs = dataSource.drmConfigs?.toMap(); + message.playerOptions = dataSource.playerOptions; case DataSourceType.file: case DataSourceType.contentUri: - if (dataSource.uri != null && dataSource.uri!.isNotEmpty) { - jsonMap['uri'] = dataSource.uri; - } + message.uri = dataSource.uri; } - - createMessageJson = jsonEncode(jsonMap); } - final int result = _ffiApi.restore(playerId, createMessageJson, resumeTime); - if (result != 0) { - // FFI restore failed, but don't throw - just return - // The player may still be in a valid state - return; + // Restore returns the new player ID (may be same or different) + final int newPlayerId = _ffiApi.restore(playerId, message, resumeTime); + + // If player ID changed, update the StreamController + if (newPlayerId != playerId && newPlayerId > 0) { + // Close old StreamController + final StreamController? oldController = + _eventControllers.remove(playerId); + if (oldController != null && !oldController.isClosed) { + await oldController.close(); + } + + // Create new StreamController for the new player ID + _eventControllers.putIfAbsent( + newPlayerId, + () => StreamController.broadcast(), + ); } + + return newPlayerId; } @override diff --git a/packages/video_player_videohole/lib/video_player.dart b/packages/video_player_videohole/lib/video_player.dart index 9377a9b1f..54a0a93ae 100644 --- a/packages/video_player_videohole/lib/video_player.dart +++ b/packages/video_player_videohole/lib/video_player.dart @@ -371,6 +371,10 @@ class VideoPlayerController extends ValueNotifier { RestoreDataSourceCallback? _onRestoreDataSource; RestoreTimeCallback? _onRestoreTime; + // Store event and error listeners for re-subscription during restore + void Function(VideoEvent)? _eventListener; + void Function(Object)? _errorListener; + /// The id of a player that hasn't been initialized. @visibleForTesting static const int kUninitializedPlayerId = -1; @@ -435,7 +439,7 @@ class VideoPlayerController extends ValueNotifier { _creatingCompleter!.complete(null); final Completer initializingCompleter = Completer(); - void eventListener(VideoEvent event) { + _eventListener = (VideoEvent event) { if (_isDisposed) { return; } @@ -509,7 +513,7 @@ class VideoPlayerController extends ValueNotifier { case VideoEventType.unknown: break; } - } + }; if (closedCaptionFile != null) { _closedCaptionFile ??= await closedCaptionFile; @@ -529,7 +533,7 @@ class VideoPlayerController extends ValueNotifier { }); } - void errorListener(Object obj) { + _errorListener = (Object obj) { final PlatformException e = obj as PlatformException; value = VideoPlayerValue.erroneous(e.message!); if (!initializingCompleter.isCompleted) { @@ -540,11 +544,11 @@ class VideoPlayerController extends ValueNotifier { if (!initializingCompleter.isCompleted) { initializingCompleter.completeError(obj); } - } + }; _eventSubscription = _videoPlayerPlatform .videoEventsFor(_playerId) - .listen(eventListener, onError: errorListener); + .listen(_eventListener!, onError: _errorListener); return initializingCompleter.future; } @@ -630,7 +634,7 @@ class VideoPlayerController extends ValueNotifier { return Timer.periodic(const Duration(milliseconds: 500), ( Timer timer, ) async { - if (_isDisposed) { + if (_isDisposed || _isDisposedOrNotInitialized) { return; } final Duration? newPosition = await position; @@ -913,11 +917,23 @@ class VideoPlayerController extends ValueNotifier { (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; final int resumeTime = (_onRestoreTime != null) ? _onRestoreTime!() : -1; - await _videoPlayerPlatform.restore( + // Restore returns the new player ID (may be same or different) + final int newPlayerId = await _videoPlayerPlatform.restore( _playerId, dataSource: dataSource, resumeTime: resumeTime, ); + + // Update playerId if it changed during restore + if (newPlayerId != _playerId && newPlayerId > 0) { + _playerId = newPlayerId; + + // Re-subscribe to event stream with the new player ID + await _eventSubscription?.cancel(); + _eventSubscription = _videoPlayerPlatform + .videoEventsFor(_playerId) + .listen(_eventListener, onError: _errorListener); + } } /// Set the rotate angle of display diff --git a/packages/video_player_videohole/lib/video_player_platform_interface.dart b/packages/video_player_videohole/lib/video_player_platform_interface.dart index 68b127015..f80932843 100644 --- a/packages/video_player_videohole/lib/video_player_platform_interface.dart +++ b/packages/video_player_videohole/lib/video_player_platform_interface.dart @@ -29,19 +29,8 @@ abstract class VideoPlayerPlatform extends PlatformInterface { /// The default instance of [VideoPlayerPlatform] to use. /// /// Defaults to [VideoPlayerTizen]. - /// - /// The [binaryMessenger] argument is used for communicating with the - /// platform-side EventChannel for event notifications. static VideoPlayerPlatform get instance => _instance; - /// Sets the default instance of [VideoPlayerPlatform] to use. - /// - /// This should be called by platform-specific code to initialize - /// the platform interface. - static void setupInstance() { - _instance = VideoPlayerTizen(); - } - /// Platform-specific plugins should override this with their own /// platform-specific class that extends [VideoPlayerPlatform] when they /// register themselves. @@ -170,7 +159,8 @@ abstract class VideoPlayerPlatform extends PlatformInterface { } /// Restores the player state when the application is resumed. - Future restore( + /// Returns the new player ID (may be same or different from the original). + Future restore( int playerId, { DataSource? dataSource, int resumeTime = -1, diff --git a/packages/video_player_videohole/tizen/src/ffi_messages.h b/packages/video_player_videohole/tizen/src/ffi_messages.h index 171423ffb..4caf3d136 100644 --- a/packages/video_player_videohole/tizen/src/ffi_messages.h +++ b/packages/video_player_videohole/tizen/src/ffi_messages.h @@ -41,8 +41,8 @@ int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height); int ffi_set_display_rotate(int64_t player_id, int32_t rotation); int ffi_suspend(int64_t player_id); -int ffi_restore(int64_t player_id, const char* create_message_json, - int64_t resume_time); +int64_t ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time); int ffi_set_activate(int64_t player_id); int ffi_set_deactivate(int64_t player_id); int ffi_set_mix_with_others(bool mix_with_others); @@ -59,255 +59,7 @@ void ffi_unregister_event_port(); namespace video_player_videohole_tizen { -// Error type -class FlutterError { - public: - explicit FlutterError(const std::string& code) : code_(code) {} - explicit FlutterError(const std::string& code, const std::string& message) - : code_(code), message_(message) {} - explicit FlutterError(const std::string& code, const std::string& message, - const flutter::EncodableValue& details) - : code_(code), message_(message), details_(details) {} - - const std::string& code() const { return code_; } - const std::string& message() const { return message_; } - const flutter::EncodableValue& details() const { return details_; } - - private: - std::string code_; - std::string message_; - flutter::EncodableValue details_; -}; - -// ErrorOr template type -template -class ErrorOr { - public: - ErrorOr(const T& rhs) : v_(rhs) {} - ErrorOr(const T&& rhs) : v_(std::move(rhs)) {} - ErrorOr(const FlutterError& rhs) : v_(rhs) {} - ErrorOr(const FlutterError&& rhs) : v_(std::move(rhs)) {} - - bool has_error() const { return std::holds_alternative(v_); } - const T& value() const { return std::get(v_); }; - const FlutterError& error() const { return std::get(v_); }; - - private: - friend class VideoPlayerVideoholeApi; - ErrorOr() = default; - T TakeValue() && { return std::get(std::move(v_)); } - - std::variant v_; -}; - -// PlayerMessage - player identifier -class PlayerMessage { - public: - explicit PlayerMessage(int64_t id) : player_id_(id) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - private: - int64_t player_id_; -}; - -// LoopingMessage - looping state -class LoopingMessage { - public: - LoopingMessage(int64_t id, bool looping) - : player_id_(id), is_looping_(looping) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - bool is_looping() const { return is_looping_; } - void set_is_looping(bool value) { is_looping_ = value; } - - private: - int64_t player_id_; - bool is_looping_; -}; - -// VolumeMessage - volume level -class VolumeMessage { - public: - VolumeMessage(int64_t id, double vol) : player_id_(id), volume_(vol) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - double volume() const { return volume_; } - void set_volume(double value) { volume_ = value; } - - private: - int64_t player_id_; - double volume_; -}; - -// PlaybackSpeedMessage - playback speed -class PlaybackSpeedMessage { - public: - PlaybackSpeedMessage(int64_t id, double speed) - : player_id_(id), speed_(speed) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - double speed() const { return speed_; } - void set_speed(double value) { speed_ = value; } - - private: - int64_t player_id_; - double speed_; -}; - -// TrackMessage - track information -class TrackMessage { - public: - TrackMessage(int64_t id, const flutter::EncodableList& tracks) - : player_id_(id), tracks_(tracks) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - const flutter::EncodableList& tracks() const { return tracks_; } - void set_tracks(const flutter::EncodableList& value) { tracks_ = value; } - - private: - int64_t player_id_; - flutter::EncodableList tracks_; -}; - -// TrackTypeMessage - track type identifier -class TrackTypeMessage { - public: - TrackTypeMessage(int64_t id, const std::string& type) - : player_id_(id), track_type_(type) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - const std::string& track_type() const { return track_type_; } - void set_track_type(const std::string& value) { track_type_ = value; } - - private: - int64_t player_id_; - std::string track_type_; -}; - -// SelectedTracksMessage - selected track info -class SelectedTracksMessage { - public: - SelectedTracksMessage(int64_t id, int64_t track_id, const std::string& type) - : player_id_(id), track_id_(track_id), track_type_(type) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - int64_t track_id() const { return track_id_; } - void set_track_id(int64_t value) { track_id_ = value; } - - const std::string& track_type() const { return track_type_; } - void set_track_type(const std::string& value) { track_type_ = value; } - - private: - int64_t player_id_; - int64_t track_id_; - std::string track_type_; -}; - -// PositionMessage - playback position -class PositionMessage { - public: - PositionMessage(int64_t id, int64_t pos) : player_id_(id), position_(pos) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - int64_t position() const { return position_; } - void set_position(int64_t value) { position_ = value; } - - private: - int64_t player_id_; - int64_t position_; -}; - -// DurationMessage - duration range -class DurationMessage { - public: - explicit DurationMessage(int64_t id) : player_id_(id) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - const std::optional& duration_range() const { - return duration_range_; - } - void set_duration_range(const flutter::EncodableList& value) { - duration_range_ = value; - } - - private: - int64_t player_id_; - std::optional duration_range_; -}; - -// GeometryMessage - display geometry (ROI) -class GeometryMessage { - public: - GeometryMessage(int64_t id, int32_t x, int32_t y, int32_t w, int32_t h) - : player_id_(id), x_(x), y_(y), width_(w), height_(h) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - int32_t x() const { return x_; } - void set_x(int32_t value) { x_ = value; } - - int32_t y() const { return y_; } - void set_y(int32_t value) { y_ = value; } - - int32_t width() const { return width_; } - void set_width(int32_t value) { width_ = value; } - - int32_t height() const { return height_; } - void set_height(int32_t value) { height_ = value; } - - private: - int64_t player_id_; - int32_t x_, y_, width_, height_; -}; - -// RotationMessage - display rotation -class RotationMessage { - public: - RotationMessage(int64_t id, int32_t r) : player_id_(id), rotation_(r) {} - - int64_t player_id() const { return player_id_; } - void set_player_id(int64_t value) { player_id_ = value; } - - int32_t rotation() const { return rotation_; } - void set_rotation(int32_t value) { rotation_ = value; } - - private: - int64_t player_id_; - int32_t rotation_; -}; - -// MixWithOthersMessage - mix with others setting -class MixWithOthersMessage { - public: - explicit MixWithOthersMessage(bool m) : mix_with_others_(m) {} - - bool mix_with_others() const { return mix_with_others_; } - void set_mix_with_others(bool value) { mix_with_others_ = value; } - - private: - bool mix_with_others_; -}; - -// CreateMessage - player creation parameters +// CreateMessage - player creation parameters (used by FFI create/restore) class CreateMessage { public: CreateMessage() = default; diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 82bbcff53..975c47712 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -230,6 +230,7 @@ bool MediaPlayer::Play() { LOG_ERROR("[MediaPlayer] player_start failed: %s.", get_error_message(ret)); return false; } + SendIsPlayingState(true); return true; } @@ -311,10 +312,15 @@ bool MediaPlayer::SeekTo(int64_t position, SeekCompletedCallback callback) { } int64_t MediaPlayer::GetPosition() { + if (!player_) { + LOG_ERROR("[MediaPlayer] player_ is null, cannot get position."); + return -1; + } + int position = 0; int ret = player_get_play_position(player_, &position); if (ret != PLAYER_ERROR_NONE) { - LOG_ERROR("[MediaPlayer] player_get_play_position failed: %s.", + LOG_DEBUG("[MediaPlayer] player_get_play_position failed: %s.", get_error_message(ret)); } LOG_DEBUG("[MediaPlayer] Video current position : %d.", position); @@ -376,7 +382,6 @@ bool MediaPlayer::IsReady() { } bool MediaPlayer::SetDisplay() { - LOG_INFO("***********SetDisplay start**************"); void *native_window = GetWindowHandle(); if (!native_window) { LOG_ERROR("[MediaPlayer] Could not get a native window handle."); @@ -400,7 +405,6 @@ bool MediaPlayer::SetDisplay() { get_error_message(ret)); return false; } - LOG_INFO("***********SetDisplay end**************"); return true; } @@ -428,20 +432,19 @@ static std::vector split(const std::string &s, char delim) { std::pair MediaPlayer::GetLiveDuration() { std::string live_duration_str = ""; - char *live_duration_buff = static_cast(malloc(sizeof(char) * 64)); - memset(live_duration_buff, 0, sizeof(char) * 64); + char live_duration_buff[64] = { + 0, + }; int ret = media_player_proxy_->player_get_adaptive_streaming_info( - player_, (void *)&live_duration_buff, PLAYER_ADAPTIVE_INFO_LIVE_DURATION); + player_, (void *)live_duration_buff, PLAYER_ADAPTIVE_INFO_LIVE_DURATION); if (ret != PLAYER_ERROR_NONE) { LOG_ERROR("[MediaPlayer] player_get_adaptive_streaming_info failed: %s", get_error_message(ret)); - free(live_duration_buff); return std::make_pair(0, 0); } - if (*live_duration_buff) { + if (live_duration_buff[0]) { live_duration_str = std::string(live_duration_buff); } - free(live_duration_buff); if (live_duration_str.empty()) { return std::make_pair(0, 0); } @@ -777,8 +780,8 @@ bool MediaPlayer::Suspend() { return true; } -bool MediaPlayer::Restore(const CreateMessage *restore_message, - int64_t resume_time) { +int64_t MediaPlayer::Restore(const CreateMessage *restore_message, + int64_t resume_time) { LOG_INFO("[MediaPlayer] Restore is called."); player_state_e player_state = PLAYER_STATE_NONE; @@ -789,7 +792,7 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, LOG_ERROR( "[MediaPlayer] Player get state failed or in invalid state[%d].", player_state); - return false; + return -1; } } @@ -799,7 +802,7 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, "instance."); if (player_ && !StopAndDestroy()) { LOG_ERROR("[MediaPlayer] Player StopAndDestroy fail."); - return false; + return -1; } return RestorePlayer(restore_message, resume_time); } @@ -810,12 +813,6 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, break; case PLAYER_STATE_PAUSED: if (pre_state_ == PLAYER_STATE_PLAYING) { - // 不尝试 Play(),直接重建 player - // 因为 Play() 可能会阻塞很长时间(甚至卡死) - // 而且最终也会 fallback 到 RestorePlayer - LOG_INFO( - "[MediaPlayer] Restore: skipping Play(), calling RestorePlayer " - "directly."); return RestorePlayer(restore_message, resume_time); } break; @@ -829,17 +826,18 @@ bool MediaPlayer::Restore(const CreateMessage *restore_message, player_state); return RestorePlayer(restore_message, resume_time); } - return true; + // Return current player ID when no restore is needed + return player_id_; } -bool MediaPlayer::RestorePlayer(const CreateMessage *restore_message, - int64_t resume_time) { +int64_t MediaPlayer::RestorePlayer(const CreateMessage *restore_message, + int64_t resume_time) { LOG_INFO("[MediaPlayer] RestorePlayer is called."); // 先清理旧的 player,避免状态冲突导致卡死 if (player_ && !StopAndDestroy()) { LOG_ERROR("[MediaPlayer] RestorePlayer: StopAndDestroy failed."); - return false; + return -1; } LOG_INFO("[MediaPlayer] RestorePlayer: old player cleaned up."); @@ -860,13 +858,15 @@ bool MediaPlayer::RestorePlayer(const CreateMessage *restore_message, if (resume_time >= 0) pre_playing_time_ = static_cast(resume_time); is_restored_ = true; - if (Create(url_, create_message_) < 0) { + int64_t new_player_id = Create(url_, create_message_); + if (new_player_id < 0) { LOG_ERROR("[MediaPlayer] Fail to create player."); is_restored_ = false; - return false; + return -1; } - return true; + // Return the new player ID + return new_player_id; } bool MediaPlayer::SetDisplayRotate(int64_t rotation) { @@ -903,13 +903,18 @@ void MediaPlayer::OnPrepared(void *user_data) { LOG_INFO("[MediaPlayer] Player prepared."); MediaPlayer *self = static_cast(user_data); - if (!self->is_initialized_) { - self->SendInitialized(); - } + // Reset event dispatch state for restored player BEFORE sending any events + // This ensures event_dispatch_state_->player points to the correct instance if (self->is_restored_) { + self->ResetEventDispatchState(); + LOG_INFO("[MediaPlayer] Event dispatch state reset for restored player."); self->OnRestoreCompleted(); } + + if (!self->is_initialized_) { + self->SendInitialized(); + } } void MediaPlayer::OnBuffering(int percent, void *user_data) { diff --git a/packages/video_player_videohole/tizen/src/media_player.h b/packages/video_player_videohole/tizen/src/media_player.h index 3a3506c2d..1c0cf8cdf 100644 --- a/packages/video_player_videohole/tizen/src/media_player.h +++ b/packages/video_player_videohole/tizen/src/media_player.h @@ -43,8 +43,8 @@ class MediaPlayer : public VideoPlayer { flutter::EncodableList GetTrackInfo(std::string track_type) override; bool SetTrackSelection(int32_t track_id, std::string track_type) override; bool Suspend() override; - bool Restore(const CreateMessage *restore_message, - int64_t resume_time) override; + int64_t Restore(const CreateMessage *restore_message, + int64_t resume_time) override; bool SetDisplayRotate(int64_t rotation) override; private: @@ -54,7 +54,8 @@ class MediaPlayer : public VideoPlayer { bool SetDrm(const std::string &uri, int drm_type, const std::string &license_server_url); bool StopAndDestroy(); - bool RestorePlayer(const CreateMessage *restore_message, int64_t resume_time); + int64_t RestorePlayer(const CreateMessage *restore_message, + int64_t resume_time); void OnRestoreCompleted(); static void OnPrepared(void *user_data); diff --git a/packages/video_player_videohole/tizen/src/video_player.cc b/packages/video_player_videohole/tizen/src/video_player.cc index 6f14329be..9322ad5ac 100644 --- a/packages/video_player_videohole/tizen/src/video_player.cc +++ b/packages/video_player_videohole/tizen/src/video_player.cc @@ -41,12 +41,6 @@ void PostEventToDart(int64_t player_id, const std::string& event_json) { return; } - LOG_INFO( - "[VideoPlayer] Posting event to Dart: player_id=%lld, event=%s, " - "port=%lld", - static_cast(player_id), event_json.c_str(), - static_cast(g_dart_port)); - // Message format: [player_id, event_json] // This matches what Dart side expects Dart_CObject player_id_obj; @@ -70,10 +64,7 @@ void PostEventToDart(int64_t player_id, const std::string& event_json) { message.value.as_array.length = 2; message.value.as_array.values = array_elements; - LOG_INFO("[VideoPlayer] Calling Dart_PostCObject_DL..."); - bool result = Dart_PostCObject_DL(g_dart_port, &message); - LOG_INFO("[VideoPlayer] Dart_PostCObject_DL result: %d", result ? 1 : 0); if (!result) { LOG_ERROR("[VideoPlayer] Failed to post event to Dart. Freeing json_copy."); @@ -219,6 +210,17 @@ VideoPlayer::~VideoPlayer() { main_context_.reset(); } +void VideoPlayer::ResetEventDispatchState() { + if (event_dispatch_state_) { + std::lock_guard lock(event_dispatch_state_->mutex); + event_dispatch_state_->disposed = false; + event_dispatch_state_->player = this; + event_dispatch_state_->pending_source_id = 0; + LOG_INFO("[VideoPlayer] ResetEventDispatchState: player=%p, this=%p", + event_dispatch_state_->player, this); + } +} + void VideoPlayer::ExecuteSinkEvents() { std::lock_guard lock(queue_mutex_); while (!encodable_event_queue_.empty()) { @@ -258,6 +260,8 @@ void VideoPlayer::ScheduleSendPendingEvents() { auto* state = new std::shared_ptr(event_dispatch_state_); GSource* source = g_idle_source_new(); + + // CRITICAL: Set callback BEFORE attaching to main context! g_source_set_callback( source, [](gpointer data) -> gboolean { diff --git a/packages/video_player_videohole/tizen/src/video_player.h b/packages/video_player_videohole/tizen/src/video_player.h index 52ced8832..470574de2 100644 --- a/packages/video_player_videohole/tizen/src/video_player.h +++ b/packages/video_player_videohole/tizen/src/video_player.h @@ -78,8 +78,9 @@ class VideoPlayer { virtual flutter::EncodableList GetTrackInfo(std::string track_type) = 0; virtual bool SetTrackSelection(int32_t track_id, std::string track_type) = 0; virtual bool Suspend() = 0; - virtual bool Restore(const CreateMessage *restore_message, - int64_t resume_time) = 0; + // Restore player and return new player ID (may be same or different) + virtual int64_t Restore(const CreateMessage *restore_message, + int64_t resume_time) = 0; virtual bool SetDisplayRotate(int64_t rotation) = 0; protected: @@ -96,6 +97,9 @@ class VideoPlayer { void SendError(const std::string &error_code, const std::string &error_message); + // Reset event dispatch state for restored player + void ResetEventDispatchState(); + int64_t player_id_; // Store player ID for FFI event callback std::mutex queue_mutex_; std::unique_ptr ecore_wl2_window_proxy_ = nullptr; diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 5d9f552bb..7cc06d6c1 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -413,9 +413,10 @@ const char* ffi_get_duration(int64_t player_id) { } auto duration_pair = player->GetDuration(); - std::string duration_json = - "{\"start\":" + std::to_string(duration_pair.first) + - ",\"end\":" + std::to_string(duration_pair.second) + "}"; + std::string duration_json = "{\"playerId\":" + std::to_string(player_id) + + ",\"durationRange\":[" + + std::to_string(duration_pair.first) + "," + + std::to_string(duration_pair.second) + "]}"; return strdup(duration_json.c_str()); } @@ -524,8 +525,8 @@ int ffi_suspend(int64_t player_id) { return player->Suspend() ? 0 : -1; } -int ffi_restore(int64_t player_id, const char* create_message_json, - int64_t resume_time) { +int64_t ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time) { auto player = GetPlayer(player_id); if (!player) { return -1; @@ -536,7 +537,17 @@ int ffi_restore(int64_t player_id, const char* create_message_json, msg = ParseCreateMessage(std::string(create_message_json)); } - return player->Restore(&msg, resume_time) ? 0 : -1; + // Restore returns the new player ID (may be same or different) + int64_t new_player_id = player->Restore(&msg, resume_time); + + // Update g_players map if player ID changed + if (new_player_id > 0 && new_player_id != player_id) { + std::unique_lock lock(g_players_mutex); + g_players.erase(player_id); + g_players[new_player_id] = player; + } + + return new_player_id; } int ffi_set_activate(int64_t player_id) { From 619dc62d6e650f8bcf0edca1f1be6f5d2fa45127 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Tue, 28 Jul 2026 18:26:56 +0800 Subject: [PATCH 12/18] code format --- packages/video_player_videohole/lib/video_player.dart | 2 +- packages/video_player_videohole/tizen/src/media_player.cc | 5 ----- 2 files changed, 1 insertion(+), 6 deletions(-) diff --git a/packages/video_player_videohole/lib/video_player.dart b/packages/video_player_videohole/lib/video_player.dart index 54a0a93ae..e1c68616b 100644 --- a/packages/video_player_videohole/lib/video_player.dart +++ b/packages/video_player_videohole/lib/video_player.dart @@ -548,7 +548,7 @@ class VideoPlayerController extends ValueNotifier { _eventSubscription = _videoPlayerPlatform .videoEventsFor(_playerId) - .listen(_eventListener!, onError: _errorListener); + .listen(_eventListener, onError: _errorListener); return initializingCompleter.future; } diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 975c47712..60ac7b20e 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -882,11 +882,6 @@ bool MediaPlayer::SetDisplayRotate(int64_t rotation) { } void MediaPlayer::OnRestoreCompleted() { - LOG_INFO( - "[MediaPlayer] OnRestoreCompleted called. pre_state_=%d, " - "pre_playing_time_=%llu", - pre_state_, pre_playing_time_); - if (pre_playing_time_ <= 0 || !SeekTo(pre_playing_time_, [this]() { if (pre_state_ == PLAYER_STATE_PLAYING) { LOG_INFO("[MediaPlayer] Restoring to PLAYING state after seek."); From 45eafa537951604e87fc2f320c6429cc97dbd818 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 29 Jul 2026 18:01:44 +0800 Subject: [PATCH 13/18] Complete the registration and destruction of playerEventPort, and restore the return type of restore. --- .../lib/src/ffi_messages.g.dart | 78 +++++++- .../lib/src/video_player_tizen.dart | 42 ++-- .../lib/video_player.dart | 29 +-- .../lib/video_player_platform_interface.dart | 10 +- .../tizen/src/ffi_messages.h | 13 +- .../tizen/src/media_player.cc | 187 ++++++++++++------ .../tizen/src/media_player.h | 11 +- .../tizen/src/video_player.cc | 139 ++++++++++--- .../tizen/src/video_player.h | 28 +-- .../tizen/src/video_player_tizen_plugin.cc | 63 ++++-- 10 files changed, 438 insertions(+), 162 deletions(-) diff --git a/packages/video_player_videohole/lib/src/ffi_messages.g.dart b/packages/video_player_videohole/lib/src/ffi_messages.g.dart index 55a5e1240..8afa29ab8 100644 --- a/packages/video_player_videohole/lib/src/ffi_messages.g.dart +++ b/packages/video_player_videohole/lib/src/ffi_messages.g.dart @@ -185,13 +185,31 @@ typedef _FFISetDeactivateDart = int Function(int); typedef _FFISetMixWithOthersNative = ffi.Int32 Function(ffi.Bool); typedef _FFISetMixWithOthersDart = int Function(bool); +// Check if video is live stream - returns 1 if live, 0 if VOD +typedef _FFIIsLiveNative = ffi.Int32 Function(ffi.Int64); +typedef _FFIIsLiveDart = int Function(int); + typedef _FFISuspendNative = ffi.Int32 Function(ffi.Int64); typedef _FFISuspendDart = int Function(int); -typedef _FFIRestoreNative = ffi.Int64 Function( +// P0-3 fix: restore returns int (0 on success, -1 on failure) +// Player ID remains unchanged after restore +typedef _FFIRestoreNative = ffi.Int32 Function( ffi.Int64, ffi.Pointer, ffi.Int64); typedef _FFIRestoreDart = int Function(int, ffi.Pointer, int); +// P0-1 fix: FFI string memory management +typedef _FFIFreeStringNative = ffi.Void Function(ffi.Pointer); +typedef _FFIFreeStringDart = void Function(ffi.Pointer); + +// P0-2 fix: Per-player event port registration +typedef _FFIRegisterPlayerEventPortNative = ffi.Void Function( + ffi.Int64, ffi.Int64); +typedef _FFIRegisterPlayerEventPortDart = void Function(int, int); + +typedef _FFIUnregisterPlayerEventPortNative = ffi.Void Function(ffi.Int64); +typedef _FFIUnregisterPlayerEventPortDart = void Function(int); + // ===== Helper Functions ===== ffi.Pointer _toPointer(String? str) { @@ -234,10 +252,17 @@ class VideoPlayerFFIBindings { late int Function(int, int, int, int, int) _ffiSetDisplayGeometry; late int Function(int, int) _ffiSetDisplayRotate; late int Function(int) _ffiSuspend; + // P0-3 fix: restore returns int (0 on success, -1 on failure) late int Function(int, ffi.Pointer, int) _ffiRestore; late int Function(int) _ffiSetActivate; late int Function(int) _ffiSetDeactivate; late int Function(bool) _ffiSetMixWithOthers; + late int Function(int) _ffiIsLive; + // P0-1 fix: FFI string memory management + late void Function(ffi.Pointer) _ffiFreeString; + // P0-2 fix: Per-player event port registration + late void Function(int, int) _ffiRegisterPlayerEventPort; + late void Function(int) _ffiUnregisterPlayerEventPort; static VideoPlayerFFIBindings get instance { _instance ??= VideoPlayerFFIBindings._(); @@ -342,6 +367,25 @@ class VideoPlayerFFIBindings { 'ffi_set_mix_with_others') .asFunction<_FFISetMixWithOthersDart>(); + // P0-1 fix: FFI string memory management + _ffiFreeString = _lib! + .lookup>('ffi_free_string') + .asFunction<_FFIFreeStringDart>(); + + // P0-2 fix: Per-player event port registration + _ffiRegisterPlayerEventPort = _lib! + .lookup>( + 'ffi_register_player_event_port') + .asFunction<_FFIRegisterPlayerEventPortDart>(); + _ffiUnregisterPlayerEventPort = _lib! + .lookup>( + 'ffi_unregister_player_event_port') + .asFunction<_FFIUnregisterPlayerEventPortDart>(); + + _ffiIsLive = _lib! + .lookup>('ffi_is_live') + .asFunction<_FFIIsLiveDart>(); + debugPrint('FFI bindings loaded successfully'); } catch (e) { debugPrint('Failed to load FFI bindings: $e'); @@ -455,7 +499,7 @@ class VideoPlayerVideoholeFFIApi { } return DurationMessage.fromJson(jsonString); } finally { - calloc.free(ptr); + bindings._ffiFreeString(ptr); } } @@ -547,7 +591,7 @@ class VideoPlayerVideoholeFFIApi { return TrackMessage.fromJson(jsonString); } finally { if (ptr != null) { - calloc.free(ptr.cast()); + bindings._ffiFreeString(ptr); } _freePointer(trackTypePtr); } @@ -573,6 +617,34 @@ class VideoPlayerVideoholeFFIApi { } return bindings._ffiSetMixWithOthers(mixWithOthers); } + + // P0-2 fix: Per-player event port registration + void registerPlayerEventPort(int playerId, int port) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + bindings._ffiRegisterPlayerEventPort(playerId, port); + } + + void unregisterPlayerEventPort(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + bindings._ffiUnregisterPlayerEventPort(playerId); + } + + /// Check if video is live stream + /// Returns true if live, false if VOD + bool isLive(int playerId) { + final bindings = VideoPlayerFFIBindings.instance; + if (!bindings.isLoaded) { + bindings.load(); + } + final int result = bindings._ffiIsLive(playerId); + return result != 0; + } } // ===== FFI Event Port Section - Using Dart_PostCObject_DL ===== diff --git a/packages/video_player_videohole/lib/src/video_player_tizen.dart b/packages/video_player_videohole/lib/src/video_player_tizen.dart index b027c410a..2daafce36 100644 --- a/packages/video_player_videohole/lib/src/video_player_tizen.dart +++ b/packages/video_player_videohole/lib/src/video_player_tizen.dart @@ -31,6 +31,9 @@ class VideoPlayerTizen extends VideoPlayerPlatform { @override Future dispose(int playerId) async { + // P0-2 fix: Unregister per-player event port before disposing + _ffiApi.unregisterPlayerEventPort(playerId); + // Close the StreamController for this player final StreamController? controller = _eventControllers.remove(playerId); @@ -76,6 +79,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { if (playerId < 0) { throw Exception('FFI create failed with code: $playerId'); } + + // P0-2 fix: Register per-player event port after successful creation + _ffiApi.registerPlayerEventPort(playerId, _eventPort!.nativePort); + debugPrint( + 'Registered player $playerId with port ${_eventPort!.nativePort}'); + return playerId; } @@ -400,7 +409,7 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } @override - Future restore( + Future restore( int playerId, { DataSource? dataSource, int resumeTime = -1, @@ -427,26 +436,13 @@ class VideoPlayerTizen extends VideoPlayerPlatform { } } - // Restore returns the new player ID (may be same or different) - final int newPlayerId = _ffiApi.restore(playerId, message, resumeTime); - - // If player ID changed, update the StreamController - if (newPlayerId != playerId && newPlayerId > 0) { - // Close old StreamController - final StreamController? oldController = - _eventControllers.remove(playerId); - if (oldController != null && !oldController.isClosed) { - await oldController.close(); - } - - // Create new StreamController for the new player ID - _eventControllers.putIfAbsent( - newPlayerId, - () => StreamController.broadcast(), - ); + // P0-3 fix: restore returns void, player ID remains unchanged + // FFI restore returns 0 on success, -1 on failure + final int result = _ffiApi.restore(playerId, message, resumeTime); + if (result != 0) { + throw Exception('FFI restore failed with code: $result'); } - - return newPlayerId; + // Player ID remains unchanged, no StreamController update needed } @override @@ -459,6 +455,12 @@ class VideoPlayerTizen extends VideoPlayerPlatform { return true; } + @override + Future isLive(int playerId) async { + // Use FFI for isLive (synchronous call) + return _ffiApi.isLive(playerId); + } + static const Map _videoFormatStringMap = { VideoFormat.ss: 'ss', diff --git a/packages/video_player_videohole/lib/video_player.dart b/packages/video_player_videohole/lib/video_player.dart index e1c68616b..9c0fd0418 100644 --- a/packages/video_player_videohole/lib/video_player.dart +++ b/packages/video_player_videohole/lib/video_player.dart @@ -908,6 +908,7 @@ class VideoPlayerController extends ValueNotifier { } /// Restores the player state when the application is resumed. + /// Player ID remains unchanged after restore. Future _restore() async { if (_isDisposedOrNotInitialized) { return; @@ -917,23 +918,13 @@ class VideoPlayerController extends ValueNotifier { (_onRestoreDataSource != null) ? _onRestoreDataSource!() : null; final int resumeTime = (_onRestoreTime != null) ? _onRestoreTime!() : -1; - // Restore returns the new player ID (may be same or different) - final int newPlayerId = await _videoPlayerPlatform.restore( + // P0-3 fix: restore returns void, player ID remains unchanged + await _videoPlayerPlatform.restore( _playerId, dataSource: dataSource, resumeTime: resumeTime, ); - - // Update playerId if it changed during restore - if (newPlayerId != _playerId && newPlayerId > 0) { - _playerId = newPlayerId; - - // Re-subscribe to event stream with the new player ID - await _eventSubscription?.cancel(); - _eventSubscription = _videoPlayerPlatform - .videoEventsFor(_playerId) - .listen(_eventListener, onError: _errorListener); - } + // Player ID remains unchanged, no need to update event subscription } /// Set the rotate angle of display @@ -944,6 +935,18 @@ class VideoPlayerController extends ValueNotifier { return _videoPlayerPlatform.setDisplayRotate(_playerId, rotation); } + + /// Check if the video is a live stream. + /// Returns true if live, false if VOD. + /// + /// This method should be called after the video is initialized. + /// The result is cached in native side to avoid repeated API calls. + Future isLive() async { + if (_isDisposedOrNotInitialized) { + return false; + } + return _videoPlayerPlatform.isLive(_playerId); + } } class _VideoAppLifeCycleObserver extends Object with WidgetsBindingObserver { diff --git a/packages/video_player_videohole/lib/video_player_platform_interface.dart b/packages/video_player_videohole/lib/video_player_platform_interface.dart index f80932843..12b6575b8 100644 --- a/packages/video_player_videohole/lib/video_player_platform_interface.dart +++ b/packages/video_player_videohole/lib/video_player_platform_interface.dart @@ -159,8 +159,8 @@ abstract class VideoPlayerPlatform extends PlatformInterface { } /// Restores the player state when the application is resumed. - /// Returns the new player ID (may be same or different from the original). - Future restore( + /// Player ID remains unchanged after restore. + Future restore( int playerId, { DataSource? dataSource, int resumeTime = -1, @@ -172,6 +172,12 @@ abstract class VideoPlayerPlatform extends PlatformInterface { Future setDisplayRotate(int playerId, DisplayRotation rotation) { throw UnimplementedError('setDisplayRotate() has not been implemented.'); } + + /// Check if the video is a live stream. + /// Returns true if live, false if VOD. + Future isLive(int playerId) { + throw UnimplementedError('isLive() has not been implemented.'); + } } /// Description of the data source used to create an instance of diff --git a/packages/video_player_videohole/tizen/src/ffi_messages.h b/packages/video_player_videohole/tizen/src/ffi_messages.h index 4caf3d136..3d79cf504 100644 --- a/packages/video_player_videohole/tizen/src/ffi_messages.h +++ b/packages/video_player_videohole/tizen/src/ffi_messages.h @@ -41,8 +41,10 @@ int ffi_set_display_geometry(int64_t player_id, int32_t x, int32_t y, int32_t width, int32_t height); int ffi_set_display_rotate(int64_t player_id, int32_t rotation); int ffi_suspend(int64_t player_id); -int64_t ffi_restore(int64_t player_id, const char* create_message_json, - int64_t resume_time); +// P0-3 fix: restore returns int (0 on success, -1 on failure) +// Player ID remains unchanged after restore +int ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time); int ffi_set_activate(int64_t player_id); int ffi_set_deactivate(int64_t player_id); int ffi_set_mix_with_others(bool mix_with_others); @@ -52,6 +54,13 @@ int ffi_initialize_api_dl(void* data); void ffi_register_event_port(int64_t port); void ffi_unregister_event_port(); +// P0-1 fix: FFI string memory management +void ffi_free_string(char* ptr); + +// P0-2 fix: Per-player event port registration +void ffi_register_player_event_port(int64_t player_id, int64_t port); +void ffi_unregister_player_event_port(int64_t player_id); + #ifdef __cplusplus } // extern "C" diff --git a/packages/video_player_videohole/tizen/src/media_player.cc b/packages/video_player_videohole/tizen/src/media_player.cc index 60ac7b20e..4cfbe637b 100644 --- a/packages/video_player_videohole/tizen/src/media_player.cc +++ b/packages/video_player_videohole/tizen/src/media_player.cc @@ -71,15 +71,26 @@ MediaPlayer::~MediaPlayer() { static int64_t player_id_counter = 1; int64_t MediaPlayer::Create(const std::string &uri, - const CreateMessage &create_message) { - LOG_INFO("[MediaPlayer] uri: %s.", uri.c_str()); + const CreateMessage &create_message, + bool reuse_existing_id) { + LOG_INFO("[MediaPlayer] Create: uri=%s, reuse_existing_id=%d", uri.c_str(), + reuse_existing_id ? 1 : 0); if (uri.empty()) { LOG_ERROR("[MediaPlayer] The uri must not be empty."); return -1; } - player_id_ = player_id_counter++; + // Only allocate new ID if not reusing or if this is the first creation + if (!reuse_existing_id || player_id_ <= 0) { + player_id_ = player_id_counter++; + LOG_INFO("[MediaPlayer] Allocated new player_id=%lld", + static_cast(player_id_)); + } else { + LOG_INFO("[MediaPlayer] Reusing existing player_id=%lld", + static_cast(player_id_)); + } + url_ = uri; create_message_ = create_message; @@ -190,8 +201,30 @@ int64_t MediaPlayer::Create(const std::string &uri, } void MediaPlayer::Dispose() { - LOG_INFO("[MediaPlayer] Disposing."); - // EventChannel has been removed, no cleanup needed + if (!player_) { + return; + } + + // Unset all callbacks BEFORE stopping/destroying player + // This prevents callbacks from firing during disposal + player_unset_buffering_cb(player_); + player_unset_completed_cb(player_); + player_unset_interrupted_cb(player_); + player_unset_error_cb(player_); + player_unset_subtitle_updated_cb(player_); + + // Stop and destroy player + player_stop(player_); + player_unprepare(player_); + player_destroy(player_); + player_ = nullptr; + + // Release DRM + if (drm_manager_) { + drm_manager_->StopDrmSession(); + drm_manager_->ReleaseDrmSession(); + drm_manager_.reset(); + } } void MediaPlayer::SetDisplayRoi(int32_t x, int32_t y, int32_t width, @@ -225,6 +258,7 @@ bool MediaPlayer::Play() { LOG_INFO("[MediaPlayer] Player already playing."); return false; } + ret = player_start(player_); if (ret != PLAYER_ERROR_NONE) { LOG_ERROR("[MediaPlayer] player_start failed: %s.", get_error_message(ret)); @@ -328,18 +362,18 @@ int64_t MediaPlayer::GetPosition() { } std::pair MediaPlayer::GetDuration() { - if (IsLive()) { - return GetLiveDuration(); - } else { - int duration = 0; - int ret = player_get_duration(player_, &duration); - if (ret != PLAYER_ERROR_NONE) { - LOG_ERROR("[MediaPlayer] player_get_duration failed: %s.", - get_error_message(ret)); - } - LOG_INFO("[MediaPlayer] Video duration: %d.", duration); - return std::make_pair(0, duration); + // if (IsLive()) { + // return GetLiveDuration(); + // } else { + int duration = 0; + int ret = player_get_duration(player_, &duration); + if (ret != PLAYER_ERROR_NONE) { + LOG_ERROR("[MediaPlayer] player_get_duration failed: %s.", + get_error_message(ret)); } + LOG_INFO("[MediaPlayer] Video duration: %d.", duration); + return std::make_pair(0, duration); + //} } void MediaPlayer::GetVideoSize(int32_t *width, int32_t *height) { @@ -734,15 +768,15 @@ bool MediaPlayer::Suspend() { "[MediaPlayer] Saved current player state: %d, playing time: %llu ms", pre_state_, pre_playing_time_); - if (IsLive()) { - pre_playing_time_ = 0; - if (!StopAndDestroy()) { - LOG_ERROR("[MediaPlayer] Player is live, StopAndDestroy fail."); - return false; - } - LOG_INFO("[MediaPlayer] Player is live: close done successfully."); - return true; - } + // if (IsLive()) { + // pre_playing_time_ = 0; + // if (!StopAndDestroy()) { + // LOG_ERROR("[MediaPlayer] Player is live, StopAndDestroy fail."); + // return false; + // } + // LOG_INFO("[MediaPlayer] Player is live: close done successfully."); + // return true; + // } res = device_proxy_->device_power_get_state(); if (res == POWER_STATE_STANDBY) { @@ -780,20 +814,17 @@ bool MediaPlayer::Suspend() { return true; } -int64_t MediaPlayer::Restore(const CreateMessage *restore_message, - int64_t resume_time) { - LOG_INFO("[MediaPlayer] Restore is called."); +bool MediaPlayer::Restore(const CreateMessage *restore_message, + int64_t resume_time) { + LOG_INFO("[MediaPlayer] Restore is called for player_id=%lld", + static_cast(player_id_)); player_state_e player_state = PLAYER_STATE_NONE; - if (player_) { - int ret = player_get_state(player_, &player_state); - if (ret != PLAYER_ERROR_NONE || (player_state != PLAYER_STATE_PAUSED && - player_state != PLAYER_STATE_PLAYING)) { - LOG_ERROR( - "[MediaPlayer] Player get state failed or in invalid state[%d].", - player_state); - return -1; - } + int ret = player_get_state(player_, &player_state); + if (ret != PLAYER_ERROR_NONE) { + LOG_ERROR("[MediaPlayer] Player get state failed: %s", + get_error_message(ret)); + return false; } if (restore_message->uri()) { @@ -809,35 +840,39 @@ int64_t MediaPlayer::Restore(const CreateMessage *restore_message, switch (player_state) { case PLAYER_STATE_NONE: + case PLAYER_STATE_IDLE: return RestorePlayer(restore_message, resume_time); - break; + + case PLAYER_STATE_READY: + return RestorePlayer(restore_message, resume_time); + case PLAYER_STATE_PAUSED: if (pre_state_ == PLAYER_STATE_PLAYING) { return RestorePlayer(restore_message, resume_time); } break; + case PLAYER_STATE_PLAYING: - // might be the case that widget has called - // restore more than once, just ignore. + // Already playing, nothing to do break; + default: - LOG_ERROR( - "[MediaPlayer] Restore: unhandled state=%d, calling RestorePlayer.", - player_state); + LOG_ERROR("[MediaPlayer] Restore: unhandled state=%d", + static_cast(player_state)); return RestorePlayer(restore_message, resume_time); } - // Return current player ID when no restore is needed - return player_id_; + + return true; } -int64_t MediaPlayer::RestorePlayer(const CreateMessage *restore_message, - int64_t resume_time) { +bool MediaPlayer::RestorePlayer(const CreateMessage *restore_message, + int64_t resume_time) { LOG_INFO("[MediaPlayer] RestorePlayer is called."); - // 先清理旧的 player,避免状态冲突导致卡死 + // Clean up old player first to avoid state conflicts if (player_ && !StopAndDestroy()) { LOG_ERROR("[MediaPlayer] RestorePlayer: StopAndDestroy failed."); - return -1; + return false; } LOG_INFO("[MediaPlayer] RestorePlayer: old player cleaned up."); @@ -858,15 +893,16 @@ int64_t MediaPlayer::RestorePlayer(const CreateMessage *restore_message, if (resume_time >= 0) pre_playing_time_ = static_cast(resume_time); is_restored_ = true; - int64_t new_player_id = Create(url_, create_message_); - if (new_player_id < 0) { + + // Reuse current player_id_ by passing reuse_existing_id = true + int64_t result = Create(url_, create_message_, true); + if (result < 0) { LOG_ERROR("[MediaPlayer] Fail to create player."); is_restored_ = false; - return -1; + return false; } - // Return the new player ID - return new_player_id; + return true; } bool MediaPlayer::SetDisplayRotate(int64_t rotation) { @@ -899,14 +935,14 @@ void MediaPlayer::OnPrepared(void *user_data) { MediaPlayer *self = static_cast(user_data); - // Reset event dispatch state for restored player BEFORE sending any events - // This ensures event_dispatch_state_->player points to the correct instance + // Reset event dispatch state for restored player if (self->is_restored_) { self->ResetEventDispatchState(); LOG_INFO("[MediaPlayer] Event dispatch state reset for restored player."); self->OnRestoreCompleted(); } + // Call SendInitialized() - it uses GetInitialDuration() which is safe if (!self->is_initialized_) { self->SendInitialized(); } @@ -916,6 +952,11 @@ void MediaPlayer::OnBuffering(int percent, void *user_data) { LOG_INFO("[MediaPlayer] Buffering percent: %d.", percent); MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + return; + } + if (percent == 100) { self->SendBufferingEnd(); self->is_buffering_ = false; @@ -931,6 +972,13 @@ void MediaPlayer::OnSeekCompleted(void *user_data) { LOG_INFO("[MediaPlayer] Seek completed."); MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + LOG_DEBUG( + "[MediaPlayer] OnSeekCompleted: player disposed, dropping callback"); + return; + } + if (self->on_seek_completed_) { self->on_seek_completed_(); self->on_seek_completed_ = nullptr; @@ -941,6 +989,13 @@ void MediaPlayer::OnPlayCompleted(void *user_data) { LOG_INFO("[MediaPlayer] Play completed."); MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + LOG_DEBUG( + "[MediaPlayer] OnPlayCompleted: player disposed, dropping callback"); + return; + } + self->SendPlayCompleted(); self->Pause(); } @@ -948,6 +1003,13 @@ void MediaPlayer::OnPlayCompleted(void *user_data) { void MediaPlayer::OnInterrupted(player_interrupted_code_e code, void *user_data) { MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + LOG_DEBUG( + "[MediaPlayer] OnInterrupted: player disposed, dropping callback"); + return; + } + self->SendIsPlayingState(false); LOG_ERROR("[MediaPlayer] Interrupt code: %d.", code); } @@ -957,6 +1019,12 @@ void MediaPlayer::OnError(int error_code, void *user_data) { get_error_message(error_code)); MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + LOG_DEBUG("[MediaPlayer] OnError: player disposed, dropping callback"); + return; + } + self->SendError("Media Player error", get_error_message(error_code)); } @@ -966,6 +1034,13 @@ void MediaPlayer::OnSubtitleUpdated(unsigned long duration, char *text, text); MediaPlayer *self = static_cast(user_data); + + if (self->IsDisposed()) { + LOG_DEBUG( + "[MediaPlayer] OnSubtitleUpdated: player disposed, dropping callback"); + return; + } + self->SendSubtitleUpdate(duration, std::string(text)); } diff --git a/packages/video_player_videohole/tizen/src/media_player.h b/packages/video_player_videohole/tizen/src/media_player.h index 1c0cf8cdf..18e218063 100644 --- a/packages/video_player_videohole/tizen/src/media_player.h +++ b/packages/video_player_videohole/tizen/src/media_player.h @@ -24,8 +24,8 @@ class MediaPlayer : public VideoPlayer { FlutterDesktopViewRef flutter_view); ~MediaPlayer(); - int64_t Create(const std::string &uri, - const CreateMessage &create_message) override; + int64_t Create(const std::string &uri, const CreateMessage &create_message, + bool reuse_existing_id = false) override; void Dispose() override; void SetDisplayRoi(int32_t x, int32_t y, int32_t width, @@ -43,8 +43,8 @@ class MediaPlayer : public VideoPlayer { flutter::EncodableList GetTrackInfo(std::string track_type) override; bool SetTrackSelection(int32_t track_id, std::string track_type) override; bool Suspend() override; - int64_t Restore(const CreateMessage *restore_message, - int64_t resume_time) override; + bool Restore(const CreateMessage *restore_message, + int64_t resume_time) override; bool SetDisplayRotate(int64_t rotation) override; private: @@ -54,8 +54,7 @@ class MediaPlayer : public VideoPlayer { bool SetDrm(const std::string &uri, int drm_type, const std::string &license_server_url); bool StopAndDestroy(); - int64_t RestorePlayer(const CreateMessage *restore_message, - int64_t resume_time); + bool RestorePlayer(const CreateMessage *restore_message, int64_t resume_time); void OnRestoreCompleted(); static void OnPrepared(void *user_data); diff --git a/packages/video_player_videohole/tizen/src/video_player.cc b/packages/video_player_videohole/tizen/src/video_player.cc index 9322ad5ac..f2ff63942 100644 --- a/packages/video_player_videohole/tizen/src/video_player.cc +++ b/packages/video_player_videohole/tizen/src/video_player.cc @@ -15,40 +15,79 @@ namespace video_player_videohole_tizen { static int64_t player_index = 1; -// Static FFI event callback - shared across all VideoPlayer instances -static DartPortEventCallback g_ffi_event_callback = nullptr; -static std::mutex g_ffi_callback_mutex; - -// Dart Port for FFI event notifications using Dart_PostCObject_DL -// Defined here (extern declared in video_player.h) -int64_t g_dart_port = -1; -std::mutex g_dart_port_mutex; - -void RegisterDartPort(int64_t port) { - std::lock_guard lock(g_dart_port_mutex); - g_dart_port = port; +// P0-2 fix: Per-player event port registration +// Each player has its own Dart port for event notifications +static std::map g_player_dart_ports; +static std::mutex g_player_ports_mutex; + +// P0-2 fix: Register Dart port for a specific player +void RegisterPlayerEventPort(int64_t player_id, int64_t dart_port) { + std::lock_guard lock(g_player_ports_mutex); + g_player_dart_ports[player_id] = dart_port; + LOG_INFO("[VideoPlayer] Registered port %lld for player %lld", + static_cast(dart_port), static_cast(player_id)); } -int64_t GetDartPort() { - std::lock_guard lock(g_dart_port_mutex); - return g_dart_port; +// P0-2 fix: Unregister Dart port for a specific player +void UnregisterPlayerEventPort(int64_t player_id) { + std::lock_guard lock(g_player_ports_mutex); + auto it = g_player_dart_ports.find(player_id); + if (it != g_player_dart_ports.end()) { + g_player_dart_ports.erase(it); + LOG_INFO("[VideoPlayer] Unregistered port for player %lld", + static_cast(player_id)); + } } +// P0-2 fix: Post event to Dart using per-player port void PostEventToDart(int64_t player_id, const std::string& event_json) { - std::lock_guard lock(g_dart_port_mutex); - if (g_dart_port < 0) { - LOG_INFO("[VideoPlayer] Dart port not registered yet."); + std::lock_guard lock(g_player_ports_mutex); + auto it = g_player_dart_ports.find(player_id); + if (it == g_player_dart_ports.end()) { + LOG_DEBUG("[VideoPlayer] Port not registered for player %lld, dropping event", + static_cast(player_id)); return; } - + + int64_t port = it->second; + + // TEMP_DEBUG: Add detailed logging for crash investigation + std::string event_type = "unknown"; + if (event_json.find("\"initialized\"") != std::string::npos) { + event_type = "initialized"; + } else if (event_json.find("\"bufferingStart\"") != std::string::npos) { + event_type = "bufferingStart"; + } else if (event_json.find("\"bufferingUpdate\"") != std::string::npos) { + event_type = "bufferingUpdate"; + } else if (event_json.find("\"bufferingEnd\"") != std::string::npos) { + event_type = "bufferingEnd"; + } else if (event_json.find("\"completed\"") != std::string::npos) { + event_type = "completed"; + } else if (event_json.find("\"subtitleUpdate\"") != std::string::npos) { + event_type = "subtitleUpdate"; + } else if (event_json.find("\"error\"") != std::string::npos) { + event_type = "error"; + } + + // LOG_INFO("[FFI_DEBUG] Pre-PostEvent: player_id=%lld, port=%lld, event_type=%s, json_len=%zu", + // static_cast(player_id), + // static_cast(port), + // event_type.c_str(), + // event_json.length()); + + // Log first 200 chars of JSON for debugging (truncated to avoid log spam) + std::string json_preview = event_json.length() > 200 ? event_json.substr(0, 200) + "..." : event_json; + //LOG_INFO("[FFI_DEBUG] JSON preview: %s", json_preview.c_str()); + // Message format: [player_id, event_json] - // This matches what Dart side expects Dart_CObject player_id_obj; player_id_obj.type = Dart_CObject_kInt64; player_id_obj.value.as_int64 = player_id; // Dart_PostCObject_DL takes ownership of the string on success char* json_copy = strdup(event_json.c_str()); + //LOG_INFO("[FFI_DEBUG] strdup completed, json_copy=%p", json_copy); + Dart_CObject event_json_obj; event_json_obj.type = Dart_CObject_kString; event_json_obj.value.as_string = json_copy; @@ -64,23 +103,26 @@ void PostEventToDart(int64_t player_id, const std::string& event_json) { message.value.as_array.length = 2; message.value.as_array.values = array_elements; - bool result = Dart_PostCObject_DL(g_dart_port, &message); + //LOG_INFO("[FFI_DEBUG] Calling Dart_PostCObject_DL..."); + bool result = Dart_PostCObject_DL(port, &message); + //LOG_INFO("[FFI_DEBUG] Dart_PostCObject_DL returned: %d", result ? 1 : 0); if (!result) { - LOG_ERROR("[VideoPlayer] Failed to post event to Dart. Freeing json_copy."); + LOG_ERROR("[VideoPlayer] Failed to post event to Dart for player %lld. Freeing json_copy.", + static_cast(player_id)); free(json_copy); } // On success, Dart takes ownership of json_copy } +// Legacy FFI event callback functions removed - use per-player port registration instead void VideoPlayer::RegisterFFIEventCallback(DartPortEventCallback callback) { - std::lock_guard lock(g_ffi_callback_mutex); - g_ffi_event_callback = std::move(callback); + // Deprecated: use RegisterPlayerEventPort instead } DartPortEventCallback VideoPlayer::GetFFIEventCallback() { - std::lock_guard lock(g_ffi_callback_mutex); - return g_ffi_event_callback; + // Deprecated: use RegisterPlayerEventPort instead + return nullptr; } // Helper function to convert EncodableValue to JSON string @@ -221,17 +263,59 @@ void VideoPlayer::ResetEventDispatchState() { } } +bool VideoPlayer::IsDisposed() const { + if (event_dispatch_state_) { + std::lock_guard lock(event_dispatch_state_->mutex); + return event_dispatch_state_->disposed; + } + return true; // If no event_dispatch_state_, consider as disposed +} + void VideoPlayer::ExecuteSinkEvents() { + // Double-check: make sure we're not disposed + if (event_dispatch_state_) { + std::lock_guard state_lock(event_dispatch_state_->mutex); + if (event_dispatch_state_->disposed) { + LOG_ERROR("[VideoPlayer] ExecuteSinkEvents: disposed, dropping events"); + return; + } + } + + // LOG_INFO("[VideoPlayer] ExecuteSinkEvents: player_id=%lld, queue_size=%zu", + // static_cast(player_id_), encodable_event_queue_.size()); + std::lock_guard lock(queue_mutex_); + int event_count = 0; while (!encodable_event_queue_.empty()) { const flutter::EncodableValue& event = encodable_event_queue_.front(); // Send to FFI using Dart_PostCObject_DL std::string event_json = EncodableValueToJson(event); + + // Extract event type for logging + std::string event_type = "unknown"; + if (event_json.find("\"event\":\"initialized\"") != std::string::npos) { + event_type = "initialized"; + } else if (event_json.find("\"event\":\"bufferingStart\"") != std::string::npos) { + event_type = "bufferingStart"; + } else if (event_json.find("\"event\":\"bufferingUpdate\"") != std::string::npos) { + event_type = "bufferingUpdate"; + } else if (event_json.find("\"event\":\"bufferingEnd\"") != std::string::npos) { + event_type = "bufferingEnd"; + } else if (event_json.find("\"event\":\"completed\"") != std::string::npos) { + event_type = "completed"; + } + + LOG_INFO("[VideoPlayer] Sending event #%d: type=%s, player_id=%lld, json_len=%zu", + event_count, event_type.c_str(), static_cast(player_id_), event_json.length()); + PostEventToDart(player_id_, event_json); + event_count++; encodable_event_queue_.pop(); } + + LOG_INFO("[VideoPlayer] ExecuteSinkEvents: sent %d events", event_count); while (!error_event_queue_.empty()) { const auto& error = error_event_queue_.front(); @@ -297,11 +381,12 @@ void VideoPlayer::PushEvent(flutter::EncodableValue encodable_value) { ScheduleSendPendingEvents(); } -void VideoPlayer::SendInitialized() { + void VideoPlayer::SendInitialized() { if (!is_initialized_) { int32_t width = 0, height = 0; GetVideoSize(&width, &height); is_initialized_ = true; + // Use GetDuration() to get the duration auto duration = GetDuration(); flutter::EncodableList duration_range{ flutter::EncodableValue(duration.first), diff --git a/packages/video_player_videohole/tizen/src/video_player.h b/packages/video_player_videohole/tizen/src/video_player.h index 470574de2..ea5c6ba2e 100644 --- a/packages/video_player_videohole/tizen/src/video_player.h +++ b/packages/video_player_videohole/tizen/src/video_player.h @@ -29,16 +29,12 @@ namespace video_player_videohole_tizen { using DartPortEventCallback = std::function; -// Static FFI event callback - shared across all VideoPlayer instances. -extern DartPortEventCallback g_dart_port_callback; -extern int64_t g_dart_port; -extern std::mutex g_dart_port_mutex; +// P0-2 fix: Per-player event port registration. +// Register Dart port for a specific player. +void RegisterPlayerEventPort(int64_t player_id, int64_t dart_port); +void UnregisterPlayerEventPort(int64_t player_id); -// Register Dart port for FFI event notifications. -void RegisterDartPort(int64_t port); -int64_t GetDartPort(); - -// Post event to Dart using Dart_PostCObject_DL. +// Post event to Dart using per-player port. void PostEventToDart(int64_t player_id, const std::string &event_json); class VideoPlayer { @@ -59,7 +55,8 @@ class VideoPlayer { virtual ~VideoPlayer(); virtual int64_t Create(const std::string &uri, - const CreateMessage &create_message) = 0; + const CreateMessage &create_message, + bool reuse_existing_id = false) = 0; virtual void Dispose() = 0; virtual void SetDisplayRoi(int32_t x, int32_t y, int32_t width, @@ -74,13 +71,15 @@ class VideoPlayer { virtual bool SeekTo(int64_t position, SeekCompletedCallback callback) = 0; virtual int64_t GetPosition() = 0; virtual std::pair GetDuration() = 0; + virtual bool IsLive() = 0; virtual bool IsReady() = 0; virtual flutter::EncodableList GetTrackInfo(std::string track_type) = 0; virtual bool SetTrackSelection(int32_t track_id, std::string track_type) = 0; virtual bool Suspend() = 0; - // Restore player and return new player ID (may be same or different) - virtual int64_t Restore(const CreateMessage *restore_message, - int64_t resume_time) = 0; + // Restore player state (returns true on success, false on failure) + // Player ID remains unchanged after restore + virtual bool Restore(const CreateMessage *restore_message, + int64_t resume_time) = 0; virtual bool SetDisplayRotate(int64_t rotation) = 0; protected: @@ -100,6 +99,9 @@ class VideoPlayer { // Reset event dispatch state for restored player void ResetEventDispatchState(); + // Check if player is disposed (for use in callbacks) + bool IsDisposed() const; + int64_t player_id_; // Store player ID for FFI event callback std::mutex queue_mutex_; std::unique_ptr ecore_wl2_window_proxy_ = nullptr; diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index 7cc06d6c1..cfff3bfc0 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -299,8 +299,6 @@ void VideoPlayerTizenPluginRegisterWithRegistrar( #include using video_player_videohole_tizen::CreateMessage; -using video_player_videohole_tizen::g_dart_port; -using video_player_videohole_tizen::g_dart_port_mutex; using video_player_videohole_tizen::g_options; using video_player_videohole_tizen::g_players; using video_player_videohole_tizen::g_players_mutex; @@ -309,6 +307,8 @@ using video_player_videohole_tizen::g_registrar_ref; using video_player_videohole_tizen::GetPlayer; using video_player_videohole_tizen::ParseCreateMessage; using video_player_videohole_tizen::VideoPlayer; +using video_player_videohole_tizen::RegisterPlayerEventPort; +using video_player_videohole_tizen::UnregisterPlayerEventPort; extern "C" { @@ -525,8 +525,8 @@ int ffi_suspend(int64_t player_id) { return player->Suspend() ? 0 : -1; } -int64_t ffi_restore(int64_t player_id, const char* create_message_json, - int64_t resume_time) { +int ffi_restore(int64_t player_id, const char* create_message_json, + int64_t resume_time) { auto player = GetPlayer(player_id); if (!player) { return -1; @@ -537,17 +537,10 @@ int64_t ffi_restore(int64_t player_id, const char* create_message_json, msg = ParseCreateMessage(std::string(create_message_json)); } - // Restore returns the new player ID (may be same or different) - int64_t new_player_id = player->Restore(&msg, resume_time); - - // Update g_players map if player ID changed - if (new_player_id > 0 && new_player_id != player_id) { - std::unique_lock lock(g_players_mutex); - g_players.erase(player_id); - g_players[new_player_id] = player; - } - - return new_player_id; + // Restore returns true on success, false on failure + // Player ID remains unchanged + bool success = player->Restore(&msg, resume_time); + return success ? 0 : -1; } int ffi_set_activate(int64_t player_id) { @@ -566,13 +559,21 @@ int ffi_set_deactivate(int64_t player_id) { return player->Deactivate() ? 0 : -1; } +int ffi_is_live(int64_t player_id) { + auto player = GetPlayer(player_id); + if (!player) { + return -1; + } + // MediaPlayer::IsLive() returns bool, cast to int for FFI + return player->IsLive() ? 1 : 0; +} + int ffi_set_mix_with_others(bool mix_with_others) { g_options.SetMixWithOthers(mix_with_others); return 0; } // FFI event port functions -// Note: g_dart_port and g_dart_port_mutex are declared in video_player.h static bool g_dart_api_dl_initialized = false; int ffi_initialize_api_dl(void* data) { @@ -586,14 +587,36 @@ int ffi_initialize_api_dl(void* data) { return 0; } +// Legacy global event port registration - kept for compatibility +// New code should use ffi_register_player_event_port instead +static int64_t g_legacy_dart_port = -1; +static std::mutex g_legacy_dart_port_mutex; + void ffi_register_event_port(int64_t port) { - std::lock_guard lock(g_dart_port_mutex); - g_dart_port = port; + std::lock_guard lock(g_legacy_dart_port_mutex); + g_legacy_dart_port = port; } void ffi_unregister_event_port() { - std::lock_guard lock(g_dart_port_mutex); - g_dart_port = 0; + std::lock_guard lock(g_legacy_dart_port_mutex); + g_legacy_dart_port = -1; +} + +// P0-1 fix: FFI string memory management +// Provides matching free for strdup() allocated strings returned by FFI functions +void ffi_free_string(char* ptr) { + if (ptr != nullptr) { + free(ptr); + } +} + +// P0-2 fix: Per-player event port registration +void ffi_register_player_event_port(int64_t player_id, int64_t port) { + RegisterPlayerEventPort(player_id, port); +} + +void ffi_unregister_player_event_port(int64_t player_id) { + UnregisterPlayerEventPort(player_id); } } // extern "C" From f5dac1bb13adeff187da3cfa1a37914eab320272 Mon Sep 17 00:00:00 2001 From: "yying.jin" Date: Wed, 29 Jul 2026 18:04:18 +0800 Subject: [PATCH 14/18] P1-1: Use nlohmann/json library for JSON parsing - Add nlohmann/json single-header library to tizen/third_party/ - Replace handwritten JSON parser with nlohmann/json in ParseJsonMap() - Simplify ParseCreateMessage() to use json library directly - Add EncodableValueFromJson() helper for JSON to EncodableValue conversion This change improves JSON parsing reliability by supporting: - Escape characters in strings - Nested objects and arrays - Unicode characters - Proper error handling with parse_error exceptions Co-Authored-By: Cline SR --- .../tizen/src/video_player_tizen_plugin.cc | 253 +- .../tizen/third_party/json.hpp | 24596 ++++++++++++++++ 2 files changed, 24660 insertions(+), 189 deletions(-) create mode 100644 packages/video_player_videohole/tizen/third_party/json.hpp diff --git a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc index cfff3bfc0..4f3e74c0f 100644 --- a/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc +++ b/packages/video_player_videohole/tizen/src/video_player_tizen_plugin.cc @@ -18,11 +18,15 @@ #include #include +#include "../third_party/json.hpp" #include "ffi_messages.h" +#include "log.h" #include "media_player.h" #include "video_player.h" #include "video_player_options.h" +using nlohmann::json; + namespace video_player_videohole_tizen { // ===== Global State ===== @@ -48,140 +52,55 @@ static std::shared_ptr GetPlayer(int64_t player_id) { return nullptr; } -// Helper function to parse simple JSON-like string to flutter::EncodableMap +// Helper function to convert JSON value to EncodableValue +static flutter::EncodableValue EncodableValueFromJson(const json& j) { + if (j.is_null()) { + return flutter::EncodableValue(); + } else if (j.is_boolean()) { + return flutter::EncodableValue(j.get()); + } else if (j.is_number_integer()) { + return flutter::EncodableValue(static_cast(j.get())); + } else if (j.is_number_float()) { + return flutter::EncodableValue(j.get()); + } else if (j.is_string()) { + return flutter::EncodableValue(j.get()); + } else if (j.is_array()) { + flutter::EncodableList list; + for (const auto& item : j) { + list.push_back(EncodableValueFromJson(item)); + } + return flutter::EncodableValue(list); + } else if (j.is_object()) { + flutter::EncodableMap map; + for (auto& [key, value] : j.items()) { + map[flutter::EncodableValue(key)] = EncodableValueFromJson(value); + } + return flutter::EncodableValue(map); + } + return flutter::EncodableValue(); +} + +// Helper function to parse JSON string to flutter::EncodableMap static flutter::EncodableMap ParseJsonMap(const std::string& json_str) { flutter::EncodableMap result; if (json_str.empty() || json_str == "{}") { return result; } - std::string content = json_str; - if (content.front() == '{') content = content.substr(1); - if (content.back() == '}') content.pop_back(); - - size_t pos = 0; - while (pos < content.length()) { - while (pos < content.length() && - (isspace(content[pos]) || content[pos] == ',')) { - pos++; - } - if (pos >= content.length()) break; - - if (content[pos] != '"') break; - pos++; - size_t key_start = pos; - while (pos < content.length() && content[pos] != '"') pos++; - std::string key = content.substr(key_start, pos - key_start); - pos++; - - while (pos < content.length() && - (isspace(content[pos]) || content[pos] == ':')) { - pos++; - } - if (pos >= content.length()) break; - - std::string value; - if (content[pos] == '"') { - pos++; - size_t val_start = pos; - while (pos < content.length() && content[pos] != '"') pos++; - value = content.substr(val_start, pos - val_start); - pos++; - result[flutter::EncodableValue(key)] = flutter::EncodableValue(value); - } else if (content[pos] == '{') { - int brace_count = 1; - pos++; - while (pos < content.length() && brace_count > 0) { - if (content[pos] == '{') - brace_count++; - else if (content[pos] == '}') - brace_count--; - pos++; - } - result[flutter::EncodableValue(key)] = flutter::EncodableMap(); - } else { - size_t val_start = pos; - while (pos < content.length() && content[pos] != ',' && - content[pos] != '}') { - pos++; - } - value = content.substr(val_start, pos - val_start); - while (!value.empty() && isspace(value.back())) value.pop_back(); - - if (value == "true") { - result[flutter::EncodableValue(key)] = flutter::EncodableValue(true); - } else if (value == "false") { - result[flutter::EncodableValue(key)] = flutter::EncodableValue(false); - } else { - try { - if (value.find('.') != std::string::npos) { - result[flutter::EncodableValue(key)] = - flutter::EncodableValue(std::stod(value)); - } else { - result[flutter::EncodableValue(key)] = - flutter::EncodableValue(std::stoll(value)); - } - } catch (...) { - result[flutter::EncodableValue(key)] = flutter::EncodableValue(value); - } + try { + json j = json::parse(json_str); + if (j.is_object()) { + for (auto& [key, value] : j.items()) { + result[flutter::EncodableValue(key)] = EncodableValueFromJson(value); } } + } catch (const json::parse_error& e) { + LOG_ERROR("[ParseJsonMap] JSON parse error: %s", e.what()); } return result; } -// Helper function to extract a string value from JSON by key -static bool ExtractStringValue(const std::string& json_str, - const std::string& key, std::string& out_value) { - std::string search_key = "\"" + key + "\""; - size_t pos = json_str.find(search_key); - if (pos == std::string::npos) return false; - - pos = json_str.find(':', pos); - if (pos == std::string::npos) return false; - - pos++; - while (pos < json_str.length() && - (isspace(json_str[pos]) || json_str[pos] == ':')) - pos++; - if (pos >= json_str.length() || json_str[pos] != '"') return false; - - pos++; - size_t end = pos; - while (end < json_str.length() && json_str[end] != '"') end++; - - out_value = json_str.substr(pos, end - pos); - return true; -} - -// Helper function to extract a nested object from JSON by key -static std::string ExtractObjectValue(const std::string& json_str, - const std::string& key) { - std::string search_key = "\"" + key + "\""; - size_t pos = json_str.find(search_key); - if (pos == std::string::npos) return ""; - - pos = json_str.find(':', pos); - if (pos == std::string::npos) return ""; - - pos++; - while (pos < json_str.length() && isspace(json_str[pos])) pos++; - if (pos >= json_str.length() || json_str[pos] != '{') return ""; - - int brace_count = 1; - size_t start = pos; - pos++; - while (pos < json_str.length() && brace_count > 0) { - if (json_str[pos] == '{') - brace_count++; - else if (json_str[pos] == '}') - brace_count--; - pos++; - } - return json_str.substr(start, pos - start); -} - // Unified function to parse CreateMessage from JSON string static video_player_videohole_tizen::CreateMessage ParseCreateMessage( const std::string& json_str) { @@ -189,85 +108,41 @@ static video_player_videohole_tizen::CreateMessage ParseCreateMessage( using flutter::EncodableValue; using video_player_videohole_tizen::CreateMessage; - video_player_videohole_tizen::CreateMessage msg; + CreateMessage msg; if (json_str.empty() || json_str == "{}") { return msg; } - std::string value; - if (ExtractStringValue(json_str, "uri", value)) { - msg.set_uri(value); - } - if (ExtractStringValue(json_str, "asset", value)) { - msg.set_asset(value); - } - if (ExtractStringValue(json_str, "packageName", value)) { - msg.set_package_name(value); - } - if (ExtractStringValue(json_str, "formatHint", value)) { - msg.set_format_hint(value); - } - - std::string nested_json; + try { + json j = json::parse(json_str); - nested_json = ExtractObjectValue(json_str, "httpHeaders"); - if (!nested_json.empty()) { - flutter::EncodableMap headers = ParseJsonMap(nested_json); - if (!headers.empty()) { - msg.set_http_headers(headers); + // Parse simple string fields + if (j.contains("uri") && !j["uri"].is_null()) { + msg.set_uri(j["uri"].get()); } - } - - nested_json = ExtractObjectValue(json_str, "playerOptions"); - if (!nested_json.empty()) { - flutter::EncodableMap options = ParseJsonMap(nested_json); - if (!options.empty()) { - msg.set_player_options(options); + if (j.contains("asset") && !j["asset"].is_null()) { + msg.set_asset(j["asset"].get()); } - } - - nested_json = ExtractObjectValue(json_str, "drmConfigs"); - if (!nested_json.empty()) { - int64_t drm_type = 0; - std::string license_url; - - size_t drm_pos = nested_json.find("\"drmType\""); - if (drm_pos != std::string::npos) { - drm_pos = nested_json.find(':', drm_pos); - if (drm_pos != std::string::npos) { - drm_pos++; - while (drm_pos < nested_json.length() && - (isspace(nested_json[drm_pos]) || nested_json[drm_pos] == ':')) - drm_pos++; - size_t end = drm_pos; - while (end < nested_json.length() && nested_json[end] != ',' && - nested_json[end] != '}' && nested_json[end] != '"') - end++; - std::string val = nested_json.substr(drm_pos, end - drm_pos); - while (!val.empty() && (val.back() == '"' || isspace(val.back()))) - val.pop_back(); - try { - drm_type = std::stoll(val); - } catch (...) { - if (val == "1") - drm_type = 1; - else if (val == "2") - drm_type = 2; - } - } + if (j.contains("packageName") && !j["packageName"].is_null()) { + msg.set_package_name(j["packageName"].get()); + } + if (j.contains("formatHint") && !j["formatHint"].is_null()) { + msg.set_format_hint(j["formatHint"].get()); } - ExtractStringValue(nested_json, "licenseServerUrl", license_url); - - flutter::EncodableMap drm_map; - drm_map[flutter::EncodableValue("drmType")] = - flutter::EncodableValue(drm_type); - if (!license_url.empty()) { - drm_map[flutter::EncodableValue("licenseServerUrl")] = - flutter::EncodableValue(license_url); + // Parse nested objects + if (j.contains("httpHeaders") && j["httpHeaders"].is_object()) { + msg.set_http_headers(ParseJsonMap(j["httpHeaders"].dump())); + } + if (j.contains("playerOptions") && j["playerOptions"].is_object()) { + msg.set_player_options(ParseJsonMap(j["playerOptions"].dump())); + } + if (j.contains("drmConfigs") && j["drmConfigs"].is_object()) { + msg.set_drm_configs(ParseJsonMap(j["drmConfigs"].dump())); } - msg.set_drm_configs(drm_map); + } catch (const json::parse_error& e) { + LOG_ERROR("[ParseCreateMessage] JSON parse error: %s", e.what()); } return msg; diff --git a/packages/video_player_videohole/tizen/third_party/json.hpp b/packages/video_player_videohole/tizen/third_party/json.hpp new file mode 100644 index 000000000..4d1a37ad7 --- /dev/null +++ b/packages/video_player_videohole/tizen/third_party/json.hpp @@ -0,0 +1,24596 @@ +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + +/****************************************************************************\ + * Note on documentation: The source files contain links to the online * + * documentation of the public API at https://json.nlohmann.me. This URL * + * contains the most recent documentation and should also be applicable to * + * previous versions; documentation for deprecated functions is not * + * removed, but marked deprecated. See "Generate documentation" section in * + * file docs/README.md. * +\****************************************************************************/ + +#ifndef INCLUDE_NLOHMANN_JSON_HPP_ +#define INCLUDE_NLOHMANN_JSON_HPP_ + +#include // all_of, find, for_each +#include // nullptr_t, ptrdiff_t, size_t +#include // hash, less +#include // initializer_list +#ifndef JSON_NO_IO + #include // istream, ostream +#endif // JSON_NO_IO +#include // random_access_iterator_tag +#include // unique_ptr +#include // accumulate +#include // string, stoi, to_string +#include // declval, forward, move, pair, swap +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// This file contains all macro definitions affecting or depending on the ABI + +#ifndef JSON_SKIP_LIBRARY_VERSION_CHECK + #if defined(NLOHMANN_JSON_VERSION_MAJOR) && defined(NLOHMANN_JSON_VERSION_MINOR) && defined(NLOHMANN_JSON_VERSION_PATCH) + #if NLOHMANN_JSON_VERSION_MAJOR != 3 || NLOHMANN_JSON_VERSION_MINOR != 11 || NLOHMANN_JSON_VERSION_PATCH != 2 + #warning "Already included a different version of the library!" + #endif + #endif +#endif + +#define NLOHMANN_JSON_VERSION_MAJOR 3 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_MINOR 11 // NOLINT(modernize-macro-to-enum) +#define NLOHMANN_JSON_VERSION_PATCH 2 // NOLINT(modernize-macro-to-enum) + +#ifndef JSON_DIAGNOSTICS + #define JSON_DIAGNOSTICS 0 +#endif + +#ifndef JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON 0 +#endif + +#if JSON_DIAGNOSTICS + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS _diag +#else + #define NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS +#endif + +#if JSON_USE_LEGACY_DISCARDED_VALUE_COMPARISON + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON _ldvcmp +#else + #define NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_NO_VERSION + #define NLOHMANN_JSON_NAMESPACE_NO_VERSION 0 +#endif + +// Construct the namespace ABI tags component +#define NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) json_abi ## a ## b +#define NLOHMANN_JSON_ABI_TAGS_CONCAT(a, b) \ + NLOHMANN_JSON_ABI_TAGS_CONCAT_EX(a, b) + +#define NLOHMANN_JSON_ABI_TAGS \ + NLOHMANN_JSON_ABI_TAGS_CONCAT( \ + NLOHMANN_JSON_ABI_TAG_DIAGNOSTICS, \ + NLOHMANN_JSON_ABI_TAG_LEGACY_DISCARDED_VALUE_COMPARISON) + +// Construct the namespace version component +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) \ + _v ## major ## _ ## minor ## _ ## patch +#define NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(major, minor, patch) \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT_EX(major, minor, patch) + +#if NLOHMANN_JSON_NAMESPACE_NO_VERSION +#define NLOHMANN_JSON_NAMESPACE_VERSION +#else +#define NLOHMANN_JSON_NAMESPACE_VERSION \ + NLOHMANN_JSON_NAMESPACE_VERSION_CONCAT(NLOHMANN_JSON_VERSION_MAJOR, \ + NLOHMANN_JSON_VERSION_MINOR, \ + NLOHMANN_JSON_VERSION_PATCH) +#endif + +// Combine namespace components +#define NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) a ## b +#define NLOHMANN_JSON_NAMESPACE_CONCAT(a, b) \ + NLOHMANN_JSON_NAMESPACE_CONCAT_EX(a, b) + +#ifndef NLOHMANN_JSON_NAMESPACE +#define NLOHMANN_JSON_NAMESPACE \ + nlohmann::NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_BEGIN +#define NLOHMANN_JSON_NAMESPACE_BEGIN \ + namespace nlohmann \ + { \ + inline namespace NLOHMANN_JSON_NAMESPACE_CONCAT( \ + NLOHMANN_JSON_ABI_TAGS, \ + NLOHMANN_JSON_NAMESPACE_VERSION) \ + { +#endif + +#ifndef NLOHMANN_JSON_NAMESPACE_END +#define NLOHMANN_JSON_NAMESPACE_END \ + } /* namespace (inline namespace) NOLINT(readability/namespace) */ \ + } // namespace nlohmann +#endif + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // transform +#include // array +#include // forward_list +#include // inserter, front_inserter, end +#include // map +#include // string +#include // tuple, make_tuple +#include // is_arithmetic, is_same, is_enum, underlying_type, is_convertible +#include // unordered_map +#include // pair, declval +#include // valarray + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // nullptr_t +#include // exception +#include // runtime_error +#include // to_string +#include // vector + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // uint8_t +#include // string + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // declval, pair +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template struct make_void +{ + using type = void; +}; +template using void_t = typename make_void::type; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +// https://en.cppreference.com/w/cpp/experimental/is_detected +struct nonesuch +{ + nonesuch() = delete; + ~nonesuch() = delete; + nonesuch(nonesuch const&) = delete; + nonesuch(nonesuch const&&) = delete; + void operator=(nonesuch const&) = delete; + void operator=(nonesuch&&) = delete; +}; + +template class Op, + class... Args> +struct detector +{ + using value_t = std::false_type; + using type = Default; +}; + +template class Op, class... Args> +struct detector>, Op, Args...> +{ + using value_t = std::true_type; + using type = Op; +}; + +template class Op, class... Args> +using is_detected = typename detector::value_t; + +template class Op, class... Args> +struct is_detected_lazy : is_detected { }; + +template class Op, class... Args> +using detected_t = typename detector::type; + +template class Op, class... Args> +using detected_or = detector; + +template class Op, class... Args> +using detected_or_t = typename detected_or::type; + +template class Op, class... Args> +using is_detected_exact = std::is_same>; + +template class Op, class... Args> +using is_detected_convertible = + std::is_convertible, To>; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + + +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-FileCopyrightText: 2016-2021 Evan Nemerson +// SPDX-License-Identifier: MIT + +/* Hedley - https://nemequ.github.io/hedley + * Created by Evan Nemerson + */ + +#if !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < 15) +#if defined(JSON_HEDLEY_VERSION) + #undef JSON_HEDLEY_VERSION +#endif +#define JSON_HEDLEY_VERSION 15 + +#if defined(JSON_HEDLEY_STRINGIFY_EX) + #undef JSON_HEDLEY_STRINGIFY_EX +#endif +#define JSON_HEDLEY_STRINGIFY_EX(x) #x + +#if defined(JSON_HEDLEY_STRINGIFY) + #undef JSON_HEDLEY_STRINGIFY +#endif +#define JSON_HEDLEY_STRINGIFY(x) JSON_HEDLEY_STRINGIFY_EX(x) + +#if defined(JSON_HEDLEY_CONCAT_EX) + #undef JSON_HEDLEY_CONCAT_EX +#endif +#define JSON_HEDLEY_CONCAT_EX(a,b) a##b + +#if defined(JSON_HEDLEY_CONCAT) + #undef JSON_HEDLEY_CONCAT +#endif +#define JSON_HEDLEY_CONCAT(a,b) JSON_HEDLEY_CONCAT_EX(a,b) + +#if defined(JSON_HEDLEY_CONCAT3_EX) + #undef JSON_HEDLEY_CONCAT3_EX +#endif +#define JSON_HEDLEY_CONCAT3_EX(a,b,c) a##b##c + +#if defined(JSON_HEDLEY_CONCAT3) + #undef JSON_HEDLEY_CONCAT3 +#endif +#define JSON_HEDLEY_CONCAT3(a,b,c) JSON_HEDLEY_CONCAT3_EX(a,b,c) + +#if defined(JSON_HEDLEY_VERSION_ENCODE) + #undef JSON_HEDLEY_VERSION_ENCODE +#endif +#define JSON_HEDLEY_VERSION_ENCODE(major,minor,revision) (((major) * 1000000) + ((minor) * 1000) + (revision)) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MAJOR) + #undef JSON_HEDLEY_VERSION_DECODE_MAJOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MAJOR(version) ((version) / 1000000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_MINOR) + #undef JSON_HEDLEY_VERSION_DECODE_MINOR +#endif +#define JSON_HEDLEY_VERSION_DECODE_MINOR(version) (((version) % 1000000) / 1000) + +#if defined(JSON_HEDLEY_VERSION_DECODE_REVISION) + #undef JSON_HEDLEY_VERSION_DECODE_REVISION +#endif +#define JSON_HEDLEY_VERSION_DECODE_REVISION(version) ((version) % 1000) + +#if defined(JSON_HEDLEY_GNUC_VERSION) + #undef JSON_HEDLEY_GNUC_VERSION +#endif +#if defined(__GNUC__) && defined(__GNUC_PATCHLEVEL__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) +#elif defined(__GNUC__) + #define JSON_HEDLEY_GNUC_VERSION JSON_HEDLEY_VERSION_ENCODE(__GNUC__, __GNUC_MINOR__, 0) +#endif + +#if defined(JSON_HEDLEY_GNUC_VERSION_CHECK) + #undef JSON_HEDLEY_GNUC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GNUC_VERSION) + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GNUC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION) + #undef JSON_HEDLEY_MSVC_VERSION +#endif +#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 140000000) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 10000000, (_MSC_FULL_VER % 10000000) / 100000, (_MSC_FULL_VER % 100000) / 100) +#elif defined(_MSC_FULL_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_FULL_VER / 1000000, (_MSC_FULL_VER % 1000000) / 10000, (_MSC_FULL_VER % 10000) / 10) +#elif defined(_MSC_VER) && !defined(__ICL) + #define JSON_HEDLEY_MSVC_VERSION JSON_HEDLEY_VERSION_ENCODE(_MSC_VER / 100, _MSC_VER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_MSVC_VERSION_CHECK) + #undef JSON_HEDLEY_MSVC_VERSION_CHECK +#endif +#if !defined(JSON_HEDLEY_MSVC_VERSION) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (0) +#elif defined(_MSC_VER) && (_MSC_VER >= 1400) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 10000000) + (minor * 100000) + (patch))) +#elif defined(_MSC_VER) && (_MSC_VER >= 1200) + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_FULL_VER >= ((major * 1000000) + (minor * 10000) + (patch))) +#else + #define JSON_HEDLEY_MSVC_VERSION_CHECK(major,minor,patch) (_MSC_VER >= ((major * 100) + (minor))) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION) + #undef JSON_HEDLEY_INTEL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, __INTEL_COMPILER_UPDATE) +#elif defined(__INTEL_COMPILER) && !defined(__ICL) + #define JSON_HEDLEY_INTEL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER / 100, __INTEL_COMPILER % 100, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_VERSION) + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #undef JSON_HEDLEY_INTEL_CL_VERSION +#endif +#if defined(__INTEL_COMPILER) && defined(__INTEL_COMPILER_UPDATE) && defined(__ICL) + #define JSON_HEDLEY_INTEL_CL_VERSION JSON_HEDLEY_VERSION_ENCODE(__INTEL_COMPILER, __INTEL_COMPILER_UPDATE, 0) +#endif + +#if defined(JSON_HEDLEY_INTEL_CL_VERSION_CHECK) + #undef JSON_HEDLEY_INTEL_CL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_INTEL_CL_VERSION) + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_INTEL_CL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_INTEL_CL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION) + #undef JSON_HEDLEY_PGI_VERSION +#endif +#if defined(__PGI) && defined(__PGIC__) && defined(__PGIC_MINOR__) && defined(__PGIC_PATCHLEVEL__) + #define JSON_HEDLEY_PGI_VERSION JSON_HEDLEY_VERSION_ENCODE(__PGIC__, __PGIC_MINOR__, __PGIC_PATCHLEVEL__) +#endif + +#if defined(JSON_HEDLEY_PGI_VERSION_CHECK) + #undef JSON_HEDLEY_PGI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PGI_VERSION) + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PGI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PGI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #undef JSON_HEDLEY_SUNPRO_VERSION +#endif +#if defined(__SUNPRO_C) && (__SUNPRO_C > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_C >> 16) & 0xf) * 10) + ((__SUNPRO_C >> 12) & 0xf), (((__SUNPRO_C >> 8) & 0xf) * 10) + ((__SUNPRO_C >> 4) & 0xf), (__SUNPRO_C & 0xf) * 10) +#elif defined(__SUNPRO_C) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_C >> 8) & 0xf, (__SUNPRO_C >> 4) & 0xf, (__SUNPRO_C) & 0xf) +#elif defined(__SUNPRO_CC) && (__SUNPRO_CC > 0x1000) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((((__SUNPRO_CC >> 16) & 0xf) * 10) + ((__SUNPRO_CC >> 12) & 0xf), (((__SUNPRO_CC >> 8) & 0xf) * 10) + ((__SUNPRO_CC >> 4) & 0xf), (__SUNPRO_CC & 0xf) * 10) +#elif defined(__SUNPRO_CC) + #define JSON_HEDLEY_SUNPRO_VERSION JSON_HEDLEY_VERSION_ENCODE((__SUNPRO_CC >> 8) & 0xf, (__SUNPRO_CC >> 4) & 0xf, (__SUNPRO_CC) & 0xf) +#endif + +#if defined(JSON_HEDLEY_SUNPRO_VERSION_CHECK) + #undef JSON_HEDLEY_SUNPRO_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_SUNPRO_VERSION) + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_SUNPRO_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_SUNPRO_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION +#endif +#if defined(__EMSCRIPTEN__) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION JSON_HEDLEY_VERSION_ENCODE(__EMSCRIPTEN_major__, __EMSCRIPTEN_minor__, __EMSCRIPTEN_tiny__) +#endif + +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK) + #undef JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_EMSCRIPTEN_VERSION) + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_EMSCRIPTEN_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_EMSCRIPTEN_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION) + #undef JSON_HEDLEY_ARM_VERSION +#endif +#if defined(__CC_ARM) && defined(__ARMCOMPILER_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCOMPILER_VERSION / 1000000, (__ARMCOMPILER_VERSION % 1000000) / 10000, (__ARMCOMPILER_VERSION % 10000) / 100) +#elif defined(__CC_ARM) && defined(__ARMCC_VERSION) + #define JSON_HEDLEY_ARM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ARMCC_VERSION / 1000000, (__ARMCC_VERSION % 1000000) / 10000, (__ARMCC_VERSION % 10000) / 100) +#endif + +#if defined(JSON_HEDLEY_ARM_VERSION_CHECK) + #undef JSON_HEDLEY_ARM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_ARM_VERSION) + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_ARM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_ARM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION) + #undef JSON_HEDLEY_IBM_VERSION +#endif +#if defined(__ibmxl__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__ibmxl_version__, __ibmxl_release__, __ibmxl_modification__) +#elif defined(__xlC__) && defined(__xlC_ver__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, (__xlC_ver__ >> 8) & 0xff) +#elif defined(__xlC__) + #define JSON_HEDLEY_IBM_VERSION JSON_HEDLEY_VERSION_ENCODE(__xlC__ >> 8, __xlC__ & 0xff, 0) +#endif + +#if defined(JSON_HEDLEY_IBM_VERSION_CHECK) + #undef JSON_HEDLEY_IBM_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IBM_VERSION) + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IBM_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IBM_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_VERSION) + #undef JSON_HEDLEY_TI_VERSION +#endif +#if \ + defined(__TI_COMPILER_VERSION__) && \ + ( \ + defined(__TMS470__) || defined(__TI_ARM__) || \ + defined(__MSP430__) || \ + defined(__TMS320C2000__) \ + ) +#if (__TI_COMPILER_VERSION__ >= 16000000) + #define JSON_HEDLEY_TI_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif +#endif + +#if defined(JSON_HEDLEY_TI_VERSION_CHECK) + #undef JSON_HEDLEY_TI_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_VERSION) + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #undef JSON_HEDLEY_TI_CL2000_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C2000__) + #define JSON_HEDLEY_TI_CL2000_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL2000_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL2000_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL2000_VERSION) + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL2000_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL2000_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #undef JSON_HEDLEY_TI_CL430_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__MSP430__) + #define JSON_HEDLEY_TI_CL430_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL430_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL430_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL430_VERSION) + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL430_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL430_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #undef JSON_HEDLEY_TI_ARMCL_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && (defined(__TMS470__) || defined(__TI_ARM__)) + #define JSON_HEDLEY_TI_ARMCL_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION_CHECK) + #undef JSON_HEDLEY_TI_ARMCL_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_ARMCL_VERSION) + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_ARMCL_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #undef JSON_HEDLEY_TI_CL6X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__TMS320C6X__) + #define JSON_HEDLEY_TI_CL6X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL6X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL6X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL6X_VERSION) + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL6X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL6X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #undef JSON_HEDLEY_TI_CL7X_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__C7000__) + #define JSON_HEDLEY_TI_CL7X_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CL7X_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CL7X_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CL7X_VERSION) + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CL7X_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CL7X_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #undef JSON_HEDLEY_TI_CLPRU_VERSION +#endif +#if defined(__TI_COMPILER_VERSION__) && defined(__PRU__) + #define JSON_HEDLEY_TI_CLPRU_VERSION JSON_HEDLEY_VERSION_ENCODE(__TI_COMPILER_VERSION__ / 1000000, (__TI_COMPILER_VERSION__ % 1000000) / 1000, (__TI_COMPILER_VERSION__ % 1000)) +#endif + +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION_CHECK) + #undef JSON_HEDLEY_TI_CLPRU_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TI_CLPRU_VERSION) + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TI_CLPRU_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION) + #undef JSON_HEDLEY_CRAY_VERSION +#endif +#if defined(_CRAYC) + #if defined(_RELEASE_PATCHLEVEL) + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, _RELEASE_PATCHLEVEL) + #else + #define JSON_HEDLEY_CRAY_VERSION JSON_HEDLEY_VERSION_ENCODE(_RELEASE_MAJOR, _RELEASE_MINOR, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_CRAY_VERSION_CHECK) + #undef JSON_HEDLEY_CRAY_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_CRAY_VERSION) + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_CRAY_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_CRAY_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION) + #undef JSON_HEDLEY_IAR_VERSION +#endif +#if defined(__IAR_SYSTEMS_ICC__) + #if __VER__ > 1000 + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE((__VER__ / 1000000), ((__VER__ / 1000) % 1000), (__VER__ % 1000)) + #else + #define JSON_HEDLEY_IAR_VERSION JSON_HEDLEY_VERSION_ENCODE(__VER__ / 100, __VER__ % 100, 0) + #endif +#endif + +#if defined(JSON_HEDLEY_IAR_VERSION_CHECK) + #undef JSON_HEDLEY_IAR_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_IAR_VERSION) + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_IAR_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_IAR_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION) + #undef JSON_HEDLEY_TINYC_VERSION +#endif +#if defined(__TINYC__) + #define JSON_HEDLEY_TINYC_VERSION JSON_HEDLEY_VERSION_ENCODE(__TINYC__ / 1000, (__TINYC__ / 100) % 10, __TINYC__ % 100) +#endif + +#if defined(JSON_HEDLEY_TINYC_VERSION_CHECK) + #undef JSON_HEDLEY_TINYC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_TINYC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_TINYC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION) + #undef JSON_HEDLEY_DMC_VERSION +#endif +#if defined(__DMC__) + #define JSON_HEDLEY_DMC_VERSION JSON_HEDLEY_VERSION_ENCODE(__DMC__ >> 8, (__DMC__ >> 4) & 0xf, __DMC__ & 0xf) +#endif + +#if defined(JSON_HEDLEY_DMC_VERSION_CHECK) + #undef JSON_HEDLEY_DMC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_DMC_VERSION) + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_DMC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_DMC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #undef JSON_HEDLEY_COMPCERT_VERSION +#endif +#if defined(__COMPCERT_VERSION__) + #define JSON_HEDLEY_COMPCERT_VERSION JSON_HEDLEY_VERSION_ENCODE(__COMPCERT_VERSION__ / 10000, (__COMPCERT_VERSION__ / 100) % 100, __COMPCERT_VERSION__ % 100) +#endif + +#if defined(JSON_HEDLEY_COMPCERT_VERSION_CHECK) + #undef JSON_HEDLEY_COMPCERT_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_COMPCERT_VERSION) + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_COMPCERT_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_COMPCERT_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION) + #undef JSON_HEDLEY_PELLES_VERSION +#endif +#if defined(__POCC__) + #define JSON_HEDLEY_PELLES_VERSION JSON_HEDLEY_VERSION_ENCODE(__POCC__ / 100, __POCC__ % 100, 0) +#endif + +#if defined(JSON_HEDLEY_PELLES_VERSION_CHECK) + #undef JSON_HEDLEY_PELLES_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_PELLES_VERSION) + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_PELLES_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_PELLES_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #undef JSON_HEDLEY_MCST_LCC_VERSION +#endif +#if defined(__LCC__) && defined(__LCC_MINOR__) + #define JSON_HEDLEY_MCST_LCC_VERSION JSON_HEDLEY_VERSION_ENCODE(__LCC__ / 100, __LCC__ % 100, __LCC_MINOR__) +#endif + +#if defined(JSON_HEDLEY_MCST_LCC_VERSION_CHECK) + #undef JSON_HEDLEY_MCST_LCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_MCST_LCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_MCST_LCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION) + #undef JSON_HEDLEY_GCC_VERSION +#endif +#if \ + defined(JSON_HEDLEY_GNUC_VERSION) && \ + !defined(__clang__) && \ + !defined(JSON_HEDLEY_INTEL_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_ARM_VERSION) && \ + !defined(JSON_HEDLEY_CRAY_VERSION) && \ + !defined(JSON_HEDLEY_TI_VERSION) && \ + !defined(JSON_HEDLEY_TI_ARMCL_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL430_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL2000_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL6X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CL7X_VERSION) && \ + !defined(JSON_HEDLEY_TI_CLPRU_VERSION) && \ + !defined(__COMPCERT__) && \ + !defined(JSON_HEDLEY_MCST_LCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION JSON_HEDLEY_GNUC_VERSION +#endif + +#if defined(JSON_HEDLEY_GCC_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_VERSION_CHECK +#endif +#if defined(JSON_HEDLEY_GCC_VERSION) + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (JSON_HEDLEY_GCC_VERSION >= JSON_HEDLEY_VERSION_ENCODE(major, minor, patch)) +#else + #define JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_ATTRIBUTE +#endif +#if \ + defined(__has_attribute) && \ + ( \ + (!defined(JSON_HEDLEY_IAR_VERSION) || JSON_HEDLEY_IAR_VERSION_CHECK(8,5,9)) \ + ) +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) __has_attribute(attribute) +#else +# define JSON_HEDLEY_HAS_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_ATTRIBUTE +#endif +#if defined(__has_attribute) + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE +#endif +#if \ + defined(__has_cpp_attribute) && \ + defined(__cplusplus) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS) + #undef JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS +#endif +#if !defined(__cplusplus) || !defined(__has_cpp_attribute) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#elif \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION) && \ + (!defined(JSON_HEDLEY_SUNPRO_VERSION) || JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0)) && \ + (!defined(JSON_HEDLEY_MSVC_VERSION) || JSON_HEDLEY_MSVC_VERSION_CHECK(19,20,0)) + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(ns::attribute) +#else + #define JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(ns,attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE +#endif +#if defined(__has_cpp_attribute) && defined(__cplusplus) + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) __has_cpp_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_CPP_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_BUILTIN) + #undef JSON_HEDLEY_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_HAS_BUILTIN(builtin) __has_builtin(builtin) +#else + #define JSON_HEDLEY_HAS_BUILTIN(builtin) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_BUILTIN) + #undef JSON_HEDLEY_GNUC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GNUC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_BUILTIN) + #undef JSON_HEDLEY_GCC_HAS_BUILTIN +#endif +#if defined(__has_builtin) + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) __has_builtin(builtin) +#else + #define JSON_HEDLEY_GCC_HAS_BUILTIN(builtin,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_FEATURE) + #undef JSON_HEDLEY_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_HAS_FEATURE(feature) __has_feature(feature) +#else + #define JSON_HEDLEY_HAS_FEATURE(feature) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_FEATURE) + #undef JSON_HEDLEY_GNUC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GNUC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_FEATURE) + #undef JSON_HEDLEY_GCC_HAS_FEATURE +#endif +#if defined(__has_feature) + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) __has_feature(feature) +#else + #define JSON_HEDLEY_GCC_HAS_FEATURE(feature,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_EXTENSION) + #undef JSON_HEDLEY_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_HAS_EXTENSION(extension) __has_extension(extension) +#else + #define JSON_HEDLEY_HAS_EXTENSION(extension) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_EXTENSION) + #undef JSON_HEDLEY_GNUC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GNUC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_EXTENSION) + #undef JSON_HEDLEY_GCC_HAS_EXTENSION +#endif +#if defined(__has_extension) + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) __has_extension(extension) +#else + #define JSON_HEDLEY_GCC_HAS_EXTENSION(extension,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GNUC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE +#endif +#if defined(__has_declspec_attribute) + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) __has_declspec_attribute(attribute) +#else + #define JSON_HEDLEY_GCC_HAS_DECLSPEC_ATTRIBUTE(attribute,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_HAS_WARNING) + #undef JSON_HEDLEY_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_HAS_WARNING(warning) __has_warning(warning) +#else + #define JSON_HEDLEY_HAS_WARNING(warning) (0) +#endif + +#if defined(JSON_HEDLEY_GNUC_HAS_WARNING) + #undef JSON_HEDLEY_GNUC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GNUC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GNUC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_GCC_HAS_WARNING) + #undef JSON_HEDLEY_GCC_HAS_WARNING +#endif +#if defined(__has_warning) + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) __has_warning(warning) +#else + #define JSON_HEDLEY_GCC_HAS_WARNING(warning,major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + defined(__clang__) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,17) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(8,0,0) || \ + (JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) && defined(__C99_PRAGMA_OPERATOR)) + #define JSON_HEDLEY_PRAGMA(value) _Pragma(#value) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_PRAGMA(value) __pragma(value) +#else + #define JSON_HEDLEY_PRAGMA(value) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_PUSH) + #undef JSON_HEDLEY_DIAGNOSTIC_PUSH +#endif +#if defined(JSON_HEDLEY_DIAGNOSTIC_POP) + #undef JSON_HEDLEY_DIAGNOSTIC_POP +#endif +#if defined(__clang__) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("clang diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("clang diagnostic pop") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("GCC diagnostic push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("GCC diagnostic pop") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH __pragma(warning(push)) + #define JSON_HEDLEY_DIAGNOSTIC_POP __pragma(warning(pop)) +#elif JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("pop") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("diag_push") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("diag_pop") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_PUSH _Pragma("warning(push)") + #define JSON_HEDLEY_DIAGNOSTIC_POP _Pragma("warning(pop)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_PUSH + #define JSON_HEDLEY_DIAGNOSTIC_POP +#endif + +/* JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_ +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat") +# if JSON_HEDLEY_HAS_WARNING("-Wc++17-extensions") +# if JSON_HEDLEY_HAS_WARNING("-Wc++1z-extensions") +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + _Pragma("clang diagnostic ignored \"-Wc++1z-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + _Pragma("clang diagnostic ignored \"-Wc++17-extensions\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# else +# define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(xpr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wc++98-compat\"") \ + xpr \ + JSON_HEDLEY_DIAGNOSTIC_POP +# endif +# endif +#endif +#if !defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(x) x +#endif + +#if defined(JSON_HEDLEY_CONST_CAST) + #undef JSON_HEDLEY_CONST_CAST +#endif +#if defined(__cplusplus) +# define JSON_HEDLEY_CONST_CAST(T, expr) (const_cast(expr)) +#elif \ + JSON_HEDLEY_HAS_WARNING("-Wcast-qual") || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_CONST_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_CONST_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_REINTERPRET_CAST) + #undef JSON_HEDLEY_REINTERPRET_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) (reinterpret_cast(expr)) +#else + #define JSON_HEDLEY_REINTERPRET_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_STATIC_CAST) + #undef JSON_HEDLEY_STATIC_CAST +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_STATIC_CAST(T, expr) (static_cast(expr)) +#else + #define JSON_HEDLEY_STATIC_CAST(T, expr) ((T) (expr)) +#endif + +#if defined(JSON_HEDLEY_CPP_CAST) + #undef JSON_HEDLEY_CPP_CAST +#endif +#if defined(__cplusplus) +# if JSON_HEDLEY_HAS_WARNING("-Wold-style-cast") +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wold-style-cast\"") \ + ((T) (expr)) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# elif JSON_HEDLEY_IAR_VERSION_CHECK(8,3,0) +# define JSON_HEDLEY_CPP_CAST(T, expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("diag_suppress=Pe137") \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_CPP_CAST(T, expr) ((T) (expr)) +# endif +#else +# define JSON_HEDLEY_CPP_CAST(T, expr) (expr) +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wdeprecated-declarations") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("clang diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warning(disable:1478 1786)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:1478 1786)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1216,1444,1445") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED __pragma(warning(disable:4996)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1215,1444") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress 1291,1718") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && !defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,E_DEPRECATED_ATT,E_DEPRECATED_ATT_MESS)") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("error_messages(off,symdeprecated,symdeprecated2)") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("diag_suppress=Pe1444,Pe1215") +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,90,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED _Pragma("warn(disable:2241)") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_DEPRECATED +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("clang diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("warning(disable:161)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:161)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 1675") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("GCC diagnostic ignored \"-Wunknown-pragmas\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS __pragma(warning(disable:4068)) +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(16,9,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 163") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress=Pe161") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS _Pragma("diag_suppress 161") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-attributes") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("clang diagnostic ignored \"-Wunknown-attributes\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(4,6,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("warning(disable:1292)") +#elif JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:1292)) +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES __pragma(warning(disable:5030)) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(20,7,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097,1098") +#elif JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("error_messages(off,attrskipunsup)") +#elif \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1173") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress=Pe1097") +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES _Pragma("diag_suppress 1097") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_CPP_ATTRIBUTES +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wcast-qual") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("clang diagnostic ignored \"-Wcast-qual\"") +#elif JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("warning(disable:2203 2331)") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL _Pragma("GCC diagnostic ignored \"-Wcast-qual\"") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_CAST_QUAL +#endif + +#if defined(JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION) + #undef JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunused-function") + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("clang diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("GCC diagnostic ignored \"-Wunused-function\"") +#elif JSON_HEDLEY_MSVC_VERSION_CHECK(1,0,0) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION __pragma(warning(disable:4505)) +#elif JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION _Pragma("diag_suppress 3142") +#else + #define JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNUSED_FUNCTION +#endif + +#if defined(JSON_HEDLEY_DEPRECATED) + #undef JSON_HEDLEY_DEPRECATED +#endif +#if defined(JSON_HEDLEY_DEPRECATED_FOR) + #undef JSON_HEDLEY_DEPRECATED_FOR +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated("Since " # since)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated("Since " #since "; use " #replacement)) +#elif \ + (JSON_HEDLEY_HAS_EXTENSION(attribute_deprecated_with_message) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,13,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(18,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,3,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,3,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__("Since " #since))) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__("Since " #since "; use " #replacement))) +#elif defined(__cplusplus) && (__cplusplus >= 201402L) + #define JSON_HEDLEY_DEPRECATED(since) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since)]]) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[deprecated("Since " #since "; use " #replacement)]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(deprecated) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_DEPRECATED(since) __attribute__((__deprecated__)) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __attribute__((__deprecated__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_PELLES_VERSION_CHECK(6,50,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_DEPRECATED(since) __declspec(deprecated) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) __declspec(deprecated) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_DEPRECATED(since) _Pragma("deprecated") + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) _Pragma("deprecated") +#else + #define JSON_HEDLEY_DEPRECATED(since) + #define JSON_HEDLEY_DEPRECATED_FOR(since, replacement) +#endif + +#if defined(JSON_HEDLEY_UNAVAILABLE) + #undef JSON_HEDLEY_UNAVAILABLE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warning) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNAVAILABLE(available_since) __attribute__((__warning__("Not available until " #available_since))) +#else + #define JSON_HEDLEY_UNAVAILABLE(available_since) +#endif + +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT +#endif +#if defined(JSON_HEDLEY_WARN_UNUSED_RESULT_MSG) + #undef JSON_HEDLEY_WARN_UNUSED_RESULT_MSG +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(warn_unused_result) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_WARN_UNUSED_RESULT __attribute__((__warn_unused_result__)) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) __attribute__((__warn_unused_result__)) +#elif (JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) >= 201907L) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard(msg)]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(nodiscard) + #define JSON_HEDLEY_WARN_UNUSED_RESULT JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[nodiscard]]) +#elif defined(_Check_return_) /* SAL */ + #define JSON_HEDLEY_WARN_UNUSED_RESULT _Check_return_ + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) _Check_return_ +#else + #define JSON_HEDLEY_WARN_UNUSED_RESULT + #define JSON_HEDLEY_WARN_UNUSED_RESULT_MSG(msg) +#endif + +#if defined(JSON_HEDLEY_SENTINEL) + #undef JSON_HEDLEY_SENTINEL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(sentinel) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_SENTINEL(position) __attribute__((__sentinel__(position))) +#else + #define JSON_HEDLEY_SENTINEL(position) +#endif + +#if defined(JSON_HEDLEY_NO_RETURN) + #undef JSON_HEDLEY_NO_RETURN +#endif +#if JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NO_RETURN __noreturn +#elif \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 201112L + #define JSON_HEDLEY_NO_RETURN _Noreturn +#elif defined(__cplusplus) && (__cplusplus >= 201103L) + #define JSON_HEDLEY_NO_RETURN JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[noreturn]]) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(noreturn) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,2,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NO_RETURN __attribute__((__noreturn__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_NO_RETURN _Pragma("does_not_return") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NO_RETURN _Pragma("FUNC_NEVER_RETURNS;") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NO_RETURN __attribute((noreturn)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NO_RETURN __declspec(noreturn) +#else + #define JSON_HEDLEY_NO_RETURN +#endif + +#if defined(JSON_HEDLEY_NO_ESCAPE) + #undef JSON_HEDLEY_NO_ESCAPE +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(noescape) + #define JSON_HEDLEY_NO_ESCAPE __attribute__((__noescape__)) +#else + #define JSON_HEDLEY_NO_ESCAPE +#endif + +#if defined(JSON_HEDLEY_UNREACHABLE) + #undef JSON_HEDLEY_UNREACHABLE +#endif +#if defined(JSON_HEDLEY_UNREACHABLE_RETURN) + #undef JSON_HEDLEY_UNREACHABLE_RETURN +#endif +#if defined(JSON_HEDLEY_ASSUME) + #undef JSON_HEDLEY_ASSUME +#endif +#if \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_ASSUME(expr) __assume(expr) +#elif JSON_HEDLEY_HAS_BUILTIN(__builtin_assume) + #define JSON_HEDLEY_ASSUME(expr) __builtin_assume(expr) +#elif \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #if defined(__cplusplus) + #define JSON_HEDLEY_ASSUME(expr) std::_nassert(expr) + #else + #define JSON_HEDLEY_ASSUME(expr) _nassert(expr) + #endif +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_unreachable) && (!defined(JSON_HEDLEY_ARM_VERSION))) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,5,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,10,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,5) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(10,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_UNREACHABLE() __builtin_unreachable() +#elif defined(JSON_HEDLEY_ASSUME) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif +#if !defined(JSON_HEDLEY_ASSUME) + #if defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, ((expr) ? 1 : (JSON_HEDLEY_UNREACHABLE(), 1))) + #else + #define JSON_HEDLEY_ASSUME(expr) JSON_HEDLEY_STATIC_CAST(void, expr) + #endif +#endif +#if defined(JSON_HEDLEY_UNREACHABLE) + #if \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (JSON_HEDLEY_STATIC_CAST(void, JSON_HEDLEY_ASSUME(0)), (value)) + #else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) JSON_HEDLEY_UNREACHABLE() + #endif +#else + #define JSON_HEDLEY_UNREACHABLE_RETURN(value) return (value) +#endif +#if !defined(JSON_HEDLEY_UNREACHABLE) + #define JSON_HEDLEY_UNREACHABLE() JSON_HEDLEY_ASSUME(0) +#endif + +JSON_HEDLEY_DIAGNOSTIC_PUSH +#if JSON_HEDLEY_HAS_WARNING("-Wpedantic") + #pragma clang diagnostic ignored "-Wpedantic" +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wc++98-compat-pedantic") && defined(__cplusplus) + #pragma clang diagnostic ignored "-Wc++98-compat-pedantic" +#endif +#if JSON_HEDLEY_GCC_HAS_WARNING("-Wvariadic-macros",4,0,0) + #if defined(__clang__) + #pragma clang diagnostic ignored "-Wvariadic-macros" + #elif defined(JSON_HEDLEY_GCC_VERSION) + #pragma GCC diagnostic ignored "-Wvariadic-macros" + #endif +#endif +#if defined(JSON_HEDLEY_NON_NULL) + #undef JSON_HEDLEY_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NON_NULL(...) __attribute__((__nonnull__(__VA_ARGS__))) +#else + #define JSON_HEDLEY_NON_NULL(...) +#endif +JSON_HEDLEY_DIAGNOSTIC_POP + +#if defined(JSON_HEDLEY_PRINTF_FORMAT) + #undef JSON_HEDLEY_PRINTF_FORMAT +#endif +#if defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && !defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(ms_printf, string_idx, first_to_check))) +#elif defined(__MINGW32__) && JSON_HEDLEY_GCC_HAS_ATTRIBUTE(format,4,4,0) && defined(__USE_MINGW_ANSI_STDIO) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(gnu_printf, string_idx, first_to_check))) +#elif \ + JSON_HEDLEY_HAS_ATTRIBUTE(format) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,6,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __attribute__((__format__(__printf__, string_idx, first_to_check))) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(6,0,0) + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) __declspec(vaformat(printf,string_idx,first_to_check)) +#else + #define JSON_HEDLEY_PRINTF_FORMAT(string_idx,first_to_check) +#endif + +#if defined(JSON_HEDLEY_CONSTEXPR) + #undef JSON_HEDLEY_CONSTEXPR +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_CONSTEXPR JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(constexpr) + #endif +#endif +#if !defined(JSON_HEDLEY_CONSTEXPR) + #define JSON_HEDLEY_CONSTEXPR +#endif + +#if defined(JSON_HEDLEY_PREDICT) + #undef JSON_HEDLEY_PREDICT +#endif +#if defined(JSON_HEDLEY_LIKELY) + #undef JSON_HEDLEY_LIKELY +#endif +#if defined(JSON_HEDLEY_UNLIKELY) + #undef JSON_HEDLEY_UNLIKELY +#endif +#if defined(JSON_HEDLEY_UNPREDICTABLE) + #undef JSON_HEDLEY_UNPREDICTABLE +#endif +#if JSON_HEDLEY_HAS_BUILTIN(__builtin_unpredictable) + #define JSON_HEDLEY_UNPREDICTABLE(expr) __builtin_unpredictable((expr)) +#endif +#if \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect_with_probability) && !defined(JSON_HEDLEY_PGI_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(9,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, value, probability) __builtin_expect_with_probability( (expr), (value), (probability)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) __builtin_expect_with_probability(!!(expr), 1 , (probability)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) __builtin_expect_with_probability(!!(expr), 0 , (probability)) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect (!!(expr), 1 ) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect (!!(expr), 0 ) +#elif \ + (JSON_HEDLEY_HAS_BUILTIN(__builtin_expect) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,15,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,7,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,27) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PREDICT(expr, expected, probability) \ + (((probability) >= 0.9) ? __builtin_expect((expr), (expected)) : (JSON_HEDLEY_STATIC_CAST(void, expected), (expr))) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 1) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 0) : !!(expr))); \ + })) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) \ + (__extension__ ({ \ + double hedley_probability_ = (probability); \ + ((hedley_probability_ >= 0.9) ? __builtin_expect(!!(expr), 0) : ((hedley_probability_ <= 0.1) ? __builtin_expect(!!(expr), 1) : !!(expr))); \ + })) +# define JSON_HEDLEY_LIKELY(expr) __builtin_expect(!!(expr), 1) +# define JSON_HEDLEY_UNLIKELY(expr) __builtin_expect(!!(expr), 0) +#else +# define JSON_HEDLEY_PREDICT(expr, expected, probability) (JSON_HEDLEY_STATIC_CAST(void, expected), (expr)) +# define JSON_HEDLEY_PREDICT_TRUE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_PREDICT_FALSE(expr, probability) (!!(expr)) +# define JSON_HEDLEY_LIKELY(expr) (!!(expr)) +# define JSON_HEDLEY_UNLIKELY(expr) (!!(expr)) +#endif +#if !defined(JSON_HEDLEY_UNPREDICTABLE) + #define JSON_HEDLEY_UNPREDICTABLE(expr) JSON_HEDLEY_PREDICT(expr, 1, 0.5) +#endif + +#if defined(JSON_HEDLEY_MALLOC) + #undef JSON_HEDLEY_MALLOC +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(malloc) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_MALLOC __attribute__((__malloc__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_MALLOC _Pragma("returns_new_memory") +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_MALLOC __declspec(restrict) +#else + #define JSON_HEDLEY_MALLOC +#endif + +#if defined(JSON_HEDLEY_PURE) + #undef JSON_HEDLEY_PURE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(pure) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,96,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PURE __attribute__((__pure__)) +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) +# define JSON_HEDLEY_PURE _Pragma("does_not_write_global_data") +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(2,0,1) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) \ + ) +# define JSON_HEDLEY_PURE _Pragma("FUNC_IS_PURE;") +#else +# define JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_CONST) + #undef JSON_HEDLEY_CONST +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(const) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(2,5,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_CONST __attribute__((__const__)) +#elif \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) + #define JSON_HEDLEY_CONST _Pragma("no_side_effect") +#else + #define JSON_HEDLEY_CONST JSON_HEDLEY_PURE +#endif + +#if defined(JSON_HEDLEY_RESTRICT) + #undef JSON_HEDLEY_RESTRICT +#endif +#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT restrict +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(14,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(17,10,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,4) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,14,0) && defined(__cplusplus)) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) || \ + defined(__clang__) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RESTRICT __restrict +#elif JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,3,0) && !defined(__cplusplus) + #define JSON_HEDLEY_RESTRICT _Restrict +#else + #define JSON_HEDLEY_RESTRICT +#endif + +#if defined(JSON_HEDLEY_INLINE) + #undef JSON_HEDLEY_INLINE +#endif +#if \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)) || \ + (defined(__cplusplus) && (__cplusplus >= 199711L)) + #define JSON_HEDLEY_INLINE inline +#elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(6,2,0) + #define JSON_HEDLEY_INLINE __inline__ +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,1,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(3,1,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,2,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(8,0,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_INLINE __inline +#else + #define JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_ALWAYS_INLINE) + #undef JSON_HEDLEY_ALWAYS_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(always_inline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) +# define JSON_HEDLEY_ALWAYS_INLINE __attribute__((__always_inline__)) JSON_HEDLEY_INLINE +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(12,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_ALWAYS_INLINE __forceinline +#elif defined(__cplusplus) && \ + ( \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) \ + ) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("FUNC_ALWAYS_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_ALWAYS_INLINE _Pragma("inline=forced") +#else +# define JSON_HEDLEY_ALWAYS_INLINE JSON_HEDLEY_INLINE +#endif + +#if defined(JSON_HEDLEY_NEVER_INLINE) + #undef JSON_HEDLEY_NEVER_INLINE +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(noinline) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(10,1,0) || \ + JSON_HEDLEY_TI_VERSION_CHECK(15,12,0) || \ + (JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(4,8,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_ARMCL_VERSION_CHECK(5,2,0) || \ + (JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL2000_VERSION_CHECK(6,4,0) || \ + (JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,0,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(4,3,0) || \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) || \ + JSON_HEDLEY_TI_CL7X_VERSION_CHECK(1,2,0) || \ + JSON_HEDLEY_TI_CLPRU_VERSION_CHECK(2,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) || \ + JSON_HEDLEY_IAR_VERSION_CHECK(8,10,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute__((__noinline__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,10,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#elif JSON_HEDLEY_PGI_VERSION_CHECK(10,2,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("noinline") +#elif JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,0,0) && defined(__cplusplus) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("FUNC_CANNOT_INLINE;") +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) + #define JSON_HEDLEY_NEVER_INLINE _Pragma("inline=never") +#elif JSON_HEDLEY_COMPCERT_VERSION_CHECK(3,2,0) + #define JSON_HEDLEY_NEVER_INLINE __attribute((noinline)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(9,0,0) + #define JSON_HEDLEY_NEVER_INLINE __declspec(noinline) +#else + #define JSON_HEDLEY_NEVER_INLINE +#endif + +#if defined(JSON_HEDLEY_PRIVATE) + #undef JSON_HEDLEY_PRIVATE +#endif +#if defined(JSON_HEDLEY_PUBLIC) + #undef JSON_HEDLEY_PUBLIC +#endif +#if defined(JSON_HEDLEY_IMPORT) + #undef JSON_HEDLEY_IMPORT +#endif +#if defined(_WIN32) || defined(__CYGWIN__) +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC __declspec(dllexport) +# define JSON_HEDLEY_IMPORT __declspec(dllimport) +#else +# if \ + JSON_HEDLEY_HAS_ATTRIBUTE(visibility) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,11,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + ( \ + defined(__TI_EABI__) && \ + ( \ + (JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,2,0) && defined(__TI_GNU_ATTRIBUTE_SUPPORT__)) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(7,5,0) \ + ) \ + ) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) +# define JSON_HEDLEY_PRIVATE __attribute__((__visibility__("hidden"))) +# define JSON_HEDLEY_PUBLIC __attribute__((__visibility__("default"))) +# else +# define JSON_HEDLEY_PRIVATE +# define JSON_HEDLEY_PUBLIC +# endif +# define JSON_HEDLEY_IMPORT extern +#endif + +#if defined(JSON_HEDLEY_NO_THROW) + #undef JSON_HEDLEY_NO_THROW +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(nothrow) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,3,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_NO_THROW __attribute__((__nothrow__)) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) + #define JSON_HEDLEY_NO_THROW __declspec(nothrow) +#else + #define JSON_HEDLEY_NO_THROW +#endif + +#if defined(JSON_HEDLEY_FALL_THROUGH) + #undef JSON_HEDLEY_FALL_THROUGH +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(fallthrough) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(7,0,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_FALL_THROUGH __attribute__((__fallthrough__)) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE_NS(clang,fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[clang::fallthrough]]) +#elif JSON_HEDLEY_HAS_CPP_ATTRIBUTE(fallthrough) + #define JSON_HEDLEY_FALL_THROUGH JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_([[fallthrough]]) +#elif defined(__fallthrough) /* SAL */ + #define JSON_HEDLEY_FALL_THROUGH __fallthrough +#else + #define JSON_HEDLEY_FALL_THROUGH +#endif + +#if defined(JSON_HEDLEY_RETURNS_NON_NULL) + #undef JSON_HEDLEY_RETURNS_NON_NULL +#endif +#if \ + JSON_HEDLEY_HAS_ATTRIBUTE(returns_nonnull) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_RETURNS_NON_NULL __attribute__((__returns_nonnull__)) +#elif defined(_Ret_notnull_) /* SAL */ + #define JSON_HEDLEY_RETURNS_NON_NULL _Ret_notnull_ +#else + #define JSON_HEDLEY_RETURNS_NON_NULL +#endif + +#if defined(JSON_HEDLEY_ARRAY_PARAM) + #undef JSON_HEDLEY_ARRAY_PARAM +#endif +#if \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L) && \ + !defined(__STDC_NO_VLA__) && \ + !defined(__cplusplus) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_TINYC_VERSION) + #define JSON_HEDLEY_ARRAY_PARAM(name) (name) +#else + #define JSON_HEDLEY_ARRAY_PARAM(name) +#endif + +#if defined(JSON_HEDLEY_IS_CONSTANT) + #undef JSON_HEDLEY_IS_CONSTANT +#endif +#if defined(JSON_HEDLEY_REQUIRE_CONSTEXPR) + #undef JSON_HEDLEY_REQUIRE_CONSTEXPR +#endif +/* JSON_HEDLEY_IS_CONSTEXPR_ is for + HEDLEY INTERNAL USE ONLY. API subject to change without notice. */ +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #undef JSON_HEDLEY_IS_CONSTEXPR_ +#endif +#if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_constant_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,19) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(4,1,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_TI_CL6X_VERSION_CHECK(6,1,0) || \ + (JSON_HEDLEY_SUNPRO_VERSION_CHECK(5,10,0) && !defined(__cplusplus)) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_MCST_LCC_VERSION_CHECK(1,25,10) + #define JSON_HEDLEY_IS_CONSTANT(expr) __builtin_constant_p(expr) +#endif +#if !defined(__cplusplus) +# if \ + JSON_HEDLEY_HAS_BUILTIN(__builtin_types_compatible_p) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(3,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(13,1,0) || \ + JSON_HEDLEY_CRAY_VERSION_CHECK(8,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,4,0) || \ + JSON_HEDLEY_TINYC_VERSION_CHECK(0,9,24) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0)), int*) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) __builtin_types_compatible_p(__typeof__((1 ? (void*) ((intptr_t) ((expr) * 0)) : (int*) 0)), int*) +#endif +# elif \ + ( \ + defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L) && \ + !defined(JSON_HEDLEY_SUNPRO_VERSION) && \ + !defined(JSON_HEDLEY_PGI_VERSION) && \ + !defined(JSON_HEDLEY_IAR_VERSION)) || \ + (JSON_HEDLEY_HAS_EXTENSION(c_generic_selections) && !defined(JSON_HEDLEY_IAR_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,9,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(17,0,0) || \ + JSON_HEDLEY_IBM_VERSION_CHECK(12,1,0) || \ + JSON_HEDLEY_ARM_VERSION_CHECK(5,3,0) +#if defined(__INTPTR_TYPE__) + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((__INTPTR_TYPE__) ((expr) * 0)) : (int*) 0), int*: 1, void*: 0) +#else + #include + #define JSON_HEDLEY_IS_CONSTEXPR_(expr) _Generic((1 ? (void*) ((intptr_t) * 0) : (int*) 0), int*: 1, void*: 0) +#endif +# elif \ + defined(JSON_HEDLEY_GCC_VERSION) || \ + defined(JSON_HEDLEY_INTEL_VERSION) || \ + defined(JSON_HEDLEY_TINYC_VERSION) || \ + defined(JSON_HEDLEY_TI_ARMCL_VERSION) || \ + JSON_HEDLEY_TI_CL430_VERSION_CHECK(18,12,0) || \ + defined(JSON_HEDLEY_TI_CL2000_VERSION) || \ + defined(JSON_HEDLEY_TI_CL6X_VERSION) || \ + defined(JSON_HEDLEY_TI_CL7X_VERSION) || \ + defined(JSON_HEDLEY_TI_CLPRU_VERSION) || \ + defined(__clang__) +# define JSON_HEDLEY_IS_CONSTEXPR_(expr) ( \ + sizeof(void) != \ + sizeof(*( \ + 1 ? \ + ((void*) ((expr) * 0L) ) : \ +((struct { char v[sizeof(void) * 2]; } *) 1) \ + ) \ + ) \ + ) +# endif +#endif +#if defined(JSON_HEDLEY_IS_CONSTEXPR_) + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) JSON_HEDLEY_IS_CONSTEXPR_(expr) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (JSON_HEDLEY_IS_CONSTEXPR_(expr) ? (expr) : (-1)) +#else + #if !defined(JSON_HEDLEY_IS_CONSTANT) + #define JSON_HEDLEY_IS_CONSTANT(expr) (0) + #endif + #define JSON_HEDLEY_REQUIRE_CONSTEXPR(expr) (expr) +#endif + +#if defined(JSON_HEDLEY_BEGIN_C_DECLS) + #undef JSON_HEDLEY_BEGIN_C_DECLS +#endif +#if defined(JSON_HEDLEY_END_C_DECLS) + #undef JSON_HEDLEY_END_C_DECLS +#endif +#if defined(JSON_HEDLEY_C_DECL) + #undef JSON_HEDLEY_C_DECL +#endif +#if defined(__cplusplus) + #define JSON_HEDLEY_BEGIN_C_DECLS extern "C" { + #define JSON_HEDLEY_END_C_DECLS } + #define JSON_HEDLEY_C_DECL extern "C" +#else + #define JSON_HEDLEY_BEGIN_C_DECLS + #define JSON_HEDLEY_END_C_DECLS + #define JSON_HEDLEY_C_DECL +#endif + +#if defined(JSON_HEDLEY_STATIC_ASSERT) + #undef JSON_HEDLEY_STATIC_ASSERT +#endif +#if \ + !defined(__cplusplus) && ( \ + (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)) || \ + (JSON_HEDLEY_HAS_FEATURE(c_static_assert) && !defined(JSON_HEDLEY_INTEL_CL_VERSION)) || \ + JSON_HEDLEY_GCC_VERSION_CHECK(6,0,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) || \ + defined(_Static_assert) \ + ) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) _Static_assert(expr, message) +#elif \ + (defined(__cplusplus) && (__cplusplus >= 201103L)) || \ + JSON_HEDLEY_MSVC_VERSION_CHECK(16,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(static_assert(expr, message)) +#else +# define JSON_HEDLEY_STATIC_ASSERT(expr, message) +#endif + +#if defined(JSON_HEDLEY_NULL) + #undef JSON_HEDLEY_NULL +#endif +#if defined(__cplusplus) + #if __cplusplus >= 201103L + #define JSON_HEDLEY_NULL JSON_HEDLEY_DIAGNOSTIC_DISABLE_CPP98_COMPAT_WRAP_(nullptr) + #elif defined(NULL) + #define JSON_HEDLEY_NULL NULL + #else + #define JSON_HEDLEY_NULL JSON_HEDLEY_STATIC_CAST(void*, 0) + #endif +#elif defined(NULL) + #define JSON_HEDLEY_NULL NULL +#else + #define JSON_HEDLEY_NULL ((void*) 0) +#endif + +#if defined(JSON_HEDLEY_MESSAGE) + #undef JSON_HEDLEY_MESSAGE +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_MESSAGE(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(message msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message msg) +#elif JSON_HEDLEY_CRAY_VERSION_CHECK(5,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(_CRI message msg) +#elif JSON_HEDLEY_IAR_VERSION_CHECK(8,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#elif JSON_HEDLEY_PELLES_VERSION_CHECK(2,0,0) +# define JSON_HEDLEY_MESSAGE(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_WARNING) + #undef JSON_HEDLEY_WARNING +#endif +#if JSON_HEDLEY_HAS_WARNING("-Wunknown-pragmas") +# define JSON_HEDLEY_WARNING(msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + JSON_HEDLEY_DIAGNOSTIC_DISABLE_UNKNOWN_PRAGMAS \ + JSON_HEDLEY_PRAGMA(clang warning msg) \ + JSON_HEDLEY_DIAGNOSTIC_POP +#elif \ + JSON_HEDLEY_GCC_VERSION_CHECK(4,8,0) || \ + JSON_HEDLEY_PGI_VERSION_CHECK(18,4,0) || \ + JSON_HEDLEY_INTEL_VERSION_CHECK(13,0,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(GCC warning msg) +#elif \ + JSON_HEDLEY_MSVC_VERSION_CHECK(15,0,0) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_PRAGMA(message(msg)) +#else +# define JSON_HEDLEY_WARNING(msg) JSON_HEDLEY_MESSAGE(msg) +#endif + +#if defined(JSON_HEDLEY_REQUIRE) + #undef JSON_HEDLEY_REQUIRE +#endif +#if defined(JSON_HEDLEY_REQUIRE_MSG) + #undef JSON_HEDLEY_REQUIRE_MSG +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(diagnose_if) +# if JSON_HEDLEY_HAS_WARNING("-Wgcc-compat") +# define JSON_HEDLEY_REQUIRE(expr) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), #expr, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("clang diagnostic ignored \"-Wgcc-compat\"") \ + __attribute__((diagnose_if(!(expr), msg, "error"))) \ + JSON_HEDLEY_DIAGNOSTIC_POP +# else +# define JSON_HEDLEY_REQUIRE(expr) __attribute__((diagnose_if(!(expr), #expr, "error"))) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) __attribute__((diagnose_if(!(expr), msg, "error"))) +# endif +#else +# define JSON_HEDLEY_REQUIRE(expr) +# define JSON_HEDLEY_REQUIRE_MSG(expr,msg) +#endif + +#if defined(JSON_HEDLEY_FLAGS) + #undef JSON_HEDLEY_FLAGS +#endif +#if JSON_HEDLEY_HAS_ATTRIBUTE(flag_enum) && (!defined(__cplusplus) || JSON_HEDLEY_HAS_WARNING("-Wbitfield-enum-conversion")) + #define JSON_HEDLEY_FLAGS __attribute__((__flag_enum__)) +#else + #define JSON_HEDLEY_FLAGS +#endif + +#if defined(JSON_HEDLEY_FLAGS_CAST) + #undef JSON_HEDLEY_FLAGS_CAST +#endif +#if JSON_HEDLEY_INTEL_VERSION_CHECK(19,0,0) +# define JSON_HEDLEY_FLAGS_CAST(T, expr) (__extension__ ({ \ + JSON_HEDLEY_DIAGNOSTIC_PUSH \ + _Pragma("warning(disable:188)") \ + ((T) (expr)); \ + JSON_HEDLEY_DIAGNOSTIC_POP \ + })) +#else +# define JSON_HEDLEY_FLAGS_CAST(T, expr) JSON_HEDLEY_STATIC_CAST(T, expr) +#endif + +#if defined(JSON_HEDLEY_EMPTY_BASES) + #undef JSON_HEDLEY_EMPTY_BASES +#endif +#if \ + (JSON_HEDLEY_MSVC_VERSION_CHECK(19,0,23918) && !JSON_HEDLEY_MSVC_VERSION_CHECK(20,0,0)) || \ + JSON_HEDLEY_INTEL_CL_VERSION_CHECK(2021,1,0) + #define JSON_HEDLEY_EMPTY_BASES __declspec(empty_bases) +#else + #define JSON_HEDLEY_EMPTY_BASES +#endif + +/* Remaining macros are deprecated. */ + +#if defined(JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK) + #undef JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK +#endif +#if defined(__clang__) + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) (0) +#else + #define JSON_HEDLEY_GCC_NOT_CLANG_VERSION_CHECK(major,minor,patch) JSON_HEDLEY_GCC_VERSION_CHECK(major,minor,patch) +#endif + +#if defined(JSON_HEDLEY_CLANG_HAS_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_CPP_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_CPP_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_BUILTIN) + #undef JSON_HEDLEY_CLANG_HAS_BUILTIN +#endif +#define JSON_HEDLEY_CLANG_HAS_BUILTIN(builtin) JSON_HEDLEY_HAS_BUILTIN(builtin) + +#if defined(JSON_HEDLEY_CLANG_HAS_FEATURE) + #undef JSON_HEDLEY_CLANG_HAS_FEATURE +#endif +#define JSON_HEDLEY_CLANG_HAS_FEATURE(feature) JSON_HEDLEY_HAS_FEATURE(feature) + +#if defined(JSON_HEDLEY_CLANG_HAS_EXTENSION) + #undef JSON_HEDLEY_CLANG_HAS_EXTENSION +#endif +#define JSON_HEDLEY_CLANG_HAS_EXTENSION(extension) JSON_HEDLEY_HAS_EXTENSION(extension) + +#if defined(JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE) + #undef JSON_HEDLEY_CLANG_HAS_DECLSPEC_DECLSPEC_ATTRIBUTE +#endif +#define JSON_HEDLEY_CLANG_HAS_DECLSPEC_ATTRIBUTE(attribute) JSON_HEDLEY_HAS_DECLSPEC_ATTRIBUTE(attribute) + +#if defined(JSON_HEDLEY_CLANG_HAS_WARNING) + #undef JSON_HEDLEY_CLANG_HAS_WARNING +#endif +#define JSON_HEDLEY_CLANG_HAS_WARNING(warning) JSON_HEDLEY_HAS_WARNING(warning) + +#endif /* !defined(JSON_HEDLEY_VERSION) || (JSON_HEDLEY_VERSION < X) */ + + +// This file contains all internal macro definitions (except those affecting ABI) +// You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them + +// #include + + +// exclude unsupported compilers +#if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) + #if defined(__clang__) + #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 + #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) + #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 + #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" + #endif + #endif +#endif + +// C++ language standard detection +// if the user manually specified the used c++ version this is skipped +#if !defined(JSON_HAS_CPP_20) && !defined(JSON_HAS_CPP_17) && !defined(JSON_HAS_CPP_14) && !defined(JSON_HAS_CPP_11) + #if (defined(__cplusplus) && __cplusplus >= 202002L) || (defined(_MSVC_LANG) && _MSVC_LANG >= 202002L) + #define JSON_HAS_CPP_20 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 + #define JSON_HAS_CPP_17 + #define JSON_HAS_CPP_14 + #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) + #define JSON_HAS_CPP_14 + #endif + // the cpp 11 flag is always specified because it is the minimal required version + #define JSON_HAS_CPP_11 +#endif + +#ifdef __has_include + #if __has_include() + #include + #endif +#endif + +#if !defined(JSON_HAS_FILESYSTEM) && !defined(JSON_HAS_EXPERIMENTAL_FILESYSTEM) + #ifdef JSON_HAS_CPP_17 + #if defined(__cpp_lib_filesystem) + #define JSON_HAS_FILESYSTEM 1 + #elif defined(__cpp_lib_experimental_filesystem) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif !defined(__has_include) + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_FILESYSTEM 1 + #elif __has_include() + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 1 + #endif + + // std::filesystem does not work on MinGW GCC 8: https://sourceforge.net/p/mingw-w64/bugs/737/ + #if defined(__MINGW32__) && defined(__GNUC__) && __GNUC__ == 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before GCC 8: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__GNUC__) && !defined(__clang__) && __GNUC__ < 8 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before Clang 7: https://en.cppreference.com/w/cpp/compiler_support + #if defined(__clang_major__) && __clang_major__ < 7 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before MSVC 19.14: https://en.cppreference.com/w/cpp/compiler_support + #if defined(_MSC_VER) && _MSC_VER < 1914 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before iOS 13 + #if defined(__IPHONE_OS_VERSION_MIN_REQUIRED) && __IPHONE_OS_VERSION_MIN_REQUIRED < 130000 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + + // no filesystem support before macOS Catalina + #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED < 101500 + #undef JSON_HAS_FILESYSTEM + #undef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #endif + #endif +#endif + +#ifndef JSON_HAS_EXPERIMENTAL_FILESYSTEM + #define JSON_HAS_EXPERIMENTAL_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_FILESYSTEM + #define JSON_HAS_FILESYSTEM 0 +#endif + +#ifndef JSON_HAS_THREE_WAY_COMPARISON + #if defined(__cpp_impl_three_way_comparison) && __cpp_impl_three_way_comparison >= 201907L \ + && defined(__cpp_lib_three_way_comparison) && __cpp_lib_three_way_comparison >= 201907L + #define JSON_HAS_THREE_WAY_COMPARISON 1 + #else + #define JSON_HAS_THREE_WAY_COMPARISON 0 + #endif +#endif + +#ifndef JSON_HAS_RANGES + // ranges header shipping in GCC 11.1.0 (released 2021-04-27) has syntax error + #if defined(__GLIBCXX__) && __GLIBCXX__ == 20210427 + #define JSON_HAS_RANGES 0 + #elif defined(__cpp_lib_ranges) + #define JSON_HAS_RANGES 1 + #else + #define JSON_HAS_RANGES 0 + #endif +#endif + +#ifdef JSON_HAS_CPP_17 + #define JSON_INLINE_VARIABLE inline +#else + #define JSON_INLINE_VARIABLE +#endif + +#if JSON_HEDLEY_HAS_ATTRIBUTE(no_unique_address) + #define JSON_NO_UNIQUE_ADDRESS [[no_unique_address]] +#else + #define JSON_NO_UNIQUE_ADDRESS +#endif + +// disable documentation warnings on clang +#if defined(__clang__) + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wdocumentation" + #pragma clang diagnostic ignored "-Wdocumentation-unknown-command" +#endif + +// allow disabling exceptions +#if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) + #define JSON_THROW(exception) throw exception + #define JSON_TRY try + #define JSON_CATCH(exception) catch(exception) + #define JSON_INTERNAL_CATCH(exception) catch(exception) +#else + #include + #define JSON_THROW(exception) std::abort() + #define JSON_TRY if(true) + #define JSON_CATCH(exception) if(false) + #define JSON_INTERNAL_CATCH(exception) if(false) +#endif + +// override exception macros +#if defined(JSON_THROW_USER) + #undef JSON_THROW + #define JSON_THROW JSON_THROW_USER +#endif +#if defined(JSON_TRY_USER) + #undef JSON_TRY + #define JSON_TRY JSON_TRY_USER +#endif +#if defined(JSON_CATCH_USER) + #undef JSON_CATCH + #define JSON_CATCH JSON_CATCH_USER + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_CATCH_USER +#endif +#if defined(JSON_INTERNAL_CATCH_USER) + #undef JSON_INTERNAL_CATCH + #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER +#endif + +// allow overriding assert +#if !defined(JSON_ASSERT) + #include // assert + #define JSON_ASSERT(x) assert(x) +#endif + +// allow to access some private functions (needed by the test suite) +#if defined(JSON_TESTS_PRIVATE) + #define JSON_PRIVATE_UNLESS_TESTED public +#else + #define JSON_PRIVATE_UNLESS_TESTED private +#endif + +/*! +@brief macro to briefly define a mapping between an enum and JSON +@def NLOHMANN_JSON_SERIALIZE_ENUM +@since version 3.4.0 +*/ +#define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ + template \ + inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [e](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.first == e; \ + }); \ + j = ((it != std::end(m)) ? it : std::begin(m))->second; \ + } \ + template \ + inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ + { \ + static_assert(std::is_enum::value, #ENUM_TYPE " must be an enum!"); \ + static const std::pair m[] = __VA_ARGS__; \ + auto it = std::find_if(std::begin(m), std::end(m), \ + [&j](const std::pair& ej_pair) -> bool \ + { \ + return ej_pair.second == j; \ + }); \ + e = ((it != std::end(m)) ? it : std::begin(m))->first; \ + } + +// Ugly macros to avoid uglier copy-paste when specializing basic_json. They +// may be removed in the future once the class is split. + +#define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ + template class ObjectType, \ + template class ArrayType, \ + class StringType, class BooleanType, class NumberIntegerType, \ + class NumberUnsignedType, class NumberFloatType, \ + template class AllocatorType, \ + template class JSONSerializer, \ + class BinaryType> + +#define NLOHMANN_BASIC_JSON_TPL \ + basic_json + +// Macros to simplify conversion from/to types + +#define NLOHMANN_JSON_EXPAND( x ) x +#define NLOHMANN_JSON_GET_MACRO(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, _29, _30, _31, _32, _33, _34, _35, _36, _37, _38, _39, _40, _41, _42, _43, _44, _45, _46, _47, _48, _49, _50, _51, _52, _53, _54, _55, _56, _57, _58, _59, _60, _61, _62, _63, _64, NAME,...) NAME +#define NLOHMANN_JSON_PASTE(...) NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_GET_MACRO(__VA_ARGS__, \ + NLOHMANN_JSON_PASTE64, \ + NLOHMANN_JSON_PASTE63, \ + NLOHMANN_JSON_PASTE62, \ + NLOHMANN_JSON_PASTE61, \ + NLOHMANN_JSON_PASTE60, \ + NLOHMANN_JSON_PASTE59, \ + NLOHMANN_JSON_PASTE58, \ + NLOHMANN_JSON_PASTE57, \ + NLOHMANN_JSON_PASTE56, \ + NLOHMANN_JSON_PASTE55, \ + NLOHMANN_JSON_PASTE54, \ + NLOHMANN_JSON_PASTE53, \ + NLOHMANN_JSON_PASTE52, \ + NLOHMANN_JSON_PASTE51, \ + NLOHMANN_JSON_PASTE50, \ + NLOHMANN_JSON_PASTE49, \ + NLOHMANN_JSON_PASTE48, \ + NLOHMANN_JSON_PASTE47, \ + NLOHMANN_JSON_PASTE46, \ + NLOHMANN_JSON_PASTE45, \ + NLOHMANN_JSON_PASTE44, \ + NLOHMANN_JSON_PASTE43, \ + NLOHMANN_JSON_PASTE42, \ + NLOHMANN_JSON_PASTE41, \ + NLOHMANN_JSON_PASTE40, \ + NLOHMANN_JSON_PASTE39, \ + NLOHMANN_JSON_PASTE38, \ + NLOHMANN_JSON_PASTE37, \ + NLOHMANN_JSON_PASTE36, \ + NLOHMANN_JSON_PASTE35, \ + NLOHMANN_JSON_PASTE34, \ + NLOHMANN_JSON_PASTE33, \ + NLOHMANN_JSON_PASTE32, \ + NLOHMANN_JSON_PASTE31, \ + NLOHMANN_JSON_PASTE30, \ + NLOHMANN_JSON_PASTE29, \ + NLOHMANN_JSON_PASTE28, \ + NLOHMANN_JSON_PASTE27, \ + NLOHMANN_JSON_PASTE26, \ + NLOHMANN_JSON_PASTE25, \ + NLOHMANN_JSON_PASTE24, \ + NLOHMANN_JSON_PASTE23, \ + NLOHMANN_JSON_PASTE22, \ + NLOHMANN_JSON_PASTE21, \ + NLOHMANN_JSON_PASTE20, \ + NLOHMANN_JSON_PASTE19, \ + NLOHMANN_JSON_PASTE18, \ + NLOHMANN_JSON_PASTE17, \ + NLOHMANN_JSON_PASTE16, \ + NLOHMANN_JSON_PASTE15, \ + NLOHMANN_JSON_PASTE14, \ + NLOHMANN_JSON_PASTE13, \ + NLOHMANN_JSON_PASTE12, \ + NLOHMANN_JSON_PASTE11, \ + NLOHMANN_JSON_PASTE10, \ + NLOHMANN_JSON_PASTE9, \ + NLOHMANN_JSON_PASTE8, \ + NLOHMANN_JSON_PASTE7, \ + NLOHMANN_JSON_PASTE6, \ + NLOHMANN_JSON_PASTE5, \ + NLOHMANN_JSON_PASTE4, \ + NLOHMANN_JSON_PASTE3, \ + NLOHMANN_JSON_PASTE2, \ + NLOHMANN_JSON_PASTE1)(__VA_ARGS__)) +#define NLOHMANN_JSON_PASTE2(func, v1) func(v1) +#define NLOHMANN_JSON_PASTE3(func, v1, v2) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE2(func, v2) +#define NLOHMANN_JSON_PASTE4(func, v1, v2, v3) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE3(func, v2, v3) +#define NLOHMANN_JSON_PASTE5(func, v1, v2, v3, v4) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE4(func, v2, v3, v4) +#define NLOHMANN_JSON_PASTE6(func, v1, v2, v3, v4, v5) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE5(func, v2, v3, v4, v5) +#define NLOHMANN_JSON_PASTE7(func, v1, v2, v3, v4, v5, v6) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE6(func, v2, v3, v4, v5, v6) +#define NLOHMANN_JSON_PASTE8(func, v1, v2, v3, v4, v5, v6, v7) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE7(func, v2, v3, v4, v5, v6, v7) +#define NLOHMANN_JSON_PASTE9(func, v1, v2, v3, v4, v5, v6, v7, v8) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE8(func, v2, v3, v4, v5, v6, v7, v8) +#define NLOHMANN_JSON_PASTE10(func, v1, v2, v3, v4, v5, v6, v7, v8, v9) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE9(func, v2, v3, v4, v5, v6, v7, v8, v9) +#define NLOHMANN_JSON_PASTE11(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE10(func, v2, v3, v4, v5, v6, v7, v8, v9, v10) +#define NLOHMANN_JSON_PASTE12(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE11(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11) +#define NLOHMANN_JSON_PASTE13(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE12(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12) +#define NLOHMANN_JSON_PASTE14(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE13(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13) +#define NLOHMANN_JSON_PASTE15(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE14(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14) +#define NLOHMANN_JSON_PASTE16(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE15(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15) +#define NLOHMANN_JSON_PASTE17(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE16(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16) +#define NLOHMANN_JSON_PASTE18(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE17(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17) +#define NLOHMANN_JSON_PASTE19(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE18(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18) +#define NLOHMANN_JSON_PASTE20(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE19(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19) +#define NLOHMANN_JSON_PASTE21(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE20(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20) +#define NLOHMANN_JSON_PASTE22(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE21(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21) +#define NLOHMANN_JSON_PASTE23(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE22(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22) +#define NLOHMANN_JSON_PASTE24(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE23(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23) +#define NLOHMANN_JSON_PASTE25(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE24(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24) +#define NLOHMANN_JSON_PASTE26(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE25(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25) +#define NLOHMANN_JSON_PASTE27(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE26(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26) +#define NLOHMANN_JSON_PASTE28(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE27(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27) +#define NLOHMANN_JSON_PASTE29(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE28(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28) +#define NLOHMANN_JSON_PASTE30(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE29(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29) +#define NLOHMANN_JSON_PASTE31(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE30(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30) +#define NLOHMANN_JSON_PASTE32(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE31(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31) +#define NLOHMANN_JSON_PASTE33(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE32(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32) +#define NLOHMANN_JSON_PASTE34(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE33(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33) +#define NLOHMANN_JSON_PASTE35(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE34(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34) +#define NLOHMANN_JSON_PASTE36(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE35(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35) +#define NLOHMANN_JSON_PASTE37(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE36(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36) +#define NLOHMANN_JSON_PASTE38(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE37(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37) +#define NLOHMANN_JSON_PASTE39(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE38(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38) +#define NLOHMANN_JSON_PASTE40(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE39(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39) +#define NLOHMANN_JSON_PASTE41(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE40(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40) +#define NLOHMANN_JSON_PASTE42(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE41(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41) +#define NLOHMANN_JSON_PASTE43(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE42(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42) +#define NLOHMANN_JSON_PASTE44(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE43(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43) +#define NLOHMANN_JSON_PASTE45(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE44(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44) +#define NLOHMANN_JSON_PASTE46(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE45(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45) +#define NLOHMANN_JSON_PASTE47(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE46(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46) +#define NLOHMANN_JSON_PASTE48(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE47(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47) +#define NLOHMANN_JSON_PASTE49(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE48(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48) +#define NLOHMANN_JSON_PASTE50(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE49(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49) +#define NLOHMANN_JSON_PASTE51(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE50(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50) +#define NLOHMANN_JSON_PASTE52(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE51(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51) +#define NLOHMANN_JSON_PASTE53(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE52(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52) +#define NLOHMANN_JSON_PASTE54(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE53(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53) +#define NLOHMANN_JSON_PASTE55(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE54(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54) +#define NLOHMANN_JSON_PASTE56(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE55(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55) +#define NLOHMANN_JSON_PASTE57(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE56(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56) +#define NLOHMANN_JSON_PASTE58(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE57(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57) +#define NLOHMANN_JSON_PASTE59(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE58(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58) +#define NLOHMANN_JSON_PASTE60(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE59(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59) +#define NLOHMANN_JSON_PASTE61(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE60(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60) +#define NLOHMANN_JSON_PASTE62(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE61(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61) +#define NLOHMANN_JSON_PASTE63(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE62(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62) +#define NLOHMANN_JSON_PASTE64(func, v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) NLOHMANN_JSON_PASTE2(func, v1) NLOHMANN_JSON_PASTE63(func, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36, v37, v38, v39, v40, v41, v42, v43, v44, v45, v46, v47, v48, v49, v50, v51, v52, v53, v54, v55, v56, v57, v58, v59, v60, v61, v62, v63) + +#define NLOHMANN_JSON_TO(v1) nlohmann_json_j[#v1] = nlohmann_json_t.v1; +#define NLOHMANN_JSON_FROM(v1) nlohmann_json_j.at(#v1).get_to(nlohmann_json_t.v1); +#define NLOHMANN_JSON_FROM_WITH_DEFAULT(v1) nlohmann_json_t.v1 = nlohmann_json_j.value(#v1, nlohmann_json_default_obj.v1); + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + friend void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + friend void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { Type nlohmann_json_default_obj; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + +/*! +@brief macro +@def NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE +@since version 3.9.0 +*/ +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM, __VA_ARGS__)) } + +#define NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE_WITH_DEFAULT(Type, ...) \ + inline void to_json(nlohmann::json& nlohmann_json_j, const Type& nlohmann_json_t) { NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_TO, __VA_ARGS__)) } \ + inline void from_json(const nlohmann::json& nlohmann_json_j, Type& nlohmann_json_t) { Type nlohmann_json_default_obj; NLOHMANN_JSON_EXPAND(NLOHMANN_JSON_PASTE(NLOHMANN_JSON_FROM_WITH_DEFAULT, __VA_ARGS__)) } + + +// inspired from https://stackoverflow.com/a/26745591 +// allows to call any std function as if (e.g. with begin): +// using std::begin; begin(x); +// +// it allows using the detected idiom to retrieve the return type +// of such an expression +#define NLOHMANN_CAN_CALL_STD_FUNC_IMPL(std_name) \ + namespace detail { \ + using std::std_name; \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + } \ + \ + namespace detail2 { \ + struct std_name##_tag \ + { \ + }; \ + \ + template \ + std_name##_tag std_name(T&&...); \ + \ + template \ + using result_of_##std_name = decltype(std_name(std::declval()...)); \ + \ + template \ + struct would_call_std_##std_name \ + { \ + static constexpr auto const value = ::nlohmann::detail:: \ + is_detected_exact::value; \ + }; \ + } /* namespace detail2 */ \ + \ + template \ + struct would_call_std_##std_name : detail2::would_call_std_##std_name \ + { \ + } + +#ifndef JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_USE_IMPLICIT_CONVERSIONS 1 +#endif + +#if JSON_USE_IMPLICIT_CONVERSIONS + #define JSON_EXPLICIT +#else + #define JSON_EXPLICIT explicit +#endif + +#ifndef JSON_DISABLE_ENUM_SERIALIZATION + #define JSON_DISABLE_ENUM_SERIALIZATION 0 +#endif + +#ifndef JSON_USE_GLOBAL_UDLS + #define JSON_USE_GLOBAL_UDLS 1 +#endif + +#if JSON_HAS_THREE_WAY_COMPARISON + #include // partial_ordering +#endif + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/////////////////////////// +// JSON type enumeration // +/////////////////////////// + +/*! +@brief the JSON type enumeration + +This enumeration collects the different JSON types. It is internally used to +distinguish the stored values, and the functions @ref basic_json::is_null(), +@ref basic_json::is_object(), @ref basic_json::is_array(), +@ref basic_json::is_string(), @ref basic_json::is_boolean(), +@ref basic_json::is_number() (with @ref basic_json::is_number_integer(), +@ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), +@ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and +@ref basic_json::is_structured() rely on it. + +@note There are three enumeration entries (number_integer, number_unsigned, and +number_float), because the library distinguishes these three types for numbers: +@ref basic_json::number_unsigned_t is used for unsigned integers, +@ref basic_json::number_integer_t is used for signed integers, and +@ref basic_json::number_float_t is used for floating-point numbers or to +approximate integers which do not fit in the limits of their respective type. + +@sa see @ref basic_json::basic_json(const value_t value_type) -- create a JSON +value with the default value for a given type + +@since version 1.0.0 +*/ +enum class value_t : std::uint8_t +{ + null, ///< null value + object, ///< object (unordered set of name/value pairs) + array, ///< array (ordered collection of values) + string, ///< string value + boolean, ///< boolean value + number_integer, ///< number value (signed integer) + number_unsigned, ///< number value (unsigned integer) + number_float, ///< number value (floating-point) + binary, ///< binary array (ordered collection of bytes) + discarded ///< discarded by the parser callback function +}; + +/*! +@brief comparison operator for JSON types + +Returns an ordering that is similar to Python: +- order: null < boolean < number < object < array < string < binary +- furthermore, each type is not smaller than itself +- discarded values are not comparable +- binary is represented as a b"" string in python and directly comparable to a + string; however, making a binary array directly comparable with a string would + be surprising behavior in a JSON file. + +@since version 1.0.0 +*/ +#if JSON_HAS_THREE_WAY_COMPARISON + inline std::partial_ordering operator<=>(const value_t lhs, const value_t rhs) noexcept // *NOPAD* +#else + inline bool operator<(const value_t lhs, const value_t rhs) noexcept +#endif +{ + static constexpr std::array order = {{ + 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, + 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */, + 6 /* binary */ + } + }; + + const auto l_index = static_cast(lhs); + const auto r_index = static_cast(rhs); +#if JSON_HAS_THREE_WAY_COMPARISON + if (l_index < order.size() && r_index < order.size()) + { + return order[l_index] <=> order[r_index]; // *NOPAD* + } + return std::partial_ordering::unordered; +#else + return l_index < order.size() && r_index < order.size() && order[l_index] < order[r_index]; +#endif +} + +// GCC selects the built-in operator< over an operator rewritten from +// a user-defined spaceship operator +// Clang, MSVC, and ICC select the rewritten candidate +// (see GCC bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=105200) +#if JSON_HAS_THREE_WAY_COMPARISON && defined(__GNUC__) +inline bool operator<(const value_t lhs, const value_t rhs) noexcept +{ + return std::is_lt(lhs <=> rhs); // *NOPAD* +} +#endif + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/*! +@brief replace all occurrences of a substring by another string + +@param[in,out] s the string to manipulate; changed so that all + occurrences of @a f are replaced with @a t +@param[in] f the substring to replace with @a t +@param[in] t the string to replace @a f + +@pre The search string @a f must not be empty. **This precondition is +enforced with an assertion.** + +@since version 2.0.0 +*/ +template +inline void replace_substring(StringType& s, const StringType& f, + const StringType& t) +{ + JSON_ASSERT(!f.empty()); + for (auto pos = s.find(f); // find first occurrence of f + pos != StringType::npos; // make sure f was found + s.replace(pos, f.size(), t), // replace with t, and + pos = s.find(f, pos + t.size())) // find next occurrence of f + {} +} + +/*! + * @brief string escaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to escape + * @return escaped string + * + * Note the order of escaping "~" to "~0" and "/" to "~1" is important. + */ +template +inline StringType escape(StringType s) +{ + replace_substring(s, StringType{"~"}, StringType{"~0"}); + replace_substring(s, StringType{"/"}, StringType{"~1"}); + return s; +} + +/*! + * @brief string unescaping as described in RFC 6901 (Sect. 4) + * @param[in] s string to unescape + * @return unescaped string + * + * Note the order of escaping "~1" to "/" and "~0" to "~" is important. + */ +template +static void unescape(StringType& s) +{ + replace_substring(s, StringType{"~1"}, StringType{"/"}); + replace_substring(s, StringType{"~0"}, StringType{"~"}); +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // size_t + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +/// struct to capture the start position of the current token +struct position_t +{ + /// the total number of characters read + std::size_t chars_read_total = 0; + /// the number of characters read in the current line + std::size_t chars_read_current_line = 0; + /// the number of lines read + std::size_t lines_read = 0; + + /// conversion to size_t to preserve SAX interface + constexpr operator size_t() const + { + return chars_read_total; + } +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-FileCopyrightText: 2018 The Abseil Authors +// SPDX-License-Identifier: MIT + + + +#include // array +#include // size_t +#include // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type +#include // index_sequence, make_index_sequence, index_sequence_for + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +using uncvref_t = typename std::remove_cv::type>::type; + +#ifdef JSON_HAS_CPP_14 + +// the following utilities are natively available in C++14 +using std::enable_if_t; +using std::index_sequence; +using std::make_index_sequence; +using std::index_sequence_for; + +#else + +// alias templates to reduce boilerplate +template +using enable_if_t = typename std::enable_if::type; + +// The following code is taken from https://github.com/abseil/abseil-cpp/blob/10cb35e459f5ecca5b2ff107635da0bfa41011b4/absl/utility/utility.h +// which is part of Google Abseil (https://github.com/abseil/abseil-cpp), licensed under the Apache License 2.0. + +//// START OF CODE FROM GOOGLE ABSEIL + +// integer_sequence +// +// Class template representing a compile-time integer sequence. An instantiation +// of `integer_sequence` has a sequence of integers encoded in its +// type through its template arguments (which is a common need when +// working with C++11 variadic templates). `absl::integer_sequence` is designed +// to be a drop-in replacement for C++14's `std::integer_sequence`. +// +// Example: +// +// template< class T, T... Ints > +// void user_function(integer_sequence); +// +// int main() +// { +// // user_function's `T` will be deduced to `int` and `Ints...` +// // will be deduced to `0, 1, 2, 3, 4`. +// user_function(make_integer_sequence()); +// } +template +struct integer_sequence +{ + using value_type = T; + static constexpr std::size_t size() noexcept + { + return sizeof...(Ints); + } +}; + +// index_sequence +// +// A helper template for an `integer_sequence` of `size_t`, +// `absl::index_sequence` is designed to be a drop-in replacement for C++14's +// `std::index_sequence`. +template +using index_sequence = integer_sequence; + +namespace utility_internal +{ + +template +struct Extend; + +// Note that SeqSize == sizeof...(Ints). It's passed explicitly for efficiency. +template +struct Extend, SeqSize, 0> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)... >; +}; + +template +struct Extend, SeqSize, 1> +{ + using type = integer_sequence < T, Ints..., (Ints + SeqSize)..., 2 * SeqSize >; +}; + +// Recursion helper for 'make_integer_sequence'. +// 'Gen::type' is an alias for 'integer_sequence'. +template +struct Gen +{ + using type = + typename Extend < typename Gen < T, N / 2 >::type, N / 2, N % 2 >::type; +}; + +template +struct Gen +{ + using type = integer_sequence; +}; + +} // namespace utility_internal + +// Compile-time sequences of integers + +// make_integer_sequence +// +// This template alias is equivalent to +// `integer_sequence`, and is designed to be a drop-in +// replacement for C++14's `std::make_integer_sequence`. +template +using make_integer_sequence = typename utility_internal::Gen::type; + +// make_index_sequence +// +// This template alias is equivalent to `index_sequence<0, 1, ..., N-1>`, +// and is designed to be a drop-in replacement for C++14's +// `std::make_index_sequence`. +template +using make_index_sequence = make_integer_sequence; + +// index_sequence_for +// +// Converts a typename pack into an index sequence of the same length, and +// is designed to be a drop-in replacement for C++14's +// `std::index_sequence_for()` +template +using index_sequence_for = make_index_sequence; + +//// END OF CODE FROM GOOGLE ABSEIL + +#endif + +// dispatch utility (taken from ranges-v3) +template struct priority_tag : priority_tag < N - 1 > {}; +template<> struct priority_tag<0> {}; + +// taken from ranges-v3 +template +struct static_const +{ + static JSON_INLINE_VARIABLE constexpr T value{}; +}; + +#ifndef JSON_HAS_CPP_17 + template + constexpr T static_const::value; +#endif + +template +inline constexpr std::array make_array(Args&& ... args) +{ + return std::array {{static_cast(std::forward(args))...}}; +} + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // numeric_limits +#include // false_type, is_constructible, is_integral, is_same, true_type +#include // declval +#include // tuple + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +#include // random_access_iterator_tag + +// #include + +// #include + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN +namespace detail +{ + +template +struct iterator_types {}; + +template +struct iterator_types < + It, + void_t> +{ + using difference_type = typename It::difference_type; + using value_type = typename It::value_type; + using pointer = typename It::pointer; + using reference = typename It::reference; + using iterator_category = typename It::iterator_category; +}; + +// This is required as some compilers implement std::iterator_traits in a way that +// doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. +template +struct iterator_traits +{ +}; + +template +struct iterator_traits < T, enable_if_t < !std::is_pointer::value >> + : iterator_types +{ +}; + +template +struct iterator_traits::value>> +{ + using iterator_category = std::random_access_iterator_tag; + using value_type = T; + using difference_type = ptrdiff_t; + using pointer = T*; + using reference = T&; +}; + +} // namespace detail +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(begin); + +NLOHMANN_JSON_NAMESPACE_END + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + + + +// #include + + +NLOHMANN_JSON_NAMESPACE_BEGIN + +NLOHMANN_CAN_CALL_STD_FUNC_IMPL(end); + +NLOHMANN_JSON_NAMESPACE_END + +// #include + +// #include + +// #include +// __ _____ _____ _____ +// __| | __| | | | JSON for Modern C++ +// | | |__ | | | | | | version 3.11.2 +// |_____|_____|_____|_|___| https://github.com/nlohmann/json +// +// SPDX-FileCopyrightText: 2013-2022 Niels Lohmann +// SPDX-License-Identifier: MIT + +#ifndef INCLUDE_NLOHMANN_JSON_FWD_HPP_ + #define INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + #include // int64_t, uint64_t + #include // map + #include // allocator + #include // string + #include // vector + + // #include + + + /*! + @brief namespace for Niels Lohmann + @see https://github.com/nlohmann + @since version 1.0.0 + */ + NLOHMANN_JSON_NAMESPACE_BEGIN + + /*! + @brief default JSONSerializer template argument + + This serializer ignores the template arguments and uses ADL + ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) + for serialization. + */ + template + struct adl_serializer; + + /// a class to store JSON values + /// @sa https://json.nlohmann.me/api/basic_json/ + template class ObjectType = + std::map, + template class ArrayType = std::vector, + class StringType = std::string, class BooleanType = bool, + class NumberIntegerType = std::int64_t, + class NumberUnsignedType = std::uint64_t, + class NumberFloatType = double, + template class AllocatorType = std::allocator, + template class JSONSerializer = + adl_serializer, + class BinaryType = std::vector> + class basic_json; + + /// @brief JSON Pointer defines a string syntax for identifying a specific value within a JSON document + /// @sa https://json.nlohmann.me/api/json_pointer/ + template + class json_pointer; + + /*! + @brief default specialization + @sa https://json.nlohmann.me/api/json/ + */ + using json = basic_json<>; + + /// @brief a minimal map-like container that preserves insertion order + /// @sa https://json.nlohmann.me/api/ordered_map/ + template + struct ordered_map; + + /// @brief specialization that maintains the insertion order of object keys + /// @sa https://json.nlohmann.me/api/ordered_json/ + using ordered_json = basic_json; + + NLOHMANN_JSON_NAMESPACE_END + +#endif // INCLUDE_NLOHMANN_JSON_FWD_HPP_ + + +NLOHMANN_JSON_NAMESPACE_BEGIN +/*! +@brief detail namespace with internal helper functions + +This namespace collects functions that should not be exposed, +implementations of some @ref basic_json methods, and meta-programming helpers. + +@since version 2.1.0 +*/ +namespace detail +{ + +///////////// +// helpers // +///////////// + +// Note to maintainers: +// +// Every trait in this file expects a non CV-qualified type. +// The only exceptions are in the 'aliases for detected' section +// (i.e. those of the form: decltype(T::member_function(std::declval()))) +// +// In this case, T has to be properly CV-qualified to constraint the function arguments +// (e.g. to_json(BasicJsonType&, const T&)) + +template struct is_basic_json : std::false_type {}; + +NLOHMANN_BASIC_JSON_TPL_DECLARATION +struct is_basic_json : std::true_type {}; + +// used by exceptions create() member functions +// true_type for pointer to possibly cv-qualified basic_json or std::nullptr_t +// false_type otherwise +template +struct is_basic_json_context : + std::integral_constant < bool, + is_basic_json::type>::type>::value + || std::is_same::value > +{}; + +////////////////////// +// json_ref helpers // +////////////////////// + +template +class json_ref; + +template +struct is_json_ref : std::false_type {}; + +template +struct is_json_ref> : std::true_type {}; + +////////////////////////// +// aliases for detected // +////////////////////////// + +template +using mapped_type_t = typename T::mapped_type; + +template +using key_type_t = typename T::key_type; + +template +using value_type_t = typename T::value_type; + +template +using difference_type_t = typename T::difference_type; + +template +using pointer_t = typename T::pointer; + +template +using reference_t = typename T::reference; + +template +using iterator_category_t = typename T::iterator_category; + +template +using to_json_function = decltype(T::to_json(std::declval()...)); + +template +using from_json_function = decltype(T::from_json(std::declval()...)); + +template +using get_template_function = decltype(std::declval().template get()); + +// trait checking if JSONSerializer::from_json(json const&, udt&) exists +template +struct has_from_json : std::false_type {}; + +// trait checking if j.get is valid +// use this trait instead of std::is_constructible or std::is_convertible, +// both rely on, or make use of implicit conversions, and thus fail when T +// has several constructors/operator= (see https://github.com/nlohmann/json/issues/958) +template +struct is_getable +{ + static constexpr bool value = is_detected::value; +}; + +template +struct has_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if JSONSerializer::from_json(json const&) exists +// this overload is used for non-default-constructible user-defined-types +template +struct has_non_default_from_json : std::false_type {}; + +template +struct has_non_default_from_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +// This trait checks if BasicJsonType::json_serializer::to_json exists +// Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. +template +struct has_to_json : std::false_type {}; + +template +struct has_to_json < BasicJsonType, T, enable_if_t < !is_basic_json::value >> +{ + using serializer = typename BasicJsonType::template json_serializer; + + static constexpr bool value = + is_detected_exact::value; +}; + +template +using detect_key_compare = typename T::key_compare; + +template +struct has_key_compare : std::integral_constant::value> {}; + +// obtains the actual object key comparator +template +struct actual_object_comparator +{ + using object_t = typename BasicJsonType::object_t; + using object_comparator_t = typename BasicJsonType::default_object_comparator_t; + using type = typename std::conditional < has_key_compare::value, + typename object_t::key_compare, object_comparator_t>::type; +}; + +template +using actual_object_comparator_t = typename actual_object_comparator::type; + +/////////////////// +// is_ functions // +/////////////////// + +// https://en.cppreference.com/w/cpp/types/conjunction +template struct conjunction : std::true_type { }; +template struct conjunction : B { }; +template +struct conjunction +: std::conditional(B::value), conjunction, B>::type {}; + +// https://en.cppreference.com/w/cpp/types/negation +template struct negation : std::integral_constant < bool, !B::value > { }; + +// Reimplementation of is_constructible and is_default_constructible, due to them being broken for +// std::pair and std::tuple until LWG 2367 fix (see https://cplusplus.github.io/LWG/lwg-defects.html#2367). +// This causes compile errors in e.g. clang 3.5 or gcc 4.9. +template +struct is_default_constructible : std::is_default_constructible {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction, is_default_constructible> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + +template +struct is_default_constructible> + : conjunction...> {}; + + +template +struct is_constructible : std::is_constructible {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + +template +struct is_constructible> : is_default_constructible> {}; + + +template +struct is_iterator_traits : std::false_type {}; + +template +struct is_iterator_traits> +{ + private: + using traits = iterator_traits; + + public: + static constexpr auto value = + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value && + is_detected::value; +}; + +template +struct is_range +{ + private: + using t_ref = typename std::add_lvalue_reference::type; + + using iterator = detected_t; + using sentinel = detected_t; + + // to be 100% correct, it should use https://en.cppreference.com/w/cpp/iterator/input_or_output_iterator + // and https://en.cppreference.com/w/cpp/iterator/sentinel_for + // but reimplementing these would be too much work, as a lot of other concepts are used underneath + static constexpr auto is_iterator_begin = + is_iterator_traits>::value; + + public: + static constexpr bool value = !std::is_same::value && !std::is_same::value && is_iterator_begin; +}; + +template +using iterator_t = enable_if_t::value, result_of_begin())>>; + +template +using range_value_t = value_type_t>>; + +// The following implementation of is_complete_type is taken from +// https://blogs.msdn.microsoft.com/vcblog/2015/12/02/partial-support-for-expression-sfinae-in-vs-2015-update-1/ +// and is written by Xiang Fan who agreed to using it in this library. + +template +struct is_complete_type : std::false_type {}; + +template +struct is_complete_type : std::true_type {}; + +template +struct is_compatible_object_type_impl : std::false_type {}; + +template +struct is_compatible_object_type_impl < + BasicJsonType, CompatibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + // macOS's is_constructible does not play well with nonesuch... + static constexpr bool value = + is_constructible::value && + is_constructible::value; +}; + +template +struct is_compatible_object_type + : is_compatible_object_type_impl {}; + +template +struct is_constructible_object_type_impl : std::false_type {}; + +template +struct is_constructible_object_type_impl < + BasicJsonType, ConstructibleObjectType, + enable_if_t < is_detected::value&& + is_detected::value >> +{ + using object_t = typename BasicJsonType::object_t; + + static constexpr bool value = + (is_default_constructible::value && + (std::is_move_assignable::value || + std::is_copy_assignable::value) && + (is_constructible::value && + std::is_same < + typename object_t::mapped_type, + typename ConstructibleObjectType::mapped_type >::value)) || + (has_from_json::value || + has_non_default_from_json < + BasicJsonType, + typename ConstructibleObjectType::mapped_type >::value); +}; + +template +struct is_constructible_object_type + : is_constructible_object_type_impl {}; + +template +struct is_compatible_string_type +{ + static constexpr auto value = + is_constructible::value; +}; + +template +struct is_constructible_string_type +{ + // launder type through decltype() to fix compilation failure on ICPC +#ifdef __INTEL_COMPILER + using laundered_type = decltype(std::declval()); +#else + using laundered_type = ConstructibleStringType; +#endif + + static constexpr auto value = + conjunction < + is_constructible, + is_detected_exact>::value; +}; + +template +struct is_compatible_array_type_impl : std::false_type {}; + +template +struct is_compatible_array_type_impl < + BasicJsonType, CompatibleArrayType, + enable_if_t < + is_detected::value&& + is_iterator_traits>>::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 + !std::is_same>::value >> +{ + static constexpr bool value = + is_constructible>::value; +}; + +template +struct is_compatible_array_type + : is_compatible_array_type_impl {}; + +template +struct is_constructible_array_type_impl : std::false_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t::value >> + : std::true_type {}; + +template +struct is_constructible_array_type_impl < + BasicJsonType, ConstructibleArrayType, + enable_if_t < !std::is_same::value&& + !is_compatible_string_type::value&& + is_default_constructible::value&& +(std::is_move_assignable::value || + std::is_copy_assignable::value)&& +is_detected::value&& +is_iterator_traits>>::value&& +is_detected::value&& +// special case for types like std::filesystem::path whose iterator's value_type are themselves +// c.f. https://github.com/nlohmann/json/pull/3073 +!std::is_same>::value&& + is_complete_type < + detected_t>::value >> +{ + using value_type = range_value_t; + + static constexpr bool value = + std::is_same::value || + has_from_json::value || + has_non_default_from_json < + BasicJsonType, + value_type >::value; +}; + +template +struct is_constructible_array_type + : is_constructible_array_type_impl {}; + +template +struct is_compatible_integer_type_impl : std::false_type {}; + +template +struct is_compatible_integer_type_impl < + RealIntegerType, CompatibleNumberIntegerType, + enable_if_t < std::is_integral::value&& + std::is_integral::value&& + !std::is_same::value >> +{ + // is there an assert somewhere on overflows? + using RealLimits = std::numeric_limits; + using CompatibleLimits = std::numeric_limits; + + static constexpr auto value = + is_constructible::value && + CompatibleLimits::is_integer && + RealLimits::is_signed == CompatibleLimits::is_signed; +}; + +template +struct is_compatible_integer_type + : is_compatible_integer_type_impl {}; + +template +struct is_compatible_type_impl: std::false_type {}; + +template +struct is_compatible_type_impl < + BasicJsonType, CompatibleType, + enable_if_t::value >> +{ + static constexpr bool value = + has_to_json::value; +}; + +template +struct is_compatible_type + : is_compatible_type_impl {}; + +template +struct is_constructible_tuple : std::false_type {}; + +template +struct is_constructible_tuple> : conjunction...> {}; + +template +struct is_json_iterator_of : std::false_type {}; + +template +struct is_json_iterator_of : std::true_type {}; + +template +struct is_json_iterator_of : std::true_type +{}; + +// checks if a given type T is a template specialization of Primary +template