X264 Encoding Suggestions

x264编码建议
本文提供了使用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

## 软件功能详细介绍 1. **文本片段管理**:可以添加、编辑、删除常用文本片段,方便快速调用 2. **分组管理**:支持创建多个分组,不同类型的文本片段可以分类存储 3. **热键绑定**:为每个文本片段绑定自定义热键,实现一键粘贴 4. **窗口置顶**:支持窗口置顶功能,方便在其他应用程序上直接使用 5. **自动隐藏**:可以设置自动隐藏,减少桌面占用空间 6. **数据持久化**:所有配置和文本片段会自动保存,下次启动时自动加载 ## 软件使用技巧说明 1. **快速添加文本**:在文本输入框中输入内容后,点击"添加内容"按钮即可快速添加 2. **批量管理**:可以同时编辑多个文本片段,提高管理效率 3. **热键冲突处理**:如果设置的热键与系统或其他软件冲突,会自动提示 4. **分组切换**:使用分组按钮可以快速切换不同类别的文本片段 5. **文本格式化**:支持在文本片段中使用换行符和制表符等格式 ## 软件操作方法指南 1. **启动软件**:双击"大飞哥软件自习室——快捷粘贴工具.exe"文件即可启动 2. **添加文本片段**: - 在主界面的文本输入框中输入要保存的内容 - 点击"添加内容"按钮 - 在弹出的对话框中设置热键和分组 - 点击"确定"保存 3. **使用热键粘贴**: - 确保软件处于运行状态 - 在需要粘贴的位置按下设置的热键 - 文本片段会自动粘贴到当前位置 4. **编辑文本片段**: - 选中要编辑的文本片段 - 点击"编辑"按钮 - 修改内容或热键设置 - 点击"确定"保存修改 5. **删除文本片段**: - 选中要删除的文本片段 - 点击"删除"按钮 - 在确认对话框中点击"确定"即可删除
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、付费专栏及课程。

余额充值