Some useful ffmpeg commands ( commandline video converting tool)

1. Converting MOV/MPEG/AVI/MP4 –> flv 
#ffmpeg -i input file output.flv

2. Convert and adjust the video file resolution to output file
# ffmpeg -i input.avi -s 500×500 output.flv

3. Converting 3GP –> FLV
#ffmpeg -i input.3gp -sameq -an output.flv

4. Converting MPEG –>3GP
#ffmpeg -i input.mpeg -ab 8.85k -acodec libamr_wb -ac 1 -ar 16000 -vcodec h263 -s qcif output.3gp

5. Converting WMV –> to MP3
#ffmpeg -i input.wmv output.mp3

6. Converting AMR –> MP3
#ffmpeg -i input.amr -ar 22050 output.mp3

7. Converting FLV –> MP4
# ffmpeg -i input.flv -ar 22050 output.mp4

Advanced flash supported conversion.

#ffmpeg -i input.flv -s 480×360 -vcodec libx264 -b 1900kb -flags +loop -cmp +chroma -me_range 16 -me_method hex -subq 5 -i_qfactor 0.71 -qcomp 0.6 -qdiff 4 -directpred 1 -flags2 +fastpskip -dts_delta_threshold 1 -acodec libfaac -ab 128000 output.mp4

This code will support to play in Iphone.

#ffmpeg -i 400b75e5081fca44d094.flv -s 320×240 -r 24 -b 200k -bt 240k -vcodec libx264 -vpre hq -coder 0 -bf 0 -flags2 -wpred-dct8x8 -level 13 -maxrate 768k -bufsize 3M -acodec libfaac -ac 2 -ar 48000 -ab 192k new_output_new1.mp4

8. Converting AAC –> Mp3
#ffmpeg -i input.aac -ar 22050 -ab 32 output.mp3

Use ffmpeg with it’s best performance

The following arguments helps you to optimize the ffmpeg conversion to get the best result of converting mp4. to flv

# ffmpeg -i input.mp4 -ar 22050 -ab 56 -acodec mp3 -r 25 -f flv -b 400 -s 320×240 output.flv

-i = specify input file
-ar = audio sample rate
-ab = audio bitrate
-acodec = audio codec
-r = framerate
-f = output format
-b = bitrate (of video!)
-s = resize to width x height

10, Convert Video –> JPG Sequence
#ffmpeg -i input.mpg -an -r 10 -y -s 320×240 video%d.jpg

11. Convert Every n seconds to JPEG
#ffmpeg -i input.mpg -r 0.2 -sameq -f image2 thumbs%02d.jpg where r is the time when jpg file created. r can be 0.2 indicate every 5 second, if you need a jpeg on every 45 seconds use 1/45.

11. Crop the video between the specified time
#ffmpeg -i input.mpg -an -ss 00:00:03 -t 00:00:01 -r 1 -y -s 320×240 video%d.jpg where
-ss : Record start time
-t : No. of second to end suppose you want to crop 2 minutes video which starts from the 10 minutes play
-ss 00:10:00 -t 00:02:00
%d : Naming with timestamp

12. Converting flv –> mp3
#ffmpeg -i input.flv -vn -acodec copy output.mp3

13. Converting WAV –> MP3 
#ffmpeg -i Input.wav -ab 128 Output.mp3
#ffmpeg -i input.avi -vn -ar 44100 -ac 2 -ab 192 -f mp3 output.mp3

14 : Encode a video sequence for the iPpod/iPhone 
ffmpeg -i input.avi input -acodec aac -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -flags +4mv+trell -aic 2 -cmp 2 -subcmp 2 -s 320×180 -title X output.mp4

15. Converting AVI –> GIF
ffmpeg -i input.avi gif_anime.gif
16. Compress .avi –> divx
#ffmpeg -i input.avi -s 320×240 -vcodec msmpeg4v2 output.avi
Source : input.avi
Audio codec : aac
Audio bitrate : 128kb/s
Video codec : mpeg4
Video bitrate : 1200kb/s
Video size : 320px par 180px
Generated video : output.mp4

