X264 Encoding Suggestions

本文提供了使用x264编码器的最佳实践,包括一般提示、命令行建议、VBV编码、Blu-ray编码及QuickTime兼容性等内容。旨在帮助用户针对不同应用场景选择合适的编码参数。


Contents

[hide]

General Tips

  • Don't use x264 as a replacement for a denoising filter. Ensure that your input looks like what you want as output (ignoring the loss in quality from compression). Doing anything else causes x264 to run less efficiently.
  • If you aren't seeing 100% CPU usage while encoding, the problem may lie with your input:
    • Raw YUV input can easily be constrained by your IO system's speed. The size of a raw frame can be calculated as: width * height * bitdepth (12 for YV12) / 8 (bits -> bytes) / 1024 (bytes -> kbytes) / 1024 (kbytes -> mbytes).
    • Avisynth scripts run in a single thread. Some filters can spawn extra threads for themselves but this doesn't give huge gains.
    • ffmpeg (and therefore ffms2) is only supported as a single-threaded decoder in x264.
  • The Flash h.264 decoder (and others) didn't support weighted P-frame prediction (--weightp) until version 10.1, which still isn't widely deployed (>90%) at time of writing. Set --weightp 0 when encoding for Flash if this is still the case.
  • Apple's QuickTime Player has various decoding issues, especially related to reference frame count. See the QuickTime encoding suggestions if you want to maintain QuickTime compatibility, and you should since they make up a large portion of computer users.

Commandline Suggestions

You can divide x264 settings into three groups:

1. Those you should touch directly

Things like --bitrate, --keyint, --slices and so forth. They depend on the requirements of your decoder and thus are ignored by x264's preset system.

2. Those you should touch via the preset system

Before the preset system existed people wrote giant commandlines specifying every option by hand. There were arguments over whether --subme 9 with --me hex was better or worse than --subme 7 with --me tesa. Crazy! Do your part to bury these memories by using --preset, --tune and --profile.

3. Those you should avoid remembering exist

--qcomp, --scenecut, and so on. Settings that probably should be built-in constants now. Their use in contemporary commandlines serve no purpose other than causing pain among readers when asking for help. Seriously, people-tweaking-obscure-parameters-because-of-a-hazy-belief-it-helps, knock it off.

VBV Encoding

The VBV (Video Buffer Verifier) system in x264 is used to constrain the output bitrate so it is suitable for streaming in a bandwidth constrained environment.

The h.264 VBV model is based around the idea of a "VBV buffer" on the decoder side. As the h.264 stream is downloaded by the client it's stored in the VBV buffer. A frame must be fully downloaded into the VBV buffer before it can be decoded.

x264 has three options that control the VBV buffer:

  1. The buffer's size is specified in kbit with --vbv-bufsize,
  2. The rate at which the buffer fills is specified in kbit/sec by --vbv-maxrate,
  3. The proportion of the buffer that must be filled before playback can start is specified by --vbv-init.

When using VBV, you always need to set the first two options and should never need to set the last one.

Examples

Example 1

Scenario: Encoding a movie to a file on your hard drive to play at a later date.

Suggestion: Do not specify any VBV settings. Your hard drive has a fast enough transfer rate that there's no need to specify any VBV constraints.

Example 2

Scenario: Encoding a video that's suitable for muxing to a Blu-ray compatible file.

Suggestion: The Blu-ray specification specifies a 40 Mbit maximum data rate (for the video) and a 30 Mbit buffer. So, specify --bluray-compat --vbv-maxrate 40000 --vbv-bufsize 30000.

Note: x264 needs more options to output a fully compliant Blu-ray file. But these options are all you need for VBV compliancy.

Example 3

Scenario: Streaming a video via Flash on a website, like Youtube.

Suggestion: You want the video to start very quickly, so there can't be more than (say) 0.5 seconds of buffering. You set a minimum connection speed requirement for viewers of 512kbit/sec. Assume that 90% of that bandwidth will be usable by your site, and that 96kbit/sec will be used by audio, which leaves 364kbit/sec for x264. So, specify --vbv-maxrate 364 --vbv-buffer 182.

Note: There are more factors than just the video VBV settings when looking at the start delay for online streaming. The above example is for a perfect world where these factors don't exist.

Blu-ray Encoding

Someone else (kierank) has done all the hard work, you can find full instructions on creating Blu-ray compliant files with x264 here. The short answer for 1080p encoding is as follows:

