SWTMoviePlayer.java
Go to the documentation of this file.
00001 package com.generalrobotix.ui.view.tdview;
00002 
00003 import java.io.*;
00004 import java.lang.reflect.InvocationTargetException;
00005 
00006 import java.awt.BorderLayout;
00007 import java.awt.Color;
00008 import java.awt.Component;
00009 import java.awt.Dimension;
00010 import java.awt.Frame;
00011 import java.awt.Graphics2D;
00012 import java.awt.Image;
00013 import java.awt.event.ActionEvent;
00014 import java.awt.event.ActionListener;
00015 import java.awt.image.BufferedImage;
00016 
00017 import javax.media.Buffer;
00018 import javax.media.ConfigureCompleteEvent;
00019 import javax.media.Controller;
00020 import javax.media.ControllerEvent;
00021 import javax.media.ControllerListener;
00022 import javax.media.Manager;
00023 import javax.media.MediaLocator;
00024 import javax.media.PrefetchCompleteEvent;
00025 import javax.media.Processor;
00026 import javax.media.RealizeCompleteEvent;
00027 import javax.media.ResourceUnavailableEvent;
00028 import javax.media.control.FrameGrabbingControl;
00029 import javax.media.control.FramePositioningControl;
00030 import javax.media.control.TrackControl;
00031 import javax.media.format.VideoFormat;
00032 import javax.swing.JButton;
00033 import javax.swing.JLabel;
00034 import javax.swing.JPanel;
00035 import javax.swing.SwingUtilities;
00036 
00037 import com.generalrobotix.ui.util.MessageBundle;
00038 import com.sun.image.codec.jpeg.*; 
00039 
00040 import org.eclipse.jface.dialogs.MessageDialog;
00041 import org.eclipse.swt.SWT;
00042 import org.eclipse.swt.awt.SWT_AWT;
00043 import org.eclipse.swt.events.ControlEvent;
00044 import org.eclipse.swt.events.ControlListener;
00045 import org.eclipse.swt.events.SelectionAdapter;
00046 import org.eclipse.swt.events.SelectionEvent;
00047 import org.eclipse.swt.events.ShellEvent;
00048 import org.eclipse.swt.events.ShellListener;
00049 import org.eclipse.swt.layout.FillLayout;
00050 import org.eclipse.swt.widgets.Composite;
00051 import org.eclipse.swt.widgets.Display;
00052 import org.eclipse.swt.widgets.FileDialog;
00053 import org.eclipse.swt.widgets.Menu;
00054 import org.eclipse.swt.widgets.MenuItem;
00055 import org.eclipse.swt.widgets.Shell;
00056 
00057 public class SWTMoviePlayer implements ControllerListener{
00058     private Component cmpVisual_=null;// 画面
00059     private Component cmpOpe_=null;// 操作板
00060     
00061     private Processor p_=null;// プロセッサ
00062     private FramePositioningControl frameCtrl_=null;// 位置コントロール
00063     private FrameGrabbingControl frameGrabCtrl_=null;// 画面いただきコントロール
00064     // 待ち用
00065     private Object waitSync = new Object();
00066     private  boolean stateTransitionOK = true;
00067     //表示用
00068     private final String STR_TITLE_="SMPlayer"; //ウィンドウタイトル文字列 //$NON-NLS-1$
00069     private final String STR_RIGHT_="(C) 2000 Kernel Inc"; //版権文字列(おまけ) //$NON-NLS-1$
00070 
00071     Shell window_ = null;
00072     Frame frame_;
00073     Composite comp_;
00074     JPanel contentPane_;
00075     int frameX,frameY;
00076     
00082     public SWTMoviePlayer( Shell shell, String fileName ){
00083         
00084         window_ = new Shell( shell, SWT.SHELL_TRIM );
00085                 window_.setSize(200, 200);
00086                 window_.setText(MessageBundle.get("SWTMoviePlayer.window.title")); //$NON-NLS-1$
00087 
00088                 createMenu();
00089                 
00090                 FillLayout layout = new FillLayout();
00091                 window_.setLayout(layout);
00092 
00093                 //----
00094         // Linuxでリサイズイベントが発行されない問題対策
00095         // https://bugs.eclipse.org/bugs/show_bug.cgi?id=168330
00096                 comp_ = new Composite( window_, SWT.EMBEDDED );
00097                 frame_ = SWT_AWT.new_Frame( comp_ );
00098 
00099                 comp_.addControlListener( new ControlListener() {
00100                         public void controlMoved(ControlEvent e) {}
00101                         public void controlResized(ControlEvent e) {
00102                 frame_.setBounds(0, 0, comp_.getSize().x, comp_.getSize().y );
00103                         }
00104         });
00105         //----
00106         
00107         window_.addShellListener(new ShellListener(){
00108             public void shellActivated(ShellEvent e) {
00109                 // TODO 自動生成されたメソッド・スタブ
00110             }
00111             public void shellClosed(ShellEvent e) {
00112                 // TODO 自動生成されたメソッド・スタブ
00113                 _remove();
00114             }
00115             public void shellDeactivated(ShellEvent e) {
00116                 // TODO 自動生成されたメソッド・スタブ
00117                 
00118             }
00119             public void shellDeiconified(ShellEvent e) {
00120                 // TODO 自動生成されたメソッド・スタブ
00121                 
00122             }
00123             public void shellIconified(ShellEvent e) {
00124                 // TODO 自動生成されたメソッド・スタブ
00125                 
00126             }
00127         });
00128         
00129         contentPane_ = new JPanel();
00130         frame_.add(contentPane_);
00131                 
00132         window_.open();
00133         window_.setSize(contentPane_.getPreferredSize().width, contentPane_.getPreferredSize().height);
00134 
00135         //枠線サイズを取得する
00136         frameX = window_.getSize().x - comp_.getSize().x;
00137                 frameY = window_.getSize().y - comp_.getSize().y;
00138                 System.out.println("frame size="+frameX+"-"+frameY); //$NON-NLS-1$ //$NON-NLS-2$
00139 
00140         //指定ファイルオープン
00141         if(_load(fileName)==false)_load(null);
00142     }
00143 
00144     private void resizeWindow(){
00145                 Display display = Display.getDefault();
00146                 
00147                 if ( display!=null && !display.isDisposed())
00148                         // TODO: syncExecではこけるのだがなぜ?
00149                         display.asyncExec(
00150                                 new Runnable(){
00151                                         public void run() {
00152                                                 window_.setSize(contentPane_.getPreferredSize().width+frameX, contentPane_.getPreferredSize().height+frameY);
00153                                         }
00154                                 }
00155                         );
00156 
00157     }
00158     
00159     private void createMenu() {
00160                 Menu menubar = new Menu(window_,SWT.BAR);
00161                 window_.setMenuBar(menubar);
00162             
00163             MenuItem item1 = new MenuItem(menubar,SWT.CASCADE);
00164             item1.setText(MessageBundle.get("SWTMoviePlayer.menu.file")); //$NON-NLS-1$
00165             
00166             Menu menu1 = new Menu(item1);
00167             item1.setMenu(menu1);
00168             
00169             MenuItem item1_1 = new MenuItem(menu1,SWT.PUSH);
00170             item1_1.setText(MessageBundle.get("SWTMoviePlayer.menu.open")); //$NON-NLS-1$
00171             item1_1.addSelectionListener(new SelectionAdapter(){
00172                         public void widgetSelected(SelectionEvent e) {
00173                                 _open();
00174                         }
00175             });
00176 
00177             MenuItem item1_3 = new MenuItem(menu1,SWT.PUSH);
00178             item1_3.setText(MessageBundle.get("SWTMoviePlayer.menu.saveAs")); //$NON-NLS-1$
00179             item1_3.addSelectionListener(new SelectionAdapter(){
00180                         public void widgetSelected(SelectionEvent e) {
00181                                 _saveImageAs();
00182                         }
00183             });
00184             
00185             MenuItem item1_4 = new MenuItem(menu1,SWT.PUSH);
00186             item1_4.setText(MessageBundle.get("SWTMoviePlayer.menu.quit")); //$NON-NLS-1$
00187             item1_4.addSelectionListener(new SelectionAdapter(){
00188                         public void widgetSelected(SelectionEvent e) {
00189                                 window_.close();
00190                         }
00191             });
00192             
00193     }
00194 
00195 
00200     File currentFile;
00201     private void _open() {
00202         FileDialog fDialog = new FileDialog(window_,SWT.OPEN);
00203 
00204         String [] exts = {"*.mpg;*.avi;*.mov"}; //$NON-NLS-1$
00205                 String [] filterNames = {MessageBundle.get("SWTMoviePlayer.dialog.filter")}; //$NON-NLS-1$
00206                 fDialog.setFilterExtensions(exts);
00207                 fDialog.setFilterNames(filterNames);
00208                 
00209                 String openPath = fDialog.open();
00210                 if( openPath != null ) {
00211                         currentFile = new File( openPath );
00212                         /*
00213             if(!_load("file:" + f.getAbsolutePath())){
00214                 MessageDialog.openError(window_, "Error", "Can't Open Movie." );
00215                 _load(null);
00216             }
00217             */
00218                         try {
00219                                 SwingUtilities.invokeAndWait(new Runnable(){
00220                                         public void run(){
00221                                     if(!_load("file:" + currentFile.getAbsolutePath())){ //$NON-NLS-1$
00222                                         _load(null);
00223                                     }
00224                                         }
00225                                 });
00226                         } catch (InterruptedException e1) {
00227                                 // TODO Auto-generated catch block
00228                                 e1.printStackTrace();
00229                         } catch (InvocationTargetException e1) {
00230                                 // TODO Auto-generated catch block
00231                                 e1.printStackTrace();
00232                         }
00233 
00234                 }
00235         
00236         /*
00237         JFileChooser chooser = new JFileChooser(System.getProperty("user.dir"));
00238         // Note: source for ExampleFileFilter can be found in FileChooserDemo,
00239         // under the demo/jfc directory in the Java 2 SDK, Standard Edition.
00240         ExampleFileFilter filter = new ExampleFileFilter();
00241         filter.addExtension("mpg");
00242         filter.addExtension("avi");
00243         filter.addExtension("mov");
00244         filter.setDescription("Movie Files");
00245         chooser.setFileFilter(filter);
00246         int returnVal = chooser.showOpenDialog(frame_);
00247         if(returnVal == JFileChooser.APPROVE_OPTION) {
00248             if(!_load("file:" + chooser.getSelectedFile().getAbsolutePath())){
00249                 //JOptionPane.showMessageDialog(frame_,  "Can't Open Movie.", "Error", JOptionPane.ERROR_MESSAGE);
00250                 new ErrorDialog(
00251                     this,
00252                     "Error",
00253                     "Can't Open Movie."
00254                 );
00255                 _load(null);
00256             }
00257         }
00258         */
00259     }
00260     
00265     private void _remove(){
00266         //remove
00267         if (cmpVisual_!=null){
00268                 contentPane_.remove(cmpVisual_);
00269             cmpVisual_=null;
00270         }
00271         if (cmpOpe_!=null){
00272                 contentPane_.remove(cmpOpe_);
00273             cmpOpe_=null;
00274         }
00275         
00276         if (p_!=null){
00277             p_.removeControllerListener(this);
00278             p_.stop();
00279             p_.close();
00280             p_=null;
00281         }
00282     }
00283 
00291     private MediaLocator _createMediaLocator(String url) {
00292 
00293         MediaLocator ml;
00294         if(url==null)return null;
00295 
00296         if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null) //$NON-NLS-1$
00297             return ml;
00298 
00299         if (url.startsWith(File.separator)) {
00300             if ((ml = new MediaLocator("file:" + url)) != null) //$NON-NLS-1$
00301             return ml;
00302         } else {
00303             String file = "file:" + System.getProperty("user.dir") + File.separator + url; //$NON-NLS-1$ //$NON-NLS-2$
00304             if ((ml = new MediaLocator(file)) != null)
00305             return ml;
00306         }
00307 
00308         return null;
00309     }
00310     
00311 
00312 
00322     private boolean _load(String fileName) {
00323         Component newVisual=null;
00324         Component newOpe=null;
00325         
00326         _remove();
00327         
00328         System.out.println("filename is "+fileName); //$NON-NLS-1$
00329         
00330         //fileName==nullならml=nullとなる
00331         MediaLocator ml=_createMediaLocator(fileName);
00332 
00333         System.out.println("ML="+ml); //$NON-NLS-1$
00334 
00335 
00336         if(ml==null){
00337             newVisual =new JPanel();//ダミー
00338             ((JPanel)newVisual).setPreferredSize(new Dimension(160,120));
00339             newVisual.setBackground(Color.black);
00340             newOpe=new JLabel(STR_RIGHT_);
00341             //window_.setText(STR_TITLE_);
00342         }else{
00343             //window_.setText("Openning " + ml +"...");
00344             try {
00345                 p_ = Manager.createProcessor(ml);
00346             } catch (Exception e) {
00347                 System.err.println("Failed to create a processor from the given url: " + e); //$NON-NLS-1$
00348                 return false;
00349             }
00350 
00351             p_.addControllerListener(this);
00352 
00353             // Put the Processor into configured state.
00354             p_.configure();
00355             if (!_waitForState(Processor.Configured)) {
00356                 System.err.println("Failed to configure the processor."); //$NON-NLS-1$
00357                 return false;
00358             }
00359 
00360             // So I can use it as a player.
00361             p_.setContentDescriptor(null);
00362 
00363             // Obtain the track controls.
00364             TrackControl tc[] = p_.getTrackControls();
00365 
00366             if (tc == null) {
00367                 System.err.println("Failed to obtain track controls from the processor."); //$NON-NLS-1$
00368                 return false;
00369             }
00370 
00371             // Search for the track control for the video track.
00372             TrackControl videoTrack = null;
00373 
00374             for (int i = 0; i < tc.length; i++) {
00375                 if (tc[i].getFormat() instanceof VideoFormat) {
00376                     videoTrack = tc[i];
00377                     break;
00378                 }
00379             }
00380 
00381             if (videoTrack == null) {
00382                 System.err.println("The input media does not contain a video track."); //$NON-NLS-1$
00383                 return false;
00384             }
00385 
00386             
00387             //FramePositioningControlを得る
00388             Object[] cnts;
00389             frameCtrl_=null;
00390             cnts=p_.getControls();
00391             for(int i=0;i<cnts.length;i++){
00392                 if(cnts[i] instanceof FramePositioningControl){
00393                     frameCtrl_=(FramePositioningControl)cnts[i];
00394                     //System.out.println(cnts[i]);
00395                 }
00396             }
00397 
00398             
00399 
00400             // Realize the processor.
00401             p_.prefetch();
00402             if (!_waitForState(Controller.Prefetched)) {
00403                 System.err.println("Failed to realize the processor."); //$NON-NLS-1$
00404                 return false;
00405             }
00406 
00407             //Rendererを得る
00408             javax.media.Renderer renderer=null;
00409             frameGrabCtrl_=null;
00410             cnts=videoTrack.getControls();
00411             for(int i=0;i<cnts.length;i++){
00412                 if(cnts[i] instanceof javax.media.Renderer){
00413                     renderer=(javax.media.Renderer)cnts[i];
00414                     //System.out.println(cnts[i]);
00415                 }
00416             }
00417             
00418             //FrameGrabbingControlを得る
00419             frameGrabCtrl_=null;
00420             cnts=renderer.getControls();
00421             for(int i=0;i<cnts.length;i++){
00422                 if(cnts[i] instanceof FrameGrabbingControl){
00423                     frameGrabCtrl_=(FrameGrabbingControl)cnts[i];
00424                     //System.out.println(cnts[i]);
00425                 }
00426             }
00427 
00428             // Display the visual & control component if there's one.
00429             newVisual = p_.getVisualComponent();
00430             
00431             JPanel panel=new JPanel();
00432             panel.setLayout(new BorderLayout());
00433             Component cc;
00434             if ((cc = p_.getControlPanelComponent()) != null) {
00435                 panel.add("Center", cc); //$NON-NLS-1$
00436             }
00437             JButton btn=new JButton(MessageBundle.get("SWTMoviePlayer.button.save"));  //$NON-NLS-1$
00438             btn.addActionListener(new  ActionListener(){
00439                     public void actionPerformed(ActionEvent e){
00440                         _saveImageAs();
00441                     }
00442                 }
00443             );
00444             panel.add("East", btn); //$NON-NLS-1$
00445             newOpe=panel;
00446             
00447             //window_.setText(STR_TITLE_ + " -" + ml);
00448         }
00449         
00450 
00451         //add
00452         contentPane_.setLayout(new BorderLayout());
00453         cmpVisual_=newVisual;
00454         if (cmpVisual_!= null) {
00455             contentPane_.add("Center", cmpVisual_); //$NON-NLS-1$
00456         }
00457         
00458         cmpOpe_=newOpe;
00459         if (cmpOpe_ != null) {
00460             contentPane_.add("South", cmpOpe_); //$NON-NLS-1$
00461         }
00462 
00463         //はじめの画面を表示
00464         if(frameCtrl_!=null){
00465             frameCtrl_.skip(1);
00466             frameCtrl_.skip(-1);
00467          }
00468 
00469         resizeWindow();
00470 
00471         return true;
00472     }
00473 
00481     private BufferedImage _convertBufferedImage(Buffer buf){
00482             MyBufferToImage bti =new MyBufferToImage((VideoFormat)buf.getFormat());
00483             Image img=bti.createImage(buf);
00484             if(img==null){
00485                 System.out.println("Can't create Image in this format!"); //$NON-NLS-1$
00486                 return null;
00487             }else{
00488                 BufferedImage bimg=new BufferedImage(img.getWidth(null),img.getHeight(null),BufferedImage.TYPE_INT_RGB);
00489                 Graphics2D g=bimg.createGraphics();
00490                 g.drawImage(img,0,0,null);
00491                 return bimg;
00492             }
00493     }
00494 
00499     JPEGImageEncoder enc;
00500     private void _saveImageAs(){
00501         if (p_ == null) {
00502                 System.out.println("not init."); //$NON-NLS-1$
00503                 return;
00504         }
00505                 try {
00506                         SwingUtilities.invokeAndWait(new Runnable(){
00507                                 public void run(){
00508                                 if (p_.getState()==Controller.Started)
00509                                     p_.stop();
00510                                 }
00511                         });
00512                 } catch (Exception e) {
00513                         e.printStackTrace();
00514                 }
00515         try{
00516             FileDialog fDialog = new FileDialog(window_,SWT.SAVE);
00517 
00518             String [] exts = {"*.jpg"}; //$NON-NLS-1$
00519                 String [] filterNames = {MessageBundle.get("SWTMoviePlayer.dialog.filter.jpeg")}; //$NON-NLS-1$
00520                 fDialog.setFilterExtensions(exts);
00521                 fDialog.setFilterNames(filterNames);
00522                 
00523                 String openPath = fDialog.open();
00524                 if( openPath != null ) {
00525                                 File f = new File( openPath );
00526 
00527                 FileOutputStream output =
00528                     new FileOutputStream(
00529                         f.getAbsolutePath()
00530                     );
00531                 enc=JPEGCodec.createJPEGEncoder(output);
00532 
00533                         try {
00534                                 SwingUtilities.invokeAndWait(new Runnable(){
00535                                         public void run(){
00536                                 try {
00537                                                                 enc.encode(_convertBufferedImage(frameGrabCtrl_.grabFrame() ));
00538                                                         } catch (Exception e) {
00539                                                                 // TODO Auto-generated catch block
00540                                                                 e.printStackTrace();
00541                                                         } 
00542                                         }
00543                                 });
00544                         } catch (Exception e) {
00545                                 e.printStackTrace();
00546                         }
00547 
00548                 //enc.encode(codec_.getLastBufferedImage()); 
00549                 output.close();
00550                 }
00551 
00552             /*          
00553                 JFileChooser chooser =
00554                 new JFileChooser(System.getProperty("user.dir"));
00555             ExampleFileFilter filter = new ExampleFileFilter();
00556             chooser.setDialogType(JFileChooser.SAVE_DIALOG);
00557             filter.addExtension("jpg");
00558             filter.setDescription("Jpeg Image");
00559             chooser.setFileFilter(filter);
00560 
00561             int returnVal = chooser.showSaveDialog(this);
00562             if(returnVal == JFileChooser.APPROVE_OPTION) {
00563                 FileOutputStream output =
00564                     new FileOutputStream(
00565                         chooser.getSelectedFile().getAbsolutePath()
00566                     );
00567                 JPEGImageEncoder enc=JPEGCodec.createJPEGEncoder(output);
00568                 enc.encode(_convertBufferedImage(frameGrabCtrl_.grabFrame() )); 
00569                 //enc.encode(codec_.getLastBufferedImage()); 
00570                 output.close();
00571             }
00572             */
00573 
00574         }catch(Exception exception){
00575                 /*
00576             JOptionPane.showMessageDialog(
00577                 this,
00578                 "Can't Save Image :" + exception.getMessage(),
00579                 "Error",
00580                 JOptionPane.ERROR_MESSAGE
00581             ); 
00582                  */
00583                 MessageDialog.openError(window_, MessageBundle.get("SWTMoviePlayer.dialog.title.error"), MessageBundle.get("SWTMoviePlayer.dialog.message.save") + exception.getMessage() ); //$NON-NLS-1$ //$NON-NLS-2$
00584         }
00585     }
00586 
00587     
00596     private boolean _waitForState(int state) {
00597         synchronized (waitSync) {
00598             try {
00599                 while (p_.getState() != state && stateTransitionOK)
00600                     waitSync.wait();
00601             } catch (Exception e) {}
00602         }
00603         return stateTransitionOK;
00604     }
00605 
00606     
00611      public void controllerUpdate(ControllerEvent evt) {
00612         if (evt instanceof ConfigureCompleteEvent ||
00613            evt instanceof RealizeCompleteEvent ||
00614            evt instanceof PrefetchCompleteEvent) {
00615                     synchronized (waitSync) {
00616                 stateTransitionOK = true;
00617                 waitSync.notifyAll();
00618             }
00619         } else if (evt instanceof ResourceUnavailableEvent) {
00620             synchronized (waitSync) {
00621                 stateTransitionOK = false;
00622                 waitSync.notifyAll();
00623             }
00624             
00625         }
00626     }
00627 
00628 }


openhrp3
Author(s): AIST, General Robotix Inc., Nakamura Lab of Dept. of Mechano Informatics at University of Tokyo
autogenerated on Thu Apr 11 2019 03:30:19