17. Converting flv –> Mp4
#ffmpeg -i sample.flv -ab 128kb -vcodec mpeg4 -b 1200kb -mbd 2 -s 320×240 final_video.mp4

some useful resources,

http://www.itbroadcastanddigitalcinema.com/ffmpeg_howto.html

http://ffmpeg.org/faq.html

Apache Kafka 0.8.0发布,高吞吐量分布式消息系统

Apache Kafka 0.8.0版本近日发布。Apache Kafka是源自LinkedIn的一种分布式日志服务,主要用Scala语言开发(少量Java),其实质是高吞吐量而功能简单的消息队列。由于架构设计独特,Kafka与传统消息队列相比,内置分区、复制和容错功能,适合大规模系统。曾有数据表明,Kafka能够每秒发布超过40万条消息。

目前Kafka已经被众多互联网公司如Twitter、Pinterest、Netflix、Tumblr、Foursquare、Square、StumbleUpon、Coursera等广泛应用,主要使用场景包括:消息处理、活动流跟踪、运营数据监测、日志聚合、流处理(与Storm配合)等。

Apache Kafka 0.8.0版本主要改进包括:

更多技术细节请参考版本说明

技术资料

利用Proxy Cache使Nginx对静态资源进行缓存

前言

Nginx是高性能的HTTP服务器,通过Proxy Cache可以使其对静态资源进行缓存。其原理就是把静态资源按照一定的规则存在本地硬盘,并且会在内存中缓存常用的资源,从而加快静态资源的响应。

配置Proxy Cache

以下为nginx配置片段:

proxy_temp_path   /usr/local/nginx/proxy_temp_dir 1 2;

#keys_zone=cache1:100m 表示这个zone名称为cache1,分配的内存大小为100MB
#/usr/local/nginx/proxy_cache_dir/cache1 表示cache1这个zone的文件要存放的目录
#levels=1:2 表示缓存目录的第一级目录是1个字符,第二级目录是2个字符,即/usr/local/nginx/proxy_cache_dir/cache1/a/1b这种形式
#inactive=1d 表示这个zone中的缓存文件如果在1天内都没有被访问,那么文件会被cache manager进程删除掉
#max_size=10g 表示这个zone的硬盘容量为10GB

proxy_cache_path  /usr/local/nginx/proxy_cache_dir/cache1  levels=1:2 keys_zone=cache1:100m inactive=1d max_size=10g;

server {
    listen 80;
    server_name *.example.com;

    #在日志格式中加入$upstream_cache_status
    log_format format1 '$remote_addr - $remote_user [$time_local]  '
        '"$request" $status $body_bytes_sent '
        '"$http_referer" "$http_user_agent" $upstream_cache_status';

    access_log log/access.log fomat1;

    #$upstream_cache_status表示资源缓存的状态,有HIT MISS EXPIRED三种状态
    add_header X-Cache $upstream_cache_status;
    location ~ .(jpg|png|gif|css|js)$ {
        proxy_pass http://127.0.0.1:81;

        #设置资源缓存的zone
        proxy_cache cache1;

        #设置缓存的key
        proxy_cache_key $host$uri$is_args$args;

        #设置状态码为200和304的响应可以进行缓存,并且缓存时间为10分钟
        proxy_cache_valid 200 304 10m;

        expires 30d;
    }
}

安装Purge模块

Purge模块被用来清除缓存

$ wget http://labs.frickle.com/files/ngx_cache_purge-1.2.tar.gz
$ tar -zxvf ngx_cache_purge-1.2.tar.gz

查看编译参数

$ /usr/local/nginx/sbin/nginx -V 

在原有的编译参数后面加上--add-module=/usr/local/ngx_cache_purge-1.2

