Пример #1
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            SetContentView(Resource.Layout.Save);
            this._userPremiumStatus
                = Intent.GetStringExtra(PremiumInterface.UserPremiunStatus.StatusFlags.ACTIVITY_FLAG);

            //set up tracking and track this activity
            trackingInterface = new TrackingInterface(this);
            //trackingInterface.TrackScreen(TrackingInterface.ActivityNames.SaveActivity);

            shareButton    = FindViewById <Button> (Resource.Id.shareButton);
            saveLayout     = FindViewById <LinearLayout> (Resource.Id.saveLayout);
            mainSaveLayout = FindViewById <LinearLayout> (Resource.Id.mainSaveLayout);
            adLinearLayout = FindViewById <LinearLayout> (Resource.Id.adLinearLayout);
            adViewHolder   = new AdViewHolder(this);

            pm = (PowerManager)GetSystemService(Context.PowerService);
            wl = pm.NewWakeLock(WakeLockFlags.ScreenDim, "My Tag");
            ActionBar.Title = "";
            internalPath    = FilesDir.Path;
            rawFileName     = "my_file";

            List <string> fileNamesArray = new List <string>();

            foreach (File file in this.FilesDir.ListFiles())
            {
                fileNamesArray.Add(file.Name);
            }

            rawFileName       = GetFullFileNameFromArray(rawFileName, fileNamesArray.ToArray());
            outputName        = "final.mp4";
            finalFileName     = "Gifaroo" + UUID.RandomUUID() + ".mp4";
            ffmpeg            = FFmpeg.GetInstance(this);
            commandDimensions = FffmpegTools.GetResizeCommandDimensions(this, rawFileName);

            mainSaveLayout.RemoveView(saveLayout);
            mainSaveLayout.RemoveView(adViewHolder.adLinearLayout);

            //Load ad only if the user is not premium
            if (this._userPremiumStatus == PremiumInterface.UserPremiunStatus.StatusFlags.STATUS_FREE)
            {
                Flurry.Analytics.FlurryAgent.SetLogEnabled(false);
                Flurry.Analytics.FlurryAgent.Init(this, "ZTKSCWYBWHW9D6F28KY5");
                nativeAd = new Flurry.Ads.FlurryAdNative(this, "save_activity_native_ad");
                nativeAd.FetchAd();
            }

            #region ffmpeg load & execution
            CreateTxtFile(this);

            string[] commands = new string[]
            {
                "-y -i " + internalPath + "/" + rawFileName + " -vf scale=" + commandDimensions + " -preset superfast " + internalPath + "/output_mp4.mp4",
                "-y -i " + internalPath + "/background.jpg -vf scale=700:700 " + internalPath + "/background_scaled.jpg",
                "-y -i " + internalPath + "/top.png -vf scale=700:700 " + internalPath + "/top_scaled.png",
                "-y -loop 1 -i " + internalPath + "/background_scaled.jpg -i " + internalPath + "/output_mp4.mp4 -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:shortest=1 -preset superfast -codec:a copy -movflags +faststart " + internalPath + "/output_1.mp4",
                "-y -i " + internalPath + "/output_1.mp4 -loop 1 -i " + internalPath + "/top_scaled.png -filter_complex overlay=(main_w-overlay_w)/2:(main_h-overlay_h)/2:shortest=1 -preset superfast -codec:a copy -movflags +faststart " + internalPath + "/final_unlooped.mp4",
                "-y -f concat -i " + internalPath + "/myList.txt -c copy " + internalPath + "/mute_final.mp4",
                "-y -i " + internalPath + "/mute_final.mp4 -i " + internalPath + "/10sec.mp3 -c:v libx264 -crf 19 -preset ultrafast -shortest -c:a aac -strict experimental -pix_fmt yuv420p -f mp4 -b:a 192k -y " + internalPath + "/" + outputName
            };

            string[] progressMessages = new string[]
            {
                "Doing some work...",
                "Making progress...",
                "Still working...",
                "Just a little bit more...",
                "Adding some final touches..."
            };


            //attempt to load ffmpeg and then execute the commands.
            FffmpegTools.XLoadBinaryResponseHandler loadResponseHandler
                = new FffmpegTools.XLoadBinaryResponseHandler();
            FffmpegTools.XExecuteBinaryResponseHandler executeResponseHandler
                = new FffmpegTools.XExecuteBinaryResponseHandler();

            //copy the ute audio file to the apps internal directory if it does not exist yet.
            if (new File(FilesDir.Path, "10sec.mp3").Exists() == false)
            {
                try
                {
                    CopyFromAssetsToStorage(this, "10sec.mp3", "10sec.mp3");
                }catch (Exception) {
                    Log.Debug("GIFAROO", "10sec.mp3 copy failed!");                     //TODO: Remove for release
                }
            }

            if (shouldRunffmpeg == true)
            {
                wl.Acquire();
                progressD = new ProgressDialog(this);
                progressD.SetMessage(progressMessages[0]);
                progressD.SetCanceledOnTouchOutside(false);
                XOnCancelListener cancelListener = new XOnCancelListener();
                progressD.SetOnCancelListener(cancelListener);

                cancelListener.EOnCanceled += (object cancelSender, EventArgs eCancel) => {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.SetMessage("Are you sure that you want to cancel?").SetTitle("Cancel?");
                    builder.SetPositiveButton("Yes",
                                              ((sender, e) => {
                        try{
                            threadsCanceled = true;
                            Finish();
                        }
                        catch (Exception) {}
                    }));
                    builder.SetNegativeButton("No",
                                              ((sender, e) => {
                        progressD.Show();
                    }));
                    AlertDialog aDialog = builder.Create();
                    aDialog.Show();
                };

                //Launched when the attempt to load the ffmpeg is finished
                loadResponseHandler.OnFfmpegLoadindAttemptFinished += (object sender, EventArgs e) => {
                    if (loadResponseHandler.failed == false)
                    {
                        new TaskFactory().StartNew(() =>
                        {
                            //var commandArray = new[] { commands[executeResponseHandler.commandsPosition] };
                            ffmpeg.Execute(
                                commands[executeResponseHandler.commandsPosition].Split(),
                                executeResponseHandler);
                        });
                    }
                    else if (loadResponseHandler.failed == true)
                    {
                        trackingInterface.TrackFffmgFailure(true);
                    }
                };

                executeResponseHandler.OnExecutionFinished += (object sender, EventArgs e) => {
                    if (executeResponseHandler.commandsPosition < commands.Length &&
                        threadsCanceled == false &&
                        executeResponseHandler.failed == false)     //run only if the threads hav not been canceled
                    {
                        try{
                            progressD.SetMessage(progressMessages[executeResponseHandler.commandsPosition]);
                        }catch (Exception) {}
                        new TaskFactory().StartNew(() => {
                            ffmpeg.Execute(
                                commands[executeResponseHandler.commandsPosition].Split(),
                                executeResponseHandler);
                        });

                        //TODO: find a better implementation
                        if (executeResponseHandler.failed == true)
                        {
                            //Report failure to analytics
                            trackingInterface.TrackFffmgFailure(false, executeResponseHandler.commandsPosition);
                            //One of the commands failed
                            progressD.Dismiss();
                            if (wl.IsHeld)                             //release the wakelock if it is held
                            {
                                wl.Release();
                            }
                            System.Console.WriteLine("FAILED: ");
                        }
                    }
                    else
                    {
                        //all commands were executed, share and show ad if the user is not premium.
                        if (progressD != null && progressD.IsShowing)
                        {
                            progressD.Dismiss();
                        }
                        wl.Release();
                        if (executeResponseHandler.failed == false)
                        {
                            //all commands succeded
                            mainSaveLayout.AddView(saveLayout);

                            //show ad
                            if (_userPremiumStatus == PremiumInterface.UserPremiunStatus.StatusFlags.STATUS_FREE &&
                                nativeAd.IsReady == true)
                            {
                                nativeAd.SetTrackingView(adLinearLayout);

                                if (nativeAd.GetAsset("summary") != null)
                                {
                                    nativeAd.GetAsset("summary").LoadAssetIntoView(adViewHolder.summary);
                                }
                                if (nativeAd.GetAsset("headline") != null)
                                {
                                    nativeAd.GetAsset("headline").LoadAssetIntoView(adViewHolder.headline);
                                }
                                if (nativeAd.GetAsset("source") != null)
                                {
                                    nativeAd.GetAsset("source").LoadAssetIntoView(adViewHolder.source);
                                }

                                if (nativeAd.GetAsset("secBrandingLogo") != null)
                                {
                                    nativeAd.GetAsset("secBrandingLogo").LoadAssetIntoView(adViewHolder.secBrandingLogo);
                                }
                                if (nativeAd.GetAsset("secHqImage") != null)
                                {
                                    nativeAd.GetAsset("secHqImage").LoadAssetIntoView(adViewHolder.secHqImage);
                                }
                                if (nativeAd.GetAsset("secImage") != null)
                                {
                                    nativeAd.GetAsset("secImage").LoadAssetIntoView(adViewHolder.secImage);
                                }
                                if (nativeAd.GetAsset("headline") != null)
                                {
                                    nativeAd.GetAsset("headline").LoadAssetIntoView(adViewHolder.headline);
                                }
                                if (nativeAd.GetAsset("callToAction") != null)
                                {
                                    adViewHolder.callToAction.Text = nativeAd.GetAsset("callToAction").Value;
                                }

                                mainSaveLayout.AddView(adViewHolder.adLinearLayout);
                            }
                            else   //make it all non-visible

                            {
                            }
                        }
                    }
                };

                progressD.Show();
                //new TaskFactory ().StartNew(()=>{
                try{
                    ffmpeg.LoadBinary(loadResponseHandler);
                }catch (Exception) {}
                //});
            }

            shareButton.Click += (object sender, EventArgs e) => {
                CreateVideoShareIntent(this, outputName);
            };
            #endregion
        }
