`
wuzijingaip
  • 浏览: 334236 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论
阅读更多
package jmfsample;


import java.io.*;
import javax.media.*;
import javax.media.util.*;
import javax.media.format.*;
import javax.media.control.*;
import javax.media.control.TrackControl;
import javax.media.protocol.DataSource;
import javax.media.protocol.ContentDescriptor;
import javax.media.protocol.PushBufferDataSource;
import javax.media.protocol.PushBufferStream;
import javax.media.control.QualityControl;
import javax.media.rtp.*;
import javax.media.rtp.rtcp.*;
import com.sun.media.rtp.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.net.*;

public class JmfV extends JFrame
{
    public static Player player=null;
    private CaptureDeviceInfo di=null;
    private MediaLocator locator=null;
    String str1="vfw:Logitech USB Video Camera:0";
    String str2="vfw:Microsoft WDM Image Capture (Win32):0";
    private Processor processor = null;
    private RTPManager rtpMgrs[];
    private DataSource dataOutput = null,ds=null,ds_1=null;
    private String ipAddress;
    private int portBase;
    public JmfV( String ipAddress,
    String pb,
    Format format )
    {
     this.ipAddress = ipAddress;
     Integer integer = Integer.valueOf(pb);
     if (integer != null)
         this.portBase = integer.intValue();
        di=CaptureDeviceManager.getDevice(str2);
        locator=di.getLocator();
        try
        {
            dataOutput=Manager.createDataSource(locator);   
            player=Manager.createRealizedPlayer(ds);
            player.start();
            Component comp=null,comp_v=null;
            if((comp=player.getControlPanelComponent())!=null)
            {
                this.getContentPane().add(comp,"North");
                if((comp_v=player.getVisualComponent())!=null)
                    this.getContentPane().add(comp_v,"Center");
            }  
            ds=Manager.createCloneableDataSource(dataOutput);
            this.setSize(320,320);
            this.setVisible(true);
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }catch(Exception e )
        {
            e.printStackTrace();
        }
    }
    public synchronized String start() {
     String result;

     // Create a processor for the specified media locator
     // and program it to output JPEG/RTP
     result = createProcessor();
     if (result != null)
         return result;

     // Create an RTP session to transmit the output of the
     // processor to the specified IP address and port no.
     result = createTransmitter();
     if (result != null) {
         processor.close();
         processor = null;
         return result;
     }

     // Start the transmission
     processor.start();
     
     return null;
        }

     
        public void stop() {
     synchronized (this) {
         if (processor != null) {
      processor.stop();
      processor.close();
      processor = null;
      for (int i = 0; i < rtpMgrs.length; i++) {
          rtpMgrs[i].removeTargets( "Session ended.");
          rtpMgrs[i].dispose();
      }
         }
     }
        }

        private String createProcessor() {
     if (locator == null)
         return "Locator is null";
     // Try to create a processor to handle the input media locator
     try {
         processor = javax.media.Manager.createProcessor(ds);
     } catch (NoProcessorException npe) {
         return "Couldn't create processor";
     } catch (IOException ioe) {
         return "IOException creating processor";
     } 

     // Wait for it to configure
     boolean result = waitForState(processor, Processor.Configured);
     if (result == false)
         return "Couldn't configure processor";

     // Get the tracks from the processor
     TrackControl [] tracks = processor.getTrackControls();

     // Do we have atleast one track?
     if (tracks == null || tracks.length < 1)
         return "Couldn't find tracks in processor";

     // Set the output content descriptor to RAW_RTP
     // This will limit the supported formats reported from
     // Track.getSupportedFormats to only valid RTP formats.
     ContentDescriptor cd = new ContentDescriptor(ContentDescriptor.RAW_RTP);
     processor.setContentDescriptor(cd);

     Format supported[];
     Format chosen;
     boolean atLeastOneTrack = false;

     // Program the tracks.
     for (int i = 0; i < tracks.length; i++) {
         Format format = tracks[i].getFormat();
         if (tracks[i].isEnabled()) {

      supported = tracks[i].getSupportedFormats();

      // We've set the output content to the RAW_RTP.
      // So all the supported formats should work with RTP.
      // We'll just pick the first one.

      if (supported.length > 0) {
          if (supported[0] instanceof VideoFormat) {
       // For video formats, we should double check the
       // sizes since not all formats work in all sizes.
       chosen = checkForVideoSizes(tracks[i].getFormat(), 
           supported[0]);
          } else
       chosen = supported[0];
          tracks[i].setFormat(chosen);
          System.err.println("Track " + i + " is set to transmit as:");
          System.err.println("  " + chosen);
          atLeastOneTrack = true;
      } else
          tracks[i].setEnabled(false);
         } else
      tracks[i].setEnabled(false);
     }

     if (!atLeastOneTrack)
         return "Couldn't set any of the tracks to a valid RTP format";

     // Realize the processor. This will internally create a flow
     // graph and attempt to create an output datasource for JPEG/RTP
     // audio frames.
     result = waitForState(processor, Controller.Realized);
     if (result == false)
         return "Couldn't realize processor";

     // Set the JPEG quality to .5.
     setJPEGQuality(processor, 0.5f);

     // Get the output data source of the processor
     dataOutput = processor.getDataOutput();

     return null;
        }


     
        private String createTransmitter() {

     // Cheated.  Should have checked the type.
     PushBufferDataSource pbds = (PushBufferDataSource)dataOutput;
     PushBufferStream pbss[] = pbds.getStreams();

     rtpMgrs = new RTPManager[pbss.length];
     SessionAddress localAddr, destAddr;
     InetAddress ipAddr;
     SendStream sendStream;
     int port;
     SourceDescription srcDesList[];

     for (int i = 0; i < pbss.length; i++) {
         try {
      rtpMgrs[i] = RTPManager.newInstance();     

      // The local session address will be created on the
      // same port as the the target port. This is necessary
      // if you use AVTransmit2 in conjunction with JMStudio.
      // JMStudio assumes -  in a unicast session - that the
      // transmitter transmits from the same port it is receiving
      // on and sends RTCP Receiver Reports back to this port of
      // the transmitting host.
      
      port = portBase + 2*i;
      ipAddr = InetAddress.getByName(ipAddress);

      localAddr = new SessionAddress( InetAddress.getLocalHost(),
          port);
      
      destAddr = new SessionAddress( ipAddr, port);

      rtpMgrs[i].initialize( localAddr);
      
      rtpMgrs[i].addTarget( destAddr);
      
      System.err.println( "Created RTP session: " + ipAddress + " " + port);
      
      sendStream = rtpMgrs[i].createSendStream(dataOutput, i);  
      sendStream.start();
         } catch (Exception  e) {
      return e.getMessage();
         }
     }

     return null;
        }


     
        Format checkForVideoSizes(Format original, Format supported) {

     int width, height;
     Dimension size = ((VideoFormat)original).getSize();
     Format jpegFmt = new Format(VideoFormat.JPEG_RTP);
     Format h263Fmt = new Format(VideoFormat.H263_RTP);

     if (supported.matches(jpegFmt)) {
         // For JPEG, make sure width and height are divisible by 8.
         width = (size.width % 8 == 0 ? size.width :
        (int)(size.width / 8) * 8);
         height = (size.height % 8 == 0 ? size.height :
        (int)(size.height / 8) * 8);
     } else if (supported.matches(h263Fmt)) {
         // For H.263, we only support some specific sizes.
         if (size.width < 128) {
      width = 128;
      height = 96;
         } else if (size.width < 176) {
      width = 176;
      height = 144;
         } else {
      width = 352;
      height = 288;
         }
     } else {
         // We don't know this particular format.  We'll just
         // leave it alone then.
         return supported;
     }

     return (new VideoFormat(null, 
        new Dimension(width, height), 
        Format.NOT_SPECIFIED,
        null,
        Format.NOT_SPECIFIED)).intersects(supported);
        }


     
        void setJPEGQuality(Player p, float val) {

     Control cs[] = p.getControls();
     QualityControl qc = null;
     VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG);

     // Loop through the controls to find the Quality control for
      // the JPEG encoder.
     for (int i = 0; i < cs.length; i++) {

         if (cs[i] instanceof QualityControl &&
      cs[i] instanceof Owned) {
      Object owner = ((Owned)cs[i]).getOwner();

      // Check to see if the owner is a Codec.
      // Then check for the output format.
      if (owner instanceof Codec) {
          Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null);
          for (int j = 0; j < fmts.length; j++) {
       if (fmts[j].matches(jpegFmt)) {
           qc = (QualityControl)cs[i];
               qc.setQuality(val);
           System.err.println("- Setting quality to " + 
         val + " on " + qc);
           break;
       }
          }
      }
      if (qc != null)
          break;
         }
     }
        }


        private Integer stateLock = new Integer(0);
        private boolean failed = false;
        
        Integer getStateLock() {
     return stateLock;
        }

        void setFailed() {
     failed = true;
        }
        
        private synchronized boolean waitForState(Processor p, int state) {
     p.addControllerListener(new StateListener());
     failed = false;

     // Call the required method on the processor
     if (state == Processor.Configured) {
         p.configure();
     } else if (state == Processor.Realized) {
         p.realize();
     }
     
     // Wait until we get an event that confirms the
     // success of the method, or a failure event.
     // See StateListener inner class
     while (p.getState() < state && !failed) {
         synchronized (getStateLock()) {
      try {
          getStateLock().wait();
      } catch (InterruptedException ie) {
          return false;
      }
         }
     }

     if (failed)
         return false;
     else
         return true;
        }


        class StateListener implements ControllerListener {

     public void controllerUpdate(ControllerEvent ce) {

         // If there was an error during configure or
         // realize, the processor will be closed
         if (ce instanceof ControllerClosedEvent)
      setFailed();

         // All controller events, send a notification
         // to the waiting thread in waitForState method.
         if (ce instanceof ControllerEvent) {
      synchronized (getStateLock()) {
          getStateLock().notifyAll();
      }
         }
     }
        }


  
        public static void main(String [] args) {
     // We need three parameters to do the transmission
     // For example,
     //   java AVTransmit2 file:/C:/media/test.mov  129.130.131.132 42050
     
     Format fmt = null;
     int i = 0;

     // Create a audio transmit object with the specified params.
     JmfV at = new JmfV("169.254.252.50", "42050", fmt);
     System.out.println("Test");
     // Start the transmission
     String result = at.start();

     // result will be non-null if there was an error. The return
     // value is a String describing the possible error. Print it.
     if (result != null) {
         System.err.println("Error : " + result);
         System.exit(0);
     }
     
     System.err.println("Start transmission for 60 seconds...");

     // Transmit for 60 seconds and then close the processor
     // This is a safeguard when using a capture data source
     // so that the capture device will be properly released
     // before quitting.
     // The right thing to do would be to have a GUI with a
     // "Stop" button that would call stop on AVTransmit2
     try {
         Thread.currentThread().sleep(60000);
     } catch (InterruptedException ie) {
     }

     // Stop the transmission
     at.stop();
     
     System.err.println("...transmission ended.");

     System.exit(0);
}
}


分享到:
评论

相关推荐

    JMF下载和安装教程

    Java Media Framework (JMF) 是一个用于开发多媒体应用程序的Java平台框架。它是Java开发者用来处理音频、视频和其他基于时间的媒体内容的工具。JMF允许在Java Applet和应用程序中集成多媒体功能,使得开发者能够...

    JMF667主控SSD开卡工具

    《JMF667主控SSD开卡工具详解》 在存储技术领域,固态硬盘(Solid State Drive,简称SSD)凭借其高速度、低延迟的优势,逐渐成为主流的存储设备。其中,主控芯片是SSD的核心组件,它负责管理数据的读写、错误校验...

    JMF 安装文件 jmf-2_1_1e-windows-i586.exe

    Java Media Framework(JMF)是Java平台上用于处理多媒体数据的一个开放源代码框架。这个"jmf-2_1_1e-windows-i586.exe"是JMF的特定版本,适用于Windows操作系统,尤其是32位(i586)系统。它的主要功能包括播放、...

    JMF608MP_2.03.059.rar

    标题中的“JMF608MP_2.03.059.rar”指的是一个名为“JMF608MP”的设备或软件的版本号为2.03.059的更新压缩包,文件格式为RAR,通常用于存储多个相关文件。RAR是一种流行的压缩格式,它能更有效地压缩数据,比ZIP等...

    JMF605电路图

    ### JMF605 固态硬盘 DIY 方案解析 #### 一、JMF605 芯片概述 JMF605 是一款专为固态硬盘(SSD)设计的主控芯片,适用于半瘦型 SSD 模块。该芯片支持多种 NAND Flash 存储类型,并具备强大的数据管理功能,如磨损...

    JMF(Java媒体框架)

    Java媒体框架(JMF,Java Media Framework)是Sun Microsystems公司开发的一个开源框架,主要用于处理音频、视频和流媒体内容。这个框架为Java开发者提供了一种在应用程序中集成多媒体功能的方法,使得开发者能够...

    JMF608&JMF609;_NAND Flash support list_ver 0.6_REV091(1).pdf

    智微科技发布了JMF608和JMF609固态硬盘主控制器的NAND Flash颗粒支持列表。这一列表详细列出了这两个控制器所支持的NAND Flash芯片型号,并且提供了一个文档编号608-00002以及修订版本0.6,发布日期为2014年5月9日。...

    JMF 安装包及JMF API

    Java Media Framework (JMF) 是一个开源的Java平台,它为开发人员提供了处理音频、视频和多媒体应用的能力。JMF 提供了丰富的接口和类,使得开发者可以方便地集成和播放各种多媒体内容。在本资源中,我们有两个关键...

    JMF605_xiufu.zip

    标题 "JMF605_xiufu.zip" 所涉及的是一个专为基于JMF605芯片的固态硬盘(SSD)设计的修复工具包。这个压缩包包含了多份文件,用于帮助用户在没有专用修复接口卡的情况下,通过USB转SSD转换线自行对SSD进行故障排查和...

    JMF下载包,java.media

    Java Media Framework(JMF)是Java平台上用于处理多媒体数据的一个框架。这个下载包包含了与`java.media`相关的组件,主要用于开发能够播放、捕获、处理和流化音频、视频的应用程序。下面将详细介绍JMF的核心功能、...

    JMF.zip_JMF W_Java 播放器_hookqq_jmf_jmf-2_0-spec

    "JMF.zip_JMF W_Java 播放器_hookqq_jmf_jmf-2_0-spec"这个压缩包包含了一个基于Java开发的媒体播放器示例,适用于初学者学习和理解JMF的用法。 JMF的核心是其组件模型,它支持多种媒体格式,包括音频、视频和流...

    基于JMF的MP3播放器

    【基于JMF的MP3播放器】是一款利用Java Media Framework(JMF)技术开发的音频播放软件,专注于播放MP3格式的音乐文件。这个播放器不仅具备基础的播放功能,如播放、暂停、停止和音量控制,还支持列表播放,用户可以...

    JMF605开卡教程

    ### JMF605开卡教程详解 #### 一、前言 在现代电子设备制造过程中,存储卡的初始化设置,即所谓的“开卡”,是一项非常重要的步骤。它确保了存储卡能够正常工作并达到最佳性能。本文档将详细介绍如何使用...

    jmf605量产工具

    【标题】"jmf605量产工具"指的是专门针对JMF605主控芯片进行批量生产的软件工具。在闪存存储设备如USB闪存盘、SD卡等的制造过程中,量产工具起到了至关重要的作用,它能进行格式化、分区、写入固件、性能测试等一...

    jmf中文开发指导,jmf中文开发指导

    Java Media Framework (JMF) 是一个开源的Java平台,用于处理多媒体数据,如音频、视频和流媒体。它为开发者提供了在Java应用程序中集成多媒体功能的能力。本开发指导将深入探讨JMF的各个方面,帮助你理解和掌握其...

    jmf-2_1_1e

    **Java Media Framework (JMF)** 是Oracle公司提供的一款开源多媒体框架,主要应用于开发音视频处理和播放的应用程序。标题中的"jmf-2_1_1e"指的是JMF的一个特定版本,即2.1.1e。这个版本是专为Windows操作系统设计...

    jmf 视屏录制 JMF 影像录制

    程序描述:用JMF2.0做的调用摄像头 进行视屏录制,是 医学上“内镜”影像学录像和截图的简单DEMO。 完整的MyEclipse项目,含有源码和所需的JAR包,编译完成有直接运行com.jake.camera.LocalVideoTest就可出现录制...

    JMF2.1 下载 最新版本*(只有安装包)

    JMF2.1 Java媒体框架(JMF)使你能够编写出功能强大的多媒体程序,却不用关心底层复杂的实现细节。JMF API的使用相对比较简单,但是能够满足几乎所有多媒体编程的需求。在这篇文章中,我将向你介绍如何用很少的代码...

    JMF 介绍及API

    Java媒体框架(JMF,Java Media Framework)是一个用于开发多媒体应用程序的开源框架,它允许开发者在Java环境中处理音频、视频等各种多媒体数据,而无需深入理解底层的复杂技术细节。JMF提供了一组丰富的API,使得...

Global site tag (gtag.js) - Google Analytics