$ ./configure --user=www --group=www --prefix=/usr/local/nginx \
--with-http_stub_status_module --with-http_ssl_module \
--with-http_realip_module --add-module=/usr/local/ngx_cache_purge-1.2
$ make && make install

退出nginx,并重新启动

$ /usr/local/nginx/sbin/nginx -s quit
$ /usr/local/nginx/sbin/nginx

配置Purge

以下是nginx中的Purge配置片段

location ~ /purge(/.*) {
    #允许的IP
    allow 127.0.0.1;
    deny all;
    proxy_cache_purge cache1 $host$1$is_args$args;
}

清除缓存

使用方式:

$ wget http://example.com/purge/uri

其中uri为静态资源的URI,如果缓存的资源的URL为 http://example.com/js/jquery.js,那么访问 http://example.com/purge/js/jquery.js则会清除缓存。

命中率

保存如下代码为hit_rate.sh:

#!/bin/bash
# author: Jeremy Wei <[email protected]>
# proxy_cache hit rate

if [ $1x != x ] then
    if [ -e $1 ] then
        HIT=`cat $1 | grep HIT | wc -l`
        ALL=`cat $1 | wc -l`
        Hit_rate=`echo "scale=2;($HIT/$ALL)*100" | bc`
        echo "Hit rate=$Hit_rate%"
    else
        echo "$1 not exsist!"
    fi
else
    echo "usage: ./hit_rate.sh file_path"
fi

使用方式

$ ./hit_rate.sh /usr/local/nginx/log/access.log

参考:

http://wiki.nginx.org/HttpProxyModule

(完)

 

作者: JeremyWei | 可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明
网址: http://weizhifeng.net/nginx-proxy-cache.html

6 Must Have Node.js Modules

So you’re thinking about using node.js: awesome. If you’re new to the community you’re probably thinking “what’s the best node.js module / library for X?” I think it’s really true when experienced language gurus say “80% of your favorite language is your favorite library.” This is the first in a series of articles will give you a high-level overview of some of our favorite node.js libraries at Nodejitsu. Today we’ll take a look at these libraries:

 

  1. cradle: A high-level, caching, CouchDB library for Node.js
  2. findit: Walk a directory tree in node.js
  3. node_redis: Redis client for node
  4. node-static: RFC2616 compliant HTTP static-file server module, with built-in caching.
  5. optimist: Light-weight option parsing for node.js
  6. xml2js: Simple XML to JavaScript object converter.

 

cradle: A high-level, caching, CouchDB library for Node.js

If you’re using CouchDB you should be using cradle. Cradle stands above the other CouchDB libraries in the node.js community: it has a robust LRU (least recently used) cache, bulk document processing, and a simple and elegant API:

 

//
// Create a connection
//
var conn = new(cradle.Connection)('http://living-room.couch', 5984, {
  cache: true,
  raw: false
});

//
// Get a database
//
var database = conn.database('newyorkcity');

//
// Now work with it
//
database.save('flatiron', {
  description: 'The neighborhood surrounding the Flatiron building',
  boundaries: {
    north: '28 Street',
    south: '18 Street',
    east: 'Park Avenue',
    west: '6 Avenue'
  }
}, function (err, res) {
  console.log(res.ok) // True
});

 

 

findit: Walk a directory tree in Node.js

A common set of problems that I see on the nodejs mailing list are advanced file system operations: watching all the files in a directory, enumerating an entire directory, etc. Recently, when working on my fork of docco to respect directory structure in the documentation produced I needed such a feature. It was surprisingly easy:

 

var findit = require('findit');

findit.find('/dir/to/walk', function (file) {
  //
  // This function is called each time a file is enumerated in the dir tree
  //
  console.log(file);
});

 

 

node_redis: Redis client for Node.js

There have been a lot of redis clients released for node.js. The question has become: which client is the right one to use? When selecting an answer to this question for any library you want to look for a few things including: the author, the recent activity, and the number of followers on GitHub. In this case the author is Matt Ranney, a member of the node.js core team. The most recent commit was yesterday, and the repository has over 300 followers.

