PCSBaseViewController.m 136 KB

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