The simplest video website (javaee+ffmpeg)

Source: Internet
Author: User

This document records one of the simplest video site systems. Prior to doing some Java EE based on the SSH (Strut2 + Spring + Hibernate) site system, but has not done a video site system, so it is intended to do a "streamlined" video site system to facilitate future testing and learning to use. This video site supports live streaming (via rtmp) and on-demand (implemented via HTTP). In order to remain streamlined, this video site system only makes the management function of network video (increase and deletion), as well as the related parameter configuration function. Because of their own in the Java EE aspect has not studied thoroughly, therefore this system has some function not to finish, later has the time to improve gradually.

Introduction Schema

The system foreground display uses div + css+ JavaScript technology. Some JavaScript plugins are displayed in the foreground, such as the cloudcarousel that generates the rotating lantern effect, the ddsmoothmenu of the navigation menu, the jquery Validation engine for form validation, and so on. Video player with FlowPlayer (including rtmp plugin) to support HTTP on-demand and rtmp live. Supposedly, the video file upload can be implemented using AJAX, but consider the work is cumbersome, so the temporary use of direct file upload method.

The backend of the system uses the most traditional three-tier architecture of the Java EE System: The action layer, the service layer, and the DAO layer. Where the action layer uses the STRUTS2 framework to handle requests from the foreground page, and the DAO layer uses the Hibernate framework for interacting with the database. The spring framework is used to integrate the action layer, service layer, and DAO layer. The front and back interactions of the system mainly use JSTL tags and el expressions. In addition, taking into account the internationalization requirements, the use of the Struts2 i18n way, all the text on all pages are extracted to save to a separate file, so that the display can be implemented in multiple languages.

When the system starts running, two threads Videothumbnailthread and Videotranscoderthread are turned on. Videothumbnailthread is used to intercept video thumbnails, and Videotranscoderthread is used for transcoding uploaded videos. These two threads are all capable of completing the function by calling Ffmpeg.exe.

In addition, the system also includes the ability to view media information. This function is completed by calling MediaInfo.dll and is no longer detailed.

As shown in the framework of the entire system, the functionality of each section is then recorded in detail later in this article.

Effect

The system mainly contains the following pages:

home Page (index.jsp): Enter the first page of the system.
Video List (videolist.jsp): A list of pages that display video resources. Depending on the type of video source, it can be divided into VOD (VOD) video list and live video list.
video Editing (videoedit.jsp): Edit the page of a video resource. Depending on the type of video source, it can be divided into VOD (VOD) editing and live editing. Depending on the operation, you can divide it into add and edit.
video content (videocontent.jsp): A page that views the contents of a video. Depending on the type of video source, it can be divided into VOD (VOD) video content and Live (live) video content.
settings (configure.jsp): Settings page. The parameters used to formulate the system.
about (about.jsp): A page that displays some information about the system.
Home

The homepage of the website is as shown. The logo is in the upper-left corner and the menu bar is in the upper right corner. For the sake of aesthetics, a light box effect is made at the top of the page, and thumbnails of some videos are displayed randomly. Several recently added videos from the on-demand list and live list are listed below the page.

On-Demand list

The On-demand list page looks like this. On this page, you can manage on-demand videos simply: view content, add, modify, and delete.

Live list

The On-demand list page looks like this. The live list essentially uses the same page as the on-demand list. On this page, you can easily manage your live video: View content, add, edit, and delete.

Video content Page

The video content page is shown below. This page contains a FlowPlayer player that plays the video content.

The on-Demand video content page is shown below.

The live video content page is shown below. Although on the surface the on-demand and live pages are exactly similar, the mechanism for VOD and live broadcasting is actually different. On-demand relies on HTTP progressive downloads, while live streaming relies on the FlowPlayer rtmp component.

Video Add page

The on-Demand video add page is shown below. This page is used to upload an on-demand video. The name input box specifies the name of the video, and file specifies the uploaded video file, and introduction can specify a brief introduction to the video. The "name" and "File" two input boxes are required, otherwise the form of the page cannot be submitted.

