CoolFlutterIJK.m 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. //
  2. // Created by Caijinglong on 2019-03-08.
  3. //
  4. #import "CoolFlutterIJK.h"
  5. #import "CoolVideoInfo.h"
  6. #import "CoolIjkNotifyChannel.h"
  7. #import <IJKMediaFramework/IJKMediaFramework.h>
  8. #import <IJKMediaFramework/IJKMediaPlayer.h>
  9. #import <AVFoundation/AVFoundation.h>
  10. #import <libkern/OSAtomic.h>
  11. @interface CoolFlutterIJK () <FlutterTexture, KKIjkNotifyDelegate>
  12. @end
  13. @implementation CoolFlutterIJK {
  14. int64_t textureId;
  15. CADisplayLink *displayLink;
  16. NSObject <FlutterTextureRegistry> *textures;
  17. IJKFFMoviePlayerController *controller;
  18. CVPixelBufferRef latestPixelBuffer;
  19. FlutterMethodChannel *channel;
  20. CoolIjkNotifyChannel *notifyChannel;
  21. int degree;
  22. }
  23. - (instancetype)initWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
  24. self = [super init];
  25. if (self) {
  26. self.registrar = registrar;
  27. textures = [self.registrar textures];
  28. textureId = [textures registerTexture:self];
  29. NSString *channelName = [NSString stringWithFormat:@"top.kikt/ijkplayer/%lli", textureId];
  30. channel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:[registrar messenger]];
  31. [channel setMethodCallHandler:^(FlutterMethodCall *call, FlutterResult result) {
  32. [self handleMethodCall:call result:result];
  33. }];
  34. }
  35. return self;
  36. }
  37. - (void)dispose {
  38. [notifyChannel dispose];
  39. [[self.registrar textures] unregisterTexture:self.id];
  40. [controller stop];
  41. [controller shutdown];
  42. controller = nil;
  43. displayLink.paused = YES;
  44. [displayLink invalidate];
  45. }
  46. - (void)handleMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {
  47. if ([@"play" isEqualToString:call.method]) {
  48. [self play];
  49. result(@(YES));
  50. } else if ([@"pause" isEqualToString:call.method]) {
  51. [self pause];
  52. result(@(YES));
  53. } else if ([@"stop" isEqualToString:call.method]) {
  54. [self stop];
  55. result(@(YES));
  56. } else if ([@"setNetworkDataSource" isEqualToString:call.method]) {
  57. @try {
  58. NSDictionary *params = call.arguments;
  59. NSString *uri = params[@"uri"];
  60. NSDictionary *headers = params[@"headers"];
  61. [self setDataSourceWithUri:uri headers:headers];
  62. result(@(YES));
  63. }
  64. @catch (NSException *exception) {
  65. NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
  66. result([FlutterError errorWithCode:@"1" message:@"设置失败" details:nil]);
  67. }
  68. } else if ([@"setAssetDataSource" isEqualToString:call.method]) {
  69. @try {
  70. NSDictionary *params = [call arguments];
  71. NSString *name = params[@"name"];
  72. NSString *pkg = params[@"package"];
  73. IJKFFMoviePlayerController *playerController = [self createControllerWithAssetName:name pkg:pkg];
  74. [self setDataSourceWithController:playerController];
  75. result(@(YES));
  76. }
  77. @catch (NSException *exception) {
  78. NSLog(@"Exception occurred: %@, %@", exception, [exception userInfo]);
  79. result([FlutterError errorWithCode:@"1" message:@"设置失败" details:nil]);
  80. }
  81. } else if ([@"setFileDataSource" isEqualToString:call.method]) {
  82. NSDictionary *params = call.arguments;
  83. NSString *path = params[@"path"];
  84. IJKFFMoviePlayerController *playerController = [self createControllerWithPath:path];
  85. [self setDataSourceWithController:playerController];
  86. result(@(YES));
  87. } else if ([@"seekTo" isEqualToString:call.method]) {
  88. NSDictionary *params = call.arguments;
  89. double target = [params[@"target"] doubleValue];
  90. [self seekTo:target];
  91. result(@(YES));
  92. } else if ([@"getInfo" isEqualToString:call.method]) {
  93. CoolVideoInfo *info = [self getInfo];
  94. result([info toMap]);
  95. } else if ([@"setVolume" isEqualToString:call.method]) {
  96. NSDictionary *params = [self params:call];
  97. float v = [params[@"volume"] floatValue] / 100;
  98. controller.playbackVolume = v;
  99. result(@(YES));
  100. } else {
  101. result(FlutterMethodNotImplemented);
  102. }
  103. }
  104. - (NSDictionary *)params:(FlutterMethodCall *)call {
  105. return call.arguments;
  106. }
  107. + (instancetype)ijkWithRegistrar:(NSObject <FlutterPluginRegistrar> *)registrar {
  108. return [[self alloc] initWithRegistrar:registrar];
  109. }
  110. - (int64_t)id {
  111. return textureId;
  112. }
  113. - (void)play {
  114. [controller play];
  115. if (displayLink) {
  116. displayLink.paused = NO;
  117. }
  118. }
  119. - (void)pause {
  120. [controller pause];
  121. if (displayLink) {
  122. displayLink.paused = YES;
  123. }
  124. }
  125. - (void)stop {
  126. [controller stop];
  127. if (displayLink) {
  128. displayLink.paused = NO;
  129. }
  130. }
  131. - (void)setDataSourceWithController:(IJKFFMoviePlayerController *)ctl {
  132. if (ctl) {
  133. controller = ctl;
  134. [self prepare];
  135. }
  136. }
  137. - (IJKFFOptions *)createOption {
  138. IJKFFOptions *options = [IJKFFOptions optionsByDefault];
  139. // see https://www.jianshu.com/p/843c86a9e9ad
  140. // [options setFormatOptionValue:@"fastseek" forKey:@"fflags"];
  141. // [options setFormatOptionIntValue:100 forKey:@"analyzemaxduration"];
  142. // [options setFormatOptionIntValue:1 forKey:@"analyzeduration"];
  143. // [options setFormatOptionIntValue:10240 forKey:@"probesize"];
  144. // [options setFormatOptionIntValue:1 forKey:@"flush_packets"];
  145. // [options setFormatOptionIntValue:5 forKey:@"reconnect"];
  146. // [options setFormatOptionIntValue:5 forKey:@"framedrop"];
  147. // [options setFormatOptionIntValue:1 forKey:@"enable-accurate-seek"];
  148. // [options setPlayerOptionIntValue:0 forKey:@"video-max-frame-width-default"];
  149. // [options setPlayerOptionIntValue:1 forKey:@"videotoolbox"];
  150. return options;
  151. }
  152. - (void)setDataSourceWithUri:(NSString *)uri headers:(NSDictionary *)headers {
  153. IJKFFOptions *options = [self createOption];
  154. if (headers) {
  155. NSMutableString *headerString = [NSMutableString new];
  156. for (NSString *key in headers.allKeys) {
  157. NSString *value = headers[key];
  158. [headerString appendFormat:@"%@:%@", key, value];
  159. [headerString appendString:@"\r\n"];
  160. }
  161. [options setFormatOptionValue:headerString forKey:@"headers"];
  162. }
  163. controller = [[IJKFFMoviePlayerController alloc] initWithContentURLString:uri withOptions:options];
  164. [self prepare];
  165. }
  166. - (void)setDegree:(int)d {
  167. degree = d;
  168. }
  169. - (void)prepare {
  170. [controller prepareToPlay];
  171. if (displayLink) {
  172. displayLink.paused = YES;
  173. [displayLink invalidate];
  174. displayLink = nil;
  175. }
  176. displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(onDisplayLink:)];
  177. [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  178. displayLink.paused = YES;
  179. notifyChannel = [CoolIjkNotifyChannel channelWithController:controller textureId:textureId registrar:self.registrar];
  180. notifyChannel.infoDelegate = self;
  181. }
  182. - (IJKFFMoviePlayerController *)createControllerWithAssetName:(NSString *)assetName pkg:(NSString *)pkg {
  183. NSString *asset;
  184. if (!pkg) {
  185. asset = [self.registrar lookupKeyForAsset:assetName];
  186. } else {
  187. asset = [self.registrar lookupKeyForAsset:assetName fromPackage:pkg];
  188. }
  189. NSString *path = [[NSBundle mainBundle] pathForResource:asset ofType:nil];
  190. NSURL *url = [NSURL fileURLWithPath:path];
  191. IJKFFOptions *options = [self createOption];
  192. return [[IJKFFMoviePlayerController alloc] initWithContentURL:url withOptions:options];
  193. }
  194. - (IJKFFMoviePlayerController *)createControllerWithPath:(NSString *)path {
  195. NSURL *url = [NSURL fileURLWithPath:path];
  196. IJKFFOptions *options = [self createOption];
  197. return [[IJKFFMoviePlayerController alloc] initWithContentURL:url withOptions:options];
  198. }
  199. - (void)seekTo:(double)target {
  200. [controller setCurrentPlaybackTime:target];
  201. }
  202. - (void)onDisplayLink:(CADisplayLink *)link {
  203. [textures textureFrameAvailable:textureId];
  204. }
  205. - (CVPixelBufferRef _Nullable)copyPixelBuffer {
  206. CVPixelBufferRef newBuffer = [controller framePixelbuffer];
  207. if (newBuffer) {
  208. CFRetain(newBuffer);
  209. CVPixelBufferRef pixelBuffer = latestPixelBuffer;
  210. while (!OSAtomicCompareAndSwapPtrBarrier(pixelBuffer, newBuffer, (void **) &latestPixelBuffer)) {
  211. pixelBuffer = latestPixelBuffer;
  212. }
  213. return pixelBuffer;
  214. }
  215. return NULL;
  216. }
  217. - (CoolVideoInfo *)getInfo {
  218. CoolVideoInfo *info = [CoolVideoInfo new];
  219. CGSize size = [controller naturalSize];
  220. NSTimeInterval duration = [controller duration];
  221. NSTimeInterval currentPlaybackTime = [controller currentPlaybackTime];
  222. info.size = size;
  223. info.duration = duration;
  224. info.currentPosition = currentPlaybackTime;
  225. info.isPlaying = [controller isPlaying];
  226. info.degree = degree;
  227. info.tcpSpeed = [controller tcpSpeed];
  228. info.outputFps = [controller fpsAtOutput];
  229. return info;
  230. }
  231. - (NSUInteger)degreeFromVideoFileWithURL:(NSURL *)url {
  232. NSUInteger mDegree = 0;
  233. AVAsset *asset = [AVAsset assetWithURL:url];
  234. NSArray *tracks = [asset tracksWithMediaType:AVMediaTypeVideo];
  235. if ([tracks count] > 0) {
  236. AVAssetTrack *videoTrack = tracks[0];
  237. CGAffineTransform t = videoTrack.preferredTransform;
  238. if (t.a == 0 && t.b == 1.0 && t.c == -1.0 && t.d == 0) {
  239. // Portrait
  240. mDegree = 90;
  241. } else if (t.a == 0 && t.b == -1.0 && t.c == 1.0 && t.d == 0) {
  242. // PortraitUpsideDown
  243. mDegree = 270;
  244. } else if (t.a == 1.0 && t.b == 0 && t.c == 0 && t.d == 1.0) {
  245. // LandscapeRight
  246. mDegree = 0;
  247. } else if (t.a == -1.0 && t.b == 0 && t.c == 0 && t.d == -1.0) {
  248. // LandscapeLeft
  249. mDegree = 180;
  250. }
  251. }
  252. return mDegree;
  253. }
  254. @end