search
HomeDatabaseMysql Tutorial使用 live555 直播来自 v4l2 的摄像头图像

结合前面的 采集 v4l2 视频, 使用 live555, 通过 rtsp 发布实时流. capture.h, capture.cpp, vcompress.h, vcompress.cpp 需要参考前面几片文章. 这里仅仅贴出 v4l2_x264_service.cpp [cpp] view plaincopy #includestdio.h #includestdlib.h #includeunistd

结合前面的 采集 v4l2 视频, 使用 live555, 通过 rtsp 发布实时流. capture.h, capture.cpp, vcompress.h, vcompress.cpp 需要参考前面几片文章. 这里仅仅贴出 v4l2_x264_service.cpp

[cpp] view plaincopy

  1. #include   
  2. #include   
  3. #include   
  4. #include   
  5.   
  6. #include   
  7. #include   
  8. #include   
  9.   
  10. #include   
  11. #include   
  12.   
  13. #include "capture.h"  
  14. #include "vcompress.h"  
  15.   
  16. static UsageEnvironment *_env = 0;  
  17.   
  18. #define SINK_PORT 3030  
  19.   
  20. #define VIDEO_WIDTH 320  
  21. #define VIDEO_HEIGHT 240  
  22. #define FRAME_PER_SEC 5.0  
  23.   
  24. pid_t gettid()  
  25. {  
  26.     return syscall(SYS_gettid);  
  27. }  
  28.   
  29.   
  30. // 使用 webcam + x264  
  31. class WebcamFrameSource : public FramedSource  
  32. {  
  33.     void *mp_capture, *mp_compress; // v4l2 + x264 encoder  
  34.     int m_started;  
  35.     void *mp_token;  
  36.   
  37. public:  
  38.     WebcamFrameSource (UsageEnvironment &env)  
  39.         : FramedSource(env)  
  40.     {  
  41.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  42.         mp_capture = capture_open("/dev/video0", VIDEO_WIDTH, VIDEO_HEIGHT, PIX_FMT_YUV420P);  
  43.         if (!mp_capture) {  
  44.             fprintf(stderr, "%s: open /dev/video0 err\n", __func__);  
  45.             exit(-1);  
  46.         }  
  47.   
  48.         mp_compress = vc_open(VIDEO_WIDTH, VIDEO_HEIGHT, FRAME_PER_SEC);  
  49.         if (!mp_compress) {  
  50.             fprintf(stderr, "%s: open x264 err\n", __func__);  
  51.             exit(-1);  
  52.         }  
  53.   
  54.         m_started = 0;  
  55.         mp_token = 0;  
  56.     }  
  57.   
  58.     ~WebcamFrameSource ()  
  59.     {  
  60.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  61.           
  62.         if (m_started) {  
  63.             envir().taskScheduler().unscheduleDelayedTask(mp_token);  
  64.         }  
  65.   
  66.         if (mp_compress)  
  67.             vc_close(mp_compress);  
  68.         if (mp_capture)  
  69.             capture_close(mp_capture);  
  70.     }  
  71.   
  72. protected:  
  73.     virtual void doGetNextFrame ()  
  74.     {  
  75.         if (m_started) return;  
  76.         m_started = 1;  
  77.   
  78.         // 根据 fps, 计算等待时间  
  79.         double delay = 1000.0 / FRAME_PER_SEC;  
  80.         int to_delay = delay * 1000;    // us  
  81.   
  82.         mp_token = envir().taskScheduler().scheduleDelayedTask(to_delay,  
  83.                 getNextFrame, this);  
  84.     }  

[cpp] view plaincopy

  1. virtual unsigned maxFrameSize() const        // 这个很重要, 如果不设置, 可能导致 getNextFrame() 出现 fMaxSize 小于实际编码帧的情况, 导致图像不完整  

[cpp] view plaincopy

  1. {    return 100*1024; }  

[cpp] view plaincopy

  1. private:  
  2.     static void getNextFrame (void *ptr)  
  3.     {  
  4.         ((WebcamFrameSource*)ptr)->getNextFrame1();  
  5.     }  
  6.   
  7.     void getNextFrame1 ()  
  8.     {  
  9.         // capture:  
  10.         Picture pic;  
  11.         if (capture_get_picture(mp_capture, &pic) 
  12.             fprintf(stderr, "==== %s: capture_get_picture err\n", __func__);  
  13.             m_started = 0;  
  14.             return;  
  15.         }  
  16.   
  17.         // compress  
  18.         const void *outbuf;  
  19.         int outlen;  
  20.         if (vc_compress(mp_compress, pic.data, pic.stride, &outbuf, &outlen) 
  21.             fprintf(stderr, "==== %s: vc_compress err\n", __func__);  
  22.             m_started = 0;  
  23.             return;  
  24.         }  
  25.   
  26.         int64_t pts, dts;  
  27.         int key;  
  28.         vc_get_last_frame_info(mp_compress, &key, &pts, &dts);  
  29.   
  30.         // save outbuf  
  31.         gettimeofday(&fPresentationTime, 0);  
  32.         fFrameSize = outlen;  
  33.         if (fFrameSize > fMaxSize) {  
  34.             fNumTruncatedBytes = fFrameSize - fMaxSize;  
  35.             fFrameSize = fMaxSize;  
  36.         }  
  37.         else {  
  38.             fNumTruncatedBytes = 0;  
  39.         }  
  40.   
  41.         memmove(fTo, outbuf, fFrameSize);  
  42.   
  43.         // notify  
  44.         afterGetting(this);  
  45.   
  46.         m_started = 0;  
  47.     }  
  48. };  
  49.   
  50. class WebcamOndemandMediaSubsession : public OnDemandServerMediaSubsession  
  51. {  
  52. public:  
  53.     static WebcamOndemandMediaSubsession *createNew (UsageEnvironment &env, FramedSource *source)  
  54.     {  
  55.         return new WebcamOndemandMediaSubsession(env, source);  
  56.     }  
  57.   
  58. protected:  
  59.     WebcamOndemandMediaSubsession (UsageEnvironment &env, FramedSource *source)  
  60.         : OnDemandServerMediaSubsession(env, True) // reuse the first source  
  61.     {  
  62.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  63.         mp_source = source;  
  64.         mp_sdp_line = 0;  
  65.     }  
  66.   
  67.     ~WebcamOndemandMediaSubsession ()  
  68.     {  
  69.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  70.         if (mp_sdp_line) free(mp_sdp_line);  
  71.     }  
  72.   
  73. private:  
  74.     static void afterPlayingDummy (void *ptr)  
  75.     {  
  76.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  77.         // ok  
  78.         WebcamOndemandMediaSubsession *This = (WebcamOndemandMediaSubsession*)ptr;  
  79.         This->m_done = 0xff;  
  80.     }  
  81.   
  82.     static void chkForAuxSDPLine (void *ptr)  
  83.     {  
  84.         WebcamOndemandMediaSubsession *This = (WebcamOndemandMediaSubsession *)ptr;  
  85.         This->chkForAuxSDPLine1();  
  86.     }  
  87.   
  88.     void chkForAuxSDPLine1 ()  
  89.     {  
  90.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  91.         if (mp_dummy_rtpsink->auxSDPLine())  
  92.             m_done = 0xff;  
  93.         else {  
  94.             int delay = 100*1000;   // 100ms  
  95.             nextTask() = envir().taskScheduler().scheduleDelayedTask(delay,  
  96.                     chkForAuxSDPLine, this);  
  97.         }  
  98.     }  
  99.   
  100. protected:  
  101.     virtual const char *getAuxSDPLine (RTPSink *sink, FramedSource *source)  
  102.     {  
  103.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  104.         if (mp_sdp_line) return mp_sdp_line;  
  105.   
  106.         mp_dummy_rtpsink = sink;  
  107.         mp_dummy_rtpsink->startPlaying(*source, 0, 0);  
  108.         //mp_dummy_rtpsink->startPlaying(*source, afterPlayingDummy, this);  
  109.         chkForAuxSDPLine(this);  
  110.         m_done = 0;  
  111.         envir().taskScheduler().doEventLoop(&m_done);  
  112.         mp_sdp_line = strdup(mp_dummy_rtpsink->auxSDPLine());  
  113.         mp_dummy_rtpsink->stopPlaying();  
  114.   
  115.         return mp_sdp_line;  
  116.     }  
  117.   
  118.     virtual RTPSink *createNewRTPSink(Groupsock *rtpsock, unsigned char type, FramedSource *source)  
  119.     {  
  120.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  121.         return H264VideoRTPSink::createNew(envir(), rtpsock, type);  
  122.     }  
  123.   
  124.     virtual FramedSource *createNewStreamSource (unsigned sid, unsigned &bitrate)  
  125.     {  
  126.         fprintf(stderr, "[%d] %s .... calling\n", gettid(), __func__);  
  127.         bitrate = 500;  
  128.         return H264VideoStreamFramer::createNew(envir(), new WebcamFrameSource(envir()));  
  129.     }  
  130.   
  131. private:  
  132.     FramedSource *mp_source;    // 对应 WebcamFrameSource  
  133.     char *mp_sdp_line;  
  134.     RTPSink *mp_dummy_rtpsink;  
  135.     char m_done;  
  136. };  
  137.   
  138. static void test_task (void *ptr)  
  139. {  
  140.     fprintf(stderr, "test: task ....\n");  
  141.     _env->taskScheduler().scheduleDelayedTask(100000, test_task, 0);  
  142. }  
  143.   
  144. static void test (UsageEnvironment &env)  
  145. {  
  146.     fprintf(stderr, "test: begin...\n");  
  147.   
  148.     char done = 0;  
  149.     int delay = 100 * 1000;  
  150.     env.taskScheduler().scheduleDelayedTask(delay, test_task, 0);  
  151.     env.taskScheduler().doEventLoop(&done);  
  152.   
  153.     fprintf(stderr, "test: end..\n");  
  154. }  
  155.   
  156. int main (int argc, char **argv)  
  157. {  
  158.     // env  
  159.     TaskScheduler *scheduler = BasicTaskScheduler::createNew();  
  160.     _env = BasicUsageEnvironment::createNew(*scheduler);  
  161.   
  162.     // test  
  163.     //test(*_env);  
  164.   
  165.     // rtsp server  
  166.     RTSPServer *rtspServer = RTSPServer::createNew(*_env, 8554);  
  167.     if (!rtspServer) {  
  168.         fprintf(stderr, "ERR: create RTSPServer err\n");  
  169.         ::exit(-1);  
  170.     }  
  171.   
  172.     // add live stream  
  173.     do {  
  174.         WebcamFrameSource *webcam_source = 0;  
  175.   
  176.         ServerMediaSession *sms = ServerMediaSession::createNew(*_env, "webcam", 0, "Session from /dev/video0");   
  177.         sms->addSubsession(WebcamOndemandMediaSubsession::createNew(*_env, webcam_source));  
  178.         rtspServer->addServerMediaSession(sms);  
  179.   
  180.         char *url = rtspServer->rtspURL(sms);  
  181.         *_env "using url \"" "\"\n";  
  182.         delete [] url;  
  183.     } while (0);  
  184.   
  185.     // run loop  
  186.     _env->taskScheduler().doEventLoop();  
  187.   
  188.     return 1;  
  189. }  