x264 --bluray-compat --bitrate X --preset veryslow --weightp 0 --bframes 3 --nal-hrd vbr --vbv-maxrate 40000 \
    --vbv-bufsize 30000 --level 4.1 --keyint X --b-pyramid strict --slices 4 --fake-interlaced \
    --aud --colorprim "bt709" --transfer "bt709" --colormatrix "bt709" --sar 1:1 \
    --pass 1 -o output.file input.file
x264 --bluray-compat  --bitrate X --preset veryslow --weightp 0 --bframes 3 --nal-hrd vbr --vbv-maxrate 40000 \
    --vbv-bufsize 30000 --level 4.1 --keyint X --b-pyramid strict --slices 4 --fake-interlaced \
    --aud --colorprim "bt709" --transfer "bt709" --colormatrix "bt709" --sar 1:1 \
    --pass 2 -o output.file input.file

Set keyint to your fps. Use a faster preset if desired. Add a --tune parameter if desired. --weightp is disabled because some hardware decoders have problems with it, not because it's mandated by the Blu-ray spec.

Encoder latency

Depending on the encoder settings you configure, x264 will keep an internal buffer of frames to improve quality. When you're just encoding a file offline this is irrelevant, but if you're working in a broadcast or streaming environment this delay can be unacceptable.

You can calculate the number of frames x264 buffer (the encoder latency) using the following pseudocode. If you use the libx264 API, see also x264_encoder_delayed_frames.

delay = 0

if b-adapt=2 and not (nopass or pass2):
    delay = MAX(bframes,3)*4
else:
    delay = bframes

if mb-tree or vbv:
     delay = MAX(delay,rc_lookahead)

if not sliced-threads:
    delay = delay + threads - 1

delay = delay + sync-lookahead