Redis is really fast, and extremely useful for storing volatile information like sessions and cached data. Lets take a look at some sample usage:

 

var redis = require("redis"),
    client = redis.createClient();

client.on("error", function (err) {
  console.log("Error " + err);
});

client.set("string key", "string val", redis.print);
client.hset("hash key", "hashtest 1", "some value", redis.print);
client.hset(["hash key", "hashtest 2", "some other value"], redis.print);
client.hkeys("hash key", function (err, replies) {
  console.log(replies.length + " replies:");
  replies.forEach(function (reply, i) {
      console.log("    " + i + ": " + reply);
  });
  client.quit();
});

 

 

node-static: RFC2616 compliant HTTP static-file server module, with built-in caching

I bet you’re wondering “What the $%^@ is RFC2616?” RFC2616 is the standards specification for HTTP 1.1, released in 1999. This spec is responsible for outlining how (among other things) files should be served over HTTP. Thus, when choosing a node.js static file server, its important to understand which libraries are standards compliant and which are not: node-static is. In addition, it has some great built-in caching which will speed up your file serving in highly concurrent scenarios.

Using node-static is easy, lets make a static file server in 7 lines of Javascript:

 

var static = require('node-static');

//
// Create a node-static server instance to serve the './public' folder
//
var file = new(static.Server)('./public');

require('http').createServer(function (request, response) {
  request.addListener('end', function () {
    //
    // Serve files!
    //
    file.serve(request, response);
  });
}).listen(8080);

 

 

optimist: Light-weight option parsing for Node.js

One of the great things about node.js is how easy it is to write (and later publish with npm) simple command-line tools in Javascript. Clearly, when one is writing a command line tool one of the most important things is to have a robust command line options parser. Our library of choice for this at Nodejitsu is optimist by substack.

Lets take a look at a sample CLI script reminiscent of FizzBuzz:

 

#!/usr/bin/env node
var argv = require('optimist').argv;

if (argv.rif - 5 * argv.xup > 7.138) {
  console.log('Buy more riffiwobbles');
}
else {
  console.log('Sell the xupptumblers');
}

 

Using this CLI script is easy:

$ ./node-optimist.js --rif=55 --xup=9.52
Buy more riffiwobbles

$ ./node-optimist.js --rif 12 --xup 8.1
Sell the xupptumblers

This library has support for -a style arguments and --argument style arguments. In addition any arguments passed without an option will be available in argv._. For more information on this library check out the repository on GitHub.

 

xml2js: Simple XML to Javascript object converter

Writing clients in node.js for APIs that expose data through JSON is almost too easy. There is no need for a complex, language-specific JSON parsing library that one might find in languages such as Ruby or Python. Just use the built-in Javascript JSON.parse method on the data returned and voila! you’ve got native Javascript objects.

But what about APIs that only expose their data through XML? You could use the native libxmljsmodule from polotek, but the overhead of dealing with individual XML nodes is non-trivial and (in my opinion) can lead to excess complexity. There is another, simpler option: the lesser knownxml2js library available on npm and GitHub.

Lets suppose that we had some XML (/me dies a little inside):

 

<?xml version="1.0" encoding="UTF-8"?>
<root>
  <child foo="bar">
    <grandchild baz="fizbuzz">grandchild content</grandchild>
  </child>
  <sibling>with content!</sibling>
</root>

 

Parsing this using xml2js is actually surprisingly easy:

 

var fs = require('fs'),
    eyes = require('eyes'),
    xml2js = require('xml2js');

var parser = new xml2js.Parser();

parser.on('end', function(result) {
  eyes.inspect(result);
});

fs.readFile(__dirname + '/foo.xml', function(err, data) {
  parser.parseString(data);
});

 

The output we would see is:

 