需要 live555 + libavcodec + libswscale + libx264, client 使用 vlc, mplayer, quicktime, .....

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What are stored procedures in MySQL?What are stored procedures in MySQL?May 01, 2025 am 12:27 AM

Stored procedures are precompiled SQL statements in MySQL for improving performance and simplifying complex operations. 1. Improve performance: After the first compilation, subsequent calls do not need to be recompiled. 2. Improve security: Restrict data table access through permission control. 3. Simplify complex operations: combine multiple SQL statements to simplify application layer logic.

How does query caching work in MySQL?How does query caching work in MySQL?May 01, 2025 am 12:26 AM

The working principle of MySQL query cache is to store the results of SELECT query, and when the same query is executed again, the cached results are directly returned. 1) Query cache improves database reading performance and finds cached results through hash values. 2) Simple configuration, set query_cache_type and query_cache_size in MySQL configuration file. 3) Use the SQL_NO_CACHE keyword to disable the cache of specific queries. 4) In high-frequency update environments, query cache may cause performance bottlenecks and needs to be optimized for use through monitoring and adjustment of parameters.

What are the advantages of using MySQL over other relational databases?What are the advantages of using MySQL over other relational databases?May 01, 2025 am 12:18 AM

The reasons why MySQL is widely used in various projects include: 1. High performance and scalability, supporting multiple storage engines; 2. Easy to use and maintain, simple configuration and rich tools; 3. Rich ecosystem, attracting a large number of community and third-party tool support; 4. Cross-platform support, suitable for multiple operating systems.

