PCSBaseViewController.m 113 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884
  1. //
  2. // PCSBaseViewController.m
  3. // PanoramicCameraSDK
  4. //
  5. // Created by 王昭威 on 2023/1/14.
  6. //
  7. #import "PCSBaseViewController.h"
  8. #import <AVFoundation/AVFoundation.h>
  9. #import "Masonry.h"
  10. #import "CameraManager.h"
  11. #import "AVCapturePhotoOutput+VersionAdaptor.h"
  12. #import "PCSRoundButton.h"
  13. #import "PCSModeList.h"
  14. #import "UIImage+ext.h"
  15. #import "PCSTools.h"
  16. #import "OperationNodeProtocol.h"
  17. #import "OperationNodeSingle.h"
  18. #import "OperationNodeMultiple.h"
  19. #import "OperationNodePanorama.h"
  20. #import "QuitMultipleModeAlertViewController.h"
  21. #import <CoreMotion/CoreMotion.h>
  22. #import "OperationNodeMovie.h"
  23. #import "SDKParameters.h"
  24. #import "PhotoListViewController.h"
  25. #import "CustomModalViewTransition.h"
  26. #import "MovieListViewController.h"
  27. #import "TimerLabel.h"
  28. #import "MoviePlayerViewController.h"
  29. #import "PanoramaOrientationView.h"
  30. #import "PanoramaGuideView.h"
  31. #import "Renderer.h"
  32. #import "CameraTextureRenderPass.h"
  33. #import "LenzSDKConstant.h"
  34. #import "TensorFlowWrapper.h"
  35. #import "DBManager.h"
  36. #import <Photos/Photos.h>
  37. #import "BaseViewTapGestureDelegate.h"
  38. #import "MovieListCellModel.h"
  39. #import "PreviewSingleViewController.h"
  40. #import "OperationNodeAIPanorama.h"
  41. #import "PhotoAlbumListViewController.h"
  42. #import "PhotoAlbumModel.h"
  43. //#import "LenStitcher.h"
  44. //#import <LenzStitchSDK/LenzStitchSDK.h>
  45. #import "LenzDataManager.h"
  46. #import "LenzHeader.h"
  47. #import "LenzCachedResourceModel.h"
  48. #import "LenzDataManager.h"
  49. #import "PCSPreviewViewController.h"
  50. #import "SVProgressHUD.h"
  51. #import "PCSAutherView.h"
  52. #import <LenzTensorFlowSDK/LenzTensorFlow.h>
  53. #define MODE_LIST_INDEX_2_MODE_ENUM(x) ((x))
  54. // PCS means panoramic camera sdk
  55. @interface PCSBaseViewController ()<AVCapturePhotoCaptureDelegate,
  56. AVCaptureFileOutputRecordingDelegate,
  57. AVCaptureAudioDataOutputSampleBufferDelegate,
  58. UIViewControllerTransitioningDelegate,
  59. AVCaptureVideoDataOutputSampleBufferDelegate,
  60. PhotoListViewControllerDelegate,
  61. PanoramaOrientationViewDelegate>
  62. @property (nonatomic, assign) CGFloat accX;
  63. @property (nonatomic, nullable, readonly) AVCaptureDevice* currentCamera;
  64. @property (nonatomic, nullable, readonly) AVCaptureDeviceInput* currentCameraInput;
  65. @property (nonatomic, strong) AVCaptureSession* captureSession;
  66. @property (nonatomic, strong) AVCaptureVideoDataOutput* videoDataOutput;
  67. @property (nonatomic, strong) AVCaptureMovieFileOutput* movieFileOutput;
  68. @property (nonatomic, strong) AVCapturePhotoOutput* photoOutput;
  69. @property (nonatomic, strong) AVCapturePhotoSettings* outputSettings;
  70. @property (nonatomic, copy) dispatch_queue_t videoDataQueue;
  71. @property (nonatomic, strong) AVAssetWriter* videoWriter;
  72. @property (nonatomic, strong) AVAssetWriterInput* videoWriterInput;
  73. @property (nonatomic, assign) BOOL cameraPrepared;
  74. @property (nonatomic, assign) BOOL flag;
  75. @property (nonatomic, assign) BOOL hasCache;
  76. @property (nonatomic, strong) UIView* focusView;
  77. @property (nonatomic, strong, nullable) NSTimer* recordTimer;
  78. @property (nonatomic) dispatch_source_t touchSourceTimer;
  79. @property (nonatomic) CGFloat touchTime;
  80. @property (nonatomic, strong, nullable) NSTimer* motionTimer;
  81. @property (nonatomic, strong) BaseViewTapGestureDelegate* tapDelegate;
  82. /**
  83. key: PhotographModeEnum
  84. value: subclass of OperationNodeProtocol
  85. */
  86. @property (nonatomic, strong) NSDictionary<NSNumber*, id<OperationNodeProtocol>>* operationNodes;
  87. @property (nonatomic, strong) NSArray<id<OperationNodeProtocol>>* operationNodesArray;
  88. @property (nonatomic) dispatch_semaphore_t videoStitchSemaphore;
  89. @property (nonatomic) LenzCachedResourceModel *resourceModel;
  90. @property (nonatomic) UIView *stitchView;
  91. @property (nonatomic) UIImageView *stitchImageView;
  92. @property (nonatomic) UILabel *stitchLabel;
  93. @property (nonatomic) CABasicAnimation *loadingAnimation;
  94. @property (nonatomic) BOOL isStitchBigImage;
  95. @property (nonatomic) CGFloat brightnessValue;
  96. @property (nonatomic) CMMotionManager *motionManager;
  97. @property (nonatomic) BOOL isTakePhoto;
  98. @property (nonatomic) NSLock *stitchkLock;
  99. @property (nonatomic) LenVideoStitchResult stitchResult;
  100. @property (nonatomic) NSNumber *startPitchX;
  101. @property (nonatomic) NSNumber *startRollY;
  102. @property (nonatomic) LenzTensorFlow *tensorFlow;
  103. @property (nonatomic) BOOL isContainSingleInReatinMode;
  104. @property (nonatomic) UILabel *aiPanPromtLabel;
  105. @property (nonatomic) PCSAutherView *authView;
  106. @end
  107. @implementation PCSBaseViewController
  108. #pragma mark - Life Circle
  109. - (void)dealloc{
  110. [self stopAllSensors];
  111. [[NSNotificationCenter defaultCenter] removeObserver:self];
  112. [[LenzDBManager shared] close];
  113. }
  114. - (void)awakeFromNib{
  115. [super awakeFromNib];
  116. [self setup];
  117. }
  118. - (void)viewDidLoad {
  119. [super viewDidLoad];
  120. // Do any additional setup after loading the view.
  121. [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
  122. [SVProgressHUD setMinimumDismissTimeInterval:1.5];
  123. [SVProgressHUD setMaximumDismissTimeInterval:3];
  124. [SVProgressHUD setFont:[UIFont systemFontOfSize:14]];
  125. self.tensorFlow = [[LenzTensorFlow alloc]initWithFileName:@"moire_mobilenetv2_79"];
  126. self.stitchkLock = [[NSLock alloc]init];
  127. self.totalArray = [[NSMutableArray alloc]init];
  128. self.cachesArray = [[NSMutableArray alloc]init];
  129. self.typeArray = [[NSMutableArray alloc]init];
  130. self.isContainSingleInReatinMode = NO;
  131. self.resourceModel = [[LenzCachedResourceModel alloc]init];
  132. self.motionManager = [[CMMotionManager alloc]init];
  133. self.motionManager.deviceMotionUpdateInterval = 1/5;
  134. [self.view addSubview:self.panoramaGuideView];
  135. [self panoramaOrientationViewslt:(PanoramaOrientationViewLeft)];
  136. self.panoramaGuideView.hidden = YES;
  137. [self.view addSubview:self.aiPanPromtLabel];
  138. [self.aiPanPromtLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  139. make.centerX.mas_equalTo(self.view);
  140. make.top.mas_equalTo(self.modeLabel.mas_bottom).mas_offset(20);
  141. make.width.mas_offset(240);
  142. make.height.mas_offset(20);
  143. }];
  144. [self.view addSubview:self.authView];
  145. [self.authView mas_makeConstraints:^(MASConstraintMaker *make) {
  146. make.edges.mas_offset(0);
  147. }];
  148. if (!JK_IS_IPHONE_X) {
  149. self.safeBottom.constant = 25;
  150. self.safeTop.constant = 15;
  151. }else{
  152. self.safeBottom.constant = 0;
  153. }
  154. [self.timerLabel updateWith:100];
  155. self.albumButton.layer.cornerRadius = 6;
  156. self.albumButton.clipsToBounds = YES;
  157. [self updateFlashButton];
  158. [PCSMotionManager shared];
  159. __weak typeof(self) weakself = self;
  160. [self.modeList reloadWith:self.operationNodesArray];
  161. self.modeList.indexChangedHandler = ^BOOL(NSUInteger newMode, NSUInteger oldMode, NSUInteger newIndex) {
  162. __strong typeof(weakself) strongSelf = weakself;
  163. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_CLEAR) {
  164. BOOL needAlert = NO;
  165. switch (self.mode) {
  166. case SDK_CAPTURE_MODE_CONTINUOUS:
  167. needAlert = self.resourceModel.continousArray.count;
  168. break;
  169. case SDK_CAPTURE_MODE_SINGLE:
  170. needAlert = self.resourceModel.singleArray.count;
  171. break;
  172. case SDK_CAPTURE_MODE_MOVIE:
  173. needAlert = self.resourceModel.movieArray.count;
  174. break;
  175. case SDK_CAPTURE_MODE_PANORAMA:
  176. needAlert = self.resourceModel.panoramArray.count;
  177. break;
  178. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  179. needAlert = self.resourceModel.aiPanoramArray.count;
  180. break;
  181. default:
  182. break;
  183. }
  184. if (needAlert) {
  185. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"切换模式会清除已拍摄数据,请确认" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  186. [alertController dismissViewControllerAnimated:NO completion:^{}];
  187. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  188. switch (self.mode) {
  189. case SDK_CAPTURE_MODE_CONTINUOUS: {
  190. [self.resourceModel.continousArray removeAllObjects];
  191. [self updateViewStatus];
  192. }
  193. break;
  194. case SDK_CAPTURE_MODE_SINGLE: {
  195. [self.resourceModel.singleArray removeAllObjects];
  196. [self updateViewStatus];
  197. }
  198. break;
  199. case SDK_CAPTURE_MODE_MOVIE:
  200. {
  201. [self.resourceModel.movieArray removeAllObjects];
  202. [self updateViewStatus];
  203. }
  204. break;
  205. case SDK_CAPTURE_MODE_PANORAMA:
  206. {
  207. [self.resourceModel.panoramArray removeAllObjects];
  208. [self updateViewStatus];
  209. }
  210. break;
  211. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  212. {
  213. [self.resourceModel.aiPanoramArray removeAllObjects];
  214. [self updateViewStatus];
  215. }
  216. break;
  217. default:
  218. break;
  219. }
  220. self.modeList.index = newIndex;
  221. [self.modeList updateItemsConstraints];
  222. [strongSelf modeWillChange:newMode oldIndex:oldMode];
  223. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  224. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newMode);
  225. strongSelf.mode = mode;
  226. // self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  227. self.ai_fullView.hidden = YES;
  228. [strongSelf modeDidChange:newMode oldIndex:oldMode];
  229. [strongSelf updateCaptureSessionWith:oldMode];
  230. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  231. [oldModelNode didQuit];
  232. }
  233. [alertController dismissViewControllerAnimated:NO completion:^{}];
  234. }];
  235. return NO;
  236. }
  237. }
  238. [strongSelf modeWillChange:newMode oldIndex:oldMode];
  239. id<OperationNodeProtocol> oldModelNode = strongSelf.currentOperationNode;
  240. PhotographModeEnum mode = (PhotographModeEnum)MODE_LIST_INDEX_2_MODE_ENUM(newMode);
  241. strongSelf.mode = mode;
  242. // self.ai_fullView.hidden = !(mode == SDK_CAPTURE_MODE_PANORAMA);
  243. self.ai_fullView.hidden = YES;
  244. [strongSelf modeDidChange:newMode oldIndex:oldMode];
  245. [strongSelf updateCaptureSessionWith:oldMode];
  246. if([oldModelNode respondsToSelector:@selector(didQuit)]){
  247. [oldModelNode didQuit];
  248. }
  249. return YES;
  250. };
  251. [self modeWillChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  252. self.modeList.mode = [SDKParameters shared].modeIndex;
  253. self.mode = [SDKParameters shared].modeIndex;
  254. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  255. UIVisualEffectView* effectView = [[UIVisualEffectView alloc] initWithEffect: [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
  256. effectView.alpha = 0.8;
  257. effectView.effect = nil;
  258. self.effectView = effectView;
  259. [self.view insertSubview:self.effectView belowSubview:self.backButton];
  260. [self.effectView mas_makeConstraints:^(MASConstraintMaker *make) {
  261. make.edges.equalTo(self.view);
  262. }];
  263. if(!self.cameraPrepared){
  264. [self prepareCamera];
  265. }
  266. [self modeDidChange:[SDKParameters shared].modeIndex oldIndex:0lu];
  267. [self updateCaptureSessionWith:0];
  268. self.panGesture = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureHandler:)];
  269. [self.view addGestureRecognizer:self.panGesture];
  270. UIImageView* loadingImageView = [[UIImageView alloc] initWithImage:[UIImage sdkImageNamed:@"loading"]];
  271. self.loadingIndicator = loadingImageView;
  272. self.loadingIndicator.hidden = YES;
  273. [self.view addSubview:self.loadingIndicator];
  274. [loadingImageView mas_remakeConstraints:^(MASConstraintMaker *make) {
  275. make.center.equalTo(self.view);
  276. }];
  277. self.savePhotoButton.titleLabel.textColor = [UIColor whiteColor];
  278. self.discardPhotoButton.titleLabel.textColor = [UIColor whiteColor];
  279. // [self.takePhotoButton mas_remakeConstraints:^(MASConstraintMaker *make) {
  280. // make.centerX.equalTo(self.view);
  281. // make.bottom.equalTo(self.view.mas_safeAreaLayoutGuideBottom);
  282. // }];
  283. [self updateUIByMode];
  284. self.panoramOrientationGuideView.delegate = self;
  285. self.ablumImageView = [[UIImageView alloc]init];
  286. [self.view addSubview:self.ablumImageView];
  287. self.ablumImageView.layer.cornerRadius = 6;
  288. self.ablumImageView.layer.masksToBounds = YES;
  289. UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showPreview:)];
  290. [self.ablumImageView addGestureRecognizer:tap];
  291. self.ablumImageView.userInteractionEnabled = YES;
  292. self.ablumImageView.hidden = YES;
  293. // self.ablumImageView.backgroundColor = [UIColor redColor];
  294. self.ablumImageView.contentMode = UIViewContentModeScaleAspectFill;
  295. [self.ablumImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  296. make.centerY.mas_equalTo(self.takePhotoButton);
  297. make.left.mas_equalTo(20);
  298. make.width.height.mas_equalTo(60);
  299. // make.top.left.mas_equalTo(50);
  300. // make.width.height.mas_equalTo(300);
  301. }];
  302. UILongPressGestureRecognizer *ges = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGes:)];
  303. // ges.numberOfTapsRequired = 1;
  304. ges.minimumPressDuration = 1;
  305. [self.takePhotoButton addGestureRecognizer:ges];
  306. self.timerLabel.layer.cornerRadius = 6;
  307. self.timerLabel.layer.masksToBounds = YES;
  308. [self.ai_fullView addTarget:self action:@selector(alFullViewAction:) forControlEvents:UIControlEventTouchUpInside];
  309. [self.view addSubview:self.stitchView];
  310. [self.stitchView mas_makeConstraints:^(MASConstraintMaker *make) {
  311. make.centerY.mas_equalTo(self.view);
  312. make.centerX.mas_equalTo(self.view);
  313. make.width.mas_offset(200);
  314. make.height.mas_offset(200);
  315. }];
  316. }
  317. - (PCSAutherView *)authView {
  318. if (!_authView) {
  319. _authView = [[PCSAutherView alloc]init];
  320. _authView.hidden = YES;
  321. }
  322. return _authView;
  323. }
  324. - (void)viewWillAppear:(BOOL)animated{
  325. [super viewWillAppear:animated];
  326. self.panGesture.enabled = YES;
  327. if([self.currentOperationNode respondsToSelector:@selector(updateUI)])
  328. [self.currentOperationNode updateUI];
  329. }
  330. - (void)viewDidAppear:(BOOL)animated{
  331. [super viewDidAppear:animated];
  332. if(self.cameraPrepared){
  333. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo]) {
  334. case AVAuthorizationStatusAuthorized:
  335. [self startCaptureSession];
  336. [[PCSMotionManager shared] startAccelerometerUpdates];
  337. break;
  338. case AVAuthorizationStatusNotDetermined:{
  339. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
  340. if(granted){
  341. [self startCaptureSession];
  342. [[PCSMotionManager shared] startAccelerometerUpdates];
  343. }
  344. else{
  345. [self showAuthorCamerIfNeed];
  346. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  347. }
  348. }];
  349. break;
  350. }
  351. case AVAuthorizationStatusDenied:{
  352. [[NSNotificationCenter defaultCenter] postNotificationName:CameraNotificationNotPermission object:self];
  353. break;
  354. }
  355. case AVAuthorizationStatusRestricted:
  356. break;
  357. default:
  358. break;
  359. }
  360. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  361. case AVAuthorizationStatusAuthorized:
  362. [self setupMicrophone];
  363. break;
  364. case AVAuthorizationStatusNotDetermined:{
  365. [AVCaptureDevice requestAccessForMediaType:AVMediaTypeAudio completionHandler:^(BOOL granted) {
  366. if(granted){
  367. [self setupMicrophone];
  368. }
  369. else{
  370. [self showAudioCamerIfNeed];
  371. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  372. }
  373. }];
  374. break;
  375. }
  376. case AVAuthorizationStatusDenied:{
  377. [[NSNotificationCenter defaultCenter] postNotificationName:MicrophoneNotificationNotPermission object:self];
  378. break;
  379. }
  380. case AVAuthorizationStatusRestricted:
  381. break;
  382. default:
  383. break;
  384. }
  385. }
  386. // [self showAuthorCamerIfNeed];
  387. }
  388. - (void)viewWillDisappear:(BOOL)animated{
  389. [super viewWillDisappear:animated];
  390. [self stopCaptureSession];
  391. [[PCSMotionManager shared] stopAccelerometerUpdates];
  392. }
  393. - (void)updateFlashButton {
  394. __block SDKFlashModeIndex flashModel = SDK_FLASH_MODE_AUTO;
  395. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  396. if (obj.model == self.mode) {
  397. flashModel = obj.flashMode;
  398. }
  399. }];
  400. switch (flashModel) {
  401. case SDK_FLASH_MODE_AUTO:{
  402. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  403. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  404. break;
  405. }
  406. case SDK_FLASH_MODE_ON:{
  407. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  408. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  409. break;
  410. }
  411. case SDK_FLASH_MODE_OFF:{
  412. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  413. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  414. break;
  415. }
  416. default:
  417. break;
  418. }
  419. }
  420. - (UIView *)stitchView {
  421. if (!_stitchView) {
  422. _stitchView = [[UIView alloc]init];
  423. [_stitchView addSubview:self.stitchImageView];
  424. [self.stitchImageView mas_makeConstraints:^(MASConstraintMaker *make) {
  425. make.centerX.mas_equalTo(_stitchView);
  426. make.top.mas_equalTo(0);
  427. make.width.height.mas_equalTo(68);
  428. }];
  429. [_stitchView addSubview:self.stitchLabel];
  430. [self.stitchLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  431. make.top.mas_equalTo(self.stitchImageView.mas_bottom).mas_offset(20);
  432. make.centerX.mas_equalTo(self.stitchImageView);
  433. }];
  434. _stitchView.hidden = YES;
  435. }
  436. return _stitchView;
  437. }
  438. - (UIImageView *)stitchImageView {
  439. if (!_stitchImageView) {
  440. _stitchImageView = [[UIImageView alloc]init];
  441. _stitchImageView.image = [UIImage loadNamed:@"loading"];
  442. }
  443. return _stitchImageView;
  444. }
  445. - (CABasicAnimation *)loadingAnimation {
  446. if (!_loadingAnimation) {
  447. _loadingAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
  448. _loadingAnimation.fromValue = [NSNumber numberWithFloat:0.f];
  449. _loadingAnimation.toValue = [NSNumber numberWithFloat: M_PI *2];
  450. _loadingAnimation.duration = 3;
  451. _loadingAnimation.autoreverses = NO;
  452. _loadingAnimation.fillMode = kCAFillModeForwards;
  453. _loadingAnimation.repeatCount = MAXFLOAT;
  454. }
  455. return _loadingAnimation;
  456. }
  457. - (UILabel *)aiPanPromtLabel {
  458. if (!_aiPanPromtLabel) {
  459. _aiPanPromtLabel = [[UILabel alloc]init];
  460. _aiPanPromtLabel.backgroundColor = [UIColor colorWithRed:33/255.0 green:33/255.0 blue:33/255.0 alpha:.2];
  461. _aiPanPromtLabel.layer.cornerRadius = 6;
  462. _aiPanPromtLabel.layer.masksToBounds = YES;
  463. _aiPanPromtLabel.textColor = [UIColor whiteColor];
  464. _aiPanPromtLabel.font = [UIFont systemFontOfSize:14];
  465. _aiPanPromtLabel.text = @"请保持手机与拍摄物平行,匀速拍摄";
  466. _aiPanPromtLabel.hidden = YES;
  467. _aiPanPromtLabel.textAlignment = NSTextAlignmentCenter;
  468. }
  469. return _aiPanPromtLabel;
  470. }
  471. - (UILabel *)stitchLabel {
  472. if (!_stitchLabel) {
  473. _stitchLabel = [[UILabel alloc]init];
  474. _stitchLabel.text = @"正在拼接中,请稍等";
  475. _stitchLabel.font = [UIFont systemFontOfSize:12];
  476. _stitchLabel.textColor = [UIColor whiteColor];
  477. }
  478. return _stitchLabel;
  479. }
  480. #pragma mark - Private Method
  481. - (void)alFullViewAction:(UIButton *)button {
  482. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  483. OperationNodePanorama *pan = nil;
  484. if ([self.currentOperationNode isKindOfClass:[OperationNodePanorama class]]) {
  485. pan = self.currentOperationNode;
  486. pan.needHiddenDir = !pan.needHiddenDir;
  487. }
  488. self.panoramOrientationGuideView.hidden = pan.needHiddenDir;
  489. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  490. OperationNodeAIPanorama *aiPan = nil;
  491. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  492. aiPan = self.currentOperationNode;
  493. aiPan.needHiddenDir = !aiPan.needHiddenDir;
  494. }
  495. self.panoramOrientationGuideView.hidden = aiPan.needHiddenDir;
  496. }
  497. }
  498. - (void)showPreview:(UITapGestureRecognizer *)tap {
  499. if (self.ablumImageView.hidden) {
  500. return;
  501. }
  502. if(self.mode != SDK_CAPTURE_MODE_SINGLE) {
  503. PCSPreviewViewController *vc = [[PCSPreviewViewController alloc]init];
  504. vc.modalPresentationStyle = UIModalPresentationFullScreen;
  505. vc.model = self.resourceModel;
  506. vc.selectIndex = self.mode;
  507. vc.dataChangeBlock = ^{
  508. [self updateViewStatus];
  509. };
  510. [self presentViewController:vc animated:YES completion:nil];
  511. } else {
  512. PreviewSingleViewController* dst = [[PreviewSingleViewController alloc]init];
  513. dst.modalPresentationStyle = UIModalPresentationFullScreen;
  514. dst.singleModeNode = self.currentOperationNode;
  515. if (self.resourceModel.singleArray.count > 0) {
  516. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  517. dst.image = model.image;
  518. }
  519. [self presentViewController:dst animated:YES completion:nil];
  520. }
  521. }
  522. + (instancetype)initWithParams:(NSDictionary *)params complete:(PCSBaseVCCompleteBLock)complete {
  523. [self parser:params];
  524. UIStoryboard* sb = [UIStoryboard storyboardWithName:[PCSTools shared].mainStoryboardName bundle:[PCSTools sdkBundle]];
  525. PCSBaseViewController *vc = (PCSBaseViewController *)[sb instantiateViewControllerWithIdentifier:@"sample"];
  526. vc.completeBlock = complete;
  527. return vc;
  528. }
  529. #pragma mark - Config param
  530. + (void)parser: (NSDictionary*)params{
  531. SDKParameters* sdkParams = [SDKParameters shared];
  532. NSString* retainedMode = params[@"dataRetainedMode"];
  533. if(retainedMode != nil){
  534. if([retainedMode isEqual:@"retain"]){
  535. sdkParams.retainedMode = SDK_DATA_RETAINED_RETAIN;
  536. }
  537. else if([retainedMode isEqual:@"clear"]){
  538. sdkParams.retainedMode = SDK_DATA_RETAINED_CLEAR;
  539. }
  540. }
  541. NSArray* arr = params[@"cameraMode"];
  542. NSDictionary<NSString*, NSNumber*>* table = @{
  543. @"continuous": @(SDK_CAPTURE_MODE_CONTINUOUS),
  544. @"single" : @(SDK_CAPTURE_MODE_SINGLE),
  545. @"video" : @(SDK_CAPTURE_MODE_MOVIE),
  546. @"panorama" : @(SDK_CAPTURE_MODE_PANORAMA),
  547. @"panoramaPlus" : @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  548. };
  549. NSMutableArray<NSNumber*>* modeIndiciesTable = [NSMutableArray array];
  550. NSMutableArray *mutabArray = [NSMutableArray array];
  551. [arr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  552. if ([obj isKindOfClass:[NSDictionary class]]) {
  553. NSDictionary *dict = (NSDictionary *)obj;
  554. NSString *mode = dict[@"mode"];
  555. if (!table[mode]) {
  556. return;
  557. }
  558. if (idx == 0) {
  559. sdkParams.modeIndex = (SDKCaptureModeIndex)table[mode].integerValue;
  560. }
  561. [modeIndiciesTable addObject:table[mode]];
  562. SDKParametersItem *item = [[SDKParametersItem alloc]init];
  563. NSString* cameraPosition = dict[@"type"];
  564. item.model = (SDKCaptureModeIndex)table[mode].integerValue;
  565. if(cameraPosition != nil){
  566. if([cameraPosition isEqual:@"back"]){
  567. item.cameraPosition = SDK_CAMERA_PISITION_BACK;
  568. item.cameraPositionString = cameraPosition;
  569. }
  570. else if([cameraPosition isEqual:@"front"]){
  571. item.cameraPosition = SDK_CAMERA_PISITION_FRONT;
  572. item.cameraPositionString = cameraPosition;
  573. }
  574. }
  575. NSNumber* recTime = dict[@"recTime"];
  576. if(recTime != nil){
  577. item.limitRecordTime = [recTime integerValue];
  578. }
  579. item.keyFrame = dict[@"keyframe"];
  580. item.isRemake = [dict[@"isRemake"] boolValue];
  581. NSNumber *quantity = dict[@"quantity"];
  582. if (quantity) {
  583. item.quantity = [quantity integerValue];
  584. }
  585. NSNumber *quality = dict[@"quality"];
  586. if (quality) {
  587. item.quality = [quality floatValue];
  588. }
  589. NSString* flashMode = dict[@"flashMode"];
  590. if(flashMode != nil){
  591. item.flashModeString = flashMode;
  592. if([flashMode isEqualToString:@"auto"]){
  593. item.flashMode = SDK_FLASH_MODE_AUTO;
  594. }
  595. else if([flashMode isEqualToString:@"on"]){
  596. item.flashMode = SDK_FLASH_MODE_ON;
  597. }
  598. else if([flashMode isEqualToString:@"off"]){
  599. item.flashMode = SDK_FLASH_MODE_OFF;
  600. }
  601. }
  602. NSNumber* videoQualityNum = dict[@"videoQuality"];
  603. if(videoQualityNum != nil){
  604. NSInteger videoQuality = [videoQualityNum integerValue];
  605. if(videoQuality == 480){
  606. item.videoQuality = SDK_VIDEO_QUALITY_480;
  607. }
  608. else if(videoQuality == 720){
  609. item.videoQuality = SDK_VIDEO_QUALITY_720;
  610. }
  611. else if(videoQuality == 1080){
  612. item.videoQuality = SDK_VIDEO_QUALITY_1080;
  613. }
  614. else if(videoQuality == 2160){
  615. item.videoQuality = SDK_VIDEO_QUALITY_2160;
  616. }
  617. }
  618. NSNumber* showPreviewForPanorama = dict[@"showPreview"];
  619. if(showPreviewForPanorama != nil){
  620. item.showPreviewForPanorama = [showPreviewForPanorama boolValue];
  621. }
  622. [mutabArray addObject:item];
  623. }
  624. }];
  625. sdkParams.modeIndices = [modeIndiciesTable copy];
  626. [SDKParameters shared].items = mutabArray;
  627. }
  628. // 拍照界面
  629. - (void)showPreviewView: (BOOL)show{
  630. self.previewLayer.hidden = !show;
  631. self.takePhotoButton.enabled = show;
  632. self.resultImageView.hidden = show;
  633. self.backButton.hidden = !show;
  634. self.flashButton.hidden = !show;
  635. self.switchButton.hidden = !show;
  636. self.discardPhotoButton.hidden = show;
  637. self.savePhotoButton.hidden = show;
  638. }
  639. - (void)setup{
  640. // 打开数据库
  641. [[LenzDBManager shared] openSqlDataBase];
  642. [LenzDataManager creatDirectory];
  643. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  644. [[PCSTools shared] cleanDiskCache];
  645. });
  646. _mode = SDK_CAPTURE_MODE_CONTINUOUS;
  647. _captureSession = [[AVCaptureSession alloc] init];
  648. _captureSession.sessionPreset = AVCaptureSessionPresetInputPriority;
  649. _movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
  650. // _movieFileOutput.maxRecordedDuration = CMTimeMake(self.parameters.limitRecordTime, 1);
  651. // setup video data output for panoramic
  652. _videoDataQueue = dispatch_queue_create("video data", DISPATCH_QUEUE_SERIAL);
  653. _videoDataOutput = [[AVCaptureVideoDataOutput alloc] init];
  654. _videoDataOutput.alwaysDiscardsLateVideoFrames = YES;
  655. _videoDataOutput.videoSettings = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:kCVPixelFormatType_32BGRA]
  656. forKey:(id)kCVPixelBufferPixelFormatTypeKey];
  657. _photoOutput = [[AVCapturePhotoOutput alloc] init];
  658. NSDictionary *setDic = @{AVVideoCodecKey:AVVideoCodecTypeJPEG};
  659. _outputSettings = [AVCapturePhotoSettings photoSettingsWithFormat:setDic];
  660. [_photoOutput setPhotoSettingsForSceneMonitoring:_outputSettings];
  661. _previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:self.captureSession];
  662. _previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  663. NSMutableArray* nodesArr = [NSMutableArray array];
  664. NSMutableDictionary* nodesDic = [NSMutableDictionary dictionary];
  665. __block SDKCaptureModeIndex defaultModeIndex = SDK_CAPTURE_MODE_CONTINUOUS;
  666. NSDictionary<NSNumber*, Class>* nodeClsTable = @{
  667. @(SDK_CAPTURE_MODE_CONTINUOUS): [OperationNodeMultiple class],
  668. @(SDK_CAPTURE_MODE_SINGLE): [OperationNodeSingle class],
  669. @(SDK_CAPTURE_MODE_MOVIE): [OperationNodeMovie class],
  670. @(SDK_CAPTURE_MODE_PANORAMA): [OperationNodePanorama class],
  671. @(SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA): [OperationNodeAIPanorama class],
  672. };
  673. [[SDKParameters shared].modeIndices enumerateObjectsUsingBlock:^(NSNumber * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  674. if (idx == 0) {
  675. defaultModeIndex = (SDKCaptureModeIndex)obj.integerValue;
  676. }
  677. if(nodeClsTable[obj] != nil){
  678. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && obj.intValue == SDK_CAPTURE_MODE_SINGLE) {
  679. self.isContainSingleInReatinMode = YES;
  680. return;
  681. } else {
  682. id node = [[nodeClsTable[obj] alloc] initWithController: self];
  683. if ([node isKindOfClass:[OperationNodeVideoBase class]]) {
  684. OperationNodeVideoBase *base = (OperationNodeVideoBase *)node;
  685. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  686. if (obj.model == self.mode) {
  687. base.recTime = obj.limitRecordTime;
  688. }
  689. }];
  690. }
  691. [nodesArr addObject: node];
  692. nodesDic[obj] = node;
  693. }
  694. }
  695. }];
  696. if ([SDKParameters shared].retainedMode == SDK_DATA_RETAINED_RETAIN && nodesArr.count == 0 && self.isContainSingleInReatinMode) {
  697. // reatin模式下只有single
  698. id node = [[OperationNodeSingle alloc] initWithController: self];
  699. [nodesArr addObject: node];
  700. nodesDic[@(SDK_CAPTURE_MODE_SINGLE)] = node;
  701. defaultModeIndex = SDK_CAPTURE_MODE_SINGLE;
  702. }
  703. [SDKParameters shared].modeIndex = defaultModeIndex;
  704. _operationNodesArray = [nodesArr copy];
  705. _operationNodes = [nodesDic copy];
  706. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
  707. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(willEnterBackground:) name:UIApplicationDidEnterBackgroundNotification object:nil];
  708. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationWillChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
  709. }
  710. - (void)startMotion {
  711. if (self.motionManager.deviceMotionAvailable) {
  712. __weak typeof(self)wearSelf = self;
  713. [self.motionManager startDeviceMotionUpdatesToQueue:[NSOperationQueue mainQueue] withHandler:^(CMDeviceMotion * _Nullable motion, NSError * _Nullable error) {
  714. if (!self.startPitchX && !self.startRollY) {
  715. self.startPitchX = @(motion.attitude.pitch * 100);
  716. self.startRollY = @(motion.attitude.roll *100);
  717. }
  718. double x = self.startPitchX.doubleValue - motion.attitude.pitch * 100;
  719. double y = self.startRollY.doubleValue - motion.attitude.roll * 100;
  720. LenVideoStitchDirction dir = (LenVideoStitchDirction)wearSelf.panoramOrientationGuideView.selectedItemIndex;
  721. if (dir == LenVideoStitchDirctionLeft || dir == LenVideoStitchDirctionRight) {
  722. if (fabs(x) < 3) {
  723. // NSLog(@"~~~~~~~~~~水平");
  724. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  725. } else {
  726. if (x > 0) {
  727. // NSLog(@"~~~~~~~~~~向下");
  728. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirDown dir:dir];
  729. } else {
  730. // NSLog(@"~~~~~~~~~~向上");
  731. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirUp dir:dir];
  732. }
  733. }
  734. } else if (dir == LenVideoStitchDirctionUp || dir == LenVideoStitchDirctionDown) {
  735. if (fabs(y) < 3) {
  736. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  737. } else {
  738. if (y > 0) {
  739. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirLeft dir:dir];
  740. } else {
  741. [wearSelf.panoramaGuideView updateArrowWith:PanoramaArrowDirRight dir:dir];
  742. }
  743. }
  744. }
  745. }];
  746. }
  747. }
  748. - (void)stopMotion {
  749. [self.motionManager stopDeviceMotionUpdates];
  750. self.startPitchX = nil;
  751. self.startRollY = nil;
  752. LenVideoStitchDirction dir = (LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex;
  753. [self.panoramaGuideView updateArrowWith:PanoramaArrowDirCenter dir:dir];
  754. }
  755. #pragma mark - Lazy Load
  756. - (BaseViewTapGestureDelegate *)tapDelegate{
  757. if(_tapDelegate == nil){
  758. _tapDelegate = [[BaseViewTapGestureDelegate alloc] init];
  759. _tapDelegate.controller = self;
  760. }
  761. return _tapDelegate;
  762. }
  763. - (AVCaptureDevice *)currentCamera{
  764. __block AVCaptureDevice* camera = nil;
  765. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  766. AVCaptureDeviceInput* inputDevice = obj;
  767. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  768. camera = inputDevice.device;
  769. *stop = YES;
  770. }
  771. }];
  772. return self.currentCameraInput.device;
  773. }
  774. - (AVCaptureDeviceInput*)currentCameraInput{
  775. __block AVCaptureDeviceInput* cameraInput = nil;
  776. [self.captureSession.inputs enumerateObjectsUsingBlock:^(__kindof AVCaptureInput * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  777. AVCaptureDeviceInput* inputDevice = obj;
  778. if([inputDevice.device hasMediaType:AVMediaTypeVideo]){
  779. cameraInput = inputDevice;
  780. *stop = YES;
  781. }
  782. }];
  783. return cameraInput;
  784. }
  785. - (SDKParameters *)parameters{
  786. return [SDKParameters shared];
  787. }
  788. #pragma mark - Action
  789. - (void)focusOn: (CGPoint)point{
  790. CGPoint pt = [self.previewLayer captureDevicePointOfInterestForPoint:point];
  791. AVCaptureDevice* curr = self.currentCamera;
  792. [[CameraManager shared] focusOn:pt device:curr];
  793. [self showFocusViewAt:point];
  794. }
  795. - (void)showFocusViewAt: (CGPoint)point{
  796. [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hideFocusView) object:nil];
  797. if(self.focusView == nil){
  798. UIImageView* imgView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 42, 42)];
  799. imgView.image = [UIImage sdkImageNamed:@"focus"];
  800. imgView.contentMode = UIViewContentModeScaleAspectFit;
  801. self.focusView = imgView;
  802. [self.view addSubview:self.focusView];
  803. }
  804. self.focusView.hidden = NO;
  805. CABasicAnimation* flash = [CABasicAnimation animationWithKeyPath:@"opacity"];
  806. flash.duration = 0.2;
  807. flash.fromValue = @(1);
  808. flash.toValue = @(0.1);
  809. flash.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
  810. flash.autoreverses = YES;
  811. flash.repeatCount = 3;
  812. [self.focusView.layer removeAnimationForKey:@"flash"];
  813. [self.focusView.layer addAnimation:flash forKey:@"flash"];
  814. self.focusView.frame = CGRectMake(point.x - 21, point.y - 21, 42, 42);
  815. [self performSelector:@selector(hideFocusView) withObject:nil afterDelay:3];
  816. }
  817. - (void)hideFocusView{
  818. [self.focusView.layer removeAnimationForKey:@"flash"];
  819. self.focusView.hidden = YES;
  820. }
  821. - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
  822. if(error != nil){
  823. return;
  824. }
  825. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  826. [self dismissViewControllerAnimated:YES completion:^{}];
  827. }
  828. else{
  829. [self startCaptureSession];
  830. [self showPreviewView:YES];
  831. }
  832. }
  833. - (AVCaptureVideoOrientation)videoOrientation{
  834. UIDeviceOrientation curr = UIDeviceOrientationUnknown;
  835. return [self videoOrientation:&curr];
  836. }
  837. - (AVCaptureVideoOrientation)videoOrientation:(UIDeviceOrientation*)currentDeviceOrientation{
  838. return [[PCSMotionManager shared] videoOrientation:currentDeviceOrientation];;
  839. }
  840. - (void)takeStillPhoto:(AVCaptureVideoPreviewLayer*)previewLayer {
  841. if ([self showAuthorCamerIfNeed]) {
  842. return;
  843. }
  844. AVCaptureConnection *connection = [self.photoOutput connectionWithMediaType:AVMediaTypeVideo];
  845. if ([connection isVideoStabilizationSupported]) {
  846. connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  847. }
  848. if(connection == nil){
  849. // [self showAlertForAuthorization];
  850. return;
  851. }
  852. if (connection.supportsVideoOrientation) {
  853. // 根据motion设置照片方向
  854. AVCaptureVideoOrientation videoOrientation = [self videoOrientation];
  855. connection.videoMirrored = self.currentCamera == [CameraManager shared].front;
  856. connection.videoOrientation = videoOrientation;
  857. }
  858. // 创建 AVCapturePhotoSettings
  859. AVCapturePhotoSettings *photoSettings = [AVCapturePhotoSettings photoSettings];
  860. if ([self.photoOutput.availablePhotoCodecTypes containsObject:AVVideoCodecTypeJPEG]) {
  861. NSDictionary *format = @{AVVideoCodecKey: AVVideoCodecTypeJPEG};
  862. photoSettings = [AVCapturePhotoSettings photoSettingsWithFormat:format];
  863. // NSLog(@"-----:%ld",(long)self.currentCameraInput.device.position);
  864. if (self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  865. photoSettings.flashMode = self.outputSettings.flashMode;
  866. }
  867. photoSettings.previewPhotoFormat = @{
  868. (NSString*)kCVPixelBufferPixelFormatTypeKey : photoSettings.availablePreviewPhotoPixelFormatTypes.firstObject,
  869. (NSString*)kCVPixelBufferWidthKey: @(160),
  870. (NSString*)kCVPixelBufferHeightKey: @(160),
  871. };
  872. }
  873. photoSettings.autoStillImageStabilizationEnabled = YES;
  874. // 拍照
  875. [self.photoOutput capturePhotoWithSettings:photoSettings delegate:self];
  876. }
  877. #pragma mark - Notification
  878. - (void)orientationWillChange: (NSNotification*)noti{
  879. NSLog(@"orientationWillChange");
  880. }
  881. - (void)willEnterForeground: (NSNotification*)noti{
  882. // if(self.broken){
  883. // [self.player play];
  884. // self.broken = NO;
  885. // }
  886. }
  887. //UIBackgroundTaskIdentifier _bgTaskToken;
  888. - (void)willEnterBackground: (NSNotification*)noti{
  889. if([self.currentOperationNode conformsToProtocol:@protocol(OperationNodeBackgroundProtocol)]){
  890. id<OperationNodeBackgroundProtocol> obj = self.currentOperationNode;
  891. if ([obj respondsToSelector:@selector(willEnterBackground:)]) {
  892. [obj willEnterBackground:noti];
  893. }
  894. }
  895. }
  896. - (void)orientationDidChange: (NSNotification*)noti{
  897. NSLog(@"orientationDidChange");
  898. if([self.currentOperationNode respondsToSelector:@selector(stop)])
  899. [self.currentOperationNode stop];
  900. }
  901. #pragma mark - alert
  902. - (void)showAlertForAuthorizationWithText: (NSString*)text{
  903. [QuitMultipleModeAlertViewController show:self title:@"" text:text leftBtnTitle:@"取消" rightBtnTitle:@"确认" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  904. [alertController dismissViewControllerAnimated:YES completion:^{
  905. // [self dismissViewControllerAnimated:YES completion:^{
  906. //
  907. // }];
  908. }];
  909. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  910. [alertController dismissViewControllerAnimated:YES completion:^{
  911. NSURL* url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
  912. if(url != nil){
  913. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:^(BOOL success) {
  914. // NSLog(succ)
  915. }];
  916. }
  917. }];
  918. }];
  919. }
  920. - (void)showAlertForAuthorization{
  921. [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  922. }
  923. - (BOOL)showAuthBoth {
  924. __block BOOL showVideoAlert = NO;
  925. AVAuthorizationStatus staus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  926. switch (staus) {
  927. case AVAuthorizationStatusDenied:{
  928. showVideoAlert = YES;
  929. break;
  930. }
  931. default:
  932. showVideoAlert = NO;
  933. break;
  934. }
  935. __block BOOL showAlert = NO;
  936. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  937. case AVAuthorizationStatusDenied:{
  938. showAlert = YES;
  939. break;
  940. }
  941. default:
  942. showAlert = NO;
  943. break;
  944. }
  945. if (showVideoAlert && showAlert) {
  946. [self.authView showAutherWith:PCSAuthPhoneAndMir];
  947. return YES;
  948. }
  949. return NO;
  950. }
  951. - (BOOL)showAuthorCamerIfNeed {
  952. __block BOOL showAlert = NO;
  953. AVAuthorizationStatus staus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
  954. switch (staus) {
  955. case AVAuthorizationStatusDenied:{
  956. [self.authView showAutherWith:PCSAuthPhone];
  957. // [self showAlertForAuthorizationWithText:@"请在系统设置里打开摄像机访问权限后重试"];
  958. showAlert = YES;
  959. break;
  960. }
  961. default:
  962. showAlert = NO;
  963. break;
  964. }
  965. return showAlert;
  966. }
  967. - (BOOL)showAudioCamerIfNeed {
  968. __block BOOL showAlert = NO;
  969. switch ([AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio]) {
  970. case AVAuthorizationStatusDenied:{
  971. [self.authView showAutherWith:PCSAuthMir];
  972. // [self showAlertForAuthorizationWithText:@"请在系统设置里打开麦克风访问权限后重试"];
  973. showAlert = YES;
  974. break;
  975. }
  976. default:
  977. showAlert = NO;
  978. break;
  979. }
  980. return showAlert;
  981. }
  982. #pragma mark - Capture
  983. - (void)takeStillPhoto{
  984. [self takeStillPhoto:self.previewLayer];
  985. }
  986. - (BOOL)startRecording{
  987. if (![self showAuthBoth]) {
  988. if ([self showAuthorCamerIfNeed] || [self showAudioCamerIfNeed]) {
  989. return NO;
  990. }
  991. } else {
  992. return NO;
  993. }
  994. if(self.movieFileOutput.isRecording){
  995. return NO;
  996. }
  997. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  998. if (obj.model == self.mode) {
  999. self.movieFileOutput.maxRecordedDuration = CMTimeMake(obj.limitRecordTime, 1);
  1000. }
  1001. }];
  1002. [self.recordTimer invalidate];
  1003. dispatch_async(dispatch_get_main_queue(), ^{
  1004. self.recordTimer = [NSTimer timerWithTimeInterval:0.2 repeats:YES block:^(NSTimer * _Nonnull timer) {
  1005. [self.timerLabel updateWith:self.movieFileOutput.recordedDuration.value / self.movieFileOutput.recordedDuration.timescale];
  1006. }];
  1007. [[NSRunLoop currentRunLoop] addTimer:self.recordTimer forMode:NSDefaultRunLoopMode];
  1008. });
  1009. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[LenzDataManager moviePath]];
  1010. AVCaptureConnection* connection = [self.movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
  1011. if ([connection isVideoStabilizationSupported]) {
  1012. connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  1013. }
  1014. if(connection == nil){
  1015. // [self showAlertForAuthorization];
  1016. return NO;
  1017. }
  1018. UIDeviceOrientation currOrientation = UIDeviceOrientationUnknown;
  1019. connection.videoOrientation = [self videoOrientation:&currOrientation];
  1020. AVCaptureDevice* camera = self.currentCamera;
  1021. [camera lockForConfiguration:nil];
  1022. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  1023. if (self.outputSettings.flashMode == AVCaptureFlashModeOff) {
  1024. [camera setTorchMode:AVCaptureTorchModeOff];
  1025. } else if (self.outputSettings.flashMode == AVCaptureFlashModeOn) {
  1026. [camera setTorchMode:AVCaptureTorchModeOn];
  1027. } else {
  1028. [camera setTorchMode:AVCaptureTorchModeAuto];
  1029. }
  1030. }
  1031. [camera unlockForConfiguration];
  1032. self.thumbnailOritaionByCurrentVideoOrientation = [UIImage imageOrientationByDeviceOrientation:currOrientation isFrontCamera:camera == [CameraManager shared].front];
  1033. [self.movieFileOutput startRecordingToOutputFileURL: tmpMovieFileUrl recordingDelegate:self];
  1034. return YES;
  1035. }
  1036. - (void)stopRecording{
  1037. [self.movieFileOutput stopRecording];
  1038. AVCaptureDevice* camera = self.currentCamera;
  1039. [camera lockForConfiguration:nil];
  1040. if ([camera hasFlash] && self.currentCameraInput.device.position == SDK_CAMERA_PISITION_BACK) {
  1041. [camera setTorchMode:AVCaptureTorchModeOff];
  1042. }
  1043. [camera unlockForConfiguration];
  1044. [self.recordTimer invalidate];
  1045. self.recordTimer = nil;
  1046. }
  1047. - (BOOL)startVideoDataOutputing{
  1048. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1049. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:PCS_NotificationNameOrientationDidChange object:nil];
  1050. UIDeviceOrientation deviceOrientation = UIDeviceOrientationPortrait;
  1051. AVCaptureVideoOrientation orientation = [self videoOrientation:&deviceOrientation];
  1052. CGFloat degree = 0;
  1053. AVCaptureDevice* camera = self.currentCamera;
  1054. CameraManager* cameraMgr = [CameraManager shared];
  1055. BOOL isFront = camera == cameraMgr.front;
  1056. BOOL isLandscape = NO;
  1057. // 前摄像头需要镜像一下
  1058. switch (deviceOrientation) {
  1059. case UIDeviceOrientationPortrait:
  1060. degree = 0;
  1061. break;
  1062. case UIDeviceOrientationLandscapeRight:
  1063. degree = isFront ? 90 : -90;
  1064. isLandscape = YES;
  1065. break;
  1066. case UIDeviceOrientationPortraitUpsideDown:
  1067. degree = 180;
  1068. break;
  1069. case UIDeviceOrientationLandscapeLeft:
  1070. degree = isFront ? -90 : 90;
  1071. isLandscape = YES;
  1072. break;
  1073. default:
  1074. break;
  1075. }
  1076. __block BOOL ret = NO;
  1077. dispatch_sync(self.videoDataQueue, ^{
  1078. if(self.videoDataOutput.sampleBufferDelegate != nil){
  1079. return;
  1080. }
  1081. if([self configureVideoWritter]){
  1082. AVCaptureConnection *connection = [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo];
  1083. if ([connection isVideoStabilizationSupported]) {
  1084. connection.preferredVideoStabilizationMode = AVCaptureVideoStabilizationModeAuto;
  1085. }
  1086. if(connection == nil){
  1087. // [self showAlertForAuthorization];
  1088. return;
  1089. }
  1090. [connection setVideoOrientation:orientation];
  1091. CGFloat aspect = isFront ? cameraMgr.frontAspect : cameraMgr.backAspect;
  1092. aspect = isLandscape ? 1.0 / aspect : aspect;
  1093. [self.videoDataOutput setSampleBufferDelegate:self queue:self.videoDataQueue];
  1094. ret = YES;
  1095. }
  1096. });
  1097. return ret;
  1098. }
  1099. - (PanoramaGuideView *)panoramaGuideView{
  1100. if (_panoramaGuideView == nil) {
  1101. _panoramaGuideView = [[PanoramaGuideView alloc]init];
  1102. _panoramaGuideView.hidden = YES;
  1103. }
  1104. return _panoramaGuideView;;
  1105. }
  1106. - (void)stopVideoDataOutputing{
  1107. [self.motionTimer invalidate];
  1108. self.motionTimer = nil;
  1109. [[NSNotificationCenter defaultCenter] removeObserver:self name:PCS_NotificationNameOrientationDidChange object:nil];
  1110. dispatch_async(self.videoDataQueue, ^{
  1111. [self.videoDataOutput setSampleBufferDelegate:nil queue:nil];
  1112. [Renderer shared].cameraPass.texture = nil;
  1113. });
  1114. [self stopMotion];
  1115. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  1116. [self updateViewStatus];
  1117. }
  1118. - (void)updateViewStatusWhenStitchSave:(BOOL)isSaveIng {
  1119. dispatch_async(dispatch_get_main_queue(), ^{
  1120. self.stitchView.hidden = !isSaveIng;
  1121. if (self.stitchView.hidden) {
  1122. [self.stitchImageView.layer removeAnimationForKey:@"loadingAnimation"];
  1123. } else {
  1124. [self.stitchImageView.layer addAnimation:self.loadingAnimation forKey:@"loadingAnimation"];
  1125. }
  1126. self.flashButton.hidden = isSaveIng;
  1127. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1128. self.panoramOrientationGuideView.hidden = YES;
  1129. self.ai_fullView.hidden = YES;
  1130. self.panoramaGuideView.hidden = YES;
  1131. } else {
  1132. self.panoramOrientationGuideView.hidden = isSaveIng;
  1133. // self.ai_fullView.hidden = isSaveIng;
  1134. self.ai_fullView.hidden = YES;
  1135. self.panoramaGuideView.hidden = isSaveIng;
  1136. }
  1137. self.modeList.hidden = isSaveIng;
  1138. self.savePhotoButton.hidden = isSaveIng;
  1139. self.takePhotoButton.hidden = isSaveIng;
  1140. // self.switchButton.hidden = isSaveIng;
  1141. self.discardPhotoButton.hidden = isSaveIng;
  1142. self.backButton.hidden = !isSaveIng;
  1143. self.ablumImageView.hidden = isSaveIng;
  1144. // self.timerLabel.hidden = isSaveIng;
  1145. });
  1146. }
  1147. - (void)updateViewStatusWhenStitchFail {
  1148. dispatch_async(dispatch_get_main_queue(), ^{
  1149. self.stitchView.hidden = YES;
  1150. self.flashButton.hidden = NO;
  1151. self.modeList.hidden = NO;
  1152. self.savePhotoButton.hidden = NO;
  1153. self.takePhotoButton.hidden = NO;
  1154. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1155. self.ai_fullView.hidden = YES;
  1156. self.panoramOrientationGuideView.hidden = YES;
  1157. self.panoramaGuideView.hidden = YES;
  1158. } else {
  1159. // self.ai_fullView.hidden = NO;
  1160. self.ai_fullView.hidden = YES;
  1161. self.panoramOrientationGuideView.hidden = NO;
  1162. self.panoramaGuideView.hidden = NO;
  1163. }
  1164. // self.switchButton.hidden = isSaveIng;
  1165. self.discardPhotoButton.hidden = NO;
  1166. self.backButton.hidden = YES;
  1167. self.ablumImageView.hidden = NO;
  1168. [self.takePhotoButton setImage:[UIImage loadNamed:@"take-photo-btn"] forState:UIControlStateNormal];
  1169. // self.timerLabel.hidden = isSaveIng;
  1170. });
  1171. }
  1172. - (BOOL)getStitchBigImageIfNeed {
  1173. BOOL isSuccess = NO;
  1174. NSString *s = [LenStitcher getCurrentPanoramaShow];
  1175. if (s.length) {
  1176. isSuccess = YES;
  1177. }
  1178. return isSuccess;
  1179. }
  1180. - (BOOL)configureVideoWritter{
  1181. // setup asset writter for the video data output
  1182. NSURL* tmpMovieFileUrl = [NSURL fileURLWithPath:[[PCSTools shared].tmpPath stringByAppendingPathComponent:@"video-data-tmp-file.mov"] isDirectory:NO];
  1183. NSError* err = nil;
  1184. [[NSFileManager defaultManager] removeItemAtURL:tmpMovieFileUrl error:nil];
  1185. self.videoWriter = [[AVAssetWriter alloc] initWithURL:tmpMovieFileUrl fileType:AVFileTypeQuickTimeMovie error:&err];
  1186. if(err != nil){
  1187. NSLog(@"%@", err);
  1188. self.videoWriter = nil;
  1189. return NO;
  1190. }
  1191. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1192. if (obj.model == self.mode) {
  1193. NSDictionary* settings = [NSDictionary dictionaryWithObjectsAndKeys:
  1194. AVVideoCodecTypeH264, AVVideoCodecKey,
  1195. [NSNumber numberWithInteger: obj.resolution.width], AVVideoWidthKey,
  1196. [NSNumber numberWithInteger: obj.resolution.height], AVVideoHeightKey,
  1197. nil];
  1198. self.videoWriterInput = [AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo outputSettings:settings];
  1199. }
  1200. }];
  1201. self.videoWriterInput.expectsMediaDataInRealTime = YES;
  1202. [self.videoWriter addInput:self.videoWriterInput];
  1203. return YES;
  1204. }
  1205. - (void)prepareCamera{
  1206. if (self.cameraPrepared) {
  1207. return;
  1208. }
  1209. __block AVCaptureDevice* device = nil;
  1210. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1211. if (obj.model == self.mode) {
  1212. device = obj.cameraPosition == SDK_CAMERA_PISITION_BACK ? [CameraManager shared].back : [CameraManager shared].front;
  1213. }
  1214. }];
  1215. if (device == nil) {
  1216. self.cameraPrepared = false;
  1217. return;
  1218. }
  1219. NSError* error;
  1220. AVCaptureDeviceInput* input = [[AVCaptureDeviceInput alloc] initWithDevice:device error:&error];
  1221. if(error != nil){
  1222. self.cameraPrepared = false;
  1223. return;
  1224. }
  1225. [self.captureSession beginConfiguration];
  1226. if([self.captureSession canAddInput:input]){
  1227. [self.captureSession addInput:input];
  1228. }
  1229. else{
  1230. return;
  1231. }
  1232. self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
  1233. self.previewLayer.frame = self.view.layer.bounds;
  1234. self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
  1235. [self.view.layer insertSublayer:self.previewLayer atIndex:0u];
  1236. if([self.captureSession canAddOutput:self.photoOutput]){
  1237. [self.captureSession addOutput:self.photoOutput];
  1238. }
  1239. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1240. [self.captureSession addOutput:self.movieFileOutput];
  1241. }
  1242. [self.captureSession commitConfiguration];
  1243. self.cameraPrepared = YES;
  1244. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1245. if (obj.model == self.mode) {
  1246. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height];
  1247. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height];
  1248. }
  1249. }];
  1250. [self updatePreViewLayer];
  1251. }
  1252. #pragma mark - Gesture
  1253. - (void)tapGestureHandler: (UITapGestureRecognizer*)gesture{
  1254. switch(gesture.state){
  1255. case UIGestureRecognizerStateBegan:{
  1256. break;
  1257. }
  1258. case UIGestureRecognizerStateChanged:{
  1259. break;
  1260. }
  1261. case UIGestureRecognizerStateEnded:{
  1262. CGPoint pt = [gesture locationInView:self.view];
  1263. [self focusOn:pt];
  1264. break;
  1265. }
  1266. case UIGestureRecognizerStateCancelled:{
  1267. break;
  1268. }
  1269. default:
  1270. break;
  1271. }
  1272. }
  1273. - (void)panGestureHandler: (UIPanGestureRecognizer*)gesture{
  1274. switch(gesture.state){
  1275. case UIGestureRecognizerStateBegan:{
  1276. break;
  1277. }
  1278. case UIGestureRecognizerStateChanged:{
  1279. if(self.flag){
  1280. return;
  1281. }
  1282. self.flag = YES;
  1283. CGPoint translation = [gesture translationInView:self.view];
  1284. [self.modeList updateIndexByTanslation:translation];
  1285. break;
  1286. }
  1287. case UIGestureRecognizerStateEnded:{
  1288. self.flag = NO;
  1289. break;
  1290. }
  1291. case UIGestureRecognizerStateCancelled:{
  1292. self.flag = NO;
  1293. break;
  1294. }
  1295. default:
  1296. self.flag = NO;
  1297. break;
  1298. }
  1299. }
  1300. #pragma mark - orientation
  1301. - (UIInterfaceOrientationMask)supportedInterfaceOrientations{
  1302. return UIInterfaceOrientationMaskPortrait;
  1303. }
  1304. - (void)updateUIByMode{
  1305. self.albumButton.hidden = YES;
  1306. self.numberOfImagesLabel.hidden = YES;
  1307. self.modeLabel.text = self.currentOperationNode.modeTitleString;
  1308. // self.ai_fullView.hidden = !(self.mode == SDK_CAPTURE_MODE_PANORAMA);
  1309. self.ai_fullView.hidden = YES;
  1310. self.panGesture.enabled = YES;
  1311. // self.controller.savePhotoButton.hidden = !self.hasCache;
  1312. // self.controller.discardPhotoButton.hidden = !self.hasCache;
  1313. //
  1314. // self.controller.albumButton.hidden = !self.hasCache;
  1315. // self.controller.backButton.hidden = self.hasCache;
  1316. if([self.currentOperationNode respondsToSelector:@selector(updateUI)]){
  1317. [self.currentOperationNode updateUI];
  1318. }
  1319. [self updatePreViewLayer];
  1320. }
  1321. - (void)updatePreViewLayer {
  1322. CGFloat width = [UIScreen mainScreen].bounds.size.width;
  1323. CGFloat height = [UIScreen mainScreen].bounds.size.height;
  1324. switch (self.mode) {
  1325. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1326. self.switchButton.hidden = NO;
  1327. self.panoramaGuideView.hidden = YES;
  1328. self.panoramOrientationGuideView.hidden = YES;
  1329. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1330. [self showAuthorCamerIfNeed];
  1331. }
  1332. break;
  1333. case SDK_CAPTURE_MODE_SINGLE: {
  1334. self.switchButton.hidden = NO;
  1335. self.panoramaGuideView.hidden = YES;
  1336. self.panoramOrientationGuideView.hidden = YES;
  1337. self.previewLayer.frame = CGRectMake(0, (height - width*4/3)/2, width, width*4/3);
  1338. [self showAuthorCamerIfNeed];
  1339. }
  1340. break;
  1341. case SDK_CAPTURE_MODE_MOVIE: {
  1342. self.switchButton.hidden = NO;
  1343. self.panoramaGuideView.hidden = YES;
  1344. self.panoramOrientationGuideView.hidden = YES;
  1345. self.previewLayer.frame = self.view.layer.bounds;
  1346. if (![self showAuthBoth]) {
  1347. [self showAudioCamerIfNeed];
  1348. }
  1349. }
  1350. break;
  1351. case SDK_CAPTURE_MODE_PANORAMA: {
  1352. self.switchButton.hidden = YES;
  1353. self.panoramaGuideView.hidden = NO;
  1354. self.panoramOrientationGuideView.hidden = NO;
  1355. self.previewLayer.frame = self.view.layer.bounds;
  1356. [self showAuthorCamerIfNeed];
  1357. }
  1358. break;
  1359. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1360. self.switchButton.hidden = YES;
  1361. self.panoramaGuideView.hidden = YES;
  1362. self.panoramOrientationGuideView.hidden = YES;
  1363. self.previewLayer.frame = self.view.layer.bounds;
  1364. [self showAuthorCamerIfNeed];
  1365. }
  1366. break;
  1367. default:
  1368. break;
  1369. }
  1370. }
  1371. - (void)modeWillChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1372. if(newIndex >= INT_MAX){
  1373. return;
  1374. }
  1375. [self.currentOperationNode willQuitOnCompletion:^() {}];
  1376. }
  1377. - (void)modeDidChange: (NSUInteger)newIndex oldIndex: (NSUInteger)oldIndex{
  1378. if(newIndex >= INT_MAX){
  1379. return;
  1380. }
  1381. // self.modeList.userInteractionEnabled = NO;
  1382. // [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]
  1383. if(self.effectView.superview != nil){
  1384. // self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1385. [UIView animateWithDuration:0.5 animations:^{
  1386. self.effectView.effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
  1387. }];
  1388. }
  1389. // dispatch_async(dispatch_get_global_queue(0, 0), ^{
  1390. if(newIndex != SDK_CAPTURE_MODE_MOVIE){
  1391. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1392. if (obj.model == self.mode) {
  1393. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.resolution.height];
  1394. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.resolution.height];
  1395. }
  1396. }];
  1397. }
  1398. else{
  1399. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1400. if (obj.model == self.mode) {
  1401. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionBack with:obj.videoResolution.height];
  1402. [[CameraManager shared] setResolutionFor:AVCaptureDevicePositionFront with:obj.videoResolution.height];
  1403. }
  1404. }];
  1405. }
  1406. // dispatch_sync(dispatch_get_main_queue(), ^{
  1407. // self.modeList.userInteractionEnabled = YES;
  1408. self.effectView.effect = nil;
  1409. // });
  1410. // });
  1411. [self updateUIByMode];
  1412. [self switchDevicePositionBack];
  1413. [self updateNumberLabel];
  1414. }
  1415. - (void)updateCaptureSessionWith:(NSInteger)oldIndex {
  1416. PhotographModeEnum oldModeEnum = (PhotographModeEnum)(oldIndex);
  1417. if((self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)
  1418. && oldModeEnum != SDK_CAPTURE_MODE_PANORAMA
  1419. && oldModeEnum != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA){
  1420. if([self.captureSession canAddOutput:self.videoDataOutput]){
  1421. [self.captureSession addOutput:self.videoDataOutput];
  1422. [self.captureSession removeOutput:self.movieFileOutput];
  1423. }
  1424. }
  1425. else if((self.mode == SDK_CAPTURE_MODE_MOVIE)
  1426. && (oldModeEnum == SDK_CAPTURE_MODE_PANORAMA
  1427. || oldModeEnum == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1428. if([self.captureSession canAddOutput:self.movieFileOutput]){
  1429. [self.captureSession addOutput:self.movieFileOutput];
  1430. [self.captureSession removeOutput:self.videoDataOutput];
  1431. }
  1432. }
  1433. }
  1434. - (void)setupMicrophone{
  1435. NSError* audioError = nil;
  1436. AVCaptureDevice* audioDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
  1437. AVCaptureDeviceInput* audioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&audioError];
  1438. if(audioError == nil){
  1439. AVCaptureAudioDataOutput* audioOutput = [[AVCaptureAudioDataOutput alloc] init];
  1440. [audioOutput setSampleBufferDelegate:self queue:dispatch_get_global_queue(0, 0)];
  1441. if([self.captureSession canAddInput:audioInput]){
  1442. [self.captureSession addInput:audioInput];
  1443. }
  1444. if([self.captureSession canAddOutput:audioOutput]){
  1445. [self.captureSession addOutput:audioOutput];
  1446. }
  1447. }
  1448. }
  1449. - (UIStatusBarStyle)preferredStatusBarStyle{
  1450. return UIStatusBarStyleLightContent;
  1451. }
  1452. #pragma mark 方向调用的代理
  1453. - (void)panoramaOrientationViewslt:(PanoramaOrientationViewDirectionEnum)direction{
  1454. // NSLog(@"方向%ld",direction);
  1455. self.panoramaGuideView.hidden = NO;
  1456. // self.ai_fullView.hidden = NO;
  1457. // [LenStitcher videoResetPath];
  1458. [UIView animateWithDuration:0.25 animations:^{
  1459. [self.panoramaGuideView mas_remakeConstraints:^(MASConstraintMaker *make) {
  1460. switch (direction) {
  1461. case PanoramaOrientationViewLeft:
  1462. case PanoramaOrientationViewRight:
  1463. {
  1464. make.left.right.offset(0);
  1465. make.centerY.mas_equalTo(self.view);
  1466. make.height.mas_equalTo(PanoramaGuideViewWOrH);
  1467. }
  1468. break;
  1469. case PanoramaOrientationViewUp:
  1470. case PanoramaOrientationViewDown:
  1471. {
  1472. make.centerX.mas_equalTo(self.view);
  1473. make.width.mas_equalTo(PanoramaGuideViewWOrH);
  1474. make.bottom.mas_equalTo(self.panoramOrientationGuideView.mas_top).offset(-25);
  1475. make.top.mas_equalTo(self.timerLabel.mas_bottom).offset(15);
  1476. }
  1477. break;
  1478. case PanoramaOrientationViewAny: {
  1479. self.panoramaGuideView.hidden = YES;
  1480. // self.ai_fullView.hidden = YES;
  1481. }
  1482. break;
  1483. default:
  1484. break;
  1485. }
  1486. }];
  1487. if (self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1488. [self.panoramaGuideView setNeedsLayout];
  1489. [self.panoramaGuideView layoutIfNeeded];
  1490. }
  1491. } completion:^(BOOL finished) {
  1492. [self.panoramaGuideView direction:direction];
  1493. }];
  1494. }
  1495. - (void)stopAllSensors{
  1496. [self.captureSession stopRunning];
  1497. [[PCSMotionManager shared] stopAccelerometerUpdates];
  1498. }
  1499. #pragma mark - session
  1500. - (void)turnTorchOff{
  1501. AVCaptureDevice* currentDevice = self.currentCamera;
  1502. if(currentDevice == nil || !currentDevice.hasTorch){
  1503. return;
  1504. }
  1505. NSError* error;
  1506. if(error == nil){
  1507. [currentDevice lockForConfiguration:&error];
  1508. currentDevice.torchMode = AVCaptureTorchModeOff;
  1509. [currentDevice unlockForConfiguration];
  1510. }
  1511. }
  1512. - (void)stopCaptureSession{
  1513. [self turnTorchOff];
  1514. if (self.captureSession.isRunning) {
  1515. [self.captureSession stopRunning];
  1516. }
  1517. }
  1518. - (void)startCaptureSession{
  1519. if (!self.cameraPrepared) {
  1520. [self prepareCamera];
  1521. }
  1522. if (self.cameraPrepared && (!self.captureSession.isRunning)) {
  1523. [self.captureSession startRunning];
  1524. }
  1525. }
  1526. #pragma mark - Btn call back
  1527. -(IBAction)switchCameraTapped:(id)sender
  1528. {
  1529. if(self.captureSession == nil){
  1530. return;
  1531. }
  1532. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1533. if(currInput == nil){
  1534. return;
  1535. }
  1536. AVCaptureDevice* currentDevice = currInput.device;
  1537. AVCaptureDevice *newCamera = nil;
  1538. if(currentDevice.position == AVCaptureDevicePositionBack){
  1539. newCamera = [CameraManager shared].front;
  1540. }
  1541. else if(currentDevice.position == AVCaptureDevicePositionFront){
  1542. newCamera = [CameraManager shared].back;
  1543. }
  1544. else{
  1545. return;
  1546. }
  1547. [self.captureSession beginConfiguration];
  1548. if(currentDevice.hasTorch){
  1549. NSError* error;
  1550. [currentDevice lockForConfiguration:&error];
  1551. currentDevice.torchMode = AVCaptureTorchModeOff;
  1552. [currentDevice unlockForConfiguration];
  1553. }
  1554. [self.captureSession removeInput:currInput];
  1555. self.flashButton.hidden = !newCamera.hasFlash;
  1556. NSError *err = nil;
  1557. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1558. if(newVideoInput == nil || err != nil){
  1559. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1560. }
  1561. else if([self.captureSession canAddInput:newVideoInput]){
  1562. [self.captureSession addInput:newVideoInput];
  1563. }
  1564. [self.captureSession commitConfiguration];
  1565. }
  1566. - (void)switchDevicePositionBack {
  1567. if(self.captureSession == nil ||
  1568. (self.mode != SDK_CAPTURE_MODE_PANORAMA && self.mode != SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)){
  1569. return;
  1570. }
  1571. AVCaptureDeviceInput* currInput = self.currentCameraInput;
  1572. if(currInput == nil){
  1573. return;
  1574. }
  1575. AVCaptureDevice* currentDevice = currInput.device;
  1576. AVCaptureDevice *newCamera = nil;
  1577. if(currentDevice.position == AVCaptureDevicePositionBack){
  1578. return;
  1579. }
  1580. if(currentDevice.position == AVCaptureDevicePositionFront){
  1581. newCamera = [CameraManager shared].back;
  1582. }
  1583. [self.captureSession beginConfiguration];
  1584. if(currentDevice.hasTorch){
  1585. NSError* error;
  1586. [currentDevice lockForConfiguration:&error];
  1587. currentDevice.torchMode = AVCaptureTorchModeOff;
  1588. [currentDevice unlockForConfiguration];
  1589. }
  1590. [self.captureSession removeInput:currInput];
  1591. NSError *err = nil;
  1592. AVCaptureDeviceInput *newVideoInput = [[AVCaptureDeviceInput alloc] initWithDevice:newCamera error:&err];
  1593. if(newVideoInput == nil || err != nil){
  1594. NSLog(@"Error creating capture device input: %@", err.localizedDescription);
  1595. } else if([self.captureSession canAddInput:newVideoInput]){
  1596. [self.captureSession addInput:newVideoInput];
  1597. }
  1598. [self.captureSession commitConfiguration];
  1599. }
  1600. - (void)takePhotoButtonTouchUpInside:(id)sender{
  1601. self.takePhotoButton.enabled = NO;
  1602. if (self.outputSettings.flashMode == AVCaptureFlashModeOn && (self.mode == SDK_CAPTURE_MODE_SINGLE || self.mode == SDK_CAPTURE_MODE_CONTINUOUS || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA)) {
  1603. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  1604. self.takePhotoButton.enabled = YES;
  1605. });
  1606. } else {
  1607. dispatch_async(dispatch_get_main_queue(), ^{
  1608. self.takePhotoButton.enabled = YES;
  1609. });
  1610. }
  1611. if(![self.currentOperationNode respondsToSelector:@selector(enable)] || self.currentOperationNode.enable){
  1612. if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1613. __block SDKParametersItem *videoItems = nil;
  1614. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1615. if (obj.model == self.mode) {
  1616. videoItems = obj;
  1617. }
  1618. }];
  1619. if (videoItems.quantity > 0 && self.resourceModel.movieArray.count >= videoItems.quantity) {
  1620. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:[NSString stringWithFormat:@"最多录制%ld条视频", videoItems.quantity]];
  1621. return;
  1622. }
  1623. }
  1624. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1625. OperationNodeAIPanorama *aiPan = nil;
  1626. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1627. aiPan = self.currentOperationNode;
  1628. if (!aiPan.isRecording) {
  1629. aiPan.AIType = OperationAITypeTap;
  1630. }
  1631. }
  1632. }
  1633. [self.currentOperationNode takePhotoButtonTouched];
  1634. if (self.mode == SDK_CAPTURE_MODE_PANORAMA && !self.isVideoStitchStopedWhenRecording) {
  1635. [LenStitcher videoResetPath];
  1636. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1637. [self.resourceModel.panoramArray addObject:itemModel];
  1638. [self startMotion];
  1639. }
  1640. }
  1641. }
  1642. - (void)longPressGes:(UILongPressGestureRecognizer *)ges {
  1643. switch (ges.state) {
  1644. case UIGestureRecognizerStateBegan:
  1645. {
  1646. if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1647. OperationNodeAIPanorama *aiPan = nil;
  1648. if ([self.currentOperationNode isKindOfClass:[OperationNodeAIPanorama class]]) {
  1649. // self.videoStitchSemaphore = dispatch_semaphore_create(1);
  1650. [LenStitcher videoResetPath];
  1651. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1652. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1653. [self startMotion];
  1654. aiPan = self.currentOperationNode;
  1655. // self.touchTime = 0;
  1656. aiPan.AIType = OperationAITypeLongPress;
  1657. [self.currentOperationNode takePhotoButtonTouched];
  1658. }
  1659. }
  1660. }
  1661. break;
  1662. case UIGestureRecognizerStateEnded:
  1663. break;
  1664. default:
  1665. break;
  1666. }
  1667. }
  1668. - (void)takePhotoButtonTouchDownInside:(id)sender{
  1669. }
  1670. - (void)flashButtonTouchUpInside:(id)sender{
  1671. AVCaptureDevice* currentDevice = self.currentCamera;
  1672. if(currentDevice == nil || !currentDevice.hasFlash){
  1673. return;
  1674. }
  1675. NSError* error = nil;
  1676. [currentDevice lockForConfiguration:&error];
  1677. if(error != nil){
  1678. return;
  1679. }
  1680. if(self.outputSettings.flashMode == AVCaptureFlashModeOn){
  1681. self.outputSettings.flashMode = AVCaptureFlashModeAuto;
  1682. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-auto-btn"] forState:UIControlStateNormal];
  1683. }
  1684. else if(self.outputSettings.flashMode == AVCaptureFlashModeAuto){
  1685. self.outputSettings.flashMode = AVCaptureFlashModeOff;
  1686. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-disable-btn"] forState:UIControlStateNormal];
  1687. }
  1688. else{
  1689. self.outputSettings.flashMode = AVCaptureFlashModeOn;
  1690. [self.flashButton setImage:[UIImage sdkImageNamed:@"flash-btn"] forState:UIControlStateNormal];
  1691. }
  1692. [currentDevice unlockForConfiguration];
  1693. }
  1694. - (void)backButtonTouchUpInside:(id)sender{
  1695. if (!self.stitchView.hidden) {
  1696. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"图片拼接中,返回会清空正在拼接的数据" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1697. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1698. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1699. [self updateViewStatusWhenStitchSave:NO];
  1700. [alertController dismissViewControllerAnimated:NO completion:^{
  1701. // [self dismissViewControllerAnimated:YES completion:^{}];
  1702. }];
  1703. }];
  1704. } else {
  1705. [self dismissViewControllerAnimated:YES completion:^{}];
  1706. }
  1707. }
  1708. - (void)makeResData:(NSMutableArray <LenzResourceItemModel *> *)array {
  1709. [array enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1710. }];
  1711. }
  1712. - (void)savePhotoButtonTouchUpInside:(id)sender{
  1713. //待优化
  1714. NSMutableArray *res = [NSMutableArray array];
  1715. __block NSInteger idIndex = 1;
  1716. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1717. idIndex += idx;
  1718. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1719. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1720. dict[@"path"] = obj.path;
  1721. dict[@"cameraMode"] = obj.cameraMode;
  1722. dict[@"cameraType"] = obj.cameraType;
  1723. dict[@"isRemake"] = @(obj.isRemake);
  1724. [res addObject:dict];
  1725. }];
  1726. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1727. idIndex += idx;
  1728. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1729. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1730. dict[@"path"] = obj.path;
  1731. dict[@"cameraMode"] = obj.cameraMode;
  1732. dict[@"cameraType"] = obj.cameraType;
  1733. dict[@"isRemake"] = @(obj.isRemake);
  1734. [res addObject:dict];
  1735. }];
  1736. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1737. idIndex += idx;
  1738. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1739. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1740. dict[@"path"] = obj.path;
  1741. dict[@"cameraMode"] = obj.cameraMode;
  1742. dict[@"cameraType"] = obj.cameraType;
  1743. dict[@"isRemake"] = @(obj.isRemake);
  1744. [res addObject:dict];
  1745. }];
  1746. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1747. if (obj.path.length) {
  1748. idIndex += idx;
  1749. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1750. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1751. dict[@"path"] = obj.path;
  1752. dict[@"cameraMode"] = obj.cameraMode;
  1753. dict[@"cameraType"] = obj.cameraType;
  1754. dict[@"isRemake"] = @(obj.isRemake);
  1755. NSMutableArray *keyFrame = [NSMutableArray array];
  1756. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1757. [keyFrame addObject:obj];
  1758. }];
  1759. dict[@"keyFrame"] = keyFrame;
  1760. [res addObject:dict];
  1761. }
  1762. }];
  1763. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1764. if (obj.path.length) {
  1765. idIndex += idx;
  1766. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1767. dict[@"id"] = [NSString stringWithFormat:@"%ld", idIndex];
  1768. dict[@"path"] = obj.path;
  1769. dict[@"cameraMode"] = obj.cameraMode;
  1770. dict[@"cameraType"] = obj.cameraType;
  1771. dict[@"isRemake"] = @(obj.isRemake);
  1772. NSMutableArray *keyFrame = [NSMutableArray array];
  1773. [obj.keyFrame enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1774. [keyFrame addObject:obj];
  1775. }];
  1776. dict[@"keyFrame"] = keyFrame;
  1777. [res addObject:dict];
  1778. }
  1779. }];
  1780. if (self.completeBlock) {
  1781. NSMutableDictionary *dict = [NSMutableDictionary dictionary];
  1782. dict[@"code"] = @(200);
  1783. dict[@"message"] = @"成功";
  1784. dict[@"data"] = res;
  1785. self.completeBlock(dict);
  1786. [self dismissViewControllerAnimated:YES completion:^{
  1787. }];
  1788. }
  1789. // self.panGesture.enabled = YES;
  1790. // // Access has not been determined.
  1791. // [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
  1792. //
  1793. // dispatch_async(dispatch_get_main_queue(), ^{
  1794. // if (status == PHAuthorizationStatusAuthorized) {
  1795. // // Access has been granted.
  1796. // [self.currentOperationNode save];
  1797. // }
  1798. // else {
  1799. // // Access has been denied.
  1800. // [self showAlertForAuthorizationWithText:@"请设置相册权限后重试"];
  1801. // }
  1802. // });
  1803. // }];
  1804. }
  1805. - (void)discardPhotoResultButtonTouchUpInside:(id)sender{
  1806. self.panGesture.enabled = YES;
  1807. // if([self.currentOperationNode respondsToSelector:@selector(discardPhotoResultButtonTouchUpInside)]){
  1808. // [self.currentOperationNode discardPhotoResultButtonTouchUpInside];
  1809. // }
  1810. NSString *title = @"返回会清空已拍摄数据,请确认!";
  1811. // if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1812. // title = @"返回会清空已拍摄视频,请确认!";
  1813. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA || self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1814. // title = @"返回会清空已拼接图片,请确认!";
  1815. // }
  1816. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:title leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1817. [alertController dismissViewControllerAnimated:NO completion:^{}];
  1818. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1819. // if (self.mode == SDK_CAPTURE_MODE_CONTINUOUS) {
  1820. [self.resourceModel.continousArray removeAllObjects];
  1821. // } else if (self.mode == SDK_CAPTURE_MODE_MOVIE) {
  1822. [self.resourceModel.movieArray removeAllObjects];
  1823. // } else if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  1824. [self.resourceModel.panoramArray removeAllObjects];
  1825. // } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  1826. [self.resourceModel.aiPanoramArray removeAllObjects];
  1827. // }
  1828. [self updateViewStatus];
  1829. [alertController dismissViewControllerAnimated:NO completion:^{
  1830. }];
  1831. }];
  1832. }
  1833. - (void)albumButtonTouchUpInside:(id)sender{
  1834. [self performSegueWithIdentifier:@"show-photoalbum" sender:nil];
  1835. // if([self.currentOperationNode respondsToSelector:@selector(segueForAlbum)]){
  1836. // [self performSegueWithIdentifier:self.currentOperationNode.segueForAlbum sender:nil];
  1837. // }
  1838. }
  1839. - (__kindof id<OperationNodeProtocol>)currentOperationNode{
  1840. // NSLog(@"======:%u",self.mode);
  1841. // NSLog(@"------:%@",self.operationNodes);
  1842. return self.operationNodes[@(self.mode)];
  1843. }
  1844. - (void)updateNumberLabel {
  1845. self.aiPanPromtLabel.hidden = YES;
  1846. switch (self.mode) {
  1847. case SDK_CAPTURE_MODE_CONTINUOUS: {
  1848. if (self.resourceModel.continousArray.count > 0) {
  1849. self.numberOfImagesLabel.hidden = NO;
  1850. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已连拍%ld张", self.resourceModel.continousArray.count];
  1851. } else {
  1852. self.numberOfImagesLabel.hidden = YES;
  1853. }
  1854. }
  1855. break;
  1856. case SDK_CAPTURE_MODE_MOVIE:{
  1857. if (self.resourceModel.movieArray.count > 0) {
  1858. self.numberOfImagesLabel.hidden = NO;
  1859. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍视频%ld条", self.resourceModel.movieArray.count];
  1860. } else {
  1861. self.numberOfImagesLabel.hidden = YES;
  1862. }
  1863. }
  1864. break;
  1865. case SDK_CAPTURE_MODE_PANORAMA:
  1866. {
  1867. if (self.resourceModel.panoramArray.count > 0) {
  1868. self.numberOfImagesLabel.hidden = NO;
  1869. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拼接%ld张", self.resourceModel.panoramArray.count];
  1870. } else {
  1871. self.numberOfImagesLabel.hidden = YES;
  1872. }
  1873. }
  1874. break;
  1875. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:
  1876. {
  1877. self.aiPanPromtLabel.hidden = NO;
  1878. if (self.resourceModel.aiPanoramArray.count > 0) {
  1879. self.numberOfImagesLabel.hidden = NO;
  1880. self.numberOfImagesLabel.text = [NSString stringWithFormat:@"已拍摄%ld张", self.resourceModel.aiPanoramArray.count];
  1881. } else {
  1882. self.numberOfImagesLabel.text = @"轻点拍照,长按录制";
  1883. self.numberOfImagesLabel.hidden = NO;
  1884. }
  1885. }
  1886. break;
  1887. default:
  1888. self.numberOfImagesLabel.hidden = YES;
  1889. break;
  1890. }
  1891. }
  1892. - (void)savePhotoWith:(NSData *)data isRemake:(BOOL)isRemake{
  1893. UIImage *image = [[UIImage alloc] initWithData:data];
  1894. NSString *path = [LenzDataManager saveImageWith:data mode:self.mode];
  1895. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  1896. itemModel.path = path;
  1897. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1898. if (obj.model == self.mode) {
  1899. itemModel.cameraType = obj.cameraPositionString;
  1900. }
  1901. }];
  1902. itemModel.mode = self.mode;
  1903. itemModel.image = image;
  1904. itemModel.isRemake = isRemake;
  1905. switch (self.mode) {
  1906. case SDK_CAPTURE_MODE_CONTINUOUS:{
  1907. [self.resourceModel.continousArray addObject:itemModel];
  1908. }
  1909. break;
  1910. case SDK_CAPTURE_MODE_SINGLE: {
  1911. [self.resourceModel.singleArray addObject:itemModel];
  1912. }
  1913. break;
  1914. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA: {
  1915. [self.resourceModel.aiPanoramArray addObject:itemModel];
  1916. }
  1917. break;
  1918. default:
  1919. break;
  1920. }
  1921. self.resourceModel.lastIndex = self.mode;
  1922. [self updateViewStatus];
  1923. // [self.cachesArray addObject:image];
  1924. //
  1925. // [self.typeArray addObject:@"photo"];
  1926. //
  1927. // [self.totalArray addObject:image];
  1928. //
  1929. // self.capturedImage = image;
  1930. [self.currentOperationNode triggered];
  1931. if(self.mode == SDK_CAPTURE_MODE_SINGLE){
  1932. // self.panGesture.enabled = NO;
  1933. [self stopCaptureSession];
  1934. [self performSegueWithIdentifier:@"preview_single" sender:nil];
  1935. // [self showPreviewView:NO];
  1936. }
  1937. else if(self.mode == SDK_CAPTURE_MODE_CONTINUOUS){
  1938. self.discardPhotoButton.hidden = NO;
  1939. self.savePhotoButton.hidden = NO;
  1940. }
  1941. self.resultImageView.image = image;
  1942. }
  1943. #pragma mark 相机单拍,和连拍的代理
  1944. - (void)captureOutput:(AVCapturePhotoOutput *)output didFinishProcessingPhoto:(AVCapturePhoto *)photo error:(NSError *)error{
  1945. NSData* imageData = [photo fileDataRepresentation];
  1946. if (imageData == nil){
  1947. NSLog(@"%s", "unable to create image data");
  1948. return;
  1949. }
  1950. UIImage *image = [[UIImage alloc] initWithData:imageData];
  1951. BOOL isRemake = [self.tensorFlow remake:image];
  1952. __block BOOL needCheckRemake = NO;
  1953. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1954. if (obj.model == self.mode) {
  1955. needCheckRemake = obj.isRemake;
  1956. }
  1957. }];
  1958. if (isRemake && needCheckRemake) {
  1959. [QuitMultipleModeAlertViewController show:self title:@"确认提醒" text:@"检测到该图片为翻拍,是否继续使用?" leftBtnTitle:@"取消" rightBtnTitle:@"确定" withLeftButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1960. [alertController dismissViewControllerAnimated:YES completion:nil];
  1961. } rightButtonCallBack:^(QuitMultipleModeAlertViewController * _Nonnull alertController) {
  1962. [alertController dismissViewControllerAnimated:YES completion:nil];
  1963. [self savePhotoWith:imageData isRemake:isRemake];
  1964. }];
  1965. } else {
  1966. [self savePhotoWith:imageData isRemake:isRemake];
  1967. }
  1968. }
  1969. - (void)updateViewStatus {
  1970. dispatch_async(dispatch_get_main_queue(), ^{
  1971. UIImage *image = nil;
  1972. NSMutableArray *continousMutArray = [NSMutableArray array];
  1973. [self.resourceModel.continousArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1974. if (obj.path && obj.image) {
  1975. [continousMutArray addObject:obj];
  1976. }
  1977. }];
  1978. self.resourceModel.continousArray = continousMutArray;
  1979. NSMutableArray *singleMutArray = [NSMutableArray array];
  1980. [self.resourceModel.singleArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1981. if (obj.path && obj.image) {
  1982. [singleMutArray addObject:obj];
  1983. }
  1984. }];
  1985. self.resourceModel.singleArray = singleMutArray;
  1986. NSMutableArray *movieMutArray = [NSMutableArray array];
  1987. [self.resourceModel.movieArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1988. if (obj.path && obj.image) {
  1989. [movieMutArray addObject:obj];
  1990. }
  1991. }];
  1992. self.resourceModel.movieArray = movieMutArray;
  1993. NSMutableArray *panoramMutArray = [NSMutableArray array];
  1994. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  1995. if (obj.path && obj.image) {
  1996. [panoramMutArray addObject:obj];
  1997. }
  1998. }];
  1999. self.resourceModel.panoramArray = panoramMutArray;
  2000. NSMutableArray *aiPanoramMutArray = [NSMutableArray array];
  2001. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2002. if (obj.path && obj.image) {
  2003. [aiPanoramMutArray addObject:obj];
  2004. }
  2005. }];
  2006. self.resourceModel.aiPanoramArray = aiPanoramMutArray;
  2007. switch (self.resourceModel.lastIndex) {
  2008. case SDK_CAPTURE_MODE_CONTINUOUS: {
  2009. if (self.resourceModel.continousArray.count > 0) {
  2010. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2011. image = model.image;
  2012. } else {
  2013. if (self.resourceModel.singleArray.count > 0) {
  2014. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2015. image = model.image;
  2016. } else if (self.resourceModel.movieArray.count > 0) {
  2017. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2018. image = model.image;
  2019. } else if (self.resourceModel.panoramArray.count > 0) {
  2020. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2021. image = model.image;
  2022. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2023. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2024. image = model.image;
  2025. }
  2026. }
  2027. }
  2028. break;
  2029. case SDK_CAPTURE_MODE_SINGLE:{
  2030. if (self.resourceModel.singleArray.count > 0) {
  2031. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2032. image = model.image;
  2033. } else {
  2034. if (self.resourceModel.continousArray.count > 0) {
  2035. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2036. image = model.image;
  2037. } else if (self.resourceModel.movieArray.count > 0) {
  2038. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2039. image = model.image;
  2040. } else if (self.resourceModel.panoramArray.count > 0) {
  2041. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2042. image = model.image;
  2043. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2044. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2045. image = model.image;
  2046. }
  2047. }
  2048. }
  2049. break;
  2050. case SDK_CAPTURE_MODE_MOVIE:{
  2051. if (self.resourceModel.movieArray.count > 0) {
  2052. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2053. image = model.image;
  2054. } else {
  2055. if (self.resourceModel.singleArray.count > 0) {
  2056. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2057. image = model.image;
  2058. } else if (self.resourceModel.continousArray.count > 0) {
  2059. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2060. image = model.image;
  2061. } else if (self.resourceModel.panoramArray.count > 0) {
  2062. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2063. image = model.image;
  2064. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2065. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2066. image = model.image;
  2067. }
  2068. }
  2069. }
  2070. break;
  2071. case SDK_CAPTURE_MODE_PANORAMA:{
  2072. if (self.resourceModel.panoramArray.count > 0) {
  2073. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2074. image = model.image;
  2075. } else {
  2076. if (self.resourceModel.singleArray.count > 0) {
  2077. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2078. image = model.image;
  2079. } else if (self.resourceModel.movieArray.count > 0) {
  2080. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2081. image = model.image;
  2082. } else if (self.resourceModel.continousArray.count > 0) {
  2083. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2084. image = model.image;
  2085. } else if (self.resourceModel.aiPanoramArray.count > 0) {
  2086. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2087. image = model.image;
  2088. }
  2089. }
  2090. }
  2091. break;
  2092. case SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA:{
  2093. if (self.resourceModel.aiPanoramArray.count > 0) {
  2094. LenzResourceItemModel *model = self.resourceModel.aiPanoramArray.lastObject;
  2095. image = model.image;
  2096. } else {
  2097. if (self.resourceModel.singleArray.count > 0) {
  2098. LenzResourceItemModel *model = self.resourceModel.singleArray.lastObject;
  2099. image = model.image;
  2100. } else if (self.resourceModel.movieArray.count > 0) {
  2101. LenzResourceItemModel *model = self.resourceModel.movieArray.lastObject;
  2102. image = model.image;
  2103. } else if (self.resourceModel.panoramArray.count > 0) {
  2104. LenzResourceItemModel *model = self.resourceModel.panoramArray.lastObject;
  2105. image = model.image;
  2106. } else if (self.resourceModel.continousArray.count > 0) {
  2107. LenzResourceItemModel *model = self.resourceModel.continousArray.lastObject;
  2108. image = model.image;
  2109. }
  2110. }
  2111. }
  2112. break;
  2113. default:
  2114. break;
  2115. }
  2116. if (image) {
  2117. self.ablumImageView.image = image;
  2118. self.ablumImageView.hidden = NO;
  2119. self.discardPhotoButton.hidden = NO;
  2120. self.savePhotoButton.hidden = NO;
  2121. self.backButton.hidden = YES;
  2122. } else {
  2123. self.ablumImageView.image = nil;
  2124. self.ablumImageView.hidden = YES;
  2125. self.discardPhotoButton.hidden = YES;
  2126. self.savePhotoButton.hidden = YES;
  2127. self.backButton.hidden = NO;
  2128. }
  2129. [self updateNumberLabel];
  2130. });
  2131. }
  2132. #pragma mark - AVCaptureFileOutputRecordingDelegate
  2133. - (void)captureOutput:(AVCaptureFileOutput *)output didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray<AVCaptureConnection *> *)connections error:(NSError *)error{
  2134. //视频录制
  2135. BOOL recordedSuccessfully = YES;
  2136. // A problem occurred: Find out if the recording was successful.
  2137. if(error.code == AVErrorMaximumDurationReached){
  2138. NSLog(@"%@", [error localizedDescription]);
  2139. }
  2140. else if (error.code == AVErrorDiskFull){
  2141. NSLog(@"%@", [error localizedDescription]);
  2142. dispatch_async(dispatch_get_main_queue(), ^{
  2143. [[NSNotificationCenter defaultCenter] postNotificationName:LenzSDKNotificationDiskIsFull object:error];
  2144. });
  2145. }
  2146. else if (error.code == AVErrorSessionWasInterrupted){
  2147. NSLog(@"%@", [error localizedDescription]);
  2148. }
  2149. id value = [[error userInfo] objectForKey:AVErrorRecordingSuccessfullyFinishedKey];
  2150. if (value) {
  2151. recordedSuccessfully = [value boolValue];
  2152. [self.recordTimer invalidate];
  2153. self.recordTimer = nil;
  2154. }
  2155. if(!recordedSuccessfully){
  2156. return;
  2157. }
  2158. OperationNodeMovie *node = nil;
  2159. if ([self.currentOperationNode isKindOfClass:[OperationNodeMovie class]]) {
  2160. node = (OperationNodeMovie *)self.currentOperationNode;
  2161. if (node.isRecording) {
  2162. [self.currentOperationNode takePhotoButtonTouched];
  2163. }
  2164. }
  2165. // NSString *path = [LenzDataManager saveVideoUrl:outputFileURL model:self.mode];
  2166. LenzResourceItemModel *itemModel = [[LenzResourceItemModel alloc]init];
  2167. itemModel.path = outputFileURL.absoluteString;
  2168. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2169. if (obj.model == self.mode) {
  2170. itemModel.cameraType = obj.cameraPositionString;
  2171. }
  2172. }];
  2173. itemModel.mode = self.mode;
  2174. itemModel.image = [self videoFrameImageWith:outputFileURL];
  2175. [self.resourceModel.movieArray addObject:itemModel];
  2176. self.resourceModel.lastIndex = self.mode;
  2177. // self.recordedFileUrl = outputFileURL;
  2178. // [self.typeArray addObject:@"movie"];
  2179. [self updateViewStatus];
  2180. [self.timerLabel updateWith:0];
  2181. dispatch_async(dispatch_get_main_queue(), ^{
  2182. [self.currentOperationNode triggered];
  2183. self.thumbnailOritaionByCurrentVideoOrientation = UIImageOrientationUp;
  2184. });
  2185. }
  2186. - (BOOL)encodeFrame:(CMSampleBufferRef) sampleBuffer{
  2187. if (CMSampleBufferDataIsReady(sampleBuffer)) {
  2188. if (self.videoWriter.status == AVAssetWriterStatusUnknown) {
  2189. CMTime startTime = CMSampleBufferGetPresentationTimeStamp(sampleBuffer);
  2190. [self.videoWriter startWriting];
  2191. [self.videoWriter startSessionAtSourceTime:startTime];
  2192. }
  2193. if (self.videoWriter.status == AVAssetWriterStatusFailed) {
  2194. NSLog(@"writer error %@", self.videoWriter.error.localizedDescription);
  2195. return NO;
  2196. }
  2197. if (self.videoWriterInput.readyForMoreMediaData) {
  2198. [self.videoWriterInput appendSampleBuffer:sampleBuffer];
  2199. return YES;
  2200. }
  2201. }
  2202. return NO;
  2203. }
  2204. #pragma mark - AVCaptureAudioDataOutputSampleBufferDelegate
  2205. #pragma mark - UIViewControllerTransitioningDelegate
  2206. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
  2207. return [[CustomModalViewTransitionPresent alloc] init];
  2208. }
  2209. - (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
  2210. return [[CustomModalViewTransitionDismiss alloc] init];
  2211. }
  2212. #pragma mark - PhotoListViewControllerDelegate
  2213. //删除视频
  2214. - (void)deleteMovie: (MovieListCellModel*)model completion: (DeleteImageCompletionCallBackType)completion{
  2215. for (int i = 0; i < self.totalArray.count; i ++) {
  2216. UIImage *image = self.totalArray[i];
  2217. if (image == (UIImage *)model.movieModel.thumbnail) {
  2218. [self.totalArray removeObjectAtIndex:i];
  2219. [self.typeArray removeObjectAtIndex:i];
  2220. break;;
  2221. }
  2222. }
  2223. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2224. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2225. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2226. [curr deleteCacheForKey:model.movieModel.fileUrl.path completion:completion];
  2227. }
  2228. }
  2229. //连拍删除
  2230. - (void)deleteImage:(UIImage *)image completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2231. // id<OperationNodeProtocol> curr = self.currentOperationNode;
  2232. for (int i = 0; i < self.totalArray.count; i ++) {
  2233. UIImage *img = self.totalArray[i];
  2234. if (img == image) {
  2235. [self.totalArray removeObjectAtIndex:i];
  2236. [self.typeArray removeObjectAtIndex:i];
  2237. break;;
  2238. }
  2239. }
  2240. id<OperationNodeProtocol> curr = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2241. if([curr respondsToSelector:@selector(deleteCacheForImage:completion:)]){
  2242. [curr deleteCacheForImage:image completion:completion];
  2243. }
  2244. }
  2245. - (void)deleteImageWithName:(NSString *)name completion:(nonnull DeleteImageCompletionCallBackType)completion{
  2246. id<OperationNodeProtocol> curr = self.currentOperationNode;
  2247. if([curr respondsToSelector:@selector(deleteCacheForKey:completion:)]){
  2248. [curr deleteCacheForKey:name completion:completion];
  2249. }
  2250. }
  2251. #pragma mark - AVCaptureVideoDataOutputSampleBufferDelegate
  2252. - (void)captureOutput:(AVCaptureOutput *)output didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {
  2253. @autoreleasepool {
  2254. if (connection == [self.videoDataOutput connectionWithMediaType:AVMediaTypeVideo]) {
  2255. [self.stitchkLock lock];
  2256. // dispatch_semaphore_wait(self.videoStitchSemaphore, DISPATCH_TIME_FOREVER);
  2257. OperationNodeVideoBase *base = nil;
  2258. if ([self.currentOperationNode isKindOfClass:[OperationNodeVideoBase class]]) {
  2259. base = (OperationNodeVideoBase *)self.currentOperationNode;
  2260. }
  2261. if (self.isVideoStitchStopedWhenRecording &&
  2262. (self.stitchResult != LenVideoStitchResultFail && self.stitchResult != LenVideoStitchResultStitchFail)) {
  2263. [self updateViewStatusWhenStitchSave:YES];
  2264. self.isStitchBigImage = YES;
  2265. }
  2266. [LenStitcher videoStitchWith:sampleBuffer
  2267. dirction:(LenVideoStitchDirction)self.panoramOrientationGuideView.selectedItemIndex
  2268. isStop:self.isVideoStitchStopedWhenRecording
  2269. complete:^(LenVideoStitchResult result, LenVideoStitchNeedSave needSave) {
  2270. self.stitchResult = result;
  2271. self.isVideoStitchStopedWhenRecording = NO;
  2272. UIImage *image = [LenStitcher getCurrentPanoramaShowImage];
  2273. LenzResourceItemModel *model = nil;
  2274. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2275. model = self.resourceModel.panoramArray.lastObject;
  2276. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2277. model = self.resourceModel.aiPanoramArray.lastObject;
  2278. }
  2279. if (!image || !model) {
  2280. [self.stitchkLock unlock];
  2281. return;
  2282. }
  2283. if (result == LenVideoStitchResultSuccess) {
  2284. dispatch_async(dispatch_get_main_queue(), ^{
  2285. if (self.isStitchBigImage) {
  2286. //保存大图拼接路径
  2287. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2288. if (obj.model == self.mode) {
  2289. model.cameraType = obj.cameraPositionString;
  2290. }
  2291. }];
  2292. model.mode = self.mode;
  2293. if ([LenStitcher getCurrentPanoramaShow]) {
  2294. model.image = image;
  2295. model.path = [LenStitcher getCurrentPanoramaShow];
  2296. }
  2297. [self updateViewStatusWhenStitchSave:NO];
  2298. self.isStitchBigImage = NO;
  2299. [self.panoramaGuideView clearImage];
  2300. [self updateViewStatus];
  2301. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2302. } else {
  2303. if (base.isRecording) {
  2304. __block BOOL keyFrame = NO;
  2305. [[SDKParameters shared].items enumerateObjectsUsingBlock:^(SDKParametersItem * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2306. if (obj.model == self.mode) {
  2307. keyFrame = obj.keyFrame;
  2308. }
  2309. }];
  2310. if (needSave && keyFrame) {
  2311. NSString *path = [LenzDataManager saveImageWith:UIImageJPEGRepresentation(image, .6) mode:self.mode];
  2312. // itemModel.path = path;
  2313. if (path) {
  2314. [model.keyFrame addObject:path];
  2315. }
  2316. }
  2317. if (self.panoramOrientationGuideView.selectedItemIndex != PanoramaOrientationViewAny) {
  2318. [self.panoramaGuideView showImageWith:image dir:self.panoramOrientationGuideView.selectedItemIndex];
  2319. } else {
  2320. self.ablumImageView.hidden = NO;
  2321. self.ablumImageView.image = image;
  2322. }
  2323. }
  2324. }
  2325. self.resourceModel.lastIndex = self.mode;
  2326. });
  2327. } else {
  2328. if (!base.isRecording) {
  2329. // [self removeLastStich];
  2330. //停止拼接,移除保存中 非success数据
  2331. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2332. NSMutableArray *array = [NSMutableArray array];
  2333. [self.resourceModel.panoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2334. if (obj.path.length) {
  2335. [array addObject:obj];
  2336. }
  2337. }];
  2338. self.resourceModel.panoramArray = array;
  2339. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2340. NSMutableArray *array = [NSMutableArray array];
  2341. [self.resourceModel.aiPanoramArray enumerateObjectsUsingBlock:^(LenzResourceItemModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
  2342. if (obj.path.length) {
  2343. [array addObject:obj];
  2344. }
  2345. }];
  2346. self.resourceModel.aiPanoramArray = array;
  2347. }
  2348. [self updateViewStatus];
  2349. [self.stitchkLock unlock];
  2350. return;
  2351. }
  2352. if (result == LenVideoStitchResultFail || result == LenVideoStitchResultStitchFail) {
  2353. if (result == LenVideoStitchResultFail) {
  2354. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接失败,流程结束"];
  2355. } else {
  2356. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"拼接大图失败,流程结束"];
  2357. }
  2358. self.isVideoStitchStopedWhenRecording = NO;
  2359. // base.isRecording = NO;
  2360. dispatch_async(dispatch_get_main_queue(), ^{
  2361. [base takePhotoButtonTouched];
  2362. [self stopMotion];
  2363. // [self takePhotoButtonTouchUpInside:[NSObject new]];
  2364. [self removeLastStich];
  2365. [self updateViewStatusWhenStitchFail];
  2366. [self.panoramaGuideView clearImage];
  2367. [self updateViewStatus];
  2368. [self.panoramaGuideView showImageWith:nil dir:self.panoramOrientationGuideView.selectedItemIndex];
  2369. });
  2370. [SVProgressHUD dismissWithDelay:3 completion:^{
  2371. }];
  2372. } else if(result == LenVideoStitchResultSlowMore) {
  2373. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2374. } else if (result == LenVideoStitchResultSlow) {
  2375. [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"目标物较少,请对准目标物低速且匀速拍摄"];
  2376. } else {
  2377. // [SVProgressHUD showImage:[UIImage imageNamed:@""] status:@"请勿往反方向移动"];
  2378. }
  2379. }
  2380. [self.stitchkLock unlock];
  2381. // dispatch_semaphore_signal(self.videoStitchSemaphore);
  2382. }];
  2383. }
  2384. }
  2385. }
  2386. - (void)removeLastStich {
  2387. if (self.mode == SDK_CAPTURE_MODE_PANORAMA) {
  2388. if (self.resourceModel.panoramArray.count > 0) {
  2389. [self.resourceModel.panoramArray removeLastObject];
  2390. }
  2391. } else if (self.mode == SDK_CAPTURE_MODE_INTELLEGENCE_PANORAMA) {
  2392. if (self.resourceModel.aiPanoramArray.count > 0) {
  2393. [self.resourceModel.aiPanoramArray removeLastObject];
  2394. }
  2395. }
  2396. }
  2397. //*
  2398. #pragma mark - Navigation
  2399. // In a storyboard-based application, you will often want to do a little preparation before navigation
  2400. - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  2401. // Get the new view controller using [segue destinationViewController].
  2402. // Pass the selected object to the new view controller.
  2403. if([segue.identifier isEqualToString:@"show-photos"]){
  2404. if([segue.destinationViewController isKindOfClass:[PhotoListViewController class]]){
  2405. PhotoListViewController* dst = segue.destinationViewController;
  2406. OperationNodeMultiple* node = self.currentOperationNode;
  2407. dst.transitioningDelegate = self;
  2408. [dst setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2409. dst.delegate = self;
  2410. }
  2411. }
  2412. else if([segue.identifier isEqualToString:@"show-movies"]){
  2413. if([segue.destinationViewController isKindOfClass:[MovieListViewController class]]){
  2414. MovieListViewController* dst = segue.destinationViewController;
  2415. OperationNodeMovie* node = self.currentOperationNode;
  2416. dst.transitioningDelegate = self;
  2417. dst.movieModels = node.cachedMovies;
  2418. dst.delegate = self;
  2419. }
  2420. }
  2421. else if([segue.identifier isEqualToString:@"preview_single"]){
  2422. PreviewSingleViewController* dst = segue.destinationViewController;
  2423. dst.singleModeNode = self.currentOperationNode;
  2424. if (self.resourceModel.singleArray.count > 0) {
  2425. LenzResourceItemModel *model = self.resourceModel.singleArray.firstObject;
  2426. dst.image = model.image;
  2427. }
  2428. // dst.image = self.capturedImage;
  2429. }else if ([segue.identifier isEqualToString:@"show-photoalbum"]){
  2430. PhotoAlbumListViewController *dst = segue.destinationViewController;
  2431. dst.typeArray = self.typeArray;
  2432. //图片数据
  2433. NSString *typeStr = self.typeArray.lastObject;
  2434. // if ([typeStr isEqualToString:@"photo"]) {
  2435. OperationNodeMultiple* node = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(0)];
  2436. // OperationNodeMultiple* node = self.currentOperationNode;
  2437. dst.node = node;
  2438. dst.photoListVC.transitioningDelegate = self;
  2439. [dst.photoListVC setImagesInMemory:node.cachesInMemory andImageNamesOnDisk:node.cachesOnDisk];
  2440. dst.photoListVC.delegate = self;
  2441. // }else if ([typeStr isEqualToString:@"movie"]) {
  2442. OperationNodeMovie* movieNode = (__kindof id<OperationNodeProtocol>)self.operationNodes[@(2)];
  2443. dst.movieListVC.transitioningDelegate = self;
  2444. dst.movieListVC.movieModels = movieNode.cachedMovies;
  2445. dst.movieListVC.delegate = self;
  2446. // }
  2447. //视频数据
  2448. }
  2449. }
  2450. //*/
  2451. - (void)clearSingleData {
  2452. [self.resourceModel.singleArray removeAllObjects];
  2453. [self updateViewStatus];
  2454. }
  2455. - (UIImage *)videoFrameImageWith:(NSURL *)url {
  2456. AVURLAsset* asset = [[AVURLAsset alloc] initWithURL:url options:nil];
  2457. AVAssetImageGenerator *generateImg = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  2458. NSError *err = NULL;
  2459. CMTime time = CMTimeMake(1, 65);
  2460. CGImageRef refImg = [generateImg copyCGImageAtTime:time actualTime:NULL error:&err];
  2461. UIImage *frameImage= [[UIImage alloc] initWithCGImage:refImg scale:1.0 orientation:self.thumbnailOritaionByCurrentVideoOrientation];
  2462. return frameImage;
  2463. }
  2464. @end