www.pudn.com > videoplayer.rar > PlayVideo.java, change:2011-03-04,size:21453b


package com.amlogic.amplayer; 
 
import java.io.File; 
import java.util.ArrayList; 
import java.util.List; 
 
import com.subtitleparser.MalformedSubException; 
import com.subtitleparser.Subtitle; 
import com.subtitleparser.SubtitleLine; 
import com.subtitleparser.*; 
 
import android.content.Intent; 
 
import android.app.Activity; 
import android.app.Dialog; 
import android.app.ProgressDialog; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Message; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.AdapterView; 
import android.widget.ArrayAdapter; 
import android.widget.ImageButton; 
import android.widget.LinearLayout; 
import android.widget.ListView; 
import android.widget.RelativeLayout; 
import android.widget.SeekBar; 
import android.widget.TextView; 
import android.widget.AdapterView.OnItemClickListener; 
import android.widget.SeekBar.OnSeekBarChangeListener; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import com.subtitleview.SubtitleView; 
 
public class PlayVideo extends Activity implements OnClickListener, OnSeekBarChangeListener { 
    private static final String TAG = "PlayVideo"; 
 
    //typedef enum { ... } player_status; 
    private static final int PLAYER_UNKNOWN  = 0; 
    private static final int PLAYER_STOPED   = 1; 
    private static final int PLAYER_RUNNING  = 2; 
    private static final int PLAYER_PAUSE    = 3; 
    private static final int PLAYER_SEARCHING= 4; 
    private static final int PLAYER_SEARCHOK = 5; 
    private static final int PLAYER_INITING  = 6; 
    private static final int PLAYER_ERROR    = 7; 
    private static final int PLAYER_PLAYEND  = 8; 
    private static final int PLAYER_START    = 9; 
    private static final int PLAYER_FF_END   = 10; 
    private static final int PLAYER_FB_END   = 11; 
    private static final int PLAYER_BUFFERING= 12; 
    private static final int PLAYER_INITOK   = 13; 
 
    static final int UPDATE_STATE_INTERVAL = (500); //in ms. 
    static final int STOP_TIMEOUT = (2 * 1000); 
     
    //peter added for callback... 
    private static final int CB_PLAYER_INFO = 0x1010; 
 
    private Handler mUpHandler; 
     
 
    private Handler mHandler; 
    private int mLastState = PLAYER_UNKNOWN; 
    private int mLastTime = -1, mLastTotalTime = 0; 
    private ProgressDialog mStopSpinner; 
    private RelativeLayout mLayout; 
    private RelativeLayout mControlsLayout;   
    private TextView mCurrTime, mTotalTime; 
    private SeekBar mSeekBar; 
    private ImageButton mPlayBtn;
    private int mOSDBpp; 
    //add for subtitle select; 
	private static String ROOT_PATH = "/"; 
    private List<String> dir_ent = new ArrayList<String>(); 
	private File cur_dir = new File(ROOT_PATH); 
	private ListView fileList = null;  
	private SubtitleView subTitle = null; 
    private LinearLayout listlayout; 
    private LinearLayout subtitlelayout; 
	private	String filename; 
	private SubtitleUtils subUtils=new SubtitleUtils(); 
 
	private native int native_reqstate(); 
	 
	static PlayVideo m_Instance = null; 

    private int getOSDBpp() { 
        int rc; 
        rc = Amplayer.native_getosdbpp();  
        Log.d(TAG, "native_getosdbpp() rc=" + rc);
        return rc; 
    }