How do you handle database upgrades in MySQL?How do you handle database upgrades in MySQL?Apr 30, 2025 am 12:28 AM

The steps for upgrading MySQL database include: 1. Backup the database, 2. Stop the current MySQL service, 3. Install the new version of MySQL, 4. Start the new version of MySQL service, 5. Recover the database. Compatibility issues are required during the upgrade process, and advanced tools such as PerconaToolkit can be used for testing and optimization.

What are the different backup strategies you can use for MySQL?What are the different backup strategies you can use for MySQL?Apr 30, 2025 am 12:28 AM

MySQL backup policies include logical backup, physical backup, incremental backup, replication-based backup, and cloud backup. 1. Logical backup uses mysqldump to export database structure and data, which is suitable for small databases and version migrations. 2. Physical backups are fast and comprehensive by copying data files, but require database consistency. 3. Incremental backup uses binary logging to record changes, which is suitable for large databases. 4. Replication-based backup reduces the impact on the production system by backing up from the server. 5. Cloud backups such as AmazonRDS provide automation solutions, but costs and control need to be considered. When selecting a policy, database size, downtime tolerance, recovery time, and recovery point goals should be considered.

What is MySQL clustering?What is MySQL clustering?Apr 30, 2025 am 12:28 AM

MySQLclusteringenhancesdatabaserobustnessandscalabilitybydistributingdataacrossmultiplenodes.ItusestheNDBenginefordatareplicationandfaulttolerance,ensuringhighavailability.Setupinvolvesconfiguringmanagement,data,andSQLnodes,withcarefulmonitoringandpe

How do you optimize database schema design for performance in MySQL?How do you optimize database schema design for performance in MySQL?Apr 30, 2025 am 12:27 AM

Optimizing database schema design in MySQL can improve performance through the following steps: 1. Index optimization: Create indexes on common query columns, balancing the overhead of query and inserting updates. 2. Table structure optimization: Reduce data redundancy through normalization or anti-normalization and improve access efficiency. 3. Data type selection: Use appropriate data types, such as INT instead of VARCHAR, to reduce storage space. 4. Partitioning and sub-table: For large data volumes, use partitioning and sub-table to disperse data to improve query and maintenance efficiency.

How can you optimize MySQL performance?How can you optimize MySQL performance?Apr 30, 2025 am 12:26 AM

TooptimizeMySQLperformance,followthesesteps:1)Implementproperindexingtospeedupqueries,2)UseEXPLAINtoanalyzeandoptimizequeryperformance,3)Adjustserverconfigurationsettingslikeinnodb_buffer_pool_sizeandmax_connections,4)Usepartitioningforlargetablestoi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.