Java tutorial
package com.xunlei.shortvideo.activity; import android.app.Activity; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.PowerManager; import android.support.v4.app.Fragment; import android.support.v7.widget.RecyclerView; import android.text.TextUtils; import android.util.Log; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.view.WindowManager; import android.widget.FrameLayout; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.duanqu.qupai.asset.AssetID; import com.duanqu.qupai.asset.AssetInfo; import com.duanqu.qupai.asset.AssetRepository; import com.duanqu.qupai.asset.AssetRepositoryClient; import com.duanqu.qupai.editor.ProjectClient; import com.duanqu.qupai.engine.session.MovieExportOptions; import com.duanqu.qupai.engine.session.ThumbnailExportOptions; import com.duanqu.qupai.engine.session.VideoSessionClient; import com.duanqu.qupai.engine.session.VideoSessionCreateInfo; import com.duanqu.qupai.frontend.android.RenderTask; import com.duanqu.qupai.license.LicenseMessage; import com.duanqu.qupai.media.android.ProjectPlayer; import com.duanqu.qupai.media.android.ProjectPlayerControl; import com.duanqu.qupai.orch.SoundProjectFactory; import com.duanqu.qupai.orch.android.SoundProjectFactoryClient; import com.duanqu.qupai.project.Project; import com.duanqu.qupai.project.ProjectConnection; import com.duanqu.qupai.project.ProjectUtil; import com.duanqu.qupai.project.UIEditorPage; import com.duanqu.qupai.project.UIMode; import com.duanqu.qupai.project.WorkspaceClient; import com.duanqu.qupai.render.RenderTaskManager; import com.duanqu.qupai.stage.SceneFactory; import com.duanqu.qupai.stage.android.BitmapLoader; import com.duanqu.qupai.stage.android.SceneFactoryClient; import com.duanqu.qupai.stage.android.Stage; import com.duanqu.qupai.stage.android.StageHost; import com.duanqu.qupaiui.editor.EditParticipant; import com.duanqu.qupaiui.editor.EditorAction; import com.duanqu.qupaiui.editor.EditorSession; import com.duanqu.qupaiui.editor.MVChooserMediator2; import com.duanqu.qupaiui.editor.ProjectClientDelegate; import com.duanqu.qupaiui.editor.ScaleTypeFormat; import com.duanqu.qupaiui.editor.VideoEditBean; import com.duanqu.qupaiui.editor.VideoScaleHelper; import com.duanqu.qupaiui.editor.download.ServerResourceManager; import com.duanqu.qupaiui.render.RenderConf; import com.duanqu.qupaiui.render.RenderConfImpl; import com.duanqu.qupaiui.render.SceneFactoryClientImpl; import com.duanqu.qupaiui.session.RenderRequest; import com.duanqu.qupaiui.session.VideoSessionClientFactoryImpl; import com.xunlei.shortvideo.Config; import com.xunlei.shortvideo.fragment.VideoEditMiscFragment; import com.xunlei.shortvideo.fragment.VideoEditThumb2Fragment; import com.xunlei.shortvideo.fragment.VideoEditTitleFragment; import com.xunlei.shortvideo.hubble.Hubble; import com.xunlei.shortvideo.hubble.data.EditCoverPageClick; import com.xunlei.shortvideo.hubble.data.EditDoneData; import com.xunlei.shortvideo.hubble.data.FilterActData; import com.xunlei.shortvideo.hubble.data.MVClickData; import com.xunlei.shortvideo.hubble.data.UploadPubPageClick; import com.xunlei.shortvideo.model.SettingManager; import com.xunlei.shortvideo.model.Util; import com.xunlei.shortvideo.provider.UploadItemDataUtils; import com.xunlei.shortvideo.provider.VideoItemDataUtils; import com.xunlei.shortvideo.provider.dao.UploadItem; import com.xunlei.shortvideo.provider.dao.VideoItem; import com.xunlei.shortvideo.provider.dao.scan.AppInfo; import com.xunlei.shortvideo.provider.dao.scan.AppScanConfig; import com.xunlei.shortvideo.upload.UploadMission; import com.xunlei.shortvideo.upload.VideoCategory; import com.xunlei.shortvideo.upload.VideoMiscConfig; import com.xunlei.shortvideo.upload.VideoUploadManager; import com.xunlei.shortvideo.upload.VideoWorkSpaceConfig; import com.xunlei.shortvideo.upload.VideoWorkSpaceManager; import com.xunlei.shortvideo.upload.scan.AppScanConfigManager; import com.xunlei.shortvideo.user.UserContext; import com.xunlei.shortvideo.utils.AppUtils; import com.xunlei.shortvideo.utils.CustomThreadPool; import com.xunlei.shortvideo.utils.DebugLog; import com.xunlei.shortvideo.utils.DeviceUtils; import com.xunlei.shortvideo.utils.NetworkUtils; import com.xunlei.shortvideo.utils.SizeFormatter; import com.xunlei.shortvideo.utils.StringUtils; import com.xunlei.shortvideo.utils.ToastManager; import com.xunlei.shortvideo.video.ShortVideo; import com.xunlei.shortvideo.video.VideoSliceConfig; import com.xunlei.shortvideo.video.third.QupaiFilterChooseMediator; import com.xunlei.shortvideo.view.dialog.AlertDialog; import com.xunlei.shortvideo.view.dialog.VideoPublishProgressDialog; import java.io.File; import java.util.Date; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import cn.kuaipan.android.R; import de.greenrobot.event.EventBus; /** * Created by aaronliu on 2016/11/4. */ public class VideoPublishLocal3Activity extends VideoPublishBase2Activity implements ProjectPlayer.OnProgressCallback, ProjectClient.OnChangeListener, RenderTaskManager.OnRenderTaskListener { protected static final String EXTRA_SHORT_VIDEO = "short_video"; protected static final String EXTRA_VIDEO_PROJECT = "project"; private static final String TAG = VideoPublishLocal3Activity.class.getSimpleName(); private static final int CHINESE_FILE_NAME_LIMITER = 5; private static final int UPLOAD_INTERVAL_LIMITER = 24 * 60 * 60 * 1000; private static final String RECORD_VIDEO_SAVE_PATH = Config.ROOT_DIR + "/video"; private static final int FILTER_TRIGGER_DISTANCE = 50; private static final float FILTER_TRIGGER_BIAS = 0.577f; //tan 30 = 0.577; private VideoItem mVideoItem; private String mVideoPath; private VideoUploadManager mManager; private UploadItem mLatestUpload; protected VideoWorkSpaceConfig mConfig; protected SurfaceView mVideoSurface; protected LinearLayout mBottomOpBar; protected FrameLayout mMvChooseContainer; protected TextView mBtnChooseMv; protected FrameLayout mFilterOpLayer; protected TextView mFilterNameTv; private QupaiFilterChooseMediator mFilterChooserMediator; private MVChooserMediator2 mMVChooserMediator; private float mDownX; private boolean mFilterChanged; private long duration; private int mFilterIndex; private SurfaceView mDisplaySurface; private ProjectPlayerControl mPlayer; private Project mProject; private RenderConf mRenderConf; private Stage mStage; private EditorSession mEditorSession; private ProjectConnection mProjectConnection; private VideoSessionClient mSessionClient; private AssetRepository mDataProvider; private ProjectClient mClient; private ProjectClientDelegate mClientDelegate; private Uri mProjectUri; private AssetRepositoryClient mRepoClient; private EditorAction mActionParser; private RecyclerView mMVlist; private RenderTaskManager mRenderTaskManager; private boolean mIsResumed = false; private VideoSessionCreateInfo mVideoSessionCreateInfo; private StageHost mStageHost; private LinearLayout mHorizontalScrollTipsView; private String mExportPath; private VideoPublishProgressDialog mRenderDialog; private AtomicBoolean mRendering = new AtomicBoolean(false); private AtomicBoolean mFilterActOnce = new AtomicBoolean(false); private Long mUserId; private PowerManager.WakeLock mWakeLock; public static void startActivityForResult(Activity activity, ShortVideo video, Uri uri, String topic, int code) { Intent intent = new Intent(activity, VideoPublishLocal3Activity.class); intent.putExtra(EXTRA_SHORT_VIDEO, video); intent.putExtra(EXTRA_TOPIC, topic); intent.putExtra(EXTRA_VIDEO_PROJECT, uri); activity.startActivityForResult(intent, code); } @Override protected void onCreate(Bundle savedInstanceState) { getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); super.onCreate(savedInstanceState); // if (TextUtils.isEmpty(mVideoPath) || !checkExistLocalFile(mVideoPath)) { // Toast.makeText(this, R.string.file_not_exist, Toast.LENGTH_SHORT).show(); // finish(); // } mManager = VideoUploadManager.getInstance(this); VideoWorkSpaceManager manager = VideoWorkSpaceManager.getInstance(this); mConfig = manager.getConfig("", VideoWorkSpaceManager.VideoType.local); mConfig.setUploadType(VideoWorkSpaceConfig.WORK_SPACE_MISC_UPLOADTYPE_SELF); mUserId = UserContext.getInstance(this).getLoginUid(); mWakeLock = ((PowerManager) getSystemService(POWER_SERVICE)) .newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, TAG); //add qupai. initQupaiEditor(); } @Override protected int geContentViewId() { return R.layout.activity_video_publish_local; } @Override public void onBackPressed() { if (isMVMode()) { hideMV(); return; } super.onBackPressed(); } @Override protected void onStart() { super.onStart(); mClientDelegate.addOnChangeListenerUnique(this); mClient.onStart(); mEditorSession.onStart(); } @Override protected void onResume() { super.onResume(); mRepoClient.connect(); onChange(mClient); mIsResumed = true; mPlayer.onStart(); mPlayer.onResume(); mEditorSession.onResume(); mActionParser.onResume(); keepOn(true); } @Override protected void onPause() { keepOn(false); mIsResumed = false; mPlayer.onPause(); mPlayer.onStop(); mEditorSession.onPause(); mRepoClient.disconnect(); mActionParser.onPause(); super.onPause(); } @Override protected void onStop() { mEditorSession.onStop(); super.onStop(); } @Override protected void onDestroy() { mPlayer.onDestroy(); mClient.onDestroy(); super.onDestroy(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_VIDEO_COVER && resultCode == RESULT_OK && data != null) { VideoSliceConfig config = (VideoSliceConfig) data .getSerializableExtra(VideoSliceConfig.VIDEO_SLICE_CONFIG); // setThumb(config.getPath(), config.getIndex(), config.getTotal()); mConfig.setIndex(config.getIndex()); mConfig.setTotal(config.getTotal()); mConfig.setCoverOffset(config.getTime()); mConfig.setUseCover(true); } if (requestCode == REQUEST_CODE_VIDEO_PERMISSION && resultCode == RESULT_OK && data != null) { mMiscConfig = (VideoMiscConfig) data.getSerializableExtra(VideoMiscConfig.VIDEO_MISC_CONFIG); } if (requestCode == RenderRequest.RENDER_MODE_EXPORT_VIDEO && resultCode == RESULT_OK && data != null) { long duration = data.getLongExtra("duration", 0); String path = data.getStringExtra("path"); File file = new File(path); loadExportedVideo(duration, file.getAbsolutePath()); } } @Override public void onAction(int id, int action, Intent data) { super.onAction(id, action, data); if (id == FRAGMENT_ID_VIDEO_COVER && action == ACTION_DONE && data != null) { VideoSliceConfig config = (VideoSliceConfig) data .getSerializableExtra(VideoSliceConfig.VIDEO_SLICE_CONFIG); mConfig.setIndex(config.getIndex()); mConfig.setTotal(config.getTotal()); mConfig.setCoverOffset(config.getTime()); mConfig.setUseCover(true); } if (id == FRAGMENT_ID_VIDEO_PERMISSION && action == ACTION_DONE && data != null) { mMiscConfig = (VideoMiscConfig) data.getSerializableExtra(VideoMiscConfig.VIDEO_MISC_CONFIG); } } @Override protected void initFromSaveInstance(Bundle savedInstance) { mVideo = (ShortVideo) savedInstance.getSerializable(EXTRA_SHORT_VIDEO); mProjectUri = (Uri) savedInstance.getParcelable(EXTRA_VIDEO_PROJECT); if (mVideo != null) { // mVideoPath = mVideo.videoUrl; } } @Override protected void initFromIntent(Intent intent) { mVideo = (ShortVideo) intent.getSerializableExtra(EXTRA_SHORT_VIDEO); mProjectUri = intent.getParcelableExtra(EXTRA_VIDEO_PROJECT); if (mVideo != null) { // mVideoPath = mVideo.videoUrl; } } @Override protected void saveInstance(Bundle outState) { if (mVideo != null) outState.putSerializable(EXTRA_SHORT_VIDEO, mVideo); if (mProjectUri != null) { outState.putParcelable(EXTRA_VIDEO_PROJECT, mProjectUri); } } @Override protected void onViewClick(View v) { switch (v.getId()) { case R.id.publish: { // String raw = mTvTitle.getText().toString(); mDefaultTopic = mDefaultTopic == null ? "" : mDefaultTopic; if (!TextUtils.isEmpty(mDefaultTopic) && !withSharp(mDefaultTopic)) { mDefaultTopic = autoAddSharp(mDefaultTopic); } mTitle = mTitle == null ? "" : mTitle; String raw = mDefaultTopic + mTitle; final String summary = StringUtils.replaceBackSpace(raw); if (!checkExistLocalFile(mConfig.getPath())) { // enableExportThumbnailTask(0, 20); // enableExportTask(20, 80); if (!mRendering.getAndSet(true)) { mPlayer.stop(); mProjectConnection.saveProject(UIMode.EDITOR); mEditorSession.onStop(); enableExportTask(0, 100); mRenderTaskManager.start(); // mProjectConnection.saveProject(UIMode.EDITOR); // RenderRequest request = new RenderProgressActivity.Request(PageRequest.from(this)) // .setProject(mProject.getUri()) // .setRenderMode(RenderRequest.RENDER_MODE_EXPORT_VIDEO); // request.startForResult(this, RenderRequest.RENDER_MODE_EXPORT_VIDEO); // RenderProgressActivity.startForResult(this, mProject.getUri(), RenderRequest.RENDER_MODE_EXPORT_VIDEO); showLoadingView(true); } return; } // if (checkVideoUploadTime()) { // Toast.makeText(getApplicationContext(), R.string.upload_video_forbidden, Toast.LENGTH_SHORT).show(); // return; // } if (!NetworkUtils.hasInternet(getApplicationContext())) { Toast.makeText(getApplicationContext(), R.string.no_network_tip, Toast.LENGTH_SHORT).show(); return; } if (mVideoItem == null) { // just return. may not be initialized here. return; } statistic_click_publish(mVideoItem, summary); // set config state mConfig.setOriginal(mMiscConfig.isOrigin() ? VideoWorkSpaceConfig.WORK_SPACE_MISC_ORIGINAL : VideoWorkSpaceConfig.WORK_SPACE_MISC_ORIGINAL_NOT); mConfig.setEncryptType( mMiscConfig.isOnlyToFans() ? VideoWorkSpaceConfig.WORK_SPACE_MISC_ENCRYPTTYPE_ONLYFANS : VideoWorkSpaceConfig.WORK_SPACE_MISC_ENCRYPTTYPE_ALL); if (NetworkUtils.isMobileNetwork(getApplicationContext())) { showDataConsumptionDialog(this, mVideoItem, mTitle, mDefaultTopic, new OnDataConsumptionClicked() { @Override public void onClick(boolean confirmed) { if (confirmed) { mManager.request(mVideoItem, summary, mTitle, mDefaultTopic, true); ToastManager.show(getApplicationContext(), R.string.uploading_video); showBindAndFinish(); } } }); } else { mManager.request(mVideoItem, mTitle, mDefaultTopic); ToastManager.show(getApplicationContext(), R.string.uploading_video); showBindAndFinish(); } // MediaController.getInstance().scheduleVideoConvert(mVideoPath); } break; case R.id.close: break; case R.id.known: mHorizontalScrollTipsView.setVisibility(View.GONE); SettingManager.setFirstEnterVideoEdit(false); break; default: break; } } @Override protected Fragment createFragment(int id) { switch (id) { case FRAGMENT_ID_VIDEO_COVER: return VideoEditThumb2Fragment.newInstance(mProjectUri, id, mConfig != null ? mConfig.getIndex() : 0); case FRAGMENT_ID_VIDEO_TOPIC: return VideoEditTitleFragment.newTopicInstance(autoRemoveSharp(mDefaultTopic), "", "", id); case FRAGMENT_ID_VIDEO_EDIT: hideMV(); return VideoEditTitleFragment.newTitleInstance(mTitle, "", "", id); case FRAGMENT_ID_VIDEO_PERMISSION: VideoMiscConfig config = VideoMiscConfig.copy(mMiscConfig); return VideoEditMiscFragment.newInstance(mVideo, config, id); default: return null; } } @Override protected void postInitUI() { // String fileName = parseVideoName(mVideoPath); // if (Util.getChineseCount(fileName) >= CHINESE_FILE_NAME_LIMITER) { // mTvTitle.append(fileName); // } // File file = new File(mVideoPath); // mVideoSurface = (SurfaceView) findViewById(R.id.surface_view); // mVideoView.setContentUri(Uri.fromFile(file)); // mVideoView.setLoopedPlay(true); // mVideoView.setLoadingEnable(true); mBottomOpBar = (LinearLayout) findViewById(R.id.bottom_opbar); mMvChooseContainer = (FrameLayout) findViewById(R.id.effect_chooser_container); mBtnChooseMv = (TextView) findViewById(R.id.mv); mFilterOpLayer = (FrameLayout) findViewById(R.id.filter); mFilterNameTv = (TextView) findViewById(R.id.filterName); mHorizontalScrollTipsView = (LinearLayout) findViewById(R.id.horizontal_scroll_tips); TextView known = (TextView) findViewById(R.id.known); if (SettingManager.isFirstEnterVideoEdit()) { mHorizontalScrollTipsView.setVisibility(View.VISIBLE); mHorizontalScrollTipsView.setOnClickListener(this); known.setOnClickListener(this); } else { mHorizontalScrollTipsView.setVisibility(View.GONE); } } @Override protected void postLoadData() { // VideoMiscConfig config = VideoMiscManager.getInstance(this).getConfigForPath(mVideoPath); // mMiscConfig = VideoMiscConfig.copy(config); mMiscConfig = new VideoMiscConfig("", true, false, ""); // loadVideoItem(); } private boolean checkExistLocalFile(String path) { if (TextUtils.isEmpty(path)) return false; File file = new File(path); return file.exists(); } private void showBindAndFinish() { if (!UserContext.getInstance(this).isExistPhoneAccount()) { AppUtils.showBindPhoneDialog(this); } else { setResult(RESULT_OK); finish(); } } private void keepOn(boolean on) { if (on) { if (!mWakeLock.isHeld()) { mWakeLock.acquire(); } } else { if (mWakeLock.isHeld()) { mWakeLock.release(); } } } private String parseVideoName(String path) { File file = new File(path); if (file.exists()) { return Util.getNameFromFilename(file.getName()); } return ""; } private boolean checkVideoUploadTime() { return mLatestUpload != null && System.currentTimeMillis() - mLatestUpload.getUploadTime() < UPLOAD_INTERVAL_LIMITER && mLatestUpload.getUploadState() != UploadMission.UploadState.failed.ordinal(); } private void loadVideoItem(String path) { mVideoPath = path; VideoItemDataUtils dataUtils = new VideoItemDataUtils(VideoItem.class); UploadItemDataUtils uploadUtils = new UploadItemDataUtils(UploadItem.class); List<VideoItem> items = dataUtils.loadByPath(mVideoPath); if (items.isEmpty()) { DebugLog.d(TAG, "something wrong happened, leave it be!"); //TODO: if return, mVideoItem will be null. //return; } mVideoItem = items.get(0); if (TextUtils.isEmpty(mVideoItem.getGcid())) mVideoItem.setGcid(DeviceUtils.calcGcid(mVideoItem.getFileAbsolutePath())); List<UploadItem> uploads = !TextUtils.isEmpty(mVideoItem.getGcid()) ? uploadUtils.loadByGcid(mVideoItem.getGcid()) : null; if (uploads != null && !uploads.isEmpty()) { mLatestUpload = uploads.get(0); } else { uploads = uploadUtils.loadByPath(mVideoPath); if (uploads != null && !uploads.isEmpty()) { mLatestUpload = uploads.get(0); } } // mConfig = manager.getConfig(mVideoPath, VideoWorkSpaceManager.VideoType.local); statistic_open(mVideoItem); EventBus.getDefault().post(new EventData()); } @Override public void onProgress(ProjectPlayer projectPlayer, long l) { // DebugLog.d(TAG, "time_nano" + TimeUnitUtil.nanosToMilliseconds(l)); } @Override public void onRenderTaskError(LicenseMessage licenseMessage) { showLoadingView(false); mPlayer.start(); ToastManager.show(this, getResources().getString(R.string.video_publish_render_error)); Hubble.onEvent(this, new EditDoneData("n")); } @Override public void onRenderTaskProgress(int i) { mRenderDialog.setProgress(i); } @Override public void onRenderTaskCompletion(long l) { mRenderDialog.setProgress(100); mPlayer.start(); Hubble.onEvent(this, new EditDoneData("y")); long duration = mProject.getDurationNano() / 1000000;// File exportedFile = new File(mExportPath);// //insert it into database and re-trigger upload. String path = exportedFile.getAbsolutePath(); loadExportedVideo(duration, path); } public interface OnDataConsumptionClicked { public void onClick(boolean confirmed); } private void showDataConsumptionDialog(final Activity activity, VideoItem item, final String title, final String topic, final OnDataConsumptionClicked listener) { String consumption = SizeFormatter.formatFileSize(activity, item.getFileSize()); AlertDialog dialog = new AlertDialog.Builder(activity) .setTitle(R.string.video_data_consumption_dialog_title) .setMessage(String.format( activity.getResources().getString(R.string.video_data_consumption_dialog_message), consumption)) .setPositiveButton(R.string.video_data_consumption_confirm, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { if (listener != null) listener.onClick(true); statistic_traffic_tips(mVideoItem, topic + title, "upload"); } }).setNegativeButton(R.string.video_data_consumption_cancel, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { statistic_traffic_tips(mVideoItem, topic + title, "cancel"); } }).create(); dialog.show(); } private void loadExportedVideo(final long duration, final String path) { CustomThreadPool.asyncWork(new Runnable() { @Override public void run() { mConfig.setPath(path); VideoWorkSpaceManager.getInstance(VideoPublishLocal3Activity.this).saveConfig(path, mConfig); insertIntoDatabase(path, duration); loadVideoItem(path); } }); } private void initQupaiEditor() { //????? mSessionClient = new VideoSessionClientFactoryImpl().createSessionClient(this, null); WorkspaceClient workspace = mSessionClient.createWorkspace(this); mProjectConnection = new ProjectConnection(workspace); mActionParser = new EditorAction(mActionExecutor); mDataProvider = mSessionClient.getAssetRepository(); mVideoSessionCreateInfo = mSessionClient.getCreateInfo(); //?? SceneFactoryClient sceneFactoryClient = new SceneFactoryClientImpl(this, mDataProvider, mSessionClient.getJSONSupport()); //?? SoundProjectFactoryClient soundFactoryClient = new SoundProjectFactoryClient(mDataProvider); mStageHost = new StageHost.Builder().addBitmapResolver(new BitmapLoader(this)) // .addBitmapResolver(new BitmapGenerator(sceneFactoryClient)) .get(); // //intent?project,??savejson,?jsonproject String projectFilePath = mProjectUri.getPath(); File projectFile = new File(projectFilePath); //?project.json???project mProject = ProjectUtil.readProject(projectFile, mSessionClient.getJSONSupport()); if (mProject != null) { mProject.setProjectDir(projectFile.getParentFile(), projectFile); mProjectConnection.setProject(mProject); } //??.?1:1????. // if(mProject.getRotation() == 90 || mProject.getRotation() == 270){ // mProject.setCanvasSize(mSessionClient.getProjectOptions().videoHeight, mSessionClient.getProjectOptions().videoWidth); // }else { // mProject.setCanvasSize(mSessionClient.getProjectOptions().videoWidth, mSessionClient.getProjectOptions().videoHeight); // } mClient = new ProjectClient(mProjectConnection, mDataProvider, sceneFactoryClient, soundFactoryClient, mSessionClient.getJSONSupport()); mClient.setDurationLimit(mProject.getDurationNano()); mClient.setVideoFramerate(mSessionClient.getProjectOptions().videoFrameRate); mClientDelegate = new ProjectClientDelegate(mClient); mRepoClient = new AssetRepositoryClient(mDataProvider); // mPlayer = new ProjectPlayerControl(mStageHost); mPlayer.setOnProgressCallback(this); // setContentView(R.layout.activity_editor); mClient.setOnChangeListener(mClientDelegate); //? mRenderConf = new RenderConfImpl(mProject, sceneFactoryClient, soundFactoryClient, mSessionClient.getJSONSupport()); // mRenderConf.setVideoFrameRate(mSessionClient.getProjectOptions().videoFrameRate); // mRenderConf.setDurationLimit(TimeUnit.NANOSECONDS.toMillis(mProject.getDurationNano())); mEditorSession = new EditorSession(this, mPlayer, mDataProvider, mRenderConf, mSessionClient.getPageNavigator(), mClient); mStage = new Stage(mStageHost); mStage.realize(); mDisplaySurface = (SurfaceView) findViewById(R.id.surface_view); //? int screenWidth = getResources().getDisplayMetrics().widthPixels; int screenHeight = getResources().getDisplayMetrics().heightPixels; FrameLayout.LayoutParams lp = (FrameLayout.LayoutParams) mDisplaySurface.getLayoutParams(); VideoScaleHelper helper = new VideoScaleHelper(); helper.setVideoWidthAndHeight(mClient.getVideoWidth(), mClient.getVideoHeight()) .setScreenWidthAndHeight(screenWidth, screenHeight).generateDisplayLayoutParams(lp); SurfaceHolder holder = mDisplaySurface.getHolder(); mPlayer.getImpl().setSurface(holder); // AspectRatioLayout video_frame = (AspectRatioLayout) findViewById(R.id.video); // video_frame.setOriginalSize(480, 480); // ViewStack view_stack = new ViewStack(View.INVISIBLE); // view_stack.addView(findViewById(R.id.effect_list_filter)); // RecyclerView filter_list_view = (RecyclerView) findViewById(R.id.effect_list_filter); mMVlist = (RecyclerView) findViewById(R.id.effect_list_mv); // mFilterChooserMediator = new QupaiFilterChooseMediator(mClient, mDataProvider); mClientDelegate.addOnChangeListener(mFilterChooserMediator); mMVChooserMediator = new MVChooserMediator2(mMVlist, mEditorSession, mClientDelegate, mRepoClient); mMVChooserMediator.setMVItemClickListener(new MVChooserMediator2.OnMVItemClickListener() { @Override public void onItemClick(RecyclerView.Adapter adapter, View view, int position) { //reset filter mFilterIndex = 0; mFilterChooserMediator.setChecked(mFilterIndex); mConfig.setUseFilter(false); mConfig.setUseMV(position != 0); } }); // ?MV new LoadDownloadMVTask().execute(); //?,? mEditorSession.setPart(UIEditorPage.FILTER_EFFECT, mFilterChooserMediator); mEditorSession.setPart(UIEditorPage.MV, mMVChooserMediator); mEditorSession.updatePlayer(Integer.MAX_VALUE); mPlayer.start(); mRenderTaskManager = new RenderTaskManager(getApplicationContext()); mRenderTaskManager.setOnRenderTaskListener(this); mFilterIndex = 0; final int total = mFilterChooserMediator.getCount(); final GestureDetector detector = new GestureDetector(new GestureDetector.OnGestureListener() { @Override public boolean onDown(MotionEvent e) { mFilterChanged = false; return false; } @Override public void onShowPress(MotionEvent e) { } @Override public boolean onSingleTapUp(MotionEvent e) { hideMV(); mFilterChanged = false; return true; } @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { float x = Math.abs(distanceX); if (x >= FILTER_TRIGGER_DISTANCE && !isMVMode()) { float y = Math.abs(distanceY); if ((y / x) < FILTER_TRIGGER_BIAS && !mFilterChanged) { //0.577 is 30 degree if (distanceX < 0) { statistic_click_filter(); mFilterChanged = true; mFilterIndex++; if (mFilterIndex >= total) { mFilterIndex = 0; } // Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged); mMVChooserMediator.resetPosition(0); mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT); mFilterChooserMediator.setChecked(mFilterIndex); mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex)); mFilterNameTv.setAlpha(1); mFilterNameTv.animate().alpha(0).setDuration(2000).start(); } else { statistic_click_filter(); mFilterChanged = true; mFilterIndex--; if (mFilterIndex < 0) { mFilterIndex = total - 1; } // Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged); mMVChooserMediator.resetPosition(0); mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT); mFilterChooserMediator.setChecked(mFilterIndex); mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex)); mFilterNameTv.setAlpha(1); mFilterNameTv.animate().alpha(0).setDuration(2000).start(); } mConfig.setUseFilter(mFilterIndex != 0); mConfig.setUseMV(false); return true; } } return false; } @Override public void onLongPress(MotionEvent e) { } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; } }); mFilterOpLayer.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { detector.onTouchEvent(event); return true; } }); // mFilterOpLayer.setOnTouchListener(new View.OnTouchListener() { // // @Override // public boolean onTouch(View v, MotionEvent event) { // switch (event.getAction()) { // case MotionEvent.ACTION_DOWN: // hideMV(); // mDownX = event.getX(); // mFilterChanged = false; //// Log.d(TAG, "DownX is " + mDownX + " mFilterChanged is " + mFilterChanged); // return true; // case MotionEvent.ACTION_MOVE: // if((event.getX() - mDownX > 50) && !mFilterChanged) { // statistic_click_filter(); // mFilterChanged = true; // mFilterIndex ++; // if(mFilterIndex >= total) { // mFilterIndex = 0; // } //// Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged); // mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT); // mFilterChooserMediator.resetPosition(mFilterIndex); // mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex)); // mFilterNameTv.setAlpha(1); // mFilterNameTv.animate().alpha(0).setDuration(2000).start(); // //select next // return true; // } else if((mDownX - event.getX() > 50) && !mFilterChanged) { // //select pre // statistic_click_filter(); // mFilterChanged = true; // mFilterIndex --; // if(mFilterIndex < 0) { // mFilterIndex = total -1; // } //// Log.d(TAG, "event.getx is " + event.getX() + " DownX is " + mDownX + " mFilterChanged is " + mFilterChanged); // mEditorSession.setActiveEditorPage(UIEditorPage.FILTER_EFFECT); // mFilterChooserMediator.resetPosition(mFilterIndex); // mFilterNameTv.setText(mFilterChooserMediator.getItemTitle(mFilterIndex)); // mFilterNameTv.setAlpha(1); // mFilterNameTv.animate().alpha(0).setDuration(2000).start(); // return true; // } // break; // case MotionEvent.ACTION_UP: // mFilterChanged = false; // return false; // } // return false; // } // }); mBtnChooseMv.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mMvChooseContainer.getVisibility() != View.VISIBLE) { mBottomOpBar.setVisibility(View.GONE); mMvChooseContainer.setVisibility(View.VISIBLE); statistic_click_mv(); } else { mBottomOpBar.setVisibility(View.VISIBLE); mMvChooseContainer.setVisibility(View.GONE); } } }); mMvChooseContainer.setVisibility(View.GONE); initDir(); } protected void hideMV() { if (mMvChooseContainer.getVisibility() == View.VISIBLE) { mBottomOpBar.setVisibility(View.VISIBLE); mMvChooseContainer.setVisibility(View.GONE); } } protected boolean isMVMode() { return mMvChooseContainer.getVisibility() == View.VISIBLE; } public void onChange(ProjectClient client) { Log.d("TIMEEDIT", "onChange VideoEditFragment2"); onChange(client, Integer.MAX_VALUE); } @Override public void onChange(ProjectClient client, int bits) { long s1 = System.currentTimeMillis(); if (!mClient.hasProject()) { return; } // UIEditorPage page = mClient.getActiveEditorPage(); // if(page == UIEditorPage.MV) { // mMvChooseContainer.setVisibility(View.GONE); // mBottomOpBar.setVisibility(View.VISIBLE); // } mEditorSession.updatePlayer(bits); mPlayer.start(); // Log.d("TIMEEDIT", "notifyChange item VideoEditFragment2 : " + bits + " " + (System.currentTimeMillis() - s1)); } //ExportTask private void enableExportTask(int progress, int total) { // String export_path = mRenderConf.getRenderOutputFilePath(); mExportPath = RECORD_VIDEO_SAVE_PATH + File.separator + new Date().getTime() + ".mp4"; SceneFactory.SceneOptions scene_opt = mRenderConf.newSceneOptions(); scene_opt.flags = Project.GENERATE_MODE_FULL_ADD_WATERMARK; scene_opt.watermarkPath = mVideoSessionCreateInfo.getWaterMarkPath(); scene_opt.watermarkPostion = mVideoSessionCreateInfo.getWaterMarkPosition(); SoundProjectFactory.SoundOptions sound_opt = mRenderConf.newSoundOptions(); String video_content = mRenderConf.getSceneJSON(scene_opt); String audio_content = mRenderConf.getSoundJSON(sound_opt); RenderTask task = new RenderTask(mStageHost); task.setVideoPixelFormat(RenderTask.PIXEL_FORMAT_NV12); MovieExportOptions options = mVideoSessionCreateInfo.getMovieExportOptions(); if (null != options) { task.configureVideo(options.getVideoEncoderOptions()); task.configureMuxer(options.getMuxerOptions()); task.setFileFormat(options.getFileFormat()); } task.setContent(video_content, audio_content, mRenderConf.getBaseURL()); task.setOutputURL(mExportPath); mRenderTaskManager.addTask(task, progress, total); } private void initDir() { File dir = new File(RECORD_VIDEO_SAVE_PATH); if (!dir.exists()) { dir.mkdir(); } } //ThumbnailTask private void enableExportThumbnailTask(int progress, int total) { ThumbnailExportOptions options = mVideoSessionCreateInfo.getThumbnailExportOptions(); SceneFactory.SceneOptions scene_opt = mRenderConf.newSceneOptions(); scene_opt.flags = Project.GENERATE_MODE_FULL_ADD_WATERMARK; scene_opt.frameCount = options.count; scene_opt.width = mRenderConf.getVideoWidth(); scene_opt.height = mRenderConf.getVideoHeight(); scene_opt.watermarkPath = mVideoSessionCreateInfo.getWaterMarkPath(); scene_opt.watermarkPostion = mVideoSessionCreateInfo.getWaterMarkPosition(); String video_content = mRenderConf.getSceneJSON(scene_opt); String export_thumbnail_path = mRenderConf.getExportThumbnailPath(); RenderTask task = new RenderTask(mStageHost); task.setContent(video_content, null, mRenderConf.getBaseURL()); task.setOutputURL(export_thumbnail_path); mRenderTaskManager.addTask(task, progress, total); } private void insertIntoDatabase(String filePath, long duration) { String appName = ""; AppScanConfigManager manager = AppScanConfigManager.getInstance(this); File file = new File(filePath); File parent = file.getParentFile(); AppScanConfig config = null; if (parent != null) { config = manager.getConfigForPath(parent.getAbsolutePath()); } AppInfo appInfo = null; if (config != null) { appInfo = manager.getAppInfoByAppId(config.getAppId()); } if (appInfo != null) { appName = appInfo.getAppName(); } else { PackageManager packageManager = this.getPackageManager(); try { PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); appName = buildAppName(info.applicationInfo.loadLabel(packageManager).toString()); } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); } } if (TextUtils.isEmpty(appName)) { appName = buildAppName(""); } String packageName = getPackageName(); VideoItem item = new VideoItem(); createVideo(item, file, appName, packageName, duration); VideoItemDataUtils dataUtils = new VideoItemDataUtils(VideoItem.class); dataUtils.insert(item); } private String buildAppName(String rawName) { return String.format("zh_cn=%s&zh_tw=%s&=", rawName, rawName); } private void createVideo(VideoItem video, File file, String appName, String packName, long duration) { video.setAppName(appName); video.setFileAbsolutePath(file.getAbsolutePath()); video.setFileName(file.getName()); video.setFileSize(file.length()); video.setGcid(DeviceUtils.calcGcid(file.getAbsolutePath())); video.setModifyTime(file.lastModified()); video.setDuration(duration); video.setPackageName(packName); } private void showLoadingView(boolean show) { // View loadingView = findViewById(R.id.empty_view); // if (loadingView != null) { // loadingView.setVisibility(show ? View.VISIBLE : View.GONE); // loadingView.findViewById(R.id.empty_icon).setVisibility(View.GONE); // loadingView.findViewById(R.id.loading_progress).setVisibility(show ? View.VISIBLE : View.GONE); // ((TextView) loadingView.findViewById(R.id.empty_message)).setText(R.string.file_loading); // } if (mRenderDialog != null && mRenderDialog.isShowing()) { mRenderDialog.dismiss(); } if (show) { mRenderDialog = VideoPublishProgressDialog.show(this, getResources().getString(R.string.file_rendering), false, null); } } private void statistic_open(VideoItem item) { //AnalyticsAgent.trackEvent(new VideoPublishData(item)); } private void statistic_click_tag(VideoItem item, String tag) { // AnalyticsAgent.trackEvent(new VideoPublishTagClick(item, tag, "upload_pub_page")); } protected void statistic_click_publish(VideoItem item, String summary) { //AnalyticsAgent.trackEvent(new VideoPublishDataClick(item, summary)); int original = mMiscConfig.isOrigin() ? VideoWorkSpaceConfig.WORK_SPACE_MISC_ORIGINAL : VideoWorkSpaceConfig.WORK_SPACE_MISC_ORIGINAL_NOT; int encrypt = mMiscConfig.isOnlyToFans() ? VideoWorkSpaceConfig.WORK_SPACE_MISC_ENCRYPTTYPE_ONLYFANS : VideoWorkSpaceConfig.WORK_SPACE_MISC_ENCRYPTTYPE_ALL; String coverType = mConfig.isUseCover() ? VideoWorkSpaceConfig.WORK_SPACE_COVER : VideoWorkSpaceConfig.WORK_SPACE_COVER_NONE; String filterType = mConfig.isUseFilter() ? VideoWorkSpaceConfig.WORK_SPACE_FILTER : VideoWorkSpaceConfig.WORK_SPACE_FILTER_NONE; String mvType = mConfig.isUseMV() ? VideoWorkSpaceConfig.WORK_SPACE_MV : VideoWorkSpaceConfig.WORK_SPACE_MV_NONE; if (mVideoItem != null && !TextUtils.isEmpty(mVideoItem.getPackageName()) && mVideoItem.getPackageName().equals(VideoCategory.cn_kuaipan_android.getName())) { Hubble.onEvent(this, new UploadPubPageClick(mUserId, item, summary, "shoot", String.valueOf(original), String.valueOf(encrypt), coverType, filterType, mvType, mTitle, autoRemoveSharp(mDefaultTopic))); } else { Hubble.onEvent(this, new UploadPubPageClick(mUserId, item, summary, "next", String.valueOf(original), String.valueOf(encrypt), coverType, filterType, mvType, mTitle, autoRemoveSharp(mDefaultTopic))); } } private void statistic_traffic_tips(VideoItem item, String summary, String state) { //AnalyticsAgent.trackEvent(new VideoUploadTrafficTipsData(item, summary, state)); } private void statistic_click_edit_cover() { //AnalyticsAgent.trackEvent(new VideoPublishDataClick(item, summary)); Hubble.onEvent(this, new EditCoverPageClick()); } private void statistic_click_mv() { Hubble.onEvent(this, new MVClickData()); } private void statistic_click_filter() { if (!mFilterActOnce.getAndSet(true)) { Hubble.onEvent(this, new FilterActData()); } } public void onEventMainThread(EventData data) { showLoadingView(false); onViewClick(mIBtnUpload); mRendering.set(false); // mIBtnUpload.setEnabled(true); } public void onEventMainThread(TrimEventData data) { } public static class EventData { } public static class TrimEventData { } private final EditorAction.Executor mActionExecutor = new EditorAction.Executor() { @Override public void doScrollToGroup(int type, int id) { // if(type == AssetInfo.TYPE_DIYOVERLAY) // diyOverlayMediator.getDIYOverlayMediator().setDIYCategoryUse(id); } @Override public void doScrollTo(AssetID asset_id) { UIEditorPage page; switch (asset_id.type) { case AssetInfo.TYPE_SHADER_MV: page = UIEditorPage.MV; break; case AssetInfo.TYPE_MUSIC: page = UIEditorPage.AUDIO_MIX; break; default: return; } EditParticipant part = mEditorSession.getPart(page); if (part != null) { part.scrollTo(asset_id); } // if (_Deleted_mv_lists != null) { // AssetID mv = mClient.getVideoMV(); // if (mv != null) { // int currentId = mv.id; // if (_Deleted_mv_lists.contains(currentId)) { // mClient.setMV(null); // mClient.commit(); // } // } // // _Deleted_mv_lists = null; // } } @Override public void doUseAsset(int type, int id, boolean confirmed) { if (id < 0) { return; } AssetID asset_id = new AssetID(type, id); switch (type) { case AssetInfo.TYPE_SHADER_MV: mEditorSession.useMV(asset_id, confirmed); break; case AssetInfo.TYPE_MUSIC: case AssetInfo.TYPE_MV_MUSIC: mEditorSession.useMusic(asset_id, confirmed); break; case AssetInfo.TYPE_DIYOVERLAY: // diyOverlayMediator.getDIYOverlayMediator().setDIYCategoryUse(id); break; } mClient.commit(); } @Override public void doDownload(int type, int id) { // if(type == AssetInfo.TYPE_DIYOVERLAY){ // diyOverlayMediator.getDIYOverlayMediator().setDIYCategoryDownload(id > 0); // } } @Override public void doSwitchPage(UIEditorPage page) { } @Override public void doStartDubbing(boolean confirmed) { // mEditorSession.startDubbing(confirmed); } }; class LoadDownloadMVTask extends AsyncTask<Void, Void, List<VideoEditBean>> { @Override protected List<VideoEditBean> doInBackground(Void... params) { return ServerResourceManager.getInstance(getApplicationContext()) .loadServerMVList(ScaleTypeFormat.SCALE_BROAD_9_16); } @Override protected void onPostExecute(List<VideoEditBean> videoEditBeen) { if (videoEditBeen != null && videoEditBeen.size() > 0 && mMVChooserMediator != null) { mMVChooserMediator.setDownloadMVAsset(videoEditBeen); } } } }