    private void setGlobalAlpha(int alpha) { 
        int rc; 
        rc = Amplayer.native_setglobalalpha(alpha);  
        Log.d(TAG, "native_setglobalalpha() rc=" + rc); 
    }
    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
        super.onCreate(savedInstanceState);   
        m_Instance = this; 
        setContentView(R.layout.playvideolayout); 
        fileList  = (ListView) findViewById(R.id.FileList); 
		fileList.setOnItemClickListener(selItem); 
		subTitle = (SubtitleView) findViewById(R.id.subTitle); 
		//init subtitle_file_position 
//		Subtitle.subtitle_file_position = 0; 
		setResult(RESULT_OK, this.getIntent()); 
        mControlsLayout = (RelativeLayout) findViewById(R.id.controlsLayout); 
        if (mControlsLayout != null) { 
            mControlsLayout.setBackgroundColor(0x00000000); 
            mControlsLayout.setVisibility(View.INVISIBLE); 
        } 
        else 
            Log.d(TAG, "controlsLayout == null"); 
 
        mLayout = (RelativeLayout) findViewById(R.id.pvlayout); 
        if (mLayout == null) 
            Log.d(TAG, "mLayout == null"); 
 
        mCurrTime = (TextView) findViewById(R.id.currentTime); 
        mTotalTime = (TextView) findViewById(R.id.totalTime); 
        mSeekBar = (SeekBar) findViewById(R.id.seekBar); 
        if(mSeekBar != null) 
        { 
        	mSeekBar.setOnSeekBarChangeListener(this); 
        } 
         
        mPlayBtn = (ImageButton) findViewById(R.id.playBtn); 
        if (mPlayBtn != null) { 
            mPlayBtn.setOnClickListener(this); 
        } 
        ImageButton browserBtn = (ImageButton) findViewById(R.id.browserBtn); 
        if (browserBtn != null) { 
            browserBtn.setOnClickListener(this); 
        } 
        ImageButton subtitleBtn = (ImageButton) findViewById(R.id.subtitleBtn); 
        if (subtitleBtn != null) { 
        	subtitleBtn.setOnClickListener(this); 
        } 
        listlayout = (LinearLayout) findViewById(R.id.listLayout); 
        if (listlayout != null) { 
        	listlayout.setVisibility(View.INVISIBLE); 
        } 
 
        mHandler = new Handler(); 
        mUpHandler = new Handler() { 
    		public void handleMessage(Message msg) { 
    			Log.d(TAG,"mp msg:"+msg.what); 
    			if(msg.what == CB_PLAYER_INFO) 
    			{ 
    				PlayerCallbackInfo pcInfo = (PlayerCallbackInfo)msg.obj; 
    				if(pcInfo != null)    				 
    					onUpdateState(pcInfo.last_sta,pcInfo.status,pcInfo.duration,pcInfo.current,pcInfo.last_time,pcInfo.errcode);	 
    				 
    			} 
    		} 
    	};  
         
        mStopSpinner = null; 

        mOSDBpp = getOSDBpp(); 
 