The live video add page is shown below. You can see that the live and on-demand add pages are very similar. The difference is that the on-demand upload is a video file, and the live stream specifies a URL (currently the URL only supports rtmp). Similar to on-demand, the "name" and "URL" two input boxes are required, or the page's form cannot be submitted.

Video editing page

The on-demand video editing page is shown below. This page is used to edit the information for an on-demand video that has completed uploading.

The live video editing page is shown below. This page is used to edit the information for live video.

Configuration

The configuration page for the system is as shown. This page is used to configure various settings for the system (in the main transcoding settings). The settings take effect after each configuration has been completed after rebooting the system. Contains the following parameters.

  • Video encoder: Transcoding uses the video encoder, the default value is "libx264".
  • Video bitrate (bps): The bitrate (in bps) of the video encoding, the default value is 500000 (500kbps).
  • Video frame rate (fps): video-encoded frame rate (FPS) with a default value of 25.
  • Audio encoder: The audio encoder used when transcoding, the default value is "Libmp3lame".
  • Audio sample rate (Hz): The sample rate for audio encoding (in Hz) and the default value is 22050 (22.05kHz).
  • Audio bitrate (bps): The bitrate of the audio encoding (in bps), the default value is 64000 (64kbps).
  • Video width (pixel): The width of the video after transcoding (in pixel), the default value is 640.
  • Video High (pixel): the height of the transcoding video (in pixel), the default value is 360.
  • Use watermark: Select whether to add watermark to the video after transcoding. If you select Yes for this option, the watermark will be added to the video after transcoding.
  • Watermark file path: The path to the watermark file, which is the path to the file relative to the root of the Web site, which defaults to "Watermark/svw.png".
  • Watermark Position-X coordinate (pixel): The position of the watermark in the video--x coordinates (in pixel), the default value is 5.
  • Watermark coordinate-y coordinate (pixel): The position of the watermark in the video--y coordinates (in pixel), the default value is 5.
  • Maintain aspect ratio and fill black edges: Choose whether to maintain the aspect ratio after transcoding. If this option selects Yes, the transcoded video will maintain a aspect ratio, and when the input and output video aspect ratios are different, black edges will be added to the output video. If this option selects No, the transcoded video is stretched to the output resolution.
  • Output Video Encapsulation Format: Output video packaging format, the default is "FLV".
  • Video Location (sec): Gets the location of the video thumbnail (in sec), which defaults to 5sec. The default value is to get the video frame at the 5th second of the video as a thumbnail of the video.
  • Upload Video Storage folder: For uploading video files, the default value is "Videoori".
  • Transcoding Video Storage folder: A video file for transcoding, the default value is "video".
  • Video Storage folder: For storing video, the default value is "Videothumbnail".

MediaInfo Information

The MediaInfo information is located in the video content page and is not displayed by default. You can display mediainfo information for a video by modifying the code in the Web page.

transcoding before the file information as shown, you can see the transcoding before the file format is mpeg-ps, video encoding for MPEG-1, audio encoding for MP2.

After transcoding the file information as shown, you can see the transcoding before the file is the FLV format, video encoding of H. MP3, audio encoding.

Multi-lingual

The system supports multiple languages. You can switch the system to English by selecting "language" and "Chinese" in the top right-hand corner menu. The English interface is as shown.

The English version of the video-on-demand list is shown.

The English version of the video content page is shown in.

The English version of the configuration interface is shown in.

Site section

The following is a simple record of the site section of the key source code. Divided into three parts: database, foreground and background.

Database

The system contains 4 tables: Video,videostate,category,configure. Here's a simple record of what each table means.

Video table

The video table is used to store the recording. Each video corresponds to a record in the videos table. The fields in this table are shown in the following table.

Note

* The URL of the VOD video is the relative path of the video file.

The following example lists several items and URL-related data in the video table (subject to space, omitting other fields).

Videostate table

The Videostate table is used to store the status of the video. The fields in this table are shown in the following table.

Currently 4 states are defined in the order in which they are executed: Wait for upload, wait, wait for transcoding, complete. Where CSS style is used to assist in displaying the status of the video. The contents of the table are as follows

Category table

Category tables are used to store video classifications. The table can be used to determine the classification of the video and has not yet done much development.

