2011年9月1日星期四

Konsole 里 Session Profile 命令的解析过程

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。

如果没有强大的动力,我基本是不会主动去读 C++ 的源代码的。事情的起因其实很简单, 就是 Jesse 在 #beihang-osc@freenode.net 上吼,想在 gnome-terminal 里不用 gconf 实现 http://vim.wikia.com/wiki/Change_cursor_shape_in_different_modes 里的效果。他想 看看 Konsole 是怎么实现的。作为伪 KDE 控的我当然不能放过这个机会啦……

第一步是从 anongit.kde.org 上 clone konsole 的源代码。无他,主要是为了打 patch 方便和那个无比好用的 git grep ;P 写这篇文章的时候 git HEAD 是 d6ca64fe4d。

然后这逛那逛的也一直没有头绪。忽然想,那个指令不是 "\<Esc>]50;CursorShape=1\x7" 和 "\<Esc>]50;CursorShape=0\x7" 么,干脆 git grep -n ']50' 试试。嘿,还真找到了:

src/Part.cpp:276: buffer.append("\033]50;").append(text.toUtf8()).append('\a');
src/konsoleprofile:3:/bin/echo -e "\033]50;$1\a"
lines 1-2/2 (END)

火速去 src/Part.cpp 第 276 行看:

void Part::changeSessionSettings(const QString& text)
    {
        // send a profile change command, the escape code format
        // is the same as the normal X-Term commands used to change the window title or icon,
        // but with a magic value of '50' for the parameter which specifies what to change
        Q_ASSERT( activeSession() );
        QByteArray buffer;
        buffer.append("\033]50;").append(text.toUtf8()).append('\a');

        activeSession()->emulation()->receiveData(buffer.constData(),buffer.length());
    }

注释说的挺清楚了,而且 033 就是 ASCII 的 ESC,a 是 x7。一切都对应上了。最后它 把指令送给了 activeSession()->emulation()->receiveData 。省略中间痛苦的寻找 过程直接说了,konsole 里每一个窗口/Tab都会有一个 Session, activeSession() 获取的是当前用户正在使用的 Session。每个 Session 里都会有一个 emulation 来模拟 terminal,处理用户的输入输出(src/Session.h 的 136 行)。 Session->emulation() 获取的就是它。具体的东西是 src/Session.cpp 129 行的 _emulation = new Vt102Emulation(); 嗯,跳去 src/Vt102Emulation.cpp 找 receiveData ,木有找 到…… .h 里也没有…… 想起来有可能在鸡肋里, Vt102Emulation 是继承 Emulation 的,于是再跳到 src/Emulation.cpp 看 receiveData

/*
       We are doing code conversion from locale to unicode first.
    TODO: Character composition from the old code.  See #96536
    */

    void Emulation::receiveData(const char* text, int length)
    {
        emit stateSet(NOTIFYACTIVITY);

        bufferedUpdate();

        QString unicodeText = _decoder->toUnicode(text,length);

        //send characters to terminal emulator
        for (int i=0;i<unicodeText.length();i++)
            receiveChar(unicodeText[i].unicode());

        //look for z-modem indicator
        //-- someone who understands more about z-modems that I do may be able to move
        //this check into the above for loop?
        for (int i=0;i<length;i++)
        {
            if (text[i] == '\030')
            {
                if ((length-i-1 > 3) && (strncmp(text+i+1, "B00", 3) == 0))
                    emit zmodemDetected();
            }
        }
    }

略掉编码转换和 z-modem 的过程,这个 receiveData 就是把东西送给了 receiveChar 。再找 receiveChar

// process application unicode input to terminal
    // this is a trivial scanner
    void Emulation::receiveChar(int c)
    {
        c &= 0xff;
        switch (c)
        {
            case '\b'      : _currentScreen->backspace();                 break;
            case '\t'      : _currentScreen->tab();                       break;
            case '\n'      : _currentScreen->newLine();                   break;
            case '\r'      : _currentScreen->toStartOfLine();             break;
            case 0x07      : emit stateSet(NOTIFYBELL);                   break;
            default        : _currentScreen->displayCharacter(c);         break;
        };
    }

不会这么简单吧!又忽然想起来, Emulation::receiveData 可能会调用 Vt102Emulation::receiveChar 的吧…… 在 src/Emulation.h 的 427 行,这货果然是 virtual 的。于是再返回 src/Vt102Emulation.cpp 找 receiveChar 。这回终于 找到处理字符序列的地方了。不过因为整个函数有101行,还要加上前面18行注释和15行宏 ,就不贴在这里了。那个函数主要是把用户输入 tokenize ,并且对 token 进行处理。这 整个过程我还不是完全理解,但是大概的内容可以猜的出来。对于本文起作用的主要是第 316 行

if (Xte         ) { processWindowAttributeChange(); resetTokenizer(); return; }

Xte 是个判断 \033] 的宏。(好吧,它其实只判断了 token 的位置和 ']') processWindowAttributeChange 就在 receiveChar 的下面

void Vt102Emulation::processWindowAttributeChange()
    {
      // Describes the window or terminal session attribute to change
      // See Session::UserTitleChange for possible values
      int attributeToChange = 0;
      int i;
      for (i = 2; i < tokenBufferPos     && 
                  tokenBuffer[i] >= '0'  && 
                  tokenBuffer[i] <= '9'; i++)
      {
        attributeToChange = 10 * attributeToChange + (tokenBuffer[i]-'0');
      }

      if (tokenBuffer[i] != ';') 
      { 
        reportDecodingError(); 
        return; 
      }
      
      QString newValue;
      newValue.reserve(tokenBufferPos-i-2);
      for (int j = 0; j < tokenBufferPos-i-2; j++)
        newValue[j] = tokenBuffer[i+1+j];
     
      _pendingTitleUpdates[attributeToChange] = newValue;
      _titleUpdateTimer->start(20);
    }

前半部分是提取 \033 和 ';' 中间的数字,然后把剩下的字串放到 _pendingTitleUpdates 里给别人处理。这里作者启动了一个 20ms 的计时器,计时器到时 间之后才会更新。这可以压缩更新的次数,避免频繁更新吧。计时器的 callback 就在下 面