        Bundle hpath = getIntent().getExtras(); 
        if (hpath != null) { 
            filename = (String)hpath.get("PATH"); 
            ROOT_PATH =filename.substring(0,filename.lastIndexOf('/'));  
   
            if(filename != null) 
            { 
                Log.d(TAG,"file chosen:" + filename); 
                //Amplayer.native_sendcmd("play:" + filename); 
                Amplayer.native_startcmd(filename);                 
                //startGetStates();
                if (mOSDBpp==32)
                    setGlobalAlpha(0x40); // for 32bpp 
                else
                    setColorKey(true); // for 16bpp
                
                return; 
            } 
        } 
        finish(); 
    } 
 
    @Override 
    public void onDestroy() { 
        super.onDestroy(); 
        int rc; 
        mHandler.removeCallbacks(mStopTimeout); 
        stopGetStates(); 
        Amplayer.native_sendcmd("stop"); 
        if (mStopSpinner != null) 
            mStopSpinner.dismiss(); 
        m_Instance = null;
        if (mOSDBpp==32)
            setGlobalAlpha(0xff); // for 32bpp 
        else
            setColorKey(false); // for 16bpp
    } 
     
    /** Called when hardware BACK key is pressed */ 
    @Override 
    public void onBackPressed() { 
        if (mControlsLayout != null) { 
            mControlsLayout.setVisibility(View.VISIBLE); 
        } 
        return; 
    } 
 
    //@Override 
    public void onClick(View source) { 
        final int sourceId = source.getId(); 
        if (sourceId == R.id.pvlayout) { 
            if (mControlsLayout != null) { 
                if (mControlsLayout.getVisibility() == View.VISIBLE) 
                    mControlsLayout.setVisibility(View.INVISIBLE); 
                else 
                    mControlsLayout.setVisibility(View.VISIBLE);            //TODO set invisible after a few seconds 
            } 
            if(listlayout != null&&listlayout.getVisibility() == View.VISIBLE) 
            { 
            	listlayout.setVisibility(View.INVISIBLE); 
            } 
        } 
        else if (sourceId == R.id.playBtn) { 
            if (mLastState == PLAYER_RUNNING) { 
                mPlayBtn.setBackgroundResource(R.drawable.play_button); 
                Amplayer.native_sendcmd("pause"); 
            } 
            else if (mLastState == PLAYER_PAUSE) { 
                mPlayBtn.setBackgroundResource(R.drawable.pause_button); 
                Amplayer.native_sendcmd("resume"); 
            } 
        } 
        else if (sourceId == R.id.browserBtn) { 
            mStopSpinner = ProgressDialog.show(PlayVideo.this, "", 
                    "Stopping...", true); 
            Amplayer.native_sendcmd("stop"); 
            mHandler.removeCallbacks(mStopTimeout); 
            mHandler.postDelayed(mStopTimeout, STOP_TIMEOUT); 
        }else if(sourceId == R.id.subtitleBtn) 
        { 
            Log.d( TAG, " receive click on subtitleBtn -----------------" ); 
        	popSubTitleOption(); 
        } 
    } 
    private void popSubTitleOption() 
    { 
        Log.d( TAG, " receive click on subtitleBtn --------------------" ); 
        Dialog dialog=new AlertDialog.Builder(PlayVideo.this) 
        .setTitle(R.string.subtitledilaogname) 
        .setItems(R.array.subtitleseletctlist, new DialogInterface.OnClickListener()  
        { 
            public void onClick(DialogInterface dialog, int which)  
            { 
 
                /* User clicked so do some stuff */ 
                Log.d(TAG, "onClick() =" + which); 
                switch(which) 
                { 
                	case 0: 
                		subTitle.setViewStatus(false); 
                		break; 
                	case 1: 
                		subTitle.setViewStatus(true); 
                		dialog.dismiss(); 
                    	browse(new File(ROOT_PATH)); 
                		break; 
                	case 2: 
//                		subTitle.setInsubStatus(true); 
						subUtils.setFileName(filename); 
						if(subUtils.getInSubTotal()>0) 
						{ 
							int index= subUtils.getSubTotal()-subUtils.getInSubTotal(); 
							String path =	subUtils.getSubPath(index);	 
							try { 
								if(subTitle.setFile(new SubID(path,0), "GBK")==Subtitle.SUBTYPE.SUB_INVALID) 
								{ 
									return; 
								} 
							} catch (Exception e) { 
								Log.d(TAG, "open:errrrrrrrrrrrrrrr"); 
								e.printStackTrace(); 
							} 
							Log.d(TAG, "path:" + path); 
                		} 
                		break; 
                	default: 
                		break; 
                } 
            } 
        }) 
        .create(); 
        dialog.show(); 
         
    } 
    private void setColorKey(boolean enable) { 
        int rc; 
        final short color = (0xf << 11) | (0x1f << 5) | (0xf << 0); 
        //final short color = 0; 
        if (enable) { 
            rc = Amplayer.native_enablecolorkey(color);  
            Log.d(TAG, "native_enablecolorkey() rc=" + rc); 
            if (rc == 0 && mLayout != null) { 
                mLayout.setBackgroundColor(0xff7f7f7f); 
                //layout.setBackgroundColor(0xff000000); 
            } 
        } 
        else { 
            if (mLayout != null) 
                mLayout.setBackgroundColor(0xff000000); 
            rc = Amplayer.native_disablecolorkey(); 
            Log.d(TAG, "native_disablecolorkey() rc=" + rc); 
        } 
    } 

    private Runnable mStopTimeout = new Runnable() { 
        public void run() { 
            Log.d(TAG, "mStopTimeout() - did not stop? quitting"); 
            stopGetStates(); 
            Amplayer.native_sendcmd("quitctrl"); 
            if (mOSDBpp==32)
                setGlobalAlpha(0xff); // for 32bpp 
            else
                setColorKey(false); // for 16bpp
            finish(); 
        } 
    }; 
     
    private Runnable mGetState = new Runnable() { 
        public void run() { 
            native_reqstate(); 
        } 
    }; 
 
    private void startGetStates() { 
        mHandler.removeCallbacks(mGetState); 
        mHandler.postDelayed(mGetState, UPDATE_STATE_INTERVAL); 
    } 
     
    private void stopGetStates() { 
        mHandler.removeCallbacks(mGetState); 
    } 
 
    private Runnable mStopped = new Runnable() { 
        public void run() { 
            stopGetStates(); 
            Amplayer.native_sendcmd("quitctrl"); 
            if (mOSDBpp==32)
                setGlobalAlpha(0xff); // for 32bpp 
            else
                setColorKey(false); // for 16bpp
            finish(); 
        } 
    }; 
     
    public static void onUpdateStateFromNative(int last_sta, int status, int full_time, 
            int current_time, int last_time, int error_no){ 
    	if(m_Instance != null){ 
	    	PlayerCallbackInfo pcInfo = new PlayerCallbackInfo(); 
	    	pcInfo.last_sta = last_sta; 
	    	pcInfo.status = status; 
	    	pcInfo.duration = full_time; 
	    	pcInfo.current = current_time; 
	    	pcInfo.last_time = last_time; 
	    	pcInfo.errcode = error_no;	    	 
			Message msg = m_Instance.mUpHandler.obtainMessage(CB_PLAYER_INFO,pcInfo); 
			m_Instance.mUpHandler.sendMessage(msg); 			 
    	} 	 
    } 
     
     
    /** 
     * Called in native thread(?) to update player state.  
     * 
     * startGetStates() -every UPDATE_STATE_INTERVAL-> 
     *    mGetState() -> native_reqstate() -JNI-> reqstate() -> onUpdateState() 
     */ 
    @SuppressWarnings("unused") 
    public void onUpdateState(int last_sta, int status, int full_time, 
                               int current_time, int last_time, int error_no) 
    { 
        //Log.d(TAG, "L369:mLastTime= " + mLastTime + " current_time= " + current_time); 
        if ((mLastTime != current_time)&& 
			((status == PLAYER_RUNNING)||(status == PLAYER_PLAYEND))) { 
         
            mLastTime = current_time; 
            mCurrTime.setText(secToTime(current_time)); 
            if (mLastTotalTime == 0) 
                mSeekBar.setProgress(0); 
            else 
                mSeekBar.setProgress(current_time*100/mLastTotalTime); 
			subTitle.tick(current_time*1000); 
        } 
        if (mLastTotalTime == 0 && full_time != 0) { 
            mLastTotalTime = full_time; 
            mTotalTime.setText(secToTime(full_time)); 
        } 
        if (mLastState != status) { 
            Log.d(TAG, "state changed: " + mLastState + " to " + status); 
            mLastState = status; 
            if (status == PLAYER_PLAYEND || status == PLAYER_STOPED) { 
                mHandler.post(mStopped); 
                return; 
            } 
            else if (status == PLAYER_RUNNING) { 
                mPlayBtn.setBackgroundResource(R.drawable.pause_button); 
            } 
            else if (status == PLAYER_PAUSE) { 
                mPlayBtn.setBackgroundResource(R.drawable.play_button); 
            } 
        } 
        if (status == PLAYER_ERROR || error_no != 0) 
        { 
        	  String InfoStr;			   
			  String ErrStr=String.format("(Error Code:-0x%x(%d))",-error_no,error_no); 
        	  switch (error_no) 
        	  { 
					case Errorno.PLAYER_UNSUPPORT: 
						InfoStr = "Unsupport Video and Audio format"; 
						break; 
					case Errorno.PLAYER_UNSUPPORT_VIDEO: 
						InfoStr = "Unsupport Video format"; 
						break; 
					case Errorno.PLAYER_UNSUPPORT_AUDIO: 
						InfoStr = "Unsupport Audio format"; 
						break; 
					case Errorno.FFMPEG_OPEN_FAILED: 
						InfoStr = "Open file("+filename+")failed"; 
						break;	 
					case  Errorno.FFMPEG_PARSE_FAILED: 
						InfoStr = "Parser file("+filename+")failed"; 
						break; 
					case  Errorno.DECODER_INIT_FAILED: 
						InfoStr = "Decode Init failed"; 
						break; 
					case  Errorno.PLAYER_NO_VIDEO: 
						InfoStr = "file("+filename+")no video"; 
						break; 
					case  Errorno.PLAYER_NO_AUDIO: 
						InfoStr = "file("+filename+")no audio"; 
						break; 
					case  Errorno.PLAYER_SET_NOVIDEO: 
						InfoStr = "set playback without video"; 
						break; 
					case  Errorno.PLAYER_SET_NOAUDIO: 
						InfoStr = "set playback without audio"; 
						break;	 
					default: 
						InfoStr = "Unknow Error"; 
						break; 
        	  }			  
            AlertDialog.Builder alert = new AlertDialog.Builder(PlayVideo.this)	;         
            alert.setTitle("ERROR").setMessage(TAG+":"+InfoStr+ErrStr);		 
			if(status == PLAYER_ERROR) 
			{ 
            	alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {			 
	          		public void onClick(DialogInterface dialog, int whichButton) {					 
	        	    	dialog.dismiss();						 
							finish(); 
	          	} 
        		}); 
			} 
			else 
			{ 
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {			 
	          		public void onClick(DialogInterface dialog, int whichButton) {					 
	        	    	dialog.dismiss();	 
	          	} 
        		}); 
			} 
        	alert.show(); 
        } 
		else 
		{ 
			mHandler.postDelayed(mGetState, UPDATE_STATE_INTERVAL); 
		} 
    } 
 
    private String secToTime(int i) 
    { 
        String retStr = null; 
        int hour = 0; 
        int minute = 0; 
        int second = 0; 
        if (i <= 0) 
            return "00:00"; 
        else 
        { 
            minute = i/60; 
            if (minute < 60) 
            { 
                second = i%60; 
                retStr = unitFormat(minute) + ":" + unitFormat(second); 
            } 
            else 
            { 
                hour = minute/60; 
                if (hour > 99) 
                    return "99:59:59"; 
                minute = minute%60; 
                second = i - hour * 3600 - minute * 60; 
                retStr = unitFormat(hour) + ":" + unitFormat(minute) + ":" + unitFormat(second); 
            } 
        } 
        return retStr; 
    } 
 
    private String unitFormat(int i) 
    { 
        String retStr = null; 
        if (i >= 0 && i < 10) 
            retStr = "0" + Integer.toString(i); 
        else 
            retStr = Integer.toString(i); 
        return retStr; 
    } 
 
	//@Override 
	public void onProgressChanged(SeekBar seekBar, int progress, 
			boolean fromUser) {		 
		int current_time = mLastTotalTime * progress /100; 
		mCurrTime.setText(secToTime(current_time)); 
		subTitle.tick(current_time*1000); 
		 
	} 
 
	//@Override 
	public void onStartTrackingTouch(SeekBar seekBar) { 
		// TODO Auto-generated method stub 
		 
	} 
 
	//@Override 
	public void onStopTrackingTouch(SeekBar seekBar) { 
		// TODO Auto-generated method stub 
		int current_time = mLastTotalTime * mSeekBar.getProgress() /100; 
		Amplayer.native_sendcmd("t:" + String.valueOf(current_time)); 
    mCurrTime.setText(secToTime(current_time)); 
	} 
	AdapterView.OnItemClickListener selItem = new OnItemClickListener() { 
		public void onItemClick(AdapterView<?> a, View v, int i, long k) { 
			Log.d(TAG, "onItemClicks"); 
			String name = dir_ent.get(i); 
			if (name.equals("..")) { // ".." 
				Log.d(TAG, "parent:" + cur_dir.getParent()); 
				if (cur_dir.getParent() != null 
						&& cur_dir != new File(ROOT_PATH)) { 
					browse(cur_dir.getParentFile()); 
				} 
			} else { 
				File clickedFile = null; 
				clickedFile = new File(cur_dir.getAbsolutePath(), name); 
				if (clickedFile != null) 
				{ 
					browse(clickedFile); 
				} 
			} 
		} 
	}; 
	private void browse(final File path) { 
		listlayout.setVisibility(View.VISIBLE); 
		if (path.isDirectory()) { 
			this.cur_dir = path; 
			addFilesToList(path.listFiles()); 
		} else { 
			try { 
				openFile(path); 
			} catch (MalformedSubException e) { 
				//TODO Auto-generated catch block 
				e.printStackTrace(); 
			} 
			listlayout.setVisibility(View.INVISIBLE); 
		} 
	} 
	 
	private void addFilesToList(File[] files) { 
		if (files != null) { 
			this.dir_ent.clear(); 
			if (this.cur_dir.getParent() != null) { 
				this.dir_ent.add(".."); 
			} 
			for (File file : files) { 
				String name = file.getName(); 
//				if (Subtitle.fileType(name) != Subtitle.FileType.TYPE_UNKNOWN) 
					this.dir_ent.add(name); 
					Log.d(TAG, "add" + name); 
			} 
			fileList.setAdapter(new ArrayAdapter<String>(this, 
					R.layout.filelistitem, this.dir_ent)); 
		} 
	} 
	 
	private void openFile(File f) throws MalformedSubException  { 
		Log.d(TAG, "open:" + f.getAbsolutePath()); 
//		stop(); 
		// load Input File 
 
		try { 
			if(subTitle.setFile(new SubID(f.getAbsolutePath(),0), "GBK")==Subtitle.SUBTYPE.SUB_INVALID) 
			{ 
				return; 
			} 
		} catch (Exception e) { 
			Log.d(TAG, "open:errrrrrrrrrrrrrrr"); 
 
			e.printStackTrace(); 
			throw new MalformedSubException("text sub parser return NULL!"); 
		} 
		Log.d(TAG, "---------"); 
 
//		if(Subtitle.fileType(f.getAbsolutePath()) == Subtitle.FileType.TYPE_SUB ) 
//		{ 
//			(subTitle.getSubtitleFile()).setFramerate(7); 
//		} 
		Log.d(TAG, "---------"); 
 
		 
//		SubtitleLine last = (SubtitleLine) subTitle.getSubtitleFile().getLast(); 
// 
//		int allSecond = 0; 
//		try { 
//			allSecond = last.getEnd().getMilValue() / 1000 + 1; 
//		} catch (Exception e1) { 
//			// TODO Auto-generated catch block 
//			e1.printStackTrace(); 
//		} 
//		Log.d(TAG, "---------"); 
// 
//		String sTime = String.format("%02d:%02d:%02d", allSecond / 3600, 
//				(allSecond % 3600) / 60, allSecond % 60); 
	} 
} 
 
class PlayerCallbackInfo{ 
	public int last_sta;  
	public int status; 
	public int current; 
	public int duration; 
	public int last_time; 
	public int errcode;    	 
}