Configure table

The Configure table is used to store system configuration information. The fields in this table are shown in the following table.

The contents of the table are as follows.

Front desk


The front desk section does not have much to record, basically is the various div and the CSS adjustment. More Jstl tags and el expressions are used. In addition, STRUTS2 tags are used to support internationalization. There are only 6 basic JSP pages:

Index.jsp: Home.
VIDEOLIST.JSP: Video List-live video list, on-demand video list.
videoedit.jsp: Video Editing-live video Add, live video editing, on-demand video add, on-demand video editing.
VIDEOCONTENT.JSP: Video Content-live video content, on-demand video content.
CONFIGURE.JSP: Configuration page.
about.jsp: About the page.

In addition to the basic pages, there are additional pages:

cfooter.jsp: Footer.
Cheader.jsp: Title bar.
csidebar_recent.jsp: Sidebar (recently added).
ERROR.JSP: Error page.
FlowPlayer player

The player used for video playback in the foreground page is FlowPlayer. There are 3 steps to installing the FlowPlayer player:
(1) JS file containing FlowPlayer

<script type= "Text/javascript" src= "Videoplayer/flowplayer-3.2.8.min.js" ></script>

(2) Add a <a> tag

<a href= "http://www.mywebsite.com/myVideo.flv"         style= "display:block;width:425px;height:300px;"         id= "Player" >      </a>

(3) Add a piece of JavaScript code that contains the FlowPlayer SWF file

<script language= "JavaScript" >   flowplayer ("Player", "path/to/the/flowplayer-3.2.18.swf");  </script>

FlowPlayer the source code for the on-demand video file over HTTP is shown below. The relative URL of the video is saved in ${video.url}.

<a id= "Player" href= "${pagecontext.request.scheme}://${pagecontext.request.servername}:${ Pagecontext.request.serverport}${pagecontext.request.contextpath}/${video.url} "> </a> <script>    FlowPlayer ("Player", "videoplayer/flowplayer-3.2.8.swf");  </script>

The sample code for FlowPlayer to play live video files via rtmp is shown below. The URL of the video is saved in ${video.url}. The FlowPlayer rtmp Plugin was used when playing rtmp. It is important to note that the URL of rtmp needs to be split separately to fill in different locations. This is where the split ('/') function separates the string into an array of strings by "/". Then fill in the "Protocol://server/app" to the Plugins netconnectionurl field, Playpath fill in the Clip's URL field.

<a id= "Player" > </a> <!--Parse RTMP URL--<script> str= ' ${video.url} ';  Arr=str.split ('/');        Rtmp://server/app/playpath  protocol=arr[0];  SERVER=ARR[2];  APP=ARR[3];  PLAYPATH=ARR[4];  Lowplayer ("Player", "videoplayer/flowplayer-3.2.8.swf", {           clip: {             //scaling: ' orig ',            Url:playpath,            provider: ' rtmp ',            Live: ' True '          },            plugins: {               rtmp: {                 URL: ' videoplayer/ Flowplayer.rtmp-3.2.8.swf ',                 netconnectionurl:protocol+ '//' +server+ '/' + App             }}}       );  Script>
Background

The background part uses Java EE's three-tier architecture for SSH (Struts2 + Spring + Hibernate), where the code is no longer documented in detail. The three tiers are the action layer, service layer, and DAO layer, respectively. The action layer uses the STRUTS2 framework, and the DAO layer uses the Hibernate framework, while spring integrates these three layers.

Baseservice/basedao

The SSH three-tier architecture, although well-done in terms of decoupling, has resulted in very cumbersome development and greatly reduced the speed of development. For convenience, Baseservice is written in the service layer for General Service operations, and Basedao is also written in the DAO layer to accomplish common DAO operations. In this way, unless there is a special requirement, you can normally do all kinds of basic operations by calling the methods in Baseservice. The interface that Baseservice contains is shown below.