void Vt102Emulation::updateTitle()
    {
        QListIterator<int> iter( _pendingTitleUpdates.keys() );
        while (iter.hasNext()) {
            int arg = iter.next();
            emit titleChanged( arg , _pendingTitleUpdates[arg] );    
        }
        _pendingTitleUpdates.clear();    
    }

简单的函数,它又发出了 titleChanged 这个信号。这个信号是在哪处理的呢?(中间 省略N多 git grep 之类的过程)是在 src/Session.cpp 的 Session::setUserTitle

void Session::setUserTitle( int what, const QString &caption )
    {
    ....
        if (what == ProfileChange) 
        {
            emit profileChangeCommandReceived(caption);
            return;
        }
    ....
    }

这个 ProfileChange 就等于我们所要的 50(src/Session.h, 341 行) ……再追踪 profileChangeCommandReceived 这个信号。(别急,快完啦)处理它的是 src/SessionManager.cpp 里的 SessionManager::sessionProfileCommandReceived

void SessionManager::sessionProfileCommandReceived(const QString& text)
    {
        // FIXME: This is inefficient, it creates a new profile instance for
        // each set of changes applied.  Instead a new profile should be created
        // only the first time changes are applied to a session

        Session* session = qobject_cast<Session*>(sender());
        Q_ASSERT( session );

        ProfileCommandParser parser;
        QHash<Profile::Property,QVariant> changes = parser.parse(text);

        Profile::Ptr newProfile = Profile::Ptr(new Profile(_sessionProfiles[session]));
        
        QHashIterator<Profile::Property,QVariant> iter(changes);
        while ( iter.hasNext() )
        {
            iter.next();
            newProfile->setProperty(iter.key(),iter.value());
        } 

        _sessionProfiles[session] = newProfile;
        applyProfile(newProfile,true);
        emit sessionUpdated(session);
    }

还是一个挂着 FIXME 的函数呢…… 不过逻辑还是比较简单的,基本上就是把当前的Profile 作为父 Profile 新建一个 Profile。然后根据命令的内容修改 Profile 的属性。也就是说 ,理论上讲,只要是 Profile 里可以改的,就可以通过 \<ESC>50;x1=y1;x2=y2\x7 来 修改。后来我又把 vim 里的 t_{S,E}I 修改成

if $TERM =~ 'xterm'
        let &t_SI = "\<Esc>]50;CursorShape=1;BlinkingCursorEnabled=true\x7"
        let &t_EI = "\<Esc>]50;CursorShape=0;BlinkingCursorEnabled=false\x7"
endif

然后在插入模式下,光标果然编程一闪一闪的竖线了。哈哈。不过需要小注意的是,用这个 方式修改的 Profile 是临时的,不会保存,新建的标签也不会继承这个 Profile。

现在就拨云见日,回顾一下整个调用过程吧

Emulation::receiveData
    ||
    \/
Vt102Emulation::receiveChar
    || tokenize/process token
    \/
Vt102Emulation::processWindowAttributeChange
    || 提取 \<ESC>] 后面的 code 和 cmd
    \/ 20ms 延迟,聚集变更
Vt102Emulation::updateTitle
    || emit titleChanged(code, cmd)
    \/
Session::setUserTitle(int, const QString &)
    || emit profileChangeCommandReceived(cmd)
    \/
SessionManager::sessionProfileCommandReceived(const QString)
{
    ...
    Profile::Ptr newProfile = Profile::Ptr(new Profile(_sessionProfiles[session]));
    ...
    newProfile->setProperty
    ...
    _sessionProfiles[session] = newProfile;
    applyProfile(newProfile,true);
    emit sessionUpdated(session);
}

回头来看,一步一步的到还挺清晰的。

多谢各位能够读到最后。作为奖励,贴一个解决上面 FIXME 的补丁吧,哈哈

commit 5fb452e51ac1a9d18952fdd26f8bfa55438aedf3
Author: Grissiom <chaos.proton@gmail.com>
Date:   Thu Sep 1 01:17:24 2011 +0800

    use a static _sessionRuntimeProfiles to store runtime profiles

diff --git a/src/SessionManager.cpp b/src/SessionManager.cpp
index 028b76f..697589c 100644
--- a/src/SessionManager.cpp
+++ b/src/SessionManager.cpp
@@ -758,9 +758,7 @@ Profile::Ptr SessionManager::findByShortcut(const QKeySequence& shortcut)

 void SessionManager::sessionProfileCommandReceived(const QString& text)
 {
-    // FIXME: This is inefficient, it creates a new profile instance for
-    // each set of changes applied.  Instead a new profile should be created
-    // only the first time changes are applied to a session
+    static QHash<Session*,Profile::Ptr> _sessionRuntimeProfiles;

     Session* session = qobject_cast<Session*>(sender());
     Q_ASSERT( session );
@@ -768,14 +766,23 @@ void SessionManager::sessionProfileCommandReceived(const QString& text)
     ProfileCommandParser parser;
     QHash<Profile::Property,QVariant> changes = parser.parse(text);

-    Profile::Ptr newProfile = Profile::Ptr(new Profile(_sessionProfiles[session]));
-
+    Profile::Ptr newProfile;
+    if (!_sessionRuntimeProfiles.contains(session))
+    {
+        newProfile = new Profile(_sessionProfiles[session]);
+        _sessionRuntimeProfiles.insert(session,newProfile);
+    }
+    else
+    {
+        newProfile = _sessionRuntimeProfiles[session];
+    }
+
     QHashIterator<Profile::Property,QVariant> iter(changes);
     while ( iter.hasNext() )
     {
         iter.next();
         newProfile->setProperty(iter.key(),iter.value());
-    }
+    }

     _sessionProfiles[session] = newProfile;
     applyProfile(newProfile,true);

C++ 代码看的比较少,Konsoel 的代码也是刚看。有什么不对的地方还请指教~;P

2010年12月13日星期一

两件难事

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议




1,idea is cheap, show me the logic

这个小标题是最近发过的一个状态。 [1] 它是说在接收观点的时候,对观点的论证比观点 本身重要。(所有意义以中文为准,英文有所偏差,见谅……)而且竟然得到了片聪大牛的回复 ,虽然我用耍赖皮的方法回复了聪……其实我那个状态本身就没有show the logic ;-P