if vbv and (vfr-input or abr or pass1:
    delay = delay + 1

Reducing x264's latency is possible, but reduces quality. If you want no latency, set --tune zerolatency. If you can handle even a little latency (ie under 1 second), it is well worth tuning the options to allow this. Here is a series of steps you can follow to incrementally reduce latency. Stop when your latency is low enough:

  1. Start with defaults
  2. Kill sync-lookahead
  3. Drop rc-lookahead to no less than ~10
  4. Drop threads to a lower value (i.e. say 6 instead of 12)
  5. Use sliced threads
  6. Disable rc-lookahead
  7. Disable b-frames
  8. Now you're at --tune zerolatency

QuickTime-compatible Encoding

There is a lot of very outdated misinformation surrounding how to encode h.264 videos that play perfectly in QuickTime. For instance that "QT supports only 1 B-Frame" and "QT doesn't support pyramidal B-Frames" which are both false as of QuickTime Player 7.7. There also used to exist a qpmin/dct bug in early versions of QuickTime Player where the player couldn't deal with a low quantizer (below 4) combined 8x8 DCT Transforms; however, that has been fixed as of QuickTime Player X.

QuickTime Player X compatibility

The Apple h.264 decoder component released with the launch of QuickTime Player X is a pretty good decoder and has only one big remaining bug. However, before we go on, you might wonder about all those people that are stuck on older versions of QuickTime Player, refusing to upgrade to QTX. That is no problem at all, because the actual decoder that is used systemwide by OS X (including by QuickTime) is a separate component from the player, and will have been updated through Software Updates even though they may not have downloaded the actual player update. So, any time we refer to QuickTime Player X, assume that anyone with 10.6 Snow Leopard or higher has that bug-fixed Apple h.264 decoder component, even if they don't specifically have QTX.

There is now just a single remaining major Apple h.264 decoder flaw:

  • A high number of reference frames (15 or more, to be precise) combined with a high number of B-Frames produces blocky, distorted video output. This is an issue you will encounter with the "veryslow" preset, since it uses up to 16 reference frames.

Solution:

  • Limit the number of reference frames to any number between 1-14. Look up the acceptable number of reference frames for your desired h.264 level and video resolution and make sure never to exceed that value or 14, whichever comes first. However, there is rarely any point in exceeding 5 reference frames anyway, and 4 frames is the maximum allowed for 1080p content in the most common levels, so a good choice is to simply pick 4 reference frames for all your encodes regardless of video resolution: --ref 4 (For Level 5+ encodes, you may want to refer to the level specifications and pick a higher number as long as you don't exceed 14.)

QuickTime Player 7.7 compatibility

Any operating system that has the option of installing QuickTime Player X will have the updated QTX decoder. That sadly means only OS X 10.6 Snow Leopard users and higher. So, if you want 10.5 Leopard users to be able to play your videos, you'll have to read this section as well since they are stuck on QuickTime Player 7.7. Note that the number of active Leopard users is in the 10% range and falling, so you may decide not bother. Then again, it's easy enough to add compatibility with their outdated Apple h.264 decoder at a very tiny penalty to quality, so you will probably find it worth it.

The decoder flaw:

  • A low quantizer (below 4) combined with 8x8 DCT Transforms produces garbled decode results in QuickTime Player 7.7 or earlier.

Solution:

  • Prevent the encoder from using quantizers below 4 with --qpmin 4. You will take an extremely minor quality loss, but far less than you would have if you had disabled 8x8 DCT instead.

Conclusion

Forget everything you may have read elsewhere on the internet. It is extremely outdated and hasn't been true for many years.

The simplest advice for QuickTime compatibility: Combine both solutions to get the most compatible encodes, fully playable by anyone on 10.5 Leopard or above, giving you 99% of the Mac userbase.

Just encode all your videos with --ref 4 --qpmin 4 and be safe in the knowledge that it will work for all Mac users that matter!

原文地址:http://mewiki.project357.com/wiki/X264_Encoding_Suggestions

内容概要:本文系统研究了全桥LLC谐振变换器的脉冲频率调制(PFM)控制策略,深入剖析其拓扑结构与工作原理,涵盖全桥逆变电路、谐振回路(Lr、Cr、Lm)、变压器及整流滤波电路的功能与协同机制。文章详细分析了变换器在不同开关频率下的三种工作模式(fs > fr、fs = fr、fm < fs < fr),阐明了其在感性区域实现原边零电压开通(ZVS)和副边零电流关断(ZCS)的软开关特性。重点阐述了PFM控制通过调节开关频率来改变谐振阻抗,从而稳定输出电压的基本原理,并论证了其在高效率(尤其轻载时)、低电磁干扰(EMI)和宽输入输出范围方面的显著优势。研究构建了基于Matlab/Simulink的完整仿真模型,对系统的稳态性能、动态响应(负载突变)和效率进行了全面仿真验证,结果证实PFM控制能有效实现输出电压的精确稳定,具备优良的动态响应能力和全负载范围内的高效率。最后,文章总结了PFM策略的有效性,并展望了结合自抗扰控制(ADRC)等先进算法优化控制性能及开展硬件实验验证的未来发展方向。; 适合人群:具备电力电子、自动控制或相关领域基础知识的研究生、科研人员及从事高性能电源设计的工程技术人员。; 使用场景及目标:①深入理解LLC谐振变换器的拓扑结构、工作模式划分及其软开关物理机制;②掌握PFM控制策略的设计思想、参数整定方法及其在提升电源转换效率与降低EMI中的核心应用;③为开发高效率、高可靠性的开关电源(如通信电源、服务器电源)提供理论依据、仿真建模指导与性能优化的技术参考。; 阅读建议:在阅读时应紧密结合文中给出的仿真模型框图与关键波形,重点精读工作模式分析与PFM控制原理部分,建议动手复现仿真以深刻体会频率调节对增益和效率的影响规律,并特别关注轻载效率表现,同时思考未来展望中提及的先进控制算法融合方向,以激发创新研究思路。
内容概要:本文系统介绍了基于Matlab的多架无人机编队控制与轨迹规划技术实现方案,聚焦于一致性分布式控制、多领航者架构、编队跟随控制及轨迹跟踪等核心算法的建模与仿真。通过Matlab代码实现了多无人机系统的编队形成、保持与动态调整,并融合RRT、人工势场法、粒子群优化(PSO)、Q-learning等智能算法,完成复杂环境下的路径规划与避障任务。文档还深入探讨了滑模控制、反步法、模型预测控制(MPC)等多种先进控制策略在无人机协同中的应用,展现了系统在动态干扰和不确定环境下的鲁棒性与自适应能力。配套提供的完整Matlab代码涵盖多种编队模式与控制算法对比案例,支持二次开发与性能验证。; 适合人群:具备自动控制理论基础和Matlab编程能力的科研人员、研究生及从事无人机系统开发的工程技术人员,尤其适用于研究多智能体协同控制、分布式编队与自主路径规划方向的专业人士。; 使用场景及目标:① 实现多无人机在复杂动态环境中的高效协同飞行与稳定编队;② 解决队形切换、轨迹实时优化与动态障碍物规避等关键问题;③ 为学术研究、毕业设计或实际工程项目提供可复现的算法框架与仿真平台支持; 其他说明:文中所有Matlab仿真代码可通过指定百度网盘链接下载,建议结合仿真运行深入理解算法细节,并根据具体应用场景进行参数调优与算法拓展。
import matplotlib.pyplot as plt import requests from bs4 import BeautifulSoup import json import time DEEPSEEK_API_KEY = "sk-4fdb53de50074209ab62928ae5c3fa12" DEEPSEEK_API_URL = "https://api.deepseek.com/v1/chat/completions" def analyze_sentiment(reviews_text): headers = { "Authorization": f"Bearer {DEEPSEEK_API_KEY}", "Content-Type": "application/json" } prompt = """Analyze these movie reviews and provide: 1. Overall sentiment score (0-100) 2. Top 3 positive aspects 3. Top 3 negative aspects 4. Improvement suggestions Return valid JSON format only: { "sentiment_score": 85, "positive_themes": ["acting", "cinematography", "story"], "negative_themes": ["pacing", "ending", "dialogue"], "suggestions": "Could improve pacing in the second act..." } Reviews:\n""" + reviews_text[:3000] try: response = requests.post( DEEPSEEK_API_URL, headers=headers, json={ "model": "deepseek-chat", "messages": [{"role": "user", "content": prompt}], "temperature": 0.3, "max_tokens": 1000 }, timeout=30 ) response.raise_for_status() # Extract JSON from API response result = response.json() content = result['choices'][0]['message']['content'] # Clean and parse the JSON if content.startswith('```json'): content = content[7:-3] # Remove markdown code block return json.loads(content.strip()) except Exception as e: print(f"API Error: {str(e)}") return { "sentiment_score": 50, "positive_themes": ["Analysis failed"] * 3, "negative_themes": ["Analysis failed"] * 3, "suggestions": "Could not analyze reviews" } def generate_report(reviews_data, analysis_result): """Generate analysis report (English only)""" # Convert analysis_result from string to dict if needed if isinstance(analysis_result, str): try: analysis_result = json.loads(analysis_result) except: analysis_result = { "sentiment_score": 50, "positive_themes": ["None"] * 3, "negative_themes": ["None"] * 3, "suggestions": "Analysis failed" } # Sentiment score visualization plt.figure(figsize=(8, 4)) bars = plt.bar(['Sentiment Score'], [analysis_result.get('sentiment_score', 0)], color=['#4CAF50' if analysis_result.get('sentiment_score', 0) > 50 else '#F44336']) # Add value labels for bar in bars: height = bar.get_height() plt.text(bar.get_x() + bar.get_width() / 2., height, f'{height:.1f}', ha='center', va='bottom') plt.ylim(0, 100) plt.title('Sentiment Analysis Result') plt.ylabel('Score (0-100)') plt.savefig('sentiment_score.png', bbox_inches='tight', dpi=120) plt.close() # Generate text report report = f""" ===== Movie Analysis Report ===== Movie: {reviews_data[0]['movie']} Reviews Analyzed: {len(reviews_data)} -------------------------- Sentiment Score: {analysis_result.get('sentiment_score', 'N/A')}/100 -------------------------- Positive Themes: - {analysis_result.get('positive_themes', ['None'])[0]} - {analysis_result.get('positive_themes', ['None'])[1]} - {analysis_result.get('positive_themes', ['None'])[2]} -------------------------- Negative Themes: - {analysis_result.get('negative_themes', ['None'])[0]} - {analysis_result.get('negative_themes', ['None'])[1]} - {analysis_result.get('negative_themes', ['None'])[2]} -------------------------- Suggestions: {analysis_result.get('suggestions', 'None')} """ with open('analysis_report.txt', 'w', encoding='utf-8') as f: f.write(report) return report def fetch_douban_reviews(store_url, output_file="douban_reviews.json", min_reviews=50): headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36" } print("Fetching movie info...") main_page = requests.get(store_url, headers=headers) soup = BeautifulSoup(main_page.text, 'html.parser') store_name = soup.find('span', property='v:itemreviewed').text.strip() print(f"Movie: {store_name}") reviews_data = [] page = 0 while len(reviews_data) < min_reviews: url = f"{store_url.rstrip('/')}/comments?start={page * 20}&limit=20" print(f"Fetching page {page + 1}...") response = requests.get(url, headers=headers) soup = BeautifulSoup(response.text, 'html.parser') for comment in soup.find_all('div', class_='comment'): reviews_data.append({ 'movie': store_name, 'content': comment.find('p').text.strip() }) page += 1 time.sleep(2) with open(output_file, 'w', encoding='utf-8') as f: json.dump(reviews_data, f, ensure_ascii=False, indent=4) print("Analyzing sentiment...") reviews_text = "\n".join([r['content'] for r in reviews_data]) analysis_result = analyze_sentiment(reviews_text) report = generate_report(reviews_data, analysis_result) print(report) if __name__ == "__main__": url = input("Enter Douban movie URL: ") fetch_douban_reviews(url)帮我详细解释这个代码,当我是初学者一样
06-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值