/** * The simplest video website * Simplest videos Website * * Lei hua Lei xiaohua * * [email protected] * Communication University/Digital TV technology * Communication Uni Versity of China/digital TV technology * http://blog.csdn.net/leixiaohua1020 * * This program is one of the simplest video website videos. It supports * 1. Live * 2. On Demand * This software is the simplest video website. * IT Support: * 1. Live Broadcast * 2.  VOD * * Package service;  Import java.util.List; /** * @author Lei * The service * to object contains some common methods */public interface Baseservice {/** * saves an object * @pa  Ram object An object */public void Save (object object);  /** * Update an object * @param an object * * * public void Update (object object);  /** * Delete an object * @param an object * * * public void Delete (Object object); /** * Reads an object of the specified name according to the ID * @param the name of the TargetName object * @param ID Object ID * @return A  Object */Public Object Readbyid (String targetname,int ID);    @SuppressWarnings ("Rawtypes")/**        * Gets all objects of the specified type * @param targetName Object Type name * @return List of objects */public list ReadAll (S  Tring TargetName); @SuppressWarnings ("Rawtypes")/** * gets multiple objects of the specified type based on "Property-value" * @param targetName Object type name * @pa The name of the property in the Ram PropertyName Object * @param the value of the property in the PropertyValue object * @return The list of objects */public list R  Eadbyproperty (String targetname,string propertyname,object propertyvalue);            /** * Gets an object of the specified type according to the property-value * @param targetName Object Type name * @param the name of the property in the PropertyName object * @param the value of the property in the PropertyValue object * @return An object */public Object Readsingle (String targetname,st  Ring Propertyname,object PropertyValue);            /** * Gets more than one object of the specified type, which can be qualified to get the number of objects and sort according to a particular property.  * @param targetName Object Type name * @param the name of the property in the PropertyName object, used to sort * @param maximum number of NUM Result object lists * @param order Ordering, you can select ASC or DESC * @return ObjectList */public list readlimitedbyorder (String targetname,string propertyname,int num,string order);            /** * Gets the number of objects of the specified type.  * @param targetName Object type name * @return quantity */public int readcount (String targetName);            /** * Gets the number of objects of the specified type, based on the attribute-value condition.            * @param targetName Object Type name * @param the name of the property in the PropertyName object * @param the value of the property in the PropertyValue object  * @return quantity */public int readcountbyproperty (final String targetname,string PropertyName, Object value);           /** * Two functions: * 1. Gets more than one object of the specified type according to "Property-value" * 2. Limits the number of objects to get, and sorts them according to specific attributes.           * @param targetName Object Type name * @param the name of the property in the Readpropertyname object to get the value of the property in the object * @param readvalue Object * @param the name of the property in the Orderpropertyname object to sort * @param the maximum number of NUM result object lists * @param order ordering, you can select ASC or Desc "* @return */public List Readbypropertyandlimitedbyorder (final String TargetName, final string readpropertyname, final Object readvalue,final string orderpropertyname, final int num, final S  Tring order); }
FFmpeg partial interception of thumbnail threads and transcoding threads

The system will open two threads after booting: Videothumbnailthread and Videotranscoderthread. Where the Videothumbnailthread thread detects the video that needs to intercept the thumbnail, calls the corresponding FFmpeg command to intercept the thumbnail, and the videotranscoderthread thread keeps monitoring the video that needs to be transcoded, Call the appropriate ffmpeg command to transcode the video. How do I determine if a video needs to intercept thumbnails and need transcoding? This is identified by the Videostateid field in the video table. After the video starts uploading, the video recording will be marked as "Wait for upload" (1th step), after uploading, the video record will be marked as "Wait" (2nd step), after completion, the video record will be marked as "Wait for transcoding" (3rd Step), after the transcoding, the video record will be marked as "complete" (4th step). Videothumbnailthread will constantly check the system "Waiting" video, after completion of the video marked as "Waiting for transcoding", Videotranscoderthread will continue to check the system "Waiting for transcoding" video, Transcoding completed after the video marked as "Done."

Integration of FFmpeg and Java

There are several areas to note in the process of ffmpeg and Java integration:

(1) Processing of paths

FFmpeg the absolute path is required to process the video, so it involves the problem of absolute path acquisition. Use ServletContext's Getrealpath ("/") method to get the absolute path of the current web app's root directory. For example, on your own computer, the following code can be used to obtain the Web application of the path:

ServletContext ServletContext;  System.out.println (Servletcontext.getrealpath ("/"));

After execution, the output is:

D:\MyEclipseWorkspace\.metadata\.me_tcat\webapps\simplest_video_website\

The path in the URL in the relative path is delimited by "/" (forward slash, Unix system use), and the path in the preceding code is delimited by "\" (backslash, used by Windows system). If the relative file path and the absolute directory path are stitched together to pass to FFmpeg, FFmpeg is recognizable, but this way the path of a "/" a "will" will give people a very awkward feeling, so you can use the Replace () method of string to replace "\" with " /"So it's a lot more neat. For example, the following code:

ServletContext ServletContext;  System.out.println (Servletcontext.getrealpath ("/"). replace (' \ \ ', '/'));

After execution, the output is:

d:/myeclipseworkspace/.metadata/.me_tcat/webapps/simplest_video_website/

(2) FFmpeg command-line invocation

The call to the FFmpeg command line can be divided into two steps:

(a) Generate commands that match settings

This step is actually a simple string concatenation process. The corresponding transcoding commands are stitched according to the configured parameters. Note that double quotes are added to both the input and output file paths. Otherwise, a path parsing error is caused when the file path contains spaces.

(b) invoking the command line

Invoking the command line using the Runtime.getruntime (). Exec (Cmdstr) method is OK. There are two common formats for CMDSTR:

cmd/c {FFmpeg command}  cmd/c start {FFmpeg command}

The first format is to execute the command directly in this window, and the second is to open a new window to execute the command. The first method I test in the Java EE environment is problematic, and no popup window is not easy to debug, so use the second method of execution.

(c) The command line waiting to be called is finished

Runtime.getruntime (). EXEC () returns the current thread directly after invoking the command. This is not in line with the actual demand. In fact, the system needs to complete the ffmpeg transcoding work, to do the next operation. The WAITFOR () method of the process can be used to block the yourselves thread until the calling program finishes running.

Truncate thumbnail command

FFmpeg intercept thumbnail commands as follows:

Ffmpeg-y-i "ourtime.flv"-ss 5-s 220x110-f image2-vframes 1 "thumbnail.jpg"

The parameters have the following meanings:

-
y: Automatically overwrite when the output file name is the same.
-I: Enter the file path (either a relative path or an absolute path).
-SS: The point at which to intercept thumbnails, here is 5s.
-S: Output the resolution of the thumbnail, here is 220x110.
-F: Output file format, here the Image2 represents the file format for the picture.
-vframes: The number of output video frames, here is 1.
The last parameter is the output thumbnail file path.
transcoding commands

The FFmpeg transcoding command is as follows:

Ffmpeg-y-i "ourtime.flv"-vcodec libx264-b:v 500000-r 25-acodec libmp3lame-b:a 64000-ar 22050-vf scale=w=640:h=360 : force_original_aspect_ratio=decrease,pad=w=640:h=360:x= (OW-IW)/2:y= (OH-IH)/2[AA];MOVIE=SVW.PNG[BB]; [AA] [Bb]overlay=x=5:y=5 "ourtime_convert.flv"

The parameters have the following meanings:

-
y: Automatically overwrite when the output file name is the same.
-I: Enter the file path (either a relative path or an absolute path).
-VCODEC: Video encoder, here is libx264.
-b:v: Video bitrate, here is 500000bps.
-r: Video frame rate, here is 25fps.
-acodec: Audio encoder, here is libmp3lame.
-b:a: Audio bitrate, here is 64000bps.
-ar: Audio sample rate, here is 22050Hz.
-VF: Filters for image stretching and watermark overlays.
The last parameter is the output video file path.

Filter (Filter) configuration

A few words about the configuration of filter:

    • The filter configuration parameter is used after the-VF parameter of the FFmpeg
    • A "," connection can be used between the filter and the output of the previous filter after the connection as input to the latter filter. Several filter forms a Filterchain (filter chain), each filterchain with ";" End. Several filter chain can form a filtergraph (filter chart). You can add "label" to the filter pad to connect other Filter,filter tags in the form of "[XX]" (where "xx" can write some characters at will, as long as it can play the role of marking).
    • The filter can use multiple parameters, with the ":" Split between the parameters.

Here's how to use several filters, respectively.

"Scale Filter"

The scale filter stretches the image using Libswscale. Its parameters have the following meanings:

W: The width of the output image.
H: The output image is high.
Force_original_aspect_ratio: To maintain the video aspect ratio, the following values can be used: (1) disable--not maintain aspect ratio, (2) reduce width or height when decrease--required; (3) increase-- Raise the width or height when needed.

For an example of Force_original_aspect_ratio: the input video resolution is 1920x800 and the filter is set to:

Scale=w=640:h=360:force_original_aspect_ratio=decrease

The output video resolution is 640x266.
"Pad Filter"
The pad filter is used to add a "black edge" to the stretched image. After the scale filter processing, the width of the video must be less than or equal to 640, while the video height must be less than or equal to 360, the need to use pad filter to fill the video on both sides (up or down), to ensure that the output video resolution of 640x360.
The PAD filter has four basic parameters:

W: Width of the video after filling
H: Height of post-populated video
X: Enter the x-coordinate of the upper-left corner of the video in the filled video
Y: Enter the y-coordinate of the upper-left corner
of the video in the filled video

A basic example of the law is as follows:

Pad=w=640:h=480:x=0:y=40

The filter fills the video as 640x480 and places the upper-left corner of the input video on (0,40).
In the process of adding black edge to the video, you need to put the input video in the center of the filled video, and the pad filter input video position is determined in the upper left corner, so it is difficult to determine the coordinates of the upper left corner of the input video. For this, the PAD filter provides the following variables.

IW: Enter the width of the video
IH: Enter the height of the video
OW: The width of the output video
Oh: High Output video

Through the above variables, you can know that if you want to put the input video in the center of the filled video, the input video should be the X coordinate (OW-IW)/2,y coordinates should be (OH-IH)/2.
"Movie Filter"
The Movie filter belongs to the source filter, which is used to read the watermark picture file (typically a PNG file). There is one place to pay special attention to the movie filter: It does not seem to support an absolute path for the input path under Windows. Because the absolute path of a file under Windows is usually "D:\test\......\watermark.png", which is followed by a ":" In the beginning of the drive letter. ":" In filter is a special character that will be parsed into the delimiter of the parameter, which causes the absolute path of the input to be resolved to 2 parameters, resulting in an error. The problem was that I had been debugging for half a day and was still unresolved. Therefore, when using the movie filter under Windows, it is necessary to ensure that the watermark file is in the current working directory for normal operation.
"Overlay Filter"
The overlay filter is used to overlay two inputs. Specific to the system in this article is to overlay the watermark file to the video file. It is commonly used with two parameters:

x: The x-coordinate of the upper-left corner of the watermark
Y: the y-coordinate of the upper-left corner of the watermark


After the processing of the above-mentioned filters, we can finally get a video with a resolution of 640x360, which maintains the aspect ratio (plus black edge) and overlays the watermark.

Project Home

Simplest Video Website

Open source China: http://git.oschina.net/leixiaohua1020/simplest_video_website

Installation steps
1. Install the Java EE Environment:
(1) Download and install the JDK
(2) Download and install Tomcat
(3) Download and install MySQL
2.FFmpeg
(1) Download and unzip the FFmpeg executable program
(2) Add the FFmpeg bin directory (which contains Ffmpeg.exe) to the system's "path" environment variable (so that the ffmpeg command can be used in any directory in the system)
3. Copying programs
(1) Modify the user name and password of the database in Webroot\web-inf\classes\hibernate.cfg.xml
(2) Copy the Webroot directory to Tomcat's WebApps directory and re-name it (e.g. "SVW")
(3) Create a database "SVW" in MySQL, execute svw.sql in it, create a table in the database, and add test data
4. Start Tomcat
5. Access HTTP://LOCALHOST:8080/SVW using a browser

Http://www.cnblogs.com/xkfz007/p/4517966.html

The simplest video website (javaee+ffmpeg)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.