发这个状态的导火索是一篇好友的日志 [2] 。那篇日志的观点不去评价,但是我看的时候 实在没看明白原文两个部分之间的推理关系,直到后来好友给我用四个回复给我解释了一遍 我才明白。这个时候我突然发现,观点并不那么重要,重要的是支撑观点的论据以及从论据 推导观点的逻辑。


现在是信息时代了,每天上网都会接触各式各样的观点,想法。最近看文章有个习惯,就是 总要看看作者是用什么来论述他的观点的,怎么样用论据来论述的。(当然受限于本人低下 的语文水平,这个目标常常达到不了……)遇到那种只讲观点不讲理由的文章,一概略过。比 如以前无聊的时候看过咸郎平的一本书,书里充斥着“我预料它是这样,几年之后果然就验 证了。”、“我说XX是那样,它就是那样”的话语,然而知识性的东西很少。这就让人读着很 不爽。 [3] 就好像如果我说“买黄金吧,保赚!”,但是任何一个理性的人都不会单纯因为 我这一句话而投资黄金一样。一个只有观点而没有靠谱论据的文章只能证明作者当时持有那 种观点,其他的什么都说明不了,甚至没法证明作者不是忽悠人的。


2,idea is cheap, show me the implementation

这个小标题是说,实现想法比想法本身重要的多。这个是晚上和嘉哥聊天的时候忽然想到的 。


可能有的人要问,为什么想法不重要呢?现在不是求创新嘛?创新就是要有新的 idea,那 么idea怎么就不重要了呢?我觉得,一个人从早晨起来到晚上睡下,睁眼看着这花花绿绿的 世界,难免会有 idea 出来。一个人要是说他什么都没想过,从来都没有过灵感,我觉得真 不可能。但是,生活为什么还是这么平淡呢?很大一部分是因为我们没有去实现自己的想法 。大的例子就不举了,一个小例子,比如,“去K歌”这个想法很多人肯定都有过。那么这个 想法和定地方,定时间再动员大家一起去这个过程比起来哪个更难呢?显然是后者。一个没 有被实现的想法就好像一个被父母抛弃到戈壁的婴儿一样,总是会夭折的。当然一个人的想 法肯定会有很多很多,不可能每个都实现。不过或许也可以想想,不知不觉中有多少有用的 想法就这样被抛弃了呢?……


3,cheapie is cheap, show me the valuable

其实上面两条说得都是废话——接收观点的时候观点不如论证重要,想出了观点(想法)之后观 点不如实现重要——不管观点是别人给你的还是自己“凭空”想出来的,既然已经“有”了,就自 然没有那些还没有(或者不是那么明显)的东西重要啊…… 日志写到这就有一种要死的感觉, 费劲吧啦的原来说的都是废话……


忽然想起笑来老师曾经推荐的李宗盛的歌《你像个孩子似的》了 [4] ,以此为结尾吧:


……
工作是容易的 赚钱是困难的
恋爱是容易的 成家是困难的
相爱是容易的 相处是困难的
决定是容易的 可是等待是困难的
……

[1]这个句型只是从 Linus 早在2000年就说过的话借过来的: http://lkml.org/lkml/2000/8/25/132
[2]http://blog.renren.com/blog/229147260/504805782?fromfriendblog
[3]后来有一次无聊的时候拿了他的另一本书看,貌似好些了……
[4]http://www.lixiaolai.com/index.php/archives/1525.html

P.S. 正如每个定理都有它的局限性一样,这里说的两个观点也有自己的局限性。不排除那 些极其牛的,极其天才的,神来之笔似的观点因为难以获得而显得珍贵。

2010年6月4日星期五

第一次面试

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。




  1. 平时对细节的注意还是不够。很多细节的问题都没有答好。会用未必代表懂啊!有的问 题是看过,但是感觉太琐碎,所以没用心记,结果面试杯具了。勿以事小而不学啊……
  2. 小概念区分得还是不清楚。尤其是答 sed 的时候把通配符 * 和正则表达式里的 * 搞混了,场面极其狼狈…… 不过最后的那个 char 符号问题答得还是比较好的 。其实那个问题我也只是平时一不小心才注意到的……
  3. 介绍自己的项目的时候还是急于显示自己的东西了,以至于一开始把面试人说得云里雾 里…… ;( 下回还是要慢慢来……

2010年4月30日星期五

北航毕设论文 latex 模板

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。

原来的源码是在北航的 ftp 上找到的,从源代码里看貌似是一个叫 WangNan 的大牛在 2006 年 3 月份写的。由于对于中文来说用 XeLateX 比较方便,而原来的模板又没有针对它的选项,所以我对原模板略作修改(改动的地方占了不到原文件的 1%),使他能更好的支持 xelatex。源码包里有一个小例子。在 texlive-20091107(under linux) 下可以编译通过。不过需要略微注意的还是字体,adobefonts 选项会选择 adobe 的那一套中文字,winfonts 会选择 Sim 那一套。linux 下面安装很简单,找到字体文件仍到 ~/.fonts 里,应该就可以了;win 下的应该也类似。


已知问题:

  1. 原模板里有一个 \CJKtilde 命令,但是他在 xeCJK 里已经没有了。因为没有找到对应的命令,所以就简单的把它注释掉了。
  2. 原模板里的 BUAAbibsty.bst 貌似有问题,在我这里一直编译不过…… 我又不知道怎么样编辑 bst 文件,所以也跳过它了。
如果有大牛能解决以上问题的,欢迎联系我。


源码包在这里。如果您在下载过程中遭遇任何问题,那不是我们的错。您遭遇了伟大的“防火墙”。您可以先爆句粗口,再平静一下心情,看看别的“健康的”网站(比如人民网之流)。过几分钟之后把上面连接里的 http 该成 https,再试试。实在不行,可以电邮我。


感谢国家。感谢原作者,模板版权归原作者所有。感谢北航开源软件俱乐部,想了半天,还是觉得把文件放到这里来共享比较合适。

2010年2月10日星期三

开了一个技术博客

在这里: http://blog.csdn.net/grissiom (好不容易在今天完成了第一篇文章……)以后这里就放一些关于生活啊之类的碎碎念吧~那里会放一些编程啊,硬件啊之类的东西。我尽量会不转帖的。有了分享,还用转贴么?把类别分开也能方便大家看。(问题是,看的人有几个呢?嘿嘿……)

最后,无论在哪里,都欢迎大家拍砖,人气低的时候欢迎灌水~;)