Пример #2
0
        //Ads fields


        //TODO: clear the ram use from this activity.
        protected override void OnCreate(Bundle bundle)
        {
            //Attempts to load ffmpeg to see if it is supported.
            //StartActivity(new Intent(this, Java.Lang.Class.ForName("android.loadffmpeg")));



            //RequestWindowFeature (WindowFeatures.IndeterminateProgress);
            RequestWindowFeature(WindowFeatures.Progress);
            SetContentView(Resource.Layout.Main);
            base.OnCreate(bundle);
            //ActionBar.SetLogo (Resource.Drawable.inappicon);
            this.Title        = string.Empty;
            trackingInterface = new TrackingInterface(this);
            //trackingInterface.TrackScreen(TrackingInterface.ActivityNames.MainActivity);

            manager = (InputMethodManager)GetSystemService(InputMethodService);

            //used to control sleeping
            pm = (PowerManager)this.GetSystemService(Service.PowerService);
            wl = pm.NewWakeLock(WakeLockFlags.ScreenDim, "My Tag");

            this.appContext = this.ApplicationContext;
            //this.activityContext = this.activityContext;

            //assign controllers/widgets
            webView              = FindViewById <WebView> (Resource.Id.webView1);
            progressBar          = FindViewById <ProgressBar> (Resource.Id.progressBar1);
            playingWarning       = FindViewById <TextView> (Resource.Id.playingWarning);
            tapAndHoldPrompt     = FindViewById <TextView> (Resource.Id.tapAndHoldPrompt);
            relativeLayout       = FindViewById <RelativeLayout> (Resource.Id.relativeLayout1);
            cancelDownloadButton = FindViewById <Button> (Resource.Id.cancelDownloadButton);

            //Flurry
            //Flurry.Analytics.FlurryAgent.Init(this, "ZTKSCWYBWHW9D6F28KY5");
            //adBanner = new Flurry.Ads.FlurryAdBanner(this, relativeLayout, "Main_activity_banner");
            //adBanner.FetchAndDisplayAd();

            relativeLayout.RemoveView(tapAndHoldPrompt);
            relativeLayout.RemoveView(playingWarning);
            relativeLayout.RemoveView(cancelDownloadButton);
            relativeLayout.RemoveView(progressBar);

            //used when the GetGifs button is pressed, contains ValueReceived event
            //myResult = new JavaScriptResult ();

            /*WEBVIEW:  load default URL,
             *          enable JavaScript,
             *          prevent Android's default browser from opening	*/

            WebBrowserChromeClient myClient   = new WebBrowserChromeClient(this);
            WebBrowserClient       viewClient = new WebBrowserClient();

            webView.SetWebChromeClient(myClient);
            webView.SetWebViewClient(viewClient);
            webView.ClearCache(true);
            webView.LoadUrl(homePage);
            webView.Settings.DomStorageEnabled = true;

            webView.Settings.JavaScriptEnabled    = true;
            webView.Settings.LoadWithOverviewMode = true;
            webView.Settings.UseWideViewPort      = true;
            webView.Settings.BuiltInZoomControls  = true;
            webView.SetBackgroundColor(Color.White);

            #region ffmpeg loading
            //load ffmpeg
            ffmpeg = FFmpeg.GetInstance(this);
            FffmpegTools.XLoadBinaryResponseHandler    loadBinaryHandler    = new FffmpegTools.XLoadBinaryResponseHandler();
            FffmpegTools.XExecuteBinaryResponseHandler executeBinaryHandler = new FffmpegTools.XExecuteBinaryResponseHandler();
            //new TaskFactory ().StartNew (()=>{
            //	ffmpeg.LoadBinary(loadBinaryHandler);
            //});
            loadBinaryHandler.OnFfmpegLoadindAttemptFinished += (object sender, EventArgs e) =>
            {
                if (loadBinaryHandler.failed)
                {
                }
            };
            #endregion

            viewClient.EOnPageStarted += delegate(object sender, EventArgs e){
                manager.HideSoftInputFromWindow(webView.WindowToken, 0);
                if (URLBar != null)
                {
                    if (webView.Url != homePage)
                    {
                        URLBar.SetQuery(webView.Url, false);
                    }
                    else if (webView.Url == homePage)
                    {
                        URLBar.SetQuery("", false);
                    }
                }
            };

            //Fired when the download button is pressed and the JavaScript interface got the value
            if (myResult != null)
            {
                myResult.ValueReceived += delegate(object sender, EventArgs e) {
                    List <string> gifUrlList =
                        GifarooTools.GetAllGifUrls(
                            myResult.ResponseString, webView.OriginalUrl);

                    //Navigate to GifGallery with GifUrls as data
                    if (gifUrlList.Count != 0)
                    {
                        var gifGallery = new Intent(this, typeof(GifGalleryActivity));
                        gifGallery.PutStringArrayListExtra("gifUrlsList", gifUrlList);
                        StartActivity(gifGallery);
                    }
                    else
                    {
                        Toast.MakeText(this, "No animated gifs found... (Not all animated images are gif files...)", ToastLength.Short).Show();
                    }
                }
            }
            ;

            //Long click will go directly to the EditGif activity
            Toast notAGifToast = Toast.MakeText(this, "That's not a supported animated image.", ToastLength.Short);
            webView.LongClick += (object sender, View.LongClickEventArgs e) => {
                //URLBar.ClearFocus();
                webView.StopLoading();                  //TODO: break point this to allow asus to reach the next activity
                WebView eventWebView    = (WebView)sender;
                var     myResultza      = eventWebView.GetHitTestResult();
                var     myResultzaType  = myResultza.Type;
                var     extra           = myResultza.Extra;
                bool    formatsupported = false;

                bool isHomepageGif = true;

#if !DEBUG
                isHomepageGif = (webView.Url != homePage);  //This only runs on release, prevents the hoemsreen gif from being longclicked.
#endif

                foreach (string extension in GifarooTools.supportedImageExtensions)
                {
                    if (isHomepageGif &&
                        extra != null &&
                        extra.Contains(extension))
                    {
                        downloadTask    = null;
                        formatsupported = true;

                        downloadAndSaveGifCancelationToken = new CancellationTokenSource();

                        try {
                            toggleLoadingControlls(false);
                            string fileName = "my_file" + extension;
                            //string newFileName = "my_file.mp4";
                            //string dimensionsString = FffmpegTools.GetResizeCommandDimensions(this, fileName);
                            //string ffmpegCommand = "-y -i "+FilesDir.Path+"/"+fileName+" -vf scale="+ dimensionsString +" -preset superfast "+FilesDir.Path+"/"+newFileName;
                            //string ffmpegCommand = "-y -i "+FilesDir.Path+"/"+fileName+" -c:v libx264 -preset superfast -crf 22 -c:a copy " +FilesDir.Path+"/"+newFileName;
                            //string ffmpegCommand = "-y -i "+FilesDir.Path+"/"+fileName+" -c:v libx264 -vprofile baseline -c:a libfaac -ar 44100 -ac 2 -b:a 128k -movflags faststart "+FilesDir.Path+"/"+newFileName;
                            //string ffmpegCommand = "-y -i " + FilesDir.Path + "/" + fileName + " -c:v libx264 -profile:v baseline -c:a libfaac -ar 44100 -ac 2 -b:a 128k -movflags faststart " + FilesDir.Path + "/" + newFileName;
                            //string ffmpegCommand = "-y -i " + FilesDir.Path + "/" + fileName + " -s 480x320 -vcodec mpeg4 -acodec aac -strict -2 -ac 1 -ar 16000 -r 13 -ab 32000 -aspect 3:2 " + FilesDir.Path + "/" + newFileName;

                            downloadTask = Task.Factory.StartNew(() => {
                                try{
                                    GifarooTools.DownloadFileFromURL(this, extra, fileName);
                                }catch (Exception se) {
                                    trackingInterface.TrackException(se.Message, false);
                                }

                                //ffmpeg.Execute(ffmpegCommand.Split(), executeBinaryHandler);
                            }, downloadAndSaveGifCancelationToken.Token);
                            downloadTask.ContinueWith((antecedent) => {
                                var editGifActivity = new Intent(this, typeof(EditGifActivity));
                                //var editGifActivity = new Intent (this, typeof(SaveActivity)); //goes to java version of save activity
                                List <string> myStringList = new List <string>();
                                myStringList.Add(fileName);//TODO: change to newFilename when ffmpeg is implemented
                                editGifActivity.PutStringArrayListExtra("gifUrl", myStringList);
                                trackingInterface.TrackFileSorceDomain(new Java.Net.URL(extra).Host);

                                StartActivity(editGifActivity);  //TODO: remove this line when ffmpeg converison is implemented correctly

                                //executeBinaryHandler.OnExecutionFinished += (object exeSender, EventArgs eexe) =>
                                //{
                                //    if (executeBinaryHandler.failed == false)
                                //        StartActivity(editGifActivity);
                                //};
                            }, downloadAndSaveGifCancelationToken.Token);
                        }
                        catch (Exception es) {
                            Toast.MakeText(this, "Something went wrong, try again.", ToastLength.Long).Show();
                            toggleLoadingControlls(true);
                            downloadTask = null;
                            trackingInterface.TrackException(es.Message, false);
                        }

                        cancelDownloadButton.Click += (object cancelSender, EventArgs cancelEA) => {
                            downloadAndSaveGifCancelationToken.Cancel();
                            toggleLoadingControlls(true);
                            SetProgressBarIndeterminateVisibility(false);
                            downloadTask = null;
                        };
                    }
                }
                if (formatsupported == false)
                {
                    SetProgressBarIndeterminateVisibility(false);
                    notAGifToast.Show();
                }
            };
        }