{
  child: {
    @: { foo: 'bar' },
    grandchild: {
      #: 'grandchild content',
      @: { baz: 'fizbuzz' }
    }
  },
  sibling: 'with content!'
}

 

If you haven’t already noticed, xml2js transforms arbitrary XML to JSON in the following way:

  • All entity tags like <child> become keys in the corresponding JSON.
  • Simple tags like <sibling>with content</sibling> become simple key:value pairs (e.g. sibling: ‘with content!’)
  • More complex tags like <child>... and <grandchild>... become complex key:value pairs where the value is an Object literal with two important properties:
    1. @: An Object representing all attributes on the specified tag
    2. #: Any text content for this XML node.

This simple mapping can greatly simplify the XML parsing logic in your node.js application and is worth checking out if you ever have to deal with the three-headed dog we all love to hate.

 

Just getting started

This is the first in a series of articles where we will outline at a high level the best-of-the-best for modules, libraries and techniques in node.js that you should be aware of. If you’re interested in writing your own node.js modules and publishing them to npm, check out isaacs new article: How to Module over at howtonode.org.

为什么要迁移到Websphere, Weblogic, and JBoss? Resin用着很好。

我们的项目在 Dual Xeon 3.0 GHz with 4 GB RAM and 36 GB SCSI/RAID5下的Resin Pro可以轻松跑415 avg. req/s ,但迁移到 JBoss/Tomcat后就降低到225 avg. req/s.

我不知道Resin clsutering或 session replication有多好,但我会说,他们可能是很好的。

关于编译resin的错误处理。

不知道什么时候开始,resin4就无法编译

错误1:aclocal: couldn’t open directory `m4′: No such file or directory

[root@datanode2 resin-pro-4.0.36]# make
CDPATH=”${ZSH_VERSION+.}:” && cd . && aclocal -I m4
perl: warning: Setting locale failed.
perl: warning: Please check that your locale settings:
LANGUAGE = (unset),
LC_ALL = (unset),
LANG = “en.UTF-8”
are supported and installed on your system.
perl: warning: Falling back to the standard locale (“C”).
aclocal: couldn’t open directory `m4′: No such file or directory
make: *** [aclocal.m4] Error 1

处理办法在resin目录下建立m4目录。

mkdir m4

问题解决。

错误2:Makefile.in not found