2010年1月30日星期六

又是一年考期时

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。

=========================================

其实这是很久以前写的东西。久到大三上的那个考期,觉得郁闷,于是就写了。但是以后的考期就还是那么过的,没有什么变化…… 以后大概也就不会有考期这个东西了,把它贴出来作为纪念吧……

=========================================


又是一年考期时


其实只是上了大学才知道“考期”这个名词,其实只是过完了大一上才知道大学里原来还有 一个“考期”的时间专门留给复习 —— 准备最后的期末考试。


或许考试这个“龙门”就是留给有准备的人跳的。不过大学以前,印象里没有留过时间专门 复习期末考试的 —— 高考除外,其性质与期末考试不同,暂不属于讨论范畴。基本上是讲 完考,考完撤,上午一门下午一门,连考三天还不费劲。


上了大学,风水变了。有孩子喊,14 天考 10 门,能熬出来都成神了。不禁莞儿。想想, 我也是这么一路抱怨过来的。当年也怨过也骂过也狠过。也曾经用一晚上两三个小时把一 学期要学的东西吞进去过。当年是这样,今年,恐怕还是这样。


“大学”这两个字或许真的有魔力。进来之前是向往,进来之后是体味。甚至有大学生们常 挂在嘴边的“大学生活”这个词来凸显生活与以前别处的不同。不过显然没有“大学学习”这 个词。不过学习确实也是不一样了。以前不用专门抽时间来复习的,现在需 要腾一个月时 间了。以前上午考一门下午考一门不皱眉头的,现在今天考一门明天考一门就要抱怨了。


我不是旁观者,我也抱怨,甚至愤恨。


可是还是要思考为什么,为什么考试密集了会抱怨,为什么要有考期。


可能是知识太多,太复杂。其实我觉得,刚来时的传言“讲一、练二、考三”,平心而论, 再夸张一点,其实是“讲三、练二、考一”。基本上老师都是“不为难”,考的肯定是讲的子 集。理论上说,上课听,记住了,考试过是没问题的。老师说“上课听讲,课下消化”,没 有听说过“上课听讲,考期消化”的。从这一点来说,考期并无必要。


没有了考期,也就无从抱怨考期安排不合理了,该抱怨没有考期了。以前还有机会过,甚 至可以拿高分,现在连机会都没有了,这怎么能行呢?


其实是抱怨错了地方。如前所述,如果功夫下在平时,期末想过很容易。可是“平时”是个 隐性的时间,“考期”是个显形的时间。人们容易注意显性而忽略隐性的东西。比如大地震 ,举国关注,可以国内关注吸烟导致死亡的人却很少。其实,每年吸烟至死 500 万人,比 大地震死亡人数要多得多。美国的伊战在 08 年的时候已经死掉 4000 多人了。不过大部 分人不是在进攻的时候死掉的,而是在漫长的占领期内一点一点被各种事件杀掉的。如果 在第一波进攻内就死掉 4000人,估计它也就顶不住国内的压力要撤军了。可是现在,有谁 在关注么?同样是死人,“大家一起死”和“一个一个慢慢死”效果就很不同。同样是学习,“ 一个学期里 学习”和“一个考期里学习”所引起的关注也就不一样 —— 更何况考期还挂一个“ 考”字呢?


这也是一种懒惰。“枪打出头鸟”,“抓典型”,有意而为之的时候是一种手段、策略;无意 而为之的时候是一种祸患:只抓住了部分而没有把握整体;只听到了聒噪的“一小撮”而没 有看到“沉默的大多数”。有人可能会拿 80/20 原则来反驳。那么我会说:“ 什么样的人能 用 20% 的时间学习 80% 的知识并且把它们掌握牢固?”


我不是,我还是要用剩下的 20% 时间吞 80% 的知识,只期望于考试考过,不奢望于牢固 掌握。悲哀啊!莫过于此。


恐惧源于不知,待到明了之后,也就无所谓惧怕了。


立此存照

2009年12月11日星期五

Some Twist on the Blog

Creative Commons License
本作品采用知识共享署名-非商业性使用 2.5 中国大陆许可协议进行许可。

I spent some time on twist my blog(grissiom.blogspot.com) today. The major changes are direct RSS feed to feedburner( http://feeds.feedburner.com/Grissiom ) and add a CC icon on the blog. I choose NOT allow commercial uses of your work and Allow modifications of your work(not require as long as others share alike). So the articles on this blog will be covered by that license. Take care of this.

Also, I found a script named rst2wp.py from Using ReStructured Text with WordPress which is wonderful work. I adapted it to meet my blogspot's need. The script can be found on my MLES repository along with my other Make Life Easier Scripts ;-)

Hope you could enjoy them :-)

2009年12月10日星期四

Extract Audio to Ogg with mencoder and oggenc

If you got a video of a though-provoking speech, you may want to convert it to a audio file which could copy into your mp3 player and be with you all the time. You can listen to it without boot up the computers. In some situations listen is much easier than seeing.

mp3 is one of the choice of the audio file formats. But for patent reason, my distribution doesn't ship lame. And I know there is ogg format [Ref1] which is more open and free. So I decided to encode all the audio into ogg format.

mencoder is part of mplayer which is very very powerful multi-media player. With mencoder/mplayer, you can play nearly all kind of video/audio files. We only care about the audio here. Let's start to work!

Basicly we need to extract the audio from the multi-media stream first:

mencoder video.mp4 -of rawaudio -ovc copy -oac pcm -o audio.pcm

-of rawaudio tells the mencoder to output audio stream only. Although the man page told me the -of option is still BETA but it works like a charm here. -ovc copy tells mencoder not to decode the video stream, which would consume less resources on your computer. -oac pcm tells mencoder to encode the audio to uncompressed PCM. Now, we can use ogg --raw audio.pcm to convert the raw pcm file to an ogg file.

