PCSBaseViewController.m 136 KB

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