[root@datanode2 resin-pro-4.0.36]# make
cd . && automake –foreign –ignore-deps
configure.ac:1568: required file `../pro/modules/c/src/Makefile.in’ not found
configure.ac:1568: required file `../pro/modules/c/src/resin/Makefile.in’ not found
configure.ac:1568: required file `../pro/modules/c/src/resinssl/Makefile.in’ not found
make: *** [Makefile.in] Error 1

解决办法:
mkdir ../pro
cp -r modules ../pro/

 

以上2个错误应该跟新版的resin没有多大关系,不过可能是我的编译器比较旧吧。

SIEGE

Siege is an http load testing and benchmarking utility. It was designed to let web developers measure their code under duress, to see how it will stand up to load on the internet. Siege supports basic authentication, cookies, HTTP and HTTPS protocols. It lets its user hit a web server with a configurable number of simulated web browsers. Those browsers place the server “under siege.”

下载最新版

wget http://www.joedog.org/pub/siege/siege-latest.tar.gz

tar -zxf siege-lastest.tar.gz

cd siege-xxx

./configure && make && install

vi /tmp/tmpurl
http://127.0.0.1/index.html
http://127.0.0.1/images/banner/1.jpg
http://127.0.0.1/images/banner/8.jpg

siege -c 100 -b -i -r 100 -f /tmp/tmpurl

100个用户,执行100次。

** SIEGE 3.0.0
** Preparing 100 concurrent users for battle.
The server is now under siege.. done.

Transactions: 10000 hits
Availability: 100.00 %
Elapsed time: 2.44 secs
Data transferred: 1396.79 MB
Response time: 0.02 secs
Transaction rate: 4098.36 trans/sec
Throughput: 572.45 MB/sec
Concurrency: 91.24
Successful transactions: 10000
Failed transactions: 0
Longest transaction: 0.23
Shortest transaction: 0.00

静态文件用nginx直接serve

#css|js|ico|gif|jpg|jpeg|png|txt|html|htm|xml|swf|wav这些都是静态文件,但应分辨,js、css可能经常会变,过期时间应小一些,图片、html基本不变,过期时间可以设长一些
location ~* ^.+\.(ico|gif|jpg|jpeg|png|html|htm)$ {
root /var/www/poseidon/root/static;
access_log off;
expires 30d;
}
location ~* ^.+\.(css|js|txt|xml|swf|wav)$ {
root /var/www/poseidon/root/static;
access_log off;
expires 24h;
}
#注:location不包括?后面带的参数,所以以上正则可以匹配http://192.168.1.16/image/sxxx.jpg?a=xxx

Node.js 究竟是什么?

Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念。它的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处理数万条同时连接到一个(只有一个)物理机的连接代码。

 

清单 2. Node 随机数字生成器
// these modules need to be imported in order to use them.
// Node has several modules. They are like any #include
// or import statement in other languages
var http = require(“http”);
var url = require(“url”);

// The most important line in any Node file. This function
// does the actual process of creating the server. Technically,
// Node tells the underlying operating system that whenever a
// connection is made, this particular callback function should be
// executed. Since we’re creating a web service with REST API,
// we want an HTTP server, which requires the http variable
// we created in the lines above.
// Finally, you can see that the callback method receives a ‘request’
// and ‘response’ object automatically. This should be familiar
// to any PHP or Java programmer.
http.createServer(function(request, response) {

// The response needs to handle all the headers, and the return codes
// These types of things are handled automatically in server programs
// like Apache and Tomcat, but Node requires everything to be done yourself
response.writeHead(200, {“Content-Type”: “text/plain”});

// Here is some unique-looking code. This is how Node retrives
// parameters passed in from client requests. The url module
// handles all these functions. The parse function
// deconstructs the URL, and places the query key-values in the
// query object. We can find the value for the “number” key
// by referencing it directly – the beauty of JavaScript.
var params = url.parse(request.url, true).query;
var input = params.number;

// These are the generic JavaScript methods that will create
// our random number that gets passed back to the caller
var numInput = new Number(input);
var numOutput = new Number(Math.random() * numInput).toFixed(0);

// Write the random number to response
response.write(numOutput);

// Node requires us to explicitly end this connection. This is because
// Node allows you to keep a connection open and pass data back and forth,
// though that advanced topic isn’t discussed in this article.
response.end();

// When we create the server, we have to explicitly connect the HTTP server to
// a port. Standard HTTP port is 80, so we’ll connect it to that one.
}).listen(80);

// Output a String to the console once the server starts up, letting us know everything
// starts up correctly
console.log(“Random Number Generator Running…”);

启动应用程序
将上面的代码放入一个名为 “random.js” 的文件中。现在,要启动这个应用程序并运行它(以便创建 HTTP 服务器并监听端口 80 上的连接),只需在您的命令提示中输入以下命令:% node random.js。下面是服务器已经启动并运行时看起来的样子:
root@ubuntu:/home/moila/ws/mike# node random.js
Random Number Generator Running…

访问应用程序
应用程序已经启动并运行。Node 正在监听所有连接,我们来测试一下。由于我们创建了一个简单的 RESTful API,所以可以使用 Web 浏览器来访问这个应用程序。键入以下地址(确保您已完成了上面的步骤):http://localhost/?number=27。
您的浏览器窗口将更改到一个介于 0 到 27 之间的随机数字。单击浏览器上的 “重新载入” 按钮,您会得到另一个随机数字。就是这样,这就是您的第一个 Node 应用程序!

 

学习

获得产品和技术