But it's far from perfect. One big problem is this way of converting will last long time. When mencoder is extracting, oggenc doesn't convert simultaneously. So the time will be doubled. The other problem is you have to provide a relatively large temperary file to contain the pcm data. The method that could kill two birds with one stone is using a pipe. So the second version will be:

mencoder video.mp4 -of rawaudio -ovc copy -oac pcm -o - | \
    oggenc --raw - -o audio.ogg                            

But this version have bugs too. mencoder will print out something like:

MEncoder r29789-4.3.3 (C) 2000-2009 MPlayer Team
success: format: 0  data: 0x0 - 0x34468059      
libavformat file format detected.               
[lavf] Audio stream found,  -aid 0              
[lavf] Video stream found,  -vid 1              
VIDEO:  [H264]  1280x720  24bpp  29.970 fps    0.0 kbps ( 0.0 kbyte/s)
[V] filefmt:44  fourcc:0x34363248  size:1280x720  fps:29.970  ftime:=0.0334
========================================================================== 
Opening audio decoder: [faad] AAC (MPEG2/4 Advanced Audio Coding)          
FAAD: compressed input bitrate missing,  assuming 128kbit/s!               
AUDIO: 44100 Hz,  2 ch,  s16le,  128.0 kbit/9.07% (ratio: 16000->176400)
Selected audio codec: [faad] afm: faad (FAAD AAC (MPEG-2/MPEG-4 Audio))    
========================================================================== 
Ignoring video stream!                                                     
videocodec: framecopy (1280x720 24bpp fourcc=34363248)                     
Pos:   0.7s     22f ( 0%)  0.00fps Trem:   0min 141mb  A-V:0.068 [0:1411]  
Skipping frame!                                                            

which will corrupt the pcm stream to stdout and cause a corrupted ogg file eventually. In man page, it said -quiet will Make console output less verbose and -really-quiet will Display even less output and status messages than with -quiet but there is no guarantee that There won't be any message to stdout. That's unbearable for our condition.

So I come up with the idea that shell can redirect file-descriptor 3-10 to stdout, stdin or stderr. So we can write the pcm stream to file descriptor 3, and redirect the fd 3 to stdout. Then, redirect the origin stdout where the messages going to /dev/null. But how to tell mencoder write the pcm stream to fd 3? The trick is simple. Actually, fd n is /proc/self/fd/n for the process. What a great design of Linux system! Now, the pipe should be clean. Here is the final version:

mencoder video.mp4 -of rawaudio -ovc copy -oac pcm \
    -o /proc/self/fd/3 3>&1 1>/dev/null | \
    oggenc --raw - -o audio.ogg

There are two things you should care:

  1. You must redirect fd 3 when dumping things into it, otherwise it will break.
  2. The order in redirection is important. 3>&1 means redirect 3 to what 1 currently is. If you 1>/dev/null and then 3>&1, fd 3 will be redirected to /dev/null as well.

Now, you can extract the audio to ogg file flawlessly. Big thanks to http://www.commandlinefu.com where tell me the usage of mencoder.

[Ref1]http://www.vorbis.com/

2009年12月8日星期二

Gappproxy plus pac is your friend to break the wall

Nearly everyone on the earth know that China has a Great Fire Wall to monitor and control connections abroad. It block some web pages that should not be seen by teenagers or have politic issues. But it blocks some useful webs too. For example, *.blogspot.com where holds many technical blogs, http://chrome.google.com/extensions where you can extent you Chromium... It's unbearable for someone(like me, although I tolerated it for quite a long time) got "Connection Reset" now and then. So I decided and managed to get through it with Gappproxy.

Why Gappproxy?

It based on GAE(Google App Engine), which is free(within quotas) and powerful and 7x24 on line. Someone may found GAE has been blocked too. I will talk on it later. There are many ways to break walls such as buy a VPS abroad and use ssh tunnel through it or use VPN. But neither I don't have the money and time to buy a VPS nor many free VPN sites are not accessible, I choose Gappproxy as my way to embrace the free world.

There are some tutorials that could teach you how to setup a Gappproxy for yourself, search it on baidu.com will give you many results. (I nearly never search sensitive topic on Google because it would bring it into trouble) So I won't reinvent the wheel. One thing I want to mention is the Gappproxy main site was blocked too(not surprisingly). So you could not retrieve the source files unless you pass the wall... Here is a link for the tarballs and you may find it accessible behind the wall:

http://gappproxy.googlecode.com/files/gappproxy-1.0.0beta.tar.gz

In this tarball, fetchserver folder have the files that should be deployed to GAE, which is equivalent to the fetchserver tarball in most tutorials; in localproxy folder there is the client need to be run on your box. Don't forget to adjust them before you deploy/run :-)

After it was fully setup, set your browser's proxy to localhost:8000. I prefer to use a pac file to do the trick.(See below) After got it run successfully, you may need to update your Gappproxy to the latest version.

Access to GAE

Actually it's quite easy to do the trick. Following this link http://ftofficer.spaces.live.com/blog/cns!423B72634E2F6B7E!1073.entry (which is also blocked, but you can search "appspot www.google.cn" in baidu.com. It will be the third entry. Take snapshot with baidu you can know what he/she is saying about, in Chinese), you can edit your /etc/hosts to let your appspot point to a www.google.cn's IP. Now your GAE will be accessible. I hope GFW won't block www.google.cn ;-)

Use a pac file to setup proxy for your web browser

The last blog I mentioned above have taught me how to use a pac file to set up proxy for web browser. Why use pac file?

  1. It's plain text file with JavaScript syntax. So it will be editable with any of your favorite text editor. I know nothing about JavaScript but a pac file is rather easy to write and understand and thus, easy to extend.
  2. It's flexible and powerful. You can set different proxies for different urls or hosts. You can even tell the browser to connect to the web directly for some urls.
  3. It's browser-independent. It's not a fancy Firefox plugin which could not run on Chromium. It's a standard which is supported by most of the browsers, Firefox, Chromium, Opera... Maybe if you find a browser which does not support it, you should not use that browser ;-) (I haven't tested it in IE though.. ;)

There are tutorials teaching you what a pac file is and how to write a pac file [Ref1], [Ref2] , so I won't reinvent the wheel again ;)

Let me use one sentence to finish this article:

Standing on the Cloud, where is the Wall?
[Ref1]http://en.wikipedia.org/wiki/Proxy_auto-config
[Ref2]http://code.google.com/p/gappproxy/wiki/UsingProxy_StepByStep# _2._使用_PAC_文件,强大、智能

2009年4月16日星期四

Suspend slackware in DELL1501

This is not true! It seems this is a kernel regression. I will post more info after the problem is identified!

Many users say that a Linux box should be shutdown as less time as possible. Because system will buffer the disk for you so the second-start-up time of an app will be much shorter. The longer time you run, the more quantity and more accurate buffer system will allocate, the faster your app will launch. If you shutdown you computer, all the buffer will gone. But I have to pay for my electricity charge! I want save power when I do not use my box. Unfortunately, Hibernate won't help because system will free "useless" pages to optimize load time.(I think) But Suspend is will keep the buffers and consume less energy. This is tested by other people.

But I suffered a disaster after resume from suspend. System goes totally unstable after resuming. I got something like this in dmesg:

[ 7962.125970] BUG: unable to handle kernel paging request at f76f5004
[ 7962.125984] IP: [] ext3_check_dir_entry+0x19/0x140
[ 7962.126000] *pde = 00007067 *pte = 77520002 
[ 7962.126010] Oops: 0000 [#1] SMP 
[ 7962.126017] last sysfs file: /sys/power/state
[ 7962.126024] Modules linked in: radeon drm vboxnetflt vboxdrv snd_seq_dummy snd_seq_oss snd_seq_midi_event snd_seq snd_seq_device snd_pcm_oss snd_mixer_oss ipv6 nls_cp936 vfat fat ext4 jbd2 crc16 fuse dell_laptop dcdbas b43 mac80211 joydev ricoh_mmc sdhci_pci cfg80211 led_class shpchp ohci_hcd sg input_polldev ati_agp agpgart video output
[ 7962.126075] 
[ 7962.126082] Pid: 6509, comm: pm-powersave Not tainted (2.6.29.1-slk-based-2 #4) Inspiron 1501 
[ 7962.126089] EIP: 0060:[] EFLAGS: 00010292 CPU: 1
[ 7962.126097] EIP is at ext3_check_dir_entry+0x19/0x140
[ 7962.126102] EAX: c0463684 EBX: f76f5000 ECX: f76f5000 EDX: f6c5a478
[ 7962.126108] ESI: f6846a00 EDI: 00002000 EBP: f6c5a478 ESP: f6785cec
[ 7962.126113]  DS: 007b ES: 007b FS: 00d8 GS: 0033 SS: 0068
[ 7962.126120] Process pm-powersave (pid: 6509, ti=f6784000 task=f7031090 task.ti=f6784000)
[ 7962.126126] Stack:
[ 7962.126129]  f7781000 d9e5ad68 f6c35040 c01e6c4d 00000000 00000000 f6785dec f6785dec
[ 7962.126141]  f6785e80 c0463684 00000000 f76f5000 f6846a00 00002000 f6e246c0 c01e86f3
[ 7962.126153]  f6e246c0 00002000 f66c2cc0 f6ba1400 00000000 c01e5a07 0000000b d9c5fbb8
[ 7962.126166] Call Trace:
[ 7962.126171]  [] dx_probe+0x8d/0x350
[ 7962.126180]  [] ext3_find_entry+0x403/0x650
[ 7962.126189]  [] ext3_truncate+0x317/0x8e0
[ 7962.126197]  [] __ext3_get_inode_loc+0xda/0x2f0
[ 7962.126205]  [] __wake_up+0x3e/0x60
[ 7962.126215]  [] ext3_lookup+0x46/0xf0
[ 7962.126222]  [] d_alloc+0xf7/0x170
[ 7962.126233]  [] do_lookup+0x1ba/0x1e0
[ 7962.126240]  [] __link_path_walk+0x675/0xd90
[ 7962.126247]  [] generic_file_aio_read+0x2fa/0x6d0
[ 7962.126257]  [] do_page_fault+0x28c/0x6a0
[ 7962.126266]  [] path_walk+0x54/0xb0
[ 7962.126273]  [] do_path_lookup+0xb0/0x160
[ 7962.126280]  [] getname+0x96/0xd0
[ 7962.126287]  [] user_path_at+0x5a/0x90
[ 7962.126295]  [] vfs_stat_fd+0x22/0x60
[ 7962.126305]  [] sys_stat64+0xf/0x30
[ 7962.126313]  [] syscall_call+0x7/0xb
[ 7962.126321] Code: ff ff 83 c4 0c 5b c3 90 90 90 90 90 90 90 90 90 90 90 83 ec 3c 89 6c 24 38 89 5c 24 2c 89 d5 89 74 24 30 89 7c 24 34 89 44 24 24 <0f> b7 41 04 3d ff ff 00 00 74 74 83 f8 0b 89 c6 0f 8f c1 00 00 
[ 7962.126379] EIP: [] ext3_check_dir_entry+0x19/0x140 SS:ESP 0068:f6785cec
[ 7962.126390] ---[ end trace a30eca9c02841218 ]---
Some process has been terminated for some reason that I don't know. Even syslogd at worst case! Firefox won't launch, su don't work, if you click icons on panel, plasma will freeze...

After some exploring, I see these lines lay in /usr/doc/pm-utils-1.2.5/README.SLACKWARE

==============================================================================

KNOWN ISSUES

****  If you encounter either of these, mail rworkman@slackware.com ****

If your alsa drivers don't correctly save and restore state across a sleep /
resume cycle (due to a buggy driver), then you will need to add the drivers
to a custom file named /etc/pm/config.d/defaults (create the file if it does
not exist already) in a variable named "SUSPEND_MODULES" - see the file at
/usr/lib/pm-utils/defaults for proper format.

The /usr/lib/pm-utils/sleep.d/90clock does not run by default.  It added
over a second to suspend, and the vast majority of hardware does not need it
to keep the clocks in sync.  If you need this hook, you can set the
NEED_CLOCK_SYNC environment variable in a custom /etc/pm/config.d/defaults
file.

==============================================================================
So I tried to set NEED_CLOCK_SYNC=1 in /etc/pm/config.d/defaults . Suspend, go to a sleep, Resume. And everything works well! Angles sing, light suddenly fills the dorm ;)

What /usr/lib/pm-utils/sleep.d/90clock actually done is here:

#!/bin/sh
# Synchronize system time with hardware time.
# TODO: Do modern kernels handle this correctly?  If so, we should detect that
#       and skip this hook.

. "${PM_FUNCTIONS}"

suspend_clock()
{
        /sbin/hwclock --systohc >/dev/null 2>&1 0<&1
}

resume_clock()
{
        /sbin/hwclock --hctosys >/dev/null 2>&1 0<&1
}

[ "$NEED_CLOCK_SYNC" ] || exit $NA

case "$1" in
        hibernate|suspend) suspend_clock ;;
        thaw|resume) resume_clock ;;
        *) exit $NA ;;
esac


A LQ post that I created to discuss this issue is here

2009年3月31日星期二

终于搞定 bzr 的 launchpad 帐户了……

纵使有一千个理由骂 bzr(而且确实有一千个理由),可还是要用它,入乡随俗么……

终于把 bzr 上的 launchpad 帐户搞定了。方法是在 ~/.bash_profile 里加一句

 export CURL_CA_BUNDLE=/usr/share/apps/kssl/ca-bundle.crt
,那个 ca-bundle.crt 是 "grep ca-bundle.crt /var/log/packages*" 找到的,竟然是 kde 包里面的一个东西 Qrz... 而且要重新 clone 上游才能有 commit 权限……

干嘛不用 git 呢?忽然想起前段时间看到的一句话:"yet another f*cking wheel -- but a better one",但是我觉得 bzr 就是"yet another f*cking wheel -- but a worse one"

2009年3月24日星期二

近况

  1. 先是帮东子装上了 Slackware,装完了之后发现 slack 确实有点不适合新手,一开始不进图形界面就是一个比较大的台阶,系统的配置都只能通过文本来解决就会让很多从 win 下转来的孩子们不知所措…… 不过还好,折腾了一下午终于大概配置好了。

    不过在配置鼠标滚轮的时候发现一个问题,安装网上说的在 InputDevice 里加入:

     Option      "ZAxisMapping" "4 5"
    还是不够,还需要把 Option "Protocol" 改成 "explorerps/2" 才行…… 不知大家有没有遇到相同的问题……

    Update: 看了 vvoody 的回复,发现改成 "IMPS/2" 也是可以的,后来自己好奇,改成了"auto",结果 xorg 自己探测的结果还是 "explorerps/2",好吧,还是信任 xorg 吧~

  2. 最近开始看 Babiloo的源码了~主要是因为1)觉得不看代码还是不行2)那个东西是用 PyQt4 写的而且是个字典程序,还可以就着学点英语。不过看的时候就觉得不爽,首先是代码是用 bzr 托管在 launchpad.com,用惯了 git 感觉 bzr 作为一个 “分布式”版本控制工具怎么就不支持本地的分支和合并……(至少是迄今为止我还不知道怎么办,特性里面也没有说……)而且 bzr 和 launchpad 绑定的太紧了……代码缩进风格和自己的也不一样…… 不过能和作者直接联系这个优势是怎么样也替代不了的~ 当找到一个 bug 的时候可以和作者直接联系,他会给你讲一些全局上的事情,能让人受益匪浅。不管怎样,先坚持下去吧~

2009年3月2日星期一

大刀向Google Reader的头上砍去

今天在 Reader 里看到这样一篇文章:《大刀向Google Reader的头上砍去》文章幽默诙谐,读后深有感触。于是反观自己的 Reader,嗯,是该整理了。

整理的时候忽然发现 GReader 有一个十分好的功能:Trends(不清楚中文是怎么翻译的)。打开他就可以看到每个订阅的阅读率。我把低于 30% 的原则上全部退订了~一下子清闲了很多。估计以后又会有一段清闲的生活了,不过节省下来的时间去干嘛呢?……

忽然记起来以前看到过一个“定律”的,就是一个人开始的时候总是会被垃圾信息包围着,但是他又不愿意去屏蔽,因为“可能”会损失有价值的信息。但是事实是从一堆垃圾信息里能提取出有价值信息的概率很小,人们总是会得到有价值信息的,但是不是通过这种“鸟枪法”。但是现在我就感觉自己的信息“确实”太闭塞了,整天两眼一摸黑,啥新闻都不知道…… 大家都是怎么样收集信息的呢?

2009年2月5日星期四

感动中国 2008 之感动我

其实一开始就觉得自己没心没肺,如果不是我妈看那个节目我也就不会搬电脑过去看了。但是既然看了,而且略微有点小感动了,那就墨迹两句吧。

看完之后我妈问我,哪个给你最大的感动?我问,你呢?她说,是那个彝族教师,因为其他人其实只是做好他们的本职工作。我觉得也是。尤其是当他说自己每月的工资只有两百块钱的时候,快不成了……其实我当时很想看看主持人是什么表情,估计她的工资是这个的百倍,身上的一件衣服就顶的上人家几个月的工资…… 能够经常上网的同学们也可以想想两百块对你来说算什么?对人家来说算什么?由此,其实中国的国情也就可见一斑了。(想说当地消费水平低的滚蛋~ 每月给你两百块钱把你扔山里19年你试试?)

其实还有一个感动的,就是神州七号的乘员组。可能是自己从小关心航空航天的事件,略微知道点其中的辛劳、危险的缘故。尤其是当舱内有火警时改变工作程序的那一段。虽然理智上感觉那样做不对,觉得要是真有火,还是先灭火为好,但是那种大无畏的勇气,祖国至上的精神,是最感动我而且我所应该学习的。

没错,本质上说他们只是完成了自己的本职工作。但是这年头,能干好自己的本职工作就比较不错了。要是还有能力,还有意志,做到像那两个彝族教师一样更好。貌似《肖申克的救赎》里有句经典台词叫“要么好好活着,要么就去死”说的就是这个事?说了半天,其实我还是属于那种“就去死”的类型,为了以后能“好好活 ”今天就先不死了,呵呵~

2009年1月14日星期三

sep.py v0.1.1 发布

咳咳~ sep.py 是我自己写的一个 python 小脚本。用来从当前目录下提取指定扩展名的文件,并且保留其目录结构~~ 我经常是先用 vvoody 的 cueconv.sh 转换下载下来的 flac啊,cue+ape啊什么的,然后在用这个脚本把转出来的东西一并提取出来,而且不会乱~;)

源代码在这里:http://github.com/grissiom/etc/raw/59d2482073b174530c27a58c8c28c8852e11d579/sep/sep.py。GPLv3 的许可证吧。代码是用 github 托管的~ 感兴趣的同学可以跟踪。非常欢迎提意见或者是 bug report。要是 bug fix 更好~ ;D

早晨发布的那个 v0.1 有问题,这个 v0.1.1 就好了~ 如果带来不便请见谅~;)

Qt4.5 will release under LGPL

消息来源。这里还有~~

2009年1月13日星期二

Burning 4GB+ file(a singal large file) into a disk

详细的讨论在这:http://www.linuxquestions.org/questions/slackware-14/k3b-says-your-mkisofs-doesnt-support-large-filesetc-696073/。

症状是K3b说“Used version of mkisofs does not have large file support.Files bigger than 2GB cannot be handled. ”于是,大文件都被丢掉了……

一开始还以为是 mkisofs 的问题,后来经人指点才知道应该选中 ISO9660 的 Level 3。查了维基百科才知道原来通过 Level 3 可以把大于4GB(或2GB)的文件分割,这样就可以刻录了。经验不敢独吞,拿出来分享~;)

2008年12月10日星期三

Slackware 12.2 is released!

Hello all slackers! I'm happy to see that Slackware 12.2 was released in Tue Dec 9 00:00:23 CST 2008 ! As said in the official announcement, it's a must-have upgrade for any Slackware user.So happy updating if you didn't keep track with the -current branch. Here is the announcement in ChangeLog:
===========================================================
Slackware 12.2 is released as -stable. Thanks as always to everyone who helped make this a great point release in the Slackware 12.x series. Without such a great community surrounding it, Slackware could not possibly be as stable and reliable as it is. Thanks to the Slackware Crew, the users of LinuxQuestions, people contributing ideas and patches on IRC and other Slackware forums, the developers at slackbuilds.org for bringing in new technologies, and everyone else who shared insights that helped to refine this release over many months. Happy release day to you all! :-)

Also, ISOs have been sent off to the replicator now to be pressed as a 6 CD set or a single DVD. The store.slackware.com is taking pre-orders -- if you like Slackware, please consider supporting the project. We've also added new black T-shirts with the traditional Slackware logo. Check them out!

Once again, thanks to the entire Slackware community for all the help and encouragement as Slackware 12.2 progressed to release. Have fun! -P.
===========================================================

2008年10月24日星期五

两小无猜

遥想当年冬霜时,
桃花别样红。

今年才知另所属,
谈笑仍依旧。

都是两小无猜时,
岂曰恨与仇!

2008年10月12日星期日

必须要写了~

记得以前看《读者》一类的杂志,其实很无聊,不过里面的"言论"板块我挺喜欢的,就是记录一些一句话似的言论……挺能发人深思或者令人开怀大笑的。前一段时间自己也从网上收集了一些,本来想再攒攒,但是今天参加了一个经济学讲座,感觉,应该说点什么了。于是有关无关的都 dump 过来吧~欢迎大家讨论~

  1. "读得太少"往往是"写不出来"的最根本原因。计算机术语中有一个有趣的缩写"GIGO"——"Garbage in, Garbage out."——"如果输入的是垃圾,那么输出的就是垃圾"。
  2. 如果你去年买了1000美元达美航空的股票,你今年只能剩下49美元。如果是房利美,你最初的1000美元只能剩下 2块5。如果是AIG,你剩下的会不足15美元。但是,如果你一年前买了1000美元的啤酒,喝光了它们,然后把喝剩的易拉罐送去回收站,你最后能换回 214美元。根据上面的事实,目前最好的投资策略是猛喝啤酒,然后回收易拉罐。
  3. 一个底层结构设计是否成功,这个设计者是否称职,我一直觉得是有一个很简单的衡量标准的。你不需要看这个设计人用了多少NB的技术,你只需要关心,他的设计,是否给其他开发人员带来了困难。一个NB的设计,是将所有困难都集中在底层搞定,把其他开发人员换成白痴都可以工作的那种;一个SB的设计,是自己弄了半天,只是为了给其他开发人员一个长达250条的注意事项,然后很NB的说,你们按照这个手册去开发,就不会有问题了。。
  4. 人:什么?明天要考高数??
    得道:什么?下节课要考高数??
    入仙:什么?刚才考的是高数??
    成佛: 什么?昨天有考试??
    高级佛爷:高数?刚才考的不是英语??
    我寝室一哥们:高数是什么树??
    有人补充:
    佛祖:是高数还是高树玛丽亚?
  5. Two days later than initially planned, "Codename" (or more traditionally KDE 4.1.2) was released just a few minutes ago.。。。 so no new features went into KDE 4.1.2, but some nice bug fixes instead. David Faure has fixed a long-standing and annoying performance issue when deleting files using KIO, so you can now accidentally delete your home directory 32 times faster For the more faint-hearted, it will also work well with other files.
  6. Although I am a typical loner in daily life, my consciousness of belonging to the invisible community of those who strive for truth, beauty, and justice has preserved me from feeling isolated.
    Albert Einstein, 1932.
  7. 过去366天里,美国股市市值蒸发了8万亿美元。每个美国家庭能摊十几万吧。
  8. 对"钱哪儿去了"这个问题,我立即回答:蒸发了。这个回答简单并且片面,如果再加上几个字,变成"蒸发了,沉淀了,减少了",大致就圆满了。 …… 商业票据少了、银行授信少了、银行票据(如承兑汇票)少了,你说"钱"是不是实实在在地减少了?
  9. 我自己说一句:

  10. 如果那天一觉醒来发现我们国家1.8万亿的美元储备不值钱了,即,平均中国每个国民损失大概一万人民币,那么,我们还会那样的崇洋媚外么?

其实,一开始是想搞笑的,可是发现忽然笑不起来了……