Spaces:
Running
Running
Duplicate from qingxu98/gpt-academic
Browse filesCo-authored-by: fuqingxu <qingxu98@users.noreply.huggingface.co>
This view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +5 -0
- .github/ISSUE_TEMPLATE/bug_report.md +25 -0
- .github/ISSUE_TEMPLATE/feature_request.md +10 -0
- .gitignore +147 -0
- Dockerfile +20 -0
- LICENSE +674 -0
- README.md +300 -0
- check_proxy.py +149 -0
- colorful.py +91 -0
- config.py +58 -0
- core_functional.py +71 -0
- crazy_functional.py +192 -0
- crazy_functions/Latex全文润色.py +175 -0
- crazy_functions/Latex全文翻译.py +175 -0
- crazy_functions/__init__.py +0 -0
- crazy_functions/crazy_functions_test.py +92 -0
- crazy_functions/crazy_utils.py +566 -0
- crazy_functions/test_project/cpp/cppipc/buffer.cpp +87 -0
- crazy_functions/test_project/cpp/cppipc/ipc.cpp +701 -0
- crazy_functions/test_project/cpp/cppipc/policy.h +25 -0
- crazy_functions/test_project/cpp/cppipc/pool_alloc.cpp +17 -0
- crazy_functions/test_project/cpp/cppipc/prod_cons.h +433 -0
- crazy_functions/test_project/cpp/cppipc/queue.h +216 -0
- crazy_functions/test_project/cpp/cppipc/shm.cpp +103 -0
- crazy_functions/test_project/cpp/cppipc/waiter.h +83 -0
- crazy_functions/test_project/cpp/cppipc/来源 +3 -0
- crazy_functions/test_project/cpp/libJPG/jpgd.cpp +3276 -0
- crazy_functions/test_project/cpp/libJPG/jpgd.h +316 -0
- crazy_functions/test_project/cpp/libJPG/jpge.cpp +1049 -0
- crazy_functions/test_project/cpp/libJPG/jpge.h +172 -0
- crazy_functions/test_project/cpp/libJPG/来源 +3 -0
- crazy_functions/test_project/cpp/longcode/jpgd.cpp +3276 -0
- crazy_functions/test_project/cpp/longcode/jpge.cpp +1049 -0
- crazy_functions/test_project/cpp/longcode/prod_cons.h +433 -0
- crazy_functions/test_project/latex/attention/background.tex +58 -0
- crazy_functions/test_project/latex/attention/introduction.tex +18 -0
- crazy_functions/test_project/latex/attention/model_architecture.tex +155 -0
- crazy_functions/test_project/latex/attention/parameter_attention.tex +45 -0
- crazy_functions/test_project/latex/attention/来源 +8 -0
- crazy_functions/test_project/python/dqn/__init__.py +2 -0
- crazy_functions/test_project/python/dqn/dqn.py +245 -0
- crazy_functions/test_project/python/dqn/policies.py +237 -0
- crazy_functions/test_project/python/dqn/来源 +2 -0
- crazy_functions/test_project/其他测试 +27 -0
- crazy_functions/下载arxiv论文翻译摘要.py +194 -0
- crazy_functions/代码重写为全英文_多线程.py +138 -0
- crazy_functions/总结word文档.py +127 -0
- crazy_functions/批量Markdown翻译.py +161 -0
- crazy_functions/批量总结PDF文档.py +166 -0
- crazy_functions/批量总结PDF文档pdfminer.py +160 -0
.gitattributes
ADDED
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.h linguist-detectable=false
|
2 |
+
*.cpp linguist-detectable=false
|
3 |
+
*.tex linguist-detectable=false
|
4 |
+
*.cs linguist-detectable=false
|
5 |
+
*.tps linguist-detectable=false
|
.github/ISSUE_TEMPLATE/bug_report.md
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Bug report
|
3 |
+
about: Create a report to help us improve
|
4 |
+
title: ''
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
- **(1) Describe the bug 简述**
|
11 |
+
|
12 |
+
|
13 |
+
- **(2) Screen Shot 截图**
|
14 |
+
|
15 |
+
|
16 |
+
- **(3) Terminal Traceback 终端traceback(如有)**
|
17 |
+
|
18 |
+
|
19 |
+
- **(4) Material to Help Reproduce Bugs 帮助我们复现的测试材料样本(如有)**
|
20 |
+
|
21 |
+
|
22 |
+
|
23 |
+
Before submitting an issue 提交issue之前:
|
24 |
+
- Please try to upgrade your code. 如果您的代码不是最新的,建议您先尝试更新代码
|
25 |
+
- Please check project wiki for common problem solutions.项目[wiki](https://github.com/binary-husky/chatgpt_academic/wiki)有一些常见问题的解决方法
|
.github/ISSUE_TEMPLATE/feature_request.md
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Feature request
|
3 |
+
about: Suggest an idea for this project
|
4 |
+
title: ''
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
|
8 |
+
---
|
9 |
+
|
10 |
+
|
.gitignore
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Byte-compiled / optimized / DLL files
|
2 |
+
__pycache__/
|
3 |
+
*.py[cod]
|
4 |
+
*$py.class
|
5 |
+
|
6 |
+
# C extensions
|
7 |
+
*.so
|
8 |
+
|
9 |
+
# Distribution / packaging
|
10 |
+
.Python
|
11 |
+
build/
|
12 |
+
develop-eggs/
|
13 |
+
dist/
|
14 |
+
downloads/
|
15 |
+
eggs/
|
16 |
+
.eggs/
|
17 |
+
lib/
|
18 |
+
lib64/
|
19 |
+
parts/
|
20 |
+
sdist/
|
21 |
+
var/
|
22 |
+
wheels/
|
23 |
+
pip-wheel-metadata/
|
24 |
+
share/python-wheels/
|
25 |
+
*.egg-info/
|
26 |
+
.installed.cfg
|
27 |
+
*.egg
|
28 |
+
MANIFEST
|
29 |
+
|
30 |
+
# PyInstaller
|
31 |
+
# Usually these files are written by a python script from a template
|
32 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
33 |
+
*.manifest
|
34 |
+
*.spec
|
35 |
+
# Installer logs
|
36 |
+
pip-log.txt
|
37 |
+
pip-delete-this-directory.txt
|
38 |
+
|
39 |
+
# Unit test / coverage reports
|
40 |
+
htmlcov/
|
41 |
+
.tox/
|
42 |
+
.nox/
|
43 |
+
.coverage
|
44 |
+
.coverage.*
|
45 |
+
.cache
|
46 |
+
nosetests.xml
|
47 |
+
coverage.xml
|
48 |
+
*.cover
|
49 |
+
*.py,cover
|
50 |
+
.hypothesis/
|
51 |
+
.pytest_cache/
|
52 |
+
|
53 |
+
# Translations
|
54 |
+
*.mo
|
55 |
+
*.pot
|
56 |
+
github
|
57 |
+
.github
|
58 |
+
TEMP
|
59 |
+
TRASH
|
60 |
+
|
61 |
+
# Django stuff:
|
62 |
+
*.log
|
63 |
+
local_settings.py
|
64 |
+
db.sqlite3
|
65 |
+
db.sqlite3-journal
|
66 |
+
|
67 |
+
# Flask stuff:
|
68 |
+
instance/
|
69 |
+
.webassets-cache
|
70 |
+
|
71 |
+
# Scrapy stuff:
|
72 |
+
.scrapy
|
73 |
+
|
74 |
+
# Sphinx documentation
|
75 |
+
docs/_build/
|
76 |
+
|
77 |
+
# PyBuilder
|
78 |
+
target/
|
79 |
+
|
80 |
+
# Jupyter Notebook
|
81 |
+
.ipynb_checkpoints
|
82 |
+
|
83 |
+
# IPython
|
84 |
+
profile_default/
|
85 |
+
ipython_config.py
|
86 |
+
|
87 |
+
# pyenv
|
88 |
+
.python-version
|
89 |
+
|
90 |
+
# pipenv
|
91 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
92 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
93 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
94 |
+
# install all needed dependencies.
|
95 |
+
#Pipfile.lock
|
96 |
+
|
97 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
98 |
+
__pypackages__/
|
99 |
+
|
100 |
+
# Celery stuff
|
101 |
+
celerybeat-schedule
|
102 |
+
celerybeat.pid
|
103 |
+
|
104 |
+
# SageMath parsed files
|
105 |
+
*.sage.py
|
106 |
+
|
107 |
+
# Environments
|
108 |
+
.env
|
109 |
+
.venv
|
110 |
+
env/
|
111 |
+
venv/
|
112 |
+
ENV/
|
113 |
+
env.bak/
|
114 |
+
venv.bak/
|
115 |
+
|
116 |
+
# Spyder project settings
|
117 |
+
.spyderproject
|
118 |
+
.spyproject
|
119 |
+
|
120 |
+
# Rope project settings
|
121 |
+
.ropeproject
|
122 |
+
|
123 |
+
# mkdocs documentation
|
124 |
+
/site
|
125 |
+
|
126 |
+
# mypy
|
127 |
+
.mypy_cache/
|
128 |
+
.dmypy.json
|
129 |
+
dmypy.json
|
130 |
+
|
131 |
+
# Pyre type checker
|
132 |
+
.pyre/
|
133 |
+
|
134 |
+
.vscode
|
135 |
+
.idea
|
136 |
+
|
137 |
+
history
|
138 |
+
ssr_conf
|
139 |
+
config_private.py
|
140 |
+
gpt_log
|
141 |
+
private.md
|
142 |
+
private_upload
|
143 |
+
other_llms
|
144 |
+
cradle*
|
145 |
+
debug*
|
146 |
+
private*
|
147 |
+
crazy_functions/test_project/pdf_and_word
|
Dockerfile
ADDED
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 此Dockerfile适用于“无本地模型”的环境构建,如果需要使用chatglm等本地模型,请参考 docs/Dockerfile+ChatGLM
|
2 |
+
# 如何构建: 先修改 `config.py`, 然后 docker build -t gpt-academic .
|
3 |
+
# 如何运行: docker run --rm -it --net=host gpt-academic
|
4 |
+
FROM python:3.11
|
5 |
+
|
6 |
+
RUN echo '[global]' > /etc/pip.conf && \
|
7 |
+
echo 'index-url = https://mirrors.aliyun.com/pypi/simple/' >> /etc/pip.conf && \
|
8 |
+
echo 'trusted-host = mirrors.aliyun.com' >> /etc/pip.conf
|
9 |
+
|
10 |
+
|
11 |
+
WORKDIR /gpt
|
12 |
+
COPY requirements.txt .
|
13 |
+
RUN pip3 install -r requirements.txt
|
14 |
+
|
15 |
+
COPY . .
|
16 |
+
|
17 |
+
# 可选步骤,用于预热模块
|
18 |
+
RUN python3 -c 'from check_proxy import warm_up_modules; warm_up_modules()'
|
19 |
+
|
20 |
+
CMD ["python3", "-u", "main.py"]
|
LICENSE
ADDED
@@ -0,0 +1,674 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
GNU GENERAL PUBLIC LICENSE
|
2 |
+
Version 3, 29 June 2007
|
3 |
+
|
4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
6 |
+
of this license document, but changing it is not allowed.
|
7 |
+
|
8 |
+
Preamble
|
9 |
+
|
10 |
+
The GNU General Public License is a free, copyleft license for
|
11 |
+
software and other kinds of works.
|
12 |
+
|
13 |
+
The licenses for most software and other practical works are designed
|
14 |
+
to take away your freedom to share and change the works. By contrast,
|
15 |
+
the GNU General Public License is intended to guarantee your freedom to
|
16 |
+
share and change all versions of a program--to make sure it remains free
|
17 |
+
software for all its users. We, the Free Software Foundation, use the
|
18 |
+
GNU General Public License for most of our software; it applies also to
|
19 |
+
any other work released this way by its authors. You can apply it to
|
20 |
+
your programs, too.
|
21 |
+
|
22 |
+
When we speak of free software, we are referring to freedom, not
|
23 |
+
price. Our General Public Licenses are designed to make sure that you
|
24 |
+
have the freedom to distribute copies of free software (and charge for
|
25 |
+
them if you wish), that you receive source code or can get it if you
|
26 |
+
want it, that you can change the software or use pieces of it in new
|
27 |
+
free programs, and that you know you can do these things.
|
28 |
+
|
29 |
+
To protect your rights, we need to prevent others from denying you
|
30 |
+
these rights or asking you to surrender the rights. Therefore, you have
|
31 |
+
certain responsibilities if you distribute copies of the software, or if
|
32 |
+
you modify it: responsibilities to respect the freedom of others.
|
33 |
+
|
34 |
+
For example, if you distribute copies of such a program, whether
|
35 |
+
gratis or for a fee, you must pass on to the recipients the same
|
36 |
+
freedoms that you received. You must make sure that they, too, receive
|
37 |
+
or can get the source code. And you must show them these terms so they
|
38 |
+
know their rights.
|
39 |
+
|
40 |
+
Developers that use the GNU GPL protect your rights with two steps:
|
41 |
+
(1) assert copyright on the software, and (2) offer you this License
|
42 |
+
giving you legal permission to copy, distribute and/or modify it.
|
43 |
+
|
44 |
+
For the developers' and authors' protection, the GPL clearly explains
|
45 |
+
that there is no warranty for this free software. For both users' and
|
46 |
+
authors' sake, the GPL requires that modified versions be marked as
|
47 |
+
changed, so that their problems will not be attributed erroneously to
|
48 |
+
authors of previous versions.
|
49 |
+
|
50 |
+
Some devices are designed to deny users access to install or run
|
51 |
+
modified versions of the software inside them, although the manufacturer
|
52 |
+
can do so. This is fundamentally incompatible with the aim of
|
53 |
+
protecting users' freedom to change the software. The systematic
|
54 |
+
pattern of such abuse occurs in the area of products for individuals to
|
55 |
+
use, which is precisely where it is most unacceptable. Therefore, we
|
56 |
+
have designed this version of the GPL to prohibit the practice for those
|
57 |
+
products. If such problems arise substantially in other domains, we
|
58 |
+
stand ready to extend this provision to those domains in future versions
|
59 |
+
of the GPL, as needed to protect the freedom of users.
|
60 |
+
|
61 |
+
Finally, every program is threatened constantly by software patents.
|
62 |
+
States should not allow patents to restrict development and use of
|
63 |
+
software on general-purpose computers, but in those that do, we wish to
|
64 |
+
avoid the special danger that patents applied to a free program could
|
65 |
+
make it effectively proprietary. To prevent this, the GPL assures that
|
66 |
+
patents cannot be used to render the program non-free.
|
67 |
+
|
68 |
+
The precise terms and conditions for copying, distribution and
|
69 |
+
modification follow.
|
70 |
+
|
71 |
+
TERMS AND CONDITIONS
|
72 |
+
|
73 |
+
0. Definitions.
|
74 |
+
|
75 |
+
"This License" refers to version 3 of the GNU General Public License.
|
76 |
+
|
77 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
78 |
+
works, such as semiconductor masks.
|
79 |
+
|
80 |
+
"The Program" refers to any copyrightable work licensed under this
|
81 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
82 |
+
"recipients" may be individuals or organizations.
|
83 |
+
|
84 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
85 |
+
in a fashion requiring copyright permission, other than the making of an
|
86 |
+
exact copy. The resulting work is called a "modified version" of the
|
87 |
+
earlier work or a work "based on" the earlier work.
|
88 |
+
|
89 |
+
A "covered work" means either the unmodified Program or a work based
|
90 |
+
on the Program.
|
91 |
+
|
92 |
+
To "propagate" a work means to do anything with it that, without
|
93 |
+
permission, would make you directly or secondarily liable for
|
94 |
+
infringement under applicable copyright law, except executing it on a
|
95 |
+
computer or modifying a private copy. Propagation includes copying,
|
96 |
+
distribution (with or without modification), making available to the
|
97 |
+
public, and in some countries other activities as well.
|
98 |
+
|
99 |
+
To "convey" a work means any kind of propagation that enables other
|
100 |
+
parties to make or receive copies. Mere interaction with a user through
|
101 |
+
a computer network, with no transfer of a copy, is not conveying.
|
102 |
+
|
103 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
104 |
+
to the extent that it includes a convenient and prominently visible
|
105 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
106 |
+
tells the user that there is no warranty for the work (except to the
|
107 |
+
extent that warranties are provided), that licensees may convey the
|
108 |
+
work under this License, and how to view a copy of this License. If
|
109 |
+
the interface presents a list of user commands or options, such as a
|
110 |
+
menu, a prominent item in the list meets this criterion.
|
111 |
+
|
112 |
+
1. Source Code.
|
113 |
+
|
114 |
+
The "source code" for a work means the preferred form of the work
|
115 |
+
for making modifications to it. "Object code" means any non-source
|
116 |
+
form of a work.
|
117 |
+
|
118 |
+
A "Standard Interface" means an interface that either is an official
|
119 |
+
standard defined by a recognized standards body, or, in the case of
|
120 |
+
interfaces specified for a particular programming language, one that
|
121 |
+
is widely used among developers working in that language.
|
122 |
+
|
123 |
+
The "System Libraries" of an executable work include anything, other
|
124 |
+
than the work as a whole, that (a) is included in the normal form of
|
125 |
+
packaging a Major Component, but which is not part of that Major
|
126 |
+
Component, and (b) serves only to enable use of the work with that
|
127 |
+
Major Component, or to implement a Standard Interface for which an
|
128 |
+
implementation is available to the public in source code form. A
|
129 |
+
"Major Component", in this context, means a major essential component
|
130 |
+
(kernel, window system, and so on) of the specific operating system
|
131 |
+
(if any) on which the executable work runs, or a compiler used to
|
132 |
+
produce the work, or an object code interpreter used to run it.
|
133 |
+
|
134 |
+
The "Corresponding Source" for a work in object code form means all
|
135 |
+
the source code needed to generate, install, and (for an executable
|
136 |
+
work) run the object code and to modify the work, including scripts to
|
137 |
+
control those activities. However, it does not include the work's
|
138 |
+
System Libraries, or general-purpose tools or generally available free
|
139 |
+
programs which are used unmodified in performing those activities but
|
140 |
+
which are not part of the work. For example, Corresponding Source
|
141 |
+
includes interface definition files associated with source files for
|
142 |
+
the work, and the source code for shared libraries and dynamically
|
143 |
+
linked subprograms that the work is specifically designed to require,
|
144 |
+
such as by intimate data communication or control flow between those
|
145 |
+
subprograms and other parts of the work.
|
146 |
+
|
147 |
+
The Corresponding Source need not include anything that users
|
148 |
+
can regenerate automatically from other parts of the Corresponding
|
149 |
+
Source.
|
150 |
+
|
151 |
+
The Corresponding Source for a work in source code form is that
|
152 |
+
same work.
|
153 |
+
|
154 |
+
2. Basic Permissions.
|
155 |
+
|
156 |
+
All rights granted under this License are granted for the term of
|
157 |
+
copyright on the Program, and are irrevocable provided the stated
|
158 |
+
conditions are met. This License explicitly affirms your unlimited
|
159 |
+
permission to run the unmodified Program. The output from running a
|
160 |
+
covered work is covered by this License only if the output, given its
|
161 |
+
content, constitutes a covered work. This License acknowledges your
|
162 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
163 |
+
|
164 |
+
You may make, run and propagate covered works that you do not
|
165 |
+
convey, without conditions so long as your license otherwise remains
|
166 |
+
in force. You may convey covered works to others for the sole purpose
|
167 |
+
of having them make modifications exclusively for you, or provide you
|
168 |
+
with facilities for running those works, provided that you comply with
|
169 |
+
the terms of this License in conveying all material for which you do
|
170 |
+
not control copyright. Those thus making or running the covered works
|
171 |
+
for you must do so exclusively on your behalf, under your direction
|
172 |
+
and control, on terms that prohibit them from making any copies of
|
173 |
+
your copyrighted material outside their relationship with you.
|
174 |
+
|
175 |
+
Conveying under any other circumstances is permitted solely under
|
176 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
177 |
+
makes it unnecessary.
|
178 |
+
|
179 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
180 |
+
|
181 |
+
No covered work shall be deemed part of an effective technological
|
182 |
+
measure under any applicable law fulfilling obligations under article
|
183 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
184 |
+
similar laws prohibiting or restricting circumvention of such
|
185 |
+
measures.
|
186 |
+
|
187 |
+
When you convey a covered work, you waive any legal power to forbid
|
188 |
+
circumvention of technological measures to the extent such circumvention
|
189 |
+
is effected by exercising rights under this License with respect to
|
190 |
+
the covered work, and you disclaim any intention to limit operation or
|
191 |
+
modification of the work as a means of enforcing, against the work's
|
192 |
+
users, your or third parties' legal rights to forbid circumvention of
|
193 |
+
technological measures.
|
194 |
+
|
195 |
+
4. Conveying Verbatim Copies.
|
196 |
+
|
197 |
+
You may convey verbatim copies of the Program's source code as you
|
198 |
+
receive it, in any medium, provided that you conspicuously and
|
199 |
+
appropriately publish on each copy an appropriate copyright notice;
|
200 |
+
keep intact all notices stating that this License and any
|
201 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
202 |
+
keep intact all notices of the absence of any warranty; and give all
|
203 |
+
recipients a copy of this License along with the Program.
|
204 |
+
|
205 |
+
You may charge any price or no price for each copy that you convey,
|
206 |
+
and you may offer support or warranty protection for a fee.
|
207 |
+
|
208 |
+
5. Conveying Modified Source Versions.
|
209 |
+
|
210 |
+
You may convey a work based on the Program, or the modifications to
|
211 |
+
produce it from the Program, in the form of source code under the
|
212 |
+
terms of section 4, provided that you also meet all of these conditions:
|
213 |
+
|
214 |
+
a) The work must carry prominent notices stating that you modified
|
215 |
+
it, and giving a relevant date.
|
216 |
+
|
217 |
+
b) The work must carry prominent notices stating that it is
|
218 |
+
released under this License and any conditions added under section
|
219 |
+
7. This requirement modifies the requirement in section 4 to
|
220 |
+
"keep intact all notices".
|
221 |
+
|
222 |
+
c) You must license the entire work, as a whole, under this
|
223 |
+
License to anyone who comes into possession of a copy. This
|
224 |
+
License will therefore apply, along with any applicable section 7
|
225 |
+
additional terms, to the whole of the work, and all its parts,
|
226 |
+
regardless of how they are packaged. This License gives no
|
227 |
+
permission to license the work in any other way, but it does not
|
228 |
+
invalidate such permission if you have separately received it.
|
229 |
+
|
230 |
+
d) If the work has interactive user interfaces, each must display
|
231 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
232 |
+
interfaces that do not display Appropriate Legal Notices, your
|
233 |
+
work need not make them do so.
|
234 |
+
|
235 |
+
A compilation of a covered work with other separate and independent
|
236 |
+
works, which are not by their nature extensions of the covered work,
|
237 |
+
and which are not combined with it such as to form a larger program,
|
238 |
+
in or on a volume of a storage or distribution medium, is called an
|
239 |
+
"aggregate" if the compilation and its resulting copyright are not
|
240 |
+
used to limit the access or legal rights of the compilation's users
|
241 |
+
beyond what the individual works permit. Inclusion of a covered work
|
242 |
+
in an aggregate does not cause this License to apply to the other
|
243 |
+
parts of the aggregate.
|
244 |
+
|
245 |
+
6. Conveying Non-Source Forms.
|
246 |
+
|
247 |
+
You may convey a covered work in object code form under the terms
|
248 |
+
of sections 4 and 5, provided that you also convey the
|
249 |
+
machine-readable Corresponding Source under the terms of this License,
|
250 |
+
in one of these ways:
|
251 |
+
|
252 |
+
a) Convey the object code in, or embodied in, a physical product
|
253 |
+
(including a physical distribution medium), accompanied by the
|
254 |
+
Corresponding Source fixed on a durable physical medium
|
255 |
+
customarily used for software interchange.
|
256 |
+
|
257 |
+
b) Convey the object code in, or embodied in, a physical product
|
258 |
+
(including a physical distribution medium), accompanied by a
|
259 |
+
written offer, valid for at least three years and valid for as
|
260 |
+
long as you offer spare parts or customer support for that product
|
261 |
+
model, to give anyone who possesses the object code either (1) a
|
262 |
+
copy of the Corresponding Source for all the software in the
|
263 |
+
product that is covered by this License, on a durable physical
|
264 |
+
medium customarily used for software interchange, for a price no
|
265 |
+
more than your reasonable cost of physically performing this
|
266 |
+
conveying of source, or (2) access to copy the
|
267 |
+
Corresponding Source from a network server at no charge.
|
268 |
+
|
269 |
+
c) Convey individual copies of the object code with a copy of the
|
270 |
+
written offer to provide the Corresponding Source. This
|
271 |
+
alternative is allowed only occasionally and noncommercially, and
|
272 |
+
only if you received the object code with such an offer, in accord
|
273 |
+
with subsection 6b.
|
274 |
+
|
275 |
+
d) Convey the object code by offering access from a designated
|
276 |
+
place (gratis or for a charge), and offer equivalent access to the
|
277 |
+
Corresponding Source in the same way through the same place at no
|
278 |
+
further charge. You need not require recipients to copy the
|
279 |
+
Corresponding Source along with the object code. If the place to
|
280 |
+
copy the object code is a network server, the Corresponding Source
|
281 |
+
may be on a different server (operated by you or a third party)
|
282 |
+
that supports equivalent copying facilities, provided you maintain
|
283 |
+
clear directions next to the object code saying where to find the
|
284 |
+
Corresponding Source. Regardless of what server hosts the
|
285 |
+
Corresponding Source, you remain obligated to ensure that it is
|
286 |
+
available for as long as needed to satisfy these requirements.
|
287 |
+
|
288 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
289 |
+
you inform other peers where the object code and Corresponding
|
290 |
+
Source of the work are being offered to the general public at no
|
291 |
+
charge under subsection 6d.
|
292 |
+
|
293 |
+
A separable portion of the object code, whose source code is excluded
|
294 |
+
from the Corresponding Source as a System Library, need not be
|
295 |
+
included in conveying the object code work.
|
296 |
+
|
297 |
+
A "User Product" is either (1) a "consumer product", which means any
|
298 |
+
tangible personal property which is normally used for personal, family,
|
299 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
300 |
+
into a dwelling. In determining whether a product is a consumer product,
|
301 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
302 |
+
product received by a particular user, "normally used" refers to a
|
303 |
+
typical or common use of that class of product, regardless of the status
|
304 |
+
of the particular user or of the way in which the particular user
|
305 |
+
actually uses, or expects or is expected to use, the product. A product
|
306 |
+
is a consumer product regardless of whether the product has substantial
|
307 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
308 |
+
the only significant mode of use of the product.
|
309 |
+
|
310 |
+
"Installation Information" for a User Product means any methods,
|
311 |
+
procedures, authorization keys, or other information required to install
|
312 |
+
and execute modified versions of a covered work in that User Product from
|
313 |
+
a modified version of its Corresponding Source. The information must
|
314 |
+
suffice to ensure that the continued functioning of the modified object
|
315 |
+
code is in no case prevented or interfered with solely because
|
316 |
+
modification has been made.
|
317 |
+
|
318 |
+
If you convey an object code work under this section in, or with, or
|
319 |
+
specifically for use in, a User Product, and the conveying occurs as
|
320 |
+
part of a transaction in which the right of possession and use of the
|
321 |
+
User Product is transferred to the recipient in perpetuity or for a
|
322 |
+
fixed term (regardless of how the transaction is characterized), the
|
323 |
+
Corresponding Source conveyed under this section must be accompanied
|
324 |
+
by the Installation Information. But this requirement does not apply
|
325 |
+
if neither you nor any third party retains the ability to install
|
326 |
+
modified object code on the User Product (for example, the work has
|
327 |
+
been installed in ROM).
|
328 |
+
|
329 |
+
The requirement to provide Installation Information does not include a
|
330 |
+
requirement to continue to provide support service, warranty, or updates
|
331 |
+
for a work that has been modified or installed by the recipient, or for
|
332 |
+
the User Product in which it has been modified or installed. Access to a
|
333 |
+
network may be denied when the modification itself materially and
|
334 |
+
adversely affects the operation of the network or violates the rules and
|
335 |
+
protocols for communication across the network.
|
336 |
+
|
337 |
+
Corresponding Source conveyed, and Installation Information provided,
|
338 |
+
in accord with this section must be in a format that is publicly
|
339 |
+
documented (and with an implementation available to the public in
|
340 |
+
source code form), and must require no special password or key for
|
341 |
+
unpacking, reading or copying.
|
342 |
+
|
343 |
+
7. Additional Terms.
|
344 |
+
|
345 |
+
"Additional permissions" are terms that supplement the terms of this
|
346 |
+
License by making exceptions from one or more of its conditions.
|
347 |
+
Additional permissions that are applicable to the entire Program shall
|
348 |
+
be treated as though they were included in this License, to the extent
|
349 |
+
that they are valid under applicable law. If additional permissions
|
350 |
+
apply only to part of the Program, that part may be used separately
|
351 |
+
under those permissions, but the entire Program remains governed by
|
352 |
+
this License without regard to the additional permissions.
|
353 |
+
|
354 |
+
When you convey a copy of a covered work, you may at your option
|
355 |
+
remove any additional permissions from that copy, or from any part of
|
356 |
+
it. (Additional permissions may be written to require their own
|
357 |
+
removal in certain cases when you modify the work.) You may place
|
358 |
+
additional permissions on material, added by you to a covered work,
|
359 |
+
for which you have or can give appropriate copyright permission.
|
360 |
+
|
361 |
+
Notwithstanding any other provision of this License, for material you
|
362 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
363 |
+
that material) supplement the terms of this License with terms:
|
364 |
+
|
365 |
+
a) Disclaiming warranty or limiting liability differently from the
|
366 |
+
terms of sections 15 and 16 of this License; or
|
367 |
+
|
368 |
+
b) Requiring preservation of specified reasonable legal notices or
|
369 |
+
author attributions in that material or in the Appropriate Legal
|
370 |
+
Notices displayed by works containing it; or
|
371 |
+
|
372 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
373 |
+
requiring that modified versions of such material be marked in
|
374 |
+
reasonable ways as different from the original version; or
|
375 |
+
|
376 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
377 |
+
authors of the material; or
|
378 |
+
|
379 |
+
e) Declining to grant rights under trademark law for use of some
|
380 |
+
trade names, trademarks, or service marks; or
|
381 |
+
|
382 |
+
f) Requiring indemnification of licensors and authors of that
|
383 |
+
material by anyone who conveys the material (or modified versions of
|
384 |
+
it) with contractual assumptions of liability to the recipient, for
|
385 |
+
any liability that these contractual assumptions directly impose on
|
386 |
+
those licensors and authors.
|
387 |
+
|
388 |
+
All other non-permissive additional terms are considered "further
|
389 |
+
restrictions" within the meaning of section 10. If the Program as you
|
390 |
+
received it, or any part of it, contains a notice stating that it is
|
391 |
+
governed by this License along with a term that is a further
|
392 |
+
restriction, you may remove that term. If a license document contains
|
393 |
+
a further restriction but permits relicensing or conveying under this
|
394 |
+
License, you may add to a covered work material governed by the terms
|
395 |
+
of that license document, provided that the further restriction does
|
396 |
+
not survive such relicensing or conveying.
|
397 |
+
|
398 |
+
If you add terms to a covered work in accord with this section, you
|
399 |
+
must place, in the relevant source files, a statement of the
|
400 |
+
additional terms that apply to those files, or a notice indicating
|
401 |
+
where to find the applicable terms.
|
402 |
+
|
403 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
404 |
+
form of a separately written license, or stated as exceptions;
|
405 |
+
the above requirements apply either way.
|
406 |
+
|
407 |
+
8. Termination.
|
408 |
+
|
409 |
+
You may not propagate or modify a covered work except as expressly
|
410 |
+
provided under this License. Any attempt otherwise to propagate or
|
411 |
+
modify it is void, and will automatically terminate your rights under
|
412 |
+
this License (including any patent licenses granted under the third
|
413 |
+
paragraph of section 11).
|
414 |
+
|
415 |
+
However, if you cease all violation of this License, then your
|
416 |
+
license from a particular copyright holder is reinstated (a)
|
417 |
+
provisionally, unless and until the copyright holder explicitly and
|
418 |
+
finally terminates your license, and (b) permanently, if the copyright
|
419 |
+
holder fails to notify you of the violation by some reasonable means
|
420 |
+
prior to 60 days after the cessation.
|
421 |
+
|
422 |
+
Moreover, your license from a particular copyright holder is
|
423 |
+
reinstated permanently if the copyright holder notifies you of the
|
424 |
+
violation by some reasonable means, this is the first time you have
|
425 |
+
received notice of violation of this License (for any work) from that
|
426 |
+
copyright holder, and you cure the violation prior to 30 days after
|
427 |
+
your receipt of the notice.
|
428 |
+
|
429 |
+
Termination of your rights under this section does not terminate the
|
430 |
+
licenses of parties who have received copies or rights from you under
|
431 |
+
this License. If your rights have been terminated and not permanently
|
432 |
+
reinstated, you do not qualify to receive new licenses for the same
|
433 |
+
material under section 10.
|
434 |
+
|
435 |
+
9. Acceptance Not Required for Having Copies.
|
436 |
+
|
437 |
+
You are not required to accept this License in order to receive or
|
438 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
439 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
440 |
+
to receive a copy likewise does not require acceptance. However,
|
441 |
+
nothing other than this License grants you permission to propagate or
|
442 |
+
modify any covered work. These actions infringe copyright if you do
|
443 |
+
not accept this License. Therefore, by modifying or propagating a
|
444 |
+
covered work, you indicate your acceptance of this License to do so.
|
445 |
+
|
446 |
+
10. Automatic Licensing of Downstream Recipients.
|
447 |
+
|
448 |
+
Each time you convey a covered work, the recipient automatically
|
449 |
+
receives a license from the original licensors, to run, modify and
|
450 |
+
propagate that work, subject to this License. You are not responsible
|
451 |
+
for enforcing compliance by third parties with this License.
|
452 |
+
|
453 |
+
An "entity transaction" is a transaction transferring control of an
|
454 |
+
organization, or substantially all assets of one, or subdividing an
|
455 |
+
organization, or merging organizations. If propagation of a covered
|
456 |
+
work results from an entity transaction, each party to that
|
457 |
+
transaction who receives a copy of the work also receives whatever
|
458 |
+
licenses to the work the party's predecessor in interest had or could
|
459 |
+
give under the previous paragraph, plus a right to possession of the
|
460 |
+
Corresponding Source of the work from the predecessor in interest, if
|
461 |
+
the predecessor has it or can get it with reasonable efforts.
|
462 |
+
|
463 |
+
You may not impose any further restrictions on the exercise of the
|
464 |
+
rights granted or affirmed under this License. For example, you may
|
465 |
+
not impose a license fee, royalty, or other charge for exercise of
|
466 |
+
rights granted under this License, and you may not initiate litigation
|
467 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
468 |
+
any patent claim is infringed by making, using, selling, offering for
|
469 |
+
sale, or importing the Program or any portion of it.
|
470 |
+
|
471 |
+
11. Patents.
|
472 |
+
|
473 |
+
A "contributor" is a copyright holder who authorizes use under this
|
474 |
+
License of the Program or a work on which the Program is based. The
|
475 |
+
work thus licensed is called the contributor's "contributor version".
|
476 |
+
|
477 |
+
A contributor's "essential patent claims" are all patent claims
|
478 |
+
owned or controlled by the contributor, whether already acquired or
|
479 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
480 |
+
by this License, of making, using, or selling its contributor version,
|
481 |
+
but do not include claims that would be infringed only as a
|
482 |
+
consequence of further modification of the contributor version. For
|
483 |
+
purposes of this definition, "control" includes the right to grant
|
484 |
+
patent sublicenses in a manner consistent with the requirements of
|
485 |
+
this License.
|
486 |
+
|
487 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
488 |
+
patent license under the contributor's essential patent claims, to
|
489 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
490 |
+
propagate the contents of its contributor version.
|
491 |
+
|
492 |
+
In the following three paragraphs, a "patent license" is any express
|
493 |
+
agreement or commitment, however denominated, not to enforce a patent
|
494 |
+
(such as an express permission to practice a patent or covenant not to
|
495 |
+
sue for patent infringement). To "grant" such a patent license to a
|
496 |
+
party means to make such an agreement or commitment not to enforce a
|
497 |
+
patent against the party.
|
498 |
+
|
499 |
+
If you convey a covered work, knowingly relying on a patent license,
|
500 |
+
and the Corresponding Source of the work is not available for anyone
|
501 |
+
to copy, free of charge and under the terms of this License, through a
|
502 |
+
publicly available network server or other readily accessible means,
|
503 |
+
then you must either (1) cause the Corresponding Source to be so
|
504 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
505 |
+
patent license for this particular work, or (3) arrange, in a manner
|
506 |
+
consistent with the requirements of this License, to extend the patent
|
507 |
+
license to downstream recipients. "Knowingly relying" means you have
|
508 |
+
actual knowledge that, but for the patent license, your conveying the
|
509 |
+
covered work in a country, or your recipient's use of the covered work
|
510 |
+
in a country, would infringe one or more identifiable patents in that
|
511 |
+
country that you have reason to believe are valid.
|
512 |
+
|
513 |
+
If, pursuant to or in connection with a single transaction or
|
514 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
515 |
+
covered work, and grant a patent license to some of the parties
|
516 |
+
receiving the covered work authorizing them to use, propagate, modify
|
517 |
+
or convey a specific copy of the covered work, then the patent license
|
518 |
+
you grant is automatically extended to all recipients of the covered
|
519 |
+
work and works based on it.
|
520 |
+
|
521 |
+
A patent license is "discriminatory" if it does not include within
|
522 |
+
the scope of its coverage, prohibits the exercise of, or is
|
523 |
+
conditioned on the non-exercise of one or more of the rights that are
|
524 |
+
specifically granted under this License. You may not convey a covered
|
525 |
+
work if you are a party to an arrangement with a third party that is
|
526 |
+
in the business of distributing software, under which you make payment
|
527 |
+
to the third party based on the extent of your activity of conveying
|
528 |
+
the work, and under which the third party grants, to any of the
|
529 |
+
parties who would receive the covered work from you, a discriminatory
|
530 |
+
patent license (a) in connection with copies of the covered work
|
531 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
532 |
+
for and in connection with specific products or compilations that
|
533 |
+
contain the covered work, unless you entered into that arrangement,
|
534 |
+
or that patent license was granted, prior to 28 March 2007.
|
535 |
+
|
536 |
+
Nothing in this License shall be construed as excluding or limiting
|
537 |
+
any implied license or other defenses to infringement that may
|
538 |
+
otherwise be available to you under applicable patent law.
|
539 |
+
|
540 |
+
12. No Surrender of Others' Freedom.
|
541 |
+
|
542 |
+
If conditions are imposed on you (whether by court order, agreement or
|
543 |
+
otherwise) that contradict the conditions of this License, they do not
|
544 |
+
excuse you from the conditions of this License. If you cannot convey a
|
545 |
+
covered work so as to satisfy simultaneously your obligations under this
|
546 |
+
License and any other pertinent obligations, then as a consequence you may
|
547 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
548 |
+
to collect a royalty for further conveying from those to whom you convey
|
549 |
+
the Program, the only way you could satisfy both those terms and this
|
550 |
+
License would be to refrain entirely from conveying the Program.
|
551 |
+
|
552 |
+
13. Use with the GNU Affero General Public License.
|
553 |
+
|
554 |
+
Notwithstanding any other provision of this License, you have
|
555 |
+
permission to link or combine any covered work with a work licensed
|
556 |
+
under version 3 of the GNU Affero General Public License into a single
|
557 |
+
combined work, and to convey the resulting work. The terms of this
|
558 |
+
License will continue to apply to the part which is the covered work,
|
559 |
+
but the special requirements of the GNU Affero General Public License,
|
560 |
+
section 13, concerning interaction through a network will apply to the
|
561 |
+
combination as such.
|
562 |
+
|
563 |
+
14. Revised Versions of this License.
|
564 |
+
|
565 |
+
The Free Software Foundation may publish revised and/or new versions of
|
566 |
+
the GNU General Public License from time to time. Such new versions will
|
567 |
+
be similar in spirit to the present version, but may differ in detail to
|
568 |
+
address new problems or concerns.
|
569 |
+
|
570 |
+
Each version is given a distinguishing version number. If the
|
571 |
+
Program specifies that a certain numbered version of the GNU General
|
572 |
+
Public License "or any later version" applies to it, you have the
|
573 |
+
option of following the terms and conditions either of that numbered
|
574 |
+
version or of any later version published by the Free Software
|
575 |
+
Foundation. If the Program does not specify a version number of the
|
576 |
+
GNU General Public License, you may choose any version ever published
|
577 |
+
by the Free Software Foundation.
|
578 |
+
|
579 |
+
If the Program specifies that a proxy can decide which future
|
580 |
+
versions of the GNU General Public License can be used, that proxy's
|
581 |
+
public statement of acceptance of a version permanently authorizes you
|
582 |
+
to choose that version for the Program.
|
583 |
+
|
584 |
+
Later license versions may give you additional or different
|
585 |
+
permissions. However, no additional obligations are imposed on any
|
586 |
+
author or copyright holder as a result of your choosing to follow a
|
587 |
+
later version.
|
588 |
+
|
589 |
+
15. Disclaimer of Warranty.
|
590 |
+
|
591 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
592 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
593 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
594 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
595 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
596 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
597 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
598 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
599 |
+
|
600 |
+
16. Limitation of Liability.
|
601 |
+
|
602 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
603 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
604 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
605 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
606 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
607 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
608 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
609 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
610 |
+
SUCH DAMAGES.
|
611 |
+
|
612 |
+
17. Interpretation of Sections 15 and 16.
|
613 |
+
|
614 |
+
If the disclaimer of warranty and limitation of liability provided
|
615 |
+
above cannot be given local legal effect according to their terms,
|
616 |
+
reviewing courts shall apply local law that most closely approximates
|
617 |
+
an absolute waiver of all civil liability in connection with the
|
618 |
+
Program, unless a warranty or assumption of liability accompanies a
|
619 |
+
copy of the Program in return for a fee.
|
620 |
+
|
621 |
+
END OF TERMS AND CONDITIONS
|
622 |
+
|
623 |
+
How to Apply These Terms to Your New Programs
|
624 |
+
|
625 |
+
If you develop a new program, and you want it to be of the greatest
|
626 |
+
possible use to the public, the best way to achieve this is to make it
|
627 |
+
free software which everyone can redistribute and change under these terms.
|
628 |
+
|
629 |
+
To do so, attach the following notices to the program. It is safest
|
630 |
+
to attach them to the start of each source file to most effectively
|
631 |
+
state the exclusion of warranty; and each file should have at least
|
632 |
+
the "copyright" line and a pointer to where the full notice is found.
|
633 |
+
|
634 |
+
<one line to give the program's name and a brief idea of what it does.>
|
635 |
+
Copyright (C) <year> <name of author>
|
636 |
+
|
637 |
+
This program is free software: you can redistribute it and/or modify
|
638 |
+
it under the terms of the GNU General Public License as published by
|
639 |
+
the Free Software Foundation, either version 3 of the License, or
|
640 |
+
(at your option) any later version.
|
641 |
+
|
642 |
+
This program is distributed in the hope that it will be useful,
|
643 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
644 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
645 |
+
GNU General Public License for more details.
|
646 |
+
|
647 |
+
You should have received a copy of the GNU General Public License
|
648 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
649 |
+
|
650 |
+
Also add information on how to contact you by electronic and paper mail.
|
651 |
+
|
652 |
+
If the program does terminal interaction, make it output a short
|
653 |
+
notice like this when it starts in an interactive mode:
|
654 |
+
|
655 |
+
<program> Copyright (C) <year> <name of author>
|
656 |
+
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
657 |
+
This is free software, and you are welcome to redistribute it
|
658 |
+
under certain conditions; type `show c' for details.
|
659 |
+
|
660 |
+
The hypothetical commands `show w' and `show c' should show the appropriate
|
661 |
+
parts of the General Public License. Of course, your program's commands
|
662 |
+
might be different; for a GUI interface, you would use an "about box".
|
663 |
+
|
664 |
+
You should also get your employer (if you work as a programmer) or school,
|
665 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
666 |
+
For more information on this, and how to apply and follow the GNU GPL, see
|
667 |
+
<https://www.gnu.org/licenses/>.
|
668 |
+
|
669 |
+
The GNU General Public License does not permit incorporating your program
|
670 |
+
into proprietary programs. If your program is a subroutine library, you
|
671 |
+
may consider it more useful to permit linking proprietary applications with
|
672 |
+
the library. If this is what you want to do, use the GNU Lesser General
|
673 |
+
Public License instead of this License. But first, please read
|
674 |
+
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
README.md
ADDED
@@ -0,0 +1,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: academic-chatgpt
|
3 |
+
emoji: 😻
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: blue
|
6 |
+
sdk: gradio
|
7 |
+
sdk_version: 3.25.0
|
8 |
+
python_version: 3.11
|
9 |
+
app_file: main.py
|
10 |
+
pinned: false
|
11 |
+
duplicated_from: qingxu98/gpt-academic
|
12 |
+
---
|
13 |
+
|
14 |
+
# ChatGPT 学术优化
|
15 |
+
|
16 |
+
**如果喜欢这个项目,请给它一个Star;如果你发明了更好用的快捷键或函数插件,欢迎发issue或者pull requests**
|
17 |
+
|
18 |
+
If you like this project, please give it a Star. If you've come up with more useful academic shortcuts or functional plugins, feel free to open an issue or pull request. We also have a README in [English|](docs/README_EN.md)[日本語|](docs/README_JP.md)[Русский|](docs/README_RS.md)[Français](docs/README_FR.md) translated by this project itself.
|
19 |
+
|
20 |
+
> **Note**
|
21 |
+
>
|
22 |
+
> 1.请注意只有**红颜色**标识的函数插件(按钮)才支持读取文件,部分插件位于插件区的**下拉菜单**中。另外我们以**最高优先级**欢迎和处理任何新插件的PR!
|
23 |
+
>
|
24 |
+
> 2.本项目中每个文件的功能都在自译解[`self_analysis.md`](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)详细说明。随着版本的迭代,您也可以随时自行点击相关函数插件,调用GPT重新生成项目的自我解析报告。常见问题汇总在[`wiki`](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%B8%B8%E8%A7%81%E9%97%AE%E9%A2%98)当中。
|
25 |
+
>
|
26 |
+
|
27 |
+
|
28 |
+
<div align="center">
|
29 |
+
|
30 |
+
功能 | 描述
|
31 |
+
--- | ---
|
32 |
+
一键润色 | 支持一键润色、一键查找论文语法错误
|
33 |
+
一键中英互译 | 一键中英互译
|
34 |
+
一键代码解释 | 可以正确显示代码、解释代码
|
35 |
+
[自定义快捷键](https://www.bilibili.com/video/BV14s4y1E7jN) | 支持自定义快捷键
|
36 |
+
[配置代理服务器](https://www.bilibili.com/video/BV1rc411W7Dr) | 支持配置代理服务器
|
37 |
+
模块化设计 | 支持自定义高阶的函数插件与[函数插件],插件支持[热更新](https://github.com/binary-husky/chatgpt_academic/wiki/%E5%87%BD%E6%95%B0%E6%8F%92%E4%BB%B6%E6%8C%87%E5%8D%97)
|
38 |
+
[自我程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] [一键读懂](https://github.com/binary-husky/chatgpt_academic/wiki/chatgpt-academic%E9%A1%B9%E7%9B%AE%E8%87%AA%E8%AF%91%E8%A7%A3%E6%8A%A5%E5%91%8A)本项目的源代码
|
39 |
+
[程序剖析](https://www.bilibili.com/video/BV1cj411A7VW) | [函数插件] 一键可以剖析其他Python/C/C++/Java/Lua/...项目树
|
40 |
+
读论文 | [函数插件] 一键解读latex论文全文并生成摘要
|
41 |
+
Latex全文翻译、润色 | [函数插件] 一键翻译或润色latex论文
|
42 |
+
批量注释生成 | [函数插件] 一键批量生成函数注释
|
43 |
+
chat分析报告生成 | [函数插件] 运行后自动生成总结汇报
|
44 |
+
[arxiv小助手](https://www.bilibili.com/video/BV1LM4y1279X) | [函数插件] 输入arxiv文章url即可一键翻译摘要+下载PDF
|
45 |
+
[PDF论文全文翻译功能](https://www.bilibili.com/video/BV1KT411x7Wn) | [函数插件] PDF论文提取题目&摘要+翻译全文(多线程)
|
46 |
+
[谷歌学术统合小助手](https://www.bilibili.com/video/BV19L411U7ia) | [函数插件] 给定任意谷歌学术搜索页面URL,让gpt帮你选择有趣的文章
|
47 |
+
公式/图片/表格显示 | 可以同时显示公式的tex形式和渲染形式,支持公式、代码高亮
|
48 |
+
多线程函数插件支持 | 支持多线调用chatgpt,一键处理海量文本或程序
|
49 |
+
启动暗色gradio[主题](https://github.com/binary-husky/chatgpt_academic/issues/173) | 在浏览器url后面添加```/?__dark-theme=true```可以切换dark主题
|
50 |
+
[多LLM模型](https://www.bilibili.com/video/BV1wT411p7yf)支持,[API2D](https://api2d.com/)接口支持 | 同时被GPT3.5、GPT4和[清华ChatGLM](https://github.com/THUDM/ChatGLM-6B)伺候的感觉一定会很不错吧?
|
51 |
+
huggingface免科学上网[在线体验](https://huggingface.co/spaces/qingxu98/gpt-academic) | 登陆huggingface后复制[此空间](https://huggingface.co/spaces/qingxu98/gpt-academic)
|
52 |
+
…… | ……
|
53 |
+
|
54 |
+
</div>
|
55 |
+
|
56 |
+
|
57 |
+
- 新界面(修改config.py中的LAYOUT选项即可实现“左右布局”和“上下布局”的切换)
|
58 |
+
<div align="center">
|
59 |
+
<img src="https://user-images.githubusercontent.com/96192199/230361456-61078362-a966-4eb5-b49e-3c62ef18b860.gif" width="700" >
|
60 |
+
</div>
|
61 |
+
|
62 |
+
|
63 |
+
- 所有按钮都通过读取functional.py动态生成,可随意加自定义功能,解放粘贴板
|
64 |
+
<div align="center">
|
65 |
+
<img src="https://user-images.githubusercontent.com/96192199/231975334-b4788e91-4887-412f-8b43-2b9c5f41d248.gif" width="700" >
|
66 |
+
</div>
|
67 |
+
|
68 |
+
- 润色/纠错
|
69 |
+
<div align="center">
|
70 |
+
<img src="https://user-images.githubusercontent.com/96192199/231980294-f374bdcb-3309-4560-b424-38ef39f04ebd.gif" width="700" >
|
71 |
+
</div>
|
72 |
+
|
73 |
+
- 如果输出包含公式,会同时以tex形式和渲染形式显示,方便复制和阅读
|
74 |
+
<div align="center">
|
75 |
+
<img src="https://user-images.githubusercontent.com/96192199/230598842-1d7fcddd-815d-40ee-af60-baf488a199df.png" width="700" >
|
76 |
+
</div>
|
77 |
+
|
78 |
+
- 懒得看项目代码?整个工程直接给chatgpt炫嘴里
|
79 |
+
<div align="center">
|
80 |
+
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="700" >
|
81 |
+
</div>
|
82 |
+
|
83 |
+
- 多种大语言模型混合调用(ChatGLM + OpenAI-GPT3.5 + [API2D](https://api2d.com/)-GPT4)
|
84 |
+
<div align="center">
|
85 |
+
<img src="https://user-images.githubusercontent.com/96192199/232537274-deca0563-7aa6-4b5d-94a2-b7c453c47794.png" width="700" >
|
86 |
+
</div>
|
87 |
+
|
88 |
+
多种大语言模型混合调用[huggingface测试版](https://huggingface.co/spaces/qingxu98/academic-chatgpt-beta)(huggingface版不支持chatglm)
|
89 |
+
|
90 |
+
|
91 |
+
---
|
92 |
+
|
93 |
+
## 安装-方法1:直接运行 (Windows, Linux or MacOS)
|
94 |
+
|
95 |
+
1. 下载项目
|
96 |
+
```sh
|
97 |
+
git clone https://github.com/binary-husky/chatgpt_academic.git
|
98 |
+
cd chatgpt_academic
|
99 |
+
```
|
100 |
+
|
101 |
+
2. 配置API_KEY和代理设置
|
102 |
+
|
103 |
+
在`config.py`中,配置 海外Proxy 和 OpenAI API KEY,说明如下
|
104 |
+
```
|
105 |
+
1. 如果你在国内,需要设置海外代理才能够顺利使用 OpenAI API,设置方法请仔细阅读config.py(1.修改其中的USE_PROXY为True; 2.按照说明修改其中的proxies)。
|
106 |
+
2. 配置 OpenAI API KEY。你需要在 OpenAI 官网上注册并获取 API KEY。一旦你拿到了 API KEY,在 config.py 文件里配置好即可。
|
107 |
+
3. 与代理网络有关的issue(网络超时、代理不起作用)汇总到 https://github.com/binary-husky/chatgpt_academic/issues/1
|
108 |
+
```
|
109 |
+
(P.S. 程序运行时会优先检查是否存在名为`config_private.py`的私密配置文件,并用其中的配置覆盖`config.py`的同名配置。因此,如果您能理解我们的配置读取逻辑,我们强烈建议您在`config.py`旁边创建一个名为`config_private.py`的新配置文件,并把`config.py`中的配置转移(复制)到`config_private.py`中。`config_private.py`不受git管控,可以让您的隐私信息更加安全。)
|
110 |
+
|
111 |
+
|
112 |
+
3. 安装依赖
|
113 |
+
```sh
|
114 |
+
# (选择一)推荐
|
115 |
+
python -m pip install -r requirements.txt
|
116 |
+
|
117 |
+
# (选择二)如果您使用anaconda,步骤也是类似的:
|
118 |
+
# (选择二.1)conda create -n gptac_venv python=3.11
|
119 |
+
# (选择二.2)conda activate gptac_venv
|
120 |
+
# (选择二.3)python -m pip install -r requirements.txt
|
121 |
+
|
122 |
+
# 备注:使用官方pip源或者阿里pip源,其他pip源(如一些大学的pip)有可能出问题,临时换源方法:
|
123 |
+
# python -m pip install -r requirements.txt -i https://mirrors.aliyun.com/pypi/simple/
|
124 |
+
```
|
125 |
+
|
126 |
+
如果需要支持清华ChatGLM,需要额外安装更多依赖(不熟悉python者、电脑配置不佳者,建议不要尝试):
|
127 |
+
```sh
|
128 |
+
python -m pip install -r request_llm/requirements_chatglm.txt
|
129 |
+
```
|
130 |
+
|
131 |
+
4. 运行
|
132 |
+
```sh
|
133 |
+
python main.py
|
134 |
+
```
|
135 |
+
|
136 |
+
5. 测试函数插件
|
137 |
+
```
|
138 |
+
- 测试Python项目分析
|
139 |
+
input区域 输入 `./crazy_functions/test_project/python/dqn` , 然后点击 "解析整个Python项目"
|
140 |
+
- 测试自我代码解读
|
141 |
+
点击 "[多线程Demo] 解析此项目本身(源码自译解)"
|
142 |
+
- 测试实验功能模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
|
143 |
+
点击 "[函数插件模板Demo] 历史上的今天"
|
144 |
+
- 函数插件区下拉菜单中有更多功能可供选择
|
145 |
+
```
|
146 |
+
|
147 |
+
## 安装-方法2:使用docker (Linux)
|
148 |
+
|
149 |
+
1. 仅ChatGPT(推荐大多数人选择)
|
150 |
+
``` sh
|
151 |
+
# 下载项目
|
152 |
+
git clone https://github.com/binary-husky/chatgpt_academic.git
|
153 |
+
cd chatgpt_academic
|
154 |
+
# 配置 海外Proxy 和 OpenAI API KEY
|
155 |
+
用任意文本编辑器编辑 config.py
|
156 |
+
# 安装
|
157 |
+
docker build -t gpt-academic .
|
158 |
+
# 运行
|
159 |
+
docker run --rm -it --net=host gpt-academic
|
160 |
+
|
161 |
+
# 测试函数插件
|
162 |
+
## 测试函数插件模板函数(要求gpt回答历史上的今天发生了什么),您可以根据此函数为模板,实现更复杂的功能
|
163 |
+
点击 "[函数插件模板Demo] 历史上的今天"
|
164 |
+
## 测试给Latex项目写摘要
|
165 |
+
input区域 输入 ./crazy_functions/test_project/latex/attention , 然后点击 "读Tex论文写摘要"
|
166 |
+
## 测试Python项目分析
|
167 |
+
input区域 输入 ./crazy_functions/test_project/python/dqn , 然后点击 "解析整个Python项目"
|
168 |
+
|
169 |
+
函数插件区下拉菜单中有更多功能可供选择
|
170 |
+
```
|
171 |
+
|
172 |
+
2. ChatGPT+ChatGLM(需要对docker非常熟悉 + 电脑配置足够强)
|
173 |
+
|
174 |
+
``` sh
|
175 |
+
# 修改dockerfile
|
176 |
+
cd docs && nano Dockerfile+ChatGLM
|
177 |
+
# How to build | 如何构建 (Dockerfile+ChatGLM在docs路径下,请先cd docs)
|
178 |
+
docker build -t gpt-academic --network=host -f Dockerfile+ChatGLM .
|
179 |
+
# How to run | 如何运行 (1) 直接运行:
|
180 |
+
docker run --rm -it --net=host --gpus=all gpt-academic
|
181 |
+
# How to run | 如何运行 (2) 我想运行之前进容器做一些调整:
|
182 |
+
docker run --rm -it --net=host --gpus=all gpt-academic bash
|
183 |
+
```
|
184 |
+
|
185 |
+
|
186 |
+
## 安装-方法3:其他部署方式
|
187 |
+
|
188 |
+
1. 远程云服务器部署
|
189 |
+
请访问[部署wiki-1](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BA%91%E6%9C%8D%E5%8A%A1%E5%99%A8%E8%BF%9C%E7%A8%8B%E9%83%A8%E7%BD%B2%E6%8C%87%E5%8D%97)
|
190 |
+
|
191 |
+
2. 使用WSL2(Windows Subsystem for Linux 子系统)
|
192 |
+
请访问[部署wiki-2](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BD%BF%E7%94%A8WSL2%EF%BC%88Windows-Subsystem-for-Linux-%E5%AD%90%E7%B3%BB%E7%BB%9F%EF%BC%89%E9%83%A8%E7%BD%B2)
|
193 |
+
|
194 |
+
|
195 |
+
## 安装-代理配置
|
196 |
+
1. 常规方法
|
197 |
+
[配置代理](https://github.com/binary-husky/chatgpt_academic/issues/1)
|
198 |
+
|
199 |
+
2. 纯新手教程
|
200 |
+
[纯新手教程](https://github.com/binary-husky/chatgpt_academic/wiki/%E4%BB%A3%E7%90%86%E8%BD%AF%E4%BB%B6%E9%97%AE%E9%A2%98%E7%9A%84%E6%96%B0%E6%89%8B%E8%A7%A3%E5%86%B3%E6%96%B9%E6%B3%95%EF%BC%88%E6%96%B9%E6%B3%95%E5%8F%AA%E9%80%82%E7%94%A8%E4%BA%8E%E6%96%B0%E6%89%8B%EF%BC%89)
|
201 |
+
|
202 |
+
|
203 |
+
---
|
204 |
+
|
205 |
+
## 自定义新的便捷按钮(学术快捷键自定义)
|
206 |
+
任意文本编辑器打开`core_functional.py`,添加条目如下,然后重启程序即可。(如果按钮已经添加成功并可见,那么前缀、后缀都支持热修改,无需重启程序即可生效。)
|
207 |
+
例如
|
208 |
+
```
|
209 |
+
"超级英译中": {
|
210 |
+
# 前缀,会被加在你的输入之前。例如,用来描述你的要求,例如翻译、解释代码、润色等等
|
211 |
+
"Prefix": "请翻译把下面一段内容成中文,然后用一个markdown表格逐一解释文中出现的专有名词:\n\n",
|
212 |
+
|
213 |
+
# 后缀,会被加在你的输入之后。例如,配合前缀可以把你的输入内容用引号圈起来。
|
214 |
+
"Suffix": "",
|
215 |
+
},
|
216 |
+
```
|
217 |
+
<div align="center">
|
218 |
+
<img src="https://user-images.githubusercontent.com/96192199/226899272-477c2134-ed71-4326-810c-29891fe4a508.png" width="500" >
|
219 |
+
</div>
|
220 |
+
|
221 |
+
---
|
222 |
+
|
223 |
+
|
224 |
+
## 部分功能展示
|
225 |
+
|
226 |
+
### 图片显示:
|
227 |
+
|
228 |
+
<div align="center">
|
229 |
+
<img src="https://user-images.githubusercontent.com/96192199/228737599-bf0a9d9c-1808-4f43-ae15-dfcc7af0f295.png" width="800" >
|
230 |
+
</div>
|
231 |
+
|
232 |
+
|
233 |
+
### 如果一个程序能够读懂并剖析自己:
|
234 |
+
|
235 |
+
<div align="center">
|
236 |
+
<img src="https://user-images.githubusercontent.com/96192199/226936850-c77d7183-0749-4c1c-9875-fd4891842d0c.png" width="800" >
|
237 |
+
</div>
|
238 |
+
|
239 |
+
<div align="center">
|
240 |
+
<img src="https://user-images.githubusercontent.com/96192199/226936618-9b487e4b-ab5b-4b6e-84c6-16942102e917.png" width="800" >
|
241 |
+
</div>
|
242 |
+
|
243 |
+
### 其他任意Python/Cpp项目剖析:
|
244 |
+
<div align="center">
|
245 |
+
<img src="https://user-images.githubusercontent.com/96192199/226935232-6b6a73ce-8900-4aee-93f9-733c7e6fef53.png" width="800" >
|
246 |
+
</div>
|
247 |
+
|
248 |
+
<div align="center">
|
249 |
+
<img src="https://user-images.githubusercontent.com/96192199/226969067-968a27c1-1b9c-486b-8b81-ab2de8d3f88a.png" width="800" >
|
250 |
+
</div>
|
251 |
+
|
252 |
+
### Latex论文一键阅读理解与摘要生成
|
253 |
+
<div align="center">
|
254 |
+
<img src="https://user-images.githubusercontent.com/96192199/227504406-86ab97cd-f208-41c3-8e4a-7000e51cf980.png" width="800" >
|
255 |
+
</div>
|
256 |
+
|
257 |
+
### 自动报告生成
|
258 |
+
<div align="center">
|
259 |
+
<img src="https://user-images.githubusercontent.com/96192199/227503770-fe29ce2c-53fd-47b0-b0ff-93805f0c2ff4.png" height="300" >
|
260 |
+
<img src="https://user-images.githubusercontent.com/96192199/227504617-7a497bb3-0a2a-4b50-9a8a-95ae60ea7afd.png" height="300" >
|
261 |
+
<img src="https://user-images.githubusercontent.com/96192199/227504005-efeaefe0-b687-49d0-bf95-2d7b7e66c348.png" height="300" >
|
262 |
+
</div>
|
263 |
+
|
264 |
+
### 模块化功能设计
|
265 |
+
<div align="center">
|
266 |
+
<img src="https://user-images.githubusercontent.com/96192199/229288270-093643c1-0018-487a-81e6-1d7809b6e90f.png" height="400" >
|
267 |
+
<img src="https://user-images.githubusercontent.com/96192199/227504931-19955f78-45cd-4d1c-adac-e71e50957915.png" height="400" >
|
268 |
+
</div>
|
269 |
+
|
270 |
+
|
271 |
+
### 源代码转译英文
|
272 |
+
|
273 |
+
<div align="center">
|
274 |
+
<img src="https://user-images.githubusercontent.com/96192199/229720562-fe6c3508-6142-4635-a83d-21eb3669baee.png" height="400" >
|
275 |
+
</div>
|
276 |
+
|
277 |
+
## Todo 与 版本规划:
|
278 |
+
- version 3.2+ (todo): 函数插件支持更多参数接口
|
279 |
+
- version 3.1: 支持同时问询多个gpt模型!支持api2d,支持多个apikey负载均衡
|
280 |
+
- version 3.0: 对chatglm和其他小型llm的支持
|
281 |
+
- version 2.6: 重构了插件结构,提高了交互性,加入更多插件
|
282 |
+
- version 2.5: 自更新,解决总结大工程源代码时文本过长、token溢出的问题
|
283 |
+
- version 2.4: (1)新增PDF全文翻译功能; (2)新增输入区切换位置的功能; (3)新增垂直布局选项; (4)多线程函数插件优化。
|
284 |
+
- version 2.3: 增强多线程交互性
|
285 |
+
- version 2.2: 函数插件支持热重载
|
286 |
+
- version 2.1: 可折叠式布局
|
287 |
+
- version 2.0: 引入模块化函数插件
|
288 |
+
- version 1.0: 基础功能
|
289 |
+
|
290 |
+
## 参考与学习
|
291 |
+
|
292 |
+
```
|
293 |
+
代码中参考了很多其他优秀项目中的设计,主要包括:
|
294 |
+
|
295 |
+
# 借鉴项目1:借鉴了ChuanhuChatGPT中诸多技巧
|
296 |
+
https://github.com/GaiZhenbiao/ChuanhuChatGPT
|
297 |
+
|
298 |
+
# 借鉴项目2:清华ChatGLM-6B:
|
299 |
+
https://github.com/THUDM/ChatGLM-6B
|
300 |
+
```
|
check_proxy.py
ADDED
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
def check_proxy(proxies):
|
3 |
+
import requests
|
4 |
+
proxies_https = proxies['https'] if proxies is not None else '无'
|
5 |
+
try:
|
6 |
+
response = requests.get("https://ipapi.co/json/",
|
7 |
+
proxies=proxies, timeout=4)
|
8 |
+
data = response.json()
|
9 |
+
print(f'查询代理的地理位置,返回的结果是{data}')
|
10 |
+
if 'country_name' in data:
|
11 |
+
country = data['country_name']
|
12 |
+
result = f"代理配置 {proxies_https}, 代理所在地:{country}"
|
13 |
+
elif 'error' in data:
|
14 |
+
result = f"代理配置 {proxies_https}, 代理所在地:未知,IP查询频率受限"
|
15 |
+
print(result)
|
16 |
+
return result
|
17 |
+
except:
|
18 |
+
result = f"代理配置 {proxies_https}, 代理所在地查询超时,代理可能无效"
|
19 |
+
print(result)
|
20 |
+
return result
|
21 |
+
|
22 |
+
|
23 |
+
def backup_and_download(current_version, remote_version):
|
24 |
+
"""
|
25 |
+
一键更新协议:备份和下载
|
26 |
+
"""
|
27 |
+
from toolbox import get_conf
|
28 |
+
import shutil
|
29 |
+
import os
|
30 |
+
import requests
|
31 |
+
import zipfile
|
32 |
+
os.makedirs(f'./history', exist_ok=True)
|
33 |
+
backup_dir = f'./history/backup-{current_version}/'
|
34 |
+
new_version_dir = f'./history/new-version-{remote_version}/'
|
35 |
+
if os.path.exists(new_version_dir):
|
36 |
+
return new_version_dir
|
37 |
+
os.makedirs(new_version_dir)
|
38 |
+
shutil.copytree('./', backup_dir, ignore=lambda x, y: ['history'])
|
39 |
+
proxies, = get_conf('proxies')
|
40 |
+
r = requests.get(
|
41 |
+
'https://github.com/binary-husky/chatgpt_academic/archive/refs/heads/master.zip', proxies=proxies, stream=True)
|
42 |
+
zip_file_path = backup_dir+'/master.zip'
|
43 |
+
with open(zip_file_path, 'wb+') as f:
|
44 |
+
f.write(r.content)
|
45 |
+
dst_path = new_version_dir
|
46 |
+
with zipfile.ZipFile(zip_file_path, "r") as zip_ref:
|
47 |
+
for zip_info in zip_ref.infolist():
|
48 |
+
dst_file_path = os.path.join(dst_path, zip_info.filename)
|
49 |
+
if os.path.exists(dst_file_path):
|
50 |
+
os.remove(dst_file_path)
|
51 |
+
zip_ref.extract(zip_info, dst_path)
|
52 |
+
return new_version_dir
|
53 |
+
|
54 |
+
|
55 |
+
def patch_and_restart(path):
|
56 |
+
"""
|
57 |
+
一键更新协议:覆盖和重启
|
58 |
+
"""
|
59 |
+
import distutils
|
60 |
+
import shutil
|
61 |
+
import os
|
62 |
+
import sys
|
63 |
+
import time
|
64 |
+
from colorful import print亮黄, print亮绿, print亮红
|
65 |
+
# if not using config_private, move origin config.py as config_private.py
|
66 |
+
if not os.path.exists('config_private.py'):
|
67 |
+
print亮黄('由于您没有设置config_private.py私密配置,现将您的现有配置移动至config_private.py以防止配置丢失,',
|
68 |
+
'另外您可以随时在history子文件夹下找回旧版的程序。')
|
69 |
+
shutil.copyfile('config.py', 'config_private.py')
|
70 |
+
distutils.dir_util.copy_tree(path+'/chatgpt_academic-master', './')
|
71 |
+
import subprocess
|
72 |
+
print亮绿('代码已经更新,即将更新pip包依赖……')
|
73 |
+
for i in reversed(range(5)): time.sleep(1); print(i)
|
74 |
+
try:
|
75 |
+
subprocess.check_call([sys.executable, '-m', 'pip', 'install', '-r', 'requirements.txt'])
|
76 |
+
except:
|
77 |
+
print亮红('pip包依赖安装出现问题,需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。')
|
78 |
+
print亮绿('更新完成,您可以随时在history子文件夹下找回旧版的程序,5s之后重启')
|
79 |
+
print亮红('假如重启失败,您可能需要手动安装新增的依赖库 `python -m pip install -r requirements.txt`,然后在用常规的`python main.py`的方式启动。')
|
80 |
+
print(' ------------------------------ -----------------------------------')
|
81 |
+
for i in reversed(range(8)): time.sleep(1); print(i)
|
82 |
+
os.execl(sys.executable, sys.executable, *sys.argv)
|
83 |
+
|
84 |
+
|
85 |
+
def get_current_version():
|
86 |
+
import json
|
87 |
+
try:
|
88 |
+
with open('./version', 'r', encoding='utf8') as f:
|
89 |
+
current_version = json.loads(f.read())['version']
|
90 |
+
except:
|
91 |
+
current_version = ""
|
92 |
+
return current_version
|
93 |
+
|
94 |
+
|
95 |
+
def auto_update():
|
96 |
+
"""
|
97 |
+
一键更新协议:查询版本和用户意见
|
98 |
+
"""
|
99 |
+
try:
|
100 |
+
from toolbox import get_conf
|
101 |
+
import requests
|
102 |
+
import time
|
103 |
+
import json
|
104 |
+
proxies, = get_conf('proxies')
|
105 |
+
response = requests.get(
|
106 |
+
"https://raw.githubusercontent.com/binary-husky/chatgpt_academic/master/version", proxies=proxies, timeout=5)
|
107 |
+
remote_json_data = json.loads(response.text)
|
108 |
+
remote_version = remote_json_data['version']
|
109 |
+
if remote_json_data["show_feature"]:
|
110 |
+
new_feature = "新功能:" + remote_json_data["new_feature"]
|
111 |
+
else:
|
112 |
+
new_feature = ""
|
113 |
+
with open('./version', 'r', encoding='utf8') as f:
|
114 |
+
current_version = f.read()
|
115 |
+
current_version = json.loads(current_version)['version']
|
116 |
+
if (remote_version - current_version) >= 0.01:
|
117 |
+
from colorful import print亮黄
|
118 |
+
print亮黄(
|
119 |
+
f'\n新版本可用。新版本:{remote_version},当前版本:{current_version}。{new_feature}')
|
120 |
+
print('(1)Github更新地址:\nhttps://github.com/binary-husky/chatgpt_academic\n')
|
121 |
+
user_instruction = input('(2)是否一键更新代码(Y+回车=确认,输入其他/无输入+回车=不更新)?')
|
122 |
+
if user_instruction in ['Y', 'y']:
|
123 |
+
path = backup_and_download(current_version, remote_version)
|
124 |
+
try:
|
125 |
+
patch_and_restart(path)
|
126 |
+
except:
|
127 |
+
print('更新失败。')
|
128 |
+
else:
|
129 |
+
print('自动更新程序:已禁用')
|
130 |
+
return
|
131 |
+
else:
|
132 |
+
return
|
133 |
+
except:
|
134 |
+
print('自动更新程序:已禁用')
|
135 |
+
|
136 |
+
def warm_up_modules():
|
137 |
+
print('正在执行一些模块的预热...')
|
138 |
+
from request_llm.bridge_all import model_info
|
139 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
140 |
+
enc.encode("模块预热", disallowed_special=())
|
141 |
+
enc = model_info["gpt-4"]['tokenizer']
|
142 |
+
enc.encode("模块预热", disallowed_special=())
|
143 |
+
|
144 |
+
if __name__ == '__main__':
|
145 |
+
import os
|
146 |
+
os.environ['no_proxy'] = '*' # 避免代理网络产生意外污染
|
147 |
+
from toolbox import get_conf
|
148 |
+
proxies, = get_conf('proxies')
|
149 |
+
check_proxy(proxies)
|
colorful.py
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import platform
|
2 |
+
from sys import stdout
|
3 |
+
|
4 |
+
if platform.system()=="Linux":
|
5 |
+
pass
|
6 |
+
else:
|
7 |
+
from colorama import init
|
8 |
+
init()
|
9 |
+
|
10 |
+
# Do you like the elegance of Chinese characters?
|
11 |
+
def print红(*kw,**kargs):
|
12 |
+
print("\033[0;31m",*kw,"\033[0m",**kargs)
|
13 |
+
def print绿(*kw,**kargs):
|
14 |
+
print("\033[0;32m",*kw,"\033[0m",**kargs)
|
15 |
+
def print黄(*kw,**kargs):
|
16 |
+
print("\033[0;33m",*kw,"\033[0m",**kargs)
|
17 |
+
def print蓝(*kw,**kargs):
|
18 |
+
print("\033[0;34m",*kw,"\033[0m",**kargs)
|
19 |
+
def print紫(*kw,**kargs):
|
20 |
+
print("\033[0;35m",*kw,"\033[0m",**kargs)
|
21 |
+
def print靛(*kw,**kargs):
|
22 |
+
print("\033[0;36m",*kw,"\033[0m",**kargs)
|
23 |
+
|
24 |
+
def print亮红(*kw,**kargs):
|
25 |
+
print("\033[1;31m",*kw,"\033[0m",**kargs)
|
26 |
+
def print亮绿(*kw,**kargs):
|
27 |
+
print("\033[1;32m",*kw,"\033[0m",**kargs)
|
28 |
+
def print亮黄(*kw,**kargs):
|
29 |
+
print("\033[1;33m",*kw,"\033[0m",**kargs)
|
30 |
+
def print亮蓝(*kw,**kargs):
|
31 |
+
print("\033[1;34m",*kw,"\033[0m",**kargs)
|
32 |
+
def print亮紫(*kw,**kargs):
|
33 |
+
print("\033[1;35m",*kw,"\033[0m",**kargs)
|
34 |
+
def print亮靛(*kw,**kargs):
|
35 |
+
print("\033[1;36m",*kw,"\033[0m",**kargs)
|
36 |
+
|
37 |
+
|
38 |
+
|
39 |
+
def print亮红(*kw,**kargs):
|
40 |
+
print("\033[1;31m",*kw,"\033[0m",**kargs)
|
41 |
+
def print亮绿(*kw,**kargs):
|
42 |
+
print("\033[1;32m",*kw,"\033[0m",**kargs)
|
43 |
+
def print亮黄(*kw,**kargs):
|
44 |
+
print("\033[1;33m",*kw,"\033[0m",**kargs)
|
45 |
+
def print亮蓝(*kw,**kargs):
|
46 |
+
print("\033[1;34m",*kw,"\033[0m",**kargs)
|
47 |
+
def print亮紫(*kw,**kargs):
|
48 |
+
print("\033[1;35m",*kw,"\033[0m",**kargs)
|
49 |
+
def print亮靛(*kw,**kargs):
|
50 |
+
print("\033[1;36m",*kw,"\033[0m",**kargs)
|
51 |
+
|
52 |
+
print_red = print红
|
53 |
+
print_green = print绿
|
54 |
+
print_yellow = print黄
|
55 |
+
print_blue = print蓝
|
56 |
+
print_purple = print紫
|
57 |
+
print_indigo = print靛
|
58 |
+
|
59 |
+
print_bold_red = print亮红
|
60 |
+
print_bold_green = print亮绿
|
61 |
+
print_bold_yellow = print亮黄
|
62 |
+
print_bold_blue = print亮蓝
|
63 |
+
print_bold_purple = print亮紫
|
64 |
+
print_bold_indigo = print亮靛
|
65 |
+
|
66 |
+
if not stdout.isatty():
|
67 |
+
# redirection, avoid a fucked up log file
|
68 |
+
print红 = print
|
69 |
+
print绿 = print
|
70 |
+
print黄 = print
|
71 |
+
print蓝 = print
|
72 |
+
print紫 = print
|
73 |
+
print靛 = print
|
74 |
+
print亮红 = print
|
75 |
+
print亮绿 = print
|
76 |
+
print亮黄 = print
|
77 |
+
print亮蓝 = print
|
78 |
+
print亮紫 = print
|
79 |
+
print亮靛 = print
|
80 |
+
print_red = print
|
81 |
+
print_green = print
|
82 |
+
print_yellow = print
|
83 |
+
print_blue = print
|
84 |
+
print_purple = print
|
85 |
+
print_indigo = print
|
86 |
+
print_bold_red = print
|
87 |
+
print_bold_green = print
|
88 |
+
print_bold_yellow = print
|
89 |
+
print_bold_blue = print
|
90 |
+
print_bold_purple = print
|
91 |
+
print_bold_indigo = print
|
config.py
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# [step 1]>> 例如: API_KEY = "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" (此key无效)
|
2 |
+
API_KEY = "sk-此处填API密钥" # 可同时填写多个API-KEY,用英文逗号分割,例如API_KEY = "sk-openaikey1,sk-openaikey2,fkxxxx-api2dkey1,fkxxxx-api2dkey2"
|
3 |
+
|
4 |
+
# [step 2]>> 改为True应用代理,如果直接在海外服务器部署,此处不修改
|
5 |
+
USE_PROXY = False
|
6 |
+
if USE_PROXY:
|
7 |
+
# 填写格式是 [协议]:// [地址] :[端口],填写之前不要忘记把USE_PROXY改成True,如果直接在海外服务器部署,此处不修改
|
8 |
+
# 例如 "socks5h://localhost:11284"
|
9 |
+
# [协议] 常见协议无非socks5h/http; 例如 v2**y 和 ss* 的默认本地协议是socks5h; 而cl**h 的默认本地协议是http
|
10 |
+
# [地址] 懂的都懂,不懂就填localhost或者127.0.0.1肯定错不了(localhost意思是代理软件安装在本机上)
|
11 |
+
# [端口] 在代理软件的设置里找。虽然不同的代理软件界面不一样,但端口号都应该在最显眼的位置上
|
12 |
+
|
13 |
+
# 代理网络的地址,打开你的科学上网软件查看代理的协议(socks5/http)、地址(localhost)和端口(11284)
|
14 |
+
proxies = {
|
15 |
+
# [协议]:// [地址] :[端口]
|
16 |
+
"http": "socks5h://localhost:11284",
|
17 |
+
"https": "socks5h://localhost:11284",
|
18 |
+
}
|
19 |
+
else:
|
20 |
+
proxies = None
|
21 |
+
|
22 |
+
# [step 3]>> 多线程函数插件中,默认允许多少路线程同时访问OpenAI。Free trial users的限制是每分钟3次,Pay-as-you-go users的限制是每分钟3500次
|
23 |
+
# 一言以蔽之:免费用户填3,OpenAI绑了信用卡的用户可以填 16 或者更高。提高限制请查询:https://platform.openai.com/docs/guides/rate-limits/overview
|
24 |
+
DEFAULT_WORKER_NUM = 3
|
25 |
+
|
26 |
+
|
27 |
+
# [step 4]>> 以下配置可以优化体验,但大部分场合下并不需要修改
|
28 |
+
# 对话窗的高度
|
29 |
+
CHATBOT_HEIGHT = 1115
|
30 |
+
|
31 |
+
# 代码高亮
|
32 |
+
CODE_HIGHLIGHT = True
|
33 |
+
|
34 |
+
# 窗口布局
|
35 |
+
LAYOUT = "LEFT-RIGHT" # "LEFT-RIGHT"(左右布局) # "TOP-DOWN"(上下布局)
|
36 |
+
|
37 |
+
# 发送请求到OpenAI后,等待多久判定为超时
|
38 |
+
TIMEOUT_SECONDS = 30
|
39 |
+
|
40 |
+
# 网页的端口, -1代表随机端口
|
41 |
+
WEB_PORT = -1
|
42 |
+
|
43 |
+
# 如果OpenAI不响应(网络卡顿、代理失败、KEY失效),重试的次数限制
|
44 |
+
MAX_RETRY = 2
|
45 |
+
|
46 |
+
# OpenAI模型选择是(gpt4现在只对申请成功的人开放)
|
47 |
+
LLM_MODEL = "gpt-3.5-turbo" # 可选 "chatglm"
|
48 |
+
AVAIL_LLM_MODELS = ["gpt-3.5-turbo", "gpt-4", "api2d-gpt-4", "api2d-gpt-3.5-turbo"]
|
49 |
+
|
50 |
+
# 本地LLM模型如ChatGLM的执行方式 CPU/GPU
|
51 |
+
LOCAL_MODEL_DEVICE = "cpu" # 可选 "cuda"
|
52 |
+
|
53 |
+
# 设置gradio的并行线程数(不需要修改)
|
54 |
+
CONCURRENT_COUNT = 100
|
55 |
+
|
56 |
+
# 设置用户名和密码(不需要修改)(相关功能不稳定,与gradio版本和网络都相关,如果本地使用不建议加这个)
|
57 |
+
# [("username", "password"), ("username2", "password2"), ...]
|
58 |
+
AUTHENTICATION = []
|
core_functional.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 'primary' 颜色对应 theme.py 中的 primary_hue
|
2 |
+
# 'secondary' 颜色对应 theme.py 中的 neutral_hue
|
3 |
+
# 'stop' 颜色对应 theme.py 中的 color_er
|
4 |
+
# 默认按钮颜色是 secondary
|
5 |
+
from toolbox import clear_line_break
|
6 |
+
|
7 |
+
|
8 |
+
def get_core_functions():
|
9 |
+
return {
|
10 |
+
"英语学术润色": {
|
11 |
+
# 前言
|
12 |
+
"Prefix": r"Below is a paragraph from an academic paper. Polish the writing to meet the academic style, " +
|
13 |
+
r"improve the spelling, grammar, clarity, concision and overall readability. When necessary, rewrite the whole sentence. " +
|
14 |
+
r"Furthermore, list all modification and explain the reasons to do so in markdown table." + "\n\n",
|
15 |
+
# 后语
|
16 |
+
"Suffix": r"",
|
17 |
+
"Color": r"secondary", # 按钮颜色
|
18 |
+
},
|
19 |
+
"中文学术润色": {
|
20 |
+
"Prefix": r"作为一名中文学术论文写作改进助理,你的任务是改进所提供文本的拼写、语法、清晰、简洁和整体可读性," +
|
21 |
+
r"同时分解长句,减少重复,并提供改进建议。请只提供文本的更正版本,避免包括解释。请编辑以下文本" + "\n\n",
|
22 |
+
"Suffix": r"",
|
23 |
+
},
|
24 |
+
"查找语法错误": {
|
25 |
+
"Prefix": r"Can you help me ensure that the grammar and the spelling is correct? " +
|
26 |
+
r"Do not try to polish the text, if no mistake is found, tell me that this paragraph is good." +
|
27 |
+
r"If you find grammar or spelling mistakes, please list mistakes you find in a two-column markdown table, " +
|
28 |
+
r"put the original text the first column, " +
|
29 |
+
r"put the corrected text in the second column and highlight the key words you fixed.""\n"
|
30 |
+
r"Example:""\n"
|
31 |
+
r"Paragraph: How is you? Do you knows what is it?""\n"
|
32 |
+
r"| Original sentence | Corrected sentence |""\n"
|
33 |
+
r"| :--- | :--- |""\n"
|
34 |
+
r"| How **is** you? | How **are** you? |""\n"
|
35 |
+
r"| Do you **knows** what **is** **it**? | Do you **know** what **it** **is** ? |""\n"
|
36 |
+
r"Below is a paragraph from an academic paper. "
|
37 |
+
r"You need to report all grammar and spelling mistakes as the example before."
|
38 |
+
+ "\n\n",
|
39 |
+
"Suffix": r"",
|
40 |
+
"PreProcess": clear_line_break, # 预处理:清除换行符
|
41 |
+
},
|
42 |
+
"中译英": {
|
43 |
+
"Prefix": r"Please translate following sentence to English:" + "\n\n",
|
44 |
+
"Suffix": r"",
|
45 |
+
},
|
46 |
+
"学术中英互译": {
|
47 |
+
"Prefix": r"I want you to act as a scientific English-Chinese translator, " +
|
48 |
+
r"I will provide you with some paragraphs in one language " +
|
49 |
+
r"and your task is to accurately and academically translate the paragraphs only into the other language. " +
|
50 |
+
r"Do not repeat the original provided paragraphs after translation. " +
|
51 |
+
r"You should use artificial intelligence tools, " +
|
52 |
+
r"such as natural language processing, and rhetorical knowledge " +
|
53 |
+
r"and experience about effective writing techniques to reply. " +
|
54 |
+
r"I'll give you my paragraphs as follows, tell me what language it is written in, and then translate:" + "\n\n",
|
55 |
+
"Suffix": "",
|
56 |
+
"Color": "secondary",
|
57 |
+
},
|
58 |
+
"英译中": {
|
59 |
+
"Prefix": r"翻译成地道的中文:" + "\n\n",
|
60 |
+
"Suffix": r"",
|
61 |
+
},
|
62 |
+
"找图片": {
|
63 |
+
"Prefix": r"我需要你找一张网络图片。使用Unsplash API(https://source.unsplash.com/960x640/?<英语关键词>)获取图片URL," +
|
64 |
+
r"然后请使用Markdown格式封装,并且不要有反斜线,不要用代码块。现在,请按以下描述给我发送图片:" + "\n\n",
|
65 |
+
"Suffix": r"",
|
66 |
+
},
|
67 |
+
"解释代码": {
|
68 |
+
"Prefix": r"请解释以下代码:" + "\n```\n",
|
69 |
+
"Suffix": "\n```\n",
|
70 |
+
},
|
71 |
+
}
|
crazy_functional.py
ADDED
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import HotReload # HotReload 的意思是热更新,修改函数插件后,不需要重启程序,代码直接生效
|
2 |
+
|
3 |
+
|
4 |
+
def get_crazy_functions():
|
5 |
+
###################### 第一组插件 ###########################
|
6 |
+
from crazy_functions.读文章写摘要 import 读文章写摘要
|
7 |
+
from crazy_functions.生成函数注释 import 批量生成函数注释
|
8 |
+
from crazy_functions.解析项目源代码 import 解析项目本身
|
9 |
+
from crazy_functions.解析项目源代码 import 解析一个Python项目
|
10 |
+
from crazy_functions.解析项目源代码 import 解析一个C项目的头文件
|
11 |
+
from crazy_functions.解析项目源代码 import 解析一个C项目
|
12 |
+
from crazy_functions.解析项目源代码 import 解析一个Golang项目
|
13 |
+
from crazy_functions.解析项目源代码 import 解析一个Java项目
|
14 |
+
from crazy_functions.解析项目源代码 import 解析一个Rect项目
|
15 |
+
from crazy_functions.高级功能函数模板 import 高阶功能模板函数
|
16 |
+
from crazy_functions.代码重写为全英文_多线程 import 全项目切换英文
|
17 |
+
from crazy_functions.Latex全文润色 import Latex英文润色
|
18 |
+
from crazy_functions.询问多个大语言模型 import 同时问询
|
19 |
+
from crazy_functions.解析项目源代码 import 解析一个Lua项目
|
20 |
+
from crazy_functions.解析项目源代码 import 解析一个CSharp项目
|
21 |
+
from crazy_functions.总结word文档 import 总结word文档
|
22 |
+
function_plugins = {
|
23 |
+
|
24 |
+
"解析整个Python项目": {
|
25 |
+
"Color": "stop", # 按钮颜色
|
26 |
+
"Function": HotReload(解析一个Python项目)
|
27 |
+
},
|
28 |
+
"批量总结Word文档": {
|
29 |
+
"Color": "stop",
|
30 |
+
"Function": HotReload(总结word文档)
|
31 |
+
},
|
32 |
+
"解析整个C++项目头文件": {
|
33 |
+
"Color": "stop", # 按钮颜色
|
34 |
+
"AsButton": False, # 加入下拉菜单中
|
35 |
+
"Function": HotReload(解析一个C项目的头文件)
|
36 |
+
},
|
37 |
+
"解析整个C++项目(.cpp/.hpp/.c/.h)": {
|
38 |
+
"Color": "stop", # 按钮颜色
|
39 |
+
"AsButton": False, # 加入下拉菜单中
|
40 |
+
"Function": HotReload(解析一个C项目)
|
41 |
+
},
|
42 |
+
"解析整个Go项目": {
|
43 |
+
"Color": "stop", # 按钮颜色
|
44 |
+
"AsButton": False, # 加入下拉菜单中
|
45 |
+
"Function": HotReload(解析一个Golang项目)
|
46 |
+
},
|
47 |
+
"解析整个Java项目": {
|
48 |
+
"Color": "stop", # 按钮颜色
|
49 |
+
"AsButton": False, # 加入下拉菜单中
|
50 |
+
"Function": HotReload(解析一个Java项目)
|
51 |
+
},
|
52 |
+
"解析整个React项目": {
|
53 |
+
"Color": "stop", # 按钮颜色
|
54 |
+
"AsButton": False, # 加入下拉菜单中
|
55 |
+
"Function": HotReload(解析一个Rect项目)
|
56 |
+
},
|
57 |
+
"解析整个Lua项目": {
|
58 |
+
"Color": "stop", # 按钮颜色
|
59 |
+
"AsButton": False, # 加入下拉菜单中
|
60 |
+
"Function": HotReload(解析一个Lua项目)
|
61 |
+
},
|
62 |
+
"解析整个CSharp项目": {
|
63 |
+
"Color": "stop", # 按钮颜色
|
64 |
+
"AsButton": False, # 加入下拉菜单中
|
65 |
+
"Function": HotReload(解析一个CSharp项目)
|
66 |
+
},
|
67 |
+
"读Tex论文写摘要": {
|
68 |
+
"Color": "stop", # 按钮颜色
|
69 |
+
"Function": HotReload(读文章写摘要)
|
70 |
+
},
|
71 |
+
"批量生成函数注释": {
|
72 |
+
"Color": "stop", # 按钮颜色
|
73 |
+
"Function": HotReload(批量生成函数注释)
|
74 |
+
},
|
75 |
+
"[多线程Demo] 解析此项目本身(源码自译解)": {
|
76 |
+
"Function": HotReload(解析项目本身)
|
77 |
+
},
|
78 |
+
"[多线程demo] 把本项目源代码切换成全英文": {
|
79 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
80 |
+
"AsButton": False, # 加入下拉菜单中
|
81 |
+
"Function": HotReload(全项目切换英文)
|
82 |
+
},
|
83 |
+
"[函数插件模板Demo] 历史上的今天": {
|
84 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
85 |
+
"Function": HotReload(高阶功能模板函数)
|
86 |
+
},
|
87 |
+
|
88 |
+
}
|
89 |
+
###################### 第二组插件 ###########################
|
90 |
+
# [第二组插件]: 经过充分测试
|
91 |
+
from crazy_functions.批量总结PDF文档 import 批量总结PDF文档
|
92 |
+
from crazy_functions.批量总结PDF文档pdfminer import 批量总结PDF文档pdfminer
|
93 |
+
from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
|
94 |
+
from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
|
95 |
+
from crazy_functions.理解PDF文档内容 import 理解PDF文档内容标准文件输入
|
96 |
+
from crazy_functions.Latex全文润色 import Latex中文润色
|
97 |
+
from crazy_functions.Latex全文翻译 import Latex中译英
|
98 |
+
from crazy_functions.Latex全文翻译 import Latex英译中
|
99 |
+
from crazy_functions.批量Markdown翻译 import Markdown中译英
|
100 |
+
from crazy_functions.批量Markdown翻译 import Markdown英译中
|
101 |
+
|
102 |
+
function_plugins.update({
|
103 |
+
"批量翻译PDF文档(多线程)": {
|
104 |
+
"Color": "stop",
|
105 |
+
"AsButton": True, # 加入下拉菜单中
|
106 |
+
"Function": HotReload(批量翻译PDF文档)
|
107 |
+
},
|
108 |
+
"询问多个GPT模型": {
|
109 |
+
"Color": "stop", # 按钮颜色
|
110 |
+
"Function": HotReload(同时问询)
|
111 |
+
},
|
112 |
+
"[测试功能] 批量总结PDF文档": {
|
113 |
+
"Color": "stop",
|
114 |
+
"AsButton": False, # 加入下拉菜单中
|
115 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
116 |
+
"Function": HotReload(批量总结PDF文档)
|
117 |
+
},
|
118 |
+
"[测试功能] 批量总结PDF文档pdfminer": {
|
119 |
+
"Color": "stop",
|
120 |
+
"AsButton": False, # 加入下拉菜单中
|
121 |
+
"Function": HotReload(批量总结PDF文档pdfminer)
|
122 |
+
},
|
123 |
+
"谷歌学术检索助手(输入谷歌学术搜索页url)": {
|
124 |
+
"Color": "stop",
|
125 |
+
"AsButton": False, # 加入下拉菜单中
|
126 |
+
"Function": HotReload(谷歌检索小助手)
|
127 |
+
},
|
128 |
+
|
129 |
+
"理解PDF文档内容 (模仿ChatPDF)": {
|
130 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
131 |
+
"Color": "stop",
|
132 |
+
"AsButton": False, # 加入下拉菜单中
|
133 |
+
"Function": HotReload(理解PDF文档内容标准文件输入)
|
134 |
+
},
|
135 |
+
"[测试功能] 英文Latex项目全文润色(输入路径或上传压缩包)": {
|
136 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
137 |
+
"Color": "stop",
|
138 |
+
"AsButton": False, # 加入下拉菜单中
|
139 |
+
"Function": HotReload(Latex英文润色)
|
140 |
+
},
|
141 |
+
"[测试功能] 中文Latex项目全文润色(输入路径或上传压缩包)": {
|
142 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
143 |
+
"Color": "stop",
|
144 |
+
"AsButton": False, # 加入下拉菜单中
|
145 |
+
"Function": HotReload(Latex中文润色)
|
146 |
+
},
|
147 |
+
"[测试功能] Latex项目全文中译英(输入路径或上传压缩包)": {
|
148 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
149 |
+
"Color": "stop",
|
150 |
+
"AsButton": False, # 加入下拉菜单中
|
151 |
+
"Function": HotReload(Latex中译英)
|
152 |
+
},
|
153 |
+
"[测试功能] Latex项目全文英译中(输入路径或上传压缩包)": {
|
154 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
155 |
+
"Color": "stop",
|
156 |
+
"AsButton": False, # 加入下拉菜单中
|
157 |
+
"Function": HotReload(Latex英译中)
|
158 |
+
},
|
159 |
+
"[测试功能] 批量Markdown中译英(输入路径或上传压缩包)": {
|
160 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
161 |
+
"Color": "stop",
|
162 |
+
"AsButton": False, # 加入下拉菜单中
|
163 |
+
"Function": HotReload(Markdown中译英)
|
164 |
+
},
|
165 |
+
"[测试功能] 批量Markdown英译中(输入路径或上传压缩包)": {
|
166 |
+
# HotReload 的意思是热更新,修改函数插件代码后,不需要重启程序,代码直接生效
|
167 |
+
"Color": "stop",
|
168 |
+
"AsButton": False, # 加入下拉菜单中
|
169 |
+
"Function": HotReload(Markdown英译中)
|
170 |
+
},
|
171 |
+
|
172 |
+
})
|
173 |
+
|
174 |
+
###################### 第三组插件 ###########################
|
175 |
+
# [第三组插件]: 尚未充分测试的函数插件,放在这里
|
176 |
+
try:
|
177 |
+
from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要
|
178 |
+
function_plugins.update({
|
179 |
+
"一键下载arxiv论文并翻译摘要(先在input输入编号,如1812.10695)": {
|
180 |
+
"Color": "stop",
|
181 |
+
"AsButton": False, # 加入下拉菜单中
|
182 |
+
"Function": HotReload(下载arxiv论文并翻译摘要)
|
183 |
+
}
|
184 |
+
})
|
185 |
+
|
186 |
+
except Exception as err:
|
187 |
+
print(f'[下载arxiv论文并翻译摘要] 插件导入失败 {str(err)}')
|
188 |
+
|
189 |
+
|
190 |
+
|
191 |
+
###################### 第n组插件 ###########################
|
192 |
+
return function_plugins
|
crazy_functions/Latex全文润色.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
fast_debug = False
|
4 |
+
|
5 |
+
class PaperFileGroup():
|
6 |
+
def __init__(self):
|
7 |
+
self.file_paths = []
|
8 |
+
self.file_contents = []
|
9 |
+
self.sp_file_contents = []
|
10 |
+
self.sp_file_index = []
|
11 |
+
self.sp_file_tag = []
|
12 |
+
|
13 |
+
# count_token
|
14 |
+
from request_llm.bridge_all import model_info
|
15 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
16 |
+
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
|
17 |
+
self.get_token_num = get_token_num
|
18 |
+
|
19 |
+
def run_file_split(self, max_token_limit=1900):
|
20 |
+
"""
|
21 |
+
将长文本分离开来
|
22 |
+
"""
|
23 |
+
for index, file_content in enumerate(self.file_contents):
|
24 |
+
if self.get_token_num(file_content) < max_token_limit:
|
25 |
+
self.sp_file_contents.append(file_content)
|
26 |
+
self.sp_file_index.append(index)
|
27 |
+
self.sp_file_tag.append(self.file_paths[index])
|
28 |
+
else:
|
29 |
+
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
30 |
+
segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit)
|
31 |
+
for j, segment in enumerate(segments):
|
32 |
+
self.sp_file_contents.append(segment)
|
33 |
+
self.sp_file_index.append(index)
|
34 |
+
self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex")
|
35 |
+
|
36 |
+
print('Segmentation: done')
|
37 |
+
|
38 |
+
def 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'):
|
39 |
+
import time, os, re
|
40 |
+
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
|
41 |
+
|
42 |
+
|
43 |
+
# <-------- 读取Latex文件,删除其中的所有注释 ---------->
|
44 |
+
pfg = PaperFileGroup()
|
45 |
+
|
46 |
+
for index, fp in enumerate(file_manifest):
|
47 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
48 |
+
file_content = f.read()
|
49 |
+
# 定义注释的正则表达式
|
50 |
+
comment_pattern = r'%.*'
|
51 |
+
# 使用正则表达式查找注释,并替换为空字符串
|
52 |
+
clean_tex_content = re.sub(comment_pattern, '', file_content)
|
53 |
+
# 记录删除注释后的文本
|
54 |
+
pfg.file_paths.append(fp)
|
55 |
+
pfg.file_contents.append(clean_tex_content)
|
56 |
+
|
57 |
+
# <-------- 拆分过长的latex文件 ---------->
|
58 |
+
pfg.run_file_split(max_token_limit=1024)
|
59 |
+
n_split = len(pfg.sp_file_contents)
|
60 |
+
|
61 |
+
# <-------- 抽取摘要 ---------->
|
62 |
+
# if language == 'en':
|
63 |
+
# abs_extract_inputs = f"Please write an abstract for this paper"
|
64 |
+
|
65 |
+
# # 单线,获取文章meta信息
|
66 |
+
# paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
67 |
+
# inputs=abs_extract_inputs,
|
68 |
+
# inputs_show_user=f"正在抽取摘要信息。",
|
69 |
+
# llm_kwargs=llm_kwargs,
|
70 |
+
# chatbot=chatbot, history=[],
|
71 |
+
# sys_prompt="Your job is to collect information from materials。",
|
72 |
+
# )
|
73 |
+
|
74 |
+
# <-------- 多线程润色开始 ---------->
|
75 |
+
if language == 'en':
|
76 |
+
inputs_array = ["Below is a section from an academic paper, polish this section to meet the academic standard, improve the grammar, clarity and overall readability, do not modify any latex command such as \section, \cite and equations:" +
|
77 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
78 |
+
inputs_show_user_array = [f"Polish {f}" for f in pfg.sp_file_tag]
|
79 |
+
sys_prompt_array = ["You are a professional academic paper writer." for _ in range(n_split)]
|
80 |
+
elif language == 'zh':
|
81 |
+
inputs_array = [f"以下是一篇学术论文中的一段内容,请将此部分润色以满足学术标准,提高语法、清晰度和整体可读性,不要修改任何LaTeX命令,例如\section,\cite和方程式:" +
|
82 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
83 |
+
inputs_show_user_array = [f"润色 {f}" for f in pfg.sp_file_tag]
|
84 |
+
sys_prompt_array=["你是一位专业的中文学术论文作家。" for _ in range(n_split)]
|
85 |
+
|
86 |
+
|
87 |
+
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
88 |
+
inputs_array=inputs_array,
|
89 |
+
inputs_show_user_array=inputs_show_user_array,
|
90 |
+
llm_kwargs=llm_kwargs,
|
91 |
+
chatbot=chatbot,
|
92 |
+
history_array=[[""] for _ in range(n_split)],
|
93 |
+
sys_prompt_array=sys_prompt_array,
|
94 |
+
# max_workers=5, # 并行任务数量限制,最多同时执行5个,其他的排队等待
|
95 |
+
scroller_max_len = 80
|
96 |
+
)
|
97 |
+
|
98 |
+
# <-------- 整理结果,退出 ---------->
|
99 |
+
create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md"
|
100 |
+
res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name)
|
101 |
+
history = gpt_response_collection
|
102 |
+
chatbot.append((f"{fp}完成了吗?", res))
|
103 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
104 |
+
|
105 |
+
|
106 |
+
@CatchException
|
107 |
+
def Latex英文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
108 |
+
# 基本信息:功能、贡献者
|
109 |
+
chatbot.append([
|
110 |
+
"函数插件功能?",
|
111 |
+
"对整个Latex项目进行润色。函数插件贡献者: Binary-Husky"])
|
112 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
113 |
+
|
114 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
115 |
+
try:
|
116 |
+
import tiktoken
|
117 |
+
except:
|
118 |
+
report_execption(chatbot, history,
|
119 |
+
a=f"解析项目: {txt}",
|
120 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
121 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
122 |
+
return
|
123 |
+
history = [] # 清空历史,以免输入溢出
|
124 |
+
import glob, os
|
125 |
+
if os.path.exists(txt):
|
126 |
+
project_folder = txt
|
127 |
+
else:
|
128 |
+
if txt == "": txt = '空空如也的输入栏'
|
129 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
130 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
131 |
+
return
|
132 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
|
133 |
+
if len(file_manifest) == 0:
|
134 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
|
135 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
136 |
+
return
|
137 |
+
yield from 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en')
|
138 |
+
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
@CatchException
|
145 |
+
def Latex中文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
146 |
+
# 基本信息:功能、贡献者
|
147 |
+
chatbot.append([
|
148 |
+
"函数插件功能?",
|
149 |
+
"对整个Latex项目进行润色。函数插件贡献者: Binary-Husky"])
|
150 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
151 |
+
|
152 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
153 |
+
try:
|
154 |
+
import tiktoken
|
155 |
+
except:
|
156 |
+
report_execption(chatbot, history,
|
157 |
+
a=f"解析项目: {txt}",
|
158 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
159 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
160 |
+
return
|
161 |
+
history = [] # 清空历史,以免输入溢出
|
162 |
+
import glob, os
|
163 |
+
if os.path.exists(txt):
|
164 |
+
project_folder = txt
|
165 |
+
else:
|
166 |
+
if txt == "": txt = '空空如也的输入栏'
|
167 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
168 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
169 |
+
return
|
170 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
|
171 |
+
if len(file_manifest) == 0:
|
172 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
|
173 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
174 |
+
return
|
175 |
+
yield from 多文件润色(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh')
|
crazy_functions/Latex全文翻译.py
ADDED
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
fast_debug = False
|
4 |
+
|
5 |
+
class PaperFileGroup():
|
6 |
+
def __init__(self):
|
7 |
+
self.file_paths = []
|
8 |
+
self.file_contents = []
|
9 |
+
self.sp_file_contents = []
|
10 |
+
self.sp_file_index = []
|
11 |
+
self.sp_file_tag = []
|
12 |
+
|
13 |
+
# count_token
|
14 |
+
from request_llm.bridge_all import model_info
|
15 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
16 |
+
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
|
17 |
+
self.get_token_num = get_token_num
|
18 |
+
|
19 |
+
def run_file_split(self, max_token_limit=1900):
|
20 |
+
"""
|
21 |
+
将长文本分离开来
|
22 |
+
"""
|
23 |
+
for index, file_content in enumerate(self.file_contents):
|
24 |
+
if self.get_token_num(file_content) < max_token_limit:
|
25 |
+
self.sp_file_contents.append(file_content)
|
26 |
+
self.sp_file_index.append(index)
|
27 |
+
self.sp_file_tag.append(self.file_paths[index])
|
28 |
+
else:
|
29 |
+
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
30 |
+
segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit)
|
31 |
+
for j, segment in enumerate(segments):
|
32 |
+
self.sp_file_contents.append(segment)
|
33 |
+
self.sp_file_index.append(index)
|
34 |
+
self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.tex")
|
35 |
+
|
36 |
+
print('Segmentation: done')
|
37 |
+
|
38 |
+
def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'):
|
39 |
+
import time, os, re
|
40 |
+
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
|
41 |
+
|
42 |
+
# <-------- 读取Latex文件,删除其中的所有注释 ---------->
|
43 |
+
pfg = PaperFileGroup()
|
44 |
+
|
45 |
+
for index, fp in enumerate(file_manifest):
|
46 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
47 |
+
file_content = f.read()
|
48 |
+
# 定义注释的正则表达式
|
49 |
+
comment_pattern = r'%.*'
|
50 |
+
# 使用正则表达式查找注释,并替换为空字符串
|
51 |
+
clean_tex_content = re.sub(comment_pattern, '', file_content)
|
52 |
+
# 记录删除注释后的文本
|
53 |
+
pfg.file_paths.append(fp)
|
54 |
+
pfg.file_contents.append(clean_tex_content)
|
55 |
+
|
56 |
+
# <-------- 拆分过长的latex文件 ---------->
|
57 |
+
pfg.run_file_split(max_token_limit=1024)
|
58 |
+
n_split = len(pfg.sp_file_contents)
|
59 |
+
|
60 |
+
# <-------- 抽取摘要 ---------->
|
61 |
+
# if language == 'en':
|
62 |
+
# abs_extract_inputs = f"Please write an abstract for this paper"
|
63 |
+
|
64 |
+
# # 单线,获取文章meta信息
|
65 |
+
# paper_meta_info = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
66 |
+
# inputs=abs_extract_inputs,
|
67 |
+
# inputs_show_user=f"正在抽取摘要信息。",
|
68 |
+
# llm_kwargs=llm_kwargs,
|
69 |
+
# chatbot=chatbot, history=[],
|
70 |
+
# sys_prompt="Your job is to collect information from materials。",
|
71 |
+
# )
|
72 |
+
|
73 |
+
# <-------- 多线程润色开始 ---------->
|
74 |
+
if language == 'en->zh':
|
75 |
+
inputs_array = ["Below is a section from an English academic paper, translate it into Chinese, do not modify any latex command such as \section, \cite and equations:" +
|
76 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
77 |
+
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
|
78 |
+
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
|
79 |
+
elif language == 'zh->en':
|
80 |
+
inputs_array = [f"Below is a section from a Chinese academic paper, translate it into English, do not modify any latex command such as \section, \cite and equations:" +
|
81 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
82 |
+
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
|
83 |
+
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
|
84 |
+
|
85 |
+
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
86 |
+
inputs_array=inputs_array,
|
87 |
+
inputs_show_user_array=inputs_show_user_array,
|
88 |
+
llm_kwargs=llm_kwargs,
|
89 |
+
chatbot=chatbot,
|
90 |
+
history_array=[[""] for _ in range(n_split)],
|
91 |
+
sys_prompt_array=sys_prompt_array,
|
92 |
+
# max_workers=5, # OpenAI所允许的最大并行过载
|
93 |
+
scroller_max_len = 80
|
94 |
+
)
|
95 |
+
|
96 |
+
# <-------- 整理结果,退出 ---------->
|
97 |
+
create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md"
|
98 |
+
res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name)
|
99 |
+
history = gpt_response_collection
|
100 |
+
chatbot.append((f"{fp}完成了吗?", res))
|
101 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
102 |
+
|
103 |
+
|
104 |
+
|
105 |
+
|
106 |
+
|
107 |
+
@CatchException
|
108 |
+
def Latex英译中(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
109 |
+
# 基本信息:功能、贡献者
|
110 |
+
chatbot.append([
|
111 |
+
"函数插件功能?",
|
112 |
+
"对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"])
|
113 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
114 |
+
|
115 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
116 |
+
try:
|
117 |
+
import tiktoken
|
118 |
+
except:
|
119 |
+
report_execption(chatbot, history,
|
120 |
+
a=f"解析项目: {txt}",
|
121 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
122 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
123 |
+
return
|
124 |
+
history = [] # 清空历史,以免输入溢出
|
125 |
+
import glob, os
|
126 |
+
if os.path.exists(txt):
|
127 |
+
project_folder = txt
|
128 |
+
else:
|
129 |
+
if txt == "": txt = '空空如也的输入栏'
|
130 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
131 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
132 |
+
return
|
133 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
|
134 |
+
if len(file_manifest) == 0:
|
135 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
|
136 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
137 |
+
return
|
138 |
+
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en->zh')
|
139 |
+
|
140 |
+
|
141 |
+
|
142 |
+
|
143 |
+
|
144 |
+
@CatchException
|
145 |
+
def Latex中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
146 |
+
# 基本信息:功能、贡献者
|
147 |
+
chatbot.append([
|
148 |
+
"函数插件功能?",
|
149 |
+
"对整个Latex项目进行翻译。函数插件贡献者: Binary-Husky"])
|
150 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
151 |
+
|
152 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
153 |
+
try:
|
154 |
+
import tiktoken
|
155 |
+
except:
|
156 |
+
report_execption(chatbot, history,
|
157 |
+
a=f"解析项目: {txt}",
|
158 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
159 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
160 |
+
return
|
161 |
+
history = [] # 清空历史,以免输入溢出
|
162 |
+
import glob, os
|
163 |
+
if os.path.exists(txt):
|
164 |
+
project_folder = txt
|
165 |
+
else:
|
166 |
+
if txt == "": txt = '空空如也的输入栏'
|
167 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
168 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
169 |
+
return
|
170 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)]
|
171 |
+
if len(file_manifest) == 0:
|
172 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex文件: {txt}")
|
173 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
174 |
+
return
|
175 |
+
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh->en')
|
crazy_functions/__init__.py
ADDED
File without changes
|
crazy_functions/crazy_functions_test.py
ADDED
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
这是什么?
|
3 |
+
这个文件用于函数插件的单元测试
|
4 |
+
运行方法 python crazy_functions/crazy_functions_test.py
|
5 |
+
"""
|
6 |
+
|
7 |
+
def validate_path():
|
8 |
+
import os, sys
|
9 |
+
dir_name = os.path.dirname(__file__)
|
10 |
+
root_dir_assume = os.path.abspath(os.path.dirname(__file__) + '/..')
|
11 |
+
os.chdir(root_dir_assume)
|
12 |
+
sys.path.append(root_dir_assume)
|
13 |
+
|
14 |
+
validate_path() # validate path so you can run from base directory
|
15 |
+
|
16 |
+
from toolbox import get_conf, ChatBotWithCookies
|
17 |
+
proxies, WEB_PORT, LLM_MODEL, CONCURRENT_COUNT, AUTHENTICATION, CHATBOT_HEIGHT, LAYOUT, API_KEY = \
|
18 |
+
get_conf('proxies', 'WEB_PORT', 'LLM_MODEL', 'CONCURRENT_COUNT', 'AUTHENTICATION', 'CHATBOT_HEIGHT', 'LAYOUT', 'API_KEY')
|
19 |
+
|
20 |
+
llm_kwargs = {
|
21 |
+
'api_key': API_KEY,
|
22 |
+
'llm_model': LLM_MODEL,
|
23 |
+
'top_p':1.0,
|
24 |
+
'max_length': None,
|
25 |
+
'temperature':1.0,
|
26 |
+
}
|
27 |
+
plugin_kwargs = { }
|
28 |
+
chatbot = ChatBotWithCookies(llm_kwargs)
|
29 |
+
history = []
|
30 |
+
system_prompt = "Serve me as a writing and programming assistant."
|
31 |
+
web_port = 1024
|
32 |
+
|
33 |
+
|
34 |
+
def test_解析一个Python项目():
|
35 |
+
from crazy_functions.解析项目源代码 import 解析一个Python项目
|
36 |
+
txt = "crazy_functions/test_project/python/dqn"
|
37 |
+
for cookies, cb, hist, msg in 解析一个Python项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
38 |
+
print(cb)
|
39 |
+
|
40 |
+
def test_解析一个Cpp项目():
|
41 |
+
from crazy_functions.解析项目源代码 import 解析一个C项目
|
42 |
+
txt = "crazy_functions/test_project/cpp/cppipc"
|
43 |
+
for cookies, cb, hist, msg in 解析一个C项目(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
44 |
+
print(cb)
|
45 |
+
|
46 |
+
def test_Latex英文润色():
|
47 |
+
from crazy_functions.Latex全文润色 import Latex英文润色
|
48 |
+
txt = "crazy_functions/test_project/latex/attention"
|
49 |
+
for cookies, cb, hist, msg in Latex英文润色(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
50 |
+
print(cb)
|
51 |
+
|
52 |
+
def test_Markdown中译英():
|
53 |
+
from crazy_functions.批量Markdown翻译 import Markdown中译英
|
54 |
+
txt = "README.md"
|
55 |
+
for cookies, cb, hist, msg in Markdown中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
56 |
+
print(cb)
|
57 |
+
|
58 |
+
def test_批量翻译PDF文档():
|
59 |
+
from crazy_functions.批量翻译PDF文档_多线程 import 批量翻译PDF文档
|
60 |
+
txt = "crazy_functions/test_project/pdf_and_word"
|
61 |
+
for cookies, cb, hist, msg in 批量翻译PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
62 |
+
print(cb)
|
63 |
+
|
64 |
+
def test_谷歌检索小助手():
|
65 |
+
from crazy_functions.谷歌检索小助手 import 谷歌检索小助手
|
66 |
+
txt = "https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=auto+reinforcement+learning&btnG="
|
67 |
+
for cookies, cb, hist, msg in 谷歌检索小助手(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
68 |
+
print(cb)
|
69 |
+
|
70 |
+
def test_总结word文档():
|
71 |
+
from crazy_functions.总结word文档 import 总结word文档
|
72 |
+
txt = "crazy_functions/test_project/pdf_and_word"
|
73 |
+
for cookies, cb, hist, msg in 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
74 |
+
print(cb)
|
75 |
+
|
76 |
+
def test_下载arxiv论文并翻译摘要():
|
77 |
+
from crazy_functions.下载arxiv论文翻译摘要 import 下载arxiv论文并翻译摘要
|
78 |
+
txt = "1812.10695"
|
79 |
+
for cookies, cb, hist, msg in 下载arxiv论文并翻译摘要(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
80 |
+
print(cb)
|
81 |
+
|
82 |
+
test_解析一个Python项目()
|
83 |
+
test_Latex英文润色()
|
84 |
+
test_Markdown中译英()
|
85 |
+
test_批量翻译PDF文档()
|
86 |
+
test_谷歌检索小助手()
|
87 |
+
test_总结word文档()
|
88 |
+
test_下载arxiv论文并翻译摘要()
|
89 |
+
test_解析一个Cpp项目()
|
90 |
+
|
91 |
+
input("程序完成,回车退出。")
|
92 |
+
print("退出。")
|
crazy_functions/crazy_utils.py
ADDED
@@ -0,0 +1,566 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import traceback
|
2 |
+
from toolbox import update_ui, get_conf
|
3 |
+
|
4 |
+
def input_clipping(inputs, history, max_token_limit):
|
5 |
+
import numpy as np
|
6 |
+
from request_llm.bridge_all import model_info
|
7 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
8 |
+
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
|
9 |
+
|
10 |
+
mode = 'input-and-history'
|
11 |
+
# 当 输入部分的token占比 小于 全文的一半时,只裁剪历史
|
12 |
+
input_token_num = get_token_num(inputs)
|
13 |
+
if input_token_num < max_token_limit//2:
|
14 |
+
mode = 'only-history'
|
15 |
+
max_token_limit = max_token_limit - input_token_num
|
16 |
+
|
17 |
+
everything = [inputs] if mode == 'input-and-history' else ['']
|
18 |
+
everything.extend(history)
|
19 |
+
n_token = get_token_num('\n'.join(everything))
|
20 |
+
everything_token = [get_token_num(e) for e in everything]
|
21 |
+
delta = max(everything_token) // 16 # 截断时的颗粒度
|
22 |
+
|
23 |
+
while n_token > max_token_limit:
|
24 |
+
where = np.argmax(everything_token)
|
25 |
+
encoded = enc.encode(everything[where], disallowed_special=())
|
26 |
+
clipped_encoded = encoded[:len(encoded)-delta]
|
27 |
+
everything[where] = enc.decode(clipped_encoded)[:-1] # -1 to remove the may-be illegal char
|
28 |
+
everything_token[where] = get_token_num(everything[where])
|
29 |
+
n_token = get_token_num('\n'.join(everything))
|
30 |
+
|
31 |
+
if mode == 'input-and-history':
|
32 |
+
inputs = everything[0]
|
33 |
+
else:
|
34 |
+
pass
|
35 |
+
history = everything[1:]
|
36 |
+
return inputs, history
|
37 |
+
|
38 |
+
def request_gpt_model_in_new_thread_with_ui_alive(
|
39 |
+
inputs, inputs_show_user, llm_kwargs,
|
40 |
+
chatbot, history, sys_prompt, refresh_interval=0.2,
|
41 |
+
handle_token_exceed=True,
|
42 |
+
retry_times_at_unknown_error=2,
|
43 |
+
):
|
44 |
+
"""
|
45 |
+
Request GPT model,请求GPT模型同时维持用户界面活跃。
|
46 |
+
|
47 |
+
输入参数 Args (以_array结尾的输入变量都是列表,列表长度为子任务的数量,执行时,会把列表拆解,放到每个子线程中分别执行):
|
48 |
+
inputs (string): List of inputs (输入)
|
49 |
+
inputs_show_user (string): List of inputs to show user(展现在报告中的输入,借助此参数,在汇总报告中隐藏啰嗦的真实输入,增强报告的可读性)
|
50 |
+
top_p (float): Top p value for sampling from model distribution (GPT参数,浮点数)
|
51 |
+
temperature (float): Temperature value for sampling from model distribution(GPT参数,浮点数)
|
52 |
+
chatbot: chatbot inputs and outputs (用户界面对话窗口句柄,用于数据流可视化)
|
53 |
+
history (list): List of chat history (历史,对话历史列表)
|
54 |
+
sys_prompt (string): List of system prompts (系统输入,列表,用于输入给GPT的前提提示,比如你是翻译官怎样怎样)
|
55 |
+
refresh_interval (float, optional): Refresh interval for UI (default: 0.2) (刷新时间间隔频率,建议低于1,不可高于3,仅仅服务于视觉效果)
|
56 |
+
handle_token_exceed:是否自动处理token溢出的情况,如果选择自动处理,则会在溢出时暴力截断,默认开启
|
57 |
+
retry_times_at_unknown_error:失败时的重试次数
|
58 |
+
|
59 |
+
输出 Returns:
|
60 |
+
future: 输出,GPT返回的结果
|
61 |
+
"""
|
62 |
+
import time
|
63 |
+
from concurrent.futures import ThreadPoolExecutor
|
64 |
+
from request_llm.bridge_all import predict_no_ui_long_connection
|
65 |
+
# 用户反馈
|
66 |
+
chatbot.append([inputs_show_user, ""])
|
67 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
|
68 |
+
executor = ThreadPoolExecutor(max_workers=16)
|
69 |
+
mutable = ["", time.time(), ""]
|
70 |
+
def _req_gpt(inputs, history, sys_prompt):
|
71 |
+
retry_op = retry_times_at_unknown_error
|
72 |
+
exceeded_cnt = 0
|
73 |
+
while True:
|
74 |
+
# watchdog error
|
75 |
+
if len(mutable) >= 2 and (time.time()-mutable[1]) > 5:
|
76 |
+
raise RuntimeError("检测到程序终止。")
|
77 |
+
try:
|
78 |
+
# 【第一种情况】:顺利完成
|
79 |
+
result = predict_no_ui_long_connection(
|
80 |
+
inputs=inputs, llm_kwargs=llm_kwargs,
|
81 |
+
history=history, sys_prompt=sys_prompt, observe_window=mutable)
|
82 |
+
return result
|
83 |
+
except ConnectionAbortedError as token_exceeded_error:
|
84 |
+
# 【第二种情况】:Token溢出
|
85 |
+
if handle_token_exceed:
|
86 |
+
exceeded_cnt += 1
|
87 |
+
# 【选择处理】 尝试计算比例,尽可能多地保留文本
|
88 |
+
from toolbox import get_reduce_token_percent
|
89 |
+
p_ratio, n_exceed = get_reduce_token_percent(str(token_exceeded_error))
|
90 |
+
MAX_TOKEN = 4096
|
91 |
+
EXCEED_ALLO = 512 + 512 * exceeded_cnt
|
92 |
+
inputs, history = input_clipping(inputs, history, max_token_limit=MAX_TOKEN-EXCEED_ALLO)
|
93 |
+
mutable[0] += f'[Local Message] 警告,文本过长将进行截断,Token溢出数:{n_exceed}。\n\n'
|
94 |
+
continue # 返回重试
|
95 |
+
else:
|
96 |
+
# 【选择放弃】
|
97 |
+
tb_str = '```\n' + traceback.format_exc() + '```'
|
98 |
+
mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n"
|
99 |
+
return mutable[0] # 放弃
|
100 |
+
except:
|
101 |
+
# 【第三种情况】:其他错误:重试几次
|
102 |
+
tb_str = '```\n' + traceback.format_exc() + '```'
|
103 |
+
print(tb_str)
|
104 |
+
mutable[0] += f"[Local Message] 警告,在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n"
|
105 |
+
if retry_op > 0:
|
106 |
+
retry_op -= 1
|
107 |
+
mutable[0] += f"[Local Message] 重试中,请稍等 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}:\n\n"
|
108 |
+
if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str):
|
109 |
+
time.sleep(30)
|
110 |
+
time.sleep(5)
|
111 |
+
continue # 返回重试
|
112 |
+
else:
|
113 |
+
time.sleep(5)
|
114 |
+
return mutable[0] # 放弃
|
115 |
+
|
116 |
+
# 提交任务
|
117 |
+
future = executor.submit(_req_gpt, inputs, history, sys_prompt)
|
118 |
+
while True:
|
119 |
+
# yield一次以刷新前端页面
|
120 |
+
time.sleep(refresh_interval)
|
121 |
+
# “喂狗”(看门狗)
|
122 |
+
mutable[1] = time.time()
|
123 |
+
if future.done():
|
124 |
+
break
|
125 |
+
chatbot[-1] = [chatbot[-1][0], mutable[0]]
|
126 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
|
127 |
+
|
128 |
+
final_result = future.result()
|
129 |
+
chatbot[-1] = [chatbot[-1][0], final_result]
|
130 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 如果最后成功了,则删除报错信息
|
131 |
+
return final_result
|
132 |
+
|
133 |
+
|
134 |
+
def request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
135 |
+
inputs_array, inputs_show_user_array, llm_kwargs,
|
136 |
+
chatbot, history_array, sys_prompt_array,
|
137 |
+
refresh_interval=0.2, max_workers=-1, scroller_max_len=30,
|
138 |
+
handle_token_exceed=True, show_user_at_complete=False,
|
139 |
+
retry_times_at_unknown_error=2,
|
140 |
+
):
|
141 |
+
"""
|
142 |
+
Request GPT model using multiple threads with UI and high efficiency
|
143 |
+
请求GPT模型的[多线程]版。
|
144 |
+
具备以下功能:
|
145 |
+
实时在UI上反馈远程数据流
|
146 |
+
使用线程池,可调节线程池的大小避免openai的流量限制错误
|
147 |
+
处理中途中止的情况
|
148 |
+
网络等出问题时,会把traceback和已经接收的数据转入输出
|
149 |
+
|
150 |
+
输入参数 Args (以_array结尾的输入变量都是列表,列表长度为子任务的数量,执行时,会把列表拆解,放到每个子线程中分别执行):
|
151 |
+
inputs_array (list): List of inputs (每个子任务的输入)
|
152 |
+
inputs_show_user_array (list): List of inputs to show user(每个子任务展现在报告中的输入,借助此参数,在汇总报告中隐藏啰嗦的真实输入,增强报告的可读性)
|
153 |
+
llm_kwargs: llm_kwargs参数
|
154 |
+
chatbot: chatbot (用户界面对话窗口句柄,用于数据流可视化)
|
155 |
+
history_array (list): List of chat history (历史对话输入,双层列表,第一层列表是子任务分解,第二层列表是对话历史)
|
156 |
+
sys_prompt_array (list): List of system prompts (系统输入,列表,用于输入给GPT的前提提示,比如你是翻译官怎样怎样)
|
157 |
+
refresh_interval (float, optional): Refresh interval for UI (default: 0.2) (刷新时间间隔频率,建议低于1,不可高于3,仅仅服务于视觉效果)
|
158 |
+
max_workers (int, optional): Maximum number of threads (default: see config.py) (最大线程数,如果子任务非常多,需要用此选项防止高频地请求openai导致错误)
|
159 |
+
scroller_max_len (int, optional): Maximum length for scroller (default: 30)(数据流的显示最后收到的多少个字符,仅仅服务于视觉效果)
|
160 |
+
handle_token_exceed (bool, optional): (是否在输入过长时,自动缩减文本)
|
161 |
+
handle_token_exceed:是否自动处理token溢出的情况,如果选择自动处理,则会在溢出时暴力截断,默认开启
|
162 |
+
show_user_at_complete (bool, optional): (在结束时,把完整输入-输出结果显示在聊天框)
|
163 |
+
retry_times_at_unknown_error:子任务失败时的重试次数
|
164 |
+
|
165 |
+
输出 Returns:
|
166 |
+
list: List of GPT model responses (每个子任务的输出汇总,如果某个子任务出错,response中会携带traceback报错信息,方便调试和定位问题。)
|
167 |
+
"""
|
168 |
+
import time, random
|
169 |
+
from concurrent.futures import ThreadPoolExecutor
|
170 |
+
from request_llm.bridge_all import predict_no_ui_long_connection
|
171 |
+
assert len(inputs_array) == len(history_array)
|
172 |
+
assert len(inputs_array) == len(sys_prompt_array)
|
173 |
+
if max_workers == -1: # 读取配置文件
|
174 |
+
try: max_workers, = get_conf('DEFAULT_WORKER_NUM')
|
175 |
+
except: max_workers = 8
|
176 |
+
if max_workers <= 0 or max_workers >= 20: max_workers = 8
|
177 |
+
# 屏蔽掉 chatglm的多线程,可能会导致严重卡顿
|
178 |
+
if not (llm_kwargs['llm_model'].startswith('gpt-') or llm_kwargs['llm_model'].startswith('api2d-')):
|
179 |
+
max_workers = 1
|
180 |
+
|
181 |
+
executor = ThreadPoolExecutor(max_workers=max_workers)
|
182 |
+
n_frag = len(inputs_array)
|
183 |
+
# 用户反馈
|
184 |
+
chatbot.append(["请开始多线程操作。", ""])
|
185 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
|
186 |
+
# 跨线程传递
|
187 |
+
mutable = [["", time.time(), "等待中"] for _ in range(n_frag)]
|
188 |
+
|
189 |
+
# 子线程任务
|
190 |
+
def _req_gpt(index, inputs, history, sys_prompt):
|
191 |
+
gpt_say = ""
|
192 |
+
retry_op = retry_times_at_unknown_error
|
193 |
+
exceeded_cnt = 0
|
194 |
+
mutable[index][2] = "执行中"
|
195 |
+
while True:
|
196 |
+
# watchdog error
|
197 |
+
if len(mutable[index]) >= 2 and (time.time()-mutable[index][1]) > 5:
|
198 |
+
raise RuntimeError("检测到程序终止。")
|
199 |
+
try:
|
200 |
+
# 【第一种情况】:顺利完成
|
201 |
+
# time.sleep(10); raise RuntimeError("测试")
|
202 |
+
gpt_say = predict_no_ui_long_connection(
|
203 |
+
inputs=inputs, llm_kwargs=llm_kwargs, history=history,
|
204 |
+
sys_prompt=sys_prompt, observe_window=mutable[index], console_slience=True
|
205 |
+
)
|
206 |
+
mutable[index][2] = "已成功"
|
207 |
+
return gpt_say
|
208 |
+
except ConnectionAbortedError as token_exceeded_error:
|
209 |
+
# 【第二种情况】:Token溢出,
|
210 |
+
if handle_token_exceed:
|
211 |
+
exceeded_cnt += 1
|
212 |
+
# 【选择处理】 尝试计算比例,尽可能多地保留文本
|
213 |
+
from toolbox import get_reduce_token_percent
|
214 |
+
p_ratio, n_exceed = get_reduce_token_percent(str(token_exceeded_error))
|
215 |
+
MAX_TOKEN = 4096
|
216 |
+
EXCEED_ALLO = 512 + 512 * exceeded_cnt
|
217 |
+
inputs, history = input_clipping(inputs, history, max_token_limit=MAX_TOKEN-EXCEED_ALLO)
|
218 |
+
gpt_say += f'[Local Message] 警告,文本过长将进行截断,Token溢出数:{n_exceed}。\n\n'
|
219 |
+
mutable[index][2] = f"截断重试"
|
220 |
+
continue # 返回重试
|
221 |
+
else:
|
222 |
+
# 【选择放弃】
|
223 |
+
tb_str = '```\n' + traceback.format_exc() + '```'
|
224 |
+
gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n"
|
225 |
+
if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0]
|
226 |
+
mutable[index][2] = "输入过长已放弃"
|
227 |
+
return gpt_say # 放弃
|
228 |
+
except:
|
229 |
+
# 【第三种情况】:其他错误
|
230 |
+
tb_str = '```\n' + traceback.format_exc() + '```'
|
231 |
+
print(tb_str)
|
232 |
+
gpt_say += f"[Local Message] 警告,线程{index}在执行过程中遭遇问题, Traceback:\n\n{tb_str}\n\n"
|
233 |
+
if len(mutable[index][0]) > 0: gpt_say += "此线程失败前收到的回答:\n\n" + mutable[index][0]
|
234 |
+
if retry_op > 0:
|
235 |
+
retry_op -= 1
|
236 |
+
wait = random.randint(5, 20)
|
237 |
+
if ("Rate limit reached" in tb_str) or ("Too Many Requests" in tb_str):
|
238 |
+
wait = wait * 3
|
239 |
+
fail_info = "OpenAI绑定信用卡可解除频率限制 "
|
240 |
+
else:
|
241 |
+
fail_info = ""
|
242 |
+
# 也许等待十几秒后,情况会好转
|
243 |
+
for i in range(wait):
|
244 |
+
mutable[index][2] = f"{fail_info}等待重试 {wait-i}"; time.sleep(1)
|
245 |
+
# 开始重试
|
246 |
+
mutable[index][2] = f"重试中 {retry_times_at_unknown_error-retry_op}/{retry_times_at_unknown_error}"
|
247 |
+
continue # 返回重试
|
248 |
+
else:
|
249 |
+
mutable[index][2] = "已失败"
|
250 |
+
wait = 5
|
251 |
+
time.sleep(5)
|
252 |
+
return gpt_say # 放弃
|
253 |
+
|
254 |
+
# 异步任务开始
|
255 |
+
futures = [executor.submit(_req_gpt, index, inputs, history, sys_prompt) for index, inputs, history, sys_prompt in zip(
|
256 |
+
range(len(inputs_array)), inputs_array, history_array, sys_prompt_array)]
|
257 |
+
cnt = 0
|
258 |
+
while True:
|
259 |
+
# yield一次以刷新前端页面
|
260 |
+
time.sleep(refresh_interval)
|
261 |
+
cnt += 1
|
262 |
+
worker_done = [h.done() for h in futures]
|
263 |
+
if all(worker_done):
|
264 |
+
executor.shutdown()
|
265 |
+
break
|
266 |
+
# 更好的UI视觉效果
|
267 |
+
observe_win = []
|
268 |
+
# 每个线程都要“喂狗”(看门狗)
|
269 |
+
for thread_index, _ in enumerate(worker_done):
|
270 |
+
mutable[thread_index][1] = time.time()
|
271 |
+
# 在前端打印些好玩的东西
|
272 |
+
for thread_index, _ in enumerate(worker_done):
|
273 |
+
print_something_really_funny = "[ ...`"+mutable[thread_index][0][-scroller_max_len:].\
|
274 |
+
replace('\n', '').replace('```', '...').replace(
|
275 |
+
' ', '.').replace('<br/>', '.....').replace('$', '.')+"`... ]"
|
276 |
+
observe_win.append(print_something_really_funny)
|
277 |
+
# 在前端打印些好玩的东西
|
278 |
+
stat_str = ''.join([f'`{mutable[thread_index][2]}`: {obs}\n\n'
|
279 |
+
if not done else f'`{mutable[thread_index][2]}`\n\n'
|
280 |
+
for thread_index, done, obs in zip(range(len(worker_done)), worker_done, observe_win)])
|
281 |
+
# 在前端打印些好玩的东西
|
282 |
+
chatbot[-1] = [chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt % 10+1))]
|
283 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
|
284 |
+
|
285 |
+
# 异步任务结束
|
286 |
+
gpt_response_collection = []
|
287 |
+
for inputs_show_user, f in zip(inputs_show_user_array, futures):
|
288 |
+
gpt_res = f.result()
|
289 |
+
gpt_response_collection.extend([inputs_show_user, gpt_res])
|
290 |
+
|
291 |
+
# 是否在结束时,在界面上显示结果
|
292 |
+
if show_user_at_complete:
|
293 |
+
for inputs_show_user, f in zip(inputs_show_user_array, futures):
|
294 |
+
gpt_res = f.result()
|
295 |
+
chatbot.append([inputs_show_user, gpt_res])
|
296 |
+
yield from update_ui(chatbot=chatbot, history=[]) # 刷新界面
|
297 |
+
time.sleep(0.3)
|
298 |
+
return gpt_response_collection
|
299 |
+
|
300 |
+
|
301 |
+
def breakdown_txt_to_satisfy_token_limit(txt, get_token_fn, limit):
|
302 |
+
def cut(txt_tocut, must_break_at_empty_line): # 递归
|
303 |
+
if get_token_fn(txt_tocut) <= limit:
|
304 |
+
return [txt_tocut]
|
305 |
+
else:
|
306 |
+
lines = txt_tocut.split('\n')
|
307 |
+
estimated_line_cut = limit / get_token_fn(txt_tocut) * len(lines)
|
308 |
+
estimated_line_cut = int(estimated_line_cut)
|
309 |
+
for cnt in reversed(range(estimated_line_cut)):
|
310 |
+
if must_break_at_empty_line:
|
311 |
+
if lines[cnt] != "":
|
312 |
+
continue
|
313 |
+
print(cnt)
|
314 |
+
prev = "\n".join(lines[:cnt])
|
315 |
+
post = "\n".join(lines[cnt:])
|
316 |
+
if get_token_fn(prev) < limit:
|
317 |
+
break
|
318 |
+
if cnt == 0:
|
319 |
+
raise RuntimeError("存在一行极长的文本!")
|
320 |
+
# print(len(post))
|
321 |
+
# 列表递归接龙
|
322 |
+
result = [prev]
|
323 |
+
result.extend(cut(post, must_break_at_empty_line))
|
324 |
+
return result
|
325 |
+
try:
|
326 |
+
return cut(txt, must_break_at_empty_line=True)
|
327 |
+
except RuntimeError:
|
328 |
+
return cut(txt, must_break_at_empty_line=False)
|
329 |
+
|
330 |
+
|
331 |
+
def force_breakdown(txt, limit, get_token_fn):
|
332 |
+
"""
|
333 |
+
当无法用标点、空行分割时,我们用最暴力的方法切割
|
334 |
+
"""
|
335 |
+
for i in reversed(range(len(txt))):
|
336 |
+
if get_token_fn(txt[:i]) < limit:
|
337 |
+
return txt[:i], txt[i:]
|
338 |
+
return "Tiktoken未知错误", "Tiktoken未知错误"
|
339 |
+
|
340 |
+
def breakdown_txt_to_satisfy_token_limit_for_pdf(txt, get_token_fn, limit):
|
341 |
+
# 递归
|
342 |
+
def cut(txt_tocut, must_break_at_empty_line, break_anyway=False):
|
343 |
+
if get_token_fn(txt_tocut) <= limit:
|
344 |
+
return [txt_tocut]
|
345 |
+
else:
|
346 |
+
lines = txt_tocut.split('\n')
|
347 |
+
estimated_line_cut = limit / get_token_fn(txt_tocut) * len(lines)
|
348 |
+
estimated_line_cut = int(estimated_line_cut)
|
349 |
+
cnt = 0
|
350 |
+
for cnt in reversed(range(estimated_line_cut)):
|
351 |
+
if must_break_at_empty_line:
|
352 |
+
if lines[cnt] != "":
|
353 |
+
continue
|
354 |
+
prev = "\n".join(lines[:cnt])
|
355 |
+
post = "\n".join(lines[cnt:])
|
356 |
+
if get_token_fn(prev) < limit:
|
357 |
+
break
|
358 |
+
if cnt == 0:
|
359 |
+
if break_anyway:
|
360 |
+
prev, post = force_breakdown(txt_tocut, limit, get_token_fn)
|
361 |
+
else:
|
362 |
+
raise RuntimeError(f"存在一行极长的文本!{txt_tocut}")
|
363 |
+
# print(len(post))
|
364 |
+
# 列表递归接龙
|
365 |
+
result = [prev]
|
366 |
+
result.extend(cut(post, must_break_at_empty_line, break_anyway=break_anyway))
|
367 |
+
return result
|
368 |
+
try:
|
369 |
+
# 第1次尝试,将双空行(\n\n)作为切分点
|
370 |
+
return cut(txt, must_break_at_empty_line=True)
|
371 |
+
except RuntimeError:
|
372 |
+
try:
|
373 |
+
# 第2次尝试,将单空行(\n)作为切分点
|
374 |
+
return cut(txt, must_break_at_empty_line=False)
|
375 |
+
except RuntimeError:
|
376 |
+
try:
|
377 |
+
# 第3次尝试,将英文句号(.)作为切分点
|
378 |
+
res = cut(txt.replace('.', '。\n'), must_break_at_empty_line=False) # 这个中文的句号是故意的,作为一个标识而存在
|
379 |
+
return [r.replace('。\n', '.') for r in res]
|
380 |
+
except RuntimeError as e:
|
381 |
+
try:
|
382 |
+
# 第4次尝试,将中文句号(。)作为切分点
|
383 |
+
res = cut(txt.replace('。', '。。\n'), must_break_at_empty_line=False)
|
384 |
+
return [r.replace('。。\n', '。') for r in res]
|
385 |
+
except RuntimeError as e:
|
386 |
+
# 第5次尝试,没办法了,随便切一下敷衍吧
|
387 |
+
return cut(txt, must_break_at_empty_line=False, break_anyway=True)
|
388 |
+
|
389 |
+
|
390 |
+
|
391 |
+
def read_and_clean_pdf_text(fp):
|
392 |
+
"""
|
393 |
+
这个函数用于分割pdf,用了很多trick,逻辑较乱,效果奇好
|
394 |
+
|
395 |
+
**输入参数说明**
|
396 |
+
- `fp`:需要读取和清理文本的pdf文件路径
|
397 |
+
|
398 |
+
**输出参数说明**
|
399 |
+
- `meta_txt`:清理后的文本内容字符串
|
400 |
+
- `page_one_meta`:第一页清理后的文本内容列表
|
401 |
+
|
402 |
+
**函数功能**
|
403 |
+
读取pdf文件并清理其中的文本内容,清理规则包括:
|
404 |
+
- 提取所有块元的文本信息,并合并为一个字符串
|
405 |
+
- 去除短块(字符数小于100)并替换为回车符
|
406 |
+
- 清理多余的空行
|
407 |
+
- 合并小写字母开头的段落块并替换为空格
|
408 |
+
- 清除重复的换行
|
409 |
+
- 将每个换行符替换为两个换行符,使每个段落之间有两个换行符分隔
|
410 |
+
"""
|
411 |
+
import fitz, copy
|
412 |
+
import re
|
413 |
+
import numpy as np
|
414 |
+
from colorful import print亮黄, print亮绿
|
415 |
+
fc = 0 # Index 0 文本
|
416 |
+
fs = 1 # Index 1 字体
|
417 |
+
fb = 2 # Index 2 框框
|
418 |
+
REMOVE_FOOT_NOTE = True # 是否丢弃掉 不是正文的内容 (比正文字体小,如参考文献、脚注、图注等)
|
419 |
+
REMOVE_FOOT_FFSIZE_PERCENT = 0.95 # 小于正文的?时,判定为不是正文(有些文章的正文部分字体大小不是100%统一的,有肉眼不可见的小变化)
|
420 |
+
def primary_ffsize(l):
|
421 |
+
"""
|
422 |
+
提取文本块主字体
|
423 |
+
"""
|
424 |
+
fsize_statiscs = {}
|
425 |
+
for wtf in l['spans']:
|
426 |
+
if wtf['size'] not in fsize_statiscs: fsize_statiscs[wtf['size']] = 0
|
427 |
+
fsize_statiscs[wtf['size']] += len(wtf['text'])
|
428 |
+
return max(fsize_statiscs, key=fsize_statiscs.get)
|
429 |
+
|
430 |
+
def ffsize_same(a,b):
|
431 |
+
"""
|
432 |
+
提取字体大小是否近似相等
|
433 |
+
"""
|
434 |
+
return abs((a-b)/max(a,b)) < 0.02
|
435 |
+
|
436 |
+
with fitz.open(fp) as doc:
|
437 |
+
meta_txt = []
|
438 |
+
meta_font = []
|
439 |
+
|
440 |
+
meta_line = []
|
441 |
+
meta_span = []
|
442 |
+
############################## <第 1 步,搜集初始信息> ##################################
|
443 |
+
for index, page in enumerate(doc):
|
444 |
+
# file_content += page.get_text()
|
445 |
+
text_areas = page.get_text("dict") # 获取页面上的文本信息
|
446 |
+
for t in text_areas['blocks']:
|
447 |
+
if 'lines' in t:
|
448 |
+
pf = 998
|
449 |
+
for l in t['lines']:
|
450 |
+
txt_line = "".join([wtf['text'] for wtf in l['spans']])
|
451 |
+
if len(txt_line) == 0: continue
|
452 |
+
pf = primary_ffsize(l)
|
453 |
+
meta_line.append([txt_line, pf, l['bbox'], l])
|
454 |
+
for wtf in l['spans']: # for l in t['lines']:
|
455 |
+
meta_span.append([wtf['text'], wtf['size'], len(wtf['text'])])
|
456 |
+
# meta_line.append(["NEW_BLOCK", pf])
|
457 |
+
# 块元提取 for each word segment with in line for each line cross-line words for each block
|
458 |
+
meta_txt.extend([" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
459 |
+
'- ', '') for t in text_areas['blocks'] if 'lines' in t])
|
460 |
+
meta_font.extend([np.mean([np.mean([wtf['size'] for wtf in l['spans']])
|
461 |
+
for l in t['lines']]) for t in text_areas['blocks'] if 'lines' in t])
|
462 |
+
if index == 0:
|
463 |
+
page_one_meta = [" ".join(["".join([wtf['text'] for wtf in l['spans']]) for l in t['lines']]).replace(
|
464 |
+
'- ', '') for t in text_areas['blocks'] if 'lines' in t]
|
465 |
+
|
466 |
+
############################## <第 2 步,获取正文主字体> ##################################
|
467 |
+
fsize_statiscs = {}
|
468 |
+
for span in meta_span:
|
469 |
+
if span[1] not in fsize_statiscs: fsize_statiscs[span[1]] = 0
|
470 |
+
fsize_statiscs[span[1]] += span[2]
|
471 |
+
main_fsize = max(fsize_statiscs, key=fsize_statiscs.get)
|
472 |
+
if REMOVE_FOOT_NOTE:
|
473 |
+
give_up_fize_threshold = main_fsize * REMOVE_FOOT_FFSIZE_PERCENT
|
474 |
+
|
475 |
+
############################## <第 3 步,切分和重新整合> ##################################
|
476 |
+
mega_sec = []
|
477 |
+
sec = []
|
478 |
+
for index, line in enumerate(meta_line):
|
479 |
+
if index == 0:
|
480 |
+
sec.append(line[fc])
|
481 |
+
continue
|
482 |
+
if REMOVE_FOOT_NOTE:
|
483 |
+
if meta_line[index][fs] <= give_up_fize_threshold:
|
484 |
+
continue
|
485 |
+
if ffsize_same(meta_line[index][fs], meta_line[index-1][fs]):
|
486 |
+
# 尝试识别段落
|
487 |
+
if meta_line[index][fc].endswith('.') and\
|
488 |
+
(meta_line[index-1][fc] != 'NEW_BLOCK') and \
|
489 |
+
(meta_line[index][fb][2] - meta_line[index][fb][0]) < (meta_line[index-1][fb][2] - meta_line[index-1][fb][0]) * 0.7:
|
490 |
+
sec[-1] += line[fc]
|
491 |
+
sec[-1] += "\n\n"
|
492 |
+
else:
|
493 |
+
sec[-1] += " "
|
494 |
+
sec[-1] += line[fc]
|
495 |
+
else:
|
496 |
+
if (index+1 < len(meta_line)) and \
|
497 |
+
meta_line[index][fs] > main_fsize:
|
498 |
+
# 单行 + 字体大
|
499 |
+
mega_sec.append(copy.deepcopy(sec))
|
500 |
+
sec = []
|
501 |
+
sec.append("# " + line[fc])
|
502 |
+
else:
|
503 |
+
# 尝试识别section
|
504 |
+
if meta_line[index-1][fs] > meta_line[index][fs]:
|
505 |
+
sec.append("\n" + line[fc])
|
506 |
+
else:
|
507 |
+
sec.append(line[fc])
|
508 |
+
mega_sec.append(copy.deepcopy(sec))
|
509 |
+
|
510 |
+
finals = []
|
511 |
+
for ms in mega_sec:
|
512 |
+
final = " ".join(ms)
|
513 |
+
final = final.replace('- ', ' ')
|
514 |
+
finals.append(final)
|
515 |
+
meta_txt = finals
|
516 |
+
|
517 |
+
############################## <第 4 步,乱七八糟的后处理> ##################################
|
518 |
+
def 把字符太少的块清除为回车(meta_txt):
|
519 |
+
for index, block_txt in enumerate(meta_txt):
|
520 |
+
if len(block_txt) < 100:
|
521 |
+
meta_txt[index] = '\n'
|
522 |
+
return meta_txt
|
523 |
+
meta_txt = 把字符太少的块清除为回车(meta_txt)
|
524 |
+
|
525 |
+
def 清理多余的空行(meta_txt):
|
526 |
+
for index in reversed(range(1, len(meta_txt))):
|
527 |
+
if meta_txt[index] == '\n' and meta_txt[index-1] == '\n':
|
528 |
+
meta_txt.pop(index)
|
529 |
+
return meta_txt
|
530 |
+
meta_txt = 清理多余的空行(meta_txt)
|
531 |
+
|
532 |
+
def 合并小写开头的段落块(meta_txt):
|
533 |
+
def starts_with_lowercase_word(s):
|
534 |
+
pattern = r"^[a-z]+"
|
535 |
+
match = re.match(pattern, s)
|
536 |
+
if match:
|
537 |
+
return True
|
538 |
+
else:
|
539 |
+
return False
|
540 |
+
for _ in range(100):
|
541 |
+
for index, block_txt in enumerate(meta_txt):
|
542 |
+
if starts_with_lowercase_word(block_txt):
|
543 |
+
if meta_txt[index-1] != '\n':
|
544 |
+
meta_txt[index-1] += ' '
|
545 |
+
else:
|
546 |
+
meta_txt[index-1] = ''
|
547 |
+
meta_txt[index-1] += meta_txt[index]
|
548 |
+
meta_txt[index] = '\n'
|
549 |
+
return meta_txt
|
550 |
+
meta_txt = 合并小写开头的段落块(meta_txt)
|
551 |
+
meta_txt = 清理多余的空行(meta_txt)
|
552 |
+
|
553 |
+
meta_txt = '\n'.join(meta_txt)
|
554 |
+
# 清除重复的换行
|
555 |
+
for _ in range(5):
|
556 |
+
meta_txt = meta_txt.replace('\n\n', '\n')
|
557 |
+
|
558 |
+
# 换行 -> 双换行
|
559 |
+
meta_txt = meta_txt.replace('\n', '\n\n')
|
560 |
+
|
561 |
+
############################## <第 5 步,展示分割效果> ##################################
|
562 |
+
# for f in finals:
|
563 |
+
# print亮黄(f)
|
564 |
+
# print亮绿('***************************')
|
565 |
+
|
566 |
+
return meta_txt, page_one_meta
|
crazy_functions/test_project/cpp/cppipc/buffer.cpp
ADDED
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "libipc/buffer.h"
|
2 |
+
#include "libipc/utility/pimpl.h"
|
3 |
+
|
4 |
+
#include <cstring>
|
5 |
+
|
6 |
+
namespace ipc {
|
7 |
+
|
8 |
+
bool operator==(buffer const & b1, buffer const & b2) {
|
9 |
+
return (b1.size() == b2.size()) && (std::memcmp(b1.data(), b2.data(), b1.size()) == 0);
|
10 |
+
}
|
11 |
+
|
12 |
+
bool operator!=(buffer const & b1, buffer const & b2) {
|
13 |
+
return !(b1 == b2);
|
14 |
+
}
|
15 |
+
|
16 |
+
class buffer::buffer_ : public pimpl<buffer_> {
|
17 |
+
public:
|
18 |
+
void* p_;
|
19 |
+
std::size_t s_;
|
20 |
+
void* a_;
|
21 |
+
buffer::destructor_t d_;
|
22 |
+
|
23 |
+
buffer_(void* p, std::size_t s, buffer::destructor_t d, void* a)
|
24 |
+
: p_(p), s_(s), a_(a), d_(d) {
|
25 |
+
}
|
26 |
+
|
27 |
+
~buffer_() {
|
28 |
+
if (d_ == nullptr) return;
|
29 |
+
d_((a_ == nullptr) ? p_ : a_, s_);
|
30 |
+
}
|
31 |
+
};
|
32 |
+
|
33 |
+
buffer::buffer()
|
34 |
+
: buffer(nullptr, 0, nullptr, nullptr) {
|
35 |
+
}
|
36 |
+
|
37 |
+
buffer::buffer(void* p, std::size_t s, destructor_t d)
|
38 |
+
: p_(p_->make(p, s, d, nullptr)) {
|
39 |
+
}
|
40 |
+
|
41 |
+
buffer::buffer(void* p, std::size_t s, destructor_t d, void* additional)
|
42 |
+
: p_(p_->make(p, s, d, additional)) {
|
43 |
+
}
|
44 |
+
|
45 |
+
buffer::buffer(void* p, std::size_t s)
|
46 |
+
: buffer(p, s, nullptr) {
|
47 |
+
}
|
48 |
+
|
49 |
+
buffer::buffer(char const & c)
|
50 |
+
: buffer(const_cast<char*>(&c), 1) {
|
51 |
+
}
|
52 |
+
|
53 |
+
buffer::buffer(buffer&& rhs)
|
54 |
+
: buffer() {
|
55 |
+
swap(rhs);
|
56 |
+
}
|
57 |
+
|
58 |
+
buffer::~buffer() {
|
59 |
+
p_->clear();
|
60 |
+
}
|
61 |
+
|
62 |
+
void buffer::swap(buffer& rhs) {
|
63 |
+
std::swap(p_, rhs.p_);
|
64 |
+
}
|
65 |
+
|
66 |
+
buffer& buffer::operator=(buffer rhs) {
|
67 |
+
swap(rhs);
|
68 |
+
return *this;
|
69 |
+
}
|
70 |
+
|
71 |
+
bool buffer::empty() const noexcept {
|
72 |
+
return (impl(p_)->p_ == nullptr) || (impl(p_)->s_ == 0);
|
73 |
+
}
|
74 |
+
|
75 |
+
void* buffer::data() noexcept {
|
76 |
+
return impl(p_)->p_;
|
77 |
+
}
|
78 |
+
|
79 |
+
void const * buffer::data() const noexcept {
|
80 |
+
return impl(p_)->p_;
|
81 |
+
}
|
82 |
+
|
83 |
+
std::size_t buffer::size() const noexcept {
|
84 |
+
return impl(p_)->s_;
|
85 |
+
}
|
86 |
+
|
87 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/ipc.cpp
ADDED
@@ -0,0 +1,701 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
#include <type_traits>
|
3 |
+
#include <cstring>
|
4 |
+
#include <algorithm>
|
5 |
+
#include <utility> // std::pair, std::move, std::forward
|
6 |
+
#include <atomic>
|
7 |
+
#include <type_traits> // aligned_storage_t
|
8 |
+
#include <string>
|
9 |
+
#include <vector>
|
10 |
+
#include <array>
|
11 |
+
#include <cassert>
|
12 |
+
|
13 |
+
#include "libipc/ipc.h"
|
14 |
+
#include "libipc/def.h"
|
15 |
+
#include "libipc/shm.h"
|
16 |
+
#include "libipc/pool_alloc.h"
|
17 |
+
#include "libipc/queue.h"
|
18 |
+
#include "libipc/policy.h"
|
19 |
+
#include "libipc/rw_lock.h"
|
20 |
+
#include "libipc/waiter.h"
|
21 |
+
|
22 |
+
#include "libipc/utility/log.h"
|
23 |
+
#include "libipc/utility/id_pool.h"
|
24 |
+
#include "libipc/utility/scope_guard.h"
|
25 |
+
#include "libipc/utility/utility.h"
|
26 |
+
|
27 |
+
#include "libipc/memory/resource.h"
|
28 |
+
#include "libipc/platform/detail.h"
|
29 |
+
#include "libipc/circ/elem_array.h"
|
30 |
+
|
31 |
+
namespace {
|
32 |
+
|
33 |
+
using msg_id_t = std::uint32_t;
|
34 |
+
using acc_t = std::atomic<msg_id_t>;
|
35 |
+
|
36 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
37 |
+
struct msg_t;
|
38 |
+
|
39 |
+
template <std::size_t AlignSize>
|
40 |
+
struct msg_t<0, AlignSize> {
|
41 |
+
msg_id_t cc_id_;
|
42 |
+
msg_id_t id_;
|
43 |
+
std::int32_t remain_;
|
44 |
+
bool storage_;
|
45 |
+
};
|
46 |
+
|
47 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
48 |
+
struct msg_t : msg_t<0, AlignSize> {
|
49 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
50 |
+
|
51 |
+
msg_t() = default;
|
52 |
+
msg_t(msg_id_t cc_id, msg_id_t id, std::int32_t remain, void const * data, std::size_t size)
|
53 |
+
: msg_t<0, AlignSize> {cc_id, id, remain, (data == nullptr) || (size == 0)} {
|
54 |
+
if (this->storage_) {
|
55 |
+
if (data != nullptr) {
|
56 |
+
// copy storage-id
|
57 |
+
*reinterpret_cast<ipc::storage_id_t*>(&data_) =
|
58 |
+
*static_cast<ipc::storage_id_t const *>(data);
|
59 |
+
}
|
60 |
+
}
|
61 |
+
else std::memcpy(&data_, data, size);
|
62 |
+
}
|
63 |
+
};
|
64 |
+
|
65 |
+
template <typename T>
|
66 |
+
ipc::buff_t make_cache(T& data, std::size_t size) {
|
67 |
+
auto ptr = ipc::mem::alloc(size);
|
68 |
+
std::memcpy(ptr, &data, (ipc::detail::min)(sizeof(data), size));
|
69 |
+
return { ptr, size, ipc::mem::free };
|
70 |
+
}
|
71 |
+
|
72 |
+
struct cache_t {
|
73 |
+
std::size_t fill_;
|
74 |
+
ipc::buff_t buff_;
|
75 |
+
|
76 |
+
cache_t(std::size_t f, ipc::buff_t && b)
|
77 |
+
: fill_(f), buff_(std::move(b))
|
78 |
+
{}
|
79 |
+
|
80 |
+
void append(void const * data, std::size_t size) {
|
81 |
+
if (fill_ >= buff_.size() || data == nullptr || size == 0) return;
|
82 |
+
auto new_fill = (ipc::detail::min)(fill_ + size, buff_.size());
|
83 |
+
std::memcpy(static_cast<ipc::byte_t*>(buff_.data()) + fill_, data, new_fill - fill_);
|
84 |
+
fill_ = new_fill;
|
85 |
+
}
|
86 |
+
};
|
87 |
+
|
88 |
+
auto cc_acc() {
|
89 |
+
static ipc::shm::handle acc_h("__CA_CONN__", sizeof(acc_t));
|
90 |
+
return static_cast<acc_t*>(acc_h.get());
|
91 |
+
}
|
92 |
+
|
93 |
+
IPC_CONSTEXPR_ std::size_t align_chunk_size(std::size_t size) noexcept {
|
94 |
+
return (((size - 1) / ipc::large_msg_align) + 1) * ipc::large_msg_align;
|
95 |
+
}
|
96 |
+
|
97 |
+
IPC_CONSTEXPR_ std::size_t calc_chunk_size(std::size_t size) noexcept {
|
98 |
+
return ipc::make_align(alignof(std::max_align_t), align_chunk_size(
|
99 |
+
ipc::make_align(alignof(std::max_align_t), sizeof(std::atomic<ipc::circ::cc_t>)) + size));
|
100 |
+
}
|
101 |
+
|
102 |
+
struct chunk_t {
|
103 |
+
std::atomic<ipc::circ::cc_t> &conns() noexcept {
|
104 |
+
return *reinterpret_cast<std::atomic<ipc::circ::cc_t> *>(this);
|
105 |
+
}
|
106 |
+
|
107 |
+
void *data() noexcept {
|
108 |
+
return reinterpret_cast<ipc::byte_t *>(this)
|
109 |
+
+ ipc::make_align(alignof(std::max_align_t), sizeof(std::atomic<ipc::circ::cc_t>));
|
110 |
+
}
|
111 |
+
};
|
112 |
+
|
113 |
+
struct chunk_info_t {
|
114 |
+
ipc::id_pool<> pool_;
|
115 |
+
ipc::spin_lock lock_;
|
116 |
+
|
117 |
+
IPC_CONSTEXPR_ static std::size_t chunks_mem_size(std::size_t chunk_size) noexcept {
|
118 |
+
return ipc::id_pool<>::max_count * chunk_size;
|
119 |
+
}
|
120 |
+
|
121 |
+
ipc::byte_t *chunks_mem() noexcept {
|
122 |
+
return reinterpret_cast<ipc::byte_t *>(this + 1);
|
123 |
+
}
|
124 |
+
|
125 |
+
chunk_t *at(std::size_t chunk_size, ipc::storage_id_t id) noexcept {
|
126 |
+
if (id < 0) return nullptr;
|
127 |
+
return reinterpret_cast<chunk_t *>(chunks_mem() + (chunk_size * id));
|
128 |
+
}
|
129 |
+
};
|
130 |
+
|
131 |
+
auto& chunk_storages() {
|
132 |
+
class chunk_handle_t {
|
133 |
+
ipc::shm::handle handle_;
|
134 |
+
|
135 |
+
public:
|
136 |
+
chunk_info_t *get_info(std::size_t chunk_size) {
|
137 |
+
if (!handle_.valid() &&
|
138 |
+
!handle_.acquire( ("__CHUNK_INFO__" + ipc::to_string(chunk_size)).c_str(),
|
139 |
+
sizeof(chunk_info_t) + chunk_info_t::chunks_mem_size(chunk_size) )) {
|
140 |
+
ipc::error("[chunk_storages] chunk_shm.id_info_.acquire failed: chunk_size = %zd\n", chunk_size);
|
141 |
+
return nullptr;
|
142 |
+
}
|
143 |
+
auto info = static_cast<chunk_info_t*>(handle_.get());
|
144 |
+
if (info == nullptr) {
|
145 |
+
ipc::error("[chunk_storages] chunk_shm.id_info_.get failed: chunk_size = %zd\n", chunk_size);
|
146 |
+
return nullptr;
|
147 |
+
}
|
148 |
+
return info;
|
149 |
+
}
|
150 |
+
};
|
151 |
+
static ipc::map<std::size_t, chunk_handle_t> chunk_hs;
|
152 |
+
return chunk_hs;
|
153 |
+
}
|
154 |
+
|
155 |
+
chunk_info_t *chunk_storage_info(std::size_t chunk_size) {
|
156 |
+
auto &storages = chunk_storages();
|
157 |
+
std::decay_t<decltype(storages)>::iterator it;
|
158 |
+
{
|
159 |
+
static ipc::rw_lock lock;
|
160 |
+
IPC_UNUSED_ std::shared_lock<ipc::rw_lock> guard {lock};
|
161 |
+
if ((it = storages.find(chunk_size)) == storages.end()) {
|
162 |
+
using chunk_handle_t = std::decay_t<decltype(storages)>::value_type::second_type;
|
163 |
+
guard.unlock();
|
164 |
+
IPC_UNUSED_ std::lock_guard<ipc::rw_lock> guard {lock};
|
165 |
+
it = storages.emplace(chunk_size, chunk_handle_t{}).first;
|
166 |
+
}
|
167 |
+
}
|
168 |
+
return it->second.get_info(chunk_size);
|
169 |
+
}
|
170 |
+
|
171 |
+
std::pair<ipc::storage_id_t, void*> acquire_storage(std::size_t size, ipc::circ::cc_t conns) {
|
172 |
+
std::size_t chunk_size = calc_chunk_size(size);
|
173 |
+
auto info = chunk_storage_info(chunk_size);
|
174 |
+
if (info == nullptr) return {};
|
175 |
+
|
176 |
+
info->lock_.lock();
|
177 |
+
info->pool_.prepare();
|
178 |
+
// got an unique id
|
179 |
+
auto id = info->pool_.acquire();
|
180 |
+
info->lock_.unlock();
|
181 |
+
|
182 |
+
auto chunk = info->at(chunk_size, id);
|
183 |
+
if (chunk == nullptr) return {};
|
184 |
+
chunk->conns().store(conns, std::memory_order_relaxed);
|
185 |
+
return { id, chunk->data() };
|
186 |
+
}
|
187 |
+
|
188 |
+
void *find_storage(ipc::storage_id_t id, std::size_t size) {
|
189 |
+
if (id < 0) {
|
190 |
+
ipc::error("[find_storage] id is invalid: id = %ld, size = %zd\n", (long)id, size);
|
191 |
+
return nullptr;
|
192 |
+
}
|
193 |
+
std::size_t chunk_size = calc_chunk_size(size);
|
194 |
+
auto info = chunk_storage_info(chunk_size);
|
195 |
+
if (info == nullptr) return nullptr;
|
196 |
+
return info->at(chunk_size, id)->data();
|
197 |
+
}
|
198 |
+
|
199 |
+
void release_storage(ipc::storage_id_t id, std::size_t size) {
|
200 |
+
if (id < 0) {
|
201 |
+
ipc::error("[release_storage] id is invalid: id = %ld, size = %zd\n", (long)id, size);
|
202 |
+
return;
|
203 |
+
}
|
204 |
+
std::size_t chunk_size = calc_chunk_size(size);
|
205 |
+
auto info = chunk_storage_info(chunk_size);
|
206 |
+
if (info == nullptr) return;
|
207 |
+
info->lock_.lock();
|
208 |
+
info->pool_.release(id);
|
209 |
+
info->lock_.unlock();
|
210 |
+
}
|
211 |
+
|
212 |
+
template <ipc::relat Rp, ipc::relat Rc>
|
213 |
+
bool sub_rc(ipc::wr<Rp, Rc, ipc::trans::unicast>,
|
214 |
+
std::atomic<ipc::circ::cc_t> &/*conns*/, ipc::circ::cc_t /*curr_conns*/, ipc::circ::cc_t /*conn_id*/) noexcept {
|
215 |
+
return true;
|
216 |
+
}
|
217 |
+
|
218 |
+
template <ipc::relat Rp, ipc::relat Rc>
|
219 |
+
bool sub_rc(ipc::wr<Rp, Rc, ipc::trans::broadcast>,
|
220 |
+
std::atomic<ipc::circ::cc_t> &conns, ipc::circ::cc_t curr_conns, ipc::circ::cc_t conn_id) noexcept {
|
221 |
+
auto last_conns = curr_conns & ~conn_id;
|
222 |
+
for (unsigned k = 0;;) {
|
223 |
+
auto chunk_conns = conns.load(std::memory_order_acquire);
|
224 |
+
if (conns.compare_exchange_weak(chunk_conns, chunk_conns & last_conns, std::memory_order_release)) {
|
225 |
+
return (chunk_conns & last_conns) == 0;
|
226 |
+
}
|
227 |
+
ipc::yield(k);
|
228 |
+
}
|
229 |
+
}
|
230 |
+
|
231 |
+
template <typename Flag>
|
232 |
+
void recycle_storage(ipc::storage_id_t id, std::size_t size, ipc::circ::cc_t curr_conns, ipc::circ::cc_t conn_id) {
|
233 |
+
if (id < 0) {
|
234 |
+
ipc::error("[recycle_storage] id is invalid: id = %ld, size = %zd\n", (long)id, size);
|
235 |
+
return;
|
236 |
+
}
|
237 |
+
std::size_t chunk_size = calc_chunk_size(size);
|
238 |
+
auto info = chunk_storage_info(chunk_size);
|
239 |
+
if (info == nullptr) return;
|
240 |
+
|
241 |
+
auto chunk = info->at(chunk_size, id);
|
242 |
+
if (chunk == nullptr) return;
|
243 |
+
|
244 |
+
if (!sub_rc(Flag{}, chunk->conns(), curr_conns, conn_id)) {
|
245 |
+
return;
|
246 |
+
}
|
247 |
+
info->lock_.lock();
|
248 |
+
info->pool_.release(id);
|
249 |
+
info->lock_.unlock();
|
250 |
+
}
|
251 |
+
|
252 |
+
template <typename MsgT>
|
253 |
+
bool clear_message(void* p) {
|
254 |
+
auto msg = static_cast<MsgT*>(p);
|
255 |
+
if (msg->storage_) {
|
256 |
+
std::int32_t r_size = static_cast<std::int32_t>(ipc::data_length) + msg->remain_;
|
257 |
+
if (r_size <= 0) {
|
258 |
+
ipc::error("[clear_message] invalid msg size: %d\n", (int)r_size);
|
259 |
+
return true;
|
260 |
+
}
|
261 |
+
release_storage(
|
262 |
+
*reinterpret_cast<ipc::storage_id_t*>(&msg->data_),
|
263 |
+
static_cast<std::size_t>(r_size));
|
264 |
+
}
|
265 |
+
return true;
|
266 |
+
}
|
267 |
+
|
268 |
+
struct conn_info_head {
|
269 |
+
|
270 |
+
ipc::string name_;
|
271 |
+
msg_id_t cc_id_; // connection-info id
|
272 |
+
ipc::detail::waiter cc_waiter_, wt_waiter_, rd_waiter_;
|
273 |
+
ipc::shm::handle acc_h_;
|
274 |
+
|
275 |
+
conn_info_head(char const * name)
|
276 |
+
: name_ {name}
|
277 |
+
, cc_id_ {(cc_acc() == nullptr) ? 0 : cc_acc()->fetch_add(1, std::memory_order_relaxed)}
|
278 |
+
, cc_waiter_{("__CC_CONN__" + name_).c_str()}
|
279 |
+
, wt_waiter_{("__WT_CONN__" + name_).c_str()}
|
280 |
+
, rd_waiter_{("__RD_CONN__" + name_).c_str()}
|
281 |
+
, acc_h_ {("__AC_CONN__" + name_).c_str(), sizeof(acc_t)} {
|
282 |
+
}
|
283 |
+
|
284 |
+
void quit_waiting() {
|
285 |
+
cc_waiter_.quit_waiting();
|
286 |
+
wt_waiter_.quit_waiting();
|
287 |
+
rd_waiter_.quit_waiting();
|
288 |
+
}
|
289 |
+
|
290 |
+
auto acc() {
|
291 |
+
return static_cast<acc_t*>(acc_h_.get());
|
292 |
+
}
|
293 |
+
|
294 |
+
auto& recv_cache() {
|
295 |
+
thread_local ipc::unordered_map<msg_id_t, cache_t> tls;
|
296 |
+
return tls;
|
297 |
+
}
|
298 |
+
};
|
299 |
+
|
300 |
+
template <typename W, typename F>
|
301 |
+
bool wait_for(W& waiter, F&& pred, std::uint64_t tm) {
|
302 |
+
if (tm == 0) return !pred();
|
303 |
+
for (unsigned k = 0; pred();) {
|
304 |
+
bool ret = true;
|
305 |
+
ipc::sleep(k, [&k, &ret, &waiter, &pred, tm] {
|
306 |
+
ret = waiter.wait_if(std::forward<F>(pred), tm);
|
307 |
+
k = 0;
|
308 |
+
});
|
309 |
+
if (!ret) return false; // timeout or fail
|
310 |
+
if (k == 0) break; // k has been reset
|
311 |
+
}
|
312 |
+
return true;
|
313 |
+
}
|
314 |
+
|
315 |
+
template <typename Policy,
|
316 |
+
std::size_t DataSize = ipc::data_length,
|
317 |
+
std::size_t AlignSize = (ipc::detail::min)(DataSize, alignof(std::max_align_t))>
|
318 |
+
struct queue_generator {
|
319 |
+
|
320 |
+
using queue_t = ipc::queue<msg_t<DataSize, AlignSize>, Policy>;
|
321 |
+
|
322 |
+
struct conn_info_t : conn_info_head {
|
323 |
+
queue_t que_;
|
324 |
+
|
325 |
+
conn_info_t(char const * name)
|
326 |
+
: conn_info_head{name}
|
327 |
+
, que_{("__QU_CONN__" +
|
328 |
+
ipc::to_string(DataSize) + "__" +
|
329 |
+
ipc::to_string(AlignSize) + "__" + name).c_str()} {
|
330 |
+
}
|
331 |
+
|
332 |
+
void disconnect_receiver() {
|
333 |
+
bool dis = que_.disconnect();
|
334 |
+
this->quit_waiting();
|
335 |
+
if (dis) {
|
336 |
+
this->recv_cache().clear();
|
337 |
+
}
|
338 |
+
}
|
339 |
+
};
|
340 |
+
};
|
341 |
+
|
342 |
+
template <typename Policy>
|
343 |
+
struct detail_impl {
|
344 |
+
|
345 |
+
using policy_t = Policy;
|
346 |
+
using flag_t = typename policy_t::flag_t;
|
347 |
+
using queue_t = typename queue_generator<policy_t>::queue_t;
|
348 |
+
using conn_info_t = typename queue_generator<policy_t>::conn_info_t;
|
349 |
+
|
350 |
+
constexpr static conn_info_t* info_of(ipc::handle_t h) noexcept {
|
351 |
+
return static_cast<conn_info_t*>(h);
|
352 |
+
}
|
353 |
+
|
354 |
+
constexpr static queue_t* queue_of(ipc::handle_t h) noexcept {
|
355 |
+
return (info_of(h) == nullptr) ? nullptr : &(info_of(h)->que_);
|
356 |
+
}
|
357 |
+
|
358 |
+
/* API implementations */
|
359 |
+
|
360 |
+
static void disconnect(ipc::handle_t h) {
|
361 |
+
auto que = queue_of(h);
|
362 |
+
if (que == nullptr) {
|
363 |
+
return;
|
364 |
+
}
|
365 |
+
que->shut_sending();
|
366 |
+
assert(info_of(h) != nullptr);
|
367 |
+
info_of(h)->disconnect_receiver();
|
368 |
+
}
|
369 |
+
|
370 |
+
static bool reconnect(ipc::handle_t * ph, bool start_to_recv) {
|
371 |
+
assert(ph != nullptr);
|
372 |
+
assert(*ph != nullptr);
|
373 |
+
auto que = queue_of(*ph);
|
374 |
+
if (que == nullptr) {
|
375 |
+
return false;
|
376 |
+
}
|
377 |
+
if (start_to_recv) {
|
378 |
+
que->shut_sending();
|
379 |
+
if (que->connect()) { // wouldn't connect twice
|
380 |
+
info_of(*ph)->cc_waiter_.broadcast();
|
381 |
+
return true;
|
382 |
+
}
|
383 |
+
return false;
|
384 |
+
}
|
385 |
+
// start_to_recv == false
|
386 |
+
if (que->connected()) {
|
387 |
+
info_of(*ph)->disconnect_receiver();
|
388 |
+
}
|
389 |
+
return que->ready_sending();
|
390 |
+
}
|
391 |
+
|
392 |
+
static bool connect(ipc::handle_t * ph, char const * name, bool start_to_recv) {
|
393 |
+
assert(ph != nullptr);
|
394 |
+
if (*ph == nullptr) {
|
395 |
+
*ph = ipc::mem::alloc<conn_info_t>(name);
|
396 |
+
}
|
397 |
+
return reconnect(ph, start_to_recv);
|
398 |
+
}
|
399 |
+
|
400 |
+
static void destroy(ipc::handle_t h) {
|
401 |
+
disconnect(h);
|
402 |
+
ipc::mem::free(info_of(h));
|
403 |
+
}
|
404 |
+
|
405 |
+
static std::size_t recv_count(ipc::handle_t h) noexcept {
|
406 |
+
auto que = queue_of(h);
|
407 |
+
if (que == nullptr) {
|
408 |
+
return ipc::invalid_value;
|
409 |
+
}
|
410 |
+
return que->conn_count();
|
411 |
+
}
|
412 |
+
|
413 |
+
static bool wait_for_recv(ipc::handle_t h, std::size_t r_count, std::uint64_t tm) {
|
414 |
+
auto que = queue_of(h);
|
415 |
+
if (que == nullptr) {
|
416 |
+
return false;
|
417 |
+
}
|
418 |
+
return wait_for(info_of(h)->cc_waiter_, [que, r_count] {
|
419 |
+
return que->conn_count() < r_count;
|
420 |
+
}, tm);
|
421 |
+
}
|
422 |
+
|
423 |
+
template <typename F>
|
424 |
+
static bool send(F&& gen_push, ipc::handle_t h, void const * data, std::size_t size) {
|
425 |
+
if (data == nullptr || size == 0) {
|
426 |
+
ipc::error("fail: send(%p, %zd)\n", data, size);
|
427 |
+
return false;
|
428 |
+
}
|
429 |
+
auto que = queue_of(h);
|
430 |
+
if (que == nullptr) {
|
431 |
+
ipc::error("fail: send, queue_of(h) == nullptr\n");
|
432 |
+
return false;
|
433 |
+
}
|
434 |
+
if (que->elems() == nullptr) {
|
435 |
+
ipc::error("fail: send, queue_of(h)->elems() == nullptr\n");
|
436 |
+
return false;
|
437 |
+
}
|
438 |
+
if (!que->ready_sending()) {
|
439 |
+
ipc::error("fail: send, que->ready_sending() == false\n");
|
440 |
+
return false;
|
441 |
+
}
|
442 |
+
ipc::circ::cc_t conns = que->elems()->connections(std::memory_order_relaxed);
|
443 |
+
if (conns == 0) {
|
444 |
+
ipc::error("fail: send, there is no receiver on this connection.\n");
|
445 |
+
return false;
|
446 |
+
}
|
447 |
+
// calc a new message id
|
448 |
+
auto acc = info_of(h)->acc();
|
449 |
+
if (acc == nullptr) {
|
450 |
+
ipc::error("fail: send, info_of(h)->acc() == nullptr\n");
|
451 |
+
return false;
|
452 |
+
}
|
453 |
+
auto msg_id = acc->fetch_add(1, std::memory_order_relaxed);
|
454 |
+
auto try_push = std::forward<F>(gen_push)(info_of(h), que, msg_id);
|
455 |
+
if (size > ipc::large_msg_limit) {
|
456 |
+
auto dat = acquire_storage(size, conns);
|
457 |
+
void * buf = dat.second;
|
458 |
+
if (buf != nullptr) {
|
459 |
+
std::memcpy(buf, data, size);
|
460 |
+
return try_push(static_cast<std::int32_t>(size) -
|
461 |
+
static_cast<std::int32_t>(ipc::data_length), &(dat.first), 0);
|
462 |
+
}
|
463 |
+
// try using message fragment
|
464 |
+
//ipc::log("fail: shm::handle for big message. msg_id: %zd, size: %zd\n", msg_id, size);
|
465 |
+
}
|
466 |
+
// push message fragment
|
467 |
+
std::int32_t offset = 0;
|
468 |
+
for (std::int32_t i = 0; i < static_cast<std::int32_t>(size / ipc::data_length); ++i, offset += ipc::data_length) {
|
469 |
+
if (!try_push(static_cast<std::int32_t>(size) - offset - static_cast<std::int32_t>(ipc::data_length),
|
470 |
+
static_cast<ipc::byte_t const *>(data) + offset, ipc::data_length)) {
|
471 |
+
return false;
|
472 |
+
}
|
473 |
+
}
|
474 |
+
// if remain > 0, this is the last message fragment
|
475 |
+
std::int32_t remain = static_cast<std::int32_t>(size) - offset;
|
476 |
+
if (remain > 0) {
|
477 |
+
if (!try_push(remain - static_cast<std::int32_t>(ipc::data_length),
|
478 |
+
static_cast<ipc::byte_t const *>(data) + offset,
|
479 |
+
static_cast<std::size_t>(remain))) {
|
480 |
+
return false;
|
481 |
+
}
|
482 |
+
}
|
483 |
+
return true;
|
484 |
+
}
|
485 |
+
|
486 |
+
static bool send(ipc::handle_t h, void const * data, std::size_t size, std::uint64_t tm) {
|
487 |
+
return send([tm](auto info, auto que, auto msg_id) {
|
488 |
+
return [tm, info, que, msg_id](std::int32_t remain, void const * data, std::size_t size) {
|
489 |
+
if (!wait_for(info->wt_waiter_, [&] {
|
490 |
+
return !que->push(
|
491 |
+
[](void*) { return true; },
|
492 |
+
info->cc_id_, msg_id, remain, data, size);
|
493 |
+
}, tm)) {
|
494 |
+
ipc::log("force_push: msg_id = %zd, remain = %d, size = %zd\n", msg_id, remain, size);
|
495 |
+
if (!que->force_push(
|
496 |
+
clear_message<typename queue_t::value_t>,
|
497 |
+
info->cc_id_, msg_id, remain, data, size)) {
|
498 |
+
return false;
|
499 |
+
}
|
500 |
+
}
|
501 |
+
info->rd_waiter_.broadcast();
|
502 |
+
return true;
|
503 |
+
};
|
504 |
+
}, h, data, size);
|
505 |
+
}
|
506 |
+
|
507 |
+
static bool try_send(ipc::handle_t h, void const * data, std::size_t size, std::uint64_t tm) {
|
508 |
+
return send([tm](auto info, auto que, auto msg_id) {
|
509 |
+
return [tm, info, que, msg_id](std::int32_t remain, void const * data, std::size_t size) {
|
510 |
+
if (!wait_for(info->wt_waiter_, [&] {
|
511 |
+
return !que->push(
|
512 |
+
[](void*) { return true; },
|
513 |
+
info->cc_id_, msg_id, remain, data, size);
|
514 |
+
}, tm)) {
|
515 |
+
return false;
|
516 |
+
}
|
517 |
+
info->rd_waiter_.broadcast();
|
518 |
+
return true;
|
519 |
+
};
|
520 |
+
}, h, data, size);
|
521 |
+
}
|
522 |
+
|
523 |
+
static ipc::buff_t recv(ipc::handle_t h, std::uint64_t tm) {
|
524 |
+
auto que = queue_of(h);
|
525 |
+
if (que == nullptr) {
|
526 |
+
ipc::error("fail: recv, queue_of(h) == nullptr\n");
|
527 |
+
return {};
|
528 |
+
}
|
529 |
+
if (!que->connected()) {
|
530 |
+
// hasn't connected yet, just return.
|
531 |
+
return {};
|
532 |
+
}
|
533 |
+
auto& rc = info_of(h)->recv_cache();
|
534 |
+
for (;;) {
|
535 |
+
// pop a new message
|
536 |
+
typename queue_t::value_t msg;
|
537 |
+
if (!wait_for(info_of(h)->rd_waiter_, [que, &msg] {
|
538 |
+
return !que->pop(msg);
|
539 |
+
}, tm)) {
|
540 |
+
// pop failed, just return.
|
541 |
+
return {};
|
542 |
+
}
|
543 |
+
info_of(h)->wt_waiter_.broadcast();
|
544 |
+
if ((info_of(h)->acc() != nullptr) && (msg.cc_id_ == info_of(h)->cc_id_)) {
|
545 |
+
continue; // ignore message to self
|
546 |
+
}
|
547 |
+
// msg.remain_ may minus & abs(msg.remain_) < data_length
|
548 |
+
std::int32_t r_size = static_cast<std::int32_t>(ipc::data_length) + msg.remain_;
|
549 |
+
if (r_size <= 0) {
|
550 |
+
ipc::error("fail: recv, r_size = %d\n", (int)r_size);
|
551 |
+
return {};
|
552 |
+
}
|
553 |
+
std::size_t msg_size = static_cast<std::size_t>(r_size);
|
554 |
+
// large message
|
555 |
+
if (msg.storage_) {
|
556 |
+
ipc::storage_id_t buf_id = *reinterpret_cast<ipc::storage_id_t*>(&msg.data_);
|
557 |
+
void* buf = find_storage(buf_id, msg_size);
|
558 |
+
if (buf != nullptr) {
|
559 |
+
struct recycle_t {
|
560 |
+
ipc::storage_id_t storage_id;
|
561 |
+
ipc::circ::cc_t curr_conns;
|
562 |
+
ipc::circ::cc_t conn_id;
|
563 |
+
} *r_info = ipc::mem::alloc<recycle_t>(recycle_t{
|
564 |
+
buf_id, que->elems()->connections(std::memory_order_relaxed), que->connected_id()
|
565 |
+
});
|
566 |
+
if (r_info == nullptr) {
|
567 |
+
ipc::log("fail: ipc::mem::alloc<recycle_t>.\n");
|
568 |
+
return ipc::buff_t{buf, msg_size}; // no recycle
|
569 |
+
} else {
|
570 |
+
return ipc::buff_t{buf, msg_size, [](void* p_info, std::size_t size) {
|
571 |
+
auto r_info = static_cast<recycle_t *>(p_info);
|
572 |
+
IPC_UNUSED_ auto finally = ipc::guard([r_info] {
|
573 |
+
ipc::mem::free(r_info);
|
574 |
+
});
|
575 |
+
recycle_storage<flag_t>(r_info->storage_id, size, r_info->curr_conns, r_info->conn_id);
|
576 |
+
}, r_info};
|
577 |
+
}
|
578 |
+
} else {
|
579 |
+
ipc::log("fail: shm::handle for large message. msg_id: %zd, buf_id: %zd, size: %zd\n", msg.id_, buf_id, msg_size);
|
580 |
+
continue;
|
581 |
+
}
|
582 |
+
}
|
583 |
+
// find cache with msg.id_
|
584 |
+
auto cac_it = rc.find(msg.id_);
|
585 |
+
if (cac_it == rc.end()) {
|
586 |
+
if (msg_size <= ipc::data_length) {
|
587 |
+
return make_cache(msg.data_, msg_size);
|
588 |
+
}
|
589 |
+
// gc
|
590 |
+
if (rc.size() > 1024) {
|
591 |
+
std::vector<msg_id_t> need_del;
|
592 |
+
for (auto const & pair : rc) {
|
593 |
+
auto cmp = std::minmax(msg.id_, pair.first);
|
594 |
+
if (cmp.second - cmp.first > 8192) {
|
595 |
+
need_del.push_back(pair.first);
|
596 |
+
}
|
597 |
+
}
|
598 |
+
for (auto id : need_del) rc.erase(id);
|
599 |
+
}
|
600 |
+
// cache the first message fragment
|
601 |
+
rc.emplace(msg.id_, cache_t { ipc::data_length, make_cache(msg.data_, msg_size) });
|
602 |
+
}
|
603 |
+
// has cached before this message
|
604 |
+
else {
|
605 |
+
auto& cac = cac_it->second;
|
606 |
+
// this is the last message fragment
|
607 |
+
if (msg.remain_ <= 0) {
|
608 |
+
cac.append(&(msg.data_), msg_size);
|
609 |
+
// finish this message, erase it from cache
|
610 |
+
auto buff = std::move(cac.buff_);
|
611 |
+
rc.erase(cac_it);
|
612 |
+
return buff;
|
613 |
+
}
|
614 |
+
// there are remain datas after this message
|
615 |
+
cac.append(&(msg.data_), ipc::data_length);
|
616 |
+
}
|
617 |
+
}
|
618 |
+
}
|
619 |
+
|
620 |
+
static ipc::buff_t try_recv(ipc::handle_t h) {
|
621 |
+
return recv(h, 0);
|
622 |
+
}
|
623 |
+
|
624 |
+
}; // detail_impl<Policy>
|
625 |
+
|
626 |
+
template <typename Flag>
|
627 |
+
using policy_t = ipc::policy::choose<ipc::circ::elem_array, Flag>;
|
628 |
+
|
629 |
+
} // internal-linkage
|
630 |
+
|
631 |
+
namespace ipc {
|
632 |
+
|
633 |
+
template <typename Flag>
|
634 |
+
ipc::handle_t chan_impl<Flag>::inited() {
|
635 |
+
ipc::detail::waiter::init();
|
636 |
+
return nullptr;
|
637 |
+
}
|
638 |
+
|
639 |
+
template <typename Flag>
|
640 |
+
bool chan_impl<Flag>::connect(ipc::handle_t * ph, char const * name, unsigned mode) {
|
641 |
+
return detail_impl<policy_t<Flag>>::connect(ph, name, mode & receiver);
|
642 |
+
}
|
643 |
+
|
644 |
+
template <typename Flag>
|
645 |
+
bool chan_impl<Flag>::reconnect(ipc::handle_t * ph, unsigned mode) {
|
646 |
+
return detail_impl<policy_t<Flag>>::reconnect(ph, mode & receiver);
|
647 |
+
}
|
648 |
+
|
649 |
+
template <typename Flag>
|
650 |
+
void chan_impl<Flag>::disconnect(ipc::handle_t h) {
|
651 |
+
detail_impl<policy_t<Flag>>::disconnect(h);
|
652 |
+
}
|
653 |
+
|
654 |
+
template <typename Flag>
|
655 |
+
void chan_impl<Flag>::destroy(ipc::handle_t h) {
|
656 |
+
detail_impl<policy_t<Flag>>::destroy(h);
|
657 |
+
}
|
658 |
+
|
659 |
+
template <typename Flag>
|
660 |
+
char const * chan_impl<Flag>::name(ipc::handle_t h) {
|
661 |
+
auto info = detail_impl<policy_t<Flag>>::info_of(h);
|
662 |
+
return (info == nullptr) ? nullptr : info->name_.c_str();
|
663 |
+
}
|
664 |
+
|
665 |
+
template <typename Flag>
|
666 |
+
std::size_t chan_impl<Flag>::recv_count(ipc::handle_t h) {
|
667 |
+
return detail_impl<policy_t<Flag>>::recv_count(h);
|
668 |
+
}
|
669 |
+
|
670 |
+
template <typename Flag>
|
671 |
+
bool chan_impl<Flag>::wait_for_recv(ipc::handle_t h, std::size_t r_count, std::uint64_t tm) {
|
672 |
+
return detail_impl<policy_t<Flag>>::wait_for_recv(h, r_count, tm);
|
673 |
+
}
|
674 |
+
|
675 |
+
template <typename Flag>
|
676 |
+
bool chan_impl<Flag>::send(ipc::handle_t h, void const * data, std::size_t size, std::uint64_t tm) {
|
677 |
+
return detail_impl<policy_t<Flag>>::send(h, data, size, tm);
|
678 |
+
}
|
679 |
+
|
680 |
+
template <typename Flag>
|
681 |
+
buff_t chan_impl<Flag>::recv(ipc::handle_t h, std::uint64_t tm) {
|
682 |
+
return detail_impl<policy_t<Flag>>::recv(h, tm);
|
683 |
+
}
|
684 |
+
|
685 |
+
template <typename Flag>
|
686 |
+
bool chan_impl<Flag>::try_send(ipc::handle_t h, void const * data, std::size_t size, std::uint64_t tm) {
|
687 |
+
return detail_impl<policy_t<Flag>>::try_send(h, data, size, tm);
|
688 |
+
}
|
689 |
+
|
690 |
+
template <typename Flag>
|
691 |
+
buff_t chan_impl<Flag>::try_recv(ipc::handle_t h) {
|
692 |
+
return detail_impl<policy_t<Flag>>::try_recv(h);
|
693 |
+
}
|
694 |
+
|
695 |
+
template struct chan_impl<ipc::wr<relat::single, relat::single, trans::unicast >>;
|
696 |
+
// template struct chan_impl<ipc::wr<relat::single, relat::multi , trans::unicast >>; // TBD
|
697 |
+
// template struct chan_impl<ipc::wr<relat::multi , relat::multi , trans::unicast >>; // TBD
|
698 |
+
template struct chan_impl<ipc::wr<relat::single, relat::multi , trans::broadcast>>;
|
699 |
+
template struct chan_impl<ipc::wr<relat::multi , relat::multi , trans::broadcast>>;
|
700 |
+
|
701 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/policy.h
ADDED
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pragma once
|
2 |
+
|
3 |
+
#include <type_traits>
|
4 |
+
|
5 |
+
#include "libipc/def.h"
|
6 |
+
#include "libipc/prod_cons.h"
|
7 |
+
|
8 |
+
#include "libipc/circ/elem_array.h"
|
9 |
+
|
10 |
+
namespace ipc {
|
11 |
+
namespace policy {
|
12 |
+
|
13 |
+
template <template <typename, std::size_t...> class Elems, typename Flag>
|
14 |
+
struct choose;
|
15 |
+
|
16 |
+
template <typename Flag>
|
17 |
+
struct choose<circ::elem_array, Flag> {
|
18 |
+
using flag_t = Flag;
|
19 |
+
|
20 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
21 |
+
using elems_t = circ::elem_array<ipc::prod_cons_impl<flag_t>, DataSize, AlignSize>;
|
22 |
+
};
|
23 |
+
|
24 |
+
} // namespace policy
|
25 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/pool_alloc.cpp
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#include "libipc/pool_alloc.h"
|
2 |
+
|
3 |
+
#include "libipc/memory/resource.h"
|
4 |
+
|
5 |
+
namespace ipc {
|
6 |
+
namespace mem {
|
7 |
+
|
8 |
+
void* pool_alloc::alloc(std::size_t size) {
|
9 |
+
return async_pool_alloc::alloc(size);
|
10 |
+
}
|
11 |
+
|
12 |
+
void pool_alloc::free(void* p, std::size_t size) {
|
13 |
+
async_pool_alloc::free(p, size);
|
14 |
+
}
|
15 |
+
|
16 |
+
} // namespace mem
|
17 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/prod_cons.h
ADDED
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pragma once
|
2 |
+
|
3 |
+
#include <atomic>
|
4 |
+
#include <utility>
|
5 |
+
#include <cstring>
|
6 |
+
#include <type_traits>
|
7 |
+
#include <cstdint>
|
8 |
+
|
9 |
+
#include "libipc/def.h"
|
10 |
+
|
11 |
+
#include "libipc/platform/detail.h"
|
12 |
+
#include "libipc/circ/elem_def.h"
|
13 |
+
#include "libipc/utility/log.h"
|
14 |
+
#include "libipc/utility/utility.h"
|
15 |
+
|
16 |
+
namespace ipc {
|
17 |
+
|
18 |
+
////////////////////////////////////////////////////////////////
|
19 |
+
/// producer-consumer implementation
|
20 |
+
////////////////////////////////////////////////////////////////
|
21 |
+
|
22 |
+
template <typename Flag>
|
23 |
+
struct prod_cons_impl;
|
24 |
+
|
25 |
+
template <>
|
26 |
+
struct prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
|
27 |
+
|
28 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
29 |
+
struct elem_t {
|
30 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
31 |
+
};
|
32 |
+
|
33 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> rd_; // read index
|
34 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
|
35 |
+
|
36 |
+
constexpr circ::u2_t cursor() const noexcept {
|
37 |
+
return 0;
|
38 |
+
}
|
39 |
+
|
40 |
+
template <typename W, typename F, typename E>
|
41 |
+
bool push(W* /*wrapper*/, F&& f, E* elems) {
|
42 |
+
auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed));
|
43 |
+
if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) {
|
44 |
+
return false; // full
|
45 |
+
}
|
46 |
+
std::forward<F>(f)(&(elems[cur_wt].data_));
|
47 |
+
wt_.fetch_add(1, std::memory_order_release);
|
48 |
+
return true;
|
49 |
+
}
|
50 |
+
|
51 |
+
/**
|
52 |
+
* In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'.
|
53 |
+
* So we could just disconnect all connections of receiver, and return false.
|
54 |
+
*/
|
55 |
+
template <typename W, typename F, typename E>
|
56 |
+
bool force_push(W* wrapper, F&&, E*) {
|
57 |
+
wrapper->elems()->disconnect_receiver(~static_cast<circ::cc_t>(0u));
|
58 |
+
return false;
|
59 |
+
}
|
60 |
+
|
61 |
+
template <typename W, typename F, typename R, typename E>
|
62 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) {
|
63 |
+
auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed));
|
64 |
+
if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) {
|
65 |
+
return false; // empty
|
66 |
+
}
|
67 |
+
std::forward<F>(f)(&(elems[cur_rd].data_));
|
68 |
+
std::forward<R>(out)(true);
|
69 |
+
rd_.fetch_add(1, std::memory_order_release);
|
70 |
+
return true;
|
71 |
+
}
|
72 |
+
};
|
73 |
+
|
74 |
+
template <>
|
75 |
+
struct prod_cons_impl<wr<relat::single, relat::multi , trans::unicast>>
|
76 |
+
: prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
|
77 |
+
|
78 |
+
template <typename W, typename F, typename E>
|
79 |
+
bool force_push(W* wrapper, F&&, E*) {
|
80 |
+
wrapper->elems()->disconnect_receiver(1);
|
81 |
+
return false;
|
82 |
+
}
|
83 |
+
|
84 |
+
template <typename W, typename F, typename R,
|
85 |
+
template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
|
86 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
|
87 |
+
byte_t buff[DS];
|
88 |
+
for (unsigned k = 0;;) {
|
89 |
+
auto cur_rd = rd_.load(std::memory_order_relaxed);
|
90 |
+
if (circ::index_of(cur_rd) ==
|
91 |
+
circ::index_of(wt_.load(std::memory_order_acquire))) {
|
92 |
+
return false; // empty
|
93 |
+
}
|
94 |
+
std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
|
95 |
+
if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
|
96 |
+
std::forward<F>(f)(buff);
|
97 |
+
std::forward<R>(out)(true);
|
98 |
+
return true;
|
99 |
+
}
|
100 |
+
ipc::yield(k);
|
101 |
+
}
|
102 |
+
}
|
103 |
+
};
|
104 |
+
|
105 |
+
template <>
|
106 |
+
struct prod_cons_impl<wr<relat::multi , relat::multi, trans::unicast>>
|
107 |
+
: prod_cons_impl<wr<relat::single, relat::multi, trans::unicast>> {
|
108 |
+
|
109 |
+
using flag_t = std::uint64_t;
|
110 |
+
|
111 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
112 |
+
struct elem_t {
|
113 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
114 |
+
std::atomic<flag_t> f_ct_ { 0 }; // commit flag
|
115 |
+
};
|
116 |
+
|
117 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
|
118 |
+
|
119 |
+
template <typename W, typename F, typename E>
|
120 |
+
bool push(W* /*wrapper*/, F&& f, E* elems) {
|
121 |
+
circ::u2_t cur_ct, nxt_ct;
|
122 |
+
for (unsigned k = 0;;) {
|
123 |
+
cur_ct = ct_.load(std::memory_order_relaxed);
|
124 |
+
if (circ::index_of(nxt_ct = cur_ct + 1) ==
|
125 |
+
circ::index_of(rd_.load(std::memory_order_acquire))) {
|
126 |
+
return false; // full
|
127 |
+
}
|
128 |
+
if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) {
|
129 |
+
break;
|
130 |
+
}
|
131 |
+
ipc::yield(k);
|
132 |
+
}
|
133 |
+
auto* el = elems + circ::index_of(cur_ct);
|
134 |
+
std::forward<F>(f)(&(el->data_));
|
135 |
+
// set flag & try update wt
|
136 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
137 |
+
while (1) {
|
138 |
+
auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
|
139 |
+
if (cur_ct != wt_.load(std::memory_order_relaxed)) {
|
140 |
+
return true;
|
141 |
+
}
|
142 |
+
if ((~cac_ct) != cur_ct) {
|
143 |
+
return true;
|
144 |
+
}
|
145 |
+
if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) {
|
146 |
+
return true;
|
147 |
+
}
|
148 |
+
wt_.store(nxt_ct, std::memory_order_release);
|
149 |
+
cur_ct = nxt_ct;
|
150 |
+
nxt_ct = cur_ct + 1;
|
151 |
+
el = elems + circ::index_of(cur_ct);
|
152 |
+
}
|
153 |
+
return true;
|
154 |
+
}
|
155 |
+
|
156 |
+
template <typename W, typename F, typename E>
|
157 |
+
bool force_push(W* wrapper, F&&, E*) {
|
158 |
+
wrapper->elems()->disconnect_receiver(1);
|
159 |
+
return false;
|
160 |
+
}
|
161 |
+
|
162 |
+
template <typename W, typename F, typename R,
|
163 |
+
template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
|
164 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
|
165 |
+
byte_t buff[DS];
|
166 |
+
for (unsigned k = 0;;) {
|
167 |
+
auto cur_rd = rd_.load(std::memory_order_relaxed);
|
168 |
+
auto cur_wt = wt_.load(std::memory_order_acquire);
|
169 |
+
auto id_rd = circ::index_of(cur_rd);
|
170 |
+
auto id_wt = circ::index_of(cur_wt);
|
171 |
+
if (id_rd == id_wt) {
|
172 |
+
auto* el = elems + id_wt;
|
173 |
+
auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
|
174 |
+
if ((~cac_ct) != cur_wt) {
|
175 |
+
return false; // empty
|
176 |
+
}
|
177 |
+
if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) {
|
178 |
+
wt_.store(cur_wt + 1, std::memory_order_release);
|
179 |
+
}
|
180 |
+
k = 0;
|
181 |
+
}
|
182 |
+
else {
|
183 |
+
std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
|
184 |
+
if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
|
185 |
+
std::forward<F>(f)(buff);
|
186 |
+
std::forward<R>(out)(true);
|
187 |
+
return true;
|
188 |
+
}
|
189 |
+
ipc::yield(k);
|
190 |
+
}
|
191 |
+
}
|
192 |
+
}
|
193 |
+
};
|
194 |
+
|
195 |
+
template <>
|
196 |
+
struct prod_cons_impl<wr<relat::single, relat::multi, trans::broadcast>> {
|
197 |
+
|
198 |
+
using rc_t = std::uint64_t;
|
199 |
+
|
200 |
+
enum : rc_t {
|
201 |
+
ep_mask = 0x00000000ffffffffull,
|
202 |
+
ep_incr = 0x0000000100000000ull
|
203 |
+
};
|
204 |
+
|
205 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
206 |
+
struct elem_t {
|
207 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
208 |
+
std::atomic<rc_t> rc_ { 0 }; // read-counter
|
209 |
+
};
|
210 |
+
|
211 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
|
212 |
+
alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer
|
213 |
+
|
214 |
+
circ::u2_t cursor() const noexcept {
|
215 |
+
return wt_.load(std::memory_order_acquire);
|
216 |
+
}
|
217 |
+
|
218 |
+
template <typename W, typename F, typename E>
|
219 |
+
bool push(W* wrapper, F&& f, E* elems) {
|
220 |
+
E* el;
|
221 |
+
for (unsigned k = 0;;) {
|
222 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
223 |
+
if (cc == 0) return false; // no reader
|
224 |
+
el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
|
225 |
+
// check all consumers have finished reading this element
|
226 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
227 |
+
circ::cc_t rem_cc = cur_rc & ep_mask;
|
228 |
+
if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) {
|
229 |
+
return false; // has not finished yet
|
230 |
+
}
|
231 |
+
// consider rem_cc to be 0 here
|
232 |
+
if (el->rc_.compare_exchange_weak(
|
233 |
+
cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
|
234 |
+
break;
|
235 |
+
}
|
236 |
+
ipc::yield(k);
|
237 |
+
}
|
238 |
+
std::forward<F>(f)(&(el->data_));
|
239 |
+
wt_.fetch_add(1, std::memory_order_release);
|
240 |
+
return true;
|
241 |
+
}
|
242 |
+
|
243 |
+
template <typename W, typename F, typename E>
|
244 |
+
bool force_push(W* wrapper, F&& f, E* elems) {
|
245 |
+
E* el;
|
246 |
+
epoch_ += ep_incr;
|
247 |
+
for (unsigned k = 0;;) {
|
248 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
249 |
+
if (cc == 0) return false; // no reader
|
250 |
+
el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
|
251 |
+
// check all consumers have finished reading this element
|
252 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
253 |
+
circ::cc_t rem_cc = cur_rc & ep_mask;
|
254 |
+
if (cc & rem_cc) {
|
255 |
+
ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
|
256 |
+
cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
|
257 |
+
if (cc == 0) return false; // no reader
|
258 |
+
}
|
259 |
+
// just compare & exchange
|
260 |
+
if (el->rc_.compare_exchange_weak(
|
261 |
+
cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
|
262 |
+
break;
|
263 |
+
}
|
264 |
+
ipc::yield(k);
|
265 |
+
}
|
266 |
+
std::forward<F>(f)(&(el->data_));
|
267 |
+
wt_.fetch_add(1, std::memory_order_release);
|
268 |
+
return true;
|
269 |
+
}
|
270 |
+
|
271 |
+
template <typename W, typename F, typename R, typename E>
|
272 |
+
bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) {
|
273 |
+
if (cur == cursor()) return false; // acquire
|
274 |
+
auto* el = elems + circ::index_of(cur++);
|
275 |
+
std::forward<F>(f)(&(el->data_));
|
276 |
+
for (unsigned k = 0;;) {
|
277 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
278 |
+
if ((cur_rc & ep_mask) == 0) {
|
279 |
+
std::forward<R>(out)(true);
|
280 |
+
return true;
|
281 |
+
}
|
282 |
+
auto nxt_rc = cur_rc & ~static_cast<rc_t>(wrapper->connected_id());
|
283 |
+
if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
|
284 |
+
std::forward<R>(out)((nxt_rc & ep_mask) == 0);
|
285 |
+
return true;
|
286 |
+
}
|
287 |
+
ipc::yield(k);
|
288 |
+
}
|
289 |
+
}
|
290 |
+
};
|
291 |
+
|
292 |
+
template <>
|
293 |
+
struct prod_cons_impl<wr<relat::multi, relat::multi, trans::broadcast>> {
|
294 |
+
|
295 |
+
using rc_t = std::uint64_t;
|
296 |
+
using flag_t = std::uint64_t;
|
297 |
+
|
298 |
+
enum : rc_t {
|
299 |
+
rc_mask = 0x00000000ffffffffull,
|
300 |
+
ep_mask = 0x00ffffffffffffffull,
|
301 |
+
ep_incr = 0x0100000000000000ull,
|
302 |
+
ic_mask = 0xff000000ffffffffull,
|
303 |
+
ic_incr = 0x0000000100000000ull
|
304 |
+
};
|
305 |
+
|
306 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
307 |
+
struct elem_t {
|
308 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
309 |
+
std::atomic<rc_t > rc_ { 0 }; // read-counter
|
310 |
+
std::atomic<flag_t> f_ct_ { 0 }; // commit flag
|
311 |
+
};
|
312 |
+
|
313 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
|
314 |
+
alignas(cache_line_size) std::atomic<rc_t> epoch_ { 0 };
|
315 |
+
|
316 |
+
circ::u2_t cursor() const noexcept {
|
317 |
+
return ct_.load(std::memory_order_acquire);
|
318 |
+
}
|
319 |
+
|
320 |
+
constexpr static rc_t inc_rc(rc_t rc) noexcept {
|
321 |
+
return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask);
|
322 |
+
}
|
323 |
+
|
324 |
+
constexpr static rc_t inc_mask(rc_t rc) noexcept {
|
325 |
+
return inc_rc(rc) & ~rc_mask;
|
326 |
+
}
|
327 |
+
|
328 |
+
template <typename W, typename F, typename E>
|
329 |
+
bool push(W* wrapper, F&& f, E* elems) {
|
330 |
+
E* el;
|
331 |
+
circ::u2_t cur_ct;
|
332 |
+
rc_t epoch = epoch_.load(std::memory_order_acquire);
|
333 |
+
for (unsigned k = 0;;) {
|
334 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
335 |
+
if (cc == 0) return false; // no reader
|
336 |
+
el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
|
337 |
+
// check all consumers have finished reading this element
|
338 |
+
auto cur_rc = el->rc_.load(std::memory_order_relaxed);
|
339 |
+
circ::cc_t rem_cc = cur_rc & rc_mask;
|
340 |
+
if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) {
|
341 |
+
return false; // has not finished yet
|
342 |
+
}
|
343 |
+
else if (!rem_cc) {
|
344 |
+
auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
|
345 |
+
if ((cur_fl != cur_ct) && cur_fl) {
|
346 |
+
return false; // full
|
347 |
+
}
|
348 |
+
}
|
349 |
+
// consider rem_cc to be 0 here
|
350 |
+
if (el->rc_.compare_exchange_weak(
|
351 |
+
cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed) &&
|
352 |
+
epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) {
|
353 |
+
break;
|
354 |
+
}
|
355 |
+
ipc::yield(k);
|
356 |
+
}
|
357 |
+
// only one thread/process would touch here at one time
|
358 |
+
ct_.store(cur_ct + 1, std::memory_order_release);
|
359 |
+
std::forward<F>(f)(&(el->data_));
|
360 |
+
// set flag & try update wt
|
361 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
362 |
+
return true;
|
363 |
+
}
|
364 |
+
|
365 |
+
template <typename W, typename F, typename E>
|
366 |
+
bool force_push(W* wrapper, F&& f, E* elems) {
|
367 |
+
E* el;
|
368 |
+
circ::u2_t cur_ct;
|
369 |
+
rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
|
370 |
+
for (unsigned k = 0;;) {
|
371 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
372 |
+
if (cc == 0) return false; // no reader
|
373 |
+
el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
|
374 |
+
// check all consumers have finished reading this element
|
375 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
376 |
+
circ::cc_t rem_cc = cur_rc & rc_mask;
|
377 |
+
if (cc & rem_cc) {
|
378 |
+
ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
|
379 |
+
cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
|
380 |
+
if (cc == 0) return false; // no reader
|
381 |
+
}
|
382 |
+
// just compare & exchange
|
383 |
+
if (el->rc_.compare_exchange_weak(
|
384 |
+
cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed)) {
|
385 |
+
if (epoch == epoch_.load(std::memory_order_acquire)) {
|
386 |
+
break;
|
387 |
+
}
|
388 |
+
else if (push(wrapper, std::forward<F>(f), elems)) {
|
389 |
+
return true;
|
390 |
+
}
|
391 |
+
epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
|
392 |
+
}
|
393 |
+
ipc::yield(k);
|
394 |
+
}
|
395 |
+
// only one thread/process would touch here at one time
|
396 |
+
ct_.store(cur_ct + 1, std::memory_order_release);
|
397 |
+
std::forward<F>(f)(&(el->data_));
|
398 |
+
// set flag & try update wt
|
399 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
400 |
+
return true;
|
401 |
+
}
|
402 |
+
|
403 |
+
template <typename W, typename F, typename R, typename E, std::size_t N>
|
404 |
+
bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) {
|
405 |
+
auto* el = elems + circ::index_of(cur);
|
406 |
+
auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
|
407 |
+
if (cur_fl != ~static_cast<flag_t>(cur)) {
|
408 |
+
return false; // empty
|
409 |
+
}
|
410 |
+
++cur;
|
411 |
+
std::forward<F>(f)(&(el->data_));
|
412 |
+
for (unsigned k = 0;;) {
|
413 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
414 |
+
if ((cur_rc & rc_mask) == 0) {
|
415 |
+
std::forward<R>(out)(true);
|
416 |
+
el->f_ct_.store(cur + N - 1, std::memory_order_release);
|
417 |
+
return true;
|
418 |
+
}
|
419 |
+
auto nxt_rc = inc_rc(cur_rc) & ~static_cast<rc_t>(wrapper->connected_id());
|
420 |
+
bool last_one = false;
|
421 |
+
if ((last_one = (nxt_rc & rc_mask) == 0)) {
|
422 |
+
el->f_ct_.store(cur + N - 1, std::memory_order_release);
|
423 |
+
}
|
424 |
+
if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
|
425 |
+
std::forward<R>(out)(last_one);
|
426 |
+
return true;
|
427 |
+
}
|
428 |
+
ipc::yield(k);
|
429 |
+
}
|
430 |
+
}
|
431 |
+
};
|
432 |
+
|
433 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/queue.h
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pragma once
|
2 |
+
|
3 |
+
#include <type_traits>
|
4 |
+
#include <new>
|
5 |
+
#include <utility> // [[since C++14]]: std::exchange
|
6 |
+
#include <algorithm>
|
7 |
+
#include <atomic>
|
8 |
+
#include <tuple>
|
9 |
+
#include <thread>
|
10 |
+
#include <chrono>
|
11 |
+
#include <string>
|
12 |
+
#include <cassert> // assert
|
13 |
+
|
14 |
+
#include "libipc/def.h"
|
15 |
+
#include "libipc/shm.h"
|
16 |
+
#include "libipc/rw_lock.h"
|
17 |
+
|
18 |
+
#include "libipc/utility/log.h"
|
19 |
+
#include "libipc/platform/detail.h"
|
20 |
+
#include "libipc/circ/elem_def.h"
|
21 |
+
|
22 |
+
namespace ipc {
|
23 |
+
namespace detail {
|
24 |
+
|
25 |
+
class queue_conn {
|
26 |
+
protected:
|
27 |
+
circ::cc_t connected_ = 0;
|
28 |
+
shm::handle elems_h_;
|
29 |
+
|
30 |
+
template <typename Elems>
|
31 |
+
Elems* open(char const * name) {
|
32 |
+
if (name == nullptr || name[0] == '\0') {
|
33 |
+
ipc::error("fail open waiter: name is empty!\n");
|
34 |
+
return nullptr;
|
35 |
+
}
|
36 |
+
if (!elems_h_.acquire(name, sizeof(Elems))) {
|
37 |
+
return nullptr;
|
38 |
+
}
|
39 |
+
auto elems = static_cast<Elems*>(elems_h_.get());
|
40 |
+
if (elems == nullptr) {
|
41 |
+
ipc::error("fail acquire elems: %s\n", name);
|
42 |
+
return nullptr;
|
43 |
+
}
|
44 |
+
elems->init();
|
45 |
+
return elems;
|
46 |
+
}
|
47 |
+
|
48 |
+
void close() {
|
49 |
+
elems_h_.release();
|
50 |
+
}
|
51 |
+
|
52 |
+
public:
|
53 |
+
queue_conn() = default;
|
54 |
+
queue_conn(const queue_conn&) = delete;
|
55 |
+
queue_conn& operator=(const queue_conn&) = delete;
|
56 |
+
|
57 |
+
bool connected() const noexcept {
|
58 |
+
return connected_ != 0;
|
59 |
+
}
|
60 |
+
|
61 |
+
circ::cc_t connected_id() const noexcept {
|
62 |
+
return connected_;
|
63 |
+
}
|
64 |
+
|
65 |
+
template <typename Elems>
|
66 |
+
auto connect(Elems* elems) noexcept
|
67 |
+
/*needs 'optional' here*/
|
68 |
+
-> std::tuple<bool, bool, decltype(std::declval<Elems>().cursor())> {
|
69 |
+
if (elems == nullptr) return {};
|
70 |
+
// if it's already connected, just return
|
71 |
+
if (connected()) return {connected(), false, 0};
|
72 |
+
connected_ = elems->connect_receiver();
|
73 |
+
return {connected(), true, elems->cursor()};
|
74 |
+
}
|
75 |
+
|
76 |
+
template <typename Elems>
|
77 |
+
bool disconnect(Elems* elems) noexcept {
|
78 |
+
if (elems == nullptr) return false;
|
79 |
+
// if it's already disconnected, just return false
|
80 |
+
if (!connected()) return false;
|
81 |
+
elems->disconnect_receiver(std::exchange(connected_, 0));
|
82 |
+
return true;
|
83 |
+
}
|
84 |
+
};
|
85 |
+
|
86 |
+
template <typename Elems>
|
87 |
+
class queue_base : public queue_conn {
|
88 |
+
using base_t = queue_conn;
|
89 |
+
|
90 |
+
public:
|
91 |
+
using elems_t = Elems;
|
92 |
+
using policy_t = typename elems_t::policy_t;
|
93 |
+
|
94 |
+
protected:
|
95 |
+
elems_t * elems_ = nullptr;
|
96 |
+
decltype(std::declval<elems_t>().cursor()) cursor_ = 0;
|
97 |
+
bool sender_flag_ = false;
|
98 |
+
|
99 |
+
public:
|
100 |
+
using base_t::base_t;
|
101 |
+
|
102 |
+
queue_base() = default;
|
103 |
+
|
104 |
+
explicit queue_base(char const * name)
|
105 |
+
: queue_base{} {
|
106 |
+
elems_ = open<elems_t>(name);
|
107 |
+
}
|
108 |
+
|
109 |
+
explicit queue_base(elems_t * elems) noexcept
|
110 |
+
: queue_base{} {
|
111 |
+
assert(elems != nullptr);
|
112 |
+
elems_ = elems;
|
113 |
+
}
|
114 |
+
|
115 |
+
/* not virtual */ ~queue_base() {
|
116 |
+
base_t::close();
|
117 |
+
}
|
118 |
+
|
119 |
+
elems_t * elems() noexcept { return elems_; }
|
120 |
+
elems_t const * elems() const noexcept { return elems_; }
|
121 |
+
|
122 |
+
bool ready_sending() noexcept {
|
123 |
+
if (elems_ == nullptr) return false;
|
124 |
+
return sender_flag_ || (sender_flag_ = elems_->connect_sender());
|
125 |
+
}
|
126 |
+
|
127 |
+
void shut_sending() noexcept {
|
128 |
+
if (elems_ == nullptr) return;
|
129 |
+
if (!sender_flag_) return;
|
130 |
+
elems_->disconnect_sender();
|
131 |
+
}
|
132 |
+
|
133 |
+
bool connect() noexcept {
|
134 |
+
auto tp = base_t::connect(elems_);
|
135 |
+
if (std::get<0>(tp) && std::get<1>(tp)) {
|
136 |
+
cursor_ = std::get<2>(tp);
|
137 |
+
return true;
|
138 |
+
}
|
139 |
+
return std::get<0>(tp);
|
140 |
+
}
|
141 |
+
|
142 |
+
bool disconnect() noexcept {
|
143 |
+
return base_t::disconnect(elems_);
|
144 |
+
}
|
145 |
+
|
146 |
+
std::size_t conn_count() const noexcept {
|
147 |
+
return (elems_ == nullptr) ? static_cast<std::size_t>(invalid_value) : elems_->conn_count();
|
148 |
+
}
|
149 |
+
|
150 |
+
bool valid() const noexcept {
|
151 |
+
return elems_ != nullptr;
|
152 |
+
}
|
153 |
+
|
154 |
+
bool empty() const noexcept {
|
155 |
+
return !valid() || (cursor_ == elems_->cursor());
|
156 |
+
}
|
157 |
+
|
158 |
+
template <typename T, typename F, typename... P>
|
159 |
+
bool push(F&& prep, P&&... params) {
|
160 |
+
if (elems_ == nullptr) return false;
|
161 |
+
return elems_->push(this, [&](void* p) {
|
162 |
+
if (prep(p)) ::new (p) T(std::forward<P>(params)...);
|
163 |
+
});
|
164 |
+
}
|
165 |
+
|
166 |
+
template <typename T, typename F, typename... P>
|
167 |
+
bool force_push(F&& prep, P&&... params) {
|
168 |
+
if (elems_ == nullptr) return false;
|
169 |
+
return elems_->force_push(this, [&](void* p) {
|
170 |
+
if (prep(p)) ::new (p) T(std::forward<P>(params)...);
|
171 |
+
});
|
172 |
+
}
|
173 |
+
|
174 |
+
template <typename T, typename F>
|
175 |
+
bool pop(T& item, F&& out) {
|
176 |
+
if (elems_ == nullptr) {
|
177 |
+
return false;
|
178 |
+
}
|
179 |
+
return elems_->pop(this, &(this->cursor_), [&item](void* p) {
|
180 |
+
::new (&item) T(std::move(*static_cast<T*>(p)));
|
181 |
+
}, std::forward<F>(out));
|
182 |
+
}
|
183 |
+
};
|
184 |
+
|
185 |
+
} // namespace detail
|
186 |
+
|
187 |
+
template <typename T, typename Policy>
|
188 |
+
class queue final : public detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>> {
|
189 |
+
using base_t = detail::queue_base<typename Policy::template elems_t<sizeof(T), alignof(T)>>;
|
190 |
+
|
191 |
+
public:
|
192 |
+
using value_t = T;
|
193 |
+
|
194 |
+
using base_t::base_t;
|
195 |
+
|
196 |
+
template <typename... P>
|
197 |
+
bool push(P&&... params) {
|
198 |
+
return base_t::template push<T>(std::forward<P>(params)...);
|
199 |
+
}
|
200 |
+
|
201 |
+
template <typename... P>
|
202 |
+
bool force_push(P&&... params) {
|
203 |
+
return base_t::template force_push<T>(std::forward<P>(params)...);
|
204 |
+
}
|
205 |
+
|
206 |
+
bool pop(T& item) {
|
207 |
+
return base_t::pop(item, [](bool) {});
|
208 |
+
}
|
209 |
+
|
210 |
+
template <typename F>
|
211 |
+
bool pop(T& item, F&& out) {
|
212 |
+
return base_t::pop(item, std::forward<F>(out));
|
213 |
+
}
|
214 |
+
};
|
215 |
+
|
216 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/shm.cpp
ADDED
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
#include <string>
|
3 |
+
#include <utility>
|
4 |
+
|
5 |
+
#include "libipc/shm.h"
|
6 |
+
|
7 |
+
#include "libipc/utility/pimpl.h"
|
8 |
+
#include "libipc/memory/resource.h"
|
9 |
+
|
10 |
+
namespace ipc {
|
11 |
+
namespace shm {
|
12 |
+
|
13 |
+
class handle::handle_ : public pimpl<handle_> {
|
14 |
+
public:
|
15 |
+
shm::id_t id_ = nullptr;
|
16 |
+
void* m_ = nullptr;
|
17 |
+
|
18 |
+
ipc::string n_;
|
19 |
+
std::size_t s_ = 0;
|
20 |
+
};
|
21 |
+
|
22 |
+
handle::handle()
|
23 |
+
: p_(p_->make()) {
|
24 |
+
}
|
25 |
+
|
26 |
+
handle::handle(char const * name, std::size_t size, unsigned mode)
|
27 |
+
: handle() {
|
28 |
+
acquire(name, size, mode);
|
29 |
+
}
|
30 |
+
|
31 |
+
handle::handle(handle&& rhs)
|
32 |
+
: handle() {
|
33 |
+
swap(rhs);
|
34 |
+
}
|
35 |
+
|
36 |
+
handle::~handle() {
|
37 |
+
release();
|
38 |
+
p_->clear();
|
39 |
+
}
|
40 |
+
|
41 |
+
void handle::swap(handle& rhs) {
|
42 |
+
std::swap(p_, rhs.p_);
|
43 |
+
}
|
44 |
+
|
45 |
+
handle& handle::operator=(handle rhs) {
|
46 |
+
swap(rhs);
|
47 |
+
return *this;
|
48 |
+
}
|
49 |
+
|
50 |
+
bool handle::valid() const noexcept {
|
51 |
+
return impl(p_)->m_ != nullptr;
|
52 |
+
}
|
53 |
+
|
54 |
+
std::size_t handle::size() const noexcept {
|
55 |
+
return impl(p_)->s_;
|
56 |
+
}
|
57 |
+
|
58 |
+
char const * handle::name() const noexcept {
|
59 |
+
return impl(p_)->n_.c_str();
|
60 |
+
}
|
61 |
+
|
62 |
+
std::int32_t handle::ref() const noexcept {
|
63 |
+
return shm::get_ref(impl(p_)->id_);
|
64 |
+
}
|
65 |
+
|
66 |
+
void handle::sub_ref() noexcept {
|
67 |
+
shm::sub_ref(impl(p_)->id_);
|
68 |
+
}
|
69 |
+
|
70 |
+
bool handle::acquire(char const * name, std::size_t size, unsigned mode) {
|
71 |
+
release();
|
72 |
+
impl(p_)->id_ = shm::acquire((impl(p_)->n_ = name).c_str(), size, mode);
|
73 |
+
impl(p_)->m_ = shm::get_mem(impl(p_)->id_, &(impl(p_)->s_));
|
74 |
+
return valid();
|
75 |
+
}
|
76 |
+
|
77 |
+
std::int32_t handle::release() {
|
78 |
+
if (impl(p_)->id_ == nullptr) return -1;
|
79 |
+
return shm::release(detach());
|
80 |
+
}
|
81 |
+
|
82 |
+
void* handle::get() const {
|
83 |
+
return impl(p_)->m_;
|
84 |
+
}
|
85 |
+
|
86 |
+
void handle::attach(id_t id) {
|
87 |
+
if (id == nullptr) return;
|
88 |
+
release();
|
89 |
+
impl(p_)->id_ = id;
|
90 |
+
impl(p_)->m_ = shm::get_mem(impl(p_)->id_, &(impl(p_)->s_));
|
91 |
+
}
|
92 |
+
|
93 |
+
id_t handle::detach() {
|
94 |
+
auto old = impl(p_)->id_;
|
95 |
+
impl(p_)->id_ = nullptr;
|
96 |
+
impl(p_)->m_ = nullptr;
|
97 |
+
impl(p_)->s_ = 0;
|
98 |
+
impl(p_)->n_.clear();
|
99 |
+
return old;
|
100 |
+
}
|
101 |
+
|
102 |
+
} // namespace shm
|
103 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/waiter.h
ADDED
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pragma once
|
2 |
+
|
3 |
+
#include <utility>
|
4 |
+
#include <string>
|
5 |
+
#include <mutex>
|
6 |
+
#include <atomic>
|
7 |
+
|
8 |
+
#include "libipc/def.h"
|
9 |
+
#include "libipc/mutex.h"
|
10 |
+
#include "libipc/condition.h"
|
11 |
+
#include "libipc/platform/detail.h"
|
12 |
+
|
13 |
+
namespace ipc {
|
14 |
+
namespace detail {
|
15 |
+
|
16 |
+
class waiter {
|
17 |
+
ipc::sync::condition cond_;
|
18 |
+
ipc::sync::mutex lock_;
|
19 |
+
std::atomic<bool> quit_ {false};
|
20 |
+
|
21 |
+
public:
|
22 |
+
static void init();
|
23 |
+
|
24 |
+
waiter() = default;
|
25 |
+
waiter(char const *name) {
|
26 |
+
open(name);
|
27 |
+
}
|
28 |
+
|
29 |
+
~waiter() {
|
30 |
+
close();
|
31 |
+
}
|
32 |
+
|
33 |
+
bool valid() const noexcept {
|
34 |
+
return cond_.valid() && lock_.valid();
|
35 |
+
}
|
36 |
+
|
37 |
+
bool open(char const *name) noexcept {
|
38 |
+
quit_.store(false, std::memory_order_relaxed);
|
39 |
+
if (!cond_.open((std::string{"_waiter_cond_"} + name).c_str())) {
|
40 |
+
return false;
|
41 |
+
}
|
42 |
+
if (!lock_.open((std::string{"_waiter_lock_"} + name).c_str())) {
|
43 |
+
cond_.close();
|
44 |
+
return false;
|
45 |
+
}
|
46 |
+
return valid();
|
47 |
+
}
|
48 |
+
|
49 |
+
void close() noexcept {
|
50 |
+
cond_.close();
|
51 |
+
lock_.close();
|
52 |
+
}
|
53 |
+
|
54 |
+
template <typename F>
|
55 |
+
bool wait_if(F &&pred, std::uint64_t tm = ipc::invalid_value) noexcept {
|
56 |
+
IPC_UNUSED_ std::lock_guard<ipc::sync::mutex> guard {lock_};
|
57 |
+
while ([this, &pred] {
|
58 |
+
return !quit_.load(std::memory_order_relaxed)
|
59 |
+
&& std::forward<F>(pred)();
|
60 |
+
}()) {
|
61 |
+
if (!cond_.wait(lock_, tm)) return false;
|
62 |
+
}
|
63 |
+
return true;
|
64 |
+
}
|
65 |
+
|
66 |
+
bool notify() noexcept {
|
67 |
+
std::lock_guard<ipc::sync::mutex>{lock_}; // barrier
|
68 |
+
return cond_.notify(lock_);
|
69 |
+
}
|
70 |
+
|
71 |
+
bool broadcast() noexcept {
|
72 |
+
std::lock_guard<ipc::sync::mutex>{lock_}; // barrier
|
73 |
+
return cond_.broadcast(lock_);
|
74 |
+
}
|
75 |
+
|
76 |
+
bool quit_waiting() {
|
77 |
+
quit_.store(true, std::memory_order_release);
|
78 |
+
return broadcast();
|
79 |
+
}
|
80 |
+
};
|
81 |
+
|
82 |
+
} // namespace detail
|
83 |
+
} // namespace ipc
|
crazy_functions/test_project/cpp/cppipc/来源
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
https://github.com/mutouyun/cpp-ipc
|
2 |
+
|
3 |
+
A high-performance inter-process communication library using shared memory on Linux/Windows.
|
crazy_functions/test_project/cpp/libJPG/jpgd.cpp
ADDED
@@ -0,0 +1,3276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// jpgd.cpp - C++ class for JPEG decompression.
|
2 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
// Last updated Apr. 16, 2011
|
4 |
+
// Alex Evans: Linear memory allocator (taken from jpge.h).
|
5 |
+
//
|
6 |
+
// Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2.
|
7 |
+
//
|
8 |
+
// Chroma upsampling quality: H2V2 is upsampled in the frequency domain, H2V1 and H1V2 are upsampled using point sampling.
|
9 |
+
// Chroma upsampling reference: "Fast Scheme for Image Size Change in the Compressed Domain"
|
10 |
+
// http://vision.ai.uiuc.edu/~dugad/research/dct/index.html
|
11 |
+
|
12 |
+
#include "jpgd.h"
|
13 |
+
#include <string.h>
|
14 |
+
|
15 |
+
#include <assert.h>
|
16 |
+
// BEGIN EPIC MOD
|
17 |
+
#define JPGD_ASSERT(x) { assert(x); CA_ASSUME(x); } (void)0
|
18 |
+
// END EPIC MOD
|
19 |
+
|
20 |
+
#ifdef _MSC_VER
|
21 |
+
#pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
|
22 |
+
#endif
|
23 |
+
|
24 |
+
// Set to 1 to enable freq. domain chroma upsampling on images using H2V2 subsampling (0=faster nearest neighbor sampling).
|
25 |
+
// This is slower, but results in higher quality on images with highly saturated colors.
|
26 |
+
#define JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING 1
|
27 |
+
|
28 |
+
#define JPGD_TRUE (1)
|
29 |
+
#define JPGD_FALSE (0)
|
30 |
+
|
31 |
+
#define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b))
|
32 |
+
#define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b))
|
33 |
+
|
34 |
+
namespace jpgd {
|
35 |
+
|
36 |
+
static inline void *jpgd_malloc(size_t nSize) { return FMemory::Malloc(nSize); }
|
37 |
+
static inline void jpgd_free(void *p) { FMemory::Free(p); }
|
38 |
+
|
39 |
+
// BEGIN EPIC MOD
|
40 |
+
//@UE3 - use UE3 BGRA encoding instead of assuming RGBA
|
41 |
+
// stolen from IImageWrapper.h
|
42 |
+
enum ERGBFormatJPG
|
43 |
+
{
|
44 |
+
Invalid = -1,
|
45 |
+
RGBA = 0,
|
46 |
+
BGRA = 1,
|
47 |
+
Gray = 2,
|
48 |
+
};
|
49 |
+
static ERGBFormatJPG jpg_format;
|
50 |
+
// END EPIC MOD
|
51 |
+
|
52 |
+
// DCT coefficients are stored in this sequence.
|
53 |
+
static int g_ZAG[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 };
|
54 |
+
|
55 |
+
enum JPEG_MARKER
|
56 |
+
{
|
57 |
+
M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8,
|
58 |
+
M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC,
|
59 |
+
M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7,
|
60 |
+
M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF,
|
61 |
+
M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0
|
62 |
+
};
|
63 |
+
|
64 |
+
enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 };
|
65 |
+
|
66 |
+
#define CONST_BITS 13
|
67 |
+
#define PASS1_BITS 2
|
68 |
+
#define SCALEDONE ((int32)1)
|
69 |
+
|
70 |
+
#define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */
|
71 |
+
#define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */
|
72 |
+
#define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */
|
73 |
+
#define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */
|
74 |
+
#define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */
|
75 |
+
#define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */
|
76 |
+
#define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */
|
77 |
+
#define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */
|
78 |
+
#define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */
|
79 |
+
#define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */
|
80 |
+
#define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */
|
81 |
+
#define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */
|
82 |
+
|
83 |
+
#define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n))
|
84 |
+
#define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n))
|
85 |
+
|
86 |
+
#define MULTIPLY(var, cnst) ((var) * (cnst))
|
87 |
+
|
88 |
+
#define CLAMP(i) ((static_cast<uint>(i) > 255) ? (((~i) >> 31) & 0xFF) : (i))
|
89 |
+
|
90 |
+
// Compiler creates a fast path 1D IDCT for X non-zero columns
|
91 |
+
template <int NONZERO_COLS>
|
92 |
+
struct Row
|
93 |
+
{
|
94 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
95 |
+
{
|
96 |
+
// ACCESS_COL() will be optimized at compile time to either an array access, or 0.
|
97 |
+
#define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0)
|
98 |
+
|
99 |
+
const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6);
|
100 |
+
|
101 |
+
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
|
102 |
+
const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
|
103 |
+
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
|
104 |
+
|
105 |
+
const int tmp0 = (ACCESS_COL(0) + ACCESS_COL(4)) << CONST_BITS;
|
106 |
+
const int tmp1 = (ACCESS_COL(0) - ACCESS_COL(4)) << CONST_BITS;
|
107 |
+
|
108 |
+
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
|
109 |
+
|
110 |
+
const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1);
|
111 |
+
|
112 |
+
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
|
113 |
+
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
|
114 |
+
|
115 |
+
const int az1 = MULTIPLY(bz1, - FIX_0_899976223);
|
116 |
+
const int az2 = MULTIPLY(bz2, - FIX_2_562915447);
|
117 |
+
const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5;
|
118 |
+
const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5;
|
119 |
+
|
120 |
+
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
|
121 |
+
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
|
122 |
+
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
|
123 |
+
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
|
124 |
+
|
125 |
+
pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS-PASS1_BITS);
|
126 |
+
pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS-PASS1_BITS);
|
127 |
+
pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS-PASS1_BITS);
|
128 |
+
pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS-PASS1_BITS);
|
129 |
+
pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS-PASS1_BITS);
|
130 |
+
pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS-PASS1_BITS);
|
131 |
+
pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS-PASS1_BITS);
|
132 |
+
pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS-PASS1_BITS);
|
133 |
+
}
|
134 |
+
};
|
135 |
+
|
136 |
+
template <>
|
137 |
+
struct Row<0>
|
138 |
+
{
|
139 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
140 |
+
{
|
141 |
+
#ifdef _MSC_VER
|
142 |
+
pTemp; pSrc;
|
143 |
+
#endif
|
144 |
+
}
|
145 |
+
};
|
146 |
+
|
147 |
+
template <>
|
148 |
+
struct Row<1>
|
149 |
+
{
|
150 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
151 |
+
{
|
152 |
+
const int dcval = (pSrc[0] << PASS1_BITS);
|
153 |
+
|
154 |
+
pTemp[0] = dcval;
|
155 |
+
pTemp[1] = dcval;
|
156 |
+
pTemp[2] = dcval;
|
157 |
+
pTemp[3] = dcval;
|
158 |
+
pTemp[4] = dcval;
|
159 |
+
pTemp[5] = dcval;
|
160 |
+
pTemp[6] = dcval;
|
161 |
+
pTemp[7] = dcval;
|
162 |
+
}
|
163 |
+
};
|
164 |
+
|
165 |
+
// Compiler creates a fast path 1D IDCT for X non-zero rows
|
166 |
+
template <int NONZERO_ROWS>
|
167 |
+
struct Col
|
168 |
+
{
|
169 |
+
static void idct(uint8* pDst_ptr, const int* pTemp)
|
170 |
+
{
|
171 |
+
// ACCESS_ROW() will be optimized at compile time to either an array access, or 0.
|
172 |
+
#define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0)
|
173 |
+
|
174 |
+
const int z2 = ACCESS_ROW(2);
|
175 |
+
const int z3 = ACCESS_ROW(6);
|
176 |
+
|
177 |
+
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
|
178 |
+
const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
|
179 |
+
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
|
180 |
+
|
181 |
+
const int tmp0 = (ACCESS_ROW(0) + ACCESS_ROW(4)) << CONST_BITS;
|
182 |
+
const int tmp1 = (ACCESS_ROW(0) - ACCESS_ROW(4)) << CONST_BITS;
|
183 |
+
|
184 |
+
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
|
185 |
+
|
186 |
+
const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1);
|
187 |
+
|
188 |
+
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
|
189 |
+
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
|
190 |
+
|
191 |
+
const int az1 = MULTIPLY(bz1, - FIX_0_899976223);
|
192 |
+
const int az2 = MULTIPLY(bz2, - FIX_2_562915447);
|
193 |
+
const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5;
|
194 |
+
const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5;
|
195 |
+
|
196 |
+
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
|
197 |
+
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
|
198 |
+
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
|
199 |
+
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
|
200 |
+
|
201 |
+
int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS+PASS1_BITS+3);
|
202 |
+
pDst_ptr[8*0] = (uint8)CLAMP(i);
|
203 |
+
|
204 |
+
i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS+PASS1_BITS+3);
|
205 |
+
pDst_ptr[8*7] = (uint8)CLAMP(i);
|
206 |
+
|
207 |
+
i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS+PASS1_BITS+3);
|
208 |
+
pDst_ptr[8*1] = (uint8)CLAMP(i);
|
209 |
+
|
210 |
+
i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS+PASS1_BITS+3);
|
211 |
+
pDst_ptr[8*6] = (uint8)CLAMP(i);
|
212 |
+
|
213 |
+
i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS+PASS1_BITS+3);
|
214 |
+
pDst_ptr[8*2] = (uint8)CLAMP(i);
|
215 |
+
|
216 |
+
i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS+PASS1_BITS+3);
|
217 |
+
pDst_ptr[8*5] = (uint8)CLAMP(i);
|
218 |
+
|
219 |
+
i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS+PASS1_BITS+3);
|
220 |
+
pDst_ptr[8*3] = (uint8)CLAMP(i);
|
221 |
+
|
222 |
+
i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS+PASS1_BITS+3);
|
223 |
+
pDst_ptr[8*4] = (uint8)CLAMP(i);
|
224 |
+
}
|
225 |
+
};
|
226 |
+
|
227 |
+
template <>
|
228 |
+
struct Col<1>
|
229 |
+
{
|
230 |
+
static void idct(uint8* pDst_ptr, const int* pTemp)
|
231 |
+
{
|
232 |
+
int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS+3);
|
233 |
+
const uint8 dcval_clamped = (uint8)CLAMP(dcval);
|
234 |
+
pDst_ptr[0*8] = dcval_clamped;
|
235 |
+
pDst_ptr[1*8] = dcval_clamped;
|
236 |
+
pDst_ptr[2*8] = dcval_clamped;
|
237 |
+
pDst_ptr[3*8] = dcval_clamped;
|
238 |
+
pDst_ptr[4*8] = dcval_clamped;
|
239 |
+
pDst_ptr[5*8] = dcval_clamped;
|
240 |
+
pDst_ptr[6*8] = dcval_clamped;
|
241 |
+
pDst_ptr[7*8] = dcval_clamped;
|
242 |
+
}
|
243 |
+
};
|
244 |
+
|
245 |
+
static const uint8 s_idct_row_table[] =
|
246 |
+
{
|
247 |
+
1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0,
|
248 |
+
4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0,
|
249 |
+
6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0,
|
250 |
+
6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0,
|
251 |
+
8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2,
|
252 |
+
8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2,
|
253 |
+
8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4,
|
254 |
+
8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8,
|
255 |
+
};
|
256 |
+
|
257 |
+
static const uint8 s_idct_col_table[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 };
|
258 |
+
|
259 |
+
void idct(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag)
|
260 |
+
{
|
261 |
+
JPGD_ASSERT(block_max_zag >= 1);
|
262 |
+
JPGD_ASSERT(block_max_zag <= 64);
|
263 |
+
|
264 |
+
if (block_max_zag == 1)
|
265 |
+
{
|
266 |
+
int k = ((pSrc_ptr[0] + 4) >> 3) + 128;
|
267 |
+
k = CLAMP(k);
|
268 |
+
k = k | (k<<8);
|
269 |
+
k = k | (k<<16);
|
270 |
+
|
271 |
+
for (int i = 8; i > 0; i--)
|
272 |
+
{
|
273 |
+
*(int*)&pDst_ptr[0] = k;
|
274 |
+
*(int*)&pDst_ptr[4] = k;
|
275 |
+
pDst_ptr += 8;
|
276 |
+
}
|
277 |
+
return;
|
278 |
+
}
|
279 |
+
|
280 |
+
int temp[64];
|
281 |
+
|
282 |
+
const jpgd_block_t* pSrc = pSrc_ptr;
|
283 |
+
int* pTemp = temp;
|
284 |
+
|
285 |
+
const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8];
|
286 |
+
int i;
|
287 |
+
for (i = 8; i > 0; i--, pRow_tab++)
|
288 |
+
{
|
289 |
+
switch (*pRow_tab)
|
290 |
+
{
|
291 |
+
case 0: Row<0>::idct(pTemp, pSrc); break;
|
292 |
+
case 1: Row<1>::idct(pTemp, pSrc); break;
|
293 |
+
case 2: Row<2>::idct(pTemp, pSrc); break;
|
294 |
+
case 3: Row<3>::idct(pTemp, pSrc); break;
|
295 |
+
case 4: Row<4>::idct(pTemp, pSrc); break;
|
296 |
+
case 5: Row<5>::idct(pTemp, pSrc); break;
|
297 |
+
case 6: Row<6>::idct(pTemp, pSrc); break;
|
298 |
+
case 7: Row<7>::idct(pTemp, pSrc); break;
|
299 |
+
case 8: Row<8>::idct(pTemp, pSrc); break;
|
300 |
+
}
|
301 |
+
|
302 |
+
pSrc += 8;
|
303 |
+
pTemp += 8;
|
304 |
+
}
|
305 |
+
|
306 |
+
pTemp = temp;
|
307 |
+
|
308 |
+
const int nonzero_rows = s_idct_col_table[block_max_zag - 1];
|
309 |
+
for (i = 8; i > 0; i--)
|
310 |
+
{
|
311 |
+
switch (nonzero_rows)
|
312 |
+
{
|
313 |
+
case 1: Col<1>::idct(pDst_ptr, pTemp); break;
|
314 |
+
case 2: Col<2>::idct(pDst_ptr, pTemp); break;
|
315 |
+
case 3: Col<3>::idct(pDst_ptr, pTemp); break;
|
316 |
+
case 4: Col<4>::idct(pDst_ptr, pTemp); break;
|
317 |
+
case 5: Col<5>::idct(pDst_ptr, pTemp); break;
|
318 |
+
case 6: Col<6>::idct(pDst_ptr, pTemp); break;
|
319 |
+
case 7: Col<7>::idct(pDst_ptr, pTemp); break;
|
320 |
+
case 8: Col<8>::idct(pDst_ptr, pTemp); break;
|
321 |
+
}
|
322 |
+
|
323 |
+
pTemp++;
|
324 |
+
pDst_ptr++;
|
325 |
+
}
|
326 |
+
}
|
327 |
+
|
328 |
+
void idct_4x4(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr)
|
329 |
+
{
|
330 |
+
int temp[64];
|
331 |
+
int* pTemp = temp;
|
332 |
+
const jpgd_block_t* pSrc = pSrc_ptr;
|
333 |
+
|
334 |
+
for (int i = 4; i > 0; i--)
|
335 |
+
{
|
336 |
+
Row<4>::idct(pTemp, pSrc);
|
337 |
+
pSrc += 8;
|
338 |
+
pTemp += 8;
|
339 |
+
}
|
340 |
+
|
341 |
+
pTemp = temp;
|
342 |
+
for (int i = 8; i > 0; i--)
|
343 |
+
{
|
344 |
+
Col<4>::idct(pDst_ptr, pTemp);
|
345 |
+
pTemp++;
|
346 |
+
pDst_ptr++;
|
347 |
+
}
|
348 |
+
}
|
349 |
+
|
350 |
+
// Retrieve one character from the input stream.
|
351 |
+
inline uint jpeg_decoder::get_char()
|
352 |
+
{
|
353 |
+
// Any bytes remaining in buffer?
|
354 |
+
if (!m_in_buf_left)
|
355 |
+
{
|
356 |
+
// Try to get more bytes.
|
357 |
+
prep_in_buffer();
|
358 |
+
// Still nothing to get?
|
359 |
+
if (!m_in_buf_left)
|
360 |
+
{
|
361 |
+
// Pad the end of the stream with 0xFF 0xD9 (EOI marker)
|
362 |
+
int t = m_tem_flag;
|
363 |
+
m_tem_flag ^= 1;
|
364 |
+
if (t)
|
365 |
+
return 0xD9;
|
366 |
+
else
|
367 |
+
return 0xFF;
|
368 |
+
}
|
369 |
+
}
|
370 |
+
|
371 |
+
uint c = *m_pIn_buf_ofs++;
|
372 |
+
m_in_buf_left--;
|
373 |
+
|
374 |
+
return c;
|
375 |
+
}
|
376 |
+
|
377 |
+
// Same as previous method, except can indicate if the character is a pad character or not.
|
378 |
+
inline uint jpeg_decoder::get_char(bool *pPadding_flag)
|
379 |
+
{
|
380 |
+
if (!m_in_buf_left)
|
381 |
+
{
|
382 |
+
prep_in_buffer();
|
383 |
+
if (!m_in_buf_left)
|
384 |
+
{
|
385 |
+
*pPadding_flag = true;
|
386 |
+
int t = m_tem_flag;
|
387 |
+
m_tem_flag ^= 1;
|
388 |
+
if (t)
|
389 |
+
return 0xD9;
|
390 |
+
else
|
391 |
+
return 0xFF;
|
392 |
+
}
|
393 |
+
}
|
394 |
+
|
395 |
+
*pPadding_flag = false;
|
396 |
+
|
397 |
+
uint c = *m_pIn_buf_ofs++;
|
398 |
+
m_in_buf_left--;
|
399 |
+
|
400 |
+
return c;
|
401 |
+
}
|
402 |
+
|
403 |
+
// Inserts a previously retrieved character back into the input buffer.
|
404 |
+
inline void jpeg_decoder::stuff_char(uint8 q)
|
405 |
+
{
|
406 |
+
*(--m_pIn_buf_ofs) = q;
|
407 |
+
m_in_buf_left++;
|
408 |
+
}
|
409 |
+
|
410 |
+
// Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered.
|
411 |
+
inline uint8 jpeg_decoder::get_octet()
|
412 |
+
{
|
413 |
+
bool padding_flag;
|
414 |
+
int c = get_char(&padding_flag);
|
415 |
+
|
416 |
+
if (c == 0xFF)
|
417 |
+
{
|
418 |
+
if (padding_flag)
|
419 |
+
return 0xFF;
|
420 |
+
|
421 |
+
c = get_char(&padding_flag);
|
422 |
+
if (padding_flag)
|
423 |
+
{
|
424 |
+
stuff_char(0xFF);
|
425 |
+
return 0xFF;
|
426 |
+
}
|
427 |
+
|
428 |
+
if (c == 0x00)
|
429 |
+
return 0xFF;
|
430 |
+
else
|
431 |
+
{
|
432 |
+
stuff_char(static_cast<uint8>(c));
|
433 |
+
stuff_char(0xFF);
|
434 |
+
return 0xFF;
|
435 |
+
}
|
436 |
+
}
|
437 |
+
|
438 |
+
return static_cast<uint8>(c);
|
439 |
+
}
|
440 |
+
|
441 |
+
// Retrieves a variable number of bits from the input stream. Does not recognize markers.
|
442 |
+
inline uint jpeg_decoder::get_bits(int num_bits)
|
443 |
+
{
|
444 |
+
if (!num_bits)
|
445 |
+
return 0;
|
446 |
+
|
447 |
+
uint i = m_bit_buf >> (32 - num_bits);
|
448 |
+
|
449 |
+
if ((m_bits_left -= num_bits) <= 0)
|
450 |
+
{
|
451 |
+
m_bit_buf <<= (num_bits += m_bits_left);
|
452 |
+
|
453 |
+
uint c1 = get_char();
|
454 |
+
uint c2 = get_char();
|
455 |
+
m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2;
|
456 |
+
|
457 |
+
m_bit_buf <<= -m_bits_left;
|
458 |
+
|
459 |
+
m_bits_left += 16;
|
460 |
+
|
461 |
+
JPGD_ASSERT(m_bits_left >= 0);
|
462 |
+
}
|
463 |
+
else
|
464 |
+
m_bit_buf <<= num_bits;
|
465 |
+
|
466 |
+
return i;
|
467 |
+
}
|
468 |
+
|
469 |
+
// Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered.
|
470 |
+
inline uint jpeg_decoder::get_bits_no_markers(int num_bits)
|
471 |
+
{
|
472 |
+
if (!num_bits)
|
473 |
+
return 0;
|
474 |
+
|
475 |
+
uint i = m_bit_buf >> (32 - num_bits);
|
476 |
+
|
477 |
+
if ((m_bits_left -= num_bits) <= 0)
|
478 |
+
{
|
479 |
+
m_bit_buf <<= (num_bits += m_bits_left);
|
480 |
+
|
481 |
+
if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF))
|
482 |
+
{
|
483 |
+
uint c1 = get_octet();
|
484 |
+
uint c2 = get_octet();
|
485 |
+
m_bit_buf |= (c1 << 8) | c2;
|
486 |
+
}
|
487 |
+
else
|
488 |
+
{
|
489 |
+
m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1];
|
490 |
+
m_in_buf_left -= 2;
|
491 |
+
m_pIn_buf_ofs += 2;
|
492 |
+
}
|
493 |
+
|
494 |
+
m_bit_buf <<= -m_bits_left;
|
495 |
+
|
496 |
+
m_bits_left += 16;
|
497 |
+
|
498 |
+
JPGD_ASSERT(m_bits_left >= 0);
|
499 |
+
}
|
500 |
+
else
|
501 |
+
m_bit_buf <<= num_bits;
|
502 |
+
|
503 |
+
return i;
|
504 |
+
}
|
505 |
+
|
506 |
+
// Decodes a Huffman encoded symbol.
|
507 |
+
inline int jpeg_decoder::huff_decode(huff_tables *pH)
|
508 |
+
{
|
509 |
+
int symbol;
|
510 |
+
|
511 |
+
// Check first 8-bits: do we have a complete symbol?
|
512 |
+
if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0)
|
513 |
+
{
|
514 |
+
// Decode more bits, use a tree traversal to find symbol.
|
515 |
+
int ofs = 23;
|
516 |
+
do
|
517 |
+
{
|
518 |
+
symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
|
519 |
+
ofs--;
|
520 |
+
} while (symbol < 0);
|
521 |
+
|
522 |
+
get_bits_no_markers(8 + (23 - ofs));
|
523 |
+
}
|
524 |
+
else
|
525 |
+
get_bits_no_markers(pH->code_size[symbol]);
|
526 |
+
|
527 |
+
return symbol;
|
528 |
+
}
|
529 |
+
|
530 |
+
// Decodes a Huffman encoded symbol.
|
531 |
+
inline int jpeg_decoder::huff_decode(huff_tables *pH, int& extra_bits)
|
532 |
+
{
|
533 |
+
int symbol;
|
534 |
+
|
535 |
+
// Check first 8-bits: do we have a complete symbol?
|
536 |
+
if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0)
|
537 |
+
{
|
538 |
+
// Use a tree traversal to find symbol.
|
539 |
+
int ofs = 23;
|
540 |
+
do
|
541 |
+
{
|
542 |
+
symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
|
543 |
+
ofs--;
|
544 |
+
} while (symbol < 0);
|
545 |
+
|
546 |
+
get_bits_no_markers(8 + (23 - ofs));
|
547 |
+
|
548 |
+
extra_bits = get_bits_no_markers(symbol & 0xF);
|
549 |
+
}
|
550 |
+
else
|
551 |
+
{
|
552 |
+
JPGD_ASSERT(((symbol >> 8) & 31) == pH->code_size[symbol & 255] + ((symbol & 0x8000) ? (symbol & 15) : 0));
|
553 |
+
|
554 |
+
if (symbol & 0x8000)
|
555 |
+
{
|
556 |
+
get_bits_no_markers((symbol >> 8) & 31);
|
557 |
+
extra_bits = symbol >> 16;
|
558 |
+
}
|
559 |
+
else
|
560 |
+
{
|
561 |
+
int code_size = (symbol >> 8) & 31;
|
562 |
+
int num_extra_bits = symbol & 0xF;
|
563 |
+
int bits = code_size + num_extra_bits;
|
564 |
+
if (bits <= (m_bits_left + 16))
|
565 |
+
extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1);
|
566 |
+
else
|
567 |
+
{
|
568 |
+
get_bits_no_markers(code_size);
|
569 |
+
extra_bits = get_bits_no_markers(num_extra_bits);
|
570 |
+
}
|
571 |
+
}
|
572 |
+
|
573 |
+
symbol &= 0xFF;
|
574 |
+
}
|
575 |
+
|
576 |
+
return symbol;
|
577 |
+
}
|
578 |
+
|
579 |
+
// Tables and macro used to fully decode the DPCM differences.
|
580 |
+
static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
|
581 |
+
static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 };
|
582 |
+
static const int s_extend_mask[] = { 0, (1<<0), (1<<1), (1<<2), (1<<3), (1<<4), (1<<5), (1<<6), (1<<7), (1<<8), (1<<9), (1<<10), (1<<11), (1<<12), (1<<13), (1<<14), (1<<15), (1<<16) };
|
583 |
+
#define HUFF_EXTEND(x,s) ((x) < s_extend_test[s] ? (x) + s_extend_offset[s] : (x))
|
584 |
+
|
585 |
+
// Clamps a value between 0-255.
|
586 |
+
inline uint8 jpeg_decoder::clamp(int i)
|
587 |
+
{
|
588 |
+
if (static_cast<uint>(i) > 255)
|
589 |
+
i = (((~i) >> 31) & 0xFF);
|
590 |
+
|
591 |
+
return static_cast<uint8>(i);
|
592 |
+
}
|
593 |
+
|
594 |
+
namespace DCT_Upsample
|
595 |
+
{
|
596 |
+
struct Matrix44
|
597 |
+
{
|
598 |
+
typedef int Element_Type;
|
599 |
+
enum { NUM_ROWS = 4, NUM_COLS = 4 };
|
600 |
+
|
601 |
+
Element_Type v[NUM_ROWS][NUM_COLS];
|
602 |
+
|
603 |
+
inline int rows() const { return NUM_ROWS; }
|
604 |
+
inline int cols() const { return NUM_COLS; }
|
605 |
+
|
606 |
+
inline const Element_Type & at(int r, int c) const { return v[r][c]; }
|
607 |
+
inline Element_Type & at(int r, int c) { return v[r][c]; }
|
608 |
+
|
609 |
+
inline Matrix44() { }
|
610 |
+
|
611 |
+
inline Matrix44& operator += (const Matrix44& a)
|
612 |
+
{
|
613 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
614 |
+
{
|
615 |
+
at(r, 0) += a.at(r, 0);
|
616 |
+
at(r, 1) += a.at(r, 1);
|
617 |
+
at(r, 2) += a.at(r, 2);
|
618 |
+
at(r, 3) += a.at(r, 3);
|
619 |
+
}
|
620 |
+
return *this;
|
621 |
+
}
|
622 |
+
|
623 |
+
inline Matrix44& operator -= (const Matrix44& a)
|
624 |
+
{
|
625 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
626 |
+
{
|
627 |
+
at(r, 0) -= a.at(r, 0);
|
628 |
+
at(r, 1) -= a.at(r, 1);
|
629 |
+
at(r, 2) -= a.at(r, 2);
|
630 |
+
at(r, 3) -= a.at(r, 3);
|
631 |
+
}
|
632 |
+
return *this;
|
633 |
+
}
|
634 |
+
|
635 |
+
friend inline Matrix44 operator + (const Matrix44& a, const Matrix44& b)
|
636 |
+
{
|
637 |
+
Matrix44 ret;
|
638 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
639 |
+
{
|
640 |
+
ret.at(r, 0) = a.at(r, 0) + b.at(r, 0);
|
641 |
+
ret.at(r, 1) = a.at(r, 1) + b.at(r, 1);
|
642 |
+
ret.at(r, 2) = a.at(r, 2) + b.at(r, 2);
|
643 |
+
ret.at(r, 3) = a.at(r, 3) + b.at(r, 3);
|
644 |
+
}
|
645 |
+
return ret;
|
646 |
+
}
|
647 |
+
|
648 |
+
friend inline Matrix44 operator - (const Matrix44& a, const Matrix44& b)
|
649 |
+
{
|
650 |
+
Matrix44 ret;
|
651 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
652 |
+
{
|
653 |
+
ret.at(r, 0) = a.at(r, 0) - b.at(r, 0);
|
654 |
+
ret.at(r, 1) = a.at(r, 1) - b.at(r, 1);
|
655 |
+
ret.at(r, 2) = a.at(r, 2) - b.at(r, 2);
|
656 |
+
ret.at(r, 3) = a.at(r, 3) - b.at(r, 3);
|
657 |
+
}
|
658 |
+
return ret;
|
659 |
+
}
|
660 |
+
|
661 |
+
static inline void add_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b)
|
662 |
+
{
|
663 |
+
for (int r = 0; r < 4; r++)
|
664 |
+
{
|
665 |
+
pDst[0*8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) + b.at(r, 0));
|
666 |
+
pDst[1*8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) + b.at(r, 1));
|
667 |
+
pDst[2*8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) + b.at(r, 2));
|
668 |
+
pDst[3*8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) + b.at(r, 3));
|
669 |
+
}
|
670 |
+
}
|
671 |
+
|
672 |
+
static inline void sub_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b)
|
673 |
+
{
|
674 |
+
for (int r = 0; r < 4; r++)
|
675 |
+
{
|
676 |
+
pDst[0*8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) - b.at(r, 0));
|
677 |
+
pDst[1*8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) - b.at(r, 1));
|
678 |
+
pDst[2*8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) - b.at(r, 2));
|
679 |
+
pDst[3*8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) - b.at(r, 3));
|
680 |
+
}
|
681 |
+
}
|
682 |
+
};
|
683 |
+
|
684 |
+
const int FRACT_BITS = 10;
|
685 |
+
const int SCALE = 1 << FRACT_BITS;
|
686 |
+
|
687 |
+
typedef int Temp_Type;
|
688 |
+
#define D(i) (((i) + (SCALE >> 1)) >> FRACT_BITS)
|
689 |
+
#define F(i) ((int)((i) * SCALE + .5f))
|
690 |
+
|
691 |
+
// Any decent C++ compiler will optimize this at compile time to a 0, or an array access.
|
692 |
+
#define AT(c, r) ((((c)>=NUM_COLS)||((r)>=NUM_ROWS)) ? 0 : pSrc[(c)+(r)*8])
|
693 |
+
|
694 |
+
// NUM_ROWS/NUM_COLS = # of non-zero rows/cols in input matrix
|
695 |
+
template<int NUM_ROWS, int NUM_COLS>
|
696 |
+
struct P_Q
|
697 |
+
{
|
698 |
+
static void calc(Matrix44& P, Matrix44& Q, const jpgd_block_t* pSrc)
|
699 |
+
{
|
700 |
+
// 4x8 = 4x8 times 8x8, matrix 0 is constant
|
701 |
+
const Temp_Type X000 = AT(0, 0);
|
702 |
+
const Temp_Type X001 = AT(0, 1);
|
703 |
+
const Temp_Type X002 = AT(0, 2);
|
704 |
+
const Temp_Type X003 = AT(0, 3);
|
705 |
+
const Temp_Type X004 = AT(0, 4);
|
706 |
+
const Temp_Type X005 = AT(0, 5);
|
707 |
+
const Temp_Type X006 = AT(0, 6);
|
708 |
+
const Temp_Type X007 = AT(0, 7);
|
709 |
+
const Temp_Type X010 = D(F(0.415735f) * AT(1, 0) + F(0.791065f) * AT(3, 0) + F(-0.352443f) * AT(5, 0) + F(0.277785f) * AT(7, 0));
|
710 |
+
const Temp_Type X011 = D(F(0.415735f) * AT(1, 1) + F(0.791065f) * AT(3, 1) + F(-0.352443f) * AT(5, 1) + F(0.277785f) * AT(7, 1));
|
711 |
+
const Temp_Type X012 = D(F(0.415735f) * AT(1, 2) + F(0.791065f) * AT(3, 2) + F(-0.352443f) * AT(5, 2) + F(0.277785f) * AT(7, 2));
|
712 |
+
const Temp_Type X013 = D(F(0.415735f) * AT(1, 3) + F(0.791065f) * AT(3, 3) + F(-0.352443f) * AT(5, 3) + F(0.277785f) * AT(7, 3));
|
713 |
+
const Temp_Type X014 = D(F(0.415735f) * AT(1, 4) + F(0.791065f) * AT(3, 4) + F(-0.352443f) * AT(5, 4) + F(0.277785f) * AT(7, 4));
|
714 |
+
const Temp_Type X015 = D(F(0.415735f) * AT(1, 5) + F(0.791065f) * AT(3, 5) + F(-0.352443f) * AT(5, 5) + F(0.277785f) * AT(7, 5));
|
715 |
+
const Temp_Type X016 = D(F(0.415735f) * AT(1, 6) + F(0.791065f) * AT(3, 6) + F(-0.352443f) * AT(5, 6) + F(0.277785f) * AT(7, 6));
|
716 |
+
const Temp_Type X017 = D(F(0.415735f) * AT(1, 7) + F(0.791065f) * AT(3, 7) + F(-0.352443f) * AT(5, 7) + F(0.277785f) * AT(7, 7));
|
717 |
+
const Temp_Type X020 = AT(4, 0);
|
718 |
+
const Temp_Type X021 = AT(4, 1);
|
719 |
+
const Temp_Type X022 = AT(4, 2);
|
720 |
+
const Temp_Type X023 = AT(4, 3);
|
721 |
+
const Temp_Type X024 = AT(4, 4);
|
722 |
+
const Temp_Type X025 = AT(4, 5);
|
723 |
+
const Temp_Type X026 = AT(4, 6);
|
724 |
+
const Temp_Type X027 = AT(4, 7);
|
725 |
+
const Temp_Type X030 = D(F(0.022887f) * AT(1, 0) + F(-0.097545f) * AT(3, 0) + F(0.490393f) * AT(5, 0) + F(0.865723f) * AT(7, 0));
|
726 |
+
const Temp_Type X031 = D(F(0.022887f) * AT(1, 1) + F(-0.097545f) * AT(3, 1) + F(0.490393f) * AT(5, 1) + F(0.865723f) * AT(7, 1));
|
727 |
+
const Temp_Type X032 = D(F(0.022887f) * AT(1, 2) + F(-0.097545f) * AT(3, 2) + F(0.490393f) * AT(5, 2) + F(0.865723f) * AT(7, 2));
|
728 |
+
const Temp_Type X033 = D(F(0.022887f) * AT(1, 3) + F(-0.097545f) * AT(3, 3) + F(0.490393f) * AT(5, 3) + F(0.865723f) * AT(7, 3));
|
729 |
+
const Temp_Type X034 = D(F(0.022887f) * AT(1, 4) + F(-0.097545f) * AT(3, 4) + F(0.490393f) * AT(5, 4) + F(0.865723f) * AT(7, 4));
|
730 |
+
const Temp_Type X035 = D(F(0.022887f) * AT(1, 5) + F(-0.097545f) * AT(3, 5) + F(0.490393f) * AT(5, 5) + F(0.865723f) * AT(7, 5));
|
731 |
+
const Temp_Type X036 = D(F(0.022887f) * AT(1, 6) + F(-0.097545f) * AT(3, 6) + F(0.490393f) * AT(5, 6) + F(0.865723f) * AT(7, 6));
|
732 |
+
const Temp_Type X037 = D(F(0.022887f) * AT(1, 7) + F(-0.097545f) * AT(3, 7) + F(0.490393f) * AT(5, 7) + F(0.865723f) * AT(7, 7));
|
733 |
+
|
734 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
735 |
+
P.at(0, 0) = X000;
|
736 |
+
P.at(0, 1) = D(X001 * F(0.415735f) + X003 * F(0.791065f) + X005 * F(-0.352443f) + X007 * F(0.277785f));
|
737 |
+
P.at(0, 2) = X004;
|
738 |
+
P.at(0, 3) = D(X001 * F(0.022887f) + X003 * F(-0.097545f) + X005 * F(0.490393f) + X007 * F(0.865723f));
|
739 |
+
P.at(1, 0) = X010;
|
740 |
+
P.at(1, 1) = D(X011 * F(0.415735f) + X013 * F(0.791065f) + X015 * F(-0.352443f) + X017 * F(0.277785f));
|
741 |
+
P.at(1, 2) = X014;
|
742 |
+
P.at(1, 3) = D(X011 * F(0.022887f) + X013 * F(-0.097545f) + X015 * F(0.490393f) + X017 * F(0.865723f));
|
743 |
+
P.at(2, 0) = X020;
|
744 |
+
P.at(2, 1) = D(X021 * F(0.415735f) + X023 * F(0.791065f) + X025 * F(-0.352443f) + X027 * F(0.277785f));
|
745 |
+
P.at(2, 2) = X024;
|
746 |
+
P.at(2, 3) = D(X021 * F(0.022887f) + X023 * F(-0.097545f) + X025 * F(0.490393f) + X027 * F(0.865723f));
|
747 |
+
P.at(3, 0) = X030;
|
748 |
+
P.at(3, 1) = D(X031 * F(0.415735f) + X033 * F(0.791065f) + X035 * F(-0.352443f) + X037 * F(0.277785f));
|
749 |
+
P.at(3, 2) = X034;
|
750 |
+
P.at(3, 3) = D(X031 * F(0.022887f) + X033 * F(-0.097545f) + X035 * F(0.490393f) + X037 * F(0.865723f));
|
751 |
+
// 40 muls 24 adds
|
752 |
+
|
753 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
754 |
+
Q.at(0, 0) = D(X001 * F(0.906127f) + X003 * F(-0.318190f) + X005 * F(0.212608f) + X007 * F(-0.180240f));
|
755 |
+
Q.at(0, 1) = X002;
|
756 |
+
Q.at(0, 2) = D(X001 * F(-0.074658f) + X003 * F(0.513280f) + X005 * F(0.768178f) + X007 * F(-0.375330f));
|
757 |
+
Q.at(0, 3) = X006;
|
758 |
+
Q.at(1, 0) = D(X011 * F(0.906127f) + X013 * F(-0.318190f) + X015 * F(0.212608f) + X017 * F(-0.180240f));
|
759 |
+
Q.at(1, 1) = X012;
|
760 |
+
Q.at(1, 2) = D(X011 * F(-0.074658f) + X013 * F(0.513280f) + X015 * F(0.768178f) + X017 * F(-0.375330f));
|
761 |
+
Q.at(1, 3) = X016;
|
762 |
+
Q.at(2, 0) = D(X021 * F(0.906127f) + X023 * F(-0.318190f) + X025 * F(0.212608f) + X027 * F(-0.180240f));
|
763 |
+
Q.at(2, 1) = X022;
|
764 |
+
Q.at(2, 2) = D(X021 * F(-0.074658f) + X023 * F(0.513280f) + X025 * F(0.768178f) + X027 * F(-0.375330f));
|
765 |
+
Q.at(2, 3) = X026;
|
766 |
+
Q.at(3, 0) = D(X031 * F(0.906127f) + X033 * F(-0.318190f) + X035 * F(0.212608f) + X037 * F(-0.180240f));
|
767 |
+
Q.at(3, 1) = X032;
|
768 |
+
Q.at(3, 2) = D(X031 * F(-0.074658f) + X033 * F(0.513280f) + X035 * F(0.768178f) + X037 * F(-0.375330f));
|
769 |
+
Q.at(3, 3) = X036;
|
770 |
+
// 40 muls 24 adds
|
771 |
+
}
|
772 |
+
};
|
773 |
+
|
774 |
+
template<int NUM_ROWS, int NUM_COLS>
|
775 |
+
struct R_S
|
776 |
+
{
|
777 |
+
static void calc(Matrix44& R, Matrix44& S, const jpgd_block_t* pSrc)
|
778 |
+
{
|
779 |
+
// 4x8 = 4x8 times 8x8, matrix 0 is constant
|
780 |
+
const Temp_Type X100 = D(F(0.906127f) * AT(1, 0) + F(-0.318190f) * AT(3, 0) + F(0.212608f) * AT(5, 0) + F(-0.180240f) * AT(7, 0));
|
781 |
+
const Temp_Type X101 = D(F(0.906127f) * AT(1, 1) + F(-0.318190f) * AT(3, 1) + F(0.212608f) * AT(5, 1) + F(-0.180240f) * AT(7, 1));
|
782 |
+
const Temp_Type X102 = D(F(0.906127f) * AT(1, 2) + F(-0.318190f) * AT(3, 2) + F(0.212608f) * AT(5, 2) + F(-0.180240f) * AT(7, 2));
|
783 |
+
const Temp_Type X103 = D(F(0.906127f) * AT(1, 3) + F(-0.318190f) * AT(3, 3) + F(0.212608f) * AT(5, 3) + F(-0.180240f) * AT(7, 3));
|
784 |
+
const Temp_Type X104 = D(F(0.906127f) * AT(1, 4) + F(-0.318190f) * AT(3, 4) + F(0.212608f) * AT(5, 4) + F(-0.180240f) * AT(7, 4));
|
785 |
+
const Temp_Type X105 = D(F(0.906127f) * AT(1, 5) + F(-0.318190f) * AT(3, 5) + F(0.212608f) * AT(5, 5) + F(-0.180240f) * AT(7, 5));
|
786 |
+
const Temp_Type X106 = D(F(0.906127f) * AT(1, 6) + F(-0.318190f) * AT(3, 6) + F(0.212608f) * AT(5, 6) + F(-0.180240f) * AT(7, 6));
|
787 |
+
const Temp_Type X107 = D(F(0.906127f) * AT(1, 7) + F(-0.318190f) * AT(3, 7) + F(0.212608f) * AT(5, 7) + F(-0.180240f) * AT(7, 7));
|
788 |
+
const Temp_Type X110 = AT(2, 0);
|
789 |
+
const Temp_Type X111 = AT(2, 1);
|
790 |
+
const Temp_Type X112 = AT(2, 2);
|
791 |
+
const Temp_Type X113 = AT(2, 3);
|
792 |
+
const Temp_Type X114 = AT(2, 4);
|
793 |
+
const Temp_Type X115 = AT(2, 5);
|
794 |
+
const Temp_Type X116 = AT(2, 6);
|
795 |
+
const Temp_Type X117 = AT(2, 7);
|
796 |
+
const Temp_Type X120 = D(F(-0.074658f) * AT(1, 0) + F(0.513280f) * AT(3, 0) + F(0.768178f) * AT(5, 0) + F(-0.375330f) * AT(7, 0));
|
797 |
+
const Temp_Type X121 = D(F(-0.074658f) * AT(1, 1) + F(0.513280f) * AT(3, 1) + F(0.768178f) * AT(5, 1) + F(-0.375330f) * AT(7, 1));
|
798 |
+
const Temp_Type X122 = D(F(-0.074658f) * AT(1, 2) + F(0.513280f) * AT(3, 2) + F(0.768178f) * AT(5, 2) + F(-0.375330f) * AT(7, 2));
|
799 |
+
const Temp_Type X123 = D(F(-0.074658f) * AT(1, 3) + F(0.513280f) * AT(3, 3) + F(0.768178f) * AT(5, 3) + F(-0.375330f) * AT(7, 3));
|
800 |
+
const Temp_Type X124 = D(F(-0.074658f) * AT(1, 4) + F(0.513280f) * AT(3, 4) + F(0.768178f) * AT(5, 4) + F(-0.375330f) * AT(7, 4));
|
801 |
+
const Temp_Type X125 = D(F(-0.074658f) * AT(1, 5) + F(0.513280f) * AT(3, 5) + F(0.768178f) * AT(5, 5) + F(-0.375330f) * AT(7, 5));
|
802 |
+
const Temp_Type X126 = D(F(-0.074658f) * AT(1, 6) + F(0.513280f) * AT(3, 6) + F(0.768178f) * AT(5, 6) + F(-0.375330f) * AT(7, 6));
|
803 |
+
const Temp_Type X127 = D(F(-0.074658f) * AT(1, 7) + F(0.513280f) * AT(3, 7) + F(0.768178f) * AT(5, 7) + F(-0.375330f) * AT(7, 7));
|
804 |
+
const Temp_Type X130 = AT(6, 0);
|
805 |
+
const Temp_Type X131 = AT(6, 1);
|
806 |
+
const Temp_Type X132 = AT(6, 2);
|
807 |
+
const Temp_Type X133 = AT(6, 3);
|
808 |
+
const Temp_Type X134 = AT(6, 4);
|
809 |
+
const Temp_Type X135 = AT(6, 5);
|
810 |
+
const Temp_Type X136 = AT(6, 6);
|
811 |
+
const Temp_Type X137 = AT(6, 7);
|
812 |
+
// 80 muls 48 adds
|
813 |
+
|
814 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
815 |
+
R.at(0, 0) = X100;
|
816 |
+
R.at(0, 1) = D(X101 * F(0.415735f) + X103 * F(0.791065f) + X105 * F(-0.352443f) + X107 * F(0.277785f));
|
817 |
+
R.at(0, 2) = X104;
|
818 |
+
R.at(0, 3) = D(X101 * F(0.022887f) + X103 * F(-0.097545f) + X105 * F(0.490393f) + X107 * F(0.865723f));
|
819 |
+
R.at(1, 0) = X110;
|
820 |
+
R.at(1, 1) = D(X111 * F(0.415735f) + X113 * F(0.791065f) + X115 * F(-0.352443f) + X117 * F(0.277785f));
|
821 |
+
R.at(1, 2) = X114;
|
822 |
+
R.at(1, 3) = D(X111 * F(0.022887f) + X113 * F(-0.097545f) + X115 * F(0.490393f) + X117 * F(0.865723f));
|
823 |
+
R.at(2, 0) = X120;
|
824 |
+
R.at(2, 1) = D(X121 * F(0.415735f) + X123 * F(0.791065f) + X125 * F(-0.352443f) + X127 * F(0.277785f));
|
825 |
+
R.at(2, 2) = X124;
|
826 |
+
R.at(2, 3) = D(X121 * F(0.022887f) + X123 * F(-0.097545f) + X125 * F(0.490393f) + X127 * F(0.865723f));
|
827 |
+
R.at(3, 0) = X130;
|
828 |
+
R.at(3, 1) = D(X131 * F(0.415735f) + X133 * F(0.791065f) + X135 * F(-0.352443f) + X137 * F(0.277785f));
|
829 |
+
R.at(3, 2) = X134;
|
830 |
+
R.at(3, 3) = D(X131 * F(0.022887f) + X133 * F(-0.097545f) + X135 * F(0.490393f) + X137 * F(0.865723f));
|
831 |
+
// 40 muls 24 adds
|
832 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
833 |
+
S.at(0, 0) = D(X101 * F(0.906127f) + X103 * F(-0.318190f) + X105 * F(0.212608f) + X107 * F(-0.180240f));
|
834 |
+
S.at(0, 1) = X102;
|
835 |
+
S.at(0, 2) = D(X101 * F(-0.074658f) + X103 * F(0.513280f) + X105 * F(0.768178f) + X107 * F(-0.375330f));
|
836 |
+
S.at(0, 3) = X106;
|
837 |
+
S.at(1, 0) = D(X111 * F(0.906127f) + X113 * F(-0.318190f) + X115 * F(0.212608f) + X117 * F(-0.180240f));
|
838 |
+
S.at(1, 1) = X112;
|
839 |
+
S.at(1, 2) = D(X111 * F(-0.074658f) + X113 * F(0.513280f) + X115 * F(0.768178f) + X117 * F(-0.375330f));
|
840 |
+
S.at(1, 3) = X116;
|
841 |
+
S.at(2, 0) = D(X121 * F(0.906127f) + X123 * F(-0.318190f) + X125 * F(0.212608f) + X127 * F(-0.180240f));
|
842 |
+
S.at(2, 1) = X122;
|
843 |
+
S.at(2, 2) = D(X121 * F(-0.074658f) + X123 * F(0.513280f) + X125 * F(0.768178f) + X127 * F(-0.375330f));
|
844 |
+
S.at(2, 3) = X126;
|
845 |
+
S.at(3, 0) = D(X131 * F(0.906127f) + X133 * F(-0.318190f) + X135 * F(0.212608f) + X137 * F(-0.180240f));
|
846 |
+
S.at(3, 1) = X132;
|
847 |
+
S.at(3, 2) = D(X131 * F(-0.074658f) + X133 * F(0.513280f) + X135 * F(0.768178f) + X137 * F(-0.375330f));
|
848 |
+
S.at(3, 3) = X136;
|
849 |
+
// 40 muls 24 adds
|
850 |
+
}
|
851 |
+
};
|
852 |
+
} // end namespace DCT_Upsample
|
853 |
+
|
854 |
+
// Unconditionally frees all allocated m_blocks.
|
855 |
+
void jpeg_decoder::free_all_blocks()
|
856 |
+
{
|
857 |
+
m_pStream = NULL;
|
858 |
+
for (mem_block *b = m_pMem_blocks; b; )
|
859 |
+
{
|
860 |
+
mem_block *n = b->m_pNext;
|
861 |
+
jpgd_free(b);
|
862 |
+
b = n;
|
863 |
+
}
|
864 |
+
m_pMem_blocks = NULL;
|
865 |
+
}
|
866 |
+
|
867 |
+
// This method handles all errors.
|
868 |
+
// It could easily be changed to use C++ exceptions.
|
869 |
+
void jpeg_decoder::stop_decoding(jpgd_status status)
|
870 |
+
{
|
871 |
+
m_error_code = status;
|
872 |
+
free_all_blocks();
|
873 |
+
longjmp(m_jmp_state, status);
|
874 |
+
|
875 |
+
// we shouldn't get here as longjmp shouldn't return, but we put it here to make it explicit
|
876 |
+
// that this function doesn't return, otherwise we get this error:
|
877 |
+
//
|
878 |
+
// error : function declared 'noreturn' should not return
|
879 |
+
exit(1);
|
880 |
+
}
|
881 |
+
|
882 |
+
void *jpeg_decoder::alloc(size_t nSize, bool zero)
|
883 |
+
{
|
884 |
+
nSize = (JPGD_MAX(nSize, 1) + 3) & ~3;
|
885 |
+
char *rv = NULL;
|
886 |
+
for (mem_block *b = m_pMem_blocks; b; b = b->m_pNext)
|
887 |
+
{
|
888 |
+
if ((b->m_used_count + nSize) <= b->m_size)
|
889 |
+
{
|
890 |
+
rv = b->m_data + b->m_used_count;
|
891 |
+
b->m_used_count += nSize;
|
892 |
+
break;
|
893 |
+
}
|
894 |
+
}
|
895 |
+
if (!rv)
|
896 |
+
{
|
897 |
+
int capacity = JPGD_MAX(32768 - 256, (nSize + 2047) & ~2047);
|
898 |
+
mem_block *b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity);
|
899 |
+
if (!b) stop_decoding(JPGD_NOTENOUGHMEM);
|
900 |
+
b->m_pNext = m_pMem_blocks; m_pMem_blocks = b;
|
901 |
+
b->m_used_count = nSize;
|
902 |
+
b->m_size = capacity;
|
903 |
+
rv = b->m_data;
|
904 |
+
}
|
905 |
+
if (zero) memset(rv, 0, nSize);
|
906 |
+
return rv;
|
907 |
+
}
|
908 |
+
|
909 |
+
void jpeg_decoder::word_clear(void *p, uint16 c, uint n)
|
910 |
+
{
|
911 |
+
uint8 *pD = (uint8*)p;
|
912 |
+
const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF;
|
913 |
+
while (n)
|
914 |
+
{
|
915 |
+
pD[0] = l; pD[1] = h; pD += 2;
|
916 |
+
n--;
|
917 |
+
}
|
918 |
+
}
|
919 |
+
|
920 |
+
// Refill the input buffer.
|
921 |
+
// This method will sit in a loop until (A) the buffer is full or (B)
|
922 |
+
// the stream's read() method reports and end of file condition.
|
923 |
+
void jpeg_decoder::prep_in_buffer()
|
924 |
+
{
|
925 |
+
m_in_buf_left = 0;
|
926 |
+
m_pIn_buf_ofs = m_in_buf;
|
927 |
+
|
928 |
+
if (m_eof_flag)
|
929 |
+
return;
|
930 |
+
|
931 |
+
do
|
932 |
+
{
|
933 |
+
int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag);
|
934 |
+
if (bytes_read == -1)
|
935 |
+
stop_decoding(JPGD_STREAM_READ);
|
936 |
+
|
937 |
+
m_in_buf_left += bytes_read;
|
938 |
+
} while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag));
|
939 |
+
|
940 |
+
m_total_bytes_read += m_in_buf_left;
|
941 |
+
|
942 |
+
// Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid).
|
943 |
+
// (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.)
|
944 |
+
word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64);
|
945 |
+
}
|
946 |
+
|
947 |
+
// Read a Huffman code table.
|
948 |
+
void jpeg_decoder::read_dht_marker()
|
949 |
+
{
|
950 |
+
int i, index, count;
|
951 |
+
uint8 huff_num[17];
|
952 |
+
uint8 huff_val[256];
|
953 |
+
|
954 |
+
uint num_left = get_bits(16);
|
955 |
+
|
956 |
+
if (num_left < 2)
|
957 |
+
stop_decoding(JPGD_BAD_DHT_MARKER);
|
958 |
+
|
959 |
+
num_left -= 2;
|
960 |
+
|
961 |
+
while (num_left)
|
962 |
+
{
|
963 |
+
index = get_bits(8);
|
964 |
+
|
965 |
+
huff_num[0] = 0;
|
966 |
+
|
967 |
+
count = 0;
|
968 |
+
|
969 |
+
for (i = 1; i <= 16; i++)
|
970 |
+
{
|
971 |
+
huff_num[i] = static_cast<uint8>(get_bits(8));
|
972 |
+
count += huff_num[i];
|
973 |
+
}
|
974 |
+
|
975 |
+
if (count > 255)
|
976 |
+
stop_decoding(JPGD_BAD_DHT_COUNTS);
|
977 |
+
|
978 |
+
for (i = 0; i < count; i++)
|
979 |
+
huff_val[i] = static_cast<uint8>(get_bits(8));
|
980 |
+
|
981 |
+
i = 1 + 16 + count;
|
982 |
+
|
983 |
+
if (num_left < (uint)i)
|
984 |
+
stop_decoding(JPGD_BAD_DHT_MARKER);
|
985 |
+
|
986 |
+
num_left -= i;
|
987 |
+
|
988 |
+
if ((index & 0x10) > 0x10)
|
989 |
+
stop_decoding(JPGD_BAD_DHT_INDEX);
|
990 |
+
|
991 |
+
index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1);
|
992 |
+
|
993 |
+
if (index >= JPGD_MAX_HUFF_TABLES)
|
994 |
+
stop_decoding(JPGD_BAD_DHT_INDEX);
|
995 |
+
|
996 |
+
if (!m_huff_num[index])
|
997 |
+
m_huff_num[index] = (uint8 *)alloc(17);
|
998 |
+
|
999 |
+
if (!m_huff_val[index])
|
1000 |
+
m_huff_val[index] = (uint8 *)alloc(256);
|
1001 |
+
|
1002 |
+
m_huff_ac[index] = (index & 0x10) != 0;
|
1003 |
+
memcpy(m_huff_num[index], huff_num, 17);
|
1004 |
+
memcpy(m_huff_val[index], huff_val, 256);
|
1005 |
+
}
|
1006 |
+
}
|
1007 |
+
|
1008 |
+
// Read a quantization table.
|
1009 |
+
void jpeg_decoder::read_dqt_marker()
|
1010 |
+
{
|
1011 |
+
int n, i, prec;
|
1012 |
+
uint num_left;
|
1013 |
+
uint temp;
|
1014 |
+
|
1015 |
+
num_left = get_bits(16);
|
1016 |
+
|
1017 |
+
if (num_left < 2)
|
1018 |
+
stop_decoding(JPGD_BAD_DQT_MARKER);
|
1019 |
+
|
1020 |
+
num_left -= 2;
|
1021 |
+
|
1022 |
+
while (num_left)
|
1023 |
+
{
|
1024 |
+
n = get_bits(8);
|
1025 |
+
prec = n >> 4;
|
1026 |
+
n &= 0x0F;
|
1027 |
+
|
1028 |
+
if (n >= JPGD_MAX_QUANT_TABLES)
|
1029 |
+
stop_decoding(JPGD_BAD_DQT_TABLE);
|
1030 |
+
|
1031 |
+
if (!m_quant[n])
|
1032 |
+
m_quant[n] = (jpgd_quant_t *)alloc(64 * sizeof(jpgd_quant_t));
|
1033 |
+
|
1034 |
+
// read quantization entries, in zag order
|
1035 |
+
for (i = 0; i < 64; i++)
|
1036 |
+
{
|
1037 |
+
temp = get_bits(8);
|
1038 |
+
|
1039 |
+
if (prec)
|
1040 |
+
temp = (temp << 8) + get_bits(8);
|
1041 |
+
|
1042 |
+
m_quant[n][i] = static_cast<jpgd_quant_t>(temp);
|
1043 |
+
}
|
1044 |
+
|
1045 |
+
i = 64 + 1;
|
1046 |
+
|
1047 |
+
if (prec)
|
1048 |
+
i += 64;
|
1049 |
+
|
1050 |
+
if (num_left < (uint)i)
|
1051 |
+
stop_decoding(JPGD_BAD_DQT_LENGTH);
|
1052 |
+
|
1053 |
+
num_left -= i;
|
1054 |
+
}
|
1055 |
+
}
|
1056 |
+
|
1057 |
+
// Read the start of frame (SOF) marker.
|
1058 |
+
void jpeg_decoder::read_sof_marker()
|
1059 |
+
{
|
1060 |
+
int i;
|
1061 |
+
uint num_left;
|
1062 |
+
|
1063 |
+
num_left = get_bits(16);
|
1064 |
+
|
1065 |
+
if (get_bits(8) != 8) /* precision: sorry, only 8-bit precision is supported right now */
|
1066 |
+
stop_decoding(JPGD_BAD_PRECISION);
|
1067 |
+
|
1068 |
+
m_image_y_size = get_bits(16);
|
1069 |
+
|
1070 |
+
if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT))
|
1071 |
+
stop_decoding(JPGD_BAD_HEIGHT);
|
1072 |
+
|
1073 |
+
m_image_x_size = get_bits(16);
|
1074 |
+
|
1075 |
+
if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH))
|
1076 |
+
stop_decoding(JPGD_BAD_WIDTH);
|
1077 |
+
|
1078 |
+
m_comps_in_frame = get_bits(8);
|
1079 |
+
|
1080 |
+
if (m_comps_in_frame > JPGD_MAX_COMPONENTS)
|
1081 |
+
stop_decoding(JPGD_TOO_MANY_COMPONENTS);
|
1082 |
+
|
1083 |
+
if (num_left != (uint)(m_comps_in_frame * 3 + 8))
|
1084 |
+
stop_decoding(JPGD_BAD_SOF_LENGTH);
|
1085 |
+
|
1086 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
1087 |
+
{
|
1088 |
+
m_comp_ident[i] = get_bits(8);
|
1089 |
+
m_comp_h_samp[i] = get_bits(4);
|
1090 |
+
m_comp_v_samp[i] = get_bits(4);
|
1091 |
+
m_comp_quant[i] = get_bits(8);
|
1092 |
+
}
|
1093 |
+
}
|
1094 |
+
|
1095 |
+
// Used to skip unrecognized markers.
|
1096 |
+
void jpeg_decoder::skip_variable_marker()
|
1097 |
+
{
|
1098 |
+
uint num_left;
|
1099 |
+
|
1100 |
+
num_left = get_bits(16);
|
1101 |
+
|
1102 |
+
if (num_left < 2)
|
1103 |
+
stop_decoding(JPGD_BAD_VARIABLE_MARKER);
|
1104 |
+
|
1105 |
+
num_left -= 2;
|
1106 |
+
|
1107 |
+
while (num_left)
|
1108 |
+
{
|
1109 |
+
get_bits(8);
|
1110 |
+
num_left--;
|
1111 |
+
}
|
1112 |
+
}
|
1113 |
+
|
1114 |
+
// Read a define restart interval (DRI) marker.
|
1115 |
+
void jpeg_decoder::read_dri_marker()
|
1116 |
+
{
|
1117 |
+
if (get_bits(16) != 4)
|
1118 |
+
stop_decoding(JPGD_BAD_DRI_LENGTH);
|
1119 |
+
|
1120 |
+
m_restart_interval = get_bits(16);
|
1121 |
+
}
|
1122 |
+
|
1123 |
+
// Read a start of scan (SOS) marker.
|
1124 |
+
void jpeg_decoder::read_sos_marker()
|
1125 |
+
{
|
1126 |
+
uint num_left;
|
1127 |
+
int i, ci, n, c, cc;
|
1128 |
+
|
1129 |
+
num_left = get_bits(16);
|
1130 |
+
|
1131 |
+
n = get_bits(8);
|
1132 |
+
|
1133 |
+
m_comps_in_scan = n;
|
1134 |
+
|
1135 |
+
num_left -= 3;
|
1136 |
+
|
1137 |
+
if ( (num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN) )
|
1138 |
+
stop_decoding(JPGD_BAD_SOS_LENGTH);
|
1139 |
+
|
1140 |
+
for (i = 0; i < n; i++)
|
1141 |
+
{
|
1142 |
+
cc = get_bits(8);
|
1143 |
+
c = get_bits(8);
|
1144 |
+
num_left -= 2;
|
1145 |
+
|
1146 |
+
for (ci = 0; ci < m_comps_in_frame; ci++)
|
1147 |
+
if (cc == m_comp_ident[ci])
|
1148 |
+
break;
|
1149 |
+
|
1150 |
+
if (ci >= m_comps_in_frame)
|
1151 |
+
stop_decoding(JPGD_BAD_SOS_COMP_ID);
|
1152 |
+
|
1153 |
+
m_comp_list[i] = ci;
|
1154 |
+
m_comp_dc_tab[ci] = (c >> 4) & 15;
|
1155 |
+
m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1);
|
1156 |
+
}
|
1157 |
+
|
1158 |
+
m_spectral_start = get_bits(8);
|
1159 |
+
m_spectral_end = get_bits(8);
|
1160 |
+
m_successive_high = get_bits(4);
|
1161 |
+
m_successive_low = get_bits(4);
|
1162 |
+
|
1163 |
+
if (!m_progressive_flag)
|
1164 |
+
{
|
1165 |
+
m_spectral_start = 0;
|
1166 |
+
m_spectral_end = 63;
|
1167 |
+
}
|
1168 |
+
|
1169 |
+
num_left -= 3;
|
1170 |
+
|
1171 |
+
while (num_left) /* read past whatever is num_left */
|
1172 |
+
{
|
1173 |
+
get_bits(8);
|
1174 |
+
num_left--;
|
1175 |
+
}
|
1176 |
+
}
|
1177 |
+
|
1178 |
+
// Finds the next marker.
|
1179 |
+
int jpeg_decoder::next_marker()
|
1180 |
+
{
|
1181 |
+
uint c, bytes;
|
1182 |
+
|
1183 |
+
bytes = 0;
|
1184 |
+
|
1185 |
+
do
|
1186 |
+
{
|
1187 |
+
do
|
1188 |
+
{
|
1189 |
+
bytes++;
|
1190 |
+
c = get_bits(8);
|
1191 |
+
} while (c != 0xFF);
|
1192 |
+
|
1193 |
+
do
|
1194 |
+
{
|
1195 |
+
c = get_bits(8);
|
1196 |
+
} while (c == 0xFF);
|
1197 |
+
|
1198 |
+
} while (c == 0);
|
1199 |
+
|
1200 |
+
// If bytes > 0 here, there where extra bytes before the marker (not good).
|
1201 |
+
|
1202 |
+
return c;
|
1203 |
+
}
|
1204 |
+
|
1205 |
+
// Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is
|
1206 |
+
// encountered.
|
1207 |
+
int jpeg_decoder::process_markers()
|
1208 |
+
{
|
1209 |
+
int c;
|
1210 |
+
|
1211 |
+
for ( ; ; )
|
1212 |
+
{
|
1213 |
+
c = next_marker();
|
1214 |
+
|
1215 |
+
switch (c)
|
1216 |
+
{
|
1217 |
+
case M_SOF0:
|
1218 |
+
case M_SOF1:
|
1219 |
+
case M_SOF2:
|
1220 |
+
case M_SOF3:
|
1221 |
+
case M_SOF5:
|
1222 |
+
case M_SOF6:
|
1223 |
+
case M_SOF7:
|
1224 |
+
// case M_JPG:
|
1225 |
+
case M_SOF9:
|
1226 |
+
case M_SOF10:
|
1227 |
+
case M_SOF11:
|
1228 |
+
case M_SOF13:
|
1229 |
+
case M_SOF14:
|
1230 |
+
case M_SOF15:
|
1231 |
+
case M_SOI:
|
1232 |
+
case M_EOI:
|
1233 |
+
case M_SOS:
|
1234 |
+
{
|
1235 |
+
return c;
|
1236 |
+
}
|
1237 |
+
case M_DHT:
|
1238 |
+
{
|
1239 |
+
read_dht_marker();
|
1240 |
+
break;
|
1241 |
+
}
|
1242 |
+
// No arithmitic support - dumb patents!
|
1243 |
+
case M_DAC:
|
1244 |
+
{
|
1245 |
+
stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
|
1246 |
+
break;
|
1247 |
+
}
|
1248 |
+
case M_DQT:
|
1249 |
+
{
|
1250 |
+
read_dqt_marker();
|
1251 |
+
break;
|
1252 |
+
}
|
1253 |
+
case M_DRI:
|
1254 |
+
{
|
1255 |
+
read_dri_marker();
|
1256 |
+
break;
|
1257 |
+
}
|
1258 |
+
//case M_APP0: /* no need to read the JFIF marker */
|
1259 |
+
|
1260 |
+
case M_JPG:
|
1261 |
+
case M_RST0: /* no parameters */
|
1262 |
+
case M_RST1:
|
1263 |
+
case M_RST2:
|
1264 |
+
case M_RST3:
|
1265 |
+
case M_RST4:
|
1266 |
+
case M_RST5:
|
1267 |
+
case M_RST6:
|
1268 |
+
case M_RST7:
|
1269 |
+
case M_TEM:
|
1270 |
+
{
|
1271 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
1272 |
+
break;
|
1273 |
+
}
|
1274 |
+
default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */
|
1275 |
+
{
|
1276 |
+
skip_variable_marker();
|
1277 |
+
break;
|
1278 |
+
}
|
1279 |
+
}
|
1280 |
+
}
|
1281 |
+
}
|
1282 |
+
|
1283 |
+
// Finds the start of image (SOI) marker.
|
1284 |
+
// This code is rather defensive: it only checks the first 512 bytes to avoid
|
1285 |
+
// false positives.
|
1286 |
+
void jpeg_decoder::locate_soi_marker()
|
1287 |
+
{
|
1288 |
+
uint lastchar, thischar;
|
1289 |
+
uint bytesleft;
|
1290 |
+
|
1291 |
+
lastchar = get_bits(8);
|
1292 |
+
|
1293 |
+
thischar = get_bits(8);
|
1294 |
+
|
1295 |
+
/* ok if it's a normal JPEG file without a special header */
|
1296 |
+
|
1297 |
+
if ((lastchar == 0xFF) && (thischar == M_SOI))
|
1298 |
+
return;
|
1299 |
+
|
1300 |
+
bytesleft = 4096; //512;
|
1301 |
+
|
1302 |
+
for ( ; ; )
|
1303 |
+
{
|
1304 |
+
if (--bytesleft == 0)
|
1305 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1306 |
+
|
1307 |
+
lastchar = thischar;
|
1308 |
+
|
1309 |
+
thischar = get_bits(8);
|
1310 |
+
|
1311 |
+
if (lastchar == 0xFF)
|
1312 |
+
{
|
1313 |
+
if (thischar == M_SOI)
|
1314 |
+
break;
|
1315 |
+
else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end
|
1316 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1317 |
+
}
|
1318 |
+
}
|
1319 |
+
|
1320 |
+
// Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad.
|
1321 |
+
thischar = (m_bit_buf >> 24) & 0xFF;
|
1322 |
+
|
1323 |
+
if (thischar != 0xFF)
|
1324 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1325 |
+
}
|
1326 |
+
|
1327 |
+
// Find a start of frame (SOF) marker.
|
1328 |
+
void jpeg_decoder::locate_sof_marker()
|
1329 |
+
{
|
1330 |
+
locate_soi_marker();
|
1331 |
+
|
1332 |
+
int c = process_markers();
|
1333 |
+
|
1334 |
+
switch (c)
|
1335 |
+
{
|
1336 |
+
case M_SOF2:
|
1337 |
+
m_progressive_flag = JPGD_TRUE;
|
1338 |
+
case M_SOF0: /* baseline DCT */
|
1339 |
+
case M_SOF1: /* extended sequential DCT */
|
1340 |
+
{
|
1341 |
+
read_sof_marker();
|
1342 |
+
break;
|
1343 |
+
}
|
1344 |
+
case M_SOF9: /* Arithmitic coding */
|
1345 |
+
{
|
1346 |
+
stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
|
1347 |
+
break;
|
1348 |
+
}
|
1349 |
+
default:
|
1350 |
+
{
|
1351 |
+
stop_decoding(JPGD_UNSUPPORTED_MARKER);
|
1352 |
+
break;
|
1353 |
+
}
|
1354 |
+
}
|
1355 |
+
}
|
1356 |
+
|
1357 |
+
// Find a start of scan (SOS) marker.
|
1358 |
+
int jpeg_decoder::locate_sos_marker()
|
1359 |
+
{
|
1360 |
+
int c;
|
1361 |
+
|
1362 |
+
c = process_markers();
|
1363 |
+
|
1364 |
+
if (c == M_EOI)
|
1365 |
+
return JPGD_FALSE;
|
1366 |
+
else if (c != M_SOS)
|
1367 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
1368 |
+
|
1369 |
+
read_sos_marker();
|
1370 |
+
|
1371 |
+
return JPGD_TRUE;
|
1372 |
+
}
|
1373 |
+
|
1374 |
+
// Reset everything to default/uninitialized state.
|
1375 |
+
void jpeg_decoder::init(jpeg_decoder_stream *pStream)
|
1376 |
+
{
|
1377 |
+
m_pMem_blocks = NULL;
|
1378 |
+
m_error_code = JPGD_SUCCESS;
|
1379 |
+
m_ready_flag = false;
|
1380 |
+
m_image_x_size = m_image_y_size = 0;
|
1381 |
+
m_pStream = pStream;
|
1382 |
+
m_progressive_flag = JPGD_FALSE;
|
1383 |
+
|
1384 |
+
memset(m_huff_ac, 0, sizeof(m_huff_ac));
|
1385 |
+
memset(m_huff_num, 0, sizeof(m_huff_num));
|
1386 |
+
memset(m_huff_val, 0, sizeof(m_huff_val));
|
1387 |
+
memset(m_quant, 0, sizeof(m_quant));
|
1388 |
+
|
1389 |
+
m_scan_type = 0;
|
1390 |
+
m_comps_in_frame = 0;
|
1391 |
+
|
1392 |
+
memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp));
|
1393 |
+
memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp));
|
1394 |
+
memset(m_comp_quant, 0, sizeof(m_comp_quant));
|
1395 |
+
memset(m_comp_ident, 0, sizeof(m_comp_ident));
|
1396 |
+
memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks));
|
1397 |
+
memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks));
|
1398 |
+
|
1399 |
+
m_comps_in_scan = 0;
|
1400 |
+
memset(m_comp_list, 0, sizeof(m_comp_list));
|
1401 |
+
memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab));
|
1402 |
+
memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab));
|
1403 |
+
|
1404 |
+
m_spectral_start = 0;
|
1405 |
+
m_spectral_end = 0;
|
1406 |
+
m_successive_low = 0;
|
1407 |
+
m_successive_high = 0;
|
1408 |
+
m_max_mcu_x_size = 0;
|
1409 |
+
m_max_mcu_y_size = 0;
|
1410 |
+
m_blocks_per_mcu = 0;
|
1411 |
+
m_max_blocks_per_row = 0;
|
1412 |
+
m_mcus_per_row = 0;
|
1413 |
+
m_mcus_per_col = 0;
|
1414 |
+
m_expanded_blocks_per_component = 0;
|
1415 |
+
m_expanded_blocks_per_mcu = 0;
|
1416 |
+
m_expanded_blocks_per_row = 0;
|
1417 |
+
m_freq_domain_chroma_upsample = false;
|
1418 |
+
|
1419 |
+
memset(m_mcu_org, 0, sizeof(m_mcu_org));
|
1420 |
+
|
1421 |
+
m_total_lines_left = 0;
|
1422 |
+
m_mcu_lines_left = 0;
|
1423 |
+
m_real_dest_bytes_per_scan_line = 0;
|
1424 |
+
m_dest_bytes_per_scan_line = 0;
|
1425 |
+
m_dest_bytes_per_pixel = 0;
|
1426 |
+
|
1427 |
+
memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs));
|
1428 |
+
|
1429 |
+
memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs));
|
1430 |
+
memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs));
|
1431 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
1432 |
+
|
1433 |
+
m_eob_run = 0;
|
1434 |
+
|
1435 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
1436 |
+
|
1437 |
+
m_pIn_buf_ofs = m_in_buf;
|
1438 |
+
m_in_buf_left = 0;
|
1439 |
+
m_eof_flag = false;
|
1440 |
+
m_tem_flag = 0;
|
1441 |
+
|
1442 |
+
memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start));
|
1443 |
+
memset(m_in_buf, 0, sizeof(m_in_buf));
|
1444 |
+
memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end));
|
1445 |
+
|
1446 |
+
m_restart_interval = 0;
|
1447 |
+
m_restarts_left = 0;
|
1448 |
+
m_next_restart_num = 0;
|
1449 |
+
|
1450 |
+
m_max_mcus_per_row = 0;
|
1451 |
+
m_max_blocks_per_mcu = 0;
|
1452 |
+
m_max_mcus_per_col = 0;
|
1453 |
+
|
1454 |
+
memset(m_last_dc_val, 0, sizeof(m_last_dc_val));
|
1455 |
+
m_pMCU_coefficients = NULL;
|
1456 |
+
m_pSample_buf = NULL;
|
1457 |
+
|
1458 |
+
m_total_bytes_read = 0;
|
1459 |
+
|
1460 |
+
m_pScan_line_0 = NULL;
|
1461 |
+
m_pScan_line_1 = NULL;
|
1462 |
+
|
1463 |
+
// Ready the input buffer.
|
1464 |
+
prep_in_buffer();
|
1465 |
+
|
1466 |
+
// Prime the bit buffer.
|
1467 |
+
m_bits_left = 16;
|
1468 |
+
m_bit_buf = 0;
|
1469 |
+
|
1470 |
+
get_bits(16);
|
1471 |
+
get_bits(16);
|
1472 |
+
|
1473 |
+
for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++)
|
1474 |
+
m_mcu_block_max_zag[i] = 64;
|
1475 |
+
}
|
1476 |
+
|
1477 |
+
#define SCALEBITS 16
|
1478 |
+
#define ONE_HALF ((int) 1 << (SCALEBITS-1))
|
1479 |
+
#define FIX(x) ((int) ((x) * (1L<<SCALEBITS) + 0.5f))
|
1480 |
+
|
1481 |
+
// Create a few tables that allow us to quickly convert YCbCr to RGB.
|
1482 |
+
void jpeg_decoder::create_look_ups()
|
1483 |
+
{
|
1484 |
+
for (int i = 0; i <= 255; i++)
|
1485 |
+
{
|
1486 |
+
int k = i - 128;
|
1487 |
+
m_crr[i] = ( FIX(1.40200f) * k + ONE_HALF) >> SCALEBITS;
|
1488 |
+
m_cbb[i] = ( FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS;
|
1489 |
+
m_crg[i] = (-FIX(0.71414f)) * k;
|
1490 |
+
m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF;
|
1491 |
+
}
|
1492 |
+
}
|
1493 |
+
|
1494 |
+
// This method throws back into the stream any bytes that where read
|
1495 |
+
// into the bit buffer during initial marker scanning.
|
1496 |
+
void jpeg_decoder::fix_in_buffer()
|
1497 |
+
{
|
1498 |
+
// In case any 0xFF's where pulled into the buffer during marker scanning.
|
1499 |
+
JPGD_ASSERT((m_bits_left & 7) == 0);
|
1500 |
+
|
1501 |
+
if (m_bits_left == 16)
|
1502 |
+
stuff_char( (uint8)(m_bit_buf & 0xFF));
|
1503 |
+
|
1504 |
+
if (m_bits_left >= 8)
|
1505 |
+
stuff_char( (uint8)((m_bit_buf >> 8) & 0xFF));
|
1506 |
+
|
1507 |
+
stuff_char((uint8)((m_bit_buf >> 16) & 0xFF));
|
1508 |
+
stuff_char((uint8)((m_bit_buf >> 24) & 0xFF));
|
1509 |
+
|
1510 |
+
m_bits_left = 16;
|
1511 |
+
get_bits_no_markers(16);
|
1512 |
+
get_bits_no_markers(16);
|
1513 |
+
}
|
1514 |
+
|
1515 |
+
void jpeg_decoder::transform_mcu(int mcu_row)
|
1516 |
+
{
|
1517 |
+
jpgd_block_t* pSrc_ptr = m_pMCU_coefficients;
|
1518 |
+
uint8* pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64;
|
1519 |
+
|
1520 |
+
for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
1521 |
+
{
|
1522 |
+
idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
|
1523 |
+
pSrc_ptr += 64;
|
1524 |
+
pDst_ptr += 64;
|
1525 |
+
}
|
1526 |
+
}
|
1527 |
+
|
1528 |
+
static const uint8 s_max_rc[64] =
|
1529 |
+
{
|
1530 |
+
17, 18, 34, 50, 50, 51, 52, 52, 52, 68, 84, 84, 84, 84, 85, 86, 86, 86, 86, 86,
|
1531 |
+
102, 118, 118, 118, 118, 118, 118, 119, 120, 120, 120, 120, 120, 120, 120, 136,
|
1532 |
+
136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136,
|
1533 |
+
136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136
|
1534 |
+
};
|
1535 |
+
|
1536 |
+
void jpeg_decoder::transform_mcu_expand(int mcu_row)
|
1537 |
+
{
|
1538 |
+
jpgd_block_t* pSrc_ptr = m_pMCU_coefficients;
|
1539 |
+
uint8* pDst_ptr = m_pSample_buf + mcu_row * m_expanded_blocks_per_mcu * 64;
|
1540 |
+
|
1541 |
+
// Y IDCT
|
1542 |
+
int mcu_block;
|
1543 |
+
for (mcu_block = 0; mcu_block < m_expanded_blocks_per_component; mcu_block++)
|
1544 |
+
{
|
1545 |
+
idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
|
1546 |
+
pSrc_ptr += 64;
|
1547 |
+
pDst_ptr += 64;
|
1548 |
+
}
|
1549 |
+
|
1550 |
+
// Chroma IDCT, with upsampling
|
1551 |
+
jpgd_block_t temp_block[64];
|
1552 |
+
|
1553 |
+
for (int i = 0; i < 2; i++)
|
1554 |
+
{
|
1555 |
+
DCT_Upsample::Matrix44 P, Q, R, S;
|
1556 |
+
|
1557 |
+
JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] >= 1);
|
1558 |
+
JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] <= 64);
|
1559 |
+
|
1560 |
+
switch (s_max_rc[m_mcu_block_max_zag[mcu_block++] - 1])
|
1561 |
+
{
|
1562 |
+
case 1*16+1:
|
1563 |
+
DCT_Upsample::P_Q<1, 1>::calc(P, Q, pSrc_ptr);
|
1564 |
+
DCT_Upsample::R_S<1, 1>::calc(R, S, pSrc_ptr);
|
1565 |
+
break;
|
1566 |
+
case 1*16+2:
|
1567 |
+
DCT_Upsample::P_Q<1, 2>::calc(P, Q, pSrc_ptr);
|
1568 |
+
DCT_Upsample::R_S<1, 2>::calc(R, S, pSrc_ptr);
|
1569 |
+
break;
|
1570 |
+
case 2*16+2:
|
1571 |
+
DCT_Upsample::P_Q<2, 2>::calc(P, Q, pSrc_ptr);
|
1572 |
+
DCT_Upsample::R_S<2, 2>::calc(R, S, pSrc_ptr);
|
1573 |
+
break;
|
1574 |
+
case 3*16+2:
|
1575 |
+
DCT_Upsample::P_Q<3, 2>::calc(P, Q, pSrc_ptr);
|
1576 |
+
DCT_Upsample::R_S<3, 2>::calc(R, S, pSrc_ptr);
|
1577 |
+
break;
|
1578 |
+
case 3*16+3:
|
1579 |
+
DCT_Upsample::P_Q<3, 3>::calc(P, Q, pSrc_ptr);
|
1580 |
+
DCT_Upsample::R_S<3, 3>::calc(R, S, pSrc_ptr);
|
1581 |
+
break;
|
1582 |
+
case 3*16+4:
|
1583 |
+
DCT_Upsample::P_Q<3, 4>::calc(P, Q, pSrc_ptr);
|
1584 |
+
DCT_Upsample::R_S<3, 4>::calc(R, S, pSrc_ptr);
|
1585 |
+
break;
|
1586 |
+
case 4*16+4:
|
1587 |
+
DCT_Upsample::P_Q<4, 4>::calc(P, Q, pSrc_ptr);
|
1588 |
+
DCT_Upsample::R_S<4, 4>::calc(R, S, pSrc_ptr);
|
1589 |
+
break;
|
1590 |
+
case 5*16+4:
|
1591 |
+
DCT_Upsample::P_Q<5, 4>::calc(P, Q, pSrc_ptr);
|
1592 |
+
DCT_Upsample::R_S<5, 4>::calc(R, S, pSrc_ptr);
|
1593 |
+
break;
|
1594 |
+
case 5*16+5:
|
1595 |
+
DCT_Upsample::P_Q<5, 5>::calc(P, Q, pSrc_ptr);
|
1596 |
+
DCT_Upsample::R_S<5, 5>::calc(R, S, pSrc_ptr);
|
1597 |
+
break;
|
1598 |
+
case 5*16+6:
|
1599 |
+
DCT_Upsample::P_Q<5, 6>::calc(P, Q, pSrc_ptr);
|
1600 |
+
DCT_Upsample::R_S<5, 6>::calc(R, S, pSrc_ptr);
|
1601 |
+
break;
|
1602 |
+
case 6*16+6:
|
1603 |
+
DCT_Upsample::P_Q<6, 6>::calc(P, Q, pSrc_ptr);
|
1604 |
+
DCT_Upsample::R_S<6, 6>::calc(R, S, pSrc_ptr);
|
1605 |
+
break;
|
1606 |
+
case 7*16+6:
|
1607 |
+
DCT_Upsample::P_Q<7, 6>::calc(P, Q, pSrc_ptr);
|
1608 |
+
DCT_Upsample::R_S<7, 6>::calc(R, S, pSrc_ptr);
|
1609 |
+
break;
|
1610 |
+
case 7*16+7:
|
1611 |
+
DCT_Upsample::P_Q<7, 7>::calc(P, Q, pSrc_ptr);
|
1612 |
+
DCT_Upsample::R_S<7, 7>::calc(R, S, pSrc_ptr);
|
1613 |
+
break;
|
1614 |
+
case 7*16+8:
|
1615 |
+
DCT_Upsample::P_Q<7, 8>::calc(P, Q, pSrc_ptr);
|
1616 |
+
DCT_Upsample::R_S<7, 8>::calc(R, S, pSrc_ptr);
|
1617 |
+
break;
|
1618 |
+
case 8*16+8:
|
1619 |
+
DCT_Upsample::P_Q<8, 8>::calc(P, Q, pSrc_ptr);
|
1620 |
+
DCT_Upsample::R_S<8, 8>::calc(R, S, pSrc_ptr);
|
1621 |
+
break;
|
1622 |
+
default:
|
1623 |
+
JPGD_ASSERT(false);
|
1624 |
+
}
|
1625 |
+
|
1626 |
+
DCT_Upsample::Matrix44 a(P + Q); P -= Q;
|
1627 |
+
DCT_Upsample::Matrix44& b = P;
|
1628 |
+
DCT_Upsample::Matrix44 c(R + S); R -= S;
|
1629 |
+
DCT_Upsample::Matrix44& d = R;
|
1630 |
+
|
1631 |
+
DCT_Upsample::Matrix44::add_and_store(temp_block, a, c);
|
1632 |
+
idct_4x4(temp_block, pDst_ptr);
|
1633 |
+
pDst_ptr += 64;
|
1634 |
+
|
1635 |
+
DCT_Upsample::Matrix44::sub_and_store(temp_block, a, c);
|
1636 |
+
idct_4x4(temp_block, pDst_ptr);
|
1637 |
+
pDst_ptr += 64;
|
1638 |
+
|
1639 |
+
DCT_Upsample::Matrix44::add_and_store(temp_block, b, d);
|
1640 |
+
idct_4x4(temp_block, pDst_ptr);
|
1641 |
+
pDst_ptr += 64;
|
1642 |
+
|
1643 |
+
DCT_Upsample::Matrix44::sub_and_store(temp_block, b, d);
|
1644 |
+
idct_4x4(temp_block, pDst_ptr);
|
1645 |
+
pDst_ptr += 64;
|
1646 |
+
|
1647 |
+
pSrc_ptr += 64;
|
1648 |
+
}
|
1649 |
+
}
|
1650 |
+
|
1651 |
+
// Loads and dequantizes the next row of (already decoded) coefficients.
|
1652 |
+
// Progressive images only.
|
1653 |
+
void jpeg_decoder::load_next_row()
|
1654 |
+
{
|
1655 |
+
int i;
|
1656 |
+
jpgd_block_t *p;
|
1657 |
+
jpgd_quant_t *q;
|
1658 |
+
int mcu_row, mcu_block, row_block = 0;
|
1659 |
+
int component_num, component_id;
|
1660 |
+
int block_x_mcu[JPGD_MAX_COMPONENTS];
|
1661 |
+
|
1662 |
+
memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int));
|
1663 |
+
|
1664 |
+
for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
1665 |
+
{
|
1666 |
+
int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
|
1667 |
+
|
1668 |
+
for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
1669 |
+
{
|
1670 |
+
component_id = m_mcu_org[mcu_block];
|
1671 |
+
q = m_quant[m_comp_quant[component_id]];
|
1672 |
+
|
1673 |
+
p = m_pMCU_coefficients + 64 * mcu_block;
|
1674 |
+
|
1675 |
+
jpgd_block_t* pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
1676 |
+
jpgd_block_t* pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
1677 |
+
p[0] = pDC[0];
|
1678 |
+
memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t));
|
1679 |
+
|
1680 |
+
for (i = 63; i > 0; i--)
|
1681 |
+
if (p[g_ZAG[i]])
|
1682 |
+
break;
|
1683 |
+
|
1684 |
+
m_mcu_block_max_zag[mcu_block] = i + 1;
|
1685 |
+
|
1686 |
+
for ( ; i >= 0; i--)
|
1687 |
+
if (p[g_ZAG[i]])
|
1688 |
+
p[g_ZAG[i]] = static_cast<jpgd_block_t>(p[g_ZAG[i]] * q[i]);
|
1689 |
+
|
1690 |
+
row_block++;
|
1691 |
+
|
1692 |
+
if (m_comps_in_scan == 1)
|
1693 |
+
block_x_mcu[component_id]++;
|
1694 |
+
else
|
1695 |
+
{
|
1696 |
+
if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
|
1697 |
+
{
|
1698 |
+
block_x_mcu_ofs = 0;
|
1699 |
+
|
1700 |
+
if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
|
1701 |
+
{
|
1702 |
+
block_y_mcu_ofs = 0;
|
1703 |
+
|
1704 |
+
block_x_mcu[component_id] += m_comp_h_samp[component_id];
|
1705 |
+
}
|
1706 |
+
}
|
1707 |
+
}
|
1708 |
+
}
|
1709 |
+
|
1710 |
+
if (m_freq_domain_chroma_upsample)
|
1711 |
+
transform_mcu_expand(mcu_row);
|
1712 |
+
else
|
1713 |
+
transform_mcu(mcu_row);
|
1714 |
+
}
|
1715 |
+
|
1716 |
+
if (m_comps_in_scan == 1)
|
1717 |
+
m_block_y_mcu[m_comp_list[0]]++;
|
1718 |
+
else
|
1719 |
+
{
|
1720 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
1721 |
+
{
|
1722 |
+
component_id = m_comp_list[component_num];
|
1723 |
+
|
1724 |
+
m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
|
1725 |
+
}
|
1726 |
+
}
|
1727 |
+
}
|
1728 |
+
|
1729 |
+
// Restart interval processing.
|
1730 |
+
void jpeg_decoder::process_restart()
|
1731 |
+
{
|
1732 |
+
int i;
|
1733 |
+
int c = 0;
|
1734 |
+
|
1735 |
+
// Align to a byte boundry
|
1736 |
+
// FIXME: Is this really necessary? get_bits_no_markers() never reads in markers!
|
1737 |
+
//get_bits_no_markers(m_bits_left & 7);
|
1738 |
+
|
1739 |
+
// Let's scan a little bit to find the marker, but not _too_ far.
|
1740 |
+
// 1536 is a "fudge factor" that determines how much to scan.
|
1741 |
+
for (i = 1536; i > 0; i--)
|
1742 |
+
if (get_char() == 0xFF)
|
1743 |
+
break;
|
1744 |
+
|
1745 |
+
if (i == 0)
|
1746 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1747 |
+
|
1748 |
+
for ( ; i > 0; i--)
|
1749 |
+
if ((c = get_char()) != 0xFF)
|
1750 |
+
break;
|
1751 |
+
|
1752 |
+
if (i == 0)
|
1753 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1754 |
+
|
1755 |
+
// Is it the expected marker? If not, something bad happened.
|
1756 |
+
if (c != (m_next_restart_num + M_RST0))
|
1757 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1758 |
+
|
1759 |
+
// Reset each component's DC prediction values.
|
1760 |
+
memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
|
1761 |
+
|
1762 |
+
m_eob_run = 0;
|
1763 |
+
|
1764 |
+
m_restarts_left = m_restart_interval;
|
1765 |
+
|
1766 |
+
m_next_restart_num = (m_next_restart_num + 1) & 7;
|
1767 |
+
|
1768 |
+
// Get the bit buffer going again...
|
1769 |
+
|
1770 |
+
m_bits_left = 16;
|
1771 |
+
get_bits_no_markers(16);
|
1772 |
+
get_bits_no_markers(16);
|
1773 |
+
}
|
1774 |
+
|
1775 |
+
static inline int dequantize_ac(int c, int q) { c *= q; return c; }
|
1776 |
+
|
1777 |
+
// Decodes and dequantizes the next row of coefficients.
|
1778 |
+
void jpeg_decoder::decode_next_row()
|
1779 |
+
{
|
1780 |
+
int row_block = 0;
|
1781 |
+
|
1782 |
+
for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
1783 |
+
{
|
1784 |
+
if ((m_restart_interval) && (m_restarts_left == 0))
|
1785 |
+
process_restart();
|
1786 |
+
|
1787 |
+
jpgd_block_t* p = m_pMCU_coefficients;
|
1788 |
+
for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64)
|
1789 |
+
{
|
1790 |
+
int component_id = m_mcu_org[mcu_block];
|
1791 |
+
jpgd_quant_t* q = m_quant[m_comp_quant[component_id]];
|
1792 |
+
|
1793 |
+
int r, s;
|
1794 |
+
s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r);
|
1795 |
+
s = HUFF_EXTEND(r, s);
|
1796 |
+
|
1797 |
+
m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]);
|
1798 |
+
|
1799 |
+
p[0] = static_cast<jpgd_block_t>(s * q[0]);
|
1800 |
+
|
1801 |
+
int prev_num_set = m_mcu_block_max_zag[mcu_block];
|
1802 |
+
|
1803 |
+
huff_tables *pH = m_pHuff_tabs[m_comp_ac_tab[component_id]];
|
1804 |
+
|
1805 |
+
int k;
|
1806 |
+
for (k = 1; k < 64; k++)
|
1807 |
+
{
|
1808 |
+
int extra_bits;
|
1809 |
+
s = huff_decode(pH, extra_bits);
|
1810 |
+
|
1811 |
+
r = s >> 4;
|
1812 |
+
s &= 15;
|
1813 |
+
|
1814 |
+
if (s)
|
1815 |
+
{
|
1816 |
+
if (r)
|
1817 |
+
{
|
1818 |
+
if ((k + r) > 63)
|
1819 |
+
stop_decoding(JPGD_DECODE_ERROR);
|
1820 |
+
|
1821 |
+
if (k < prev_num_set)
|
1822 |
+
{
|
1823 |
+
int n = JPGD_MIN(r, prev_num_set - k);
|
1824 |
+
int kt = k;
|
1825 |
+
while (n--)
|
1826 |
+
p[g_ZAG[kt++]] = 0;
|
1827 |
+
}
|
1828 |
+
|
1829 |
+
k += r;
|
1830 |
+
}
|
1831 |
+
|
1832 |
+
s = HUFF_EXTEND(extra_bits, s);
|
1833 |
+
|
1834 |
+
JPGD_ASSERT(k < 64);
|
1835 |
+
|
1836 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(dequantize_ac(s, q[k])); //s * q[k];
|
1837 |
+
}
|
1838 |
+
else
|
1839 |
+
{
|
1840 |
+
if (r == 15)
|
1841 |
+
{
|
1842 |
+
if ((k + 16) > 64)
|
1843 |
+
stop_decoding(JPGD_DECODE_ERROR);
|
1844 |
+
|
1845 |
+
if (k < prev_num_set)
|
1846 |
+
{
|
1847 |
+
int n = JPGD_MIN(16, prev_num_set - k);
|
1848 |
+
int kt = k;
|
1849 |
+
while (n--)
|
1850 |
+
{
|
1851 |
+
JPGD_ASSERT(kt <= 63);
|
1852 |
+
p[g_ZAG[kt++]] = 0;
|
1853 |
+
}
|
1854 |
+
}
|
1855 |
+
|
1856 |
+
k += 16 - 1; // - 1 because the loop counter is k
|
1857 |
+
// BEGIN EPIC MOD
|
1858 |
+
JPGD_ASSERT(k < 64 && p[g_ZAG[k]] == 0);
|
1859 |
+
// END EPIC MOD
|
1860 |
+
}
|
1861 |
+
else
|
1862 |
+
break;
|
1863 |
+
}
|
1864 |
+
}
|
1865 |
+
|
1866 |
+
if (k < prev_num_set)
|
1867 |
+
{
|
1868 |
+
int kt = k;
|
1869 |
+
while (kt < prev_num_set)
|
1870 |
+
p[g_ZAG[kt++]] = 0;
|
1871 |
+
}
|
1872 |
+
|
1873 |
+
m_mcu_block_max_zag[mcu_block] = k;
|
1874 |
+
|
1875 |
+
row_block++;
|
1876 |
+
}
|
1877 |
+
|
1878 |
+
if (m_freq_domain_chroma_upsample)
|
1879 |
+
transform_mcu_expand(mcu_row);
|
1880 |
+
else
|
1881 |
+
transform_mcu(mcu_row);
|
1882 |
+
|
1883 |
+
m_restarts_left--;
|
1884 |
+
}
|
1885 |
+
}
|
1886 |
+
|
1887 |
+
// YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB
|
1888 |
+
void jpeg_decoder::H1V1Convert()
|
1889 |
+
{
|
1890 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1891 |
+
uint8 *d = m_pScan_line_0;
|
1892 |
+
uint8 *s = m_pSample_buf + row * 8;
|
1893 |
+
|
1894 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1895 |
+
{
|
1896 |
+
for (int j = 0; j < 8; j++)
|
1897 |
+
{
|
1898 |
+
int y = s[j];
|
1899 |
+
int cb = s[64+j];
|
1900 |
+
int cr = s[128+j];
|
1901 |
+
|
1902 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
1903 |
+
{
|
1904 |
+
d[0] = clamp(y + m_cbb[cb]);
|
1905 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
1906 |
+
d[2] = clamp(y + m_crr[cr]);
|
1907 |
+
d[3] = 255;
|
1908 |
+
}
|
1909 |
+
else
|
1910 |
+
{
|
1911 |
+
d[0] = clamp(y + m_crr[cr]);
|
1912 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
1913 |
+
d[2] = clamp(y + m_cbb[cb]);
|
1914 |
+
d[3] = 255;
|
1915 |
+
}
|
1916 |
+
d += 4;
|
1917 |
+
}
|
1918 |
+
|
1919 |
+
s += 64*3;
|
1920 |
+
}
|
1921 |
+
}
|
1922 |
+
|
1923 |
+
// YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB
|
1924 |
+
void jpeg_decoder::H2V1Convert()
|
1925 |
+
{
|
1926 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1927 |
+
uint8 *d0 = m_pScan_line_0;
|
1928 |
+
uint8 *y = m_pSample_buf + row * 8;
|
1929 |
+
uint8 *c = m_pSample_buf + 2*64 + row * 8;
|
1930 |
+
|
1931 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1932 |
+
{
|
1933 |
+
for (int l = 0; l < 2; l++)
|
1934 |
+
{
|
1935 |
+
for (int j = 0; j < 4; j++)
|
1936 |
+
{
|
1937 |
+
int cb = c[0];
|
1938 |
+
int cr = c[64];
|
1939 |
+
|
1940 |
+
int rc = m_crr[cr];
|
1941 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
1942 |
+
int bc = m_cbb[cb];
|
1943 |
+
|
1944 |
+
int yy = y[j<<1];
|
1945 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
1946 |
+
{
|
1947 |
+
d0[0] = clamp(yy+bc);
|
1948 |
+
d0[1] = clamp(yy+gc);
|
1949 |
+
d0[2] = clamp(yy+rc);
|
1950 |
+
d0[3] = 255;
|
1951 |
+
yy = y[(j<<1)+1];
|
1952 |
+
d0[4] = clamp(yy+bc);
|
1953 |
+
d0[5] = clamp(yy+gc);
|
1954 |
+
d0[6] = clamp(yy+rc);
|
1955 |
+
d0[7] = 255;
|
1956 |
+
}
|
1957 |
+
else
|
1958 |
+
{
|
1959 |
+
d0[0] = clamp(yy+rc);
|
1960 |
+
d0[1] = clamp(yy+gc);
|
1961 |
+
d0[2] = clamp(yy+bc);
|
1962 |
+
d0[3] = 255;
|
1963 |
+
yy = y[(j<<1)+1];
|
1964 |
+
d0[4] = clamp(yy+rc);
|
1965 |
+
d0[5] = clamp(yy+gc);
|
1966 |
+
d0[6] = clamp(yy+bc);
|
1967 |
+
d0[7] = 255;
|
1968 |
+
}
|
1969 |
+
|
1970 |
+
d0 += 8;
|
1971 |
+
|
1972 |
+
c++;
|
1973 |
+
}
|
1974 |
+
y += 64;
|
1975 |
+
}
|
1976 |
+
|
1977 |
+
y += 64*4 - 64*2;
|
1978 |
+
c += 64*4 - 8;
|
1979 |
+
}
|
1980 |
+
}
|
1981 |
+
|
1982 |
+
// YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB
|
1983 |
+
void jpeg_decoder::H1V2Convert()
|
1984 |
+
{
|
1985 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1986 |
+
uint8 *d0 = m_pScan_line_0;
|
1987 |
+
uint8 *d1 = m_pScan_line_1;
|
1988 |
+
uint8 *y;
|
1989 |
+
uint8 *c;
|
1990 |
+
|
1991 |
+
if (row < 8)
|
1992 |
+
y = m_pSample_buf + row * 8;
|
1993 |
+
else
|
1994 |
+
y = m_pSample_buf + 64*1 + (row & 7) * 8;
|
1995 |
+
|
1996 |
+
c = m_pSample_buf + 64*2 + (row >> 1) * 8;
|
1997 |
+
|
1998 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1999 |
+
{
|
2000 |
+
for (int j = 0; j < 8; j++)
|
2001 |
+
{
|
2002 |
+
int cb = c[0+j];
|
2003 |
+
int cr = c[64+j];
|
2004 |
+
|
2005 |
+
int rc = m_crr[cr];
|
2006 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
2007 |
+
int bc = m_cbb[cb];
|
2008 |
+
|
2009 |
+
int yy = y[j];
|
2010 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2011 |
+
{
|
2012 |
+
d0[0] = clamp(yy+bc);
|
2013 |
+
d0[1] = clamp(yy+gc);
|
2014 |
+
d0[2] = clamp(yy+rc);
|
2015 |
+
d0[3] = 255;
|
2016 |
+
yy = y[8+j];
|
2017 |
+
d1[0] = clamp(yy+bc);
|
2018 |
+
d1[1] = clamp(yy+gc);
|
2019 |
+
d1[2] = clamp(yy+rc);
|
2020 |
+
d1[3] = 255;
|
2021 |
+
}
|
2022 |
+
else
|
2023 |
+
{
|
2024 |
+
d0[0] = clamp(yy+rc);
|
2025 |
+
d0[1] = clamp(yy+gc);
|
2026 |
+
d0[2] = clamp(yy+bc);
|
2027 |
+
d0[3] = 255;
|
2028 |
+
yy = y[8+j];
|
2029 |
+
d1[0] = clamp(yy+rc);
|
2030 |
+
d1[1] = clamp(yy+gc);
|
2031 |
+
d1[2] = clamp(yy+bc);
|
2032 |
+
d1[3] = 255;
|
2033 |
+
}
|
2034 |
+
|
2035 |
+
d0 += 4;
|
2036 |
+
d1 += 4;
|
2037 |
+
}
|
2038 |
+
|
2039 |
+
y += 64*4;
|
2040 |
+
c += 64*4;
|
2041 |
+
}
|
2042 |
+
}
|
2043 |
+
|
2044 |
+
// YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB
|
2045 |
+
void jpeg_decoder::H2V2Convert()
|
2046 |
+
{
|
2047 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2048 |
+
uint8 *d0 = m_pScan_line_0;
|
2049 |
+
uint8 *d1 = m_pScan_line_1;
|
2050 |
+
uint8 *y;
|
2051 |
+
uint8 *c;
|
2052 |
+
|
2053 |
+
if (row < 8)
|
2054 |
+
y = m_pSample_buf + row * 8;
|
2055 |
+
else
|
2056 |
+
y = m_pSample_buf + 64*2 + (row & 7) * 8;
|
2057 |
+
|
2058 |
+
c = m_pSample_buf + 64*4 + (row >> 1) * 8;
|
2059 |
+
|
2060 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2061 |
+
{
|
2062 |
+
for (int l = 0; l < 2; l++)
|
2063 |
+
{
|
2064 |
+
for (int j = 0; j < 8; j += 2)
|
2065 |
+
{
|
2066 |
+
int cb = c[0];
|
2067 |
+
int cr = c[64];
|
2068 |
+
|
2069 |
+
int rc = m_crr[cr];
|
2070 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
2071 |
+
int bc = m_cbb[cb];
|
2072 |
+
|
2073 |
+
int yy = y[j];
|
2074 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2075 |
+
{
|
2076 |
+
d0[0] = clamp(yy+bc);
|
2077 |
+
d0[1] = clamp(yy+gc);
|
2078 |
+
d0[2] = clamp(yy+rc);
|
2079 |
+
d0[3] = 255;
|
2080 |
+
yy = y[j+1];
|
2081 |
+
d0[4] = clamp(yy+bc);
|
2082 |
+
d0[5] = clamp(yy+gc);
|
2083 |
+
d0[6] = clamp(yy+rc);
|
2084 |
+
d0[7] = 255;
|
2085 |
+
yy = y[j+8];
|
2086 |
+
d1[0] = clamp(yy+bc);
|
2087 |
+
d1[1] = clamp(yy+gc);
|
2088 |
+
d1[2] = clamp(yy+rc);
|
2089 |
+
d1[3] = 255;
|
2090 |
+
yy = y[j+8+1];
|
2091 |
+
d1[4] = clamp(yy+bc);
|
2092 |
+
d1[5] = clamp(yy+gc);
|
2093 |
+
d1[6] = clamp(yy+rc);
|
2094 |
+
d1[7] = 255;
|
2095 |
+
}
|
2096 |
+
else
|
2097 |
+
{
|
2098 |
+
d0[0] = clamp(yy+rc);
|
2099 |
+
d0[1] = clamp(yy+gc);
|
2100 |
+
d0[2] = clamp(yy+bc);
|
2101 |
+
d0[3] = 255;
|
2102 |
+
yy = y[j+1];
|
2103 |
+
d0[4] = clamp(yy+rc);
|
2104 |
+
d0[5] = clamp(yy+gc);
|
2105 |
+
d0[6] = clamp(yy+bc);
|
2106 |
+
d0[7] = 255;
|
2107 |
+
yy = y[j+8];
|
2108 |
+
d1[0] = clamp(yy+rc);
|
2109 |
+
d1[1] = clamp(yy+gc);
|
2110 |
+
d1[2] = clamp(yy+bc);
|
2111 |
+
d1[3] = 255;
|
2112 |
+
yy = y[j+8+1];
|
2113 |
+
d1[4] = clamp(yy+rc);
|
2114 |
+
d1[5] = clamp(yy+gc);
|
2115 |
+
d1[6] = clamp(yy+bc);
|
2116 |
+
d1[7] = 255;
|
2117 |
+
}
|
2118 |
+
|
2119 |
+
d0 += 8;
|
2120 |
+
d1 += 8;
|
2121 |
+
|
2122 |
+
c++;
|
2123 |
+
}
|
2124 |
+
y += 64;
|
2125 |
+
}
|
2126 |
+
|
2127 |
+
y += 64*6 - 64*2;
|
2128 |
+
c += 64*6 - 8;
|
2129 |
+
}
|
2130 |
+
}
|
2131 |
+
|
2132 |
+
// Y (1 block per MCU) to 8-bit grayscale
|
2133 |
+
void jpeg_decoder::gray_convert()
|
2134 |
+
{
|
2135 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2136 |
+
uint8 *d = m_pScan_line_0;
|
2137 |
+
uint8 *s = m_pSample_buf + row * 8;
|
2138 |
+
|
2139 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2140 |
+
{
|
2141 |
+
*(uint *)d = *(uint *)s;
|
2142 |
+
*(uint *)(&d[4]) = *(uint *)(&s[4]);
|
2143 |
+
|
2144 |
+
s += 64;
|
2145 |
+
d += 8;
|
2146 |
+
}
|
2147 |
+
}
|
2148 |
+
|
2149 |
+
void jpeg_decoder::expanded_convert()
|
2150 |
+
{
|
2151 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2152 |
+
|
2153 |
+
uint8* Py = m_pSample_buf + (row / 8) * 64 * m_comp_h_samp[0] + (row & 7) * 8;
|
2154 |
+
|
2155 |
+
uint8* d = m_pScan_line_0;
|
2156 |
+
|
2157 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2158 |
+
{
|
2159 |
+
for (int k = 0; k < m_max_mcu_x_size; k += 8)
|
2160 |
+
{
|
2161 |
+
const int Y_ofs = k * 8;
|
2162 |
+
const int Cb_ofs = Y_ofs + 64 * m_expanded_blocks_per_component;
|
2163 |
+
const int Cr_ofs = Y_ofs + 64 * m_expanded_blocks_per_component * 2;
|
2164 |
+
for (int j = 0; j < 8; j++)
|
2165 |
+
{
|
2166 |
+
int y = Py[Y_ofs + j];
|
2167 |
+
int cb = Py[Cb_ofs + j];
|
2168 |
+
int cr = Py[Cr_ofs + j];
|
2169 |
+
|
2170 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2171 |
+
{
|
2172 |
+
d[0] = clamp(y + m_cbb[cb]);
|
2173 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
2174 |
+
d[2] = clamp(y + m_crr[cr]);
|
2175 |
+
d[3] = 255;
|
2176 |
+
}
|
2177 |
+
else
|
2178 |
+
{
|
2179 |
+
d[0] = clamp(y + m_crr[cr]);
|
2180 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
2181 |
+
d[2] = clamp(y + m_cbb[cb]);
|
2182 |
+
d[3] = 255;
|
2183 |
+
}
|
2184 |
+
|
2185 |
+
d += 4;
|
2186 |
+
}
|
2187 |
+
}
|
2188 |
+
|
2189 |
+
Py += 64 * m_expanded_blocks_per_mcu;
|
2190 |
+
}
|
2191 |
+
}
|
2192 |
+
|
2193 |
+
// Find end of image (EOI) marker, so we can return to the user the exact size of the input stream.
|
2194 |
+
void jpeg_decoder::find_eoi()
|
2195 |
+
{
|
2196 |
+
if (!m_progressive_flag)
|
2197 |
+
{
|
2198 |
+
// Attempt to read the EOI marker.
|
2199 |
+
//get_bits_no_markers(m_bits_left & 7);
|
2200 |
+
|
2201 |
+
// Prime the bit buffer
|
2202 |
+
m_bits_left = 16;
|
2203 |
+
get_bits(16);
|
2204 |
+
get_bits(16);
|
2205 |
+
|
2206 |
+
// The next marker _should_ be EOI
|
2207 |
+
process_markers();
|
2208 |
+
}
|
2209 |
+
|
2210 |
+
m_total_bytes_read -= m_in_buf_left;
|
2211 |
+
}
|
2212 |
+
|
2213 |
+
int jpeg_decoder::decode(const void** pScan_line, uint* pScan_line_len)
|
2214 |
+
{
|
2215 |
+
if ((m_error_code) || (!m_ready_flag))
|
2216 |
+
return JPGD_FAILED;
|
2217 |
+
|
2218 |
+
if (m_total_lines_left == 0)
|
2219 |
+
return JPGD_DONE;
|
2220 |
+
|
2221 |
+
if (m_mcu_lines_left == 0)
|
2222 |
+
{
|
2223 |
+
if (setjmp(m_jmp_state))
|
2224 |
+
return JPGD_FAILED;
|
2225 |
+
|
2226 |
+
if (m_progressive_flag)
|
2227 |
+
load_next_row();
|
2228 |
+
else
|
2229 |
+
decode_next_row();
|
2230 |
+
|
2231 |
+
// Find the EOI marker if that was the last row.
|
2232 |
+
if (m_total_lines_left <= m_max_mcu_y_size)
|
2233 |
+
find_eoi();
|
2234 |
+
|
2235 |
+
m_mcu_lines_left = m_max_mcu_y_size;
|
2236 |
+
}
|
2237 |
+
|
2238 |
+
if (m_freq_domain_chroma_upsample)
|
2239 |
+
{
|
2240 |
+
expanded_convert();
|
2241 |
+
*pScan_line = m_pScan_line_0;
|
2242 |
+
}
|
2243 |
+
else
|
2244 |
+
{
|
2245 |
+
switch (m_scan_type)
|
2246 |
+
{
|
2247 |
+
case JPGD_YH2V2:
|
2248 |
+
{
|
2249 |
+
if ((m_mcu_lines_left & 1) == 0)
|
2250 |
+
{
|
2251 |
+
H2V2Convert();
|
2252 |
+
*pScan_line = m_pScan_line_0;
|
2253 |
+
}
|
2254 |
+
else
|
2255 |
+
*pScan_line = m_pScan_line_1;
|
2256 |
+
|
2257 |
+
break;
|
2258 |
+
}
|
2259 |
+
case JPGD_YH2V1:
|
2260 |
+
{
|
2261 |
+
H2V1Convert();
|
2262 |
+
*pScan_line = m_pScan_line_0;
|
2263 |
+
break;
|
2264 |
+
}
|
2265 |
+
case JPGD_YH1V2:
|
2266 |
+
{
|
2267 |
+
if ((m_mcu_lines_left & 1) == 0)
|
2268 |
+
{
|
2269 |
+
H1V2Convert();
|
2270 |
+
*pScan_line = m_pScan_line_0;
|
2271 |
+
}
|
2272 |
+
else
|
2273 |
+
*pScan_line = m_pScan_line_1;
|
2274 |
+
|
2275 |
+
break;
|
2276 |
+
}
|
2277 |
+
case JPGD_YH1V1:
|
2278 |
+
{
|
2279 |
+
H1V1Convert();
|
2280 |
+
*pScan_line = m_pScan_line_0;
|
2281 |
+
break;
|
2282 |
+
}
|
2283 |
+
case JPGD_GRAYSCALE:
|
2284 |
+
{
|
2285 |
+
gray_convert();
|
2286 |
+
*pScan_line = m_pScan_line_0;
|
2287 |
+
|
2288 |
+
break;
|
2289 |
+
}
|
2290 |
+
}
|
2291 |
+
}
|
2292 |
+
|
2293 |
+
*pScan_line_len = m_real_dest_bytes_per_scan_line;
|
2294 |
+
|
2295 |
+
m_mcu_lines_left--;
|
2296 |
+
m_total_lines_left--;
|
2297 |
+
|
2298 |
+
return JPGD_SUCCESS;
|
2299 |
+
}
|
2300 |
+
|
2301 |
+
// Creates the tables needed for efficient Huffman decoding.
|
2302 |
+
void jpeg_decoder::make_huff_table(int index, huff_tables *pH)
|
2303 |
+
{
|
2304 |
+
int p, i, l, si;
|
2305 |
+
uint8 huffsize[257];
|
2306 |
+
uint huffcode[257];
|
2307 |
+
uint code;
|
2308 |
+
uint subtree;
|
2309 |
+
int code_size;
|
2310 |
+
int lastp;
|
2311 |
+
int nextfreeentry;
|
2312 |
+
int currententry;
|
2313 |
+
|
2314 |
+
pH->ac_table = m_huff_ac[index] != 0;
|
2315 |
+
|
2316 |
+
p = 0;
|
2317 |
+
|
2318 |
+
for (l = 1; l <= 16; l++)
|
2319 |
+
{
|
2320 |
+
for (i = 1; i <= m_huff_num[index][l]; i++)
|
2321 |
+
huffsize[p++] = static_cast<uint8>(l);
|
2322 |
+
}
|
2323 |
+
|
2324 |
+
huffsize[p] = 0;
|
2325 |
+
|
2326 |
+
lastp = p;
|
2327 |
+
|
2328 |
+
code = 0;
|
2329 |
+
si = huffsize[0];
|
2330 |
+
p = 0;
|
2331 |
+
|
2332 |
+
while (huffsize[p])
|
2333 |
+
{
|
2334 |
+
while (huffsize[p] == si)
|
2335 |
+
{
|
2336 |
+
huffcode[p++] = code;
|
2337 |
+
code++;
|
2338 |
+
}
|
2339 |
+
|
2340 |
+
code <<= 1;
|
2341 |
+
si++;
|
2342 |
+
}
|
2343 |
+
|
2344 |
+
memset(pH->look_up, 0, sizeof(pH->look_up));
|
2345 |
+
memset(pH->look_up2, 0, sizeof(pH->look_up2));
|
2346 |
+
memset(pH->tree, 0, sizeof(pH->tree));
|
2347 |
+
memset(pH->code_size, 0, sizeof(pH->code_size));
|
2348 |
+
|
2349 |
+
nextfreeentry = -1;
|
2350 |
+
|
2351 |
+
p = 0;
|
2352 |
+
|
2353 |
+
while (p < lastp)
|
2354 |
+
{
|
2355 |
+
i = m_huff_val[index][p];
|
2356 |
+
code = huffcode[p];
|
2357 |
+
code_size = huffsize[p];
|
2358 |
+
|
2359 |
+
pH->code_size[i] = static_cast<uint8>(code_size);
|
2360 |
+
|
2361 |
+
if (code_size <= 8)
|
2362 |
+
{
|
2363 |
+
code <<= (8 - code_size);
|
2364 |
+
|
2365 |
+
for (l = 1 << (8 - code_size); l > 0; l--)
|
2366 |
+
{
|
2367 |
+
JPGD_ASSERT(i < 256);
|
2368 |
+
|
2369 |
+
pH->look_up[code] = i;
|
2370 |
+
|
2371 |
+
bool has_extrabits = false;
|
2372 |
+
int extra_bits = 0;
|
2373 |
+
int num_extra_bits = i & 15;
|
2374 |
+
|
2375 |
+
int bits_to_fetch = code_size;
|
2376 |
+
if (num_extra_bits)
|
2377 |
+
{
|
2378 |
+
int total_codesize = code_size + num_extra_bits;
|
2379 |
+
if (total_codesize <= 8)
|
2380 |
+
{
|
2381 |
+
has_extrabits = true;
|
2382 |
+
extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize));
|
2383 |
+
JPGD_ASSERT(extra_bits <= 0x7FFF);
|
2384 |
+
bits_to_fetch += num_extra_bits;
|
2385 |
+
}
|
2386 |
+
}
|
2387 |
+
|
2388 |
+
if (!has_extrabits)
|
2389 |
+
pH->look_up2[code] = i | (bits_to_fetch << 8);
|
2390 |
+
else
|
2391 |
+
pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8);
|
2392 |
+
|
2393 |
+
code++;
|
2394 |
+
}
|
2395 |
+
}
|
2396 |
+
else
|
2397 |
+
{
|
2398 |
+
subtree = (code >> (code_size - 8)) & 0xFF;
|
2399 |
+
|
2400 |
+
currententry = pH->look_up[subtree];
|
2401 |
+
|
2402 |
+
if (currententry == 0)
|
2403 |
+
{
|
2404 |
+
pH->look_up[subtree] = currententry = nextfreeentry;
|
2405 |
+
pH->look_up2[subtree] = currententry = nextfreeentry;
|
2406 |
+
|
2407 |
+
nextfreeentry -= 2;
|
2408 |
+
}
|
2409 |
+
|
2410 |
+
code <<= (16 - (code_size - 8));
|
2411 |
+
|
2412 |
+
for (l = code_size; l > 9; l--)
|
2413 |
+
{
|
2414 |
+
if ((code & 0x8000) == 0)
|
2415 |
+
currententry--;
|
2416 |
+
|
2417 |
+
if (pH->tree[-currententry - 1] == 0)
|
2418 |
+
{
|
2419 |
+
pH->tree[-currententry - 1] = nextfreeentry;
|
2420 |
+
|
2421 |
+
currententry = nextfreeentry;
|
2422 |
+
|
2423 |
+
nextfreeentry -= 2;
|
2424 |
+
}
|
2425 |
+
else
|
2426 |
+
currententry = pH->tree[-currententry - 1];
|
2427 |
+
|
2428 |
+
code <<= 1;
|
2429 |
+
}
|
2430 |
+
|
2431 |
+
if ((code & 0x8000) == 0)
|
2432 |
+
currententry--;
|
2433 |
+
|
2434 |
+
pH->tree[-currententry - 1] = i;
|
2435 |
+
}
|
2436 |
+
|
2437 |
+
p++;
|
2438 |
+
}
|
2439 |
+
}
|
2440 |
+
|
2441 |
+
// Verifies the quantization tables needed for this scan are available.
|
2442 |
+
void jpeg_decoder::check_quant_tables()
|
2443 |
+
{
|
2444 |
+
for (int i = 0; i < m_comps_in_scan; i++)
|
2445 |
+
if (m_quant[m_comp_quant[m_comp_list[i]]] == NULL)
|
2446 |
+
stop_decoding(JPGD_UNDEFINED_QUANT_TABLE);
|
2447 |
+
}
|
2448 |
+
|
2449 |
+
// Verifies that all the Huffman tables needed for this scan are available.
|
2450 |
+
void jpeg_decoder::check_huff_tables()
|
2451 |
+
{
|
2452 |
+
for (int i = 0; i < m_comps_in_scan; i++)
|
2453 |
+
{
|
2454 |
+
if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == NULL))
|
2455 |
+
stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
|
2456 |
+
|
2457 |
+
if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == NULL))
|
2458 |
+
stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
|
2459 |
+
}
|
2460 |
+
|
2461 |
+
for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++)
|
2462 |
+
if (m_huff_num[i])
|
2463 |
+
{
|
2464 |
+
if (!m_pHuff_tabs[i])
|
2465 |
+
m_pHuff_tabs[i] = (huff_tables *)alloc(sizeof(huff_tables));
|
2466 |
+
|
2467 |
+
make_huff_table(i, m_pHuff_tabs[i]);
|
2468 |
+
}
|
2469 |
+
}
|
2470 |
+
|
2471 |
+
// Determines the component order inside each MCU.
|
2472 |
+
// Also calcs how many MCU's are on each row, etc.
|
2473 |
+
void jpeg_decoder::calc_mcu_block_order()
|
2474 |
+
{
|
2475 |
+
int component_num, component_id;
|
2476 |
+
int max_h_samp = 0, max_v_samp = 0;
|
2477 |
+
|
2478 |
+
for (component_id = 0; component_id < m_comps_in_frame; component_id++)
|
2479 |
+
{
|
2480 |
+
if (m_comp_h_samp[component_id] > max_h_samp)
|
2481 |
+
max_h_samp = m_comp_h_samp[component_id];
|
2482 |
+
|
2483 |
+
if (m_comp_v_samp[component_id] > max_v_samp)
|
2484 |
+
max_v_samp = m_comp_v_samp[component_id];
|
2485 |
+
}
|
2486 |
+
|
2487 |
+
for (component_id = 0; component_id < m_comps_in_frame; component_id++)
|
2488 |
+
{
|
2489 |
+
m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8;
|
2490 |
+
m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8;
|
2491 |
+
}
|
2492 |
+
|
2493 |
+
if (m_comps_in_scan == 1)
|
2494 |
+
{
|
2495 |
+
m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]];
|
2496 |
+
m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]];
|
2497 |
+
}
|
2498 |
+
else
|
2499 |
+
{
|
2500 |
+
m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp;
|
2501 |
+
m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp;
|
2502 |
+
}
|
2503 |
+
|
2504 |
+
if (m_comps_in_scan == 1)
|
2505 |
+
{
|
2506 |
+
m_mcu_org[0] = m_comp_list[0];
|
2507 |
+
|
2508 |
+
m_blocks_per_mcu = 1;
|
2509 |
+
}
|
2510 |
+
else
|
2511 |
+
{
|
2512 |
+
m_blocks_per_mcu = 0;
|
2513 |
+
|
2514 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
2515 |
+
{
|
2516 |
+
int num_blocks;
|
2517 |
+
|
2518 |
+
component_id = m_comp_list[component_num];
|
2519 |
+
|
2520 |
+
num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id];
|
2521 |
+
|
2522 |
+
while (num_blocks--)
|
2523 |
+
m_mcu_org[m_blocks_per_mcu++] = component_id;
|
2524 |
+
}
|
2525 |
+
}
|
2526 |
+
}
|
2527 |
+
|
2528 |
+
// Starts a new scan.
|
2529 |
+
int jpeg_decoder::init_scan()
|
2530 |
+
{
|
2531 |
+
if (!locate_sos_marker())
|
2532 |
+
return JPGD_FALSE;
|
2533 |
+
|
2534 |
+
calc_mcu_block_order();
|
2535 |
+
|
2536 |
+
check_huff_tables();
|
2537 |
+
|
2538 |
+
check_quant_tables();
|
2539 |
+
|
2540 |
+
memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
|
2541 |
+
|
2542 |
+
m_eob_run = 0;
|
2543 |
+
|
2544 |
+
if (m_restart_interval)
|
2545 |
+
{
|
2546 |
+
m_restarts_left = m_restart_interval;
|
2547 |
+
m_next_restart_num = 0;
|
2548 |
+
}
|
2549 |
+
|
2550 |
+
fix_in_buffer();
|
2551 |
+
|
2552 |
+
return JPGD_TRUE;
|
2553 |
+
}
|
2554 |
+
|
2555 |
+
// Starts a frame. Determines if the number of components or sampling factors
|
2556 |
+
// are supported.
|
2557 |
+
void jpeg_decoder::init_frame()
|
2558 |
+
{
|
2559 |
+
int i;
|
2560 |
+
|
2561 |
+
if (m_comps_in_frame == 1)
|
2562 |
+
{
|
2563 |
+
if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1))
|
2564 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2565 |
+
|
2566 |
+
m_scan_type = JPGD_GRAYSCALE;
|
2567 |
+
m_max_blocks_per_mcu = 1;
|
2568 |
+
m_max_mcu_x_size = 8;
|
2569 |
+
m_max_mcu_y_size = 8;
|
2570 |
+
}
|
2571 |
+
else if (m_comps_in_frame == 3)
|
2572 |
+
{
|
2573 |
+
if ( ((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) ||
|
2574 |
+
((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)) )
|
2575 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2576 |
+
|
2577 |
+
if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
|
2578 |
+
{
|
2579 |
+
m_scan_type = JPGD_YH1V1;
|
2580 |
+
|
2581 |
+
m_max_blocks_per_mcu = 3;
|
2582 |
+
m_max_mcu_x_size = 8;
|
2583 |
+
m_max_mcu_y_size = 8;
|
2584 |
+
}
|
2585 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
|
2586 |
+
{
|
2587 |
+
m_scan_type = JPGD_YH2V1;
|
2588 |
+
m_max_blocks_per_mcu = 4;
|
2589 |
+
m_max_mcu_x_size = 16;
|
2590 |
+
m_max_mcu_y_size = 8;
|
2591 |
+
}
|
2592 |
+
else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2))
|
2593 |
+
{
|
2594 |
+
m_scan_type = JPGD_YH1V2;
|
2595 |
+
m_max_blocks_per_mcu = 4;
|
2596 |
+
m_max_mcu_x_size = 8;
|
2597 |
+
m_max_mcu_y_size = 16;
|
2598 |
+
}
|
2599 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
|
2600 |
+
{
|
2601 |
+
m_scan_type = JPGD_YH2V2;
|
2602 |
+
m_max_blocks_per_mcu = 6;
|
2603 |
+
m_max_mcu_x_size = 16;
|
2604 |
+
m_max_mcu_y_size = 16;
|
2605 |
+
}
|
2606 |
+
else
|
2607 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2608 |
+
}
|
2609 |
+
else
|
2610 |
+
stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
|
2611 |
+
|
2612 |
+
m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size;
|
2613 |
+
m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size;
|
2614 |
+
|
2615 |
+
// These values are for the *destination* pixels: after conversion.
|
2616 |
+
if (m_scan_type == JPGD_GRAYSCALE)
|
2617 |
+
m_dest_bytes_per_pixel = 1;
|
2618 |
+
else
|
2619 |
+
m_dest_bytes_per_pixel = 4;
|
2620 |
+
|
2621 |
+
m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel;
|
2622 |
+
|
2623 |
+
m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel);
|
2624 |
+
|
2625 |
+
// Initialize two scan line buffers.
|
2626 |
+
m_pScan_line_0 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
|
2627 |
+
if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2))
|
2628 |
+
m_pScan_line_1 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
|
2629 |
+
|
2630 |
+
m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu;
|
2631 |
+
|
2632 |
+
// Should never happen
|
2633 |
+
if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW)
|
2634 |
+
stop_decoding(JPGD_ASSERTION_ERROR);
|
2635 |
+
|
2636 |
+
// Allocate the coefficient buffer, enough for one MCU
|
2637 |
+
m_pMCU_coefficients = (jpgd_block_t*)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t));
|
2638 |
+
|
2639 |
+
for (i = 0; i < m_max_blocks_per_mcu; i++)
|
2640 |
+
m_mcu_block_max_zag[i] = 64;
|
2641 |
+
|
2642 |
+
m_expanded_blocks_per_component = m_comp_h_samp[0] * m_comp_v_samp[0];
|
2643 |
+
m_expanded_blocks_per_mcu = m_expanded_blocks_per_component * m_comps_in_frame;
|
2644 |
+
m_expanded_blocks_per_row = m_max_mcus_per_row * m_expanded_blocks_per_mcu;
|
2645 |
+
// Freq. domain chroma upsampling is only supported for H2V2 subsampling factor.
|
2646 |
+
// BEGIN EPIC MOD
|
2647 |
+
#if JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING
|
2648 |
+
m_freq_domain_chroma_upsample = (m_expanded_blocks_per_mcu == 4*3);
|
2649 |
+
#else
|
2650 |
+
m_freq_domain_chroma_upsample = 0;
|
2651 |
+
#endif
|
2652 |
+
// END EPIC MOD
|
2653 |
+
|
2654 |
+
if (m_freq_domain_chroma_upsample)
|
2655 |
+
m_pSample_buf = (uint8 *)alloc(m_expanded_blocks_per_row * 64);
|
2656 |
+
else
|
2657 |
+
m_pSample_buf = (uint8 *)alloc(m_max_blocks_per_row * 64);
|
2658 |
+
|
2659 |
+
m_total_lines_left = m_image_y_size;
|
2660 |
+
|
2661 |
+
m_mcu_lines_left = 0;
|
2662 |
+
|
2663 |
+
create_look_ups();
|
2664 |
+
}
|
2665 |
+
|
2666 |
+
// The coeff_buf series of methods originally stored the coefficients
|
2667 |
+
// into a "virtual" file which was located in EMS, XMS, or a disk file. A cache
|
2668 |
+
// was used to make this process more efficient. Now, we can store the entire
|
2669 |
+
// thing in RAM.
|
2670 |
+
jpeg_decoder::coeff_buf* jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y)
|
2671 |
+
{
|
2672 |
+
coeff_buf* cb = (coeff_buf*)alloc(sizeof(coeff_buf));
|
2673 |
+
|
2674 |
+
cb->block_num_x = block_num_x;
|
2675 |
+
cb->block_num_y = block_num_y;
|
2676 |
+
cb->block_len_x = block_len_x;
|
2677 |
+
cb->block_len_y = block_len_y;
|
2678 |
+
cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t);
|
2679 |
+
cb->pData = (uint8 *)alloc(cb->block_size * block_num_x * block_num_y, true);
|
2680 |
+
return cb;
|
2681 |
+
}
|
2682 |
+
|
2683 |
+
inline jpgd_block_t *jpeg_decoder::coeff_buf_getp(coeff_buf *cb, int block_x, int block_y)
|
2684 |
+
{
|
2685 |
+
JPGD_ASSERT((block_x < cb->block_num_x) && (block_y < cb->block_num_y));
|
2686 |
+
return (jpgd_block_t *)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x));
|
2687 |
+
}
|
2688 |
+
|
2689 |
+
// The following methods decode the various types of m_blocks encountered
|
2690 |
+
// in progressively encoded images.
|
2691 |
+
void jpeg_decoder::decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2692 |
+
{
|
2693 |
+
int s, r;
|
2694 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
|
2695 |
+
|
2696 |
+
if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0)
|
2697 |
+
{
|
2698 |
+
r = pD->get_bits_no_markers(s);
|
2699 |
+
s = HUFF_EXTEND(r, s);
|
2700 |
+
}
|
2701 |
+
|
2702 |
+
pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]);
|
2703 |
+
|
2704 |
+
p[0] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
|
2705 |
+
}
|
2706 |
+
|
2707 |
+
void jpeg_decoder::decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2708 |
+
{
|
2709 |
+
if (pD->get_bits_no_markers(1))
|
2710 |
+
{
|
2711 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
|
2712 |
+
|
2713 |
+
p[0] |= (1 << pD->m_successive_low);
|
2714 |
+
}
|
2715 |
+
}
|
2716 |
+
|
2717 |
+
void jpeg_decoder::decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2718 |
+
{
|
2719 |
+
int k, s, r;
|
2720 |
+
|
2721 |
+
if (pD->m_eob_run)
|
2722 |
+
{
|
2723 |
+
pD->m_eob_run--;
|
2724 |
+
return;
|
2725 |
+
}
|
2726 |
+
|
2727 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
|
2728 |
+
|
2729 |
+
for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++)
|
2730 |
+
{
|
2731 |
+
s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
|
2732 |
+
|
2733 |
+
r = s >> 4;
|
2734 |
+
s &= 15;
|
2735 |
+
|
2736 |
+
if (s)
|
2737 |
+
{
|
2738 |
+
if ((k += r) > 63)
|
2739 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2740 |
+
|
2741 |
+
r = pD->get_bits_no_markers(s);
|
2742 |
+
s = HUFF_EXTEND(r, s);
|
2743 |
+
|
2744 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
|
2745 |
+
}
|
2746 |
+
else
|
2747 |
+
{
|
2748 |
+
if (r == 15)
|
2749 |
+
{
|
2750 |
+
if ((k += 15) > 63)
|
2751 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2752 |
+
}
|
2753 |
+
else
|
2754 |
+
{
|
2755 |
+
pD->m_eob_run = 1 << r;
|
2756 |
+
|
2757 |
+
if (r)
|
2758 |
+
pD->m_eob_run += pD->get_bits_no_markers(r);
|
2759 |
+
|
2760 |
+
pD->m_eob_run--;
|
2761 |
+
|
2762 |
+
break;
|
2763 |
+
}
|
2764 |
+
}
|
2765 |
+
}
|
2766 |
+
}
|
2767 |
+
|
2768 |
+
void jpeg_decoder::decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2769 |
+
{
|
2770 |
+
int s, k, r;
|
2771 |
+
int p1 = 1 << pD->m_successive_low;
|
2772 |
+
int m1 = (-1) << pD->m_successive_low;
|
2773 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
|
2774 |
+
|
2775 |
+
k = pD->m_spectral_start;
|
2776 |
+
|
2777 |
+
if (pD->m_eob_run == 0)
|
2778 |
+
{
|
2779 |
+
for ( ; k <= pD->m_spectral_end; k++)
|
2780 |
+
{
|
2781 |
+
s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
|
2782 |
+
|
2783 |
+
r = s >> 4;
|
2784 |
+
s &= 15;
|
2785 |
+
|
2786 |
+
if (s)
|
2787 |
+
{
|
2788 |
+
if (s != 1)
|
2789 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2790 |
+
|
2791 |
+
if (pD->get_bits_no_markers(1))
|
2792 |
+
s = p1;
|
2793 |
+
else
|
2794 |
+
s = m1;
|
2795 |
+
}
|
2796 |
+
else
|
2797 |
+
{
|
2798 |
+
if (r != 15)
|
2799 |
+
{
|
2800 |
+
pD->m_eob_run = 1 << r;
|
2801 |
+
|
2802 |
+
if (r)
|
2803 |
+
pD->m_eob_run += pD->get_bits_no_markers(r);
|
2804 |
+
|
2805 |
+
break;
|
2806 |
+
}
|
2807 |
+
}
|
2808 |
+
|
2809 |
+
do
|
2810 |
+
{
|
2811 |
+
// BEGIN EPIC MOD
|
2812 |
+
JPGD_ASSERT(k < 64);
|
2813 |
+
// END EPIC MOD
|
2814 |
+
|
2815 |
+
jpgd_block_t *this_coef = p + g_ZAG[k];
|
2816 |
+
|
2817 |
+
if (*this_coef != 0)
|
2818 |
+
{
|
2819 |
+
if (pD->get_bits_no_markers(1))
|
2820 |
+
{
|
2821 |
+
if ((*this_coef & p1) == 0)
|
2822 |
+
{
|
2823 |
+
if (*this_coef >= 0)
|
2824 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
|
2825 |
+
else
|
2826 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
|
2827 |
+
}
|
2828 |
+
}
|
2829 |
+
}
|
2830 |
+
else
|
2831 |
+
{
|
2832 |
+
if (--r < 0)
|
2833 |
+
break;
|
2834 |
+
}
|
2835 |
+
|
2836 |
+
k++;
|
2837 |
+
|
2838 |
+
} while (k <= pD->m_spectral_end);
|
2839 |
+
|
2840 |
+
if ((s) && (k < 64))
|
2841 |
+
{
|
2842 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(s);
|
2843 |
+
}
|
2844 |
+
}
|
2845 |
+
}
|
2846 |
+
|
2847 |
+
if (pD->m_eob_run > 0)
|
2848 |
+
{
|
2849 |
+
for ( ; k <= pD->m_spectral_end; k++)
|
2850 |
+
{
|
2851 |
+
// BEGIN EPIC MOD
|
2852 |
+
JPGD_ASSERT(k < 64);
|
2853 |
+
// END EPIC MOD
|
2854 |
+
|
2855 |
+
jpgd_block_t *this_coef = p + g_ZAG[k];
|
2856 |
+
|
2857 |
+
if (*this_coef != 0)
|
2858 |
+
{
|
2859 |
+
if (pD->get_bits_no_markers(1))
|
2860 |
+
{
|
2861 |
+
if ((*this_coef & p1) == 0)
|
2862 |
+
{
|
2863 |
+
if (*this_coef >= 0)
|
2864 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
|
2865 |
+
else
|
2866 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
|
2867 |
+
}
|
2868 |
+
}
|
2869 |
+
}
|
2870 |
+
}
|
2871 |
+
|
2872 |
+
pD->m_eob_run--;
|
2873 |
+
}
|
2874 |
+
}
|
2875 |
+
|
2876 |
+
// Decode a scan in a progressively encoded image.
|
2877 |
+
void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func)
|
2878 |
+
{
|
2879 |
+
int mcu_row, mcu_col, mcu_block;
|
2880 |
+
int block_x_mcu[JPGD_MAX_COMPONENTS], m_block_y_mcu[JPGD_MAX_COMPONENTS];
|
2881 |
+
|
2882 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
2883 |
+
|
2884 |
+
for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++)
|
2885 |
+
{
|
2886 |
+
int component_num, component_id;
|
2887 |
+
|
2888 |
+
memset(block_x_mcu, 0, sizeof(block_x_mcu));
|
2889 |
+
|
2890 |
+
for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
2891 |
+
{
|
2892 |
+
int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
|
2893 |
+
|
2894 |
+
if ((m_restart_interval) && (m_restarts_left == 0))
|
2895 |
+
process_restart();
|
2896 |
+
|
2897 |
+
for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
2898 |
+
{
|
2899 |
+
component_id = m_mcu_org[mcu_block];
|
2900 |
+
|
2901 |
+
decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
2902 |
+
|
2903 |
+
if (m_comps_in_scan == 1)
|
2904 |
+
block_x_mcu[component_id]++;
|
2905 |
+
else
|
2906 |
+
{
|
2907 |
+
if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
|
2908 |
+
{
|
2909 |
+
block_x_mcu_ofs = 0;
|
2910 |
+
|
2911 |
+
if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
|
2912 |
+
{
|
2913 |
+
block_y_mcu_ofs = 0;
|
2914 |
+
block_x_mcu[component_id] += m_comp_h_samp[component_id];
|
2915 |
+
}
|
2916 |
+
}
|
2917 |
+
}
|
2918 |
+
}
|
2919 |
+
|
2920 |
+
m_restarts_left--;
|
2921 |
+
}
|
2922 |
+
|
2923 |
+
if (m_comps_in_scan == 1)
|
2924 |
+
m_block_y_mcu[m_comp_list[0]]++;
|
2925 |
+
else
|
2926 |
+
{
|
2927 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
2928 |
+
{
|
2929 |
+
component_id = m_comp_list[component_num];
|
2930 |
+
m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
|
2931 |
+
}
|
2932 |
+
}
|
2933 |
+
}
|
2934 |
+
}
|
2935 |
+
|
2936 |
+
// Decode a progressively encoded image.
|
2937 |
+
void jpeg_decoder::init_progressive()
|
2938 |
+
{
|
2939 |
+
int i;
|
2940 |
+
|
2941 |
+
if (m_comps_in_frame == 4)
|
2942 |
+
stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
|
2943 |
+
|
2944 |
+
// Allocate the coefficient buffers.
|
2945 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
2946 |
+
{
|
2947 |
+
m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1);
|
2948 |
+
m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8);
|
2949 |
+
}
|
2950 |
+
|
2951 |
+
for ( ; ; )
|
2952 |
+
{
|
2953 |
+
int dc_only_scan, refinement_scan;
|
2954 |
+
pDecode_block_func decode_block_func;
|
2955 |
+
|
2956 |
+
if (!init_scan())
|
2957 |
+
break;
|
2958 |
+
|
2959 |
+
dc_only_scan = (m_spectral_start == 0);
|
2960 |
+
refinement_scan = (m_successive_high != 0);
|
2961 |
+
|
2962 |
+
if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63))
|
2963 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2964 |
+
|
2965 |
+
if (dc_only_scan)
|
2966 |
+
{
|
2967 |
+
if (m_spectral_end)
|
2968 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2969 |
+
}
|
2970 |
+
else if (m_comps_in_scan != 1) /* AC scans can only contain one component */
|
2971 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2972 |
+
|
2973 |
+
if ((refinement_scan) && (m_successive_low != m_successive_high - 1))
|
2974 |
+
stop_decoding(JPGD_BAD_SOS_SUCCESSIVE);
|
2975 |
+
|
2976 |
+
if (dc_only_scan)
|
2977 |
+
{
|
2978 |
+
if (refinement_scan)
|
2979 |
+
decode_block_func = decode_block_dc_refine;
|
2980 |
+
else
|
2981 |
+
decode_block_func = decode_block_dc_first;
|
2982 |
+
}
|
2983 |
+
else
|
2984 |
+
{
|
2985 |
+
if (refinement_scan)
|
2986 |
+
decode_block_func = decode_block_ac_refine;
|
2987 |
+
else
|
2988 |
+
decode_block_func = decode_block_ac_first;
|
2989 |
+
}
|
2990 |
+
|
2991 |
+
decode_scan(decode_block_func);
|
2992 |
+
|
2993 |
+
m_bits_left = 16;
|
2994 |
+
get_bits(16);
|
2995 |
+
get_bits(16);
|
2996 |
+
}
|
2997 |
+
|
2998 |
+
m_comps_in_scan = m_comps_in_frame;
|
2999 |
+
|
3000 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
3001 |
+
m_comp_list[i] = i;
|
3002 |
+
|
3003 |
+
calc_mcu_block_order();
|
3004 |
+
}
|
3005 |
+
|
3006 |
+
void jpeg_decoder::init_sequential()
|
3007 |
+
{
|
3008 |
+
if (!init_scan())
|
3009 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
3010 |
+
}
|
3011 |
+
|
3012 |
+
void jpeg_decoder::decode_start()
|
3013 |
+
{
|
3014 |
+
init_frame();
|
3015 |
+
|
3016 |
+
if (m_progressive_flag)
|
3017 |
+
init_progressive();
|
3018 |
+
else
|
3019 |
+
init_sequential();
|
3020 |
+
}
|
3021 |
+
|
3022 |
+
void jpeg_decoder::decode_init(jpeg_decoder_stream *pStream)
|
3023 |
+
{
|
3024 |
+
init(pStream);
|
3025 |
+
locate_sof_marker();
|
3026 |
+
}
|
3027 |
+
|
3028 |
+
jpeg_decoder::jpeg_decoder(jpeg_decoder_stream *pStream)
|
3029 |
+
{
|
3030 |
+
if (setjmp(m_jmp_state))
|
3031 |
+
return;
|
3032 |
+
decode_init(pStream);
|
3033 |
+
}
|
3034 |
+
|
3035 |
+
int jpeg_decoder::begin_decoding()
|
3036 |
+
{
|
3037 |
+
if (m_ready_flag)
|
3038 |
+
return JPGD_SUCCESS;
|
3039 |
+
|
3040 |
+
if (m_error_code)
|
3041 |
+
return JPGD_FAILED;
|
3042 |
+
|
3043 |
+
if (setjmp(m_jmp_state))
|
3044 |
+
return JPGD_FAILED;
|
3045 |
+
|
3046 |
+
decode_start();
|
3047 |
+
|
3048 |
+
m_ready_flag = true;
|
3049 |
+
|
3050 |
+
return JPGD_SUCCESS;
|
3051 |
+
}
|
3052 |
+
|
3053 |
+
jpeg_decoder::~jpeg_decoder()
|
3054 |
+
{
|
3055 |
+
free_all_blocks();
|
3056 |
+
}
|
3057 |
+
|
3058 |
+
jpeg_decoder_file_stream::jpeg_decoder_file_stream()
|
3059 |
+
{
|
3060 |
+
m_pFile = NULL;
|
3061 |
+
m_eof_flag = false;
|
3062 |
+
m_error_flag = false;
|
3063 |
+
}
|
3064 |
+
|
3065 |
+
void jpeg_decoder_file_stream::close()
|
3066 |
+
{
|
3067 |
+
if (m_pFile)
|
3068 |
+
{
|
3069 |
+
fclose(m_pFile);
|
3070 |
+
m_pFile = NULL;
|
3071 |
+
}
|
3072 |
+
|
3073 |
+
m_eof_flag = false;
|
3074 |
+
m_error_flag = false;
|
3075 |
+
}
|
3076 |
+
|
3077 |
+
jpeg_decoder_file_stream::~jpeg_decoder_file_stream()
|
3078 |
+
{
|
3079 |
+
close();
|
3080 |
+
}
|
3081 |
+
|
3082 |
+
bool jpeg_decoder_file_stream::open(const char *Pfilename)
|
3083 |
+
{
|
3084 |
+
close();
|
3085 |
+
|
3086 |
+
m_eof_flag = false;
|
3087 |
+
m_error_flag = false;
|
3088 |
+
|
3089 |
+
#if defined(_MSC_VER)
|
3090 |
+
m_pFile = NULL;
|
3091 |
+
fopen_s(&m_pFile, Pfilename, "rb");
|
3092 |
+
#else
|
3093 |
+
m_pFile = fopen(Pfilename, "rb");
|
3094 |
+
#endif
|
3095 |
+
return m_pFile != NULL;
|
3096 |
+
}
|
3097 |
+
|
3098 |
+
int jpeg_decoder_file_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
|
3099 |
+
{
|
3100 |
+
if (!m_pFile)
|
3101 |
+
return -1;
|
3102 |
+
|
3103 |
+
if (m_eof_flag)
|
3104 |
+
{
|
3105 |
+
*pEOF_flag = true;
|
3106 |
+
return 0;
|
3107 |
+
}
|
3108 |
+
|
3109 |
+
if (m_error_flag)
|
3110 |
+
return -1;
|
3111 |
+
|
3112 |
+
int bytes_read = static_cast<int>(fread(pBuf, 1, max_bytes_to_read, m_pFile));
|
3113 |
+
if (bytes_read < max_bytes_to_read)
|
3114 |
+
{
|
3115 |
+
if (ferror(m_pFile))
|
3116 |
+
{
|
3117 |
+
m_error_flag = true;
|
3118 |
+
return -1;
|
3119 |
+
}
|
3120 |
+
|
3121 |
+
m_eof_flag = true;
|
3122 |
+
*pEOF_flag = true;
|
3123 |
+
}
|
3124 |
+
|
3125 |
+
return bytes_read;
|
3126 |
+
}
|
3127 |
+
|
3128 |
+
bool jpeg_decoder_mem_stream::open(const uint8 *pSrc_data, uint size)
|
3129 |
+
{
|
3130 |
+
close();
|
3131 |
+
m_pSrc_data = pSrc_data;
|
3132 |
+
m_ofs = 0;
|
3133 |
+
m_size = size;
|
3134 |
+
return true;
|
3135 |
+
}
|
3136 |
+
|
3137 |
+
int jpeg_decoder_mem_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
|
3138 |
+
{
|
3139 |
+
*pEOF_flag = false;
|
3140 |
+
|
3141 |
+
if (!m_pSrc_data)
|
3142 |
+
return -1;
|
3143 |
+
|
3144 |
+
uint bytes_remaining = m_size - m_ofs;
|
3145 |
+
if ((uint)max_bytes_to_read > bytes_remaining)
|
3146 |
+
{
|
3147 |
+
max_bytes_to_read = bytes_remaining;
|
3148 |
+
*pEOF_flag = true;
|
3149 |
+
}
|
3150 |
+
|
3151 |
+
memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read);
|
3152 |
+
m_ofs += max_bytes_to_read;
|
3153 |
+
|
3154 |
+
return max_bytes_to_read;
|
3155 |
+
}
|
3156 |
+
|
3157 |
+
unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps)
|
3158 |
+
{
|
3159 |
+
if (!actual_comps)
|
3160 |
+
return NULL;
|
3161 |
+
*actual_comps = 0;
|
3162 |
+
|
3163 |
+
if ((!pStream) || (!width) || (!height) || (!req_comps))
|
3164 |
+
return NULL;
|
3165 |
+
|
3166 |
+
if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4))
|
3167 |
+
return NULL;
|
3168 |
+
|
3169 |
+
jpeg_decoder decoder(pStream);
|
3170 |
+
if (decoder.get_error_code() != JPGD_SUCCESS)
|
3171 |
+
return NULL;
|
3172 |
+
|
3173 |
+
const int image_width = decoder.get_width(), image_height = decoder.get_height();
|
3174 |
+
*width = image_width;
|
3175 |
+
*height = image_height;
|
3176 |
+
*actual_comps = decoder.get_num_components();
|
3177 |
+
|
3178 |
+
if (decoder.begin_decoding() != JPGD_SUCCESS)
|
3179 |
+
return NULL;
|
3180 |
+
|
3181 |
+
const int dst_bpl = image_width * req_comps;
|
3182 |
+
|
3183 |
+
uint8 *pImage_data = (uint8*)jpgd_malloc(dst_bpl * image_height);
|
3184 |
+
if (!pImage_data)
|
3185 |
+
return NULL;
|
3186 |
+
|
3187 |
+
for (int y = 0; y < image_height; y++)
|
3188 |
+
{
|
3189 |
+
const uint8* pScan_line = 0;
|
3190 |
+
uint scan_line_len;
|
3191 |
+
if (decoder.decode((const void**)&pScan_line, &scan_line_len) != JPGD_SUCCESS)
|
3192 |
+
{
|
3193 |
+
jpgd_free(pImage_data);
|
3194 |
+
return NULL;
|
3195 |
+
}
|
3196 |
+
|
3197 |
+
uint8 *pDst = pImage_data + y * dst_bpl;
|
3198 |
+
|
3199 |
+
if (((req_comps == 4) && (decoder.get_num_components() == 3)) ||
|
3200 |
+
((req_comps == 1) && (decoder.get_num_components() == 1)))
|
3201 |
+
{
|
3202 |
+
memcpy(pDst, pScan_line, dst_bpl);
|
3203 |
+
}
|
3204 |
+
else if (decoder.get_num_components() == 1)
|
3205 |
+
{
|
3206 |
+
if (req_comps == 3)
|
3207 |
+
{
|
3208 |
+
for (int x = 0; x < image_width; x++)
|
3209 |
+
{
|
3210 |
+
uint8 luma = pScan_line[x];
|
3211 |
+
pDst[0] = luma;
|
3212 |
+
pDst[1] = luma;
|
3213 |
+
pDst[2] = luma;
|
3214 |
+
pDst += 3;
|
3215 |
+
}
|
3216 |
+
}
|
3217 |
+
else
|
3218 |
+
{
|
3219 |
+
for (int x = 0; x < image_width; x++)
|
3220 |
+
{
|
3221 |
+
uint8 luma = pScan_line[x];
|
3222 |
+
pDst[0] = luma;
|
3223 |
+
pDst[1] = luma;
|
3224 |
+
pDst[2] = luma;
|
3225 |
+
pDst[3] = 255;
|
3226 |
+
pDst += 4;
|
3227 |
+
}
|
3228 |
+
}
|
3229 |
+
}
|
3230 |
+
else if (decoder.get_num_components() == 3)
|
3231 |
+
{
|
3232 |
+
if (req_comps == 1)
|
3233 |
+
{
|
3234 |
+
const int YR = 19595, YG = 38470, YB = 7471;
|
3235 |
+
for (int x = 0; x < image_width; x++)
|
3236 |
+
{
|
3237 |
+
int r = pScan_line[x*4+0];
|
3238 |
+
int g = pScan_line[x*4+1];
|
3239 |
+
int b = pScan_line[x*4+2];
|
3240 |
+
*pDst++ = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
3241 |
+
}
|
3242 |
+
}
|
3243 |
+
else
|
3244 |
+
{
|
3245 |
+
for (int x = 0; x < image_width; x++)
|
3246 |
+
{
|
3247 |
+
pDst[0] = pScan_line[x*4+0];
|
3248 |
+
pDst[1] = pScan_line[x*4+1];
|
3249 |
+
pDst[2] = pScan_line[x*4+2];
|
3250 |
+
pDst += 3;
|
3251 |
+
}
|
3252 |
+
}
|
3253 |
+
}
|
3254 |
+
}
|
3255 |
+
|
3256 |
+
return pImage_data;
|
3257 |
+
}
|
3258 |
+
|
3259 |
+
// BEGIN EPIC MOD
|
3260 |
+
unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format)
|
3261 |
+
{
|
3262 |
+
jpg_format = (ERGBFormatJPG)format;
|
3263 |
+
// EMD EPIC MOD
|
3264 |
+
jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size);
|
3265 |
+
return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps);
|
3266 |
+
}
|
3267 |
+
|
3268 |
+
unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps)
|
3269 |
+
{
|
3270 |
+
jpgd::jpeg_decoder_file_stream file_stream;
|
3271 |
+
if (!file_stream.open(pSrc_filename))
|
3272 |
+
return NULL;
|
3273 |
+
return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps);
|
3274 |
+
}
|
3275 |
+
|
3276 |
+
} // namespace jpgd
|
crazy_functions/test_project/cpp/libJPG/jpgd.h
ADDED
@@ -0,0 +1,316 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// jpgd.h - C++ class for JPEG decompression.
|
2 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
#ifndef JPEG_DECODER_H
|
4 |
+
#define JPEG_DECODER_H
|
5 |
+
|
6 |
+
#include <stdlib.h>
|
7 |
+
#include <stdio.h>
|
8 |
+
#include <setjmp.h>
|
9 |
+
|
10 |
+
namespace jpgd
|
11 |
+
{
|
12 |
+
typedef unsigned char uint8;
|
13 |
+
typedef signed short int16;
|
14 |
+
typedef unsigned short uint16;
|
15 |
+
typedef unsigned int uint;
|
16 |
+
typedef signed int int32;
|
17 |
+
|
18 |
+
// Loads a JPEG image from a memory buffer or a file.
|
19 |
+
// req_comps can be 1 (grayscale), 3 (RGB), or 4 (RGBA).
|
20 |
+
// On return, width/height will be set to the image's dimensions, and actual_comps will be set to the either 1 (grayscale) or 3 (RGB).
|
21 |
+
// Notes: For more control over where and how the source data is read, see the decompress_jpeg_image_from_stream() function below, or call the jpeg_decoder class directly.
|
22 |
+
// Requesting a 8 or 32bpp image is currently a little faster than 24bpp because the jpeg_decoder class itself currently always unpacks to either 8 or 32bpp.
|
23 |
+
// BEGIN EPIC MOD
|
24 |
+
//unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps);
|
25 |
+
unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format);
|
26 |
+
// END EPIC MOD
|
27 |
+
unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps);
|
28 |
+
|
29 |
+
// Success/failure error codes.
|
30 |
+
enum jpgd_status
|
31 |
+
{
|
32 |
+
JPGD_SUCCESS = 0, JPGD_FAILED = -1, JPGD_DONE = 1,
|
33 |
+
JPGD_BAD_DHT_COUNTS = -256, JPGD_BAD_DHT_INDEX, JPGD_BAD_DHT_MARKER, JPGD_BAD_DQT_MARKER, JPGD_BAD_DQT_TABLE,
|
34 |
+
JPGD_BAD_PRECISION, JPGD_BAD_HEIGHT, JPGD_BAD_WIDTH, JPGD_TOO_MANY_COMPONENTS,
|
35 |
+
JPGD_BAD_SOF_LENGTH, JPGD_BAD_VARIABLE_MARKER, JPGD_BAD_DRI_LENGTH, JPGD_BAD_SOS_LENGTH,
|
36 |
+
JPGD_BAD_SOS_COMP_ID, JPGD_W_EXTRA_BYTES_BEFORE_MARKER, JPGD_NO_ARITHMITIC_SUPPORT, JPGD_UNEXPECTED_MARKER,
|
37 |
+
JPGD_NOT_JPEG, JPGD_UNSUPPORTED_MARKER, JPGD_BAD_DQT_LENGTH, JPGD_TOO_MANY_BLOCKS,
|
38 |
+
JPGD_UNDEFINED_QUANT_TABLE, JPGD_UNDEFINED_HUFF_TABLE, JPGD_NOT_SINGLE_SCAN, JPGD_UNSUPPORTED_COLORSPACE,
|
39 |
+
JPGD_UNSUPPORTED_SAMP_FACTORS, JPGD_DECODE_ERROR, JPGD_BAD_RESTART_MARKER, JPGD_ASSERTION_ERROR,
|
40 |
+
JPGD_BAD_SOS_SPECTRAL, JPGD_BAD_SOS_SUCCESSIVE, JPGD_STREAM_READ, JPGD_NOTENOUGHMEM
|
41 |
+
};
|
42 |
+
|
43 |
+
// Input stream interface.
|
44 |
+
// Derive from this class to read input data from sources other than files or memory. Set m_eof_flag to true when no more data is available.
|
45 |
+
// The decoder is rather greedy: it will keep on calling this method until its internal input buffer is full, or until the EOF flag is set.
|
46 |
+
// It the input stream contains data after the JPEG stream's EOI (end of image) marker it will probably be pulled into the internal buffer.
|
47 |
+
// Call the get_total_bytes_read() method to determine the actual size of the JPEG stream after successful decoding.
|
48 |
+
class jpeg_decoder_stream
|
49 |
+
{
|
50 |
+
public:
|
51 |
+
jpeg_decoder_stream() { }
|
52 |
+
virtual ~jpeg_decoder_stream() { }
|
53 |
+
|
54 |
+
// The read() method is called when the internal input buffer is empty.
|
55 |
+
// Parameters:
|
56 |
+
// pBuf - input buffer
|
57 |
+
// max_bytes_to_read - maximum bytes that can be written to pBuf
|
58 |
+
// pEOF_flag - set this to true if at end of stream (no more bytes remaining)
|
59 |
+
// Returns -1 on error, otherwise return the number of bytes actually written to the buffer (which may be 0).
|
60 |
+
// Notes: This method will be called in a loop until you set *pEOF_flag to true or the internal buffer is full.
|
61 |
+
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag) = 0;
|
62 |
+
};
|
63 |
+
|
64 |
+
// stdio FILE stream class.
|
65 |
+
class jpeg_decoder_file_stream : public jpeg_decoder_stream
|
66 |
+
{
|
67 |
+
jpeg_decoder_file_stream(const jpeg_decoder_file_stream &);
|
68 |
+
jpeg_decoder_file_stream &operator =(const jpeg_decoder_file_stream &);
|
69 |
+
|
70 |
+
FILE *m_pFile;
|
71 |
+
bool m_eof_flag, m_error_flag;
|
72 |
+
|
73 |
+
public:
|
74 |
+
jpeg_decoder_file_stream();
|
75 |
+
virtual ~jpeg_decoder_file_stream();
|
76 |
+
|
77 |
+
bool open(const char *Pfilename);
|
78 |
+
void close();
|
79 |
+
|
80 |
+
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
|
81 |
+
};
|
82 |
+
|
83 |
+
// Memory stream class.
|
84 |
+
class jpeg_decoder_mem_stream : public jpeg_decoder_stream
|
85 |
+
{
|
86 |
+
const uint8 *m_pSrc_data;
|
87 |
+
uint m_ofs, m_size;
|
88 |
+
|
89 |
+
public:
|
90 |
+
jpeg_decoder_mem_stream() : m_pSrc_data(NULL), m_ofs(0), m_size(0) { }
|
91 |
+
jpeg_decoder_mem_stream(const uint8 *pSrc_data, uint size) : m_pSrc_data(pSrc_data), m_ofs(0), m_size(size) { }
|
92 |
+
|
93 |
+
virtual ~jpeg_decoder_mem_stream() { }
|
94 |
+
|
95 |
+
bool open(const uint8 *pSrc_data, uint size);
|
96 |
+
void close() { m_pSrc_data = NULL; m_ofs = 0; m_size = 0; }
|
97 |
+
|
98 |
+
virtual int read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag);
|
99 |
+
};
|
100 |
+
|
101 |
+
// Loads JPEG file from a jpeg_decoder_stream.
|
102 |
+
unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps);
|
103 |
+
|
104 |
+
enum
|
105 |
+
{
|
106 |
+
JPGD_IN_BUF_SIZE = 8192, JPGD_MAX_BLOCKS_PER_MCU = 10, JPGD_MAX_HUFF_TABLES = 8, JPGD_MAX_QUANT_TABLES = 4,
|
107 |
+
JPGD_MAX_COMPONENTS = 4, JPGD_MAX_COMPS_IN_SCAN = 4, JPGD_MAX_BLOCKS_PER_ROW = 8192, JPGD_MAX_HEIGHT = 16384, JPGD_MAX_WIDTH = 16384
|
108 |
+
};
|
109 |
+
|
110 |
+
typedef int16 jpgd_quant_t;
|
111 |
+
typedef int16 jpgd_block_t;
|
112 |
+
|
113 |
+
class jpeg_decoder
|
114 |
+
{
|
115 |
+
public:
|
116 |
+
// Call get_error_code() after constructing to determine if the stream is valid or not. You may call the get_width(), get_height(), etc.
|
117 |
+
// methods after the constructor is called. You may then either destruct the object, or begin decoding the image by calling begin_decoding(), then decode() on each scanline.
|
118 |
+
jpeg_decoder(jpeg_decoder_stream *pStream);
|
119 |
+
|
120 |
+
~jpeg_decoder();
|
121 |
+
|
122 |
+
// Call this method after constructing the object to begin decompression.
|
123 |
+
// If JPGD_SUCCESS is returned you may then call decode() on each scanline.
|
124 |
+
int begin_decoding();
|
125 |
+
|
126 |
+
// Returns the next scan line.
|
127 |
+
// For grayscale images, pScan_line will point to a buffer containing 8-bit pixels (get_bytes_per_pixel() will return 1).
|
128 |
+
// Otherwise, it will always point to a buffer containing 32-bit RGBA pixels (A will always be 255, and get_bytes_per_pixel() will return 4).
|
129 |
+
// Returns JPGD_SUCCESS if a scan line has been returned.
|
130 |
+
// Returns JPGD_DONE if all scan lines have been returned.
|
131 |
+
// Returns JPGD_FAILED if an error occurred. Call get_error_code() for a more info.
|
132 |
+
int decode(const void** pScan_line, uint* pScan_line_len);
|
133 |
+
|
134 |
+
inline jpgd_status get_error_code() const { return m_error_code; }
|
135 |
+
|
136 |
+
inline int get_width() const { return m_image_x_size; }
|
137 |
+
inline int get_height() const { return m_image_y_size; }
|
138 |
+
|
139 |
+
inline int get_num_components() const { return m_comps_in_frame; }
|
140 |
+
|
141 |
+
inline int get_bytes_per_pixel() const { return m_dest_bytes_per_pixel; }
|
142 |
+
inline int get_bytes_per_scan_line() const { return m_image_x_size * get_bytes_per_pixel(); }
|
143 |
+
|
144 |
+
// Returns the total number of bytes actually consumed by the decoder (which should equal the actual size of the JPEG file).
|
145 |
+
inline int get_total_bytes_read() const { return m_total_bytes_read; }
|
146 |
+
|
147 |
+
private:
|
148 |
+
jpeg_decoder(const jpeg_decoder &);
|
149 |
+
jpeg_decoder &operator =(const jpeg_decoder &);
|
150 |
+
|
151 |
+
typedef void (*pDecode_block_func)(jpeg_decoder *, int, int, int);
|
152 |
+
|
153 |
+
struct huff_tables
|
154 |
+
{
|
155 |
+
bool ac_table;
|
156 |
+
uint look_up[256];
|
157 |
+
uint look_up2[256];
|
158 |
+
uint8 code_size[256];
|
159 |
+
uint tree[512];
|
160 |
+
};
|
161 |
+
|
162 |
+
struct coeff_buf
|
163 |
+
{
|
164 |
+
uint8 *pData;
|
165 |
+
int block_num_x, block_num_y;
|
166 |
+
int block_len_x, block_len_y;
|
167 |
+
int block_size;
|
168 |
+
};
|
169 |
+
|
170 |
+
struct mem_block
|
171 |
+
{
|
172 |
+
mem_block *m_pNext;
|
173 |
+
size_t m_used_count;
|
174 |
+
size_t m_size;
|
175 |
+
char m_data[1];
|
176 |
+
};
|
177 |
+
|
178 |
+
jmp_buf m_jmp_state;
|
179 |
+
mem_block *m_pMem_blocks;
|
180 |
+
int m_image_x_size;
|
181 |
+
int m_image_y_size;
|
182 |
+
jpeg_decoder_stream *m_pStream;
|
183 |
+
int m_progressive_flag;
|
184 |
+
uint8 m_huff_ac[JPGD_MAX_HUFF_TABLES];
|
185 |
+
uint8* m_huff_num[JPGD_MAX_HUFF_TABLES]; // pointer to number of Huffman codes per bit size
|
186 |
+
uint8* m_huff_val[JPGD_MAX_HUFF_TABLES]; // pointer to Huffman codes per bit size
|
187 |
+
jpgd_quant_t* m_quant[JPGD_MAX_QUANT_TABLES]; // pointer to quantization tables
|
188 |
+
int m_scan_type; // Gray, Yh1v1, Yh1v2, Yh2v1, Yh2v2 (CMYK111, CMYK4114 no longer supported)
|
189 |
+
int m_comps_in_frame; // # of components in frame
|
190 |
+
int m_comp_h_samp[JPGD_MAX_COMPONENTS]; // component's horizontal sampling factor
|
191 |
+
int m_comp_v_samp[JPGD_MAX_COMPONENTS]; // component's vertical sampling factor
|
192 |
+
int m_comp_quant[JPGD_MAX_COMPONENTS]; // component's quantization table selector
|
193 |
+
int m_comp_ident[JPGD_MAX_COMPONENTS]; // component's ID
|
194 |
+
int m_comp_h_blocks[JPGD_MAX_COMPONENTS];
|
195 |
+
int m_comp_v_blocks[JPGD_MAX_COMPONENTS];
|
196 |
+
int m_comps_in_scan; // # of components in scan
|
197 |
+
int m_comp_list[JPGD_MAX_COMPS_IN_SCAN]; // components in this scan
|
198 |
+
int m_comp_dc_tab[JPGD_MAX_COMPONENTS]; // component's DC Huffman coding table selector
|
199 |
+
int m_comp_ac_tab[JPGD_MAX_COMPONENTS]; // component's AC Huffman coding table selector
|
200 |
+
int m_spectral_start; // spectral selection start
|
201 |
+
int m_spectral_end; // spectral selection end
|
202 |
+
int m_successive_low; // successive approximation low
|
203 |
+
int m_successive_high; // successive approximation high
|
204 |
+
int m_max_mcu_x_size; // MCU's max. X size in pixels
|
205 |
+
int m_max_mcu_y_size; // MCU's max. Y size in pixels
|
206 |
+
int m_blocks_per_mcu;
|
207 |
+
int m_max_blocks_per_row;
|
208 |
+
int m_mcus_per_row, m_mcus_per_col;
|
209 |
+
int m_mcu_org[JPGD_MAX_BLOCKS_PER_MCU];
|
210 |
+
int m_total_lines_left; // total # lines left in image
|
211 |
+
int m_mcu_lines_left; // total # lines left in this MCU
|
212 |
+
int m_real_dest_bytes_per_scan_line;
|
213 |
+
int m_dest_bytes_per_scan_line; // rounded up
|
214 |
+
int m_dest_bytes_per_pixel; // 4 (RGB) or 1 (Y)
|
215 |
+
huff_tables* m_pHuff_tabs[JPGD_MAX_HUFF_TABLES];
|
216 |
+
coeff_buf* m_dc_coeffs[JPGD_MAX_COMPONENTS];
|
217 |
+
coeff_buf* m_ac_coeffs[JPGD_MAX_COMPONENTS];
|
218 |
+
int m_eob_run;
|
219 |
+
int m_block_y_mcu[JPGD_MAX_COMPONENTS];
|
220 |
+
uint8* m_pIn_buf_ofs;
|
221 |
+
int m_in_buf_left;
|
222 |
+
int m_tem_flag;
|
223 |
+
bool m_eof_flag;
|
224 |
+
uint8 m_in_buf_pad_start[128];
|
225 |
+
uint8 m_in_buf[JPGD_IN_BUF_SIZE + 128];
|
226 |
+
uint8 m_in_buf_pad_end[128];
|
227 |
+
int m_bits_left;
|
228 |
+
uint m_bit_buf;
|
229 |
+
int m_restart_interval;
|
230 |
+
int m_restarts_left;
|
231 |
+
int m_next_restart_num;
|
232 |
+
int m_max_mcus_per_row;
|
233 |
+
int m_max_blocks_per_mcu;
|
234 |
+
int m_expanded_blocks_per_mcu;
|
235 |
+
int m_expanded_blocks_per_row;
|
236 |
+
int m_expanded_blocks_per_component;
|
237 |
+
bool m_freq_domain_chroma_upsample;
|
238 |
+
int m_max_mcus_per_col;
|
239 |
+
uint m_last_dc_val[JPGD_MAX_COMPONENTS];
|
240 |
+
jpgd_block_t* m_pMCU_coefficients;
|
241 |
+
int m_mcu_block_max_zag[JPGD_MAX_BLOCKS_PER_MCU];
|
242 |
+
uint8* m_pSample_buf;
|
243 |
+
int m_crr[256];
|
244 |
+
int m_cbb[256];
|
245 |
+
int m_crg[256];
|
246 |
+
int m_cbg[256];
|
247 |
+
uint8* m_pScan_line_0;
|
248 |
+
uint8* m_pScan_line_1;
|
249 |
+
jpgd_status m_error_code;
|
250 |
+
bool m_ready_flag;
|
251 |
+
int m_total_bytes_read;
|
252 |
+
|
253 |
+
void free_all_blocks();
|
254 |
+
// BEGIN EPIC MOD
|
255 |
+
UE_NORETURN void stop_decoding(jpgd_status status);
|
256 |
+
// END EPIC MOD
|
257 |
+
void *alloc(size_t n, bool zero = false);
|
258 |
+
void word_clear(void *p, uint16 c, uint n);
|
259 |
+
void prep_in_buffer();
|
260 |
+
void read_dht_marker();
|
261 |
+
void read_dqt_marker();
|
262 |
+
void read_sof_marker();
|
263 |
+
void skip_variable_marker();
|
264 |
+
void read_dri_marker();
|
265 |
+
void read_sos_marker();
|
266 |
+
int next_marker();
|
267 |
+
int process_markers();
|
268 |
+
void locate_soi_marker();
|
269 |
+
void locate_sof_marker();
|
270 |
+
int locate_sos_marker();
|
271 |
+
void init(jpeg_decoder_stream * pStream);
|
272 |
+
void create_look_ups();
|
273 |
+
void fix_in_buffer();
|
274 |
+
void transform_mcu(int mcu_row);
|
275 |
+
void transform_mcu_expand(int mcu_row);
|
276 |
+
coeff_buf* coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y);
|
277 |
+
inline jpgd_block_t *coeff_buf_getp(coeff_buf *cb, int block_x, int block_y);
|
278 |
+
void load_next_row();
|
279 |
+
void decode_next_row();
|
280 |
+
void make_huff_table(int index, huff_tables *pH);
|
281 |
+
void check_quant_tables();
|
282 |
+
void check_huff_tables();
|
283 |
+
void calc_mcu_block_order();
|
284 |
+
int init_scan();
|
285 |
+
void init_frame();
|
286 |
+
void process_restart();
|
287 |
+
void decode_scan(pDecode_block_func decode_block_func);
|
288 |
+
void init_progressive();
|
289 |
+
void init_sequential();
|
290 |
+
void decode_start();
|
291 |
+
void decode_init(jpeg_decoder_stream * pStream);
|
292 |
+
void H2V2Convert();
|
293 |
+
void H2V1Convert();
|
294 |
+
void H1V2Convert();
|
295 |
+
void H1V1Convert();
|
296 |
+
void gray_convert();
|
297 |
+
void expanded_convert();
|
298 |
+
void find_eoi();
|
299 |
+
inline uint get_char();
|
300 |
+
inline uint get_char(bool *pPadding_flag);
|
301 |
+
inline void stuff_char(uint8 q);
|
302 |
+
inline uint8 get_octet();
|
303 |
+
inline uint get_bits(int num_bits);
|
304 |
+
inline uint get_bits_no_markers(int numbits);
|
305 |
+
inline int huff_decode(huff_tables *pH);
|
306 |
+
inline int huff_decode(huff_tables *pH, int& extrabits);
|
307 |
+
static inline uint8 clamp(int i);
|
308 |
+
static void decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
309 |
+
static void decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
310 |
+
static void decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
311 |
+
static void decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y);
|
312 |
+
};
|
313 |
+
|
314 |
+
} // namespace jpgd
|
315 |
+
|
316 |
+
#endif // JPEG_DECODER_H
|
crazy_functions/test_project/cpp/libJPG/jpge.cpp
ADDED
@@ -0,0 +1,1049 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// jpge.cpp - C++ class for JPEG compression.
|
2 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
// v1.01, Dec. 18, 2010 - Initial release
|
4 |
+
// v1.02, Apr. 6, 2011 - Removed 2x2 ordered dither in H2V1 chroma subsampling method load_block_16_8_8(). (The rounding factor was 2, when it should have been 1. Either way, it wasn't helping.)
|
5 |
+
// v1.03, Apr. 16, 2011 - Added support for optimized Huffman code tables, optimized dynamic memory allocation down to only 1 alloc.
|
6 |
+
// Also from Alex Evans: Added RGBA support, linear memory allocator (no longer needed in v1.03).
|
7 |
+
// v1.04, May. 19, 2012: Forgot to set m_pFile ptr to NULL in cfile_stream::close(). Thanks to Owen Kaluza for reporting this bug.
|
8 |
+
// Code tweaks to fix VS2008 static code analysis warnings (all looked harmless).
|
9 |
+
// Code review revealed method load_block_16_8_8() (used for the non-default H2V1 sampling mode to downsample chroma) somehow didn't get the rounding factor fix from v1.02.
|
10 |
+
|
11 |
+
#include "jpge.h"
|
12 |
+
|
13 |
+
#include <stdlib.h>
|
14 |
+
#include <string.h>
|
15 |
+
#if PLATFORM_WINDOWS
|
16 |
+
#include <malloc.h>
|
17 |
+
#endif
|
18 |
+
|
19 |
+
#define JPGE_MAX(a,b) (((a)>(b))?(a):(b))
|
20 |
+
#define JPGE_MIN(a,b) (((a)<(b))?(a):(b))
|
21 |
+
|
22 |
+
namespace jpge {
|
23 |
+
|
24 |
+
static inline void *jpge_malloc(size_t nSize) { return FMemory::Malloc(nSize); }
|
25 |
+
static inline void jpge_free(void *p) { FMemory::Free(p);; }
|
26 |
+
|
27 |
+
// Various JPEG enums and tables.
|
28 |
+
enum { M_SOF0 = 0xC0, M_DHT = 0xC4, M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_APP0 = 0xE0 };
|
29 |
+
enum { DC_LUM_CODES = 12, AC_LUM_CODES = 256, DC_CHROMA_CODES = 12, AC_CHROMA_CODES = 256, MAX_HUFF_SYMBOLS = 257, MAX_HUFF_CODESIZE = 32 };
|
30 |
+
|
31 |
+
static uint8 s_zag[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 };
|
32 |
+
static int16 s_std_lum_quant[64] = { 16,11,12,14,12,10,16,14,13,14,18,17,16,19,24,40,26,24,22,22,24,49,35,37,29,40,58,51,61,60,57,51,56,55,64,72,92,78,64,68,87,69,55,56,80,109,81,87,95,98,103,104,103,62,77,113,121,112,100,120,92,101,103,99 };
|
33 |
+
static int16 s_std_croma_quant[64] = { 17,18,18,24,21,24,47,26,26,47,99,66,56,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99 };
|
34 |
+
static uint8 s_dc_lum_bits[17] = { 0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0 };
|
35 |
+
static uint8 s_dc_lum_val[DC_LUM_CODES] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
|
36 |
+
static uint8 s_ac_lum_bits[17] = { 0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d };
|
37 |
+
static uint8 s_ac_lum_val[AC_LUM_CODES] =
|
38 |
+
{
|
39 |
+
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
|
40 |
+
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
|
41 |
+
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
|
42 |
+
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
|
43 |
+
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
|
44 |
+
0xf9,0xfa
|
45 |
+
};
|
46 |
+
static uint8 s_dc_chroma_bits[17] = { 0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 };
|
47 |
+
static uint8 s_dc_chroma_val[DC_CHROMA_CODES] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
|
48 |
+
static uint8 s_ac_chroma_bits[17] = { 0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77 };
|
49 |
+
static uint8 s_ac_chroma_val[AC_CHROMA_CODES] =
|
50 |
+
{
|
51 |
+
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
|
52 |
+
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
|
53 |
+
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
|
54 |
+
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
|
55 |
+
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
|
56 |
+
0xf9,0xfa
|
57 |
+
};
|
58 |
+
|
59 |
+
// Low-level helper functions.
|
60 |
+
template <class T> inline void clear_obj(T &obj) { memset(&obj, 0, sizeof(obj)); }
|
61 |
+
|
62 |
+
const int YR = 19595, YG = 38470, YB = 7471, CB_R = -11059, CB_G = -21709, CB_B = 32768, CR_R = 32768, CR_G = -27439, CR_B = -5329;
|
63 |
+
static inline uint8 clamp(int i) { if (static_cast<uint>(i) > 255U) { if (i < 0) i = 0; else if (i > 255) i = 255; } return static_cast<uint8>(i); }
|
64 |
+
|
65 |
+
static void RGB_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
66 |
+
{
|
67 |
+
for ( ; num_pixels; pDst += 3, pSrc += 3, num_pixels--)
|
68 |
+
{
|
69 |
+
const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
|
70 |
+
pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
71 |
+
pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
|
72 |
+
pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
|
73 |
+
}
|
74 |
+
}
|
75 |
+
|
76 |
+
static void RGB_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
77 |
+
{
|
78 |
+
for ( ; num_pixels; pDst++, pSrc += 3, num_pixels--)
|
79 |
+
pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
|
80 |
+
}
|
81 |
+
|
82 |
+
static void RGBA_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
83 |
+
{
|
84 |
+
for ( ; num_pixels; pDst += 3, pSrc += 4, num_pixels--)
|
85 |
+
{
|
86 |
+
const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
|
87 |
+
pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
88 |
+
pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
|
89 |
+
pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
|
90 |
+
}
|
91 |
+
}
|
92 |
+
|
93 |
+
static void RGBA_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
94 |
+
{
|
95 |
+
for ( ; num_pixels; pDst++, pSrc += 4, num_pixels--)
|
96 |
+
pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
|
97 |
+
}
|
98 |
+
|
99 |
+
static void Y_to_YCC(uint8* pDst, const uint8* pSrc, int num_pixels)
|
100 |
+
{
|
101 |
+
for( ; num_pixels; pDst += 3, pSrc++, num_pixels--) { pDst[0] = pSrc[0]; pDst[1] = 128; pDst[2] = 128; }
|
102 |
+
}
|
103 |
+
|
104 |
+
// Forward DCT - DCT derived from jfdctint.
|
105 |
+
#define CONST_BITS 13
|
106 |
+
#define ROW_BITS 2
|
107 |
+
#define DCT_DESCALE(x, n) (((x) + (((int32)1) << ((n) - 1))) >> (n))
|
108 |
+
#define DCT_MUL(var, c) (static_cast<int16>(var) * static_cast<int32>(c))
|
109 |
+
#define DCT1D(s0, s1, s2, s3, s4, s5, s6, s7) \
|
110 |
+
int32 t0 = s0 + s7, t7 = s0 - s7, t1 = s1 + s6, t6 = s1 - s6, t2 = s2 + s5, t5 = s2 - s5, t3 = s3 + s4, t4 = s3 - s4; \
|
111 |
+
int32 t10 = t0 + t3, t13 = t0 - t3, t11 = t1 + t2, t12 = t1 - t2; \
|
112 |
+
int32 u1 = DCT_MUL(t12 + t13, 4433); \
|
113 |
+
s2 = u1 + DCT_MUL(t13, 6270); \
|
114 |
+
s6 = u1 + DCT_MUL(t12, -15137); \
|
115 |
+
u1 = t4 + t7; \
|
116 |
+
int32 u2 = t5 + t6, u3 = t4 + t6, u4 = t5 + t7; \
|
117 |
+
int32 z5 = DCT_MUL(u3 + u4, 9633); \
|
118 |
+
t4 = DCT_MUL(t4, 2446); t5 = DCT_MUL(t5, 16819); \
|
119 |
+
t6 = DCT_MUL(t6, 25172); t7 = DCT_MUL(t7, 12299); \
|
120 |
+
u1 = DCT_MUL(u1, -7373); u2 = DCT_MUL(u2, -20995); \
|
121 |
+
u3 = DCT_MUL(u3, -16069); u4 = DCT_MUL(u4, -3196); \
|
122 |
+
u3 += z5; u4 += z5; \
|
123 |
+
s0 = t10 + t11; s1 = t7 + u1 + u4; s3 = t6 + u2 + u3; s4 = t10 - t11; s5 = t5 + u2 + u4; s7 = t4 + u1 + u3;
|
124 |
+
|
125 |
+
static void DCT2D(int32 *p)
|
126 |
+
{
|
127 |
+
int32 c, *q = p;
|
128 |
+
for (c = 7; c >= 0; c--, q += 8)
|
129 |
+
{
|
130 |
+
int32 s0 = q[0], s1 = q[1], s2 = q[2], s3 = q[3], s4 = q[4], s5 = q[5], s6 = q[6], s7 = q[7];
|
131 |
+
DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
|
132 |
+
q[0] = s0 << ROW_BITS; q[1] = DCT_DESCALE(s1, CONST_BITS-ROW_BITS); q[2] = DCT_DESCALE(s2, CONST_BITS-ROW_BITS); q[3] = DCT_DESCALE(s3, CONST_BITS-ROW_BITS);
|
133 |
+
q[4] = s4 << ROW_BITS; q[5] = DCT_DESCALE(s5, CONST_BITS-ROW_BITS); q[6] = DCT_DESCALE(s6, CONST_BITS-ROW_BITS); q[7] = DCT_DESCALE(s7, CONST_BITS-ROW_BITS);
|
134 |
+
}
|
135 |
+
for (q = p, c = 7; c >= 0; c--, q++)
|
136 |
+
{
|
137 |
+
int32 s0 = q[0*8], s1 = q[1*8], s2 = q[2*8], s3 = q[3*8], s4 = q[4*8], s5 = q[5*8], s6 = q[6*8], s7 = q[7*8];
|
138 |
+
DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
|
139 |
+
q[0*8] = DCT_DESCALE(s0, ROW_BITS+3); q[1*8] = DCT_DESCALE(s1, CONST_BITS+ROW_BITS+3); q[2*8] = DCT_DESCALE(s2, CONST_BITS+ROW_BITS+3); q[3*8] = DCT_DESCALE(s3, CONST_BITS+ROW_BITS+3);
|
140 |
+
q[4*8] = DCT_DESCALE(s4, ROW_BITS+3); q[5*8] = DCT_DESCALE(s5, CONST_BITS+ROW_BITS+3); q[6*8] = DCT_DESCALE(s6, CONST_BITS+ROW_BITS+3); q[7*8] = DCT_DESCALE(s7, CONST_BITS+ROW_BITS+3);
|
141 |
+
}
|
142 |
+
}
|
143 |
+
|
144 |
+
struct sym_freq { uint m_key, m_sym_index; };
|
145 |
+
|
146 |
+
// Radix sorts sym_freq[] array by 32-bit key m_key. Returns ptr to sorted values.
|
147 |
+
static inline sym_freq* radix_sort_syms(uint num_syms, sym_freq* pSyms0, sym_freq* pSyms1)
|
148 |
+
{
|
149 |
+
const uint cMaxPasses = 4;
|
150 |
+
uint32 hist[256 * cMaxPasses]; clear_obj(hist);
|
151 |
+
for (uint i = 0; i < num_syms; i++) { uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; hist[256*2 + ((freq >> 16) & 0xFF)]++; hist[256*3 + ((freq >> 24) & 0xFF)]++; }
|
152 |
+
sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1;
|
153 |
+
uint total_passes = cMaxPasses; while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
|
154 |
+
for (uint pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
|
155 |
+
{
|
156 |
+
const uint32* pHist = &hist[pass << 8];
|
157 |
+
uint offsets[256], cur_ofs = 0;
|
158 |
+
for (uint i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
|
159 |
+
for (uint i = 0; i < num_syms; i++)
|
160 |
+
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
|
161 |
+
sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t;
|
162 |
+
}
|
163 |
+
return pCur_syms;
|
164 |
+
}
|
165 |
+
|
166 |
+
// calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
|
167 |
+
static void calculate_minimum_redundancy(sym_freq *A, int n)
|
168 |
+
{
|
169 |
+
int root, leaf, next, avbl, used, dpth;
|
170 |
+
if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
|
171 |
+
A[0].m_key += A[1].m_key; root = 0; leaf = 2;
|
172 |
+
for (next=1; next < n-1; next++)
|
173 |
+
{
|
174 |
+
if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = next; } else A[next].m_key = A[leaf++].m_key;
|
175 |
+
if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key += A[root].m_key; A[root++].m_key = next; } else A[next].m_key += A[leaf++].m_key;
|
176 |
+
}
|
177 |
+
A[n-2].m_key = 0;
|
178 |
+
for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
|
179 |
+
avbl = 1; used = dpth = 0; root = n-2; next = n-1;
|
180 |
+
while (avbl>0)
|
181 |
+
{
|
182 |
+
while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
|
183 |
+
while (avbl>used) { A[next--].m_key = dpth; avbl--; }
|
184 |
+
avbl = 2*used; dpth++; used = 0;
|
185 |
+
}
|
186 |
+
}
|
187 |
+
|
188 |
+
// Limits canonical Huffman code table's max code size to max_code_size.
|
189 |
+
static void huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
|
190 |
+
{
|
191 |
+
if (code_list_len <= 1) return;
|
192 |
+
|
193 |
+
for (int i = max_code_size + 1; i <= MAX_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
|
194 |
+
|
195 |
+
uint32 total = 0;
|
196 |
+
for (int i = max_code_size; i > 0; i--)
|
197 |
+
total += (((uint32)pNum_codes[i]) << (max_code_size - i));
|
198 |
+
|
199 |
+
while (total != (1UL << max_code_size))
|
200 |
+
{
|
201 |
+
pNum_codes[max_code_size]--;
|
202 |
+
for (int i = max_code_size - 1; i > 0; i--)
|
203 |
+
{
|
204 |
+
if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
|
205 |
+
}
|
206 |
+
total--;
|
207 |
+
}
|
208 |
+
}
|
209 |
+
|
210 |
+
// Generates an optimized offman table.
|
211 |
+
void jpeg_encoder::optimize_huffman_table(int table_num, int table_len)
|
212 |
+
{
|
213 |
+
sym_freq syms0[MAX_HUFF_SYMBOLS], syms1[MAX_HUFF_SYMBOLS];
|
214 |
+
syms0[0].m_key = 1; syms0[0].m_sym_index = 0; // dummy symbol, assures that no valid code contains all 1's
|
215 |
+
int num_used_syms = 1;
|
216 |
+
const uint32 *pSym_count = &m_huff_count[table_num][0];
|
217 |
+
for (int i = 0; i < table_len; i++)
|
218 |
+
if (pSym_count[i]) { syms0[num_used_syms].m_key = pSym_count[i]; syms0[num_used_syms++].m_sym_index = i + 1; }
|
219 |
+
sym_freq* pSyms = radix_sort_syms(num_used_syms, syms0, syms1);
|
220 |
+
calculate_minimum_redundancy(pSyms, num_used_syms);
|
221 |
+
|
222 |
+
// Count the # of symbols of each code size.
|
223 |
+
int num_codes[1 + MAX_HUFF_CODESIZE]; clear_obj(num_codes);
|
224 |
+
for (int i = 0; i < num_used_syms; i++)
|
225 |
+
num_codes[pSyms[i].m_key]++;
|
226 |
+
|
227 |
+
const uint JPGE_CODE_SIZE_LIMIT = 16; // the maximum possible size of a JPEG Huffman code (valid range is [9,16] - 9 vs. 8 because of the dummy symbol)
|
228 |
+
huffman_enforce_max_code_size(num_codes, num_used_syms, JPGE_CODE_SIZE_LIMIT);
|
229 |
+
|
230 |
+
// Compute m_huff_bits array, which contains the # of symbols per code size.
|
231 |
+
clear_obj(m_huff_bits[table_num]);
|
232 |
+
for (int i = 1; i <= (int)JPGE_CODE_SIZE_LIMIT; i++)
|
233 |
+
m_huff_bits[table_num][i] = static_cast<uint8>(num_codes[i]);
|
234 |
+
|
235 |
+
// Remove the dummy symbol added above, which must be in largest bucket.
|
236 |
+
for (int i = JPGE_CODE_SIZE_LIMIT; i >= 1; i--)
|
237 |
+
{
|
238 |
+
if (m_huff_bits[table_num][i]) { m_huff_bits[table_num][i]--; break; }
|
239 |
+
}
|
240 |
+
|
241 |
+
// Compute the m_huff_val array, which contains the symbol indices sorted by code size (smallest to largest).
|
242 |
+
for (int i = num_used_syms - 1; i >= 1; i--)
|
243 |
+
m_huff_val[table_num][num_used_syms - 1 - i] = static_cast<uint8>(pSyms[i].m_sym_index - 1);
|
244 |
+
}
|
245 |
+
|
246 |
+
// JPEG marker generation.
|
247 |
+
void jpeg_encoder::emit_byte(uint8 i)
|
248 |
+
{
|
249 |
+
m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_obj(i);
|
250 |
+
}
|
251 |
+
|
252 |
+
void jpeg_encoder::emit_word(uint i)
|
253 |
+
{
|
254 |
+
emit_byte(uint8(i >> 8)); emit_byte(uint8(i & 0xFF));
|
255 |
+
}
|
256 |
+
|
257 |
+
void jpeg_encoder::emit_marker(int marker)
|
258 |
+
{
|
259 |
+
emit_byte(uint8(0xFF)); emit_byte(uint8(marker));
|
260 |
+
}
|
261 |
+
|
262 |
+
// Emit JFIF marker
|
263 |
+
void jpeg_encoder::emit_jfif_app0()
|
264 |
+
{
|
265 |
+
emit_marker(M_APP0);
|
266 |
+
emit_word(2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1);
|
267 |
+
emit_byte(0x4A); emit_byte(0x46); emit_byte(0x49); emit_byte(0x46); /* Identifier: ASCII "JFIF" */
|
268 |
+
emit_byte(0);
|
269 |
+
emit_byte(1); /* Major version */
|
270 |
+
emit_byte(1); /* Minor version */
|
271 |
+
emit_byte(0); /* Density unit */
|
272 |
+
emit_word(1);
|
273 |
+
emit_word(1);
|
274 |
+
emit_byte(0); /* No thumbnail image */
|
275 |
+
emit_byte(0);
|
276 |
+
}
|
277 |
+
|
278 |
+
// Emit quantization tables
|
279 |
+
void jpeg_encoder::emit_dqt()
|
280 |
+
{
|
281 |
+
for (int i = 0; i < ((m_num_components == 3) ? 2 : 1); i++)
|
282 |
+
{
|
283 |
+
emit_marker(M_DQT);
|
284 |
+
emit_word(64 + 1 + 2);
|
285 |
+
emit_byte(static_cast<uint8>(i));
|
286 |
+
for (int j = 0; j < 64; j++)
|
287 |
+
emit_byte(static_cast<uint8>(m_quantization_tables[i][j]));
|
288 |
+
}
|
289 |
+
}
|
290 |
+
|
291 |
+
// Emit start of frame marker
|
292 |
+
void jpeg_encoder::emit_sof()
|
293 |
+
{
|
294 |
+
emit_marker(M_SOF0); /* baseline */
|
295 |
+
emit_word(3 * m_num_components + 2 + 5 + 1);
|
296 |
+
emit_byte(8); /* precision */
|
297 |
+
emit_word(m_image_y);
|
298 |
+
emit_word(m_image_x);
|
299 |
+
emit_byte(m_num_components);
|
300 |
+
for (int i = 0; i < m_num_components; i++)
|
301 |
+
{
|
302 |
+
emit_byte(static_cast<uint8>(i + 1)); /* component ID */
|
303 |
+
emit_byte((m_comp_h_samp[i] << 4) + m_comp_v_samp[i]); /* h and v sampling */
|
304 |
+
emit_byte(i > 0); /* quant. table num */
|
305 |
+
}
|
306 |
+
}
|
307 |
+
|
308 |
+
// Emit Huffman table.
|
309 |
+
void jpeg_encoder::emit_dht(uint8 *bits, uint8 *val, int index, bool ac_flag)
|
310 |
+
{
|
311 |
+
emit_marker(M_DHT);
|
312 |
+
|
313 |
+
int length = 0;
|
314 |
+
for (int i = 1; i <= 16; i++)
|
315 |
+
length += bits[i];
|
316 |
+
|
317 |
+
emit_word(length + 2 + 1 + 16);
|
318 |
+
emit_byte(static_cast<uint8>(index + (ac_flag << 4)));
|
319 |
+
|
320 |
+
for (int i = 1; i <= 16; i++)
|
321 |
+
emit_byte(bits[i]);
|
322 |
+
|
323 |
+
for (int i = 0; i < length; i++)
|
324 |
+
emit_byte(val[i]);
|
325 |
+
}
|
326 |
+
|
327 |
+
// Emit all Huffman tables.
|
328 |
+
void jpeg_encoder::emit_dhts()
|
329 |
+
{
|
330 |
+
emit_dht(m_huff_bits[0+0], m_huff_val[0+0], 0, false);
|
331 |
+
emit_dht(m_huff_bits[2+0], m_huff_val[2+0], 0, true);
|
332 |
+
if (m_num_components == 3)
|
333 |
+
{
|
334 |
+
emit_dht(m_huff_bits[0+1], m_huff_val[0+1], 1, false);
|
335 |
+
emit_dht(m_huff_bits[2+1], m_huff_val[2+1], 1, true);
|
336 |
+
}
|
337 |
+
}
|
338 |
+
|
339 |
+
// emit start of scan
|
340 |
+
void jpeg_encoder::emit_sos()
|
341 |
+
{
|
342 |
+
emit_marker(M_SOS);
|
343 |
+
emit_word(2 * m_num_components + 2 + 1 + 3);
|
344 |
+
emit_byte(m_num_components);
|
345 |
+
for (int i = 0; i < m_num_components; i++)
|
346 |
+
{
|
347 |
+
emit_byte(static_cast<uint8>(i + 1));
|
348 |
+
if (i == 0)
|
349 |
+
emit_byte((0 << 4) + 0);
|
350 |
+
else
|
351 |
+
emit_byte((1 << 4) + 1);
|
352 |
+
}
|
353 |
+
emit_byte(0); /* spectral selection */
|
354 |
+
emit_byte(63);
|
355 |
+
emit_byte(0);
|
356 |
+
}
|
357 |
+
|
358 |
+
// Emit all markers at beginning of image file.
|
359 |
+
void jpeg_encoder::emit_markers()
|
360 |
+
{
|
361 |
+
emit_marker(M_SOI);
|
362 |
+
emit_jfif_app0();
|
363 |
+
emit_dqt();
|
364 |
+
emit_sof();
|
365 |
+
emit_dhts();
|
366 |
+
emit_sos();
|
367 |
+
}
|
368 |
+
|
369 |
+
// Compute the actual canonical Huffman codes/code sizes given the JPEG huff bits and val arrays.
|
370 |
+
void jpeg_encoder::compute_huffman_table(uint *codes, uint8 *code_sizes, uint8 *bits, uint8 *val)
|
371 |
+
{
|
372 |
+
int i, l, last_p, si;
|
373 |
+
uint8 huff_size[257];
|
374 |
+
uint huff_code[257];
|
375 |
+
uint code;
|
376 |
+
|
377 |
+
int p = 0;
|
378 |
+
for (l = 1; l <= 16; l++)
|
379 |
+
for (i = 1; i <= bits[l]; i++)
|
380 |
+
huff_size[p++] = (char)l;
|
381 |
+
|
382 |
+
huff_size[p] = 0; last_p = p; // write sentinel
|
383 |
+
|
384 |
+
code = 0; si = huff_size[0]; p = 0;
|
385 |
+
|
386 |
+
while (huff_size[p])
|
387 |
+
{
|
388 |
+
while (huff_size[p] == si)
|
389 |
+
huff_code[p++] = code++;
|
390 |
+
code <<= 1;
|
391 |
+
si++;
|
392 |
+
}
|
393 |
+
|
394 |
+
memset(codes, 0, sizeof(codes[0])*256);
|
395 |
+
memset(code_sizes, 0, sizeof(code_sizes[0])*256);
|
396 |
+
for (p = 0; p < last_p; p++)
|
397 |
+
{
|
398 |
+
codes[val[p]] = huff_code[p];
|
399 |
+
code_sizes[val[p]] = huff_size[p];
|
400 |
+
}
|
401 |
+
}
|
402 |
+
|
403 |
+
// Quantization table generation.
|
404 |
+
void jpeg_encoder::compute_quant_table(int32 *pDst, int16 *pSrc)
|
405 |
+
{
|
406 |
+
int32 q;
|
407 |
+
if (m_params.m_quality < 50)
|
408 |
+
q = 5000 / m_params.m_quality;
|
409 |
+
else
|
410 |
+
q = 200 - m_params.m_quality * 2;
|
411 |
+
for (int i = 0; i < 64; i++)
|
412 |
+
{
|
413 |
+
int32 j = *pSrc++; j = (j * q + 50L) / 100L;
|
414 |
+
*pDst++ = JPGE_MIN(JPGE_MAX(j, 1), 255);
|
415 |
+
}
|
416 |
+
}
|
417 |
+
|
418 |
+
// Higher-level methods.
|
419 |
+
void jpeg_encoder::first_pass_init()
|
420 |
+
{
|
421 |
+
m_bit_buffer = 0; m_bits_in = 0;
|
422 |
+
memset(m_last_dc_val, 0, 3 * sizeof(m_last_dc_val[0]));
|
423 |
+
m_mcu_y_ofs = 0;
|
424 |
+
m_pass_num = 1;
|
425 |
+
}
|
426 |
+
|
427 |
+
bool jpeg_encoder::second_pass_init()
|
428 |
+
{
|
429 |
+
compute_huffman_table(&m_huff_codes[0+0][0], &m_huff_code_sizes[0+0][0], m_huff_bits[0+0], m_huff_val[0+0]);
|
430 |
+
compute_huffman_table(&m_huff_codes[2+0][0], &m_huff_code_sizes[2+0][0], m_huff_bits[2+0], m_huff_val[2+0]);
|
431 |
+
if (m_num_components > 1)
|
432 |
+
{
|
433 |
+
compute_huffman_table(&m_huff_codes[0+1][0], &m_huff_code_sizes[0+1][0], m_huff_bits[0+1], m_huff_val[0+1]);
|
434 |
+
compute_huffman_table(&m_huff_codes[2+1][0], &m_huff_code_sizes[2+1][0], m_huff_bits[2+1], m_huff_val[2+1]);
|
435 |
+
}
|
436 |
+
first_pass_init();
|
437 |
+
emit_markers();
|
438 |
+
m_pass_num = 2;
|
439 |
+
return true;
|
440 |
+
}
|
441 |
+
|
442 |
+
bool jpeg_encoder::jpg_open(int p_x_res, int p_y_res, int src_channels)
|
443 |
+
{
|
444 |
+
m_num_components = 3;
|
445 |
+
switch (m_params.m_subsampling)
|
446 |
+
{
|
447 |
+
case Y_ONLY:
|
448 |
+
{
|
449 |
+
m_num_components = 1;
|
450 |
+
m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
|
451 |
+
m_mcu_x = 8; m_mcu_y = 8;
|
452 |
+
break;
|
453 |
+
}
|
454 |
+
case H1V1:
|
455 |
+
{
|
456 |
+
m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
|
457 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
458 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
459 |
+
m_mcu_x = 8; m_mcu_y = 8;
|
460 |
+
break;
|
461 |
+
}
|
462 |
+
case H2V1:
|
463 |
+
{
|
464 |
+
m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 1;
|
465 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
466 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
467 |
+
m_mcu_x = 16; m_mcu_y = 8;
|
468 |
+
break;
|
469 |
+
}
|
470 |
+
case H2V2:
|
471 |
+
{
|
472 |
+
m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 2;
|
473 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
474 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
475 |
+
m_mcu_x = 16; m_mcu_y = 16;
|
476 |
+
}
|
477 |
+
}
|
478 |
+
|
479 |
+
m_image_x = p_x_res; m_image_y = p_y_res;
|
480 |
+
m_image_bpp = src_channels;
|
481 |
+
m_image_bpl = m_image_x * src_channels;
|
482 |
+
m_image_x_mcu = (m_image_x + m_mcu_x - 1) & (~(m_mcu_x - 1));
|
483 |
+
m_image_y_mcu = (m_image_y + m_mcu_y - 1) & (~(m_mcu_y - 1));
|
484 |
+
m_image_bpl_xlt = m_image_x * m_num_components;
|
485 |
+
m_image_bpl_mcu = m_image_x_mcu * m_num_components;
|
486 |
+
m_mcus_per_row = m_image_x_mcu / m_mcu_x;
|
487 |
+
|
488 |
+
if ((m_mcu_lines[0] = static_cast<uint8*>(jpge_malloc(m_image_bpl_mcu * m_mcu_y))) == NULL) return false;
|
489 |
+
for (int i = 1; i < m_mcu_y; i++)
|
490 |
+
m_mcu_lines[i] = m_mcu_lines[i-1] + m_image_bpl_mcu;
|
491 |
+
|
492 |
+
compute_quant_table(m_quantization_tables[0], s_std_lum_quant);
|
493 |
+
compute_quant_table(m_quantization_tables[1], m_params.m_no_chroma_discrim_flag ? s_std_lum_quant : s_std_croma_quant);
|
494 |
+
|
495 |
+
m_out_buf_left = JPGE_OUT_BUF_SIZE;
|
496 |
+
m_pOut_buf = m_out_buf;
|
497 |
+
|
498 |
+
if (m_params.m_two_pass_flag)
|
499 |
+
{
|
500 |
+
clear_obj(m_huff_count);
|
501 |
+
first_pass_init();
|
502 |
+
}
|
503 |
+
else
|
504 |
+
{
|
505 |
+
memcpy(m_huff_bits[0+0], s_dc_lum_bits, 17); memcpy(m_huff_val [0+0], s_dc_lum_val, DC_LUM_CODES);
|
506 |
+
memcpy(m_huff_bits[2+0], s_ac_lum_bits, 17); memcpy(m_huff_val [2+0], s_ac_lum_val, AC_LUM_CODES);
|
507 |
+
memcpy(m_huff_bits[0+1], s_dc_chroma_bits, 17); memcpy(m_huff_val [0+1], s_dc_chroma_val, DC_CHROMA_CODES);
|
508 |
+
memcpy(m_huff_bits[2+1], s_ac_chroma_bits, 17); memcpy(m_huff_val [2+1], s_ac_chroma_val, AC_CHROMA_CODES);
|
509 |
+
if (!second_pass_init()) return false; // in effect, skip over the first pass
|
510 |
+
}
|
511 |
+
return m_all_stream_writes_succeeded;
|
512 |
+
}
|
513 |
+
|
514 |
+
void jpeg_encoder::load_block_8_8_grey(int x)
|
515 |
+
{
|
516 |
+
uint8 *pSrc;
|
517 |
+
sample_array_t *pDst = m_sample_array;
|
518 |
+
x <<= 3;
|
519 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
520 |
+
{
|
521 |
+
pSrc = m_mcu_lines[i] + x;
|
522 |
+
pDst[0] = pSrc[0] - 128; pDst[1] = pSrc[1] - 128; pDst[2] = pSrc[2] - 128; pDst[3] = pSrc[3] - 128;
|
523 |
+
pDst[4] = pSrc[4] - 128; pDst[5] = pSrc[5] - 128; pDst[6] = pSrc[6] - 128; pDst[7] = pSrc[7] - 128;
|
524 |
+
}
|
525 |
+
}
|
526 |
+
|
527 |
+
void jpeg_encoder::load_block_8_8(int x, int y, int c)
|
528 |
+
{
|
529 |
+
uint8 *pSrc;
|
530 |
+
sample_array_t *pDst = m_sample_array;
|
531 |
+
x = (x * (8 * 3)) + c;
|
532 |
+
y <<= 3;
|
533 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
534 |
+
{
|
535 |
+
pSrc = m_mcu_lines[y + i] + x;
|
536 |
+
pDst[0] = pSrc[0 * 3] - 128; pDst[1] = pSrc[1 * 3] - 128; pDst[2] = pSrc[2 * 3] - 128; pDst[3] = pSrc[3 * 3] - 128;
|
537 |
+
pDst[4] = pSrc[4 * 3] - 128; pDst[5] = pSrc[5 * 3] - 128; pDst[6] = pSrc[6 * 3] - 128; pDst[7] = pSrc[7 * 3] - 128;
|
538 |
+
}
|
539 |
+
}
|
540 |
+
|
541 |
+
void jpeg_encoder::load_block_16_8(int x, int c)
|
542 |
+
{
|
543 |
+
uint8 *pSrc1, *pSrc2;
|
544 |
+
sample_array_t *pDst = m_sample_array;
|
545 |
+
x = (x * (16 * 3)) + c;
|
546 |
+
int a = 0, b = 2;
|
547 |
+
for (int i = 0; i < 16; i += 2, pDst += 8)
|
548 |
+
{
|
549 |
+
pSrc1 = m_mcu_lines[i + 0] + x;
|
550 |
+
pSrc2 = m_mcu_lines[i + 1] + x;
|
551 |
+
pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3] + pSrc2[ 0 * 3] + pSrc2[ 1 * 3] + a) >> 2) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3] + pSrc2[ 2 * 3] + pSrc2[ 3 * 3] + b) >> 2) - 128;
|
552 |
+
pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3] + pSrc2[ 4 * 3] + pSrc2[ 5 * 3] + a) >> 2) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3] + pSrc2[ 6 * 3] + pSrc2[ 7 * 3] + b) >> 2) - 128;
|
553 |
+
pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3] + pSrc2[ 8 * 3] + pSrc2[ 9 * 3] + a) >> 2) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3] + pSrc2[10 * 3] + pSrc2[11 * 3] + b) >> 2) - 128;
|
554 |
+
pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3] + pSrc2[12 * 3] + pSrc2[13 * 3] + a) >> 2) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3] + pSrc2[14 * 3] + pSrc2[15 * 3] + b) >> 2) - 128;
|
555 |
+
int temp = a; a = b; b = temp;
|
556 |
+
}
|
557 |
+
}
|
558 |
+
|
559 |
+
void jpeg_encoder::load_block_16_8_8(int x, int c)
|
560 |
+
{
|
561 |
+
uint8 *pSrc1;
|
562 |
+
sample_array_t *pDst = m_sample_array;
|
563 |
+
x = (x * (16 * 3)) + c;
|
564 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
565 |
+
{
|
566 |
+
pSrc1 = m_mcu_lines[i + 0] + x;
|
567 |
+
pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3]) >> 1) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3]) >> 1) - 128;
|
568 |
+
pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3]) >> 1) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3]) >> 1) - 128;
|
569 |
+
pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3]) >> 1) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3]) >> 1) - 128;
|
570 |
+
pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3]) >> 1) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3]) >> 1) - 128;
|
571 |
+
}
|
572 |
+
}
|
573 |
+
|
574 |
+
void jpeg_encoder::load_quantized_coefficients(int component_num)
|
575 |
+
{
|
576 |
+
int32 *q = m_quantization_tables[component_num > 0];
|
577 |
+
int16 *pDst = m_coefficient_array;
|
578 |
+
for (int i = 0; i < 64; i++)
|
579 |
+
{
|
580 |
+
sample_array_t j = m_sample_array[s_zag[i]];
|
581 |
+
if (j < 0)
|
582 |
+
{
|
583 |
+
if ((j = -j + (*q >> 1)) < *q)
|
584 |
+
*pDst++ = 0;
|
585 |
+
else
|
586 |
+
*pDst++ = static_cast<int16>(-(j / *q));
|
587 |
+
}
|
588 |
+
else
|
589 |
+
{
|
590 |
+
if ((j = j + (*q >> 1)) < *q)
|
591 |
+
*pDst++ = 0;
|
592 |
+
else
|
593 |
+
*pDst++ = static_cast<int16>((j / *q));
|
594 |
+
}
|
595 |
+
q++;
|
596 |
+
}
|
597 |
+
}
|
598 |
+
|
599 |
+
void jpeg_encoder::flush_output_buffer()
|
600 |
+
{
|
601 |
+
if (m_out_buf_left != JPGE_OUT_BUF_SIZE)
|
602 |
+
m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_buf(m_out_buf, JPGE_OUT_BUF_SIZE - m_out_buf_left);
|
603 |
+
m_pOut_buf = m_out_buf;
|
604 |
+
m_out_buf_left = JPGE_OUT_BUF_SIZE;
|
605 |
+
}
|
606 |
+
|
607 |
+
void jpeg_encoder::put_bits(uint bits, uint len)
|
608 |
+
{
|
609 |
+
m_bit_buffer |= ((uint32)bits << (24 - (m_bits_in += len)));
|
610 |
+
while (m_bits_in >= 8)
|
611 |
+
{
|
612 |
+
uint8 c;
|
613 |
+
#define JPGE_PUT_BYTE(c) { *m_pOut_buf++ = (c); if (--m_out_buf_left == 0) flush_output_buffer(); }
|
614 |
+
JPGE_PUT_BYTE(c = (uint8)((m_bit_buffer >> 16) & 0xFF));
|
615 |
+
if (c == 0xFF) JPGE_PUT_BYTE(0);
|
616 |
+
m_bit_buffer <<= 8;
|
617 |
+
m_bits_in -= 8;
|
618 |
+
}
|
619 |
+
}
|
620 |
+
|
621 |
+
void jpeg_encoder::code_coefficients_pass_one(int component_num)
|
622 |
+
{
|
623 |
+
if (component_num >= 3) return; // just to shut up static analysis
|
624 |
+
int i, run_len, nbits, temp1;
|
625 |
+
int16 *src = m_coefficient_array;
|
626 |
+
uint32 *dc_count = component_num ? m_huff_count[0 + 1] : m_huff_count[0 + 0], *ac_count = component_num ? m_huff_count[2 + 1] : m_huff_count[2 + 0];
|
627 |
+
|
628 |
+
temp1 = src[0] - m_last_dc_val[component_num];
|
629 |
+
m_last_dc_val[component_num] = src[0];
|
630 |
+
if (temp1 < 0) temp1 = -temp1;
|
631 |
+
|
632 |
+
nbits = 0;
|
633 |
+
while (temp1)
|
634 |
+
{
|
635 |
+
nbits++; temp1 >>= 1;
|
636 |
+
}
|
637 |
+
|
638 |
+
dc_count[nbits]++;
|
639 |
+
for (run_len = 0, i = 1; i < 64; i++)
|
640 |
+
{
|
641 |
+
if ((temp1 = m_coefficient_array[i]) == 0)
|
642 |
+
run_len++;
|
643 |
+
else
|
644 |
+
{
|
645 |
+
while (run_len >= 16)
|
646 |
+
{
|
647 |
+
ac_count[0xF0]++;
|
648 |
+
run_len -= 16;
|
649 |
+
}
|
650 |
+
if (temp1 < 0) temp1 = -temp1;
|
651 |
+
nbits = 1;
|
652 |
+
while (temp1 >>= 1) nbits++;
|
653 |
+
ac_count[(run_len << 4) + nbits]++;
|
654 |
+
run_len = 0;
|
655 |
+
}
|
656 |
+
}
|
657 |
+
if (run_len) ac_count[0]++;
|
658 |
+
}
|
659 |
+
|
660 |
+
void jpeg_encoder::code_coefficients_pass_two(int component_num)
|
661 |
+
{
|
662 |
+
int i, j, run_len, nbits, temp1, temp2;
|
663 |
+
int16 *pSrc = m_coefficient_array;
|
664 |
+
uint *codes[2];
|
665 |
+
uint8 *code_sizes[2];
|
666 |
+
|
667 |
+
if (component_num == 0)
|
668 |
+
{
|
669 |
+
codes[0] = m_huff_codes[0 + 0]; codes[1] = m_huff_codes[2 + 0];
|
670 |
+
code_sizes[0] = m_huff_code_sizes[0 + 0]; code_sizes[1] = m_huff_code_sizes[2 + 0];
|
671 |
+
}
|
672 |
+
else
|
673 |
+
{
|
674 |
+
codes[0] = m_huff_codes[0 + 1]; codes[1] = m_huff_codes[2 + 1];
|
675 |
+
code_sizes[0] = m_huff_code_sizes[0 + 1]; code_sizes[1] = m_huff_code_sizes[2 + 1];
|
676 |
+
}
|
677 |
+
|
678 |
+
temp1 = temp2 = pSrc[0] - m_last_dc_val[component_num];
|
679 |
+
m_last_dc_val[component_num] = pSrc[0];
|
680 |
+
|
681 |
+
if (temp1 < 0)
|
682 |
+
{
|
683 |
+
temp1 = -temp1; temp2--;
|
684 |
+
}
|
685 |
+
|
686 |
+
nbits = 0;
|
687 |
+
while (temp1)
|
688 |
+
{
|
689 |
+
nbits++; temp1 >>= 1;
|
690 |
+
}
|
691 |
+
|
692 |
+
put_bits(codes[0][nbits], code_sizes[0][nbits]);
|
693 |
+
if (nbits) put_bits(temp2 & ((1 << nbits) - 1), nbits);
|
694 |
+
|
695 |
+
for (run_len = 0, i = 1; i < 64; i++)
|
696 |
+
{
|
697 |
+
if ((temp1 = m_coefficient_array[i]) == 0)
|
698 |
+
run_len++;
|
699 |
+
else
|
700 |
+
{
|
701 |
+
while (run_len >= 16)
|
702 |
+
{
|
703 |
+
put_bits(codes[1][0xF0], code_sizes[1][0xF0]);
|
704 |
+
run_len -= 16;
|
705 |
+
}
|
706 |
+
if ((temp2 = temp1) < 0)
|
707 |
+
{
|
708 |
+
temp1 = -temp1;
|
709 |
+
temp2--;
|
710 |
+
}
|
711 |
+
nbits = 1;
|
712 |
+
while (temp1 >>= 1)
|
713 |
+
nbits++;
|
714 |
+
j = (run_len << 4) + nbits;
|
715 |
+
put_bits(codes[1][j], code_sizes[1][j]);
|
716 |
+
put_bits(temp2 & ((1 << nbits) - 1), nbits);
|
717 |
+
run_len = 0;
|
718 |
+
}
|
719 |
+
}
|
720 |
+
if (run_len)
|
721 |
+
put_bits(codes[1][0], code_sizes[1][0]);
|
722 |
+
}
|
723 |
+
|
724 |
+
void jpeg_encoder::code_block(int component_num)
|
725 |
+
{
|
726 |
+
DCT2D(m_sample_array);
|
727 |
+
load_quantized_coefficients(component_num);
|
728 |
+
if (m_pass_num == 1)
|
729 |
+
code_coefficients_pass_one(component_num);
|
730 |
+
else
|
731 |
+
code_coefficients_pass_two(component_num);
|
732 |
+
}
|
733 |
+
|
734 |
+
void jpeg_encoder::process_mcu_row()
|
735 |
+
{
|
736 |
+
if (m_num_components == 1)
|
737 |
+
{
|
738 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
739 |
+
{
|
740 |
+
load_block_8_8_grey(i); code_block(0);
|
741 |
+
}
|
742 |
+
}
|
743 |
+
else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
|
744 |
+
{
|
745 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
746 |
+
{
|
747 |
+
load_block_8_8(i, 0, 0); code_block(0); load_block_8_8(i, 0, 1); code_block(1); load_block_8_8(i, 0, 2); code_block(2);
|
748 |
+
}
|
749 |
+
}
|
750 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
|
751 |
+
{
|
752 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
753 |
+
{
|
754 |
+
load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
|
755 |
+
load_block_16_8_8(i, 1); code_block(1); load_block_16_8_8(i, 2); code_block(2);
|
756 |
+
}
|
757 |
+
}
|
758 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
|
759 |
+
{
|
760 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
761 |
+
{
|
762 |
+
load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
|
763 |
+
load_block_8_8(i * 2 + 0, 1, 0); code_block(0); load_block_8_8(i * 2 + 1, 1, 0); code_block(0);
|
764 |
+
load_block_16_8(i, 1); code_block(1); load_block_16_8(i, 2); code_block(2);
|
765 |
+
}
|
766 |
+
}
|
767 |
+
}
|
768 |
+
|
769 |
+
bool jpeg_encoder::terminate_pass_one()
|
770 |
+
{
|
771 |
+
optimize_huffman_table(0+0, DC_LUM_CODES); optimize_huffman_table(2+0, AC_LUM_CODES);
|
772 |
+
if (m_num_components > 1)
|
773 |
+
{
|
774 |
+
optimize_huffman_table(0+1, DC_CHROMA_CODES); optimize_huffman_table(2+1, AC_CHROMA_CODES);
|
775 |
+
}
|
776 |
+
return second_pass_init();
|
777 |
+
}
|
778 |
+
|
779 |
+
bool jpeg_encoder::terminate_pass_two()
|
780 |
+
{
|
781 |
+
put_bits(0x7F, 7);
|
782 |
+
flush_output_buffer();
|
783 |
+
emit_marker(M_EOI);
|
784 |
+
m_pass_num++; // purposely bump up m_pass_num, for debugging
|
785 |
+
return true;
|
786 |
+
}
|
787 |
+
|
788 |
+
bool jpeg_encoder::process_end_of_image()
|
789 |
+
{
|
790 |
+
if (m_mcu_y_ofs)
|
791 |
+
{
|
792 |
+
if (m_mcu_y_ofs < 16) // check here just to shut up static analysis
|
793 |
+
{
|
794 |
+
for (int i = m_mcu_y_ofs; i < m_mcu_y; i++)
|
795 |
+
memcpy(m_mcu_lines[i], m_mcu_lines[m_mcu_y_ofs - 1], m_image_bpl_mcu);
|
796 |
+
}
|
797 |
+
|
798 |
+
process_mcu_row();
|
799 |
+
}
|
800 |
+
|
801 |
+
if (m_pass_num == 1)
|
802 |
+
return terminate_pass_one();
|
803 |
+
else
|
804 |
+
return terminate_pass_two();
|
805 |
+
}
|
806 |
+
|
807 |
+
void jpeg_encoder::load_mcu(const void *pSrc)
|
808 |
+
{
|
809 |
+
const uint8* Psrc = reinterpret_cast<const uint8*>(pSrc);
|
810 |
+
|
811 |
+
uint8* pDst = m_mcu_lines[m_mcu_y_ofs]; // OK to write up to m_image_bpl_xlt bytes to pDst
|
812 |
+
|
813 |
+
if (m_num_components == 1)
|
814 |
+
{
|
815 |
+
if (m_image_bpp == 4)
|
816 |
+
RGBA_to_Y(pDst, Psrc, m_image_x);
|
817 |
+
else if (m_image_bpp == 3)
|
818 |
+
RGB_to_Y(pDst, Psrc, m_image_x);
|
819 |
+
else
|
820 |
+
memcpy(pDst, Psrc, m_image_x);
|
821 |
+
}
|
822 |
+
else
|
823 |
+
{
|
824 |
+
if (m_image_bpp == 4)
|
825 |
+
RGBA_to_YCC(pDst, Psrc, m_image_x);
|
826 |
+
else if (m_image_bpp == 3)
|
827 |
+
RGB_to_YCC(pDst, Psrc, m_image_x);
|
828 |
+
else
|
829 |
+
Y_to_YCC(pDst, Psrc, m_image_x);
|
830 |
+
}
|
831 |
+
|
832 |
+
// Possibly duplicate pixels at end of scanline if not a multiple of 8 or 16
|
833 |
+
if (m_num_components == 1)
|
834 |
+
memset(m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt, pDst[m_image_bpl_xlt - 1], m_image_x_mcu - m_image_x);
|
835 |
+
else
|
836 |
+
{
|
837 |
+
const uint8 y = pDst[m_image_bpl_xlt - 3 + 0], cb = pDst[m_image_bpl_xlt - 3 + 1], cr = pDst[m_image_bpl_xlt - 3 + 2];
|
838 |
+
uint8 *q = m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt;
|
839 |
+
for (int i = m_image_x; i < m_image_x_mcu; i++)
|
840 |
+
{
|
841 |
+
*q++ = y; *q++ = cb; *q++ = cr;
|
842 |
+
}
|
843 |
+
}
|
844 |
+
|
845 |
+
if (++m_mcu_y_ofs == m_mcu_y)
|
846 |
+
{
|
847 |
+
process_mcu_row();
|
848 |
+
m_mcu_y_ofs = 0;
|
849 |
+
}
|
850 |
+
}
|
851 |
+
|
852 |
+
void jpeg_encoder::clear()
|
853 |
+
{
|
854 |
+
m_mcu_lines[0] = NULL;
|
855 |
+
m_pass_num = 0;
|
856 |
+
m_all_stream_writes_succeeded = true;
|
857 |
+
}
|
858 |
+
|
859 |
+
jpeg_encoder::jpeg_encoder()
|
860 |
+
{
|
861 |
+
clear();
|
862 |
+
}
|
863 |
+
|
864 |
+
jpeg_encoder::~jpeg_encoder()
|
865 |
+
{
|
866 |
+
deinit();
|
867 |
+
}
|
868 |
+
|
869 |
+
bool jpeg_encoder::init(output_stream *pStream, int64_t width, int64_t height, int64_t src_channels, const params &comp_params)
|
870 |
+
{
|
871 |
+
deinit();
|
872 |
+
if (((!pStream) || (width < 1) || (height < 1)) || ((src_channels != 1) && (src_channels != 3) && (src_channels != 4)) || (!comp_params.check_valid())) return false;
|
873 |
+
m_pStream = pStream;
|
874 |
+
m_params = comp_params;
|
875 |
+
return jpg_open(width, height, src_channels);
|
876 |
+
}
|
877 |
+
|
878 |
+
void jpeg_encoder::deinit()
|
879 |
+
{
|
880 |
+
jpge_free(m_mcu_lines[0]);
|
881 |
+
clear();
|
882 |
+
}
|
883 |
+
|
884 |
+
bool jpeg_encoder::process_scanline(const void* pScanline)
|
885 |
+
{
|
886 |
+
if ((m_pass_num < 1) || (m_pass_num > 2)) return false;
|
887 |
+
if (m_all_stream_writes_succeeded)
|
888 |
+
{
|
889 |
+
if (!pScanline)
|
890 |
+
{
|
891 |
+
if (!process_end_of_image()) return false;
|
892 |
+
}
|
893 |
+
else
|
894 |
+
{
|
895 |
+
load_mcu(pScanline);
|
896 |
+
}
|
897 |
+
}
|
898 |
+
return m_all_stream_writes_succeeded;
|
899 |
+
}
|
900 |
+
|
901 |
+
// Higher level wrappers/examples (optional).
|
902 |
+
#include <stdio.h>
|
903 |
+
|
904 |
+
class cfile_stream : public output_stream
|
905 |
+
{
|
906 |
+
cfile_stream(const cfile_stream &);
|
907 |
+
cfile_stream &operator= (const cfile_stream &);
|
908 |
+
|
909 |
+
FILE* m_pFile;
|
910 |
+
bool m_bStatus;
|
911 |
+
|
912 |
+
public:
|
913 |
+
cfile_stream() : m_pFile(NULL), m_bStatus(false) { }
|
914 |
+
|
915 |
+
virtual ~cfile_stream()
|
916 |
+
{
|
917 |
+
close();
|
918 |
+
}
|
919 |
+
|
920 |
+
bool open(const char *pFilename)
|
921 |
+
{
|
922 |
+
close();
|
923 |
+
#if defined(_MSC_VER)
|
924 |
+
if (fopen_s(&m_pFile, pFilename, "wb") != 0)
|
925 |
+
{
|
926 |
+
return false;
|
927 |
+
}
|
928 |
+
#else
|
929 |
+
m_pFile = fopen(pFilename, "wb");
|
930 |
+
#endif
|
931 |
+
m_bStatus = (m_pFile != NULL);
|
932 |
+
return m_bStatus;
|
933 |
+
}
|
934 |
+
|
935 |
+
bool close()
|
936 |
+
{
|
937 |
+
if (m_pFile)
|
938 |
+
{
|
939 |
+
if (fclose(m_pFile) == EOF)
|
940 |
+
{
|
941 |
+
m_bStatus = false;
|
942 |
+
}
|
943 |
+
m_pFile = NULL;
|
944 |
+
}
|
945 |
+
return m_bStatus;
|
946 |
+
}
|
947 |
+
|
948 |
+
virtual bool put_buf(const void* pBuf, int64_t len)
|
949 |
+
{
|
950 |
+
m_bStatus = m_bStatus && (fwrite(pBuf, len, 1, m_pFile) == 1);
|
951 |
+
return m_bStatus;
|
952 |
+
}
|
953 |
+
|
954 |
+
uint get_size() const
|
955 |
+
{
|
956 |
+
return m_pFile ? ftell(m_pFile) : 0;
|
957 |
+
}
|
958 |
+
};
|
959 |
+
|
960 |
+
// Writes JPEG image to file.
|
961 |
+
bool compress_image_to_jpeg_file(const char *pFilename, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params)
|
962 |
+
{
|
963 |
+
cfile_stream dst_stream;
|
964 |
+
if (!dst_stream.open(pFilename))
|
965 |
+
return false;
|
966 |
+
|
967 |
+
jpge::jpeg_encoder dst_image;
|
968 |
+
if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
|
969 |
+
return false;
|
970 |
+
|
971 |
+
for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
|
972 |
+
{
|
973 |
+
for (int64_t i = 0; i < height; i++)
|
974 |
+
{
|
975 |
+
// i, width, and num_channels are all 64bit
|
976 |
+
const uint8* pBuf = pImage_data + i * width * num_channels;
|
977 |
+
if (!dst_image.process_scanline(pBuf))
|
978 |
+
return false;
|
979 |
+
}
|
980 |
+
if (!dst_image.process_scanline(NULL))
|
981 |
+
return false;
|
982 |
+
}
|
983 |
+
|
984 |
+
dst_image.deinit();
|
985 |
+
|
986 |
+
return dst_stream.close();
|
987 |
+
}
|
988 |
+
|
989 |
+
class memory_stream : public output_stream
|
990 |
+
{
|
991 |
+
memory_stream(const memory_stream &);
|
992 |
+
memory_stream &operator= (const memory_stream &);
|
993 |
+
|
994 |
+
uint8 *m_pBuf;
|
995 |
+
uint64_t m_buf_size, m_buf_ofs;
|
996 |
+
|
997 |
+
public:
|
998 |
+
memory_stream(void *pBuf, uint64_t buf_size) : m_pBuf(static_cast<uint8*>(pBuf)), m_buf_size(buf_size), m_buf_ofs(0) { }
|
999 |
+
|
1000 |
+
virtual ~memory_stream() { }
|
1001 |
+
|
1002 |
+
virtual bool put_buf(const void* pBuf, int64_t len)
|
1003 |
+
{
|
1004 |
+
uint64_t buf_remaining = m_buf_size - m_buf_ofs;
|
1005 |
+
if ((uint64_t)len > buf_remaining)
|
1006 |
+
return false;
|
1007 |
+
memcpy(m_pBuf + m_buf_ofs, pBuf, len);
|
1008 |
+
m_buf_ofs += len;
|
1009 |
+
return true;
|
1010 |
+
}
|
1011 |
+
|
1012 |
+
uint64_t get_size() const
|
1013 |
+
{
|
1014 |
+
return m_buf_ofs;
|
1015 |
+
}
|
1016 |
+
};
|
1017 |
+
|
1018 |
+
bool compress_image_to_jpeg_file_in_memory(void *pDstBuf, int64_t &buf_size, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params)
|
1019 |
+
{
|
1020 |
+
if ((!pDstBuf) || (!buf_size))
|
1021 |
+
return false;
|
1022 |
+
|
1023 |
+
memory_stream dst_stream(pDstBuf, buf_size);
|
1024 |
+
|
1025 |
+
buf_size = 0;
|
1026 |
+
|
1027 |
+
jpge::jpeg_encoder dst_image;
|
1028 |
+
if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
|
1029 |
+
return false;
|
1030 |
+
|
1031 |
+
for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
|
1032 |
+
{
|
1033 |
+
for (int64_t i = 0; i < height; i++)
|
1034 |
+
{
|
1035 |
+
const uint8* pScanline = pImage_data + i * width * num_channels;
|
1036 |
+
if (!dst_image.process_scanline(pScanline))
|
1037 |
+
return false;
|
1038 |
+
}
|
1039 |
+
if (!dst_image.process_scanline(NULL))
|
1040 |
+
return false;
|
1041 |
+
}
|
1042 |
+
|
1043 |
+
dst_image.deinit();
|
1044 |
+
|
1045 |
+
buf_size = dst_stream.get_size();
|
1046 |
+
return true;
|
1047 |
+
}
|
1048 |
+
|
1049 |
+
} // namespace jpge
|
crazy_functions/test_project/cpp/libJPG/jpge.h
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
// jpge.h - C++ class for JPEG compression.
|
3 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
4 |
+
// Alex Evans: Added RGBA support, linear memory allocator.
|
5 |
+
#ifndef JPEG_ENCODER_H
|
6 |
+
#define JPEG_ENCODER_H
|
7 |
+
|
8 |
+
#include <stdint.h>
|
9 |
+
|
10 |
+
namespace jpge
|
11 |
+
{
|
12 |
+
typedef unsigned char uint8;
|
13 |
+
typedef signed short int16;
|
14 |
+
typedef signed int int32;
|
15 |
+
typedef unsigned short uint16;
|
16 |
+
typedef unsigned int uint32;
|
17 |
+
typedef unsigned int uint;
|
18 |
+
|
19 |
+
// JPEG chroma subsampling factors. Y_ONLY (grayscale images) and H2V2 (color images) are the most common.
|
20 |
+
enum subsampling_t { Y_ONLY = 0, H1V1 = 1, H2V1 = 2, H2V2 = 3 };
|
21 |
+
|
22 |
+
// JPEG compression parameters structure.
|
23 |
+
struct params
|
24 |
+
{
|
25 |
+
inline params() : m_quality(85), m_subsampling(H2V2), m_no_chroma_discrim_flag(false), m_two_pass_flag(false) { }
|
26 |
+
|
27 |
+
inline bool check_valid() const
|
28 |
+
{
|
29 |
+
if ((m_quality < 1) || (m_quality > 100)) return false;
|
30 |
+
if ((uint)m_subsampling > (uint)H2V2) return false;
|
31 |
+
return true;
|
32 |
+
}
|
33 |
+
|
34 |
+
// Quality: 1-100, higher is better. Typical values are around 50-95.
|
35 |
+
int m_quality;
|
36 |
+
|
37 |
+
// m_subsampling:
|
38 |
+
// 0 = Y (grayscale) only
|
39 |
+
// 1 = YCbCr, no subsampling (H1V1, YCbCr 1x1x1, 3 blocks per MCU)
|
40 |
+
// 2 = YCbCr, H2V1 subsampling (YCbCr 2x1x1, 4 blocks per MCU)
|
41 |
+
// 3 = YCbCr, H2V2 subsampling (YCbCr 4x1x1, 6 blocks per MCU-- very common)
|
42 |
+
subsampling_t m_subsampling;
|
43 |
+
|
44 |
+
// Disables CbCr discrimination - only intended for testing.
|
45 |
+
// If true, the Y quantization table is also used for the CbCr channels.
|
46 |
+
bool m_no_chroma_discrim_flag;
|
47 |
+
|
48 |
+
bool m_two_pass_flag;
|
49 |
+
};
|
50 |
+
|
51 |
+
// Writes JPEG image to a file.
|
52 |
+
// num_channels must be 1 (Y) or 3 (RGB), image pitch must be width*num_channels.
|
53 |
+
bool compress_image_to_jpeg_file(const char *pFilename, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params = params());
|
54 |
+
|
55 |
+
// Writes JPEG image to memory buffer.
|
56 |
+
// On entry, buf_size is the size of the output buffer pointed at by pBuf, which should be at least ~1024 bytes.
|
57 |
+
// If return value is true, buf_size will be set to the size of the compressed data.
|
58 |
+
bool compress_image_to_jpeg_file_in_memory(void *pBuf, int64_t &buf_size, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params = params());
|
59 |
+
|
60 |
+
// Output stream abstract class - used by the jpeg_encoder class to write to the output stream.
|
61 |
+
// put_buf() is generally called with len==JPGE_OUT_BUF_SIZE bytes, but for headers it'll be called with smaller amounts.
|
62 |
+
class output_stream
|
63 |
+
{
|
64 |
+
public:
|
65 |
+
virtual ~output_stream() { };
|
66 |
+
virtual bool put_buf(const void* Pbuf, int64_t len) = 0;
|
67 |
+
template<class T> inline bool put_obj(const T& obj) { return put_buf(&obj, sizeof(T)); }
|
68 |
+
};
|
69 |
+
|
70 |
+
// Lower level jpeg_encoder class - useful if more control is needed than the above helper functions.
|
71 |
+
class jpeg_encoder
|
72 |
+
{
|
73 |
+
public:
|
74 |
+
jpeg_encoder();
|
75 |
+
~jpeg_encoder();
|
76 |
+
|
77 |
+
// Initializes the compressor.
|
78 |
+
// pStream: The stream object to use for writing compressed data.
|
79 |
+
// params - Compression parameters structure, defined above.
|
80 |
+
// width, height - Image dimensions.
|
81 |
+
// channels - May be 1, or 3. 1 indicates grayscale, 3 indicates RGB source data.
|
82 |
+
// Returns false on out of memory or if a stream write fails.
|
83 |
+
bool init(output_stream *pStream, int64_t width, int64_t height, int64_t src_channels, const params &comp_params = params());
|
84 |
+
|
85 |
+
const params &get_params() const { return m_params; }
|
86 |
+
|
87 |
+
// Deinitializes the compressor, freeing any allocated memory. May be called at any time.
|
88 |
+
void deinit();
|
89 |
+
|
90 |
+
uint get_total_passes() const { return m_params.m_two_pass_flag ? 2 : 1; }
|
91 |
+
inline uint get_cur_pass() { return m_pass_num; }
|
92 |
+
|
93 |
+
// Call this method with each source scanline.
|
94 |
+
// width * src_channels bytes per scanline is expected (RGB or Y format).
|
95 |
+
// You must call with NULL after all scanlines are processed to finish compression.
|
96 |
+
// Returns false on out of memory or if a stream write fails.
|
97 |
+
bool process_scanline(const void* pScanline);
|
98 |
+
|
99 |
+
private:
|
100 |
+
jpeg_encoder(const jpeg_encoder &);
|
101 |
+
jpeg_encoder &operator =(const jpeg_encoder &);
|
102 |
+
|
103 |
+
typedef int32 sample_array_t;
|
104 |
+
|
105 |
+
output_stream *m_pStream;
|
106 |
+
params m_params;
|
107 |
+
uint8 m_num_components;
|
108 |
+
uint8 m_comp_h_samp[3], m_comp_v_samp[3];
|
109 |
+
int m_image_x, m_image_y, m_image_bpp, m_image_bpl;
|
110 |
+
int m_image_x_mcu, m_image_y_mcu;
|
111 |
+
int m_image_bpl_xlt, m_image_bpl_mcu;
|
112 |
+
int m_mcus_per_row;
|
113 |
+
int m_mcu_x, m_mcu_y;
|
114 |
+
uint8 *m_mcu_lines[16];
|
115 |
+
uint8 m_mcu_y_ofs;
|
116 |
+
sample_array_t m_sample_array[64];
|
117 |
+
int16 m_coefficient_array[64];
|
118 |
+
int32 m_quantization_tables[2][64];
|
119 |
+
uint m_huff_codes[4][256];
|
120 |
+
uint8 m_huff_code_sizes[4][256];
|
121 |
+
uint8 m_huff_bits[4][17];
|
122 |
+
uint8 m_huff_val[4][256];
|
123 |
+
uint32 m_huff_count[4][256];
|
124 |
+
int m_last_dc_val[3];
|
125 |
+
enum { JPGE_OUT_BUF_SIZE = 2048 };
|
126 |
+
uint8 m_out_buf[JPGE_OUT_BUF_SIZE];
|
127 |
+
uint8 *m_pOut_buf;
|
128 |
+
uint m_out_buf_left;
|
129 |
+
uint32 m_bit_buffer;
|
130 |
+
uint m_bits_in;
|
131 |
+
uint8 m_pass_num;
|
132 |
+
bool m_all_stream_writes_succeeded;
|
133 |
+
|
134 |
+
void optimize_huffman_table(int table_num, int table_len);
|
135 |
+
void emit_byte(uint8 i);
|
136 |
+
void emit_word(uint i);
|
137 |
+
void emit_marker(int marker);
|
138 |
+
void emit_jfif_app0();
|
139 |
+
void emit_dqt();
|
140 |
+
void emit_sof();
|
141 |
+
void emit_dht(uint8 *bits, uint8 *val, int index, bool ac_flag);
|
142 |
+
void emit_dhts();
|
143 |
+
void emit_sos();
|
144 |
+
void emit_markers();
|
145 |
+
void compute_huffman_table(uint *codes, uint8 *code_sizes, uint8 *bits, uint8 *val);
|
146 |
+
void compute_quant_table(int32 *dst, int16 *src);
|
147 |
+
void adjust_quant_table(int32 *dst, int32 *src);
|
148 |
+
void first_pass_init();
|
149 |
+
bool second_pass_init();
|
150 |
+
bool jpg_open(int p_x_res, int p_y_res, int src_channels);
|
151 |
+
void load_block_8_8_grey(int x);
|
152 |
+
void load_block_8_8(int x, int y, int c);
|
153 |
+
void load_block_16_8(int x, int c);
|
154 |
+
void load_block_16_8_8(int x, int c);
|
155 |
+
void load_quantized_coefficients(int component_num);
|
156 |
+
void flush_output_buffer();
|
157 |
+
void put_bits(uint bits, uint len);
|
158 |
+
void code_coefficients_pass_one(int component_num);
|
159 |
+
void code_coefficients_pass_two(int component_num);
|
160 |
+
void code_block(int component_num);
|
161 |
+
void process_mcu_row();
|
162 |
+
bool terminate_pass_one();
|
163 |
+
bool terminate_pass_two();
|
164 |
+
bool process_end_of_image();
|
165 |
+
void load_mcu(const void* src);
|
166 |
+
void clear();
|
167 |
+
void init();
|
168 |
+
};
|
169 |
+
|
170 |
+
} // namespace jpge
|
171 |
+
|
172 |
+
#endif // JPEG_ENCODER
|
crazy_functions/test_project/cpp/libJPG/来源
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
jpge.h - C++ class for JPEG compression.
|
2 |
+
Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
Alex Evans: Added RGBA support, linear memory allocator.
|
crazy_functions/test_project/cpp/longcode/jpgd.cpp
ADDED
@@ -0,0 +1,3276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// jpgd.cpp - C++ class for JPEG decompression.
|
2 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
// Last updated Apr. 16, 2011
|
4 |
+
// Alex Evans: Linear memory allocator (taken from jpge.h).
|
5 |
+
//
|
6 |
+
// Supports progressive and baseline sequential JPEG image files, and the most common chroma subsampling factors: Y, H1V1, H2V1, H1V2, and H2V2.
|
7 |
+
//
|
8 |
+
// Chroma upsampling quality: H2V2 is upsampled in the frequency domain, H2V1 and H1V2 are upsampled using point sampling.
|
9 |
+
// Chroma upsampling reference: "Fast Scheme for Image Size Change in the Compressed Domain"
|
10 |
+
// http://vision.ai.uiuc.edu/~dugad/research/dct/index.html
|
11 |
+
|
12 |
+
#include "jpgd.h"
|
13 |
+
#include <string.h>
|
14 |
+
|
15 |
+
#include <assert.h>
|
16 |
+
// BEGIN EPIC MOD
|
17 |
+
#define JPGD_ASSERT(x) { assert(x); CA_ASSUME(x); } (void)0
|
18 |
+
// END EPIC MOD
|
19 |
+
|
20 |
+
#ifdef _MSC_VER
|
21 |
+
#pragma warning (disable : 4611) // warning C4611: interaction between '_setjmp' and C++ object destruction is non-portable
|
22 |
+
#endif
|
23 |
+
|
24 |
+
// Set to 1 to enable freq. domain chroma upsampling on images using H2V2 subsampling (0=faster nearest neighbor sampling).
|
25 |
+
// This is slower, but results in higher quality on images with highly saturated colors.
|
26 |
+
#define JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING 1
|
27 |
+
|
28 |
+
#define JPGD_TRUE (1)
|
29 |
+
#define JPGD_FALSE (0)
|
30 |
+
|
31 |
+
#define JPGD_MAX(a,b) (((a)>(b)) ? (a) : (b))
|
32 |
+
#define JPGD_MIN(a,b) (((a)<(b)) ? (a) : (b))
|
33 |
+
|
34 |
+
namespace jpgd {
|
35 |
+
|
36 |
+
static inline void *jpgd_malloc(size_t nSize) { return FMemory::Malloc(nSize); }
|
37 |
+
static inline void jpgd_free(void *p) { FMemory::Free(p); }
|
38 |
+
|
39 |
+
// BEGIN EPIC MOD
|
40 |
+
//@UE3 - use UE3 BGRA encoding instead of assuming RGBA
|
41 |
+
// stolen from IImageWrapper.h
|
42 |
+
enum ERGBFormatJPG
|
43 |
+
{
|
44 |
+
Invalid = -1,
|
45 |
+
RGBA = 0,
|
46 |
+
BGRA = 1,
|
47 |
+
Gray = 2,
|
48 |
+
};
|
49 |
+
static ERGBFormatJPG jpg_format;
|
50 |
+
// END EPIC MOD
|
51 |
+
|
52 |
+
// DCT coefficients are stored in this sequence.
|
53 |
+
static int g_ZAG[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 };
|
54 |
+
|
55 |
+
enum JPEG_MARKER
|
56 |
+
{
|
57 |
+
M_SOF0 = 0xC0, M_SOF1 = 0xC1, M_SOF2 = 0xC2, M_SOF3 = 0xC3, M_SOF5 = 0xC5, M_SOF6 = 0xC6, M_SOF7 = 0xC7, M_JPG = 0xC8,
|
58 |
+
M_SOF9 = 0xC9, M_SOF10 = 0xCA, M_SOF11 = 0xCB, M_SOF13 = 0xCD, M_SOF14 = 0xCE, M_SOF15 = 0xCF, M_DHT = 0xC4, M_DAC = 0xCC,
|
59 |
+
M_RST0 = 0xD0, M_RST1 = 0xD1, M_RST2 = 0xD2, M_RST3 = 0xD3, M_RST4 = 0xD4, M_RST5 = 0xD5, M_RST6 = 0xD6, M_RST7 = 0xD7,
|
60 |
+
M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_DNL = 0xDC, M_DRI = 0xDD, M_DHP = 0xDE, M_EXP = 0xDF,
|
61 |
+
M_APP0 = 0xE0, M_APP15 = 0xEF, M_JPG0 = 0xF0, M_JPG13 = 0xFD, M_COM = 0xFE, M_TEM = 0x01, M_ERROR = 0x100, RST0 = 0xD0
|
62 |
+
};
|
63 |
+
|
64 |
+
enum JPEG_SUBSAMPLING { JPGD_GRAYSCALE = 0, JPGD_YH1V1, JPGD_YH2V1, JPGD_YH1V2, JPGD_YH2V2 };
|
65 |
+
|
66 |
+
#define CONST_BITS 13
|
67 |
+
#define PASS1_BITS 2
|
68 |
+
#define SCALEDONE ((int32)1)
|
69 |
+
|
70 |
+
#define FIX_0_298631336 ((int32)2446) /* FIX(0.298631336) */
|
71 |
+
#define FIX_0_390180644 ((int32)3196) /* FIX(0.390180644) */
|
72 |
+
#define FIX_0_541196100 ((int32)4433) /* FIX(0.541196100) */
|
73 |
+
#define FIX_0_765366865 ((int32)6270) /* FIX(0.765366865) */
|
74 |
+
#define FIX_0_899976223 ((int32)7373) /* FIX(0.899976223) */
|
75 |
+
#define FIX_1_175875602 ((int32)9633) /* FIX(1.175875602) */
|
76 |
+
#define FIX_1_501321110 ((int32)12299) /* FIX(1.501321110) */
|
77 |
+
#define FIX_1_847759065 ((int32)15137) /* FIX(1.847759065) */
|
78 |
+
#define FIX_1_961570560 ((int32)16069) /* FIX(1.961570560) */
|
79 |
+
#define FIX_2_053119869 ((int32)16819) /* FIX(2.053119869) */
|
80 |
+
#define FIX_2_562915447 ((int32)20995) /* FIX(2.562915447) */
|
81 |
+
#define FIX_3_072711026 ((int32)25172) /* FIX(3.072711026) */
|
82 |
+
|
83 |
+
#define DESCALE(x,n) (((x) + (SCALEDONE << ((n)-1))) >> (n))
|
84 |
+
#define DESCALE_ZEROSHIFT(x,n) (((x) + (128 << (n)) + (SCALEDONE << ((n)-1))) >> (n))
|
85 |
+
|
86 |
+
#define MULTIPLY(var, cnst) ((var) * (cnst))
|
87 |
+
|
88 |
+
#define CLAMP(i) ((static_cast<uint>(i) > 255) ? (((~i) >> 31) & 0xFF) : (i))
|
89 |
+
|
90 |
+
// Compiler creates a fast path 1D IDCT for X non-zero columns
|
91 |
+
template <int NONZERO_COLS>
|
92 |
+
struct Row
|
93 |
+
{
|
94 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
95 |
+
{
|
96 |
+
// ACCESS_COL() will be optimized at compile time to either an array access, or 0.
|
97 |
+
#define ACCESS_COL(x) (((x) < NONZERO_COLS) ? (int)pSrc[x] : 0)
|
98 |
+
|
99 |
+
const int z2 = ACCESS_COL(2), z3 = ACCESS_COL(6);
|
100 |
+
|
101 |
+
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
|
102 |
+
const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
|
103 |
+
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
|
104 |
+
|
105 |
+
const int tmp0 = (ACCESS_COL(0) + ACCESS_COL(4)) << CONST_BITS;
|
106 |
+
const int tmp1 = (ACCESS_COL(0) - ACCESS_COL(4)) << CONST_BITS;
|
107 |
+
|
108 |
+
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
|
109 |
+
|
110 |
+
const int atmp0 = ACCESS_COL(7), atmp1 = ACCESS_COL(5), atmp2 = ACCESS_COL(3), atmp3 = ACCESS_COL(1);
|
111 |
+
|
112 |
+
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
|
113 |
+
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
|
114 |
+
|
115 |
+
const int az1 = MULTIPLY(bz1, - FIX_0_899976223);
|
116 |
+
const int az2 = MULTIPLY(bz2, - FIX_2_562915447);
|
117 |
+
const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5;
|
118 |
+
const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5;
|
119 |
+
|
120 |
+
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
|
121 |
+
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
|
122 |
+
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
|
123 |
+
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
|
124 |
+
|
125 |
+
pTemp[0] = DESCALE(tmp10 + btmp3, CONST_BITS-PASS1_BITS);
|
126 |
+
pTemp[7] = DESCALE(tmp10 - btmp3, CONST_BITS-PASS1_BITS);
|
127 |
+
pTemp[1] = DESCALE(tmp11 + btmp2, CONST_BITS-PASS1_BITS);
|
128 |
+
pTemp[6] = DESCALE(tmp11 - btmp2, CONST_BITS-PASS1_BITS);
|
129 |
+
pTemp[2] = DESCALE(tmp12 + btmp1, CONST_BITS-PASS1_BITS);
|
130 |
+
pTemp[5] = DESCALE(tmp12 - btmp1, CONST_BITS-PASS1_BITS);
|
131 |
+
pTemp[3] = DESCALE(tmp13 + btmp0, CONST_BITS-PASS1_BITS);
|
132 |
+
pTemp[4] = DESCALE(tmp13 - btmp0, CONST_BITS-PASS1_BITS);
|
133 |
+
}
|
134 |
+
};
|
135 |
+
|
136 |
+
template <>
|
137 |
+
struct Row<0>
|
138 |
+
{
|
139 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
140 |
+
{
|
141 |
+
#ifdef _MSC_VER
|
142 |
+
pTemp; pSrc;
|
143 |
+
#endif
|
144 |
+
}
|
145 |
+
};
|
146 |
+
|
147 |
+
template <>
|
148 |
+
struct Row<1>
|
149 |
+
{
|
150 |
+
static void idct(int* pTemp, const jpgd_block_t* pSrc)
|
151 |
+
{
|
152 |
+
const int dcval = (pSrc[0] << PASS1_BITS);
|
153 |
+
|
154 |
+
pTemp[0] = dcval;
|
155 |
+
pTemp[1] = dcval;
|
156 |
+
pTemp[2] = dcval;
|
157 |
+
pTemp[3] = dcval;
|
158 |
+
pTemp[4] = dcval;
|
159 |
+
pTemp[5] = dcval;
|
160 |
+
pTemp[6] = dcval;
|
161 |
+
pTemp[7] = dcval;
|
162 |
+
}
|
163 |
+
};
|
164 |
+
|
165 |
+
// Compiler creates a fast path 1D IDCT for X non-zero rows
|
166 |
+
template <int NONZERO_ROWS>
|
167 |
+
struct Col
|
168 |
+
{
|
169 |
+
static void idct(uint8* pDst_ptr, const int* pTemp)
|
170 |
+
{
|
171 |
+
// ACCESS_ROW() will be optimized at compile time to either an array access, or 0.
|
172 |
+
#define ACCESS_ROW(x) (((x) < NONZERO_ROWS) ? pTemp[x * 8] : 0)
|
173 |
+
|
174 |
+
const int z2 = ACCESS_ROW(2);
|
175 |
+
const int z3 = ACCESS_ROW(6);
|
176 |
+
|
177 |
+
const int z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
|
178 |
+
const int tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
|
179 |
+
const int tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
|
180 |
+
|
181 |
+
const int tmp0 = (ACCESS_ROW(0) + ACCESS_ROW(4)) << CONST_BITS;
|
182 |
+
const int tmp1 = (ACCESS_ROW(0) - ACCESS_ROW(4)) << CONST_BITS;
|
183 |
+
|
184 |
+
const int tmp10 = tmp0 + tmp3, tmp13 = tmp0 - tmp3, tmp11 = tmp1 + tmp2, tmp12 = tmp1 - tmp2;
|
185 |
+
|
186 |
+
const int atmp0 = ACCESS_ROW(7), atmp1 = ACCESS_ROW(5), atmp2 = ACCESS_ROW(3), atmp3 = ACCESS_ROW(1);
|
187 |
+
|
188 |
+
const int bz1 = atmp0 + atmp3, bz2 = atmp1 + atmp2, bz3 = atmp0 + atmp2, bz4 = atmp1 + atmp3;
|
189 |
+
const int bz5 = MULTIPLY(bz3 + bz4, FIX_1_175875602);
|
190 |
+
|
191 |
+
const int az1 = MULTIPLY(bz1, - FIX_0_899976223);
|
192 |
+
const int az2 = MULTIPLY(bz2, - FIX_2_562915447);
|
193 |
+
const int az3 = MULTIPLY(bz3, - FIX_1_961570560) + bz5;
|
194 |
+
const int az4 = MULTIPLY(bz4, - FIX_0_390180644) + bz5;
|
195 |
+
|
196 |
+
const int btmp0 = MULTIPLY(atmp0, FIX_0_298631336) + az1 + az3;
|
197 |
+
const int btmp1 = MULTIPLY(atmp1, FIX_2_053119869) + az2 + az4;
|
198 |
+
const int btmp2 = MULTIPLY(atmp2, FIX_3_072711026) + az2 + az3;
|
199 |
+
const int btmp3 = MULTIPLY(atmp3, FIX_1_501321110) + az1 + az4;
|
200 |
+
|
201 |
+
int i = DESCALE_ZEROSHIFT(tmp10 + btmp3, CONST_BITS+PASS1_BITS+3);
|
202 |
+
pDst_ptr[8*0] = (uint8)CLAMP(i);
|
203 |
+
|
204 |
+
i = DESCALE_ZEROSHIFT(tmp10 - btmp3, CONST_BITS+PASS1_BITS+3);
|
205 |
+
pDst_ptr[8*7] = (uint8)CLAMP(i);
|
206 |
+
|
207 |
+
i = DESCALE_ZEROSHIFT(tmp11 + btmp2, CONST_BITS+PASS1_BITS+3);
|
208 |
+
pDst_ptr[8*1] = (uint8)CLAMP(i);
|
209 |
+
|
210 |
+
i = DESCALE_ZEROSHIFT(tmp11 - btmp2, CONST_BITS+PASS1_BITS+3);
|
211 |
+
pDst_ptr[8*6] = (uint8)CLAMP(i);
|
212 |
+
|
213 |
+
i = DESCALE_ZEROSHIFT(tmp12 + btmp1, CONST_BITS+PASS1_BITS+3);
|
214 |
+
pDst_ptr[8*2] = (uint8)CLAMP(i);
|
215 |
+
|
216 |
+
i = DESCALE_ZEROSHIFT(tmp12 - btmp1, CONST_BITS+PASS1_BITS+3);
|
217 |
+
pDst_ptr[8*5] = (uint8)CLAMP(i);
|
218 |
+
|
219 |
+
i = DESCALE_ZEROSHIFT(tmp13 + btmp0, CONST_BITS+PASS1_BITS+3);
|
220 |
+
pDst_ptr[8*3] = (uint8)CLAMP(i);
|
221 |
+
|
222 |
+
i = DESCALE_ZEROSHIFT(tmp13 - btmp0, CONST_BITS+PASS1_BITS+3);
|
223 |
+
pDst_ptr[8*4] = (uint8)CLAMP(i);
|
224 |
+
}
|
225 |
+
};
|
226 |
+
|
227 |
+
template <>
|
228 |
+
struct Col<1>
|
229 |
+
{
|
230 |
+
static void idct(uint8* pDst_ptr, const int* pTemp)
|
231 |
+
{
|
232 |
+
int dcval = DESCALE_ZEROSHIFT(pTemp[0], PASS1_BITS+3);
|
233 |
+
const uint8 dcval_clamped = (uint8)CLAMP(dcval);
|
234 |
+
pDst_ptr[0*8] = dcval_clamped;
|
235 |
+
pDst_ptr[1*8] = dcval_clamped;
|
236 |
+
pDst_ptr[2*8] = dcval_clamped;
|
237 |
+
pDst_ptr[3*8] = dcval_clamped;
|
238 |
+
pDst_ptr[4*8] = dcval_clamped;
|
239 |
+
pDst_ptr[5*8] = dcval_clamped;
|
240 |
+
pDst_ptr[6*8] = dcval_clamped;
|
241 |
+
pDst_ptr[7*8] = dcval_clamped;
|
242 |
+
}
|
243 |
+
};
|
244 |
+
|
245 |
+
static const uint8 s_idct_row_table[] =
|
246 |
+
{
|
247 |
+
1,0,0,0,0,0,0,0, 2,0,0,0,0,0,0,0, 2,1,0,0,0,0,0,0, 2,1,1,0,0,0,0,0, 2,2,1,0,0,0,0,0, 3,2,1,0,0,0,0,0, 4,2,1,0,0,0,0,0, 4,3,1,0,0,0,0,0,
|
248 |
+
4,3,2,0,0,0,0,0, 4,3,2,1,0,0,0,0, 4,3,2,1,1,0,0,0, 4,3,2,2,1,0,0,0, 4,3,3,2,1,0,0,0, 4,4,3,2,1,0,0,0, 5,4,3,2,1,0,0,0, 6,4,3,2,1,0,0,0,
|
249 |
+
6,5,3,2,1,0,0,0, 6,5,4,2,1,0,0,0, 6,5,4,3,1,0,0,0, 6,5,4,3,2,0,0,0, 6,5,4,3,2,1,0,0, 6,5,4,3,2,1,1,0, 6,5,4,3,2,2,1,0, 6,5,4,3,3,2,1,0,
|
250 |
+
6,5,4,4,3,2,1,0, 6,5,5,4,3,2,1,0, 6,6,5,4,3,2,1,0, 7,6,5,4,3,2,1,0, 8,6,5,4,3,2,1,0, 8,7,5,4,3,2,1,0, 8,7,6,4,3,2,1,0, 8,7,6,5,3,2,1,0,
|
251 |
+
8,7,6,5,4,2,1,0, 8,7,6,5,4,3,1,0, 8,7,6,5,4,3,2,0, 8,7,6,5,4,3,2,1, 8,7,6,5,4,3,2,2, 8,7,6,5,4,3,3,2, 8,7,6,5,4,4,3,2, 8,7,6,5,5,4,3,2,
|
252 |
+
8,7,6,6,5,4,3,2, 8,7,7,6,5,4,3,2, 8,8,7,6,5,4,3,2, 8,8,8,6,5,4,3,2, 8,8,8,7,5,4,3,2, 8,8,8,7,6,4,3,2, 8,8,8,7,6,5,3,2, 8,8,8,7,6,5,4,2,
|
253 |
+
8,8,8,7,6,5,4,3, 8,8,8,7,6,5,4,4, 8,8,8,7,6,5,5,4, 8,8,8,7,6,6,5,4, 8,8,8,7,7,6,5,4, 8,8,8,8,7,6,5,4, 8,8,8,8,8,6,5,4, 8,8,8,8,8,7,5,4,
|
254 |
+
8,8,8,8,8,7,6,4, 8,8,8,8,8,7,6,5, 8,8,8,8,8,7,6,6, 8,8,8,8,8,7,7,6, 8,8,8,8,8,8,7,6, 8,8,8,8,8,8,8,6, 8,8,8,8,8,8,8,7, 8,8,8,8,8,8,8,8,
|
255 |
+
};
|
256 |
+
|
257 |
+
static const uint8 s_idct_col_table[] = { 1, 1, 2, 3, 3, 3, 3, 3, 3, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 };
|
258 |
+
|
259 |
+
void idct(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr, int block_max_zag)
|
260 |
+
{
|
261 |
+
JPGD_ASSERT(block_max_zag >= 1);
|
262 |
+
JPGD_ASSERT(block_max_zag <= 64);
|
263 |
+
|
264 |
+
if (block_max_zag == 1)
|
265 |
+
{
|
266 |
+
int k = ((pSrc_ptr[0] + 4) >> 3) + 128;
|
267 |
+
k = CLAMP(k);
|
268 |
+
k = k | (k<<8);
|
269 |
+
k = k | (k<<16);
|
270 |
+
|
271 |
+
for (int i = 8; i > 0; i--)
|
272 |
+
{
|
273 |
+
*(int*)&pDst_ptr[0] = k;
|
274 |
+
*(int*)&pDst_ptr[4] = k;
|
275 |
+
pDst_ptr += 8;
|
276 |
+
}
|
277 |
+
return;
|
278 |
+
}
|
279 |
+
|
280 |
+
int temp[64];
|
281 |
+
|
282 |
+
const jpgd_block_t* pSrc = pSrc_ptr;
|
283 |
+
int* pTemp = temp;
|
284 |
+
|
285 |
+
const uint8* pRow_tab = &s_idct_row_table[(block_max_zag - 1) * 8];
|
286 |
+
int i;
|
287 |
+
for (i = 8; i > 0; i--, pRow_tab++)
|
288 |
+
{
|
289 |
+
switch (*pRow_tab)
|
290 |
+
{
|
291 |
+
case 0: Row<0>::idct(pTemp, pSrc); break;
|
292 |
+
case 1: Row<1>::idct(pTemp, pSrc); break;
|
293 |
+
case 2: Row<2>::idct(pTemp, pSrc); break;
|
294 |
+
case 3: Row<3>::idct(pTemp, pSrc); break;
|
295 |
+
case 4: Row<4>::idct(pTemp, pSrc); break;
|
296 |
+
case 5: Row<5>::idct(pTemp, pSrc); break;
|
297 |
+
case 6: Row<6>::idct(pTemp, pSrc); break;
|
298 |
+
case 7: Row<7>::idct(pTemp, pSrc); break;
|
299 |
+
case 8: Row<8>::idct(pTemp, pSrc); break;
|
300 |
+
}
|
301 |
+
|
302 |
+
pSrc += 8;
|
303 |
+
pTemp += 8;
|
304 |
+
}
|
305 |
+
|
306 |
+
pTemp = temp;
|
307 |
+
|
308 |
+
const int nonzero_rows = s_idct_col_table[block_max_zag - 1];
|
309 |
+
for (i = 8; i > 0; i--)
|
310 |
+
{
|
311 |
+
switch (nonzero_rows)
|
312 |
+
{
|
313 |
+
case 1: Col<1>::idct(pDst_ptr, pTemp); break;
|
314 |
+
case 2: Col<2>::idct(pDst_ptr, pTemp); break;
|
315 |
+
case 3: Col<3>::idct(pDst_ptr, pTemp); break;
|
316 |
+
case 4: Col<4>::idct(pDst_ptr, pTemp); break;
|
317 |
+
case 5: Col<5>::idct(pDst_ptr, pTemp); break;
|
318 |
+
case 6: Col<6>::idct(pDst_ptr, pTemp); break;
|
319 |
+
case 7: Col<7>::idct(pDst_ptr, pTemp); break;
|
320 |
+
case 8: Col<8>::idct(pDst_ptr, pTemp); break;
|
321 |
+
}
|
322 |
+
|
323 |
+
pTemp++;
|
324 |
+
pDst_ptr++;
|
325 |
+
}
|
326 |
+
}
|
327 |
+
|
328 |
+
void idct_4x4(const jpgd_block_t* pSrc_ptr, uint8* pDst_ptr)
|
329 |
+
{
|
330 |
+
int temp[64];
|
331 |
+
int* pTemp = temp;
|
332 |
+
const jpgd_block_t* pSrc = pSrc_ptr;
|
333 |
+
|
334 |
+
for (int i = 4; i > 0; i--)
|
335 |
+
{
|
336 |
+
Row<4>::idct(pTemp, pSrc);
|
337 |
+
pSrc += 8;
|
338 |
+
pTemp += 8;
|
339 |
+
}
|
340 |
+
|
341 |
+
pTemp = temp;
|
342 |
+
for (int i = 8; i > 0; i--)
|
343 |
+
{
|
344 |
+
Col<4>::idct(pDst_ptr, pTemp);
|
345 |
+
pTemp++;
|
346 |
+
pDst_ptr++;
|
347 |
+
}
|
348 |
+
}
|
349 |
+
|
350 |
+
// Retrieve one character from the input stream.
|
351 |
+
inline uint jpeg_decoder::get_char()
|
352 |
+
{
|
353 |
+
// Any bytes remaining in buffer?
|
354 |
+
if (!m_in_buf_left)
|
355 |
+
{
|
356 |
+
// Try to get more bytes.
|
357 |
+
prep_in_buffer();
|
358 |
+
// Still nothing to get?
|
359 |
+
if (!m_in_buf_left)
|
360 |
+
{
|
361 |
+
// Pad the end of the stream with 0xFF 0xD9 (EOI marker)
|
362 |
+
int t = m_tem_flag;
|
363 |
+
m_tem_flag ^= 1;
|
364 |
+
if (t)
|
365 |
+
return 0xD9;
|
366 |
+
else
|
367 |
+
return 0xFF;
|
368 |
+
}
|
369 |
+
}
|
370 |
+
|
371 |
+
uint c = *m_pIn_buf_ofs++;
|
372 |
+
m_in_buf_left--;
|
373 |
+
|
374 |
+
return c;
|
375 |
+
}
|
376 |
+
|
377 |
+
// Same as previous method, except can indicate if the character is a pad character or not.
|
378 |
+
inline uint jpeg_decoder::get_char(bool *pPadding_flag)
|
379 |
+
{
|
380 |
+
if (!m_in_buf_left)
|
381 |
+
{
|
382 |
+
prep_in_buffer();
|
383 |
+
if (!m_in_buf_left)
|
384 |
+
{
|
385 |
+
*pPadding_flag = true;
|
386 |
+
int t = m_tem_flag;
|
387 |
+
m_tem_flag ^= 1;
|
388 |
+
if (t)
|
389 |
+
return 0xD9;
|
390 |
+
else
|
391 |
+
return 0xFF;
|
392 |
+
}
|
393 |
+
}
|
394 |
+
|
395 |
+
*pPadding_flag = false;
|
396 |
+
|
397 |
+
uint c = *m_pIn_buf_ofs++;
|
398 |
+
m_in_buf_left--;
|
399 |
+
|
400 |
+
return c;
|
401 |
+
}
|
402 |
+
|
403 |
+
// Inserts a previously retrieved character back into the input buffer.
|
404 |
+
inline void jpeg_decoder::stuff_char(uint8 q)
|
405 |
+
{
|
406 |
+
*(--m_pIn_buf_ofs) = q;
|
407 |
+
m_in_buf_left++;
|
408 |
+
}
|
409 |
+
|
410 |
+
// Retrieves one character from the input stream, but does not read past markers. Will continue to return 0xFF when a marker is encountered.
|
411 |
+
inline uint8 jpeg_decoder::get_octet()
|
412 |
+
{
|
413 |
+
bool padding_flag;
|
414 |
+
int c = get_char(&padding_flag);
|
415 |
+
|
416 |
+
if (c == 0xFF)
|
417 |
+
{
|
418 |
+
if (padding_flag)
|
419 |
+
return 0xFF;
|
420 |
+
|
421 |
+
c = get_char(&padding_flag);
|
422 |
+
if (padding_flag)
|
423 |
+
{
|
424 |
+
stuff_char(0xFF);
|
425 |
+
return 0xFF;
|
426 |
+
}
|
427 |
+
|
428 |
+
if (c == 0x00)
|
429 |
+
return 0xFF;
|
430 |
+
else
|
431 |
+
{
|
432 |
+
stuff_char(static_cast<uint8>(c));
|
433 |
+
stuff_char(0xFF);
|
434 |
+
return 0xFF;
|
435 |
+
}
|
436 |
+
}
|
437 |
+
|
438 |
+
return static_cast<uint8>(c);
|
439 |
+
}
|
440 |
+
|
441 |
+
// Retrieves a variable number of bits from the input stream. Does not recognize markers.
|
442 |
+
inline uint jpeg_decoder::get_bits(int num_bits)
|
443 |
+
{
|
444 |
+
if (!num_bits)
|
445 |
+
return 0;
|
446 |
+
|
447 |
+
uint i = m_bit_buf >> (32 - num_bits);
|
448 |
+
|
449 |
+
if ((m_bits_left -= num_bits) <= 0)
|
450 |
+
{
|
451 |
+
m_bit_buf <<= (num_bits += m_bits_left);
|
452 |
+
|
453 |
+
uint c1 = get_char();
|
454 |
+
uint c2 = get_char();
|
455 |
+
m_bit_buf = (m_bit_buf & 0xFFFF0000) | (c1 << 8) | c2;
|
456 |
+
|
457 |
+
m_bit_buf <<= -m_bits_left;
|
458 |
+
|
459 |
+
m_bits_left += 16;
|
460 |
+
|
461 |
+
JPGD_ASSERT(m_bits_left >= 0);
|
462 |
+
}
|
463 |
+
else
|
464 |
+
m_bit_buf <<= num_bits;
|
465 |
+
|
466 |
+
return i;
|
467 |
+
}
|
468 |
+
|
469 |
+
// Retrieves a variable number of bits from the input stream. Markers will not be read into the input bit buffer. Instead, an infinite number of all 1's will be returned when a marker is encountered.
|
470 |
+
inline uint jpeg_decoder::get_bits_no_markers(int num_bits)
|
471 |
+
{
|
472 |
+
if (!num_bits)
|
473 |
+
return 0;
|
474 |
+
|
475 |
+
uint i = m_bit_buf >> (32 - num_bits);
|
476 |
+
|
477 |
+
if ((m_bits_left -= num_bits) <= 0)
|
478 |
+
{
|
479 |
+
m_bit_buf <<= (num_bits += m_bits_left);
|
480 |
+
|
481 |
+
if ((m_in_buf_left < 2) || (m_pIn_buf_ofs[0] == 0xFF) || (m_pIn_buf_ofs[1] == 0xFF))
|
482 |
+
{
|
483 |
+
uint c1 = get_octet();
|
484 |
+
uint c2 = get_octet();
|
485 |
+
m_bit_buf |= (c1 << 8) | c2;
|
486 |
+
}
|
487 |
+
else
|
488 |
+
{
|
489 |
+
m_bit_buf |= ((uint)m_pIn_buf_ofs[0] << 8) | m_pIn_buf_ofs[1];
|
490 |
+
m_in_buf_left -= 2;
|
491 |
+
m_pIn_buf_ofs += 2;
|
492 |
+
}
|
493 |
+
|
494 |
+
m_bit_buf <<= -m_bits_left;
|
495 |
+
|
496 |
+
m_bits_left += 16;
|
497 |
+
|
498 |
+
JPGD_ASSERT(m_bits_left >= 0);
|
499 |
+
}
|
500 |
+
else
|
501 |
+
m_bit_buf <<= num_bits;
|
502 |
+
|
503 |
+
return i;
|
504 |
+
}
|
505 |
+
|
506 |
+
// Decodes a Huffman encoded symbol.
|
507 |
+
inline int jpeg_decoder::huff_decode(huff_tables *pH)
|
508 |
+
{
|
509 |
+
int symbol;
|
510 |
+
|
511 |
+
// Check first 8-bits: do we have a complete symbol?
|
512 |
+
if ((symbol = pH->look_up[m_bit_buf >> 24]) < 0)
|
513 |
+
{
|
514 |
+
// Decode more bits, use a tree traversal to find symbol.
|
515 |
+
int ofs = 23;
|
516 |
+
do
|
517 |
+
{
|
518 |
+
symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
|
519 |
+
ofs--;
|
520 |
+
} while (symbol < 0);
|
521 |
+
|
522 |
+
get_bits_no_markers(8 + (23 - ofs));
|
523 |
+
}
|
524 |
+
else
|
525 |
+
get_bits_no_markers(pH->code_size[symbol]);
|
526 |
+
|
527 |
+
return symbol;
|
528 |
+
}
|
529 |
+
|
530 |
+
// Decodes a Huffman encoded symbol.
|
531 |
+
inline int jpeg_decoder::huff_decode(huff_tables *pH, int& extra_bits)
|
532 |
+
{
|
533 |
+
int symbol;
|
534 |
+
|
535 |
+
// Check first 8-bits: do we have a complete symbol?
|
536 |
+
if ((symbol = pH->look_up2[m_bit_buf >> 24]) < 0)
|
537 |
+
{
|
538 |
+
// Use a tree traversal to find symbol.
|
539 |
+
int ofs = 23;
|
540 |
+
do
|
541 |
+
{
|
542 |
+
symbol = pH->tree[-(int)(symbol + ((m_bit_buf >> ofs) & 1))];
|
543 |
+
ofs--;
|
544 |
+
} while (symbol < 0);
|
545 |
+
|
546 |
+
get_bits_no_markers(8 + (23 - ofs));
|
547 |
+
|
548 |
+
extra_bits = get_bits_no_markers(symbol & 0xF);
|
549 |
+
}
|
550 |
+
else
|
551 |
+
{
|
552 |
+
JPGD_ASSERT(((symbol >> 8) & 31) == pH->code_size[symbol & 255] + ((symbol & 0x8000) ? (symbol & 15) : 0));
|
553 |
+
|
554 |
+
if (symbol & 0x8000)
|
555 |
+
{
|
556 |
+
get_bits_no_markers((symbol >> 8) & 31);
|
557 |
+
extra_bits = symbol >> 16;
|
558 |
+
}
|
559 |
+
else
|
560 |
+
{
|
561 |
+
int code_size = (symbol >> 8) & 31;
|
562 |
+
int num_extra_bits = symbol & 0xF;
|
563 |
+
int bits = code_size + num_extra_bits;
|
564 |
+
if (bits <= (m_bits_left + 16))
|
565 |
+
extra_bits = get_bits_no_markers(bits) & ((1 << num_extra_bits) - 1);
|
566 |
+
else
|
567 |
+
{
|
568 |
+
get_bits_no_markers(code_size);
|
569 |
+
extra_bits = get_bits_no_markers(num_extra_bits);
|
570 |
+
}
|
571 |
+
}
|
572 |
+
|
573 |
+
symbol &= 0xFF;
|
574 |
+
}
|
575 |
+
|
576 |
+
return symbol;
|
577 |
+
}
|
578 |
+
|
579 |
+
// Tables and macro used to fully decode the DPCM differences.
|
580 |
+
static const int s_extend_test[16] = { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
|
581 |
+
static const int s_extend_offset[16] = { 0, -1, -3, -7, -15, -31, -63, -127, -255, -511, -1023, -2047, -4095, -8191, -16383, -32767 };
|
582 |
+
static const int s_extend_mask[] = { 0, (1<<0), (1<<1), (1<<2), (1<<3), (1<<4), (1<<5), (1<<6), (1<<7), (1<<8), (1<<9), (1<<10), (1<<11), (1<<12), (1<<13), (1<<14), (1<<15), (1<<16) };
|
583 |
+
#define HUFF_EXTEND(x,s) ((x) < s_extend_test[s] ? (x) + s_extend_offset[s] : (x))
|
584 |
+
|
585 |
+
// Clamps a value between 0-255.
|
586 |
+
inline uint8 jpeg_decoder::clamp(int i)
|
587 |
+
{
|
588 |
+
if (static_cast<uint>(i) > 255)
|
589 |
+
i = (((~i) >> 31) & 0xFF);
|
590 |
+
|
591 |
+
return static_cast<uint8>(i);
|
592 |
+
}
|
593 |
+
|
594 |
+
namespace DCT_Upsample
|
595 |
+
{
|
596 |
+
struct Matrix44
|
597 |
+
{
|
598 |
+
typedef int Element_Type;
|
599 |
+
enum { NUM_ROWS = 4, NUM_COLS = 4 };
|
600 |
+
|
601 |
+
Element_Type v[NUM_ROWS][NUM_COLS];
|
602 |
+
|
603 |
+
inline int rows() const { return NUM_ROWS; }
|
604 |
+
inline int cols() const { return NUM_COLS; }
|
605 |
+
|
606 |
+
inline const Element_Type & at(int r, int c) const { return v[r][c]; }
|
607 |
+
inline Element_Type & at(int r, int c) { return v[r][c]; }
|
608 |
+
|
609 |
+
inline Matrix44() { }
|
610 |
+
|
611 |
+
inline Matrix44& operator += (const Matrix44& a)
|
612 |
+
{
|
613 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
614 |
+
{
|
615 |
+
at(r, 0) += a.at(r, 0);
|
616 |
+
at(r, 1) += a.at(r, 1);
|
617 |
+
at(r, 2) += a.at(r, 2);
|
618 |
+
at(r, 3) += a.at(r, 3);
|
619 |
+
}
|
620 |
+
return *this;
|
621 |
+
}
|
622 |
+
|
623 |
+
inline Matrix44& operator -= (const Matrix44& a)
|
624 |
+
{
|
625 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
626 |
+
{
|
627 |
+
at(r, 0) -= a.at(r, 0);
|
628 |
+
at(r, 1) -= a.at(r, 1);
|
629 |
+
at(r, 2) -= a.at(r, 2);
|
630 |
+
at(r, 3) -= a.at(r, 3);
|
631 |
+
}
|
632 |
+
return *this;
|
633 |
+
}
|
634 |
+
|
635 |
+
friend inline Matrix44 operator + (const Matrix44& a, const Matrix44& b)
|
636 |
+
{
|
637 |
+
Matrix44 ret;
|
638 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
639 |
+
{
|
640 |
+
ret.at(r, 0) = a.at(r, 0) + b.at(r, 0);
|
641 |
+
ret.at(r, 1) = a.at(r, 1) + b.at(r, 1);
|
642 |
+
ret.at(r, 2) = a.at(r, 2) + b.at(r, 2);
|
643 |
+
ret.at(r, 3) = a.at(r, 3) + b.at(r, 3);
|
644 |
+
}
|
645 |
+
return ret;
|
646 |
+
}
|
647 |
+
|
648 |
+
friend inline Matrix44 operator - (const Matrix44& a, const Matrix44& b)
|
649 |
+
{
|
650 |
+
Matrix44 ret;
|
651 |
+
for (int r = 0; r < NUM_ROWS; r++)
|
652 |
+
{
|
653 |
+
ret.at(r, 0) = a.at(r, 0) - b.at(r, 0);
|
654 |
+
ret.at(r, 1) = a.at(r, 1) - b.at(r, 1);
|
655 |
+
ret.at(r, 2) = a.at(r, 2) - b.at(r, 2);
|
656 |
+
ret.at(r, 3) = a.at(r, 3) - b.at(r, 3);
|
657 |
+
}
|
658 |
+
return ret;
|
659 |
+
}
|
660 |
+
|
661 |
+
static inline void add_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b)
|
662 |
+
{
|
663 |
+
for (int r = 0; r < 4; r++)
|
664 |
+
{
|
665 |
+
pDst[0*8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) + b.at(r, 0));
|
666 |
+
pDst[1*8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) + b.at(r, 1));
|
667 |
+
pDst[2*8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) + b.at(r, 2));
|
668 |
+
pDst[3*8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) + b.at(r, 3));
|
669 |
+
}
|
670 |
+
}
|
671 |
+
|
672 |
+
static inline void sub_and_store(jpgd_block_t* pDst, const Matrix44& a, const Matrix44& b)
|
673 |
+
{
|
674 |
+
for (int r = 0; r < 4; r++)
|
675 |
+
{
|
676 |
+
pDst[0*8 + r] = static_cast<jpgd_block_t>(a.at(r, 0) - b.at(r, 0));
|
677 |
+
pDst[1*8 + r] = static_cast<jpgd_block_t>(a.at(r, 1) - b.at(r, 1));
|
678 |
+
pDst[2*8 + r] = static_cast<jpgd_block_t>(a.at(r, 2) - b.at(r, 2));
|
679 |
+
pDst[3*8 + r] = static_cast<jpgd_block_t>(a.at(r, 3) - b.at(r, 3));
|
680 |
+
}
|
681 |
+
}
|
682 |
+
};
|
683 |
+
|
684 |
+
const int FRACT_BITS = 10;
|
685 |
+
const int SCALE = 1 << FRACT_BITS;
|
686 |
+
|
687 |
+
typedef int Temp_Type;
|
688 |
+
#define D(i) (((i) + (SCALE >> 1)) >> FRACT_BITS)
|
689 |
+
#define F(i) ((int)((i) * SCALE + .5f))
|
690 |
+
|
691 |
+
// Any decent C++ compiler will optimize this at compile time to a 0, or an array access.
|
692 |
+
#define AT(c, r) ((((c)>=NUM_COLS)||((r)>=NUM_ROWS)) ? 0 : pSrc[(c)+(r)*8])
|
693 |
+
|
694 |
+
// NUM_ROWS/NUM_COLS = # of non-zero rows/cols in input matrix
|
695 |
+
template<int NUM_ROWS, int NUM_COLS>
|
696 |
+
struct P_Q
|
697 |
+
{
|
698 |
+
static void calc(Matrix44& P, Matrix44& Q, const jpgd_block_t* pSrc)
|
699 |
+
{
|
700 |
+
// 4x8 = 4x8 times 8x8, matrix 0 is constant
|
701 |
+
const Temp_Type X000 = AT(0, 0);
|
702 |
+
const Temp_Type X001 = AT(0, 1);
|
703 |
+
const Temp_Type X002 = AT(0, 2);
|
704 |
+
const Temp_Type X003 = AT(0, 3);
|
705 |
+
const Temp_Type X004 = AT(0, 4);
|
706 |
+
const Temp_Type X005 = AT(0, 5);
|
707 |
+
const Temp_Type X006 = AT(0, 6);
|
708 |
+
const Temp_Type X007 = AT(0, 7);
|
709 |
+
const Temp_Type X010 = D(F(0.415735f) * AT(1, 0) + F(0.791065f) * AT(3, 0) + F(-0.352443f) * AT(5, 0) + F(0.277785f) * AT(7, 0));
|
710 |
+
const Temp_Type X011 = D(F(0.415735f) * AT(1, 1) + F(0.791065f) * AT(3, 1) + F(-0.352443f) * AT(5, 1) + F(0.277785f) * AT(7, 1));
|
711 |
+
const Temp_Type X012 = D(F(0.415735f) * AT(1, 2) + F(0.791065f) * AT(3, 2) + F(-0.352443f) * AT(5, 2) + F(0.277785f) * AT(7, 2));
|
712 |
+
const Temp_Type X013 = D(F(0.415735f) * AT(1, 3) + F(0.791065f) * AT(3, 3) + F(-0.352443f) * AT(5, 3) + F(0.277785f) * AT(7, 3));
|
713 |
+
const Temp_Type X014 = D(F(0.415735f) * AT(1, 4) + F(0.791065f) * AT(3, 4) + F(-0.352443f) * AT(5, 4) + F(0.277785f) * AT(7, 4));
|
714 |
+
const Temp_Type X015 = D(F(0.415735f) * AT(1, 5) + F(0.791065f) * AT(3, 5) + F(-0.352443f) * AT(5, 5) + F(0.277785f) * AT(7, 5));
|
715 |
+
const Temp_Type X016 = D(F(0.415735f) * AT(1, 6) + F(0.791065f) * AT(3, 6) + F(-0.352443f) * AT(5, 6) + F(0.277785f) * AT(7, 6));
|
716 |
+
const Temp_Type X017 = D(F(0.415735f) * AT(1, 7) + F(0.791065f) * AT(3, 7) + F(-0.352443f) * AT(5, 7) + F(0.277785f) * AT(7, 7));
|
717 |
+
const Temp_Type X020 = AT(4, 0);
|
718 |
+
const Temp_Type X021 = AT(4, 1);
|
719 |
+
const Temp_Type X022 = AT(4, 2);
|
720 |
+
const Temp_Type X023 = AT(4, 3);
|
721 |
+
const Temp_Type X024 = AT(4, 4);
|
722 |
+
const Temp_Type X025 = AT(4, 5);
|
723 |
+
const Temp_Type X026 = AT(4, 6);
|
724 |
+
const Temp_Type X027 = AT(4, 7);
|
725 |
+
const Temp_Type X030 = D(F(0.022887f) * AT(1, 0) + F(-0.097545f) * AT(3, 0) + F(0.490393f) * AT(5, 0) + F(0.865723f) * AT(7, 0));
|
726 |
+
const Temp_Type X031 = D(F(0.022887f) * AT(1, 1) + F(-0.097545f) * AT(3, 1) + F(0.490393f) * AT(5, 1) + F(0.865723f) * AT(7, 1));
|
727 |
+
const Temp_Type X032 = D(F(0.022887f) * AT(1, 2) + F(-0.097545f) * AT(3, 2) + F(0.490393f) * AT(5, 2) + F(0.865723f) * AT(7, 2));
|
728 |
+
const Temp_Type X033 = D(F(0.022887f) * AT(1, 3) + F(-0.097545f) * AT(3, 3) + F(0.490393f) * AT(5, 3) + F(0.865723f) * AT(7, 3));
|
729 |
+
const Temp_Type X034 = D(F(0.022887f) * AT(1, 4) + F(-0.097545f) * AT(3, 4) + F(0.490393f) * AT(5, 4) + F(0.865723f) * AT(7, 4));
|
730 |
+
const Temp_Type X035 = D(F(0.022887f) * AT(1, 5) + F(-0.097545f) * AT(3, 5) + F(0.490393f) * AT(5, 5) + F(0.865723f) * AT(7, 5));
|
731 |
+
const Temp_Type X036 = D(F(0.022887f) * AT(1, 6) + F(-0.097545f) * AT(3, 6) + F(0.490393f) * AT(5, 6) + F(0.865723f) * AT(7, 6));
|
732 |
+
const Temp_Type X037 = D(F(0.022887f) * AT(1, 7) + F(-0.097545f) * AT(3, 7) + F(0.490393f) * AT(5, 7) + F(0.865723f) * AT(7, 7));
|
733 |
+
|
734 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
735 |
+
P.at(0, 0) = X000;
|
736 |
+
P.at(0, 1) = D(X001 * F(0.415735f) + X003 * F(0.791065f) + X005 * F(-0.352443f) + X007 * F(0.277785f));
|
737 |
+
P.at(0, 2) = X004;
|
738 |
+
P.at(0, 3) = D(X001 * F(0.022887f) + X003 * F(-0.097545f) + X005 * F(0.490393f) + X007 * F(0.865723f));
|
739 |
+
P.at(1, 0) = X010;
|
740 |
+
P.at(1, 1) = D(X011 * F(0.415735f) + X013 * F(0.791065f) + X015 * F(-0.352443f) + X017 * F(0.277785f));
|
741 |
+
P.at(1, 2) = X014;
|
742 |
+
P.at(1, 3) = D(X011 * F(0.022887f) + X013 * F(-0.097545f) + X015 * F(0.490393f) + X017 * F(0.865723f));
|
743 |
+
P.at(2, 0) = X020;
|
744 |
+
P.at(2, 1) = D(X021 * F(0.415735f) + X023 * F(0.791065f) + X025 * F(-0.352443f) + X027 * F(0.277785f));
|
745 |
+
P.at(2, 2) = X024;
|
746 |
+
P.at(2, 3) = D(X021 * F(0.022887f) + X023 * F(-0.097545f) + X025 * F(0.490393f) + X027 * F(0.865723f));
|
747 |
+
P.at(3, 0) = X030;
|
748 |
+
P.at(3, 1) = D(X031 * F(0.415735f) + X033 * F(0.791065f) + X035 * F(-0.352443f) + X037 * F(0.277785f));
|
749 |
+
P.at(3, 2) = X034;
|
750 |
+
P.at(3, 3) = D(X031 * F(0.022887f) + X033 * F(-0.097545f) + X035 * F(0.490393f) + X037 * F(0.865723f));
|
751 |
+
// 40 muls 24 adds
|
752 |
+
|
753 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
754 |
+
Q.at(0, 0) = D(X001 * F(0.906127f) + X003 * F(-0.318190f) + X005 * F(0.212608f) + X007 * F(-0.180240f));
|
755 |
+
Q.at(0, 1) = X002;
|
756 |
+
Q.at(0, 2) = D(X001 * F(-0.074658f) + X003 * F(0.513280f) + X005 * F(0.768178f) + X007 * F(-0.375330f));
|
757 |
+
Q.at(0, 3) = X006;
|
758 |
+
Q.at(1, 0) = D(X011 * F(0.906127f) + X013 * F(-0.318190f) + X015 * F(0.212608f) + X017 * F(-0.180240f));
|
759 |
+
Q.at(1, 1) = X012;
|
760 |
+
Q.at(1, 2) = D(X011 * F(-0.074658f) + X013 * F(0.513280f) + X015 * F(0.768178f) + X017 * F(-0.375330f));
|
761 |
+
Q.at(1, 3) = X016;
|
762 |
+
Q.at(2, 0) = D(X021 * F(0.906127f) + X023 * F(-0.318190f) + X025 * F(0.212608f) + X027 * F(-0.180240f));
|
763 |
+
Q.at(2, 1) = X022;
|
764 |
+
Q.at(2, 2) = D(X021 * F(-0.074658f) + X023 * F(0.513280f) + X025 * F(0.768178f) + X027 * F(-0.375330f));
|
765 |
+
Q.at(2, 3) = X026;
|
766 |
+
Q.at(3, 0) = D(X031 * F(0.906127f) + X033 * F(-0.318190f) + X035 * F(0.212608f) + X037 * F(-0.180240f));
|
767 |
+
Q.at(3, 1) = X032;
|
768 |
+
Q.at(3, 2) = D(X031 * F(-0.074658f) + X033 * F(0.513280f) + X035 * F(0.768178f) + X037 * F(-0.375330f));
|
769 |
+
Q.at(3, 3) = X036;
|
770 |
+
// 40 muls 24 adds
|
771 |
+
}
|
772 |
+
};
|
773 |
+
|
774 |
+
template<int NUM_ROWS, int NUM_COLS>
|
775 |
+
struct R_S
|
776 |
+
{
|
777 |
+
static void calc(Matrix44& R, Matrix44& S, const jpgd_block_t* pSrc)
|
778 |
+
{
|
779 |
+
// 4x8 = 4x8 times 8x8, matrix 0 is constant
|
780 |
+
const Temp_Type X100 = D(F(0.906127f) * AT(1, 0) + F(-0.318190f) * AT(3, 0) + F(0.212608f) * AT(5, 0) + F(-0.180240f) * AT(7, 0));
|
781 |
+
const Temp_Type X101 = D(F(0.906127f) * AT(1, 1) + F(-0.318190f) * AT(3, 1) + F(0.212608f) * AT(5, 1) + F(-0.180240f) * AT(7, 1));
|
782 |
+
const Temp_Type X102 = D(F(0.906127f) * AT(1, 2) + F(-0.318190f) * AT(3, 2) + F(0.212608f) * AT(5, 2) + F(-0.180240f) * AT(7, 2));
|
783 |
+
const Temp_Type X103 = D(F(0.906127f) * AT(1, 3) + F(-0.318190f) * AT(3, 3) + F(0.212608f) * AT(5, 3) + F(-0.180240f) * AT(7, 3));
|
784 |
+
const Temp_Type X104 = D(F(0.906127f) * AT(1, 4) + F(-0.318190f) * AT(3, 4) + F(0.212608f) * AT(5, 4) + F(-0.180240f) * AT(7, 4));
|
785 |
+
const Temp_Type X105 = D(F(0.906127f) * AT(1, 5) + F(-0.318190f) * AT(3, 5) + F(0.212608f) * AT(5, 5) + F(-0.180240f) * AT(7, 5));
|
786 |
+
const Temp_Type X106 = D(F(0.906127f) * AT(1, 6) + F(-0.318190f) * AT(3, 6) + F(0.212608f) * AT(5, 6) + F(-0.180240f) * AT(7, 6));
|
787 |
+
const Temp_Type X107 = D(F(0.906127f) * AT(1, 7) + F(-0.318190f) * AT(3, 7) + F(0.212608f) * AT(5, 7) + F(-0.180240f) * AT(7, 7));
|
788 |
+
const Temp_Type X110 = AT(2, 0);
|
789 |
+
const Temp_Type X111 = AT(2, 1);
|
790 |
+
const Temp_Type X112 = AT(2, 2);
|
791 |
+
const Temp_Type X113 = AT(2, 3);
|
792 |
+
const Temp_Type X114 = AT(2, 4);
|
793 |
+
const Temp_Type X115 = AT(2, 5);
|
794 |
+
const Temp_Type X116 = AT(2, 6);
|
795 |
+
const Temp_Type X117 = AT(2, 7);
|
796 |
+
const Temp_Type X120 = D(F(-0.074658f) * AT(1, 0) + F(0.513280f) * AT(3, 0) + F(0.768178f) * AT(5, 0) + F(-0.375330f) * AT(7, 0));
|
797 |
+
const Temp_Type X121 = D(F(-0.074658f) * AT(1, 1) + F(0.513280f) * AT(3, 1) + F(0.768178f) * AT(5, 1) + F(-0.375330f) * AT(7, 1));
|
798 |
+
const Temp_Type X122 = D(F(-0.074658f) * AT(1, 2) + F(0.513280f) * AT(3, 2) + F(0.768178f) * AT(5, 2) + F(-0.375330f) * AT(7, 2));
|
799 |
+
const Temp_Type X123 = D(F(-0.074658f) * AT(1, 3) + F(0.513280f) * AT(3, 3) + F(0.768178f) * AT(5, 3) + F(-0.375330f) * AT(7, 3));
|
800 |
+
const Temp_Type X124 = D(F(-0.074658f) * AT(1, 4) + F(0.513280f) * AT(3, 4) + F(0.768178f) * AT(5, 4) + F(-0.375330f) * AT(7, 4));
|
801 |
+
const Temp_Type X125 = D(F(-0.074658f) * AT(1, 5) + F(0.513280f) * AT(3, 5) + F(0.768178f) * AT(5, 5) + F(-0.375330f) * AT(7, 5));
|
802 |
+
const Temp_Type X126 = D(F(-0.074658f) * AT(1, 6) + F(0.513280f) * AT(3, 6) + F(0.768178f) * AT(5, 6) + F(-0.375330f) * AT(7, 6));
|
803 |
+
const Temp_Type X127 = D(F(-0.074658f) * AT(1, 7) + F(0.513280f) * AT(3, 7) + F(0.768178f) * AT(5, 7) + F(-0.375330f) * AT(7, 7));
|
804 |
+
const Temp_Type X130 = AT(6, 0);
|
805 |
+
const Temp_Type X131 = AT(6, 1);
|
806 |
+
const Temp_Type X132 = AT(6, 2);
|
807 |
+
const Temp_Type X133 = AT(6, 3);
|
808 |
+
const Temp_Type X134 = AT(6, 4);
|
809 |
+
const Temp_Type X135 = AT(6, 5);
|
810 |
+
const Temp_Type X136 = AT(6, 6);
|
811 |
+
const Temp_Type X137 = AT(6, 7);
|
812 |
+
// 80 muls 48 adds
|
813 |
+
|
814 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
815 |
+
R.at(0, 0) = X100;
|
816 |
+
R.at(0, 1) = D(X101 * F(0.415735f) + X103 * F(0.791065f) + X105 * F(-0.352443f) + X107 * F(0.277785f));
|
817 |
+
R.at(0, 2) = X104;
|
818 |
+
R.at(0, 3) = D(X101 * F(0.022887f) + X103 * F(-0.097545f) + X105 * F(0.490393f) + X107 * F(0.865723f));
|
819 |
+
R.at(1, 0) = X110;
|
820 |
+
R.at(1, 1) = D(X111 * F(0.415735f) + X113 * F(0.791065f) + X115 * F(-0.352443f) + X117 * F(0.277785f));
|
821 |
+
R.at(1, 2) = X114;
|
822 |
+
R.at(1, 3) = D(X111 * F(0.022887f) + X113 * F(-0.097545f) + X115 * F(0.490393f) + X117 * F(0.865723f));
|
823 |
+
R.at(2, 0) = X120;
|
824 |
+
R.at(2, 1) = D(X121 * F(0.415735f) + X123 * F(0.791065f) + X125 * F(-0.352443f) + X127 * F(0.277785f));
|
825 |
+
R.at(2, 2) = X124;
|
826 |
+
R.at(2, 3) = D(X121 * F(0.022887f) + X123 * F(-0.097545f) + X125 * F(0.490393f) + X127 * F(0.865723f));
|
827 |
+
R.at(3, 0) = X130;
|
828 |
+
R.at(3, 1) = D(X131 * F(0.415735f) + X133 * F(0.791065f) + X135 * F(-0.352443f) + X137 * F(0.277785f));
|
829 |
+
R.at(3, 2) = X134;
|
830 |
+
R.at(3, 3) = D(X131 * F(0.022887f) + X133 * F(-0.097545f) + X135 * F(0.490393f) + X137 * F(0.865723f));
|
831 |
+
// 40 muls 24 adds
|
832 |
+
// 4x4 = 4x8 times 8x4, matrix 1 is constant
|
833 |
+
S.at(0, 0) = D(X101 * F(0.906127f) + X103 * F(-0.318190f) + X105 * F(0.212608f) + X107 * F(-0.180240f));
|
834 |
+
S.at(0, 1) = X102;
|
835 |
+
S.at(0, 2) = D(X101 * F(-0.074658f) + X103 * F(0.513280f) + X105 * F(0.768178f) + X107 * F(-0.375330f));
|
836 |
+
S.at(0, 3) = X106;
|
837 |
+
S.at(1, 0) = D(X111 * F(0.906127f) + X113 * F(-0.318190f) + X115 * F(0.212608f) + X117 * F(-0.180240f));
|
838 |
+
S.at(1, 1) = X112;
|
839 |
+
S.at(1, 2) = D(X111 * F(-0.074658f) + X113 * F(0.513280f) + X115 * F(0.768178f) + X117 * F(-0.375330f));
|
840 |
+
S.at(1, 3) = X116;
|
841 |
+
S.at(2, 0) = D(X121 * F(0.906127f) + X123 * F(-0.318190f) + X125 * F(0.212608f) + X127 * F(-0.180240f));
|
842 |
+
S.at(2, 1) = X122;
|
843 |
+
S.at(2, 2) = D(X121 * F(-0.074658f) + X123 * F(0.513280f) + X125 * F(0.768178f) + X127 * F(-0.375330f));
|
844 |
+
S.at(2, 3) = X126;
|
845 |
+
S.at(3, 0) = D(X131 * F(0.906127f) + X133 * F(-0.318190f) + X135 * F(0.212608f) + X137 * F(-0.180240f));
|
846 |
+
S.at(3, 1) = X132;
|
847 |
+
S.at(3, 2) = D(X131 * F(-0.074658f) + X133 * F(0.513280f) + X135 * F(0.768178f) + X137 * F(-0.375330f));
|
848 |
+
S.at(3, 3) = X136;
|
849 |
+
// 40 muls 24 adds
|
850 |
+
}
|
851 |
+
};
|
852 |
+
} // end namespace DCT_Upsample
|
853 |
+
|
854 |
+
// Unconditionally frees all allocated m_blocks.
|
855 |
+
void jpeg_decoder::free_all_blocks()
|
856 |
+
{
|
857 |
+
m_pStream = NULL;
|
858 |
+
for (mem_block *b = m_pMem_blocks; b; )
|
859 |
+
{
|
860 |
+
mem_block *n = b->m_pNext;
|
861 |
+
jpgd_free(b);
|
862 |
+
b = n;
|
863 |
+
}
|
864 |
+
m_pMem_blocks = NULL;
|
865 |
+
}
|
866 |
+
|
867 |
+
// This method handles all errors.
|
868 |
+
// It could easily be changed to use C++ exceptions.
|
869 |
+
void jpeg_decoder::stop_decoding(jpgd_status status)
|
870 |
+
{
|
871 |
+
m_error_code = status;
|
872 |
+
free_all_blocks();
|
873 |
+
longjmp(m_jmp_state, status);
|
874 |
+
|
875 |
+
// we shouldn't get here as longjmp shouldn't return, but we put it here to make it explicit
|
876 |
+
// that this function doesn't return, otherwise we get this error:
|
877 |
+
//
|
878 |
+
// error : function declared 'noreturn' should not return
|
879 |
+
exit(1);
|
880 |
+
}
|
881 |
+
|
882 |
+
void *jpeg_decoder::alloc(size_t nSize, bool zero)
|
883 |
+
{
|
884 |
+
nSize = (JPGD_MAX(nSize, 1) + 3) & ~3;
|
885 |
+
char *rv = NULL;
|
886 |
+
for (mem_block *b = m_pMem_blocks; b; b = b->m_pNext)
|
887 |
+
{
|
888 |
+
if ((b->m_used_count + nSize) <= b->m_size)
|
889 |
+
{
|
890 |
+
rv = b->m_data + b->m_used_count;
|
891 |
+
b->m_used_count += nSize;
|
892 |
+
break;
|
893 |
+
}
|
894 |
+
}
|
895 |
+
if (!rv)
|
896 |
+
{
|
897 |
+
int capacity = JPGD_MAX(32768 - 256, (nSize + 2047) & ~2047);
|
898 |
+
mem_block *b = (mem_block*)jpgd_malloc(sizeof(mem_block) + capacity);
|
899 |
+
if (!b) stop_decoding(JPGD_NOTENOUGHMEM);
|
900 |
+
b->m_pNext = m_pMem_blocks; m_pMem_blocks = b;
|
901 |
+
b->m_used_count = nSize;
|
902 |
+
b->m_size = capacity;
|
903 |
+
rv = b->m_data;
|
904 |
+
}
|
905 |
+
if (zero) memset(rv, 0, nSize);
|
906 |
+
return rv;
|
907 |
+
}
|
908 |
+
|
909 |
+
void jpeg_decoder::word_clear(void *p, uint16 c, uint n)
|
910 |
+
{
|
911 |
+
uint8 *pD = (uint8*)p;
|
912 |
+
const uint8 l = c & 0xFF, h = (c >> 8) & 0xFF;
|
913 |
+
while (n)
|
914 |
+
{
|
915 |
+
pD[0] = l; pD[1] = h; pD += 2;
|
916 |
+
n--;
|
917 |
+
}
|
918 |
+
}
|
919 |
+
|
920 |
+
// Refill the input buffer.
|
921 |
+
// This method will sit in a loop until (A) the buffer is full or (B)
|
922 |
+
// the stream's read() method reports and end of file condition.
|
923 |
+
void jpeg_decoder::prep_in_buffer()
|
924 |
+
{
|
925 |
+
m_in_buf_left = 0;
|
926 |
+
m_pIn_buf_ofs = m_in_buf;
|
927 |
+
|
928 |
+
if (m_eof_flag)
|
929 |
+
return;
|
930 |
+
|
931 |
+
do
|
932 |
+
{
|
933 |
+
int bytes_read = m_pStream->read(m_in_buf + m_in_buf_left, JPGD_IN_BUF_SIZE - m_in_buf_left, &m_eof_flag);
|
934 |
+
if (bytes_read == -1)
|
935 |
+
stop_decoding(JPGD_STREAM_READ);
|
936 |
+
|
937 |
+
m_in_buf_left += bytes_read;
|
938 |
+
} while ((m_in_buf_left < JPGD_IN_BUF_SIZE) && (!m_eof_flag));
|
939 |
+
|
940 |
+
m_total_bytes_read += m_in_buf_left;
|
941 |
+
|
942 |
+
// Pad the end of the block with M_EOI (prevents the decompressor from going off the rails if the stream is invalid).
|
943 |
+
// (This dates way back to when this decompressor was written in C/asm, and the all-asm Huffman decoder did some fancy things to increase perf.)
|
944 |
+
word_clear(m_pIn_buf_ofs + m_in_buf_left, 0xD9FF, 64);
|
945 |
+
}
|
946 |
+
|
947 |
+
// Read a Huffman code table.
|
948 |
+
void jpeg_decoder::read_dht_marker()
|
949 |
+
{
|
950 |
+
int i, index, count;
|
951 |
+
uint8 huff_num[17];
|
952 |
+
uint8 huff_val[256];
|
953 |
+
|
954 |
+
uint num_left = get_bits(16);
|
955 |
+
|
956 |
+
if (num_left < 2)
|
957 |
+
stop_decoding(JPGD_BAD_DHT_MARKER);
|
958 |
+
|
959 |
+
num_left -= 2;
|
960 |
+
|
961 |
+
while (num_left)
|
962 |
+
{
|
963 |
+
index = get_bits(8);
|
964 |
+
|
965 |
+
huff_num[0] = 0;
|
966 |
+
|
967 |
+
count = 0;
|
968 |
+
|
969 |
+
for (i = 1; i <= 16; i++)
|
970 |
+
{
|
971 |
+
huff_num[i] = static_cast<uint8>(get_bits(8));
|
972 |
+
count += huff_num[i];
|
973 |
+
}
|
974 |
+
|
975 |
+
if (count > 255)
|
976 |
+
stop_decoding(JPGD_BAD_DHT_COUNTS);
|
977 |
+
|
978 |
+
for (i = 0; i < count; i++)
|
979 |
+
huff_val[i] = static_cast<uint8>(get_bits(8));
|
980 |
+
|
981 |
+
i = 1 + 16 + count;
|
982 |
+
|
983 |
+
if (num_left < (uint)i)
|
984 |
+
stop_decoding(JPGD_BAD_DHT_MARKER);
|
985 |
+
|
986 |
+
num_left -= i;
|
987 |
+
|
988 |
+
if ((index & 0x10) > 0x10)
|
989 |
+
stop_decoding(JPGD_BAD_DHT_INDEX);
|
990 |
+
|
991 |
+
index = (index & 0x0F) + ((index & 0x10) >> 4) * (JPGD_MAX_HUFF_TABLES >> 1);
|
992 |
+
|
993 |
+
if (index >= JPGD_MAX_HUFF_TABLES)
|
994 |
+
stop_decoding(JPGD_BAD_DHT_INDEX);
|
995 |
+
|
996 |
+
if (!m_huff_num[index])
|
997 |
+
m_huff_num[index] = (uint8 *)alloc(17);
|
998 |
+
|
999 |
+
if (!m_huff_val[index])
|
1000 |
+
m_huff_val[index] = (uint8 *)alloc(256);
|
1001 |
+
|
1002 |
+
m_huff_ac[index] = (index & 0x10) != 0;
|
1003 |
+
memcpy(m_huff_num[index], huff_num, 17);
|
1004 |
+
memcpy(m_huff_val[index], huff_val, 256);
|
1005 |
+
}
|
1006 |
+
}
|
1007 |
+
|
1008 |
+
// Read a quantization table.
|
1009 |
+
void jpeg_decoder::read_dqt_marker()
|
1010 |
+
{
|
1011 |
+
int n, i, prec;
|
1012 |
+
uint num_left;
|
1013 |
+
uint temp;
|
1014 |
+
|
1015 |
+
num_left = get_bits(16);
|
1016 |
+
|
1017 |
+
if (num_left < 2)
|
1018 |
+
stop_decoding(JPGD_BAD_DQT_MARKER);
|
1019 |
+
|
1020 |
+
num_left -= 2;
|
1021 |
+
|
1022 |
+
while (num_left)
|
1023 |
+
{
|
1024 |
+
n = get_bits(8);
|
1025 |
+
prec = n >> 4;
|
1026 |
+
n &= 0x0F;
|
1027 |
+
|
1028 |
+
if (n >= JPGD_MAX_QUANT_TABLES)
|
1029 |
+
stop_decoding(JPGD_BAD_DQT_TABLE);
|
1030 |
+
|
1031 |
+
if (!m_quant[n])
|
1032 |
+
m_quant[n] = (jpgd_quant_t *)alloc(64 * sizeof(jpgd_quant_t));
|
1033 |
+
|
1034 |
+
// read quantization entries, in zag order
|
1035 |
+
for (i = 0; i < 64; i++)
|
1036 |
+
{
|
1037 |
+
temp = get_bits(8);
|
1038 |
+
|
1039 |
+
if (prec)
|
1040 |
+
temp = (temp << 8) + get_bits(8);
|
1041 |
+
|
1042 |
+
m_quant[n][i] = static_cast<jpgd_quant_t>(temp);
|
1043 |
+
}
|
1044 |
+
|
1045 |
+
i = 64 + 1;
|
1046 |
+
|
1047 |
+
if (prec)
|
1048 |
+
i += 64;
|
1049 |
+
|
1050 |
+
if (num_left < (uint)i)
|
1051 |
+
stop_decoding(JPGD_BAD_DQT_LENGTH);
|
1052 |
+
|
1053 |
+
num_left -= i;
|
1054 |
+
}
|
1055 |
+
}
|
1056 |
+
|
1057 |
+
// Read the start of frame (SOF) marker.
|
1058 |
+
void jpeg_decoder::read_sof_marker()
|
1059 |
+
{
|
1060 |
+
int i;
|
1061 |
+
uint num_left;
|
1062 |
+
|
1063 |
+
num_left = get_bits(16);
|
1064 |
+
|
1065 |
+
if (get_bits(8) != 8) /* precision: sorry, only 8-bit precision is supported right now */
|
1066 |
+
stop_decoding(JPGD_BAD_PRECISION);
|
1067 |
+
|
1068 |
+
m_image_y_size = get_bits(16);
|
1069 |
+
|
1070 |
+
if ((m_image_y_size < 1) || (m_image_y_size > JPGD_MAX_HEIGHT))
|
1071 |
+
stop_decoding(JPGD_BAD_HEIGHT);
|
1072 |
+
|
1073 |
+
m_image_x_size = get_bits(16);
|
1074 |
+
|
1075 |
+
if ((m_image_x_size < 1) || (m_image_x_size > JPGD_MAX_WIDTH))
|
1076 |
+
stop_decoding(JPGD_BAD_WIDTH);
|
1077 |
+
|
1078 |
+
m_comps_in_frame = get_bits(8);
|
1079 |
+
|
1080 |
+
if (m_comps_in_frame > JPGD_MAX_COMPONENTS)
|
1081 |
+
stop_decoding(JPGD_TOO_MANY_COMPONENTS);
|
1082 |
+
|
1083 |
+
if (num_left != (uint)(m_comps_in_frame * 3 + 8))
|
1084 |
+
stop_decoding(JPGD_BAD_SOF_LENGTH);
|
1085 |
+
|
1086 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
1087 |
+
{
|
1088 |
+
m_comp_ident[i] = get_bits(8);
|
1089 |
+
m_comp_h_samp[i] = get_bits(4);
|
1090 |
+
m_comp_v_samp[i] = get_bits(4);
|
1091 |
+
m_comp_quant[i] = get_bits(8);
|
1092 |
+
}
|
1093 |
+
}
|
1094 |
+
|
1095 |
+
// Used to skip unrecognized markers.
|
1096 |
+
void jpeg_decoder::skip_variable_marker()
|
1097 |
+
{
|
1098 |
+
uint num_left;
|
1099 |
+
|
1100 |
+
num_left = get_bits(16);
|
1101 |
+
|
1102 |
+
if (num_left < 2)
|
1103 |
+
stop_decoding(JPGD_BAD_VARIABLE_MARKER);
|
1104 |
+
|
1105 |
+
num_left -= 2;
|
1106 |
+
|
1107 |
+
while (num_left)
|
1108 |
+
{
|
1109 |
+
get_bits(8);
|
1110 |
+
num_left--;
|
1111 |
+
}
|
1112 |
+
}
|
1113 |
+
|
1114 |
+
// Read a define restart interval (DRI) marker.
|
1115 |
+
void jpeg_decoder::read_dri_marker()
|
1116 |
+
{
|
1117 |
+
if (get_bits(16) != 4)
|
1118 |
+
stop_decoding(JPGD_BAD_DRI_LENGTH);
|
1119 |
+
|
1120 |
+
m_restart_interval = get_bits(16);
|
1121 |
+
}
|
1122 |
+
|
1123 |
+
// Read a start of scan (SOS) marker.
|
1124 |
+
void jpeg_decoder::read_sos_marker()
|
1125 |
+
{
|
1126 |
+
uint num_left;
|
1127 |
+
int i, ci, n, c, cc;
|
1128 |
+
|
1129 |
+
num_left = get_bits(16);
|
1130 |
+
|
1131 |
+
n = get_bits(8);
|
1132 |
+
|
1133 |
+
m_comps_in_scan = n;
|
1134 |
+
|
1135 |
+
num_left -= 3;
|
1136 |
+
|
1137 |
+
if ( (num_left != (uint)(n * 2 + 3)) || (n < 1) || (n > JPGD_MAX_COMPS_IN_SCAN) )
|
1138 |
+
stop_decoding(JPGD_BAD_SOS_LENGTH);
|
1139 |
+
|
1140 |
+
for (i = 0; i < n; i++)
|
1141 |
+
{
|
1142 |
+
cc = get_bits(8);
|
1143 |
+
c = get_bits(8);
|
1144 |
+
num_left -= 2;
|
1145 |
+
|
1146 |
+
for (ci = 0; ci < m_comps_in_frame; ci++)
|
1147 |
+
if (cc == m_comp_ident[ci])
|
1148 |
+
break;
|
1149 |
+
|
1150 |
+
if (ci >= m_comps_in_frame)
|
1151 |
+
stop_decoding(JPGD_BAD_SOS_COMP_ID);
|
1152 |
+
|
1153 |
+
m_comp_list[i] = ci;
|
1154 |
+
m_comp_dc_tab[ci] = (c >> 4) & 15;
|
1155 |
+
m_comp_ac_tab[ci] = (c & 15) + (JPGD_MAX_HUFF_TABLES >> 1);
|
1156 |
+
}
|
1157 |
+
|
1158 |
+
m_spectral_start = get_bits(8);
|
1159 |
+
m_spectral_end = get_bits(8);
|
1160 |
+
m_successive_high = get_bits(4);
|
1161 |
+
m_successive_low = get_bits(4);
|
1162 |
+
|
1163 |
+
if (!m_progressive_flag)
|
1164 |
+
{
|
1165 |
+
m_spectral_start = 0;
|
1166 |
+
m_spectral_end = 63;
|
1167 |
+
}
|
1168 |
+
|
1169 |
+
num_left -= 3;
|
1170 |
+
|
1171 |
+
while (num_left) /* read past whatever is num_left */
|
1172 |
+
{
|
1173 |
+
get_bits(8);
|
1174 |
+
num_left--;
|
1175 |
+
}
|
1176 |
+
}
|
1177 |
+
|
1178 |
+
// Finds the next marker.
|
1179 |
+
int jpeg_decoder::next_marker()
|
1180 |
+
{
|
1181 |
+
uint c, bytes;
|
1182 |
+
|
1183 |
+
bytes = 0;
|
1184 |
+
|
1185 |
+
do
|
1186 |
+
{
|
1187 |
+
do
|
1188 |
+
{
|
1189 |
+
bytes++;
|
1190 |
+
c = get_bits(8);
|
1191 |
+
} while (c != 0xFF);
|
1192 |
+
|
1193 |
+
do
|
1194 |
+
{
|
1195 |
+
c = get_bits(8);
|
1196 |
+
} while (c == 0xFF);
|
1197 |
+
|
1198 |
+
} while (c == 0);
|
1199 |
+
|
1200 |
+
// If bytes > 0 here, there where extra bytes before the marker (not good).
|
1201 |
+
|
1202 |
+
return c;
|
1203 |
+
}
|
1204 |
+
|
1205 |
+
// Process markers. Returns when an SOFx, SOI, EOI, or SOS marker is
|
1206 |
+
// encountered.
|
1207 |
+
int jpeg_decoder::process_markers()
|
1208 |
+
{
|
1209 |
+
int c;
|
1210 |
+
|
1211 |
+
for ( ; ; )
|
1212 |
+
{
|
1213 |
+
c = next_marker();
|
1214 |
+
|
1215 |
+
switch (c)
|
1216 |
+
{
|
1217 |
+
case M_SOF0:
|
1218 |
+
case M_SOF1:
|
1219 |
+
case M_SOF2:
|
1220 |
+
case M_SOF3:
|
1221 |
+
case M_SOF5:
|
1222 |
+
case M_SOF6:
|
1223 |
+
case M_SOF7:
|
1224 |
+
// case M_JPG:
|
1225 |
+
case M_SOF9:
|
1226 |
+
case M_SOF10:
|
1227 |
+
case M_SOF11:
|
1228 |
+
case M_SOF13:
|
1229 |
+
case M_SOF14:
|
1230 |
+
case M_SOF15:
|
1231 |
+
case M_SOI:
|
1232 |
+
case M_EOI:
|
1233 |
+
case M_SOS:
|
1234 |
+
{
|
1235 |
+
return c;
|
1236 |
+
}
|
1237 |
+
case M_DHT:
|
1238 |
+
{
|
1239 |
+
read_dht_marker();
|
1240 |
+
break;
|
1241 |
+
}
|
1242 |
+
// No arithmitic support - dumb patents!
|
1243 |
+
case M_DAC:
|
1244 |
+
{
|
1245 |
+
stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
|
1246 |
+
break;
|
1247 |
+
}
|
1248 |
+
case M_DQT:
|
1249 |
+
{
|
1250 |
+
read_dqt_marker();
|
1251 |
+
break;
|
1252 |
+
}
|
1253 |
+
case M_DRI:
|
1254 |
+
{
|
1255 |
+
read_dri_marker();
|
1256 |
+
break;
|
1257 |
+
}
|
1258 |
+
//case M_APP0: /* no need to read the JFIF marker */
|
1259 |
+
|
1260 |
+
case M_JPG:
|
1261 |
+
case M_RST0: /* no parameters */
|
1262 |
+
case M_RST1:
|
1263 |
+
case M_RST2:
|
1264 |
+
case M_RST3:
|
1265 |
+
case M_RST4:
|
1266 |
+
case M_RST5:
|
1267 |
+
case M_RST6:
|
1268 |
+
case M_RST7:
|
1269 |
+
case M_TEM:
|
1270 |
+
{
|
1271 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
1272 |
+
break;
|
1273 |
+
}
|
1274 |
+
default: /* must be DNL, DHP, EXP, APPn, JPGn, COM, or RESn or APP0 */
|
1275 |
+
{
|
1276 |
+
skip_variable_marker();
|
1277 |
+
break;
|
1278 |
+
}
|
1279 |
+
}
|
1280 |
+
}
|
1281 |
+
}
|
1282 |
+
|
1283 |
+
// Finds the start of image (SOI) marker.
|
1284 |
+
// This code is rather defensive: it only checks the first 512 bytes to avoid
|
1285 |
+
// false positives.
|
1286 |
+
void jpeg_decoder::locate_soi_marker()
|
1287 |
+
{
|
1288 |
+
uint lastchar, thischar;
|
1289 |
+
uint bytesleft;
|
1290 |
+
|
1291 |
+
lastchar = get_bits(8);
|
1292 |
+
|
1293 |
+
thischar = get_bits(8);
|
1294 |
+
|
1295 |
+
/* ok if it's a normal JPEG file without a special header */
|
1296 |
+
|
1297 |
+
if ((lastchar == 0xFF) && (thischar == M_SOI))
|
1298 |
+
return;
|
1299 |
+
|
1300 |
+
bytesleft = 4096; //512;
|
1301 |
+
|
1302 |
+
for ( ; ; )
|
1303 |
+
{
|
1304 |
+
if (--bytesleft == 0)
|
1305 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1306 |
+
|
1307 |
+
lastchar = thischar;
|
1308 |
+
|
1309 |
+
thischar = get_bits(8);
|
1310 |
+
|
1311 |
+
if (lastchar == 0xFF)
|
1312 |
+
{
|
1313 |
+
if (thischar == M_SOI)
|
1314 |
+
break;
|
1315 |
+
else if (thischar == M_EOI) // get_bits will keep returning M_EOI if we read past the end
|
1316 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1317 |
+
}
|
1318 |
+
}
|
1319 |
+
|
1320 |
+
// Check the next character after marker: if it's not 0xFF, it can't be the start of the next marker, so the file is bad.
|
1321 |
+
thischar = (m_bit_buf >> 24) & 0xFF;
|
1322 |
+
|
1323 |
+
if (thischar != 0xFF)
|
1324 |
+
stop_decoding(JPGD_NOT_JPEG);
|
1325 |
+
}
|
1326 |
+
|
1327 |
+
// Find a start of frame (SOF) marker.
|
1328 |
+
void jpeg_decoder::locate_sof_marker()
|
1329 |
+
{
|
1330 |
+
locate_soi_marker();
|
1331 |
+
|
1332 |
+
int c = process_markers();
|
1333 |
+
|
1334 |
+
switch (c)
|
1335 |
+
{
|
1336 |
+
case M_SOF2:
|
1337 |
+
m_progressive_flag = JPGD_TRUE;
|
1338 |
+
case M_SOF0: /* baseline DCT */
|
1339 |
+
case M_SOF1: /* extended sequential DCT */
|
1340 |
+
{
|
1341 |
+
read_sof_marker();
|
1342 |
+
break;
|
1343 |
+
}
|
1344 |
+
case M_SOF9: /* Arithmitic coding */
|
1345 |
+
{
|
1346 |
+
stop_decoding(JPGD_NO_ARITHMITIC_SUPPORT);
|
1347 |
+
break;
|
1348 |
+
}
|
1349 |
+
default:
|
1350 |
+
{
|
1351 |
+
stop_decoding(JPGD_UNSUPPORTED_MARKER);
|
1352 |
+
break;
|
1353 |
+
}
|
1354 |
+
}
|
1355 |
+
}
|
1356 |
+
|
1357 |
+
// Find a start of scan (SOS) marker.
|
1358 |
+
int jpeg_decoder::locate_sos_marker()
|
1359 |
+
{
|
1360 |
+
int c;
|
1361 |
+
|
1362 |
+
c = process_markers();
|
1363 |
+
|
1364 |
+
if (c == M_EOI)
|
1365 |
+
return JPGD_FALSE;
|
1366 |
+
else if (c != M_SOS)
|
1367 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
1368 |
+
|
1369 |
+
read_sos_marker();
|
1370 |
+
|
1371 |
+
return JPGD_TRUE;
|
1372 |
+
}
|
1373 |
+
|
1374 |
+
// Reset everything to default/uninitialized state.
|
1375 |
+
void jpeg_decoder::init(jpeg_decoder_stream *pStream)
|
1376 |
+
{
|
1377 |
+
m_pMem_blocks = NULL;
|
1378 |
+
m_error_code = JPGD_SUCCESS;
|
1379 |
+
m_ready_flag = false;
|
1380 |
+
m_image_x_size = m_image_y_size = 0;
|
1381 |
+
m_pStream = pStream;
|
1382 |
+
m_progressive_flag = JPGD_FALSE;
|
1383 |
+
|
1384 |
+
memset(m_huff_ac, 0, sizeof(m_huff_ac));
|
1385 |
+
memset(m_huff_num, 0, sizeof(m_huff_num));
|
1386 |
+
memset(m_huff_val, 0, sizeof(m_huff_val));
|
1387 |
+
memset(m_quant, 0, sizeof(m_quant));
|
1388 |
+
|
1389 |
+
m_scan_type = 0;
|
1390 |
+
m_comps_in_frame = 0;
|
1391 |
+
|
1392 |
+
memset(m_comp_h_samp, 0, sizeof(m_comp_h_samp));
|
1393 |
+
memset(m_comp_v_samp, 0, sizeof(m_comp_v_samp));
|
1394 |
+
memset(m_comp_quant, 0, sizeof(m_comp_quant));
|
1395 |
+
memset(m_comp_ident, 0, sizeof(m_comp_ident));
|
1396 |
+
memset(m_comp_h_blocks, 0, sizeof(m_comp_h_blocks));
|
1397 |
+
memset(m_comp_v_blocks, 0, sizeof(m_comp_v_blocks));
|
1398 |
+
|
1399 |
+
m_comps_in_scan = 0;
|
1400 |
+
memset(m_comp_list, 0, sizeof(m_comp_list));
|
1401 |
+
memset(m_comp_dc_tab, 0, sizeof(m_comp_dc_tab));
|
1402 |
+
memset(m_comp_ac_tab, 0, sizeof(m_comp_ac_tab));
|
1403 |
+
|
1404 |
+
m_spectral_start = 0;
|
1405 |
+
m_spectral_end = 0;
|
1406 |
+
m_successive_low = 0;
|
1407 |
+
m_successive_high = 0;
|
1408 |
+
m_max_mcu_x_size = 0;
|
1409 |
+
m_max_mcu_y_size = 0;
|
1410 |
+
m_blocks_per_mcu = 0;
|
1411 |
+
m_max_blocks_per_row = 0;
|
1412 |
+
m_mcus_per_row = 0;
|
1413 |
+
m_mcus_per_col = 0;
|
1414 |
+
m_expanded_blocks_per_component = 0;
|
1415 |
+
m_expanded_blocks_per_mcu = 0;
|
1416 |
+
m_expanded_blocks_per_row = 0;
|
1417 |
+
m_freq_domain_chroma_upsample = false;
|
1418 |
+
|
1419 |
+
memset(m_mcu_org, 0, sizeof(m_mcu_org));
|
1420 |
+
|
1421 |
+
m_total_lines_left = 0;
|
1422 |
+
m_mcu_lines_left = 0;
|
1423 |
+
m_real_dest_bytes_per_scan_line = 0;
|
1424 |
+
m_dest_bytes_per_scan_line = 0;
|
1425 |
+
m_dest_bytes_per_pixel = 0;
|
1426 |
+
|
1427 |
+
memset(m_pHuff_tabs, 0, sizeof(m_pHuff_tabs));
|
1428 |
+
|
1429 |
+
memset(m_dc_coeffs, 0, sizeof(m_dc_coeffs));
|
1430 |
+
memset(m_ac_coeffs, 0, sizeof(m_ac_coeffs));
|
1431 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
1432 |
+
|
1433 |
+
m_eob_run = 0;
|
1434 |
+
|
1435 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
1436 |
+
|
1437 |
+
m_pIn_buf_ofs = m_in_buf;
|
1438 |
+
m_in_buf_left = 0;
|
1439 |
+
m_eof_flag = false;
|
1440 |
+
m_tem_flag = 0;
|
1441 |
+
|
1442 |
+
memset(m_in_buf_pad_start, 0, sizeof(m_in_buf_pad_start));
|
1443 |
+
memset(m_in_buf, 0, sizeof(m_in_buf));
|
1444 |
+
memset(m_in_buf_pad_end, 0, sizeof(m_in_buf_pad_end));
|
1445 |
+
|
1446 |
+
m_restart_interval = 0;
|
1447 |
+
m_restarts_left = 0;
|
1448 |
+
m_next_restart_num = 0;
|
1449 |
+
|
1450 |
+
m_max_mcus_per_row = 0;
|
1451 |
+
m_max_blocks_per_mcu = 0;
|
1452 |
+
m_max_mcus_per_col = 0;
|
1453 |
+
|
1454 |
+
memset(m_last_dc_val, 0, sizeof(m_last_dc_val));
|
1455 |
+
m_pMCU_coefficients = NULL;
|
1456 |
+
m_pSample_buf = NULL;
|
1457 |
+
|
1458 |
+
m_total_bytes_read = 0;
|
1459 |
+
|
1460 |
+
m_pScan_line_0 = NULL;
|
1461 |
+
m_pScan_line_1 = NULL;
|
1462 |
+
|
1463 |
+
// Ready the input buffer.
|
1464 |
+
prep_in_buffer();
|
1465 |
+
|
1466 |
+
// Prime the bit buffer.
|
1467 |
+
m_bits_left = 16;
|
1468 |
+
m_bit_buf = 0;
|
1469 |
+
|
1470 |
+
get_bits(16);
|
1471 |
+
get_bits(16);
|
1472 |
+
|
1473 |
+
for (int i = 0; i < JPGD_MAX_BLOCKS_PER_MCU; i++)
|
1474 |
+
m_mcu_block_max_zag[i] = 64;
|
1475 |
+
}
|
1476 |
+
|
1477 |
+
#define SCALEBITS 16
|
1478 |
+
#define ONE_HALF ((int) 1 << (SCALEBITS-1))
|
1479 |
+
#define FIX(x) ((int) ((x) * (1L<<SCALEBITS) + 0.5f))
|
1480 |
+
|
1481 |
+
// Create a few tables that allow us to quickly convert YCbCr to RGB.
|
1482 |
+
void jpeg_decoder::create_look_ups()
|
1483 |
+
{
|
1484 |
+
for (int i = 0; i <= 255; i++)
|
1485 |
+
{
|
1486 |
+
int k = i - 128;
|
1487 |
+
m_crr[i] = ( FIX(1.40200f) * k + ONE_HALF) >> SCALEBITS;
|
1488 |
+
m_cbb[i] = ( FIX(1.77200f) * k + ONE_HALF) >> SCALEBITS;
|
1489 |
+
m_crg[i] = (-FIX(0.71414f)) * k;
|
1490 |
+
m_cbg[i] = (-FIX(0.34414f)) * k + ONE_HALF;
|
1491 |
+
}
|
1492 |
+
}
|
1493 |
+
|
1494 |
+
// This method throws back into the stream any bytes that where read
|
1495 |
+
// into the bit buffer during initial marker scanning.
|
1496 |
+
void jpeg_decoder::fix_in_buffer()
|
1497 |
+
{
|
1498 |
+
// In case any 0xFF's where pulled into the buffer during marker scanning.
|
1499 |
+
JPGD_ASSERT((m_bits_left & 7) == 0);
|
1500 |
+
|
1501 |
+
if (m_bits_left == 16)
|
1502 |
+
stuff_char( (uint8)(m_bit_buf & 0xFF));
|
1503 |
+
|
1504 |
+
if (m_bits_left >= 8)
|
1505 |
+
stuff_char( (uint8)((m_bit_buf >> 8) & 0xFF));
|
1506 |
+
|
1507 |
+
stuff_char((uint8)((m_bit_buf >> 16) & 0xFF));
|
1508 |
+
stuff_char((uint8)((m_bit_buf >> 24) & 0xFF));
|
1509 |
+
|
1510 |
+
m_bits_left = 16;
|
1511 |
+
get_bits_no_markers(16);
|
1512 |
+
get_bits_no_markers(16);
|
1513 |
+
}
|
1514 |
+
|
1515 |
+
void jpeg_decoder::transform_mcu(int mcu_row)
|
1516 |
+
{
|
1517 |
+
jpgd_block_t* pSrc_ptr = m_pMCU_coefficients;
|
1518 |
+
uint8* pDst_ptr = m_pSample_buf + mcu_row * m_blocks_per_mcu * 64;
|
1519 |
+
|
1520 |
+
for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
1521 |
+
{
|
1522 |
+
idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
|
1523 |
+
pSrc_ptr += 64;
|
1524 |
+
pDst_ptr += 64;
|
1525 |
+
}
|
1526 |
+
}
|
1527 |
+
|
1528 |
+
static const uint8 s_max_rc[64] =
|
1529 |
+
{
|
1530 |
+
17, 18, 34, 50, 50, 51, 52, 52, 52, 68, 84, 84, 84, 84, 85, 86, 86, 86, 86, 86,
|
1531 |
+
102, 118, 118, 118, 118, 118, 118, 119, 120, 120, 120, 120, 120, 120, 120, 136,
|
1532 |
+
136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136,
|
1533 |
+
136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136, 136
|
1534 |
+
};
|
1535 |
+
|
1536 |
+
void jpeg_decoder::transform_mcu_expand(int mcu_row)
|
1537 |
+
{
|
1538 |
+
jpgd_block_t* pSrc_ptr = m_pMCU_coefficients;
|
1539 |
+
uint8* pDst_ptr = m_pSample_buf + mcu_row * m_expanded_blocks_per_mcu * 64;
|
1540 |
+
|
1541 |
+
// Y IDCT
|
1542 |
+
int mcu_block;
|
1543 |
+
for (mcu_block = 0; mcu_block < m_expanded_blocks_per_component; mcu_block++)
|
1544 |
+
{
|
1545 |
+
idct(pSrc_ptr, pDst_ptr, m_mcu_block_max_zag[mcu_block]);
|
1546 |
+
pSrc_ptr += 64;
|
1547 |
+
pDst_ptr += 64;
|
1548 |
+
}
|
1549 |
+
|
1550 |
+
// Chroma IDCT, with upsampling
|
1551 |
+
jpgd_block_t temp_block[64];
|
1552 |
+
|
1553 |
+
for (int i = 0; i < 2; i++)
|
1554 |
+
{
|
1555 |
+
DCT_Upsample::Matrix44 P, Q, R, S;
|
1556 |
+
|
1557 |
+
JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] >= 1);
|
1558 |
+
JPGD_ASSERT(m_mcu_block_max_zag[mcu_block] <= 64);
|
1559 |
+
|
1560 |
+
switch (s_max_rc[m_mcu_block_max_zag[mcu_block++] - 1])
|
1561 |
+
{
|
1562 |
+
case 1*16+1:
|
1563 |
+
DCT_Upsample::P_Q<1, 1>::calc(P, Q, pSrc_ptr);
|
1564 |
+
DCT_Upsample::R_S<1, 1>::calc(R, S, pSrc_ptr);
|
1565 |
+
break;
|
1566 |
+
case 1*16+2:
|
1567 |
+
DCT_Upsample::P_Q<1, 2>::calc(P, Q, pSrc_ptr);
|
1568 |
+
DCT_Upsample::R_S<1, 2>::calc(R, S, pSrc_ptr);
|
1569 |
+
break;
|
1570 |
+
case 2*16+2:
|
1571 |
+
DCT_Upsample::P_Q<2, 2>::calc(P, Q, pSrc_ptr);
|
1572 |
+
DCT_Upsample::R_S<2, 2>::calc(R, S, pSrc_ptr);
|
1573 |
+
break;
|
1574 |
+
case 3*16+2:
|
1575 |
+
DCT_Upsample::P_Q<3, 2>::calc(P, Q, pSrc_ptr);
|
1576 |
+
DCT_Upsample::R_S<3, 2>::calc(R, S, pSrc_ptr);
|
1577 |
+
break;
|
1578 |
+
case 3*16+3:
|
1579 |
+
DCT_Upsample::P_Q<3, 3>::calc(P, Q, pSrc_ptr);
|
1580 |
+
DCT_Upsample::R_S<3, 3>::calc(R, S, pSrc_ptr);
|
1581 |
+
break;
|
1582 |
+
case 3*16+4:
|
1583 |
+
DCT_Upsample::P_Q<3, 4>::calc(P, Q, pSrc_ptr);
|
1584 |
+
DCT_Upsample::R_S<3, 4>::calc(R, S, pSrc_ptr);
|
1585 |
+
break;
|
1586 |
+
case 4*16+4:
|
1587 |
+
DCT_Upsample::P_Q<4, 4>::calc(P, Q, pSrc_ptr);
|
1588 |
+
DCT_Upsample::R_S<4, 4>::calc(R, S, pSrc_ptr);
|
1589 |
+
break;
|
1590 |
+
case 5*16+4:
|
1591 |
+
DCT_Upsample::P_Q<5, 4>::calc(P, Q, pSrc_ptr);
|
1592 |
+
DCT_Upsample::R_S<5, 4>::calc(R, S, pSrc_ptr);
|
1593 |
+
break;
|
1594 |
+
case 5*16+5:
|
1595 |
+
DCT_Upsample::P_Q<5, 5>::calc(P, Q, pSrc_ptr);
|
1596 |
+
DCT_Upsample::R_S<5, 5>::calc(R, S, pSrc_ptr);
|
1597 |
+
break;
|
1598 |
+
case 5*16+6:
|
1599 |
+
DCT_Upsample::P_Q<5, 6>::calc(P, Q, pSrc_ptr);
|
1600 |
+
DCT_Upsample::R_S<5, 6>::calc(R, S, pSrc_ptr);
|
1601 |
+
break;
|
1602 |
+
case 6*16+6:
|
1603 |
+
DCT_Upsample::P_Q<6, 6>::calc(P, Q, pSrc_ptr);
|
1604 |
+
DCT_Upsample::R_S<6, 6>::calc(R, S, pSrc_ptr);
|
1605 |
+
break;
|
1606 |
+
case 7*16+6:
|
1607 |
+
DCT_Upsample::P_Q<7, 6>::calc(P, Q, pSrc_ptr);
|
1608 |
+
DCT_Upsample::R_S<7, 6>::calc(R, S, pSrc_ptr);
|
1609 |
+
break;
|
1610 |
+
case 7*16+7:
|
1611 |
+
DCT_Upsample::P_Q<7, 7>::calc(P, Q, pSrc_ptr);
|
1612 |
+
DCT_Upsample::R_S<7, 7>::calc(R, S, pSrc_ptr);
|
1613 |
+
break;
|
1614 |
+
case 7*16+8:
|
1615 |
+
DCT_Upsample::P_Q<7, 8>::calc(P, Q, pSrc_ptr);
|
1616 |
+
DCT_Upsample::R_S<7, 8>::calc(R, S, pSrc_ptr);
|
1617 |
+
break;
|
1618 |
+
case 8*16+8:
|
1619 |
+
DCT_Upsample::P_Q<8, 8>::calc(P, Q, pSrc_ptr);
|
1620 |
+
DCT_Upsample::R_S<8, 8>::calc(R, S, pSrc_ptr);
|
1621 |
+
break;
|
1622 |
+
default:
|
1623 |
+
JPGD_ASSERT(false);
|
1624 |
+
}
|
1625 |
+
|
1626 |
+
DCT_Upsample::Matrix44 a(P + Q); P -= Q;
|
1627 |
+
DCT_Upsample::Matrix44& b = P;
|
1628 |
+
DCT_Upsample::Matrix44 c(R + S); R -= S;
|
1629 |
+
DCT_Upsample::Matrix44& d = R;
|
1630 |
+
|
1631 |
+
DCT_Upsample::Matrix44::add_and_store(temp_block, a, c);
|
1632 |
+
idct_4x4(temp_block, pDst_ptr);
|
1633 |
+
pDst_ptr += 64;
|
1634 |
+
|
1635 |
+
DCT_Upsample::Matrix44::sub_and_store(temp_block, a, c);
|
1636 |
+
idct_4x4(temp_block, pDst_ptr);
|
1637 |
+
pDst_ptr += 64;
|
1638 |
+
|
1639 |
+
DCT_Upsample::Matrix44::add_and_store(temp_block, b, d);
|
1640 |
+
idct_4x4(temp_block, pDst_ptr);
|
1641 |
+
pDst_ptr += 64;
|
1642 |
+
|
1643 |
+
DCT_Upsample::Matrix44::sub_and_store(temp_block, b, d);
|
1644 |
+
idct_4x4(temp_block, pDst_ptr);
|
1645 |
+
pDst_ptr += 64;
|
1646 |
+
|
1647 |
+
pSrc_ptr += 64;
|
1648 |
+
}
|
1649 |
+
}
|
1650 |
+
|
1651 |
+
// Loads and dequantizes the next row of (already decoded) coefficients.
|
1652 |
+
// Progressive images only.
|
1653 |
+
void jpeg_decoder::load_next_row()
|
1654 |
+
{
|
1655 |
+
int i;
|
1656 |
+
jpgd_block_t *p;
|
1657 |
+
jpgd_quant_t *q;
|
1658 |
+
int mcu_row, mcu_block, row_block = 0;
|
1659 |
+
int component_num, component_id;
|
1660 |
+
int block_x_mcu[JPGD_MAX_COMPONENTS];
|
1661 |
+
|
1662 |
+
memset(block_x_mcu, 0, JPGD_MAX_COMPONENTS * sizeof(int));
|
1663 |
+
|
1664 |
+
for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
1665 |
+
{
|
1666 |
+
int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
|
1667 |
+
|
1668 |
+
for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
1669 |
+
{
|
1670 |
+
component_id = m_mcu_org[mcu_block];
|
1671 |
+
q = m_quant[m_comp_quant[component_id]];
|
1672 |
+
|
1673 |
+
p = m_pMCU_coefficients + 64 * mcu_block;
|
1674 |
+
|
1675 |
+
jpgd_block_t* pAC = coeff_buf_getp(m_ac_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
1676 |
+
jpgd_block_t* pDC = coeff_buf_getp(m_dc_coeffs[component_id], block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
1677 |
+
p[0] = pDC[0];
|
1678 |
+
memcpy(&p[1], &pAC[1], 63 * sizeof(jpgd_block_t));
|
1679 |
+
|
1680 |
+
for (i = 63; i > 0; i--)
|
1681 |
+
if (p[g_ZAG[i]])
|
1682 |
+
break;
|
1683 |
+
|
1684 |
+
m_mcu_block_max_zag[mcu_block] = i + 1;
|
1685 |
+
|
1686 |
+
for ( ; i >= 0; i--)
|
1687 |
+
if (p[g_ZAG[i]])
|
1688 |
+
p[g_ZAG[i]] = static_cast<jpgd_block_t>(p[g_ZAG[i]] * q[i]);
|
1689 |
+
|
1690 |
+
row_block++;
|
1691 |
+
|
1692 |
+
if (m_comps_in_scan == 1)
|
1693 |
+
block_x_mcu[component_id]++;
|
1694 |
+
else
|
1695 |
+
{
|
1696 |
+
if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
|
1697 |
+
{
|
1698 |
+
block_x_mcu_ofs = 0;
|
1699 |
+
|
1700 |
+
if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
|
1701 |
+
{
|
1702 |
+
block_y_mcu_ofs = 0;
|
1703 |
+
|
1704 |
+
block_x_mcu[component_id] += m_comp_h_samp[component_id];
|
1705 |
+
}
|
1706 |
+
}
|
1707 |
+
}
|
1708 |
+
}
|
1709 |
+
|
1710 |
+
if (m_freq_domain_chroma_upsample)
|
1711 |
+
transform_mcu_expand(mcu_row);
|
1712 |
+
else
|
1713 |
+
transform_mcu(mcu_row);
|
1714 |
+
}
|
1715 |
+
|
1716 |
+
if (m_comps_in_scan == 1)
|
1717 |
+
m_block_y_mcu[m_comp_list[0]]++;
|
1718 |
+
else
|
1719 |
+
{
|
1720 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
1721 |
+
{
|
1722 |
+
component_id = m_comp_list[component_num];
|
1723 |
+
|
1724 |
+
m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
|
1725 |
+
}
|
1726 |
+
}
|
1727 |
+
}
|
1728 |
+
|
1729 |
+
// Restart interval processing.
|
1730 |
+
void jpeg_decoder::process_restart()
|
1731 |
+
{
|
1732 |
+
int i;
|
1733 |
+
int c = 0;
|
1734 |
+
|
1735 |
+
// Align to a byte boundry
|
1736 |
+
// FIXME: Is this really necessary? get_bits_no_markers() never reads in markers!
|
1737 |
+
//get_bits_no_markers(m_bits_left & 7);
|
1738 |
+
|
1739 |
+
// Let's scan a little bit to find the marker, but not _too_ far.
|
1740 |
+
// 1536 is a "fudge factor" that determines how much to scan.
|
1741 |
+
for (i = 1536; i > 0; i--)
|
1742 |
+
if (get_char() == 0xFF)
|
1743 |
+
break;
|
1744 |
+
|
1745 |
+
if (i == 0)
|
1746 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1747 |
+
|
1748 |
+
for ( ; i > 0; i--)
|
1749 |
+
if ((c = get_char()) != 0xFF)
|
1750 |
+
break;
|
1751 |
+
|
1752 |
+
if (i == 0)
|
1753 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1754 |
+
|
1755 |
+
// Is it the expected marker? If not, something bad happened.
|
1756 |
+
if (c != (m_next_restart_num + M_RST0))
|
1757 |
+
stop_decoding(JPGD_BAD_RESTART_MARKER);
|
1758 |
+
|
1759 |
+
// Reset each component's DC prediction values.
|
1760 |
+
memset(&m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
|
1761 |
+
|
1762 |
+
m_eob_run = 0;
|
1763 |
+
|
1764 |
+
m_restarts_left = m_restart_interval;
|
1765 |
+
|
1766 |
+
m_next_restart_num = (m_next_restart_num + 1) & 7;
|
1767 |
+
|
1768 |
+
// Get the bit buffer going again...
|
1769 |
+
|
1770 |
+
m_bits_left = 16;
|
1771 |
+
get_bits_no_markers(16);
|
1772 |
+
get_bits_no_markers(16);
|
1773 |
+
}
|
1774 |
+
|
1775 |
+
static inline int dequantize_ac(int c, int q) { c *= q; return c; }
|
1776 |
+
|
1777 |
+
// Decodes and dequantizes the next row of coefficients.
|
1778 |
+
void jpeg_decoder::decode_next_row()
|
1779 |
+
{
|
1780 |
+
int row_block = 0;
|
1781 |
+
|
1782 |
+
for (int mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
1783 |
+
{
|
1784 |
+
if ((m_restart_interval) && (m_restarts_left == 0))
|
1785 |
+
process_restart();
|
1786 |
+
|
1787 |
+
jpgd_block_t* p = m_pMCU_coefficients;
|
1788 |
+
for (int mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++, p += 64)
|
1789 |
+
{
|
1790 |
+
int component_id = m_mcu_org[mcu_block];
|
1791 |
+
jpgd_quant_t* q = m_quant[m_comp_quant[component_id]];
|
1792 |
+
|
1793 |
+
int r, s;
|
1794 |
+
s = huff_decode(m_pHuff_tabs[m_comp_dc_tab[component_id]], r);
|
1795 |
+
s = HUFF_EXTEND(r, s);
|
1796 |
+
|
1797 |
+
m_last_dc_val[component_id] = (s += m_last_dc_val[component_id]);
|
1798 |
+
|
1799 |
+
p[0] = static_cast<jpgd_block_t>(s * q[0]);
|
1800 |
+
|
1801 |
+
int prev_num_set = m_mcu_block_max_zag[mcu_block];
|
1802 |
+
|
1803 |
+
huff_tables *pH = m_pHuff_tabs[m_comp_ac_tab[component_id]];
|
1804 |
+
|
1805 |
+
int k;
|
1806 |
+
for (k = 1; k < 64; k++)
|
1807 |
+
{
|
1808 |
+
int extra_bits;
|
1809 |
+
s = huff_decode(pH, extra_bits);
|
1810 |
+
|
1811 |
+
r = s >> 4;
|
1812 |
+
s &= 15;
|
1813 |
+
|
1814 |
+
if (s)
|
1815 |
+
{
|
1816 |
+
if (r)
|
1817 |
+
{
|
1818 |
+
if ((k + r) > 63)
|
1819 |
+
stop_decoding(JPGD_DECODE_ERROR);
|
1820 |
+
|
1821 |
+
if (k < prev_num_set)
|
1822 |
+
{
|
1823 |
+
int n = JPGD_MIN(r, prev_num_set - k);
|
1824 |
+
int kt = k;
|
1825 |
+
while (n--)
|
1826 |
+
p[g_ZAG[kt++]] = 0;
|
1827 |
+
}
|
1828 |
+
|
1829 |
+
k += r;
|
1830 |
+
}
|
1831 |
+
|
1832 |
+
s = HUFF_EXTEND(extra_bits, s);
|
1833 |
+
|
1834 |
+
JPGD_ASSERT(k < 64);
|
1835 |
+
|
1836 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(dequantize_ac(s, q[k])); //s * q[k];
|
1837 |
+
}
|
1838 |
+
else
|
1839 |
+
{
|
1840 |
+
if (r == 15)
|
1841 |
+
{
|
1842 |
+
if ((k + 16) > 64)
|
1843 |
+
stop_decoding(JPGD_DECODE_ERROR);
|
1844 |
+
|
1845 |
+
if (k < prev_num_set)
|
1846 |
+
{
|
1847 |
+
int n = JPGD_MIN(16, prev_num_set - k);
|
1848 |
+
int kt = k;
|
1849 |
+
while (n--)
|
1850 |
+
{
|
1851 |
+
JPGD_ASSERT(kt <= 63);
|
1852 |
+
p[g_ZAG[kt++]] = 0;
|
1853 |
+
}
|
1854 |
+
}
|
1855 |
+
|
1856 |
+
k += 16 - 1; // - 1 because the loop counter is k
|
1857 |
+
// BEGIN EPIC MOD
|
1858 |
+
JPGD_ASSERT(k < 64 && p[g_ZAG[k]] == 0);
|
1859 |
+
// END EPIC MOD
|
1860 |
+
}
|
1861 |
+
else
|
1862 |
+
break;
|
1863 |
+
}
|
1864 |
+
}
|
1865 |
+
|
1866 |
+
if (k < prev_num_set)
|
1867 |
+
{
|
1868 |
+
int kt = k;
|
1869 |
+
while (kt < prev_num_set)
|
1870 |
+
p[g_ZAG[kt++]] = 0;
|
1871 |
+
}
|
1872 |
+
|
1873 |
+
m_mcu_block_max_zag[mcu_block] = k;
|
1874 |
+
|
1875 |
+
row_block++;
|
1876 |
+
}
|
1877 |
+
|
1878 |
+
if (m_freq_domain_chroma_upsample)
|
1879 |
+
transform_mcu_expand(mcu_row);
|
1880 |
+
else
|
1881 |
+
transform_mcu(mcu_row);
|
1882 |
+
|
1883 |
+
m_restarts_left--;
|
1884 |
+
}
|
1885 |
+
}
|
1886 |
+
|
1887 |
+
// YCbCr H1V1 (1x1:1:1, 3 m_blocks per MCU) to RGB
|
1888 |
+
void jpeg_decoder::H1V1Convert()
|
1889 |
+
{
|
1890 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1891 |
+
uint8 *d = m_pScan_line_0;
|
1892 |
+
uint8 *s = m_pSample_buf + row * 8;
|
1893 |
+
|
1894 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1895 |
+
{
|
1896 |
+
for (int j = 0; j < 8; j++)
|
1897 |
+
{
|
1898 |
+
int y = s[j];
|
1899 |
+
int cb = s[64+j];
|
1900 |
+
int cr = s[128+j];
|
1901 |
+
|
1902 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
1903 |
+
{
|
1904 |
+
d[0] = clamp(y + m_cbb[cb]);
|
1905 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
1906 |
+
d[2] = clamp(y + m_crr[cr]);
|
1907 |
+
d[3] = 255;
|
1908 |
+
}
|
1909 |
+
else
|
1910 |
+
{
|
1911 |
+
d[0] = clamp(y + m_crr[cr]);
|
1912 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
1913 |
+
d[2] = clamp(y + m_cbb[cb]);
|
1914 |
+
d[3] = 255;
|
1915 |
+
}
|
1916 |
+
d += 4;
|
1917 |
+
}
|
1918 |
+
|
1919 |
+
s += 64*3;
|
1920 |
+
}
|
1921 |
+
}
|
1922 |
+
|
1923 |
+
// YCbCr H2V1 (2x1:1:1, 4 m_blocks per MCU) to RGB
|
1924 |
+
void jpeg_decoder::H2V1Convert()
|
1925 |
+
{
|
1926 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1927 |
+
uint8 *d0 = m_pScan_line_0;
|
1928 |
+
uint8 *y = m_pSample_buf + row * 8;
|
1929 |
+
uint8 *c = m_pSample_buf + 2*64 + row * 8;
|
1930 |
+
|
1931 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1932 |
+
{
|
1933 |
+
for (int l = 0; l < 2; l++)
|
1934 |
+
{
|
1935 |
+
for (int j = 0; j < 4; j++)
|
1936 |
+
{
|
1937 |
+
int cb = c[0];
|
1938 |
+
int cr = c[64];
|
1939 |
+
|
1940 |
+
int rc = m_crr[cr];
|
1941 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
1942 |
+
int bc = m_cbb[cb];
|
1943 |
+
|
1944 |
+
int yy = y[j<<1];
|
1945 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
1946 |
+
{
|
1947 |
+
d0[0] = clamp(yy+bc);
|
1948 |
+
d0[1] = clamp(yy+gc);
|
1949 |
+
d0[2] = clamp(yy+rc);
|
1950 |
+
d0[3] = 255;
|
1951 |
+
yy = y[(j<<1)+1];
|
1952 |
+
d0[4] = clamp(yy+bc);
|
1953 |
+
d0[5] = clamp(yy+gc);
|
1954 |
+
d0[6] = clamp(yy+rc);
|
1955 |
+
d0[7] = 255;
|
1956 |
+
}
|
1957 |
+
else
|
1958 |
+
{
|
1959 |
+
d0[0] = clamp(yy+rc);
|
1960 |
+
d0[1] = clamp(yy+gc);
|
1961 |
+
d0[2] = clamp(yy+bc);
|
1962 |
+
d0[3] = 255;
|
1963 |
+
yy = y[(j<<1)+1];
|
1964 |
+
d0[4] = clamp(yy+rc);
|
1965 |
+
d0[5] = clamp(yy+gc);
|
1966 |
+
d0[6] = clamp(yy+bc);
|
1967 |
+
d0[7] = 255;
|
1968 |
+
}
|
1969 |
+
|
1970 |
+
d0 += 8;
|
1971 |
+
|
1972 |
+
c++;
|
1973 |
+
}
|
1974 |
+
y += 64;
|
1975 |
+
}
|
1976 |
+
|
1977 |
+
y += 64*4 - 64*2;
|
1978 |
+
c += 64*4 - 8;
|
1979 |
+
}
|
1980 |
+
}
|
1981 |
+
|
1982 |
+
// YCbCr H2V1 (1x2:1:1, 4 m_blocks per MCU) to RGB
|
1983 |
+
void jpeg_decoder::H1V2Convert()
|
1984 |
+
{
|
1985 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
1986 |
+
uint8 *d0 = m_pScan_line_0;
|
1987 |
+
uint8 *d1 = m_pScan_line_1;
|
1988 |
+
uint8 *y;
|
1989 |
+
uint8 *c;
|
1990 |
+
|
1991 |
+
if (row < 8)
|
1992 |
+
y = m_pSample_buf + row * 8;
|
1993 |
+
else
|
1994 |
+
y = m_pSample_buf + 64*1 + (row & 7) * 8;
|
1995 |
+
|
1996 |
+
c = m_pSample_buf + 64*2 + (row >> 1) * 8;
|
1997 |
+
|
1998 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
1999 |
+
{
|
2000 |
+
for (int j = 0; j < 8; j++)
|
2001 |
+
{
|
2002 |
+
int cb = c[0+j];
|
2003 |
+
int cr = c[64+j];
|
2004 |
+
|
2005 |
+
int rc = m_crr[cr];
|
2006 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
2007 |
+
int bc = m_cbb[cb];
|
2008 |
+
|
2009 |
+
int yy = y[j];
|
2010 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2011 |
+
{
|
2012 |
+
d0[0] = clamp(yy+bc);
|
2013 |
+
d0[1] = clamp(yy+gc);
|
2014 |
+
d0[2] = clamp(yy+rc);
|
2015 |
+
d0[3] = 255;
|
2016 |
+
yy = y[8+j];
|
2017 |
+
d1[0] = clamp(yy+bc);
|
2018 |
+
d1[1] = clamp(yy+gc);
|
2019 |
+
d1[2] = clamp(yy+rc);
|
2020 |
+
d1[3] = 255;
|
2021 |
+
}
|
2022 |
+
else
|
2023 |
+
{
|
2024 |
+
d0[0] = clamp(yy+rc);
|
2025 |
+
d0[1] = clamp(yy+gc);
|
2026 |
+
d0[2] = clamp(yy+bc);
|
2027 |
+
d0[3] = 255;
|
2028 |
+
yy = y[8+j];
|
2029 |
+
d1[0] = clamp(yy+rc);
|
2030 |
+
d1[1] = clamp(yy+gc);
|
2031 |
+
d1[2] = clamp(yy+bc);
|
2032 |
+
d1[3] = 255;
|
2033 |
+
}
|
2034 |
+
|
2035 |
+
d0 += 4;
|
2036 |
+
d1 += 4;
|
2037 |
+
}
|
2038 |
+
|
2039 |
+
y += 64*4;
|
2040 |
+
c += 64*4;
|
2041 |
+
}
|
2042 |
+
}
|
2043 |
+
|
2044 |
+
// YCbCr H2V2 (2x2:1:1, 6 m_blocks per MCU) to RGB
|
2045 |
+
void jpeg_decoder::H2V2Convert()
|
2046 |
+
{
|
2047 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2048 |
+
uint8 *d0 = m_pScan_line_0;
|
2049 |
+
uint8 *d1 = m_pScan_line_1;
|
2050 |
+
uint8 *y;
|
2051 |
+
uint8 *c;
|
2052 |
+
|
2053 |
+
if (row < 8)
|
2054 |
+
y = m_pSample_buf + row * 8;
|
2055 |
+
else
|
2056 |
+
y = m_pSample_buf + 64*2 + (row & 7) * 8;
|
2057 |
+
|
2058 |
+
c = m_pSample_buf + 64*4 + (row >> 1) * 8;
|
2059 |
+
|
2060 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2061 |
+
{
|
2062 |
+
for (int l = 0; l < 2; l++)
|
2063 |
+
{
|
2064 |
+
for (int j = 0; j < 8; j += 2)
|
2065 |
+
{
|
2066 |
+
int cb = c[0];
|
2067 |
+
int cr = c[64];
|
2068 |
+
|
2069 |
+
int rc = m_crr[cr];
|
2070 |
+
int gc = ((m_crg[cr] + m_cbg[cb]) >> 16);
|
2071 |
+
int bc = m_cbb[cb];
|
2072 |
+
|
2073 |
+
int yy = y[j];
|
2074 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2075 |
+
{
|
2076 |
+
d0[0] = clamp(yy+bc);
|
2077 |
+
d0[1] = clamp(yy+gc);
|
2078 |
+
d0[2] = clamp(yy+rc);
|
2079 |
+
d0[3] = 255;
|
2080 |
+
yy = y[j+1];
|
2081 |
+
d0[4] = clamp(yy+bc);
|
2082 |
+
d0[5] = clamp(yy+gc);
|
2083 |
+
d0[6] = clamp(yy+rc);
|
2084 |
+
d0[7] = 255;
|
2085 |
+
yy = y[j+8];
|
2086 |
+
d1[0] = clamp(yy+bc);
|
2087 |
+
d1[1] = clamp(yy+gc);
|
2088 |
+
d1[2] = clamp(yy+rc);
|
2089 |
+
d1[3] = 255;
|
2090 |
+
yy = y[j+8+1];
|
2091 |
+
d1[4] = clamp(yy+bc);
|
2092 |
+
d1[5] = clamp(yy+gc);
|
2093 |
+
d1[6] = clamp(yy+rc);
|
2094 |
+
d1[7] = 255;
|
2095 |
+
}
|
2096 |
+
else
|
2097 |
+
{
|
2098 |
+
d0[0] = clamp(yy+rc);
|
2099 |
+
d0[1] = clamp(yy+gc);
|
2100 |
+
d0[2] = clamp(yy+bc);
|
2101 |
+
d0[3] = 255;
|
2102 |
+
yy = y[j+1];
|
2103 |
+
d0[4] = clamp(yy+rc);
|
2104 |
+
d0[5] = clamp(yy+gc);
|
2105 |
+
d0[6] = clamp(yy+bc);
|
2106 |
+
d0[7] = 255;
|
2107 |
+
yy = y[j+8];
|
2108 |
+
d1[0] = clamp(yy+rc);
|
2109 |
+
d1[1] = clamp(yy+gc);
|
2110 |
+
d1[2] = clamp(yy+bc);
|
2111 |
+
d1[3] = 255;
|
2112 |
+
yy = y[j+8+1];
|
2113 |
+
d1[4] = clamp(yy+rc);
|
2114 |
+
d1[5] = clamp(yy+gc);
|
2115 |
+
d1[6] = clamp(yy+bc);
|
2116 |
+
d1[7] = 255;
|
2117 |
+
}
|
2118 |
+
|
2119 |
+
d0 += 8;
|
2120 |
+
d1 += 8;
|
2121 |
+
|
2122 |
+
c++;
|
2123 |
+
}
|
2124 |
+
y += 64;
|
2125 |
+
}
|
2126 |
+
|
2127 |
+
y += 64*6 - 64*2;
|
2128 |
+
c += 64*6 - 8;
|
2129 |
+
}
|
2130 |
+
}
|
2131 |
+
|
2132 |
+
// Y (1 block per MCU) to 8-bit grayscale
|
2133 |
+
void jpeg_decoder::gray_convert()
|
2134 |
+
{
|
2135 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2136 |
+
uint8 *d = m_pScan_line_0;
|
2137 |
+
uint8 *s = m_pSample_buf + row * 8;
|
2138 |
+
|
2139 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2140 |
+
{
|
2141 |
+
*(uint *)d = *(uint *)s;
|
2142 |
+
*(uint *)(&d[4]) = *(uint *)(&s[4]);
|
2143 |
+
|
2144 |
+
s += 64;
|
2145 |
+
d += 8;
|
2146 |
+
}
|
2147 |
+
}
|
2148 |
+
|
2149 |
+
void jpeg_decoder::expanded_convert()
|
2150 |
+
{
|
2151 |
+
int row = m_max_mcu_y_size - m_mcu_lines_left;
|
2152 |
+
|
2153 |
+
uint8* Py = m_pSample_buf + (row / 8) * 64 * m_comp_h_samp[0] + (row & 7) * 8;
|
2154 |
+
|
2155 |
+
uint8* d = m_pScan_line_0;
|
2156 |
+
|
2157 |
+
for (int i = m_max_mcus_per_row; i > 0; i--)
|
2158 |
+
{
|
2159 |
+
for (int k = 0; k < m_max_mcu_x_size; k += 8)
|
2160 |
+
{
|
2161 |
+
const int Y_ofs = k * 8;
|
2162 |
+
const int Cb_ofs = Y_ofs + 64 * m_expanded_blocks_per_component;
|
2163 |
+
const int Cr_ofs = Y_ofs + 64 * m_expanded_blocks_per_component * 2;
|
2164 |
+
for (int j = 0; j < 8; j++)
|
2165 |
+
{
|
2166 |
+
int y = Py[Y_ofs + j];
|
2167 |
+
int cb = Py[Cb_ofs + j];
|
2168 |
+
int cr = Py[Cr_ofs + j];
|
2169 |
+
|
2170 |
+
if (jpg_format == ERGBFormatJPG::BGRA)
|
2171 |
+
{
|
2172 |
+
d[0] = clamp(y + m_cbb[cb]);
|
2173 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
2174 |
+
d[2] = clamp(y + m_crr[cr]);
|
2175 |
+
d[3] = 255;
|
2176 |
+
}
|
2177 |
+
else
|
2178 |
+
{
|
2179 |
+
d[0] = clamp(y + m_crr[cr]);
|
2180 |
+
d[1] = clamp(y + ((m_crg[cr] + m_cbg[cb]) >> 16));
|
2181 |
+
d[2] = clamp(y + m_cbb[cb]);
|
2182 |
+
d[3] = 255;
|
2183 |
+
}
|
2184 |
+
|
2185 |
+
d += 4;
|
2186 |
+
}
|
2187 |
+
}
|
2188 |
+
|
2189 |
+
Py += 64 * m_expanded_blocks_per_mcu;
|
2190 |
+
}
|
2191 |
+
}
|
2192 |
+
|
2193 |
+
// Find end of image (EOI) marker, so we can return to the user the exact size of the input stream.
|
2194 |
+
void jpeg_decoder::find_eoi()
|
2195 |
+
{
|
2196 |
+
if (!m_progressive_flag)
|
2197 |
+
{
|
2198 |
+
// Attempt to read the EOI marker.
|
2199 |
+
//get_bits_no_markers(m_bits_left & 7);
|
2200 |
+
|
2201 |
+
// Prime the bit buffer
|
2202 |
+
m_bits_left = 16;
|
2203 |
+
get_bits(16);
|
2204 |
+
get_bits(16);
|
2205 |
+
|
2206 |
+
// The next marker _should_ be EOI
|
2207 |
+
process_markers();
|
2208 |
+
}
|
2209 |
+
|
2210 |
+
m_total_bytes_read -= m_in_buf_left;
|
2211 |
+
}
|
2212 |
+
|
2213 |
+
int jpeg_decoder::decode(const void** pScan_line, uint* pScan_line_len)
|
2214 |
+
{
|
2215 |
+
if ((m_error_code) || (!m_ready_flag))
|
2216 |
+
return JPGD_FAILED;
|
2217 |
+
|
2218 |
+
if (m_total_lines_left == 0)
|
2219 |
+
return JPGD_DONE;
|
2220 |
+
|
2221 |
+
if (m_mcu_lines_left == 0)
|
2222 |
+
{
|
2223 |
+
if (setjmp(m_jmp_state))
|
2224 |
+
return JPGD_FAILED;
|
2225 |
+
|
2226 |
+
if (m_progressive_flag)
|
2227 |
+
load_next_row();
|
2228 |
+
else
|
2229 |
+
decode_next_row();
|
2230 |
+
|
2231 |
+
// Find the EOI marker if that was the last row.
|
2232 |
+
if (m_total_lines_left <= m_max_mcu_y_size)
|
2233 |
+
find_eoi();
|
2234 |
+
|
2235 |
+
m_mcu_lines_left = m_max_mcu_y_size;
|
2236 |
+
}
|
2237 |
+
|
2238 |
+
if (m_freq_domain_chroma_upsample)
|
2239 |
+
{
|
2240 |
+
expanded_convert();
|
2241 |
+
*pScan_line = m_pScan_line_0;
|
2242 |
+
}
|
2243 |
+
else
|
2244 |
+
{
|
2245 |
+
switch (m_scan_type)
|
2246 |
+
{
|
2247 |
+
case JPGD_YH2V2:
|
2248 |
+
{
|
2249 |
+
if ((m_mcu_lines_left & 1) == 0)
|
2250 |
+
{
|
2251 |
+
H2V2Convert();
|
2252 |
+
*pScan_line = m_pScan_line_0;
|
2253 |
+
}
|
2254 |
+
else
|
2255 |
+
*pScan_line = m_pScan_line_1;
|
2256 |
+
|
2257 |
+
break;
|
2258 |
+
}
|
2259 |
+
case JPGD_YH2V1:
|
2260 |
+
{
|
2261 |
+
H2V1Convert();
|
2262 |
+
*pScan_line = m_pScan_line_0;
|
2263 |
+
break;
|
2264 |
+
}
|
2265 |
+
case JPGD_YH1V2:
|
2266 |
+
{
|
2267 |
+
if ((m_mcu_lines_left & 1) == 0)
|
2268 |
+
{
|
2269 |
+
H1V2Convert();
|
2270 |
+
*pScan_line = m_pScan_line_0;
|
2271 |
+
}
|
2272 |
+
else
|
2273 |
+
*pScan_line = m_pScan_line_1;
|
2274 |
+
|
2275 |
+
break;
|
2276 |
+
}
|
2277 |
+
case JPGD_YH1V1:
|
2278 |
+
{
|
2279 |
+
H1V1Convert();
|
2280 |
+
*pScan_line = m_pScan_line_0;
|
2281 |
+
break;
|
2282 |
+
}
|
2283 |
+
case JPGD_GRAYSCALE:
|
2284 |
+
{
|
2285 |
+
gray_convert();
|
2286 |
+
*pScan_line = m_pScan_line_0;
|
2287 |
+
|
2288 |
+
break;
|
2289 |
+
}
|
2290 |
+
}
|
2291 |
+
}
|
2292 |
+
|
2293 |
+
*pScan_line_len = m_real_dest_bytes_per_scan_line;
|
2294 |
+
|
2295 |
+
m_mcu_lines_left--;
|
2296 |
+
m_total_lines_left--;
|
2297 |
+
|
2298 |
+
return JPGD_SUCCESS;
|
2299 |
+
}
|
2300 |
+
|
2301 |
+
// Creates the tables needed for efficient Huffman decoding.
|
2302 |
+
void jpeg_decoder::make_huff_table(int index, huff_tables *pH)
|
2303 |
+
{
|
2304 |
+
int p, i, l, si;
|
2305 |
+
uint8 huffsize[257];
|
2306 |
+
uint huffcode[257];
|
2307 |
+
uint code;
|
2308 |
+
uint subtree;
|
2309 |
+
int code_size;
|
2310 |
+
int lastp;
|
2311 |
+
int nextfreeentry;
|
2312 |
+
int currententry;
|
2313 |
+
|
2314 |
+
pH->ac_table = m_huff_ac[index] != 0;
|
2315 |
+
|
2316 |
+
p = 0;
|
2317 |
+
|
2318 |
+
for (l = 1; l <= 16; l++)
|
2319 |
+
{
|
2320 |
+
for (i = 1; i <= m_huff_num[index][l]; i++)
|
2321 |
+
huffsize[p++] = static_cast<uint8>(l);
|
2322 |
+
}
|
2323 |
+
|
2324 |
+
huffsize[p] = 0;
|
2325 |
+
|
2326 |
+
lastp = p;
|
2327 |
+
|
2328 |
+
code = 0;
|
2329 |
+
si = huffsize[0];
|
2330 |
+
p = 0;
|
2331 |
+
|
2332 |
+
while (huffsize[p])
|
2333 |
+
{
|
2334 |
+
while (huffsize[p] == si)
|
2335 |
+
{
|
2336 |
+
huffcode[p++] = code;
|
2337 |
+
code++;
|
2338 |
+
}
|
2339 |
+
|
2340 |
+
code <<= 1;
|
2341 |
+
si++;
|
2342 |
+
}
|
2343 |
+
|
2344 |
+
memset(pH->look_up, 0, sizeof(pH->look_up));
|
2345 |
+
memset(pH->look_up2, 0, sizeof(pH->look_up2));
|
2346 |
+
memset(pH->tree, 0, sizeof(pH->tree));
|
2347 |
+
memset(pH->code_size, 0, sizeof(pH->code_size));
|
2348 |
+
|
2349 |
+
nextfreeentry = -1;
|
2350 |
+
|
2351 |
+
p = 0;
|
2352 |
+
|
2353 |
+
while (p < lastp)
|
2354 |
+
{
|
2355 |
+
i = m_huff_val[index][p];
|
2356 |
+
code = huffcode[p];
|
2357 |
+
code_size = huffsize[p];
|
2358 |
+
|
2359 |
+
pH->code_size[i] = static_cast<uint8>(code_size);
|
2360 |
+
|
2361 |
+
if (code_size <= 8)
|
2362 |
+
{
|
2363 |
+
code <<= (8 - code_size);
|
2364 |
+
|
2365 |
+
for (l = 1 << (8 - code_size); l > 0; l--)
|
2366 |
+
{
|
2367 |
+
JPGD_ASSERT(i < 256);
|
2368 |
+
|
2369 |
+
pH->look_up[code] = i;
|
2370 |
+
|
2371 |
+
bool has_extrabits = false;
|
2372 |
+
int extra_bits = 0;
|
2373 |
+
int num_extra_bits = i & 15;
|
2374 |
+
|
2375 |
+
int bits_to_fetch = code_size;
|
2376 |
+
if (num_extra_bits)
|
2377 |
+
{
|
2378 |
+
int total_codesize = code_size + num_extra_bits;
|
2379 |
+
if (total_codesize <= 8)
|
2380 |
+
{
|
2381 |
+
has_extrabits = true;
|
2382 |
+
extra_bits = ((1 << num_extra_bits) - 1) & (code >> (8 - total_codesize));
|
2383 |
+
JPGD_ASSERT(extra_bits <= 0x7FFF);
|
2384 |
+
bits_to_fetch += num_extra_bits;
|
2385 |
+
}
|
2386 |
+
}
|
2387 |
+
|
2388 |
+
if (!has_extrabits)
|
2389 |
+
pH->look_up2[code] = i | (bits_to_fetch << 8);
|
2390 |
+
else
|
2391 |
+
pH->look_up2[code] = i | 0x8000 | (extra_bits << 16) | (bits_to_fetch << 8);
|
2392 |
+
|
2393 |
+
code++;
|
2394 |
+
}
|
2395 |
+
}
|
2396 |
+
else
|
2397 |
+
{
|
2398 |
+
subtree = (code >> (code_size - 8)) & 0xFF;
|
2399 |
+
|
2400 |
+
currententry = pH->look_up[subtree];
|
2401 |
+
|
2402 |
+
if (currententry == 0)
|
2403 |
+
{
|
2404 |
+
pH->look_up[subtree] = currententry = nextfreeentry;
|
2405 |
+
pH->look_up2[subtree] = currententry = nextfreeentry;
|
2406 |
+
|
2407 |
+
nextfreeentry -= 2;
|
2408 |
+
}
|
2409 |
+
|
2410 |
+
code <<= (16 - (code_size - 8));
|
2411 |
+
|
2412 |
+
for (l = code_size; l > 9; l--)
|
2413 |
+
{
|
2414 |
+
if ((code & 0x8000) == 0)
|
2415 |
+
currententry--;
|
2416 |
+
|
2417 |
+
if (pH->tree[-currententry - 1] == 0)
|
2418 |
+
{
|
2419 |
+
pH->tree[-currententry - 1] = nextfreeentry;
|
2420 |
+
|
2421 |
+
currententry = nextfreeentry;
|
2422 |
+
|
2423 |
+
nextfreeentry -= 2;
|
2424 |
+
}
|
2425 |
+
else
|
2426 |
+
currententry = pH->tree[-currententry - 1];
|
2427 |
+
|
2428 |
+
code <<= 1;
|
2429 |
+
}
|
2430 |
+
|
2431 |
+
if ((code & 0x8000) == 0)
|
2432 |
+
currententry--;
|
2433 |
+
|
2434 |
+
pH->tree[-currententry - 1] = i;
|
2435 |
+
}
|
2436 |
+
|
2437 |
+
p++;
|
2438 |
+
}
|
2439 |
+
}
|
2440 |
+
|
2441 |
+
// Verifies the quantization tables needed for this scan are available.
|
2442 |
+
void jpeg_decoder::check_quant_tables()
|
2443 |
+
{
|
2444 |
+
for (int i = 0; i < m_comps_in_scan; i++)
|
2445 |
+
if (m_quant[m_comp_quant[m_comp_list[i]]] == NULL)
|
2446 |
+
stop_decoding(JPGD_UNDEFINED_QUANT_TABLE);
|
2447 |
+
}
|
2448 |
+
|
2449 |
+
// Verifies that all the Huffman tables needed for this scan are available.
|
2450 |
+
void jpeg_decoder::check_huff_tables()
|
2451 |
+
{
|
2452 |
+
for (int i = 0; i < m_comps_in_scan; i++)
|
2453 |
+
{
|
2454 |
+
if ((m_spectral_start == 0) && (m_huff_num[m_comp_dc_tab[m_comp_list[i]]] == NULL))
|
2455 |
+
stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
|
2456 |
+
|
2457 |
+
if ((m_spectral_end > 0) && (m_huff_num[m_comp_ac_tab[m_comp_list[i]]] == NULL))
|
2458 |
+
stop_decoding(JPGD_UNDEFINED_HUFF_TABLE);
|
2459 |
+
}
|
2460 |
+
|
2461 |
+
for (int i = 0; i < JPGD_MAX_HUFF_TABLES; i++)
|
2462 |
+
if (m_huff_num[i])
|
2463 |
+
{
|
2464 |
+
if (!m_pHuff_tabs[i])
|
2465 |
+
m_pHuff_tabs[i] = (huff_tables *)alloc(sizeof(huff_tables));
|
2466 |
+
|
2467 |
+
make_huff_table(i, m_pHuff_tabs[i]);
|
2468 |
+
}
|
2469 |
+
}
|
2470 |
+
|
2471 |
+
// Determines the component order inside each MCU.
|
2472 |
+
// Also calcs how many MCU's are on each row, etc.
|
2473 |
+
void jpeg_decoder::calc_mcu_block_order()
|
2474 |
+
{
|
2475 |
+
int component_num, component_id;
|
2476 |
+
int max_h_samp = 0, max_v_samp = 0;
|
2477 |
+
|
2478 |
+
for (component_id = 0; component_id < m_comps_in_frame; component_id++)
|
2479 |
+
{
|
2480 |
+
if (m_comp_h_samp[component_id] > max_h_samp)
|
2481 |
+
max_h_samp = m_comp_h_samp[component_id];
|
2482 |
+
|
2483 |
+
if (m_comp_v_samp[component_id] > max_v_samp)
|
2484 |
+
max_v_samp = m_comp_v_samp[component_id];
|
2485 |
+
}
|
2486 |
+
|
2487 |
+
for (component_id = 0; component_id < m_comps_in_frame; component_id++)
|
2488 |
+
{
|
2489 |
+
m_comp_h_blocks[component_id] = ((((m_image_x_size * m_comp_h_samp[component_id]) + (max_h_samp - 1)) / max_h_samp) + 7) / 8;
|
2490 |
+
m_comp_v_blocks[component_id] = ((((m_image_y_size * m_comp_v_samp[component_id]) + (max_v_samp - 1)) / max_v_samp) + 7) / 8;
|
2491 |
+
}
|
2492 |
+
|
2493 |
+
if (m_comps_in_scan == 1)
|
2494 |
+
{
|
2495 |
+
m_mcus_per_row = m_comp_h_blocks[m_comp_list[0]];
|
2496 |
+
m_mcus_per_col = m_comp_v_blocks[m_comp_list[0]];
|
2497 |
+
}
|
2498 |
+
else
|
2499 |
+
{
|
2500 |
+
m_mcus_per_row = (((m_image_x_size + 7) / 8) + (max_h_samp - 1)) / max_h_samp;
|
2501 |
+
m_mcus_per_col = (((m_image_y_size + 7) / 8) + (max_v_samp - 1)) / max_v_samp;
|
2502 |
+
}
|
2503 |
+
|
2504 |
+
if (m_comps_in_scan == 1)
|
2505 |
+
{
|
2506 |
+
m_mcu_org[0] = m_comp_list[0];
|
2507 |
+
|
2508 |
+
m_blocks_per_mcu = 1;
|
2509 |
+
}
|
2510 |
+
else
|
2511 |
+
{
|
2512 |
+
m_blocks_per_mcu = 0;
|
2513 |
+
|
2514 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
2515 |
+
{
|
2516 |
+
int num_blocks;
|
2517 |
+
|
2518 |
+
component_id = m_comp_list[component_num];
|
2519 |
+
|
2520 |
+
num_blocks = m_comp_h_samp[component_id] * m_comp_v_samp[component_id];
|
2521 |
+
|
2522 |
+
while (num_blocks--)
|
2523 |
+
m_mcu_org[m_blocks_per_mcu++] = component_id;
|
2524 |
+
}
|
2525 |
+
}
|
2526 |
+
}
|
2527 |
+
|
2528 |
+
// Starts a new scan.
|
2529 |
+
int jpeg_decoder::init_scan()
|
2530 |
+
{
|
2531 |
+
if (!locate_sos_marker())
|
2532 |
+
return JPGD_FALSE;
|
2533 |
+
|
2534 |
+
calc_mcu_block_order();
|
2535 |
+
|
2536 |
+
check_huff_tables();
|
2537 |
+
|
2538 |
+
check_quant_tables();
|
2539 |
+
|
2540 |
+
memset(m_last_dc_val, 0, m_comps_in_frame * sizeof(uint));
|
2541 |
+
|
2542 |
+
m_eob_run = 0;
|
2543 |
+
|
2544 |
+
if (m_restart_interval)
|
2545 |
+
{
|
2546 |
+
m_restarts_left = m_restart_interval;
|
2547 |
+
m_next_restart_num = 0;
|
2548 |
+
}
|
2549 |
+
|
2550 |
+
fix_in_buffer();
|
2551 |
+
|
2552 |
+
return JPGD_TRUE;
|
2553 |
+
}
|
2554 |
+
|
2555 |
+
// Starts a frame. Determines if the number of components or sampling factors
|
2556 |
+
// are supported.
|
2557 |
+
void jpeg_decoder::init_frame()
|
2558 |
+
{
|
2559 |
+
int i;
|
2560 |
+
|
2561 |
+
if (m_comps_in_frame == 1)
|
2562 |
+
{
|
2563 |
+
if ((m_comp_h_samp[0] != 1) || (m_comp_v_samp[0] != 1))
|
2564 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2565 |
+
|
2566 |
+
m_scan_type = JPGD_GRAYSCALE;
|
2567 |
+
m_max_blocks_per_mcu = 1;
|
2568 |
+
m_max_mcu_x_size = 8;
|
2569 |
+
m_max_mcu_y_size = 8;
|
2570 |
+
}
|
2571 |
+
else if (m_comps_in_frame == 3)
|
2572 |
+
{
|
2573 |
+
if ( ((m_comp_h_samp[1] != 1) || (m_comp_v_samp[1] != 1)) ||
|
2574 |
+
((m_comp_h_samp[2] != 1) || (m_comp_v_samp[2] != 1)) )
|
2575 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2576 |
+
|
2577 |
+
if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
|
2578 |
+
{
|
2579 |
+
m_scan_type = JPGD_YH1V1;
|
2580 |
+
|
2581 |
+
m_max_blocks_per_mcu = 3;
|
2582 |
+
m_max_mcu_x_size = 8;
|
2583 |
+
m_max_mcu_y_size = 8;
|
2584 |
+
}
|
2585 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
|
2586 |
+
{
|
2587 |
+
m_scan_type = JPGD_YH2V1;
|
2588 |
+
m_max_blocks_per_mcu = 4;
|
2589 |
+
m_max_mcu_x_size = 16;
|
2590 |
+
m_max_mcu_y_size = 8;
|
2591 |
+
}
|
2592 |
+
else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 2))
|
2593 |
+
{
|
2594 |
+
m_scan_type = JPGD_YH1V2;
|
2595 |
+
m_max_blocks_per_mcu = 4;
|
2596 |
+
m_max_mcu_x_size = 8;
|
2597 |
+
m_max_mcu_y_size = 16;
|
2598 |
+
}
|
2599 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
|
2600 |
+
{
|
2601 |
+
m_scan_type = JPGD_YH2V2;
|
2602 |
+
m_max_blocks_per_mcu = 6;
|
2603 |
+
m_max_mcu_x_size = 16;
|
2604 |
+
m_max_mcu_y_size = 16;
|
2605 |
+
}
|
2606 |
+
else
|
2607 |
+
stop_decoding(JPGD_UNSUPPORTED_SAMP_FACTORS);
|
2608 |
+
}
|
2609 |
+
else
|
2610 |
+
stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
|
2611 |
+
|
2612 |
+
m_max_mcus_per_row = (m_image_x_size + (m_max_mcu_x_size - 1)) / m_max_mcu_x_size;
|
2613 |
+
m_max_mcus_per_col = (m_image_y_size + (m_max_mcu_y_size - 1)) / m_max_mcu_y_size;
|
2614 |
+
|
2615 |
+
// These values are for the *destination* pixels: after conversion.
|
2616 |
+
if (m_scan_type == JPGD_GRAYSCALE)
|
2617 |
+
m_dest_bytes_per_pixel = 1;
|
2618 |
+
else
|
2619 |
+
m_dest_bytes_per_pixel = 4;
|
2620 |
+
|
2621 |
+
m_dest_bytes_per_scan_line = ((m_image_x_size + 15) & 0xFFF0) * m_dest_bytes_per_pixel;
|
2622 |
+
|
2623 |
+
m_real_dest_bytes_per_scan_line = (m_image_x_size * m_dest_bytes_per_pixel);
|
2624 |
+
|
2625 |
+
// Initialize two scan line buffers.
|
2626 |
+
m_pScan_line_0 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
|
2627 |
+
if ((m_scan_type == JPGD_YH1V2) || (m_scan_type == JPGD_YH2V2))
|
2628 |
+
m_pScan_line_1 = (uint8 *)alloc(m_dest_bytes_per_scan_line, true);
|
2629 |
+
|
2630 |
+
m_max_blocks_per_row = m_max_mcus_per_row * m_max_blocks_per_mcu;
|
2631 |
+
|
2632 |
+
// Should never happen
|
2633 |
+
if (m_max_blocks_per_row > JPGD_MAX_BLOCKS_PER_ROW)
|
2634 |
+
stop_decoding(JPGD_ASSERTION_ERROR);
|
2635 |
+
|
2636 |
+
// Allocate the coefficient buffer, enough for one MCU
|
2637 |
+
m_pMCU_coefficients = (jpgd_block_t*)alloc(m_max_blocks_per_mcu * 64 * sizeof(jpgd_block_t));
|
2638 |
+
|
2639 |
+
for (i = 0; i < m_max_blocks_per_mcu; i++)
|
2640 |
+
m_mcu_block_max_zag[i] = 64;
|
2641 |
+
|
2642 |
+
m_expanded_blocks_per_component = m_comp_h_samp[0] * m_comp_v_samp[0];
|
2643 |
+
m_expanded_blocks_per_mcu = m_expanded_blocks_per_component * m_comps_in_frame;
|
2644 |
+
m_expanded_blocks_per_row = m_max_mcus_per_row * m_expanded_blocks_per_mcu;
|
2645 |
+
// Freq. domain chroma upsampling is only supported for H2V2 subsampling factor.
|
2646 |
+
// BEGIN EPIC MOD
|
2647 |
+
#if JPGD_SUPPORT_FREQ_DOMAIN_UPSAMPLING
|
2648 |
+
m_freq_domain_chroma_upsample = (m_expanded_blocks_per_mcu == 4*3);
|
2649 |
+
#else
|
2650 |
+
m_freq_domain_chroma_upsample = 0;
|
2651 |
+
#endif
|
2652 |
+
// END EPIC MOD
|
2653 |
+
|
2654 |
+
if (m_freq_domain_chroma_upsample)
|
2655 |
+
m_pSample_buf = (uint8 *)alloc(m_expanded_blocks_per_row * 64);
|
2656 |
+
else
|
2657 |
+
m_pSample_buf = (uint8 *)alloc(m_max_blocks_per_row * 64);
|
2658 |
+
|
2659 |
+
m_total_lines_left = m_image_y_size;
|
2660 |
+
|
2661 |
+
m_mcu_lines_left = 0;
|
2662 |
+
|
2663 |
+
create_look_ups();
|
2664 |
+
}
|
2665 |
+
|
2666 |
+
// The coeff_buf series of methods originally stored the coefficients
|
2667 |
+
// into a "virtual" file which was located in EMS, XMS, or a disk file. A cache
|
2668 |
+
// was used to make this process more efficient. Now, we can store the entire
|
2669 |
+
// thing in RAM.
|
2670 |
+
jpeg_decoder::coeff_buf* jpeg_decoder::coeff_buf_open(int block_num_x, int block_num_y, int block_len_x, int block_len_y)
|
2671 |
+
{
|
2672 |
+
coeff_buf* cb = (coeff_buf*)alloc(sizeof(coeff_buf));
|
2673 |
+
|
2674 |
+
cb->block_num_x = block_num_x;
|
2675 |
+
cb->block_num_y = block_num_y;
|
2676 |
+
cb->block_len_x = block_len_x;
|
2677 |
+
cb->block_len_y = block_len_y;
|
2678 |
+
cb->block_size = (block_len_x * block_len_y) * sizeof(jpgd_block_t);
|
2679 |
+
cb->pData = (uint8 *)alloc(cb->block_size * block_num_x * block_num_y, true);
|
2680 |
+
return cb;
|
2681 |
+
}
|
2682 |
+
|
2683 |
+
inline jpgd_block_t *jpeg_decoder::coeff_buf_getp(coeff_buf *cb, int block_x, int block_y)
|
2684 |
+
{
|
2685 |
+
JPGD_ASSERT((block_x < cb->block_num_x) && (block_y < cb->block_num_y));
|
2686 |
+
return (jpgd_block_t *)(cb->pData + block_x * cb->block_size + block_y * (cb->block_size * cb->block_num_x));
|
2687 |
+
}
|
2688 |
+
|
2689 |
+
// The following methods decode the various types of m_blocks encountered
|
2690 |
+
// in progressively encoded images.
|
2691 |
+
void jpeg_decoder::decode_block_dc_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2692 |
+
{
|
2693 |
+
int s, r;
|
2694 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
|
2695 |
+
|
2696 |
+
if ((s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_dc_tab[component_id]])) != 0)
|
2697 |
+
{
|
2698 |
+
r = pD->get_bits_no_markers(s);
|
2699 |
+
s = HUFF_EXTEND(r, s);
|
2700 |
+
}
|
2701 |
+
|
2702 |
+
pD->m_last_dc_val[component_id] = (s += pD->m_last_dc_val[component_id]);
|
2703 |
+
|
2704 |
+
p[0] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
|
2705 |
+
}
|
2706 |
+
|
2707 |
+
void jpeg_decoder::decode_block_dc_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2708 |
+
{
|
2709 |
+
if (pD->get_bits_no_markers(1))
|
2710 |
+
{
|
2711 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_dc_coeffs[component_id], block_x, block_y);
|
2712 |
+
|
2713 |
+
p[0] |= (1 << pD->m_successive_low);
|
2714 |
+
}
|
2715 |
+
}
|
2716 |
+
|
2717 |
+
void jpeg_decoder::decode_block_ac_first(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2718 |
+
{
|
2719 |
+
int k, s, r;
|
2720 |
+
|
2721 |
+
if (pD->m_eob_run)
|
2722 |
+
{
|
2723 |
+
pD->m_eob_run--;
|
2724 |
+
return;
|
2725 |
+
}
|
2726 |
+
|
2727 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
|
2728 |
+
|
2729 |
+
for (k = pD->m_spectral_start; k <= pD->m_spectral_end; k++)
|
2730 |
+
{
|
2731 |
+
s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
|
2732 |
+
|
2733 |
+
r = s >> 4;
|
2734 |
+
s &= 15;
|
2735 |
+
|
2736 |
+
if (s)
|
2737 |
+
{
|
2738 |
+
if ((k += r) > 63)
|
2739 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2740 |
+
|
2741 |
+
r = pD->get_bits_no_markers(s);
|
2742 |
+
s = HUFF_EXTEND(r, s);
|
2743 |
+
|
2744 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(s << pD->m_successive_low);
|
2745 |
+
}
|
2746 |
+
else
|
2747 |
+
{
|
2748 |
+
if (r == 15)
|
2749 |
+
{
|
2750 |
+
if ((k += 15) > 63)
|
2751 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2752 |
+
}
|
2753 |
+
else
|
2754 |
+
{
|
2755 |
+
pD->m_eob_run = 1 << r;
|
2756 |
+
|
2757 |
+
if (r)
|
2758 |
+
pD->m_eob_run += pD->get_bits_no_markers(r);
|
2759 |
+
|
2760 |
+
pD->m_eob_run--;
|
2761 |
+
|
2762 |
+
break;
|
2763 |
+
}
|
2764 |
+
}
|
2765 |
+
}
|
2766 |
+
}
|
2767 |
+
|
2768 |
+
void jpeg_decoder::decode_block_ac_refine(jpeg_decoder *pD, int component_id, int block_x, int block_y)
|
2769 |
+
{
|
2770 |
+
int s, k, r;
|
2771 |
+
int p1 = 1 << pD->m_successive_low;
|
2772 |
+
int m1 = (-1) << pD->m_successive_low;
|
2773 |
+
jpgd_block_t *p = pD->coeff_buf_getp(pD->m_ac_coeffs[component_id], block_x, block_y);
|
2774 |
+
|
2775 |
+
k = pD->m_spectral_start;
|
2776 |
+
|
2777 |
+
if (pD->m_eob_run == 0)
|
2778 |
+
{
|
2779 |
+
for ( ; k <= pD->m_spectral_end; k++)
|
2780 |
+
{
|
2781 |
+
s = pD->huff_decode(pD->m_pHuff_tabs[pD->m_comp_ac_tab[component_id]]);
|
2782 |
+
|
2783 |
+
r = s >> 4;
|
2784 |
+
s &= 15;
|
2785 |
+
|
2786 |
+
if (s)
|
2787 |
+
{
|
2788 |
+
if (s != 1)
|
2789 |
+
pD->stop_decoding(JPGD_DECODE_ERROR);
|
2790 |
+
|
2791 |
+
if (pD->get_bits_no_markers(1))
|
2792 |
+
s = p1;
|
2793 |
+
else
|
2794 |
+
s = m1;
|
2795 |
+
}
|
2796 |
+
else
|
2797 |
+
{
|
2798 |
+
if (r != 15)
|
2799 |
+
{
|
2800 |
+
pD->m_eob_run = 1 << r;
|
2801 |
+
|
2802 |
+
if (r)
|
2803 |
+
pD->m_eob_run += pD->get_bits_no_markers(r);
|
2804 |
+
|
2805 |
+
break;
|
2806 |
+
}
|
2807 |
+
}
|
2808 |
+
|
2809 |
+
do
|
2810 |
+
{
|
2811 |
+
// BEGIN EPIC MOD
|
2812 |
+
JPGD_ASSERT(k < 64);
|
2813 |
+
// END EPIC MOD
|
2814 |
+
|
2815 |
+
jpgd_block_t *this_coef = p + g_ZAG[k];
|
2816 |
+
|
2817 |
+
if (*this_coef != 0)
|
2818 |
+
{
|
2819 |
+
if (pD->get_bits_no_markers(1))
|
2820 |
+
{
|
2821 |
+
if ((*this_coef & p1) == 0)
|
2822 |
+
{
|
2823 |
+
if (*this_coef >= 0)
|
2824 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
|
2825 |
+
else
|
2826 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
|
2827 |
+
}
|
2828 |
+
}
|
2829 |
+
}
|
2830 |
+
else
|
2831 |
+
{
|
2832 |
+
if (--r < 0)
|
2833 |
+
break;
|
2834 |
+
}
|
2835 |
+
|
2836 |
+
k++;
|
2837 |
+
|
2838 |
+
} while (k <= pD->m_spectral_end);
|
2839 |
+
|
2840 |
+
if ((s) && (k < 64))
|
2841 |
+
{
|
2842 |
+
p[g_ZAG[k]] = static_cast<jpgd_block_t>(s);
|
2843 |
+
}
|
2844 |
+
}
|
2845 |
+
}
|
2846 |
+
|
2847 |
+
if (pD->m_eob_run > 0)
|
2848 |
+
{
|
2849 |
+
for ( ; k <= pD->m_spectral_end; k++)
|
2850 |
+
{
|
2851 |
+
// BEGIN EPIC MOD
|
2852 |
+
JPGD_ASSERT(k < 64);
|
2853 |
+
// END EPIC MOD
|
2854 |
+
|
2855 |
+
jpgd_block_t *this_coef = p + g_ZAG[k];
|
2856 |
+
|
2857 |
+
if (*this_coef != 0)
|
2858 |
+
{
|
2859 |
+
if (pD->get_bits_no_markers(1))
|
2860 |
+
{
|
2861 |
+
if ((*this_coef & p1) == 0)
|
2862 |
+
{
|
2863 |
+
if (*this_coef >= 0)
|
2864 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + p1);
|
2865 |
+
else
|
2866 |
+
*this_coef = static_cast<jpgd_block_t>(*this_coef + m1);
|
2867 |
+
}
|
2868 |
+
}
|
2869 |
+
}
|
2870 |
+
}
|
2871 |
+
|
2872 |
+
pD->m_eob_run--;
|
2873 |
+
}
|
2874 |
+
}
|
2875 |
+
|
2876 |
+
// Decode a scan in a progressively encoded image.
|
2877 |
+
void jpeg_decoder::decode_scan(pDecode_block_func decode_block_func)
|
2878 |
+
{
|
2879 |
+
int mcu_row, mcu_col, mcu_block;
|
2880 |
+
int block_x_mcu[JPGD_MAX_COMPONENTS], m_block_y_mcu[JPGD_MAX_COMPONENTS];
|
2881 |
+
|
2882 |
+
memset(m_block_y_mcu, 0, sizeof(m_block_y_mcu));
|
2883 |
+
|
2884 |
+
for (mcu_col = 0; mcu_col < m_mcus_per_col; mcu_col++)
|
2885 |
+
{
|
2886 |
+
int component_num, component_id;
|
2887 |
+
|
2888 |
+
memset(block_x_mcu, 0, sizeof(block_x_mcu));
|
2889 |
+
|
2890 |
+
for (mcu_row = 0; mcu_row < m_mcus_per_row; mcu_row++)
|
2891 |
+
{
|
2892 |
+
int block_x_mcu_ofs = 0, block_y_mcu_ofs = 0;
|
2893 |
+
|
2894 |
+
if ((m_restart_interval) && (m_restarts_left == 0))
|
2895 |
+
process_restart();
|
2896 |
+
|
2897 |
+
for (mcu_block = 0; mcu_block < m_blocks_per_mcu; mcu_block++)
|
2898 |
+
{
|
2899 |
+
component_id = m_mcu_org[mcu_block];
|
2900 |
+
|
2901 |
+
decode_block_func(this, component_id, block_x_mcu[component_id] + block_x_mcu_ofs, m_block_y_mcu[component_id] + block_y_mcu_ofs);
|
2902 |
+
|
2903 |
+
if (m_comps_in_scan == 1)
|
2904 |
+
block_x_mcu[component_id]++;
|
2905 |
+
else
|
2906 |
+
{
|
2907 |
+
if (++block_x_mcu_ofs == m_comp_h_samp[component_id])
|
2908 |
+
{
|
2909 |
+
block_x_mcu_ofs = 0;
|
2910 |
+
|
2911 |
+
if (++block_y_mcu_ofs == m_comp_v_samp[component_id])
|
2912 |
+
{
|
2913 |
+
block_y_mcu_ofs = 0;
|
2914 |
+
block_x_mcu[component_id] += m_comp_h_samp[component_id];
|
2915 |
+
}
|
2916 |
+
}
|
2917 |
+
}
|
2918 |
+
}
|
2919 |
+
|
2920 |
+
m_restarts_left--;
|
2921 |
+
}
|
2922 |
+
|
2923 |
+
if (m_comps_in_scan == 1)
|
2924 |
+
m_block_y_mcu[m_comp_list[0]]++;
|
2925 |
+
else
|
2926 |
+
{
|
2927 |
+
for (component_num = 0; component_num < m_comps_in_scan; component_num++)
|
2928 |
+
{
|
2929 |
+
component_id = m_comp_list[component_num];
|
2930 |
+
m_block_y_mcu[component_id] += m_comp_v_samp[component_id];
|
2931 |
+
}
|
2932 |
+
}
|
2933 |
+
}
|
2934 |
+
}
|
2935 |
+
|
2936 |
+
// Decode a progressively encoded image.
|
2937 |
+
void jpeg_decoder::init_progressive()
|
2938 |
+
{
|
2939 |
+
int i;
|
2940 |
+
|
2941 |
+
if (m_comps_in_frame == 4)
|
2942 |
+
stop_decoding(JPGD_UNSUPPORTED_COLORSPACE);
|
2943 |
+
|
2944 |
+
// Allocate the coefficient buffers.
|
2945 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
2946 |
+
{
|
2947 |
+
m_dc_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 1, 1);
|
2948 |
+
m_ac_coeffs[i] = coeff_buf_open(m_max_mcus_per_row * m_comp_h_samp[i], m_max_mcus_per_col * m_comp_v_samp[i], 8, 8);
|
2949 |
+
}
|
2950 |
+
|
2951 |
+
for ( ; ; )
|
2952 |
+
{
|
2953 |
+
int dc_only_scan, refinement_scan;
|
2954 |
+
pDecode_block_func decode_block_func;
|
2955 |
+
|
2956 |
+
if (!init_scan())
|
2957 |
+
break;
|
2958 |
+
|
2959 |
+
dc_only_scan = (m_spectral_start == 0);
|
2960 |
+
refinement_scan = (m_successive_high != 0);
|
2961 |
+
|
2962 |
+
if ((m_spectral_start > m_spectral_end) || (m_spectral_end > 63))
|
2963 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2964 |
+
|
2965 |
+
if (dc_only_scan)
|
2966 |
+
{
|
2967 |
+
if (m_spectral_end)
|
2968 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2969 |
+
}
|
2970 |
+
else if (m_comps_in_scan != 1) /* AC scans can only contain one component */
|
2971 |
+
stop_decoding(JPGD_BAD_SOS_SPECTRAL);
|
2972 |
+
|
2973 |
+
if ((refinement_scan) && (m_successive_low != m_successive_high - 1))
|
2974 |
+
stop_decoding(JPGD_BAD_SOS_SUCCESSIVE);
|
2975 |
+
|
2976 |
+
if (dc_only_scan)
|
2977 |
+
{
|
2978 |
+
if (refinement_scan)
|
2979 |
+
decode_block_func = decode_block_dc_refine;
|
2980 |
+
else
|
2981 |
+
decode_block_func = decode_block_dc_first;
|
2982 |
+
}
|
2983 |
+
else
|
2984 |
+
{
|
2985 |
+
if (refinement_scan)
|
2986 |
+
decode_block_func = decode_block_ac_refine;
|
2987 |
+
else
|
2988 |
+
decode_block_func = decode_block_ac_first;
|
2989 |
+
}
|
2990 |
+
|
2991 |
+
decode_scan(decode_block_func);
|
2992 |
+
|
2993 |
+
m_bits_left = 16;
|
2994 |
+
get_bits(16);
|
2995 |
+
get_bits(16);
|
2996 |
+
}
|
2997 |
+
|
2998 |
+
m_comps_in_scan = m_comps_in_frame;
|
2999 |
+
|
3000 |
+
for (i = 0; i < m_comps_in_frame; i++)
|
3001 |
+
m_comp_list[i] = i;
|
3002 |
+
|
3003 |
+
calc_mcu_block_order();
|
3004 |
+
}
|
3005 |
+
|
3006 |
+
void jpeg_decoder::init_sequential()
|
3007 |
+
{
|
3008 |
+
if (!init_scan())
|
3009 |
+
stop_decoding(JPGD_UNEXPECTED_MARKER);
|
3010 |
+
}
|
3011 |
+
|
3012 |
+
void jpeg_decoder::decode_start()
|
3013 |
+
{
|
3014 |
+
init_frame();
|
3015 |
+
|
3016 |
+
if (m_progressive_flag)
|
3017 |
+
init_progressive();
|
3018 |
+
else
|
3019 |
+
init_sequential();
|
3020 |
+
}
|
3021 |
+
|
3022 |
+
void jpeg_decoder::decode_init(jpeg_decoder_stream *pStream)
|
3023 |
+
{
|
3024 |
+
init(pStream);
|
3025 |
+
locate_sof_marker();
|
3026 |
+
}
|
3027 |
+
|
3028 |
+
jpeg_decoder::jpeg_decoder(jpeg_decoder_stream *pStream)
|
3029 |
+
{
|
3030 |
+
if (setjmp(m_jmp_state))
|
3031 |
+
return;
|
3032 |
+
decode_init(pStream);
|
3033 |
+
}
|
3034 |
+
|
3035 |
+
int jpeg_decoder::begin_decoding()
|
3036 |
+
{
|
3037 |
+
if (m_ready_flag)
|
3038 |
+
return JPGD_SUCCESS;
|
3039 |
+
|
3040 |
+
if (m_error_code)
|
3041 |
+
return JPGD_FAILED;
|
3042 |
+
|
3043 |
+
if (setjmp(m_jmp_state))
|
3044 |
+
return JPGD_FAILED;
|
3045 |
+
|
3046 |
+
decode_start();
|
3047 |
+
|
3048 |
+
m_ready_flag = true;
|
3049 |
+
|
3050 |
+
return JPGD_SUCCESS;
|
3051 |
+
}
|
3052 |
+
|
3053 |
+
jpeg_decoder::~jpeg_decoder()
|
3054 |
+
{
|
3055 |
+
free_all_blocks();
|
3056 |
+
}
|
3057 |
+
|
3058 |
+
jpeg_decoder_file_stream::jpeg_decoder_file_stream()
|
3059 |
+
{
|
3060 |
+
m_pFile = NULL;
|
3061 |
+
m_eof_flag = false;
|
3062 |
+
m_error_flag = false;
|
3063 |
+
}
|
3064 |
+
|
3065 |
+
void jpeg_decoder_file_stream::close()
|
3066 |
+
{
|
3067 |
+
if (m_pFile)
|
3068 |
+
{
|
3069 |
+
fclose(m_pFile);
|
3070 |
+
m_pFile = NULL;
|
3071 |
+
}
|
3072 |
+
|
3073 |
+
m_eof_flag = false;
|
3074 |
+
m_error_flag = false;
|
3075 |
+
}
|
3076 |
+
|
3077 |
+
jpeg_decoder_file_stream::~jpeg_decoder_file_stream()
|
3078 |
+
{
|
3079 |
+
close();
|
3080 |
+
}
|
3081 |
+
|
3082 |
+
bool jpeg_decoder_file_stream::open(const char *Pfilename)
|
3083 |
+
{
|
3084 |
+
close();
|
3085 |
+
|
3086 |
+
m_eof_flag = false;
|
3087 |
+
m_error_flag = false;
|
3088 |
+
|
3089 |
+
#if defined(_MSC_VER)
|
3090 |
+
m_pFile = NULL;
|
3091 |
+
fopen_s(&m_pFile, Pfilename, "rb");
|
3092 |
+
#else
|
3093 |
+
m_pFile = fopen(Pfilename, "rb");
|
3094 |
+
#endif
|
3095 |
+
return m_pFile != NULL;
|
3096 |
+
}
|
3097 |
+
|
3098 |
+
int jpeg_decoder_file_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
|
3099 |
+
{
|
3100 |
+
if (!m_pFile)
|
3101 |
+
return -1;
|
3102 |
+
|
3103 |
+
if (m_eof_flag)
|
3104 |
+
{
|
3105 |
+
*pEOF_flag = true;
|
3106 |
+
return 0;
|
3107 |
+
}
|
3108 |
+
|
3109 |
+
if (m_error_flag)
|
3110 |
+
return -1;
|
3111 |
+
|
3112 |
+
int bytes_read = static_cast<int>(fread(pBuf, 1, max_bytes_to_read, m_pFile));
|
3113 |
+
if (bytes_read < max_bytes_to_read)
|
3114 |
+
{
|
3115 |
+
if (ferror(m_pFile))
|
3116 |
+
{
|
3117 |
+
m_error_flag = true;
|
3118 |
+
return -1;
|
3119 |
+
}
|
3120 |
+
|
3121 |
+
m_eof_flag = true;
|
3122 |
+
*pEOF_flag = true;
|
3123 |
+
}
|
3124 |
+
|
3125 |
+
return bytes_read;
|
3126 |
+
}
|
3127 |
+
|
3128 |
+
bool jpeg_decoder_mem_stream::open(const uint8 *pSrc_data, uint size)
|
3129 |
+
{
|
3130 |
+
close();
|
3131 |
+
m_pSrc_data = pSrc_data;
|
3132 |
+
m_ofs = 0;
|
3133 |
+
m_size = size;
|
3134 |
+
return true;
|
3135 |
+
}
|
3136 |
+
|
3137 |
+
int jpeg_decoder_mem_stream::read(uint8 *pBuf, int max_bytes_to_read, bool *pEOF_flag)
|
3138 |
+
{
|
3139 |
+
*pEOF_flag = false;
|
3140 |
+
|
3141 |
+
if (!m_pSrc_data)
|
3142 |
+
return -1;
|
3143 |
+
|
3144 |
+
uint bytes_remaining = m_size - m_ofs;
|
3145 |
+
if ((uint)max_bytes_to_read > bytes_remaining)
|
3146 |
+
{
|
3147 |
+
max_bytes_to_read = bytes_remaining;
|
3148 |
+
*pEOF_flag = true;
|
3149 |
+
}
|
3150 |
+
|
3151 |
+
memcpy(pBuf, m_pSrc_data + m_ofs, max_bytes_to_read);
|
3152 |
+
m_ofs += max_bytes_to_read;
|
3153 |
+
|
3154 |
+
return max_bytes_to_read;
|
3155 |
+
}
|
3156 |
+
|
3157 |
+
unsigned char *decompress_jpeg_image_from_stream(jpeg_decoder_stream *pStream, int *width, int *height, int *actual_comps, int req_comps)
|
3158 |
+
{
|
3159 |
+
if (!actual_comps)
|
3160 |
+
return NULL;
|
3161 |
+
*actual_comps = 0;
|
3162 |
+
|
3163 |
+
if ((!pStream) || (!width) || (!height) || (!req_comps))
|
3164 |
+
return NULL;
|
3165 |
+
|
3166 |
+
if ((req_comps != 1) && (req_comps != 3) && (req_comps != 4))
|
3167 |
+
return NULL;
|
3168 |
+
|
3169 |
+
jpeg_decoder decoder(pStream);
|
3170 |
+
if (decoder.get_error_code() != JPGD_SUCCESS)
|
3171 |
+
return NULL;
|
3172 |
+
|
3173 |
+
const int image_width = decoder.get_width(), image_height = decoder.get_height();
|
3174 |
+
*width = image_width;
|
3175 |
+
*height = image_height;
|
3176 |
+
*actual_comps = decoder.get_num_components();
|
3177 |
+
|
3178 |
+
if (decoder.begin_decoding() != JPGD_SUCCESS)
|
3179 |
+
return NULL;
|
3180 |
+
|
3181 |
+
const int dst_bpl = image_width * req_comps;
|
3182 |
+
|
3183 |
+
uint8 *pImage_data = (uint8*)jpgd_malloc(dst_bpl * image_height);
|
3184 |
+
if (!pImage_data)
|
3185 |
+
return NULL;
|
3186 |
+
|
3187 |
+
for (int y = 0; y < image_height; y++)
|
3188 |
+
{
|
3189 |
+
const uint8* pScan_line = 0;
|
3190 |
+
uint scan_line_len;
|
3191 |
+
if (decoder.decode((const void**)&pScan_line, &scan_line_len) != JPGD_SUCCESS)
|
3192 |
+
{
|
3193 |
+
jpgd_free(pImage_data);
|
3194 |
+
return NULL;
|
3195 |
+
}
|
3196 |
+
|
3197 |
+
uint8 *pDst = pImage_data + y * dst_bpl;
|
3198 |
+
|
3199 |
+
if (((req_comps == 4) && (decoder.get_num_components() == 3)) ||
|
3200 |
+
((req_comps == 1) && (decoder.get_num_components() == 1)))
|
3201 |
+
{
|
3202 |
+
memcpy(pDst, pScan_line, dst_bpl);
|
3203 |
+
}
|
3204 |
+
else if (decoder.get_num_components() == 1)
|
3205 |
+
{
|
3206 |
+
if (req_comps == 3)
|
3207 |
+
{
|
3208 |
+
for (int x = 0; x < image_width; x++)
|
3209 |
+
{
|
3210 |
+
uint8 luma = pScan_line[x];
|
3211 |
+
pDst[0] = luma;
|
3212 |
+
pDst[1] = luma;
|
3213 |
+
pDst[2] = luma;
|
3214 |
+
pDst += 3;
|
3215 |
+
}
|
3216 |
+
}
|
3217 |
+
else
|
3218 |
+
{
|
3219 |
+
for (int x = 0; x < image_width; x++)
|
3220 |
+
{
|
3221 |
+
uint8 luma = pScan_line[x];
|
3222 |
+
pDst[0] = luma;
|
3223 |
+
pDst[1] = luma;
|
3224 |
+
pDst[2] = luma;
|
3225 |
+
pDst[3] = 255;
|
3226 |
+
pDst += 4;
|
3227 |
+
}
|
3228 |
+
}
|
3229 |
+
}
|
3230 |
+
else if (decoder.get_num_components() == 3)
|
3231 |
+
{
|
3232 |
+
if (req_comps == 1)
|
3233 |
+
{
|
3234 |
+
const int YR = 19595, YG = 38470, YB = 7471;
|
3235 |
+
for (int x = 0; x < image_width; x++)
|
3236 |
+
{
|
3237 |
+
int r = pScan_line[x*4+0];
|
3238 |
+
int g = pScan_line[x*4+1];
|
3239 |
+
int b = pScan_line[x*4+2];
|
3240 |
+
*pDst++ = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
3241 |
+
}
|
3242 |
+
}
|
3243 |
+
else
|
3244 |
+
{
|
3245 |
+
for (int x = 0; x < image_width; x++)
|
3246 |
+
{
|
3247 |
+
pDst[0] = pScan_line[x*4+0];
|
3248 |
+
pDst[1] = pScan_line[x*4+1];
|
3249 |
+
pDst[2] = pScan_line[x*4+2];
|
3250 |
+
pDst += 3;
|
3251 |
+
}
|
3252 |
+
}
|
3253 |
+
}
|
3254 |
+
}
|
3255 |
+
|
3256 |
+
return pImage_data;
|
3257 |
+
}
|
3258 |
+
|
3259 |
+
// BEGIN EPIC MOD
|
3260 |
+
unsigned char *decompress_jpeg_image_from_memory(const unsigned char *pSrc_data, int src_data_size, int *width, int *height, int *actual_comps, int req_comps, int format)
|
3261 |
+
{
|
3262 |
+
jpg_format = (ERGBFormatJPG)format;
|
3263 |
+
// EMD EPIC MOD
|
3264 |
+
jpgd::jpeg_decoder_mem_stream mem_stream(pSrc_data, src_data_size);
|
3265 |
+
return decompress_jpeg_image_from_stream(&mem_stream, width, height, actual_comps, req_comps);
|
3266 |
+
}
|
3267 |
+
|
3268 |
+
unsigned char *decompress_jpeg_image_from_file(const char *pSrc_filename, int *width, int *height, int *actual_comps, int req_comps)
|
3269 |
+
{
|
3270 |
+
jpgd::jpeg_decoder_file_stream file_stream;
|
3271 |
+
if (!file_stream.open(pSrc_filename))
|
3272 |
+
return NULL;
|
3273 |
+
return decompress_jpeg_image_from_stream(&file_stream, width, height, actual_comps, req_comps);
|
3274 |
+
}
|
3275 |
+
|
3276 |
+
} // namespace jpgd
|
crazy_functions/test_project/cpp/longcode/jpge.cpp
ADDED
@@ -0,0 +1,1049 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
// jpge.cpp - C++ class for JPEG compression.
|
2 |
+
// Public domain, Rich Geldreich <richgel99@gmail.com>
|
3 |
+
// v1.01, Dec. 18, 2010 - Initial release
|
4 |
+
// v1.02, Apr. 6, 2011 - Removed 2x2 ordered dither in H2V1 chroma subsampling method load_block_16_8_8(). (The rounding factor was 2, when it should have been 1. Either way, it wasn't helping.)
|
5 |
+
// v1.03, Apr. 16, 2011 - Added support for optimized Huffman code tables, optimized dynamic memory allocation down to only 1 alloc.
|
6 |
+
// Also from Alex Evans: Added RGBA support, linear memory allocator (no longer needed in v1.03).
|
7 |
+
// v1.04, May. 19, 2012: Forgot to set m_pFile ptr to NULL in cfile_stream::close(). Thanks to Owen Kaluza for reporting this bug.
|
8 |
+
// Code tweaks to fix VS2008 static code analysis warnings (all looked harmless).
|
9 |
+
// Code review revealed method load_block_16_8_8() (used for the non-default H2V1 sampling mode to downsample chroma) somehow didn't get the rounding factor fix from v1.02.
|
10 |
+
|
11 |
+
#include "jpge.h"
|
12 |
+
|
13 |
+
#include <stdlib.h>
|
14 |
+
#include <string.h>
|
15 |
+
#if PLATFORM_WINDOWS
|
16 |
+
#include <malloc.h>
|
17 |
+
#endif
|
18 |
+
|
19 |
+
#define JPGE_MAX(a,b) (((a)>(b))?(a):(b))
|
20 |
+
#define JPGE_MIN(a,b) (((a)<(b))?(a):(b))
|
21 |
+
|
22 |
+
namespace jpge {
|
23 |
+
|
24 |
+
static inline void *jpge_malloc(size_t nSize) { return FMemory::Malloc(nSize); }
|
25 |
+
static inline void jpge_free(void *p) { FMemory::Free(p);; }
|
26 |
+
|
27 |
+
// Various JPEG enums and tables.
|
28 |
+
enum { M_SOF0 = 0xC0, M_DHT = 0xC4, M_SOI = 0xD8, M_EOI = 0xD9, M_SOS = 0xDA, M_DQT = 0xDB, M_APP0 = 0xE0 };
|
29 |
+
enum { DC_LUM_CODES = 12, AC_LUM_CODES = 256, DC_CHROMA_CODES = 12, AC_CHROMA_CODES = 256, MAX_HUFF_SYMBOLS = 257, MAX_HUFF_CODESIZE = 32 };
|
30 |
+
|
31 |
+
static uint8 s_zag[64] = { 0,1,8,16,9,2,3,10,17,24,32,25,18,11,4,5,12,19,26,33,40,48,41,34,27,20,13,6,7,14,21,28,35,42,49,56,57,50,43,36,29,22,15,23,30,37,44,51,58,59,52,45,38,31,39,46,53,60,61,54,47,55,62,63 };
|
32 |
+
static int16 s_std_lum_quant[64] = { 16,11,12,14,12,10,16,14,13,14,18,17,16,19,24,40,26,24,22,22,24,49,35,37,29,40,58,51,61,60,57,51,56,55,64,72,92,78,64,68,87,69,55,56,80,109,81,87,95,98,103,104,103,62,77,113,121,112,100,120,92,101,103,99 };
|
33 |
+
static int16 s_std_croma_quant[64] = { 17,18,18,24,21,24,47,26,26,47,99,66,56,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99 };
|
34 |
+
static uint8 s_dc_lum_bits[17] = { 0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0 };
|
35 |
+
static uint8 s_dc_lum_val[DC_LUM_CODES] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
|
36 |
+
static uint8 s_ac_lum_bits[17] = { 0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,0x7d };
|
37 |
+
static uint8 s_ac_lum_val[AC_LUM_CODES] =
|
38 |
+
{
|
39 |
+
0x01,0x02,0x03,0x00,0x04,0x11,0x05,0x12,0x21,0x31,0x41,0x06,0x13,0x51,0x61,0x07,0x22,0x71,0x14,0x32,0x81,0x91,0xa1,0x08,0x23,0x42,0xb1,0xc1,0x15,0x52,0xd1,0xf0,
|
40 |
+
0x24,0x33,0x62,0x72,0x82,0x09,0x0a,0x16,0x17,0x18,0x19,0x1a,0x25,0x26,0x27,0x28,0x29,0x2a,0x34,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,0x49,
|
41 |
+
0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x83,0x84,0x85,0x86,0x87,0x88,0x89,
|
42 |
+
0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,0xc4,0xc5,
|
43 |
+
0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
|
44 |
+
0xf9,0xfa
|
45 |
+
};
|
46 |
+
static uint8 s_dc_chroma_bits[17] = { 0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0 };
|
47 |
+
static uint8 s_dc_chroma_val[DC_CHROMA_CODES] = { 0,1,2,3,4,5,6,7,8,9,10,11 };
|
48 |
+
static uint8 s_ac_chroma_bits[17] = { 0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,0x77 };
|
49 |
+
static uint8 s_ac_chroma_val[AC_CHROMA_CODES] =
|
50 |
+
{
|
51 |
+
0x00,0x01,0x02,0x03,0x11,0x04,0x05,0x21,0x31,0x06,0x12,0x41,0x51,0x07,0x61,0x71,0x13,0x22,0x32,0x81,0x08,0x14,0x42,0x91,0xa1,0xb1,0xc1,0x09,0x23,0x33,0x52,0xf0,
|
52 |
+
0x15,0x62,0x72,0xd1,0x0a,0x16,0x24,0x34,0xe1,0x25,0xf1,0x17,0x18,0x19,0x1a,0x26,0x27,0x28,0x29,0x2a,0x35,0x36,0x37,0x38,0x39,0x3a,0x43,0x44,0x45,0x46,0x47,0x48,
|
53 |
+
0x49,0x4a,0x53,0x54,0x55,0x56,0x57,0x58,0x59,0x5a,0x63,0x64,0x65,0x66,0x67,0x68,0x69,0x6a,0x73,0x74,0x75,0x76,0x77,0x78,0x79,0x7a,0x82,0x83,0x84,0x85,0x86,0x87,
|
54 |
+
0x88,0x89,0x8a,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xc2,0xc3,
|
55 |
+
0xc4,0xc5,0xc6,0xc7,0xc8,0xc9,0xca,0xd2,0xd3,0xd4,0xd5,0xd6,0xd7,0xd8,0xd9,0xda,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,
|
56 |
+
0xf9,0xfa
|
57 |
+
};
|
58 |
+
|
59 |
+
// Low-level helper functions.
|
60 |
+
template <class T> inline void clear_obj(T &obj) { memset(&obj, 0, sizeof(obj)); }
|
61 |
+
|
62 |
+
const int YR = 19595, YG = 38470, YB = 7471, CB_R = -11059, CB_G = -21709, CB_B = 32768, CR_R = 32768, CR_G = -27439, CR_B = -5329;
|
63 |
+
static inline uint8 clamp(int i) { if (static_cast<uint>(i) > 255U) { if (i < 0) i = 0; else if (i > 255) i = 255; } return static_cast<uint8>(i); }
|
64 |
+
|
65 |
+
static void RGB_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
66 |
+
{
|
67 |
+
for ( ; num_pixels; pDst += 3, pSrc += 3, num_pixels--)
|
68 |
+
{
|
69 |
+
const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
|
70 |
+
pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
71 |
+
pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
|
72 |
+
pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
|
73 |
+
}
|
74 |
+
}
|
75 |
+
|
76 |
+
static void RGB_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
77 |
+
{
|
78 |
+
for ( ; num_pixels; pDst++, pSrc += 3, num_pixels--)
|
79 |
+
pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
|
80 |
+
}
|
81 |
+
|
82 |
+
static void RGBA_to_YCC(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
83 |
+
{
|
84 |
+
for ( ; num_pixels; pDst += 3, pSrc += 4, num_pixels--)
|
85 |
+
{
|
86 |
+
const int r = pSrc[0], g = pSrc[1], b = pSrc[2];
|
87 |
+
pDst[0] = static_cast<uint8>((r * YR + g * YG + b * YB + 32768) >> 16);
|
88 |
+
pDst[1] = clamp(128 + ((r * CB_R + g * CB_G + b * CB_B + 32768) >> 16));
|
89 |
+
pDst[2] = clamp(128 + ((r * CR_R + g * CR_G + b * CR_B + 32768) >> 16));
|
90 |
+
}
|
91 |
+
}
|
92 |
+
|
93 |
+
static void RGBA_to_Y(uint8* pDst, const uint8 *pSrc, int num_pixels)
|
94 |
+
{
|
95 |
+
for ( ; num_pixels; pDst++, pSrc += 4, num_pixels--)
|
96 |
+
pDst[0] = static_cast<uint8>((pSrc[0] * YR + pSrc[1] * YG + pSrc[2] * YB + 32768) >> 16);
|
97 |
+
}
|
98 |
+
|
99 |
+
static void Y_to_YCC(uint8* pDst, const uint8* pSrc, int num_pixels)
|
100 |
+
{
|
101 |
+
for( ; num_pixels; pDst += 3, pSrc++, num_pixels--) { pDst[0] = pSrc[0]; pDst[1] = 128; pDst[2] = 128; }
|
102 |
+
}
|
103 |
+
|
104 |
+
// Forward DCT - DCT derived from jfdctint.
|
105 |
+
#define CONST_BITS 13
|
106 |
+
#define ROW_BITS 2
|
107 |
+
#define DCT_DESCALE(x, n) (((x) + (((int32)1) << ((n) - 1))) >> (n))
|
108 |
+
#define DCT_MUL(var, c) (static_cast<int16>(var) * static_cast<int32>(c))
|
109 |
+
#define DCT1D(s0, s1, s2, s3, s4, s5, s6, s7) \
|
110 |
+
int32 t0 = s0 + s7, t7 = s0 - s7, t1 = s1 + s6, t6 = s1 - s6, t2 = s2 + s5, t5 = s2 - s5, t3 = s3 + s4, t4 = s3 - s4; \
|
111 |
+
int32 t10 = t0 + t3, t13 = t0 - t3, t11 = t1 + t2, t12 = t1 - t2; \
|
112 |
+
int32 u1 = DCT_MUL(t12 + t13, 4433); \
|
113 |
+
s2 = u1 + DCT_MUL(t13, 6270); \
|
114 |
+
s6 = u1 + DCT_MUL(t12, -15137); \
|
115 |
+
u1 = t4 + t7; \
|
116 |
+
int32 u2 = t5 + t6, u3 = t4 + t6, u4 = t5 + t7; \
|
117 |
+
int32 z5 = DCT_MUL(u3 + u4, 9633); \
|
118 |
+
t4 = DCT_MUL(t4, 2446); t5 = DCT_MUL(t5, 16819); \
|
119 |
+
t6 = DCT_MUL(t6, 25172); t7 = DCT_MUL(t7, 12299); \
|
120 |
+
u1 = DCT_MUL(u1, -7373); u2 = DCT_MUL(u2, -20995); \
|
121 |
+
u3 = DCT_MUL(u3, -16069); u4 = DCT_MUL(u4, -3196); \
|
122 |
+
u3 += z5; u4 += z5; \
|
123 |
+
s0 = t10 + t11; s1 = t7 + u1 + u4; s3 = t6 + u2 + u3; s4 = t10 - t11; s5 = t5 + u2 + u4; s7 = t4 + u1 + u3;
|
124 |
+
|
125 |
+
static void DCT2D(int32 *p)
|
126 |
+
{
|
127 |
+
int32 c, *q = p;
|
128 |
+
for (c = 7; c >= 0; c--, q += 8)
|
129 |
+
{
|
130 |
+
int32 s0 = q[0], s1 = q[1], s2 = q[2], s3 = q[3], s4 = q[4], s5 = q[5], s6 = q[6], s7 = q[7];
|
131 |
+
DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
|
132 |
+
q[0] = s0 << ROW_BITS; q[1] = DCT_DESCALE(s1, CONST_BITS-ROW_BITS); q[2] = DCT_DESCALE(s2, CONST_BITS-ROW_BITS); q[3] = DCT_DESCALE(s3, CONST_BITS-ROW_BITS);
|
133 |
+
q[4] = s4 << ROW_BITS; q[5] = DCT_DESCALE(s5, CONST_BITS-ROW_BITS); q[6] = DCT_DESCALE(s6, CONST_BITS-ROW_BITS); q[7] = DCT_DESCALE(s7, CONST_BITS-ROW_BITS);
|
134 |
+
}
|
135 |
+
for (q = p, c = 7; c >= 0; c--, q++)
|
136 |
+
{
|
137 |
+
int32 s0 = q[0*8], s1 = q[1*8], s2 = q[2*8], s3 = q[3*8], s4 = q[4*8], s5 = q[5*8], s6 = q[6*8], s7 = q[7*8];
|
138 |
+
DCT1D(s0, s1, s2, s3, s4, s5, s6, s7);
|
139 |
+
q[0*8] = DCT_DESCALE(s0, ROW_BITS+3); q[1*8] = DCT_DESCALE(s1, CONST_BITS+ROW_BITS+3); q[2*8] = DCT_DESCALE(s2, CONST_BITS+ROW_BITS+3); q[3*8] = DCT_DESCALE(s3, CONST_BITS+ROW_BITS+3);
|
140 |
+
q[4*8] = DCT_DESCALE(s4, ROW_BITS+3); q[5*8] = DCT_DESCALE(s5, CONST_BITS+ROW_BITS+3); q[6*8] = DCT_DESCALE(s6, CONST_BITS+ROW_BITS+3); q[7*8] = DCT_DESCALE(s7, CONST_BITS+ROW_BITS+3);
|
141 |
+
}
|
142 |
+
}
|
143 |
+
|
144 |
+
struct sym_freq { uint m_key, m_sym_index; };
|
145 |
+
|
146 |
+
// Radix sorts sym_freq[] array by 32-bit key m_key. Returns ptr to sorted values.
|
147 |
+
static inline sym_freq* radix_sort_syms(uint num_syms, sym_freq* pSyms0, sym_freq* pSyms1)
|
148 |
+
{
|
149 |
+
const uint cMaxPasses = 4;
|
150 |
+
uint32 hist[256 * cMaxPasses]; clear_obj(hist);
|
151 |
+
for (uint i = 0; i < num_syms; i++) { uint freq = pSyms0[i].m_key; hist[freq & 0xFF]++; hist[256 + ((freq >> 8) & 0xFF)]++; hist[256*2 + ((freq >> 16) & 0xFF)]++; hist[256*3 + ((freq >> 24) & 0xFF)]++; }
|
152 |
+
sym_freq* pCur_syms = pSyms0, *pNew_syms = pSyms1;
|
153 |
+
uint total_passes = cMaxPasses; while ((total_passes > 1) && (num_syms == hist[(total_passes - 1) * 256])) total_passes--;
|
154 |
+
for (uint pass_shift = 0, pass = 0; pass < total_passes; pass++, pass_shift += 8)
|
155 |
+
{
|
156 |
+
const uint32* pHist = &hist[pass << 8];
|
157 |
+
uint offsets[256], cur_ofs = 0;
|
158 |
+
for (uint i = 0; i < 256; i++) { offsets[i] = cur_ofs; cur_ofs += pHist[i]; }
|
159 |
+
for (uint i = 0; i < num_syms; i++)
|
160 |
+
pNew_syms[offsets[(pCur_syms[i].m_key >> pass_shift) & 0xFF]++] = pCur_syms[i];
|
161 |
+
sym_freq* t = pCur_syms; pCur_syms = pNew_syms; pNew_syms = t;
|
162 |
+
}
|
163 |
+
return pCur_syms;
|
164 |
+
}
|
165 |
+
|
166 |
+
// calculate_minimum_redundancy() originally written by: Alistair Moffat, alistair@cs.mu.oz.au, Jyrki Katajainen, jyrki@diku.dk, November 1996.
|
167 |
+
static void calculate_minimum_redundancy(sym_freq *A, int n)
|
168 |
+
{
|
169 |
+
int root, leaf, next, avbl, used, dpth;
|
170 |
+
if (n==0) return; else if (n==1) { A[0].m_key = 1; return; }
|
171 |
+
A[0].m_key += A[1].m_key; root = 0; leaf = 2;
|
172 |
+
for (next=1; next < n-1; next++)
|
173 |
+
{
|
174 |
+
if (leaf>=n || A[root].m_key<A[leaf].m_key) { A[next].m_key = A[root].m_key; A[root++].m_key = next; } else A[next].m_key = A[leaf++].m_key;
|
175 |
+
if (leaf>=n || (root<next && A[root].m_key<A[leaf].m_key)) { A[next].m_key += A[root].m_key; A[root++].m_key = next; } else A[next].m_key += A[leaf++].m_key;
|
176 |
+
}
|
177 |
+
A[n-2].m_key = 0;
|
178 |
+
for (next=n-3; next>=0; next--) A[next].m_key = A[A[next].m_key].m_key+1;
|
179 |
+
avbl = 1; used = dpth = 0; root = n-2; next = n-1;
|
180 |
+
while (avbl>0)
|
181 |
+
{
|
182 |
+
while (root>=0 && (int)A[root].m_key==dpth) { used++; root--; }
|
183 |
+
while (avbl>used) { A[next--].m_key = dpth; avbl--; }
|
184 |
+
avbl = 2*used; dpth++; used = 0;
|
185 |
+
}
|
186 |
+
}
|
187 |
+
|
188 |
+
// Limits canonical Huffman code table's max code size to max_code_size.
|
189 |
+
static void huffman_enforce_max_code_size(int *pNum_codes, int code_list_len, int max_code_size)
|
190 |
+
{
|
191 |
+
if (code_list_len <= 1) return;
|
192 |
+
|
193 |
+
for (int i = max_code_size + 1; i <= MAX_HUFF_CODESIZE; i++) pNum_codes[max_code_size] += pNum_codes[i];
|
194 |
+
|
195 |
+
uint32 total = 0;
|
196 |
+
for (int i = max_code_size; i > 0; i--)
|
197 |
+
total += (((uint32)pNum_codes[i]) << (max_code_size - i));
|
198 |
+
|
199 |
+
while (total != (1UL << max_code_size))
|
200 |
+
{
|
201 |
+
pNum_codes[max_code_size]--;
|
202 |
+
for (int i = max_code_size - 1; i > 0; i--)
|
203 |
+
{
|
204 |
+
if (pNum_codes[i]) { pNum_codes[i]--; pNum_codes[i + 1] += 2; break; }
|
205 |
+
}
|
206 |
+
total--;
|
207 |
+
}
|
208 |
+
}
|
209 |
+
|
210 |
+
// Generates an optimized offman table.
|
211 |
+
void jpeg_encoder::optimize_huffman_table(int table_num, int table_len)
|
212 |
+
{
|
213 |
+
sym_freq syms0[MAX_HUFF_SYMBOLS], syms1[MAX_HUFF_SYMBOLS];
|
214 |
+
syms0[0].m_key = 1; syms0[0].m_sym_index = 0; // dummy symbol, assures that no valid code contains all 1's
|
215 |
+
int num_used_syms = 1;
|
216 |
+
const uint32 *pSym_count = &m_huff_count[table_num][0];
|
217 |
+
for (int i = 0; i < table_len; i++)
|
218 |
+
if (pSym_count[i]) { syms0[num_used_syms].m_key = pSym_count[i]; syms0[num_used_syms++].m_sym_index = i + 1; }
|
219 |
+
sym_freq* pSyms = radix_sort_syms(num_used_syms, syms0, syms1);
|
220 |
+
calculate_minimum_redundancy(pSyms, num_used_syms);
|
221 |
+
|
222 |
+
// Count the # of symbols of each code size.
|
223 |
+
int num_codes[1 + MAX_HUFF_CODESIZE]; clear_obj(num_codes);
|
224 |
+
for (int i = 0; i < num_used_syms; i++)
|
225 |
+
num_codes[pSyms[i].m_key]++;
|
226 |
+
|
227 |
+
const uint JPGE_CODE_SIZE_LIMIT = 16; // the maximum possible size of a JPEG Huffman code (valid range is [9,16] - 9 vs. 8 because of the dummy symbol)
|
228 |
+
huffman_enforce_max_code_size(num_codes, num_used_syms, JPGE_CODE_SIZE_LIMIT);
|
229 |
+
|
230 |
+
// Compute m_huff_bits array, which contains the # of symbols per code size.
|
231 |
+
clear_obj(m_huff_bits[table_num]);
|
232 |
+
for (int i = 1; i <= (int)JPGE_CODE_SIZE_LIMIT; i++)
|
233 |
+
m_huff_bits[table_num][i] = static_cast<uint8>(num_codes[i]);
|
234 |
+
|
235 |
+
// Remove the dummy symbol added above, which must be in largest bucket.
|
236 |
+
for (int i = JPGE_CODE_SIZE_LIMIT; i >= 1; i--)
|
237 |
+
{
|
238 |
+
if (m_huff_bits[table_num][i]) { m_huff_bits[table_num][i]--; break; }
|
239 |
+
}
|
240 |
+
|
241 |
+
// Compute the m_huff_val array, which contains the symbol indices sorted by code size (smallest to largest).
|
242 |
+
for (int i = num_used_syms - 1; i >= 1; i--)
|
243 |
+
m_huff_val[table_num][num_used_syms - 1 - i] = static_cast<uint8>(pSyms[i].m_sym_index - 1);
|
244 |
+
}
|
245 |
+
|
246 |
+
// JPEG marker generation.
|
247 |
+
void jpeg_encoder::emit_byte(uint8 i)
|
248 |
+
{
|
249 |
+
m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_obj(i);
|
250 |
+
}
|
251 |
+
|
252 |
+
void jpeg_encoder::emit_word(uint i)
|
253 |
+
{
|
254 |
+
emit_byte(uint8(i >> 8)); emit_byte(uint8(i & 0xFF));
|
255 |
+
}
|
256 |
+
|
257 |
+
void jpeg_encoder::emit_marker(int marker)
|
258 |
+
{
|
259 |
+
emit_byte(uint8(0xFF)); emit_byte(uint8(marker));
|
260 |
+
}
|
261 |
+
|
262 |
+
// Emit JFIF marker
|
263 |
+
void jpeg_encoder::emit_jfif_app0()
|
264 |
+
{
|
265 |
+
emit_marker(M_APP0);
|
266 |
+
emit_word(2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1);
|
267 |
+
emit_byte(0x4A); emit_byte(0x46); emit_byte(0x49); emit_byte(0x46); /* Identifier: ASCII "JFIF" */
|
268 |
+
emit_byte(0);
|
269 |
+
emit_byte(1); /* Major version */
|
270 |
+
emit_byte(1); /* Minor version */
|
271 |
+
emit_byte(0); /* Density unit */
|
272 |
+
emit_word(1);
|
273 |
+
emit_word(1);
|
274 |
+
emit_byte(0); /* No thumbnail image */
|
275 |
+
emit_byte(0);
|
276 |
+
}
|
277 |
+
|
278 |
+
// Emit quantization tables
|
279 |
+
void jpeg_encoder::emit_dqt()
|
280 |
+
{
|
281 |
+
for (int i = 0; i < ((m_num_components == 3) ? 2 : 1); i++)
|
282 |
+
{
|
283 |
+
emit_marker(M_DQT);
|
284 |
+
emit_word(64 + 1 + 2);
|
285 |
+
emit_byte(static_cast<uint8>(i));
|
286 |
+
for (int j = 0; j < 64; j++)
|
287 |
+
emit_byte(static_cast<uint8>(m_quantization_tables[i][j]));
|
288 |
+
}
|
289 |
+
}
|
290 |
+
|
291 |
+
// Emit start of frame marker
|
292 |
+
void jpeg_encoder::emit_sof()
|
293 |
+
{
|
294 |
+
emit_marker(M_SOF0); /* baseline */
|
295 |
+
emit_word(3 * m_num_components + 2 + 5 + 1);
|
296 |
+
emit_byte(8); /* precision */
|
297 |
+
emit_word(m_image_y);
|
298 |
+
emit_word(m_image_x);
|
299 |
+
emit_byte(m_num_components);
|
300 |
+
for (int i = 0; i < m_num_components; i++)
|
301 |
+
{
|
302 |
+
emit_byte(static_cast<uint8>(i + 1)); /* component ID */
|
303 |
+
emit_byte((m_comp_h_samp[i] << 4) + m_comp_v_samp[i]); /* h and v sampling */
|
304 |
+
emit_byte(i > 0); /* quant. table num */
|
305 |
+
}
|
306 |
+
}
|
307 |
+
|
308 |
+
// Emit Huffman table.
|
309 |
+
void jpeg_encoder::emit_dht(uint8 *bits, uint8 *val, int index, bool ac_flag)
|
310 |
+
{
|
311 |
+
emit_marker(M_DHT);
|
312 |
+
|
313 |
+
int length = 0;
|
314 |
+
for (int i = 1; i <= 16; i++)
|
315 |
+
length += bits[i];
|
316 |
+
|
317 |
+
emit_word(length + 2 + 1 + 16);
|
318 |
+
emit_byte(static_cast<uint8>(index + (ac_flag << 4)));
|
319 |
+
|
320 |
+
for (int i = 1; i <= 16; i++)
|
321 |
+
emit_byte(bits[i]);
|
322 |
+
|
323 |
+
for (int i = 0; i < length; i++)
|
324 |
+
emit_byte(val[i]);
|
325 |
+
}
|
326 |
+
|
327 |
+
// Emit all Huffman tables.
|
328 |
+
void jpeg_encoder::emit_dhts()
|
329 |
+
{
|
330 |
+
emit_dht(m_huff_bits[0+0], m_huff_val[0+0], 0, false);
|
331 |
+
emit_dht(m_huff_bits[2+0], m_huff_val[2+0], 0, true);
|
332 |
+
if (m_num_components == 3)
|
333 |
+
{
|
334 |
+
emit_dht(m_huff_bits[0+1], m_huff_val[0+1], 1, false);
|
335 |
+
emit_dht(m_huff_bits[2+1], m_huff_val[2+1], 1, true);
|
336 |
+
}
|
337 |
+
}
|
338 |
+
|
339 |
+
// emit start of scan
|
340 |
+
void jpeg_encoder::emit_sos()
|
341 |
+
{
|
342 |
+
emit_marker(M_SOS);
|
343 |
+
emit_word(2 * m_num_components + 2 + 1 + 3);
|
344 |
+
emit_byte(m_num_components);
|
345 |
+
for (int i = 0; i < m_num_components; i++)
|
346 |
+
{
|
347 |
+
emit_byte(static_cast<uint8>(i + 1));
|
348 |
+
if (i == 0)
|
349 |
+
emit_byte((0 << 4) + 0);
|
350 |
+
else
|
351 |
+
emit_byte((1 << 4) + 1);
|
352 |
+
}
|
353 |
+
emit_byte(0); /* spectral selection */
|
354 |
+
emit_byte(63);
|
355 |
+
emit_byte(0);
|
356 |
+
}
|
357 |
+
|
358 |
+
// Emit all markers at beginning of image file.
|
359 |
+
void jpeg_encoder::emit_markers()
|
360 |
+
{
|
361 |
+
emit_marker(M_SOI);
|
362 |
+
emit_jfif_app0();
|
363 |
+
emit_dqt();
|
364 |
+
emit_sof();
|
365 |
+
emit_dhts();
|
366 |
+
emit_sos();
|
367 |
+
}
|
368 |
+
|
369 |
+
// Compute the actual canonical Huffman codes/code sizes given the JPEG huff bits and val arrays.
|
370 |
+
void jpeg_encoder::compute_huffman_table(uint *codes, uint8 *code_sizes, uint8 *bits, uint8 *val)
|
371 |
+
{
|
372 |
+
int i, l, last_p, si;
|
373 |
+
uint8 huff_size[257];
|
374 |
+
uint huff_code[257];
|
375 |
+
uint code;
|
376 |
+
|
377 |
+
int p = 0;
|
378 |
+
for (l = 1; l <= 16; l++)
|
379 |
+
for (i = 1; i <= bits[l]; i++)
|
380 |
+
huff_size[p++] = (char)l;
|
381 |
+
|
382 |
+
huff_size[p] = 0; last_p = p; // write sentinel
|
383 |
+
|
384 |
+
code = 0; si = huff_size[0]; p = 0;
|
385 |
+
|
386 |
+
while (huff_size[p])
|
387 |
+
{
|
388 |
+
while (huff_size[p] == si)
|
389 |
+
huff_code[p++] = code++;
|
390 |
+
code <<= 1;
|
391 |
+
si++;
|
392 |
+
}
|
393 |
+
|
394 |
+
memset(codes, 0, sizeof(codes[0])*256);
|
395 |
+
memset(code_sizes, 0, sizeof(code_sizes[0])*256);
|
396 |
+
for (p = 0; p < last_p; p++)
|
397 |
+
{
|
398 |
+
codes[val[p]] = huff_code[p];
|
399 |
+
code_sizes[val[p]] = huff_size[p];
|
400 |
+
}
|
401 |
+
}
|
402 |
+
|
403 |
+
// Quantization table generation.
|
404 |
+
void jpeg_encoder::compute_quant_table(int32 *pDst, int16 *pSrc)
|
405 |
+
{
|
406 |
+
int32 q;
|
407 |
+
if (m_params.m_quality < 50)
|
408 |
+
q = 5000 / m_params.m_quality;
|
409 |
+
else
|
410 |
+
q = 200 - m_params.m_quality * 2;
|
411 |
+
for (int i = 0; i < 64; i++)
|
412 |
+
{
|
413 |
+
int32 j = *pSrc++; j = (j * q + 50L) / 100L;
|
414 |
+
*pDst++ = JPGE_MIN(JPGE_MAX(j, 1), 255);
|
415 |
+
}
|
416 |
+
}
|
417 |
+
|
418 |
+
// Higher-level methods.
|
419 |
+
void jpeg_encoder::first_pass_init()
|
420 |
+
{
|
421 |
+
m_bit_buffer = 0; m_bits_in = 0;
|
422 |
+
memset(m_last_dc_val, 0, 3 * sizeof(m_last_dc_val[0]));
|
423 |
+
m_mcu_y_ofs = 0;
|
424 |
+
m_pass_num = 1;
|
425 |
+
}
|
426 |
+
|
427 |
+
bool jpeg_encoder::second_pass_init()
|
428 |
+
{
|
429 |
+
compute_huffman_table(&m_huff_codes[0+0][0], &m_huff_code_sizes[0+0][0], m_huff_bits[0+0], m_huff_val[0+0]);
|
430 |
+
compute_huffman_table(&m_huff_codes[2+0][0], &m_huff_code_sizes[2+0][0], m_huff_bits[2+0], m_huff_val[2+0]);
|
431 |
+
if (m_num_components > 1)
|
432 |
+
{
|
433 |
+
compute_huffman_table(&m_huff_codes[0+1][0], &m_huff_code_sizes[0+1][0], m_huff_bits[0+1], m_huff_val[0+1]);
|
434 |
+
compute_huffman_table(&m_huff_codes[2+1][0], &m_huff_code_sizes[2+1][0], m_huff_bits[2+1], m_huff_val[2+1]);
|
435 |
+
}
|
436 |
+
first_pass_init();
|
437 |
+
emit_markers();
|
438 |
+
m_pass_num = 2;
|
439 |
+
return true;
|
440 |
+
}
|
441 |
+
|
442 |
+
bool jpeg_encoder::jpg_open(int p_x_res, int p_y_res, int src_channels)
|
443 |
+
{
|
444 |
+
m_num_components = 3;
|
445 |
+
switch (m_params.m_subsampling)
|
446 |
+
{
|
447 |
+
case Y_ONLY:
|
448 |
+
{
|
449 |
+
m_num_components = 1;
|
450 |
+
m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
|
451 |
+
m_mcu_x = 8; m_mcu_y = 8;
|
452 |
+
break;
|
453 |
+
}
|
454 |
+
case H1V1:
|
455 |
+
{
|
456 |
+
m_comp_h_samp[0] = 1; m_comp_v_samp[0] = 1;
|
457 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
458 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
459 |
+
m_mcu_x = 8; m_mcu_y = 8;
|
460 |
+
break;
|
461 |
+
}
|
462 |
+
case H2V1:
|
463 |
+
{
|
464 |
+
m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 1;
|
465 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
466 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
467 |
+
m_mcu_x = 16; m_mcu_y = 8;
|
468 |
+
break;
|
469 |
+
}
|
470 |
+
case H2V2:
|
471 |
+
{
|
472 |
+
m_comp_h_samp[0] = 2; m_comp_v_samp[0] = 2;
|
473 |
+
m_comp_h_samp[1] = 1; m_comp_v_samp[1] = 1;
|
474 |
+
m_comp_h_samp[2] = 1; m_comp_v_samp[2] = 1;
|
475 |
+
m_mcu_x = 16; m_mcu_y = 16;
|
476 |
+
}
|
477 |
+
}
|
478 |
+
|
479 |
+
m_image_x = p_x_res; m_image_y = p_y_res;
|
480 |
+
m_image_bpp = src_channels;
|
481 |
+
m_image_bpl = m_image_x * src_channels;
|
482 |
+
m_image_x_mcu = (m_image_x + m_mcu_x - 1) & (~(m_mcu_x - 1));
|
483 |
+
m_image_y_mcu = (m_image_y + m_mcu_y - 1) & (~(m_mcu_y - 1));
|
484 |
+
m_image_bpl_xlt = m_image_x * m_num_components;
|
485 |
+
m_image_bpl_mcu = m_image_x_mcu * m_num_components;
|
486 |
+
m_mcus_per_row = m_image_x_mcu / m_mcu_x;
|
487 |
+
|
488 |
+
if ((m_mcu_lines[0] = static_cast<uint8*>(jpge_malloc(m_image_bpl_mcu * m_mcu_y))) == NULL) return false;
|
489 |
+
for (int i = 1; i < m_mcu_y; i++)
|
490 |
+
m_mcu_lines[i] = m_mcu_lines[i-1] + m_image_bpl_mcu;
|
491 |
+
|
492 |
+
compute_quant_table(m_quantization_tables[0], s_std_lum_quant);
|
493 |
+
compute_quant_table(m_quantization_tables[1], m_params.m_no_chroma_discrim_flag ? s_std_lum_quant : s_std_croma_quant);
|
494 |
+
|
495 |
+
m_out_buf_left = JPGE_OUT_BUF_SIZE;
|
496 |
+
m_pOut_buf = m_out_buf;
|
497 |
+
|
498 |
+
if (m_params.m_two_pass_flag)
|
499 |
+
{
|
500 |
+
clear_obj(m_huff_count);
|
501 |
+
first_pass_init();
|
502 |
+
}
|
503 |
+
else
|
504 |
+
{
|
505 |
+
memcpy(m_huff_bits[0+0], s_dc_lum_bits, 17); memcpy(m_huff_val [0+0], s_dc_lum_val, DC_LUM_CODES);
|
506 |
+
memcpy(m_huff_bits[2+0], s_ac_lum_bits, 17); memcpy(m_huff_val [2+0], s_ac_lum_val, AC_LUM_CODES);
|
507 |
+
memcpy(m_huff_bits[0+1], s_dc_chroma_bits, 17); memcpy(m_huff_val [0+1], s_dc_chroma_val, DC_CHROMA_CODES);
|
508 |
+
memcpy(m_huff_bits[2+1], s_ac_chroma_bits, 17); memcpy(m_huff_val [2+1], s_ac_chroma_val, AC_CHROMA_CODES);
|
509 |
+
if (!second_pass_init()) return false; // in effect, skip over the first pass
|
510 |
+
}
|
511 |
+
return m_all_stream_writes_succeeded;
|
512 |
+
}
|
513 |
+
|
514 |
+
void jpeg_encoder::load_block_8_8_grey(int x)
|
515 |
+
{
|
516 |
+
uint8 *pSrc;
|
517 |
+
sample_array_t *pDst = m_sample_array;
|
518 |
+
x <<= 3;
|
519 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
520 |
+
{
|
521 |
+
pSrc = m_mcu_lines[i] + x;
|
522 |
+
pDst[0] = pSrc[0] - 128; pDst[1] = pSrc[1] - 128; pDst[2] = pSrc[2] - 128; pDst[3] = pSrc[3] - 128;
|
523 |
+
pDst[4] = pSrc[4] - 128; pDst[5] = pSrc[5] - 128; pDst[6] = pSrc[6] - 128; pDst[7] = pSrc[7] - 128;
|
524 |
+
}
|
525 |
+
}
|
526 |
+
|
527 |
+
void jpeg_encoder::load_block_8_8(int x, int y, int c)
|
528 |
+
{
|
529 |
+
uint8 *pSrc;
|
530 |
+
sample_array_t *pDst = m_sample_array;
|
531 |
+
x = (x * (8 * 3)) + c;
|
532 |
+
y <<= 3;
|
533 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
534 |
+
{
|
535 |
+
pSrc = m_mcu_lines[y + i] + x;
|
536 |
+
pDst[0] = pSrc[0 * 3] - 128; pDst[1] = pSrc[1 * 3] - 128; pDst[2] = pSrc[2 * 3] - 128; pDst[3] = pSrc[3 * 3] - 128;
|
537 |
+
pDst[4] = pSrc[4 * 3] - 128; pDst[5] = pSrc[5 * 3] - 128; pDst[6] = pSrc[6 * 3] - 128; pDst[7] = pSrc[7 * 3] - 128;
|
538 |
+
}
|
539 |
+
}
|
540 |
+
|
541 |
+
void jpeg_encoder::load_block_16_8(int x, int c)
|
542 |
+
{
|
543 |
+
uint8 *pSrc1, *pSrc2;
|
544 |
+
sample_array_t *pDst = m_sample_array;
|
545 |
+
x = (x * (16 * 3)) + c;
|
546 |
+
int a = 0, b = 2;
|
547 |
+
for (int i = 0; i < 16; i += 2, pDst += 8)
|
548 |
+
{
|
549 |
+
pSrc1 = m_mcu_lines[i + 0] + x;
|
550 |
+
pSrc2 = m_mcu_lines[i + 1] + x;
|
551 |
+
pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3] + pSrc2[ 0 * 3] + pSrc2[ 1 * 3] + a) >> 2) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3] + pSrc2[ 2 * 3] + pSrc2[ 3 * 3] + b) >> 2) - 128;
|
552 |
+
pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3] + pSrc2[ 4 * 3] + pSrc2[ 5 * 3] + a) >> 2) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3] + pSrc2[ 6 * 3] + pSrc2[ 7 * 3] + b) >> 2) - 128;
|
553 |
+
pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3] + pSrc2[ 8 * 3] + pSrc2[ 9 * 3] + a) >> 2) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3] + pSrc2[10 * 3] + pSrc2[11 * 3] + b) >> 2) - 128;
|
554 |
+
pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3] + pSrc2[12 * 3] + pSrc2[13 * 3] + a) >> 2) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3] + pSrc2[14 * 3] + pSrc2[15 * 3] + b) >> 2) - 128;
|
555 |
+
int temp = a; a = b; b = temp;
|
556 |
+
}
|
557 |
+
}
|
558 |
+
|
559 |
+
void jpeg_encoder::load_block_16_8_8(int x, int c)
|
560 |
+
{
|
561 |
+
uint8 *pSrc1;
|
562 |
+
sample_array_t *pDst = m_sample_array;
|
563 |
+
x = (x * (16 * 3)) + c;
|
564 |
+
for (int i = 0; i < 8; i++, pDst += 8)
|
565 |
+
{
|
566 |
+
pSrc1 = m_mcu_lines[i + 0] + x;
|
567 |
+
pDst[0] = ((pSrc1[ 0 * 3] + pSrc1[ 1 * 3]) >> 1) - 128; pDst[1] = ((pSrc1[ 2 * 3] + pSrc1[ 3 * 3]) >> 1) - 128;
|
568 |
+
pDst[2] = ((pSrc1[ 4 * 3] + pSrc1[ 5 * 3]) >> 1) - 128; pDst[3] = ((pSrc1[ 6 * 3] + pSrc1[ 7 * 3]) >> 1) - 128;
|
569 |
+
pDst[4] = ((pSrc1[ 8 * 3] + pSrc1[ 9 * 3]) >> 1) - 128; pDst[5] = ((pSrc1[10 * 3] + pSrc1[11 * 3]) >> 1) - 128;
|
570 |
+
pDst[6] = ((pSrc1[12 * 3] + pSrc1[13 * 3]) >> 1) - 128; pDst[7] = ((pSrc1[14 * 3] + pSrc1[15 * 3]) >> 1) - 128;
|
571 |
+
}
|
572 |
+
}
|
573 |
+
|
574 |
+
void jpeg_encoder::load_quantized_coefficients(int component_num)
|
575 |
+
{
|
576 |
+
int32 *q = m_quantization_tables[component_num > 0];
|
577 |
+
int16 *pDst = m_coefficient_array;
|
578 |
+
for (int i = 0; i < 64; i++)
|
579 |
+
{
|
580 |
+
sample_array_t j = m_sample_array[s_zag[i]];
|
581 |
+
if (j < 0)
|
582 |
+
{
|
583 |
+
if ((j = -j + (*q >> 1)) < *q)
|
584 |
+
*pDst++ = 0;
|
585 |
+
else
|
586 |
+
*pDst++ = static_cast<int16>(-(j / *q));
|
587 |
+
}
|
588 |
+
else
|
589 |
+
{
|
590 |
+
if ((j = j + (*q >> 1)) < *q)
|
591 |
+
*pDst++ = 0;
|
592 |
+
else
|
593 |
+
*pDst++ = static_cast<int16>((j / *q));
|
594 |
+
}
|
595 |
+
q++;
|
596 |
+
}
|
597 |
+
}
|
598 |
+
|
599 |
+
void jpeg_encoder::flush_output_buffer()
|
600 |
+
{
|
601 |
+
if (m_out_buf_left != JPGE_OUT_BUF_SIZE)
|
602 |
+
m_all_stream_writes_succeeded = m_all_stream_writes_succeeded && m_pStream->put_buf(m_out_buf, JPGE_OUT_BUF_SIZE - m_out_buf_left);
|
603 |
+
m_pOut_buf = m_out_buf;
|
604 |
+
m_out_buf_left = JPGE_OUT_BUF_SIZE;
|
605 |
+
}
|
606 |
+
|
607 |
+
void jpeg_encoder::put_bits(uint bits, uint len)
|
608 |
+
{
|
609 |
+
m_bit_buffer |= ((uint32)bits << (24 - (m_bits_in += len)));
|
610 |
+
while (m_bits_in >= 8)
|
611 |
+
{
|
612 |
+
uint8 c;
|
613 |
+
#define JPGE_PUT_BYTE(c) { *m_pOut_buf++ = (c); if (--m_out_buf_left == 0) flush_output_buffer(); }
|
614 |
+
JPGE_PUT_BYTE(c = (uint8)((m_bit_buffer >> 16) & 0xFF));
|
615 |
+
if (c == 0xFF) JPGE_PUT_BYTE(0);
|
616 |
+
m_bit_buffer <<= 8;
|
617 |
+
m_bits_in -= 8;
|
618 |
+
}
|
619 |
+
}
|
620 |
+
|
621 |
+
void jpeg_encoder::code_coefficients_pass_one(int component_num)
|
622 |
+
{
|
623 |
+
if (component_num >= 3) return; // just to shut up static analysis
|
624 |
+
int i, run_len, nbits, temp1;
|
625 |
+
int16 *src = m_coefficient_array;
|
626 |
+
uint32 *dc_count = component_num ? m_huff_count[0 + 1] : m_huff_count[0 + 0], *ac_count = component_num ? m_huff_count[2 + 1] : m_huff_count[2 + 0];
|
627 |
+
|
628 |
+
temp1 = src[0] - m_last_dc_val[component_num];
|
629 |
+
m_last_dc_val[component_num] = src[0];
|
630 |
+
if (temp1 < 0) temp1 = -temp1;
|
631 |
+
|
632 |
+
nbits = 0;
|
633 |
+
while (temp1)
|
634 |
+
{
|
635 |
+
nbits++; temp1 >>= 1;
|
636 |
+
}
|
637 |
+
|
638 |
+
dc_count[nbits]++;
|
639 |
+
for (run_len = 0, i = 1; i < 64; i++)
|
640 |
+
{
|
641 |
+
if ((temp1 = m_coefficient_array[i]) == 0)
|
642 |
+
run_len++;
|
643 |
+
else
|
644 |
+
{
|
645 |
+
while (run_len >= 16)
|
646 |
+
{
|
647 |
+
ac_count[0xF0]++;
|
648 |
+
run_len -= 16;
|
649 |
+
}
|
650 |
+
if (temp1 < 0) temp1 = -temp1;
|
651 |
+
nbits = 1;
|
652 |
+
while (temp1 >>= 1) nbits++;
|
653 |
+
ac_count[(run_len << 4) + nbits]++;
|
654 |
+
run_len = 0;
|
655 |
+
}
|
656 |
+
}
|
657 |
+
if (run_len) ac_count[0]++;
|
658 |
+
}
|
659 |
+
|
660 |
+
void jpeg_encoder::code_coefficients_pass_two(int component_num)
|
661 |
+
{
|
662 |
+
int i, j, run_len, nbits, temp1, temp2;
|
663 |
+
int16 *pSrc = m_coefficient_array;
|
664 |
+
uint *codes[2];
|
665 |
+
uint8 *code_sizes[2];
|
666 |
+
|
667 |
+
if (component_num == 0)
|
668 |
+
{
|
669 |
+
codes[0] = m_huff_codes[0 + 0]; codes[1] = m_huff_codes[2 + 0];
|
670 |
+
code_sizes[0] = m_huff_code_sizes[0 + 0]; code_sizes[1] = m_huff_code_sizes[2 + 0];
|
671 |
+
}
|
672 |
+
else
|
673 |
+
{
|
674 |
+
codes[0] = m_huff_codes[0 + 1]; codes[1] = m_huff_codes[2 + 1];
|
675 |
+
code_sizes[0] = m_huff_code_sizes[0 + 1]; code_sizes[1] = m_huff_code_sizes[2 + 1];
|
676 |
+
}
|
677 |
+
|
678 |
+
temp1 = temp2 = pSrc[0] - m_last_dc_val[component_num];
|
679 |
+
m_last_dc_val[component_num] = pSrc[0];
|
680 |
+
|
681 |
+
if (temp1 < 0)
|
682 |
+
{
|
683 |
+
temp1 = -temp1; temp2--;
|
684 |
+
}
|
685 |
+
|
686 |
+
nbits = 0;
|
687 |
+
while (temp1)
|
688 |
+
{
|
689 |
+
nbits++; temp1 >>= 1;
|
690 |
+
}
|
691 |
+
|
692 |
+
put_bits(codes[0][nbits], code_sizes[0][nbits]);
|
693 |
+
if (nbits) put_bits(temp2 & ((1 << nbits) - 1), nbits);
|
694 |
+
|
695 |
+
for (run_len = 0, i = 1; i < 64; i++)
|
696 |
+
{
|
697 |
+
if ((temp1 = m_coefficient_array[i]) == 0)
|
698 |
+
run_len++;
|
699 |
+
else
|
700 |
+
{
|
701 |
+
while (run_len >= 16)
|
702 |
+
{
|
703 |
+
put_bits(codes[1][0xF0], code_sizes[1][0xF0]);
|
704 |
+
run_len -= 16;
|
705 |
+
}
|
706 |
+
if ((temp2 = temp1) < 0)
|
707 |
+
{
|
708 |
+
temp1 = -temp1;
|
709 |
+
temp2--;
|
710 |
+
}
|
711 |
+
nbits = 1;
|
712 |
+
while (temp1 >>= 1)
|
713 |
+
nbits++;
|
714 |
+
j = (run_len << 4) + nbits;
|
715 |
+
put_bits(codes[1][j], code_sizes[1][j]);
|
716 |
+
put_bits(temp2 & ((1 << nbits) - 1), nbits);
|
717 |
+
run_len = 0;
|
718 |
+
}
|
719 |
+
}
|
720 |
+
if (run_len)
|
721 |
+
put_bits(codes[1][0], code_sizes[1][0]);
|
722 |
+
}
|
723 |
+
|
724 |
+
void jpeg_encoder::code_block(int component_num)
|
725 |
+
{
|
726 |
+
DCT2D(m_sample_array);
|
727 |
+
load_quantized_coefficients(component_num);
|
728 |
+
if (m_pass_num == 1)
|
729 |
+
code_coefficients_pass_one(component_num);
|
730 |
+
else
|
731 |
+
code_coefficients_pass_two(component_num);
|
732 |
+
}
|
733 |
+
|
734 |
+
void jpeg_encoder::process_mcu_row()
|
735 |
+
{
|
736 |
+
if (m_num_components == 1)
|
737 |
+
{
|
738 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
739 |
+
{
|
740 |
+
load_block_8_8_grey(i); code_block(0);
|
741 |
+
}
|
742 |
+
}
|
743 |
+
else if ((m_comp_h_samp[0] == 1) && (m_comp_v_samp[0] == 1))
|
744 |
+
{
|
745 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
746 |
+
{
|
747 |
+
load_block_8_8(i, 0, 0); code_block(0); load_block_8_8(i, 0, 1); code_block(1); load_block_8_8(i, 0, 2); code_block(2);
|
748 |
+
}
|
749 |
+
}
|
750 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 1))
|
751 |
+
{
|
752 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
753 |
+
{
|
754 |
+
load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
|
755 |
+
load_block_16_8_8(i, 1); code_block(1); load_block_16_8_8(i, 2); code_block(2);
|
756 |
+
}
|
757 |
+
}
|
758 |
+
else if ((m_comp_h_samp[0] == 2) && (m_comp_v_samp[0] == 2))
|
759 |
+
{
|
760 |
+
for (int i = 0; i < m_mcus_per_row; i++)
|
761 |
+
{
|
762 |
+
load_block_8_8(i * 2 + 0, 0, 0); code_block(0); load_block_8_8(i * 2 + 1, 0, 0); code_block(0);
|
763 |
+
load_block_8_8(i * 2 + 0, 1, 0); code_block(0); load_block_8_8(i * 2 + 1, 1, 0); code_block(0);
|
764 |
+
load_block_16_8(i, 1); code_block(1); load_block_16_8(i, 2); code_block(2);
|
765 |
+
}
|
766 |
+
}
|
767 |
+
}
|
768 |
+
|
769 |
+
bool jpeg_encoder::terminate_pass_one()
|
770 |
+
{
|
771 |
+
optimize_huffman_table(0+0, DC_LUM_CODES); optimize_huffman_table(2+0, AC_LUM_CODES);
|
772 |
+
if (m_num_components > 1)
|
773 |
+
{
|
774 |
+
optimize_huffman_table(0+1, DC_CHROMA_CODES); optimize_huffman_table(2+1, AC_CHROMA_CODES);
|
775 |
+
}
|
776 |
+
return second_pass_init();
|
777 |
+
}
|
778 |
+
|
779 |
+
bool jpeg_encoder::terminate_pass_two()
|
780 |
+
{
|
781 |
+
put_bits(0x7F, 7);
|
782 |
+
flush_output_buffer();
|
783 |
+
emit_marker(M_EOI);
|
784 |
+
m_pass_num++; // purposely bump up m_pass_num, for debugging
|
785 |
+
return true;
|
786 |
+
}
|
787 |
+
|
788 |
+
bool jpeg_encoder::process_end_of_image()
|
789 |
+
{
|
790 |
+
if (m_mcu_y_ofs)
|
791 |
+
{
|
792 |
+
if (m_mcu_y_ofs < 16) // check here just to shut up static analysis
|
793 |
+
{
|
794 |
+
for (int i = m_mcu_y_ofs; i < m_mcu_y; i++)
|
795 |
+
memcpy(m_mcu_lines[i], m_mcu_lines[m_mcu_y_ofs - 1], m_image_bpl_mcu);
|
796 |
+
}
|
797 |
+
|
798 |
+
process_mcu_row();
|
799 |
+
}
|
800 |
+
|
801 |
+
if (m_pass_num == 1)
|
802 |
+
return terminate_pass_one();
|
803 |
+
else
|
804 |
+
return terminate_pass_two();
|
805 |
+
}
|
806 |
+
|
807 |
+
void jpeg_encoder::load_mcu(const void *pSrc)
|
808 |
+
{
|
809 |
+
const uint8* Psrc = reinterpret_cast<const uint8*>(pSrc);
|
810 |
+
|
811 |
+
uint8* pDst = m_mcu_lines[m_mcu_y_ofs]; // OK to write up to m_image_bpl_xlt bytes to pDst
|
812 |
+
|
813 |
+
if (m_num_components == 1)
|
814 |
+
{
|
815 |
+
if (m_image_bpp == 4)
|
816 |
+
RGBA_to_Y(pDst, Psrc, m_image_x);
|
817 |
+
else if (m_image_bpp == 3)
|
818 |
+
RGB_to_Y(pDst, Psrc, m_image_x);
|
819 |
+
else
|
820 |
+
memcpy(pDst, Psrc, m_image_x);
|
821 |
+
}
|
822 |
+
else
|
823 |
+
{
|
824 |
+
if (m_image_bpp == 4)
|
825 |
+
RGBA_to_YCC(pDst, Psrc, m_image_x);
|
826 |
+
else if (m_image_bpp == 3)
|
827 |
+
RGB_to_YCC(pDst, Psrc, m_image_x);
|
828 |
+
else
|
829 |
+
Y_to_YCC(pDst, Psrc, m_image_x);
|
830 |
+
}
|
831 |
+
|
832 |
+
// Possibly duplicate pixels at end of scanline if not a multiple of 8 or 16
|
833 |
+
if (m_num_components == 1)
|
834 |
+
memset(m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt, pDst[m_image_bpl_xlt - 1], m_image_x_mcu - m_image_x);
|
835 |
+
else
|
836 |
+
{
|
837 |
+
const uint8 y = pDst[m_image_bpl_xlt - 3 + 0], cb = pDst[m_image_bpl_xlt - 3 + 1], cr = pDst[m_image_bpl_xlt - 3 + 2];
|
838 |
+
uint8 *q = m_mcu_lines[m_mcu_y_ofs] + m_image_bpl_xlt;
|
839 |
+
for (int i = m_image_x; i < m_image_x_mcu; i++)
|
840 |
+
{
|
841 |
+
*q++ = y; *q++ = cb; *q++ = cr;
|
842 |
+
}
|
843 |
+
}
|
844 |
+
|
845 |
+
if (++m_mcu_y_ofs == m_mcu_y)
|
846 |
+
{
|
847 |
+
process_mcu_row();
|
848 |
+
m_mcu_y_ofs = 0;
|
849 |
+
}
|
850 |
+
}
|
851 |
+
|
852 |
+
void jpeg_encoder::clear()
|
853 |
+
{
|
854 |
+
m_mcu_lines[0] = NULL;
|
855 |
+
m_pass_num = 0;
|
856 |
+
m_all_stream_writes_succeeded = true;
|
857 |
+
}
|
858 |
+
|
859 |
+
jpeg_encoder::jpeg_encoder()
|
860 |
+
{
|
861 |
+
clear();
|
862 |
+
}
|
863 |
+
|
864 |
+
jpeg_encoder::~jpeg_encoder()
|
865 |
+
{
|
866 |
+
deinit();
|
867 |
+
}
|
868 |
+
|
869 |
+
bool jpeg_encoder::init(output_stream *pStream, int64_t width, int64_t height, int64_t src_channels, const params &comp_params)
|
870 |
+
{
|
871 |
+
deinit();
|
872 |
+
if (((!pStream) || (width < 1) || (height < 1)) || ((src_channels != 1) && (src_channels != 3) && (src_channels != 4)) || (!comp_params.check_valid())) return false;
|
873 |
+
m_pStream = pStream;
|
874 |
+
m_params = comp_params;
|
875 |
+
return jpg_open(width, height, src_channels);
|
876 |
+
}
|
877 |
+
|
878 |
+
void jpeg_encoder::deinit()
|
879 |
+
{
|
880 |
+
jpge_free(m_mcu_lines[0]);
|
881 |
+
clear();
|
882 |
+
}
|
883 |
+
|
884 |
+
bool jpeg_encoder::process_scanline(const void* pScanline)
|
885 |
+
{
|
886 |
+
if ((m_pass_num < 1) || (m_pass_num > 2)) return false;
|
887 |
+
if (m_all_stream_writes_succeeded)
|
888 |
+
{
|
889 |
+
if (!pScanline)
|
890 |
+
{
|
891 |
+
if (!process_end_of_image()) return false;
|
892 |
+
}
|
893 |
+
else
|
894 |
+
{
|
895 |
+
load_mcu(pScanline);
|
896 |
+
}
|
897 |
+
}
|
898 |
+
return m_all_stream_writes_succeeded;
|
899 |
+
}
|
900 |
+
|
901 |
+
// Higher level wrappers/examples (optional).
|
902 |
+
#include <stdio.h>
|
903 |
+
|
904 |
+
class cfile_stream : public output_stream
|
905 |
+
{
|
906 |
+
cfile_stream(const cfile_stream &);
|
907 |
+
cfile_stream &operator= (const cfile_stream &);
|
908 |
+
|
909 |
+
FILE* m_pFile;
|
910 |
+
bool m_bStatus;
|
911 |
+
|
912 |
+
public:
|
913 |
+
cfile_stream() : m_pFile(NULL), m_bStatus(false) { }
|
914 |
+
|
915 |
+
virtual ~cfile_stream()
|
916 |
+
{
|
917 |
+
close();
|
918 |
+
}
|
919 |
+
|
920 |
+
bool open(const char *pFilename)
|
921 |
+
{
|
922 |
+
close();
|
923 |
+
#if defined(_MSC_VER)
|
924 |
+
if (fopen_s(&m_pFile, pFilename, "wb") != 0)
|
925 |
+
{
|
926 |
+
return false;
|
927 |
+
}
|
928 |
+
#else
|
929 |
+
m_pFile = fopen(pFilename, "wb");
|
930 |
+
#endif
|
931 |
+
m_bStatus = (m_pFile != NULL);
|
932 |
+
return m_bStatus;
|
933 |
+
}
|
934 |
+
|
935 |
+
bool close()
|
936 |
+
{
|
937 |
+
if (m_pFile)
|
938 |
+
{
|
939 |
+
if (fclose(m_pFile) == EOF)
|
940 |
+
{
|
941 |
+
m_bStatus = false;
|
942 |
+
}
|
943 |
+
m_pFile = NULL;
|
944 |
+
}
|
945 |
+
return m_bStatus;
|
946 |
+
}
|
947 |
+
|
948 |
+
virtual bool put_buf(const void* pBuf, int64_t len)
|
949 |
+
{
|
950 |
+
m_bStatus = m_bStatus && (fwrite(pBuf, len, 1, m_pFile) == 1);
|
951 |
+
return m_bStatus;
|
952 |
+
}
|
953 |
+
|
954 |
+
uint get_size() const
|
955 |
+
{
|
956 |
+
return m_pFile ? ftell(m_pFile) : 0;
|
957 |
+
}
|
958 |
+
};
|
959 |
+
|
960 |
+
// Writes JPEG image to file.
|
961 |
+
bool compress_image_to_jpeg_file(const char *pFilename, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params)
|
962 |
+
{
|
963 |
+
cfile_stream dst_stream;
|
964 |
+
if (!dst_stream.open(pFilename))
|
965 |
+
return false;
|
966 |
+
|
967 |
+
jpge::jpeg_encoder dst_image;
|
968 |
+
if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
|
969 |
+
return false;
|
970 |
+
|
971 |
+
for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
|
972 |
+
{
|
973 |
+
for (int64_t i = 0; i < height; i++)
|
974 |
+
{
|
975 |
+
// i, width, and num_channels are all 64bit
|
976 |
+
const uint8* pBuf = pImage_data + i * width * num_channels;
|
977 |
+
if (!dst_image.process_scanline(pBuf))
|
978 |
+
return false;
|
979 |
+
}
|
980 |
+
if (!dst_image.process_scanline(NULL))
|
981 |
+
return false;
|
982 |
+
}
|
983 |
+
|
984 |
+
dst_image.deinit();
|
985 |
+
|
986 |
+
return dst_stream.close();
|
987 |
+
}
|
988 |
+
|
989 |
+
class memory_stream : public output_stream
|
990 |
+
{
|
991 |
+
memory_stream(const memory_stream &);
|
992 |
+
memory_stream &operator= (const memory_stream &);
|
993 |
+
|
994 |
+
uint8 *m_pBuf;
|
995 |
+
uint64_t m_buf_size, m_buf_ofs;
|
996 |
+
|
997 |
+
public:
|
998 |
+
memory_stream(void *pBuf, uint64_t buf_size) : m_pBuf(static_cast<uint8*>(pBuf)), m_buf_size(buf_size), m_buf_ofs(0) { }
|
999 |
+
|
1000 |
+
virtual ~memory_stream() { }
|
1001 |
+
|
1002 |
+
virtual bool put_buf(const void* pBuf, int64_t len)
|
1003 |
+
{
|
1004 |
+
uint64_t buf_remaining = m_buf_size - m_buf_ofs;
|
1005 |
+
if ((uint64_t)len > buf_remaining)
|
1006 |
+
return false;
|
1007 |
+
memcpy(m_pBuf + m_buf_ofs, pBuf, len);
|
1008 |
+
m_buf_ofs += len;
|
1009 |
+
return true;
|
1010 |
+
}
|
1011 |
+
|
1012 |
+
uint64_t get_size() const
|
1013 |
+
{
|
1014 |
+
return m_buf_ofs;
|
1015 |
+
}
|
1016 |
+
};
|
1017 |
+
|
1018 |
+
bool compress_image_to_jpeg_file_in_memory(void *pDstBuf, int64_t &buf_size, int64_t width, int64_t height, int64_t num_channels, const uint8 *pImage_data, const params &comp_params)
|
1019 |
+
{
|
1020 |
+
if ((!pDstBuf) || (!buf_size))
|
1021 |
+
return false;
|
1022 |
+
|
1023 |
+
memory_stream dst_stream(pDstBuf, buf_size);
|
1024 |
+
|
1025 |
+
buf_size = 0;
|
1026 |
+
|
1027 |
+
jpge::jpeg_encoder dst_image;
|
1028 |
+
if (!dst_image.init(&dst_stream, width, height, num_channels, comp_params))
|
1029 |
+
return false;
|
1030 |
+
|
1031 |
+
for (uint pass_index = 0; pass_index < dst_image.get_total_passes(); pass_index++)
|
1032 |
+
{
|
1033 |
+
for (int64_t i = 0; i < height; i++)
|
1034 |
+
{
|
1035 |
+
const uint8* pScanline = pImage_data + i * width * num_channels;
|
1036 |
+
if (!dst_image.process_scanline(pScanline))
|
1037 |
+
return false;
|
1038 |
+
}
|
1039 |
+
if (!dst_image.process_scanline(NULL))
|
1040 |
+
return false;
|
1041 |
+
}
|
1042 |
+
|
1043 |
+
dst_image.deinit();
|
1044 |
+
|
1045 |
+
buf_size = dst_stream.get_size();
|
1046 |
+
return true;
|
1047 |
+
}
|
1048 |
+
|
1049 |
+
} // namespace jpge
|
crazy_functions/test_project/cpp/longcode/prod_cons.h
ADDED
@@ -0,0 +1,433 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#pragma once
|
2 |
+
|
3 |
+
#include <atomic>
|
4 |
+
#include <utility>
|
5 |
+
#include <cstring>
|
6 |
+
#include <type_traits>
|
7 |
+
#include <cstdint>
|
8 |
+
|
9 |
+
#include "libipc/def.h"
|
10 |
+
|
11 |
+
#include "libipc/platform/detail.h"
|
12 |
+
#include "libipc/circ/elem_def.h"
|
13 |
+
#include "libipc/utility/log.h"
|
14 |
+
#include "libipc/utility/utility.h"
|
15 |
+
|
16 |
+
namespace ipc {
|
17 |
+
|
18 |
+
////////////////////////////////////////////////////////////////
|
19 |
+
/// producer-consumer implementation
|
20 |
+
////////////////////////////////////////////////////////////////
|
21 |
+
|
22 |
+
template <typename Flag>
|
23 |
+
struct prod_cons_impl;
|
24 |
+
|
25 |
+
template <>
|
26 |
+
struct prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
|
27 |
+
|
28 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
29 |
+
struct elem_t {
|
30 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
31 |
+
};
|
32 |
+
|
33 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> rd_; // read index
|
34 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
|
35 |
+
|
36 |
+
constexpr circ::u2_t cursor() const noexcept {
|
37 |
+
return 0;
|
38 |
+
}
|
39 |
+
|
40 |
+
template <typename W, typename F, typename E>
|
41 |
+
bool push(W* /*wrapper*/, F&& f, E* elems) {
|
42 |
+
auto cur_wt = circ::index_of(wt_.load(std::memory_order_relaxed));
|
43 |
+
if (cur_wt == circ::index_of(rd_.load(std::memory_order_acquire) - 1)) {
|
44 |
+
return false; // full
|
45 |
+
}
|
46 |
+
std::forward<F>(f)(&(elems[cur_wt].data_));
|
47 |
+
wt_.fetch_add(1, std::memory_order_release);
|
48 |
+
return true;
|
49 |
+
}
|
50 |
+
|
51 |
+
/**
|
52 |
+
* In single-single-unicast, 'force_push' means 'no reader' or 'the only one reader is dead'.
|
53 |
+
* So we could just disconnect all connections of receiver, and return false.
|
54 |
+
*/
|
55 |
+
template <typename W, typename F, typename E>
|
56 |
+
bool force_push(W* wrapper, F&&, E*) {
|
57 |
+
wrapper->elems()->disconnect_receiver(~static_cast<circ::cc_t>(0u));
|
58 |
+
return false;
|
59 |
+
}
|
60 |
+
|
61 |
+
template <typename W, typename F, typename R, typename E>
|
62 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E* elems) {
|
63 |
+
auto cur_rd = circ::index_of(rd_.load(std::memory_order_relaxed));
|
64 |
+
if (cur_rd == circ::index_of(wt_.load(std::memory_order_acquire))) {
|
65 |
+
return false; // empty
|
66 |
+
}
|
67 |
+
std::forward<F>(f)(&(elems[cur_rd].data_));
|
68 |
+
std::forward<R>(out)(true);
|
69 |
+
rd_.fetch_add(1, std::memory_order_release);
|
70 |
+
return true;
|
71 |
+
}
|
72 |
+
};
|
73 |
+
|
74 |
+
template <>
|
75 |
+
struct prod_cons_impl<wr<relat::single, relat::multi , trans::unicast>>
|
76 |
+
: prod_cons_impl<wr<relat::single, relat::single, trans::unicast>> {
|
77 |
+
|
78 |
+
template <typename W, typename F, typename E>
|
79 |
+
bool force_push(W* wrapper, F&&, E*) {
|
80 |
+
wrapper->elems()->disconnect_receiver(1);
|
81 |
+
return false;
|
82 |
+
}
|
83 |
+
|
84 |
+
template <typename W, typename F, typename R,
|
85 |
+
template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
|
86 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
|
87 |
+
byte_t buff[DS];
|
88 |
+
for (unsigned k = 0;;) {
|
89 |
+
auto cur_rd = rd_.load(std::memory_order_relaxed);
|
90 |
+
if (circ::index_of(cur_rd) ==
|
91 |
+
circ::index_of(wt_.load(std::memory_order_acquire))) {
|
92 |
+
return false; // empty
|
93 |
+
}
|
94 |
+
std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
|
95 |
+
if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
|
96 |
+
std::forward<F>(f)(buff);
|
97 |
+
std::forward<R>(out)(true);
|
98 |
+
return true;
|
99 |
+
}
|
100 |
+
ipc::yield(k);
|
101 |
+
}
|
102 |
+
}
|
103 |
+
};
|
104 |
+
|
105 |
+
template <>
|
106 |
+
struct prod_cons_impl<wr<relat::multi , relat::multi, trans::unicast>>
|
107 |
+
: prod_cons_impl<wr<relat::single, relat::multi, trans::unicast>> {
|
108 |
+
|
109 |
+
using flag_t = std::uint64_t;
|
110 |
+
|
111 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
112 |
+
struct elem_t {
|
113 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
114 |
+
std::atomic<flag_t> f_ct_ { 0 }; // commit flag
|
115 |
+
};
|
116 |
+
|
117 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
|
118 |
+
|
119 |
+
template <typename W, typename F, typename E>
|
120 |
+
bool push(W* /*wrapper*/, F&& f, E* elems) {
|
121 |
+
circ::u2_t cur_ct, nxt_ct;
|
122 |
+
for (unsigned k = 0;;) {
|
123 |
+
cur_ct = ct_.load(std::memory_order_relaxed);
|
124 |
+
if (circ::index_of(nxt_ct = cur_ct + 1) ==
|
125 |
+
circ::index_of(rd_.load(std::memory_order_acquire))) {
|
126 |
+
return false; // full
|
127 |
+
}
|
128 |
+
if (ct_.compare_exchange_weak(cur_ct, nxt_ct, std::memory_order_acq_rel)) {
|
129 |
+
break;
|
130 |
+
}
|
131 |
+
ipc::yield(k);
|
132 |
+
}
|
133 |
+
auto* el = elems + circ::index_of(cur_ct);
|
134 |
+
std::forward<F>(f)(&(el->data_));
|
135 |
+
// set flag & try update wt
|
136 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
137 |
+
while (1) {
|
138 |
+
auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
|
139 |
+
if (cur_ct != wt_.load(std::memory_order_relaxed)) {
|
140 |
+
return true;
|
141 |
+
}
|
142 |
+
if ((~cac_ct) != cur_ct) {
|
143 |
+
return true;
|
144 |
+
}
|
145 |
+
if (!el->f_ct_.compare_exchange_strong(cac_ct, 0, std::memory_order_relaxed)) {
|
146 |
+
return true;
|
147 |
+
}
|
148 |
+
wt_.store(nxt_ct, std::memory_order_release);
|
149 |
+
cur_ct = nxt_ct;
|
150 |
+
nxt_ct = cur_ct + 1;
|
151 |
+
el = elems + circ::index_of(cur_ct);
|
152 |
+
}
|
153 |
+
return true;
|
154 |
+
}
|
155 |
+
|
156 |
+
template <typename W, typename F, typename E>
|
157 |
+
bool force_push(W* wrapper, F&&, E*) {
|
158 |
+
wrapper->elems()->disconnect_receiver(1);
|
159 |
+
return false;
|
160 |
+
}
|
161 |
+
|
162 |
+
template <typename W, typename F, typename R,
|
163 |
+
template <std::size_t, std::size_t> class E, std::size_t DS, std::size_t AS>
|
164 |
+
bool pop(W* /*wrapper*/, circ::u2_t& /*cur*/, F&& f, R&& out, E<DS, AS>* elems) {
|
165 |
+
byte_t buff[DS];
|
166 |
+
for (unsigned k = 0;;) {
|
167 |
+
auto cur_rd = rd_.load(std::memory_order_relaxed);
|
168 |
+
auto cur_wt = wt_.load(std::memory_order_acquire);
|
169 |
+
auto id_rd = circ::index_of(cur_rd);
|
170 |
+
auto id_wt = circ::index_of(cur_wt);
|
171 |
+
if (id_rd == id_wt) {
|
172 |
+
auto* el = elems + id_wt;
|
173 |
+
auto cac_ct = el->f_ct_.load(std::memory_order_acquire);
|
174 |
+
if ((~cac_ct) != cur_wt) {
|
175 |
+
return false; // empty
|
176 |
+
}
|
177 |
+
if (el->f_ct_.compare_exchange_weak(cac_ct, 0, std::memory_order_relaxed)) {
|
178 |
+
wt_.store(cur_wt + 1, std::memory_order_release);
|
179 |
+
}
|
180 |
+
k = 0;
|
181 |
+
}
|
182 |
+
else {
|
183 |
+
std::memcpy(buff, &(elems[circ::index_of(cur_rd)].data_), sizeof(buff));
|
184 |
+
if (rd_.compare_exchange_weak(cur_rd, cur_rd + 1, std::memory_order_release)) {
|
185 |
+
std::forward<F>(f)(buff);
|
186 |
+
std::forward<R>(out)(true);
|
187 |
+
return true;
|
188 |
+
}
|
189 |
+
ipc::yield(k);
|
190 |
+
}
|
191 |
+
}
|
192 |
+
}
|
193 |
+
};
|
194 |
+
|
195 |
+
template <>
|
196 |
+
struct prod_cons_impl<wr<relat::single, relat::multi, trans::broadcast>> {
|
197 |
+
|
198 |
+
using rc_t = std::uint64_t;
|
199 |
+
|
200 |
+
enum : rc_t {
|
201 |
+
ep_mask = 0x00000000ffffffffull,
|
202 |
+
ep_incr = 0x0000000100000000ull
|
203 |
+
};
|
204 |
+
|
205 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
206 |
+
struct elem_t {
|
207 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
208 |
+
std::atomic<rc_t> rc_ { 0 }; // read-counter
|
209 |
+
};
|
210 |
+
|
211 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> wt_; // write index
|
212 |
+
alignas(cache_line_size) rc_t epoch_ { 0 }; // only one writer
|
213 |
+
|
214 |
+
circ::u2_t cursor() const noexcept {
|
215 |
+
return wt_.load(std::memory_order_acquire);
|
216 |
+
}
|
217 |
+
|
218 |
+
template <typename W, typename F, typename E>
|
219 |
+
bool push(W* wrapper, F&& f, E* elems) {
|
220 |
+
E* el;
|
221 |
+
for (unsigned k = 0;;) {
|
222 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
223 |
+
if (cc == 0) return false; // no reader
|
224 |
+
el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
|
225 |
+
// check all consumers have finished reading this element
|
226 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
227 |
+
circ::cc_t rem_cc = cur_rc & ep_mask;
|
228 |
+
if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch_)) {
|
229 |
+
return false; // has not finished yet
|
230 |
+
}
|
231 |
+
// consider rem_cc to be 0 here
|
232 |
+
if (el->rc_.compare_exchange_weak(
|
233 |
+
cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
|
234 |
+
break;
|
235 |
+
}
|
236 |
+
ipc::yield(k);
|
237 |
+
}
|
238 |
+
std::forward<F>(f)(&(el->data_));
|
239 |
+
wt_.fetch_add(1, std::memory_order_release);
|
240 |
+
return true;
|
241 |
+
}
|
242 |
+
|
243 |
+
template <typename W, typename F, typename E>
|
244 |
+
bool force_push(W* wrapper, F&& f, E* elems) {
|
245 |
+
E* el;
|
246 |
+
epoch_ += ep_incr;
|
247 |
+
for (unsigned k = 0;;) {
|
248 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
249 |
+
if (cc == 0) return false; // no reader
|
250 |
+
el = elems + circ::index_of(wt_.load(std::memory_order_relaxed));
|
251 |
+
// check all consumers have finished reading this element
|
252 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
253 |
+
circ::cc_t rem_cc = cur_rc & ep_mask;
|
254 |
+
if (cc & rem_cc) {
|
255 |
+
ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
|
256 |
+
cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
|
257 |
+
if (cc == 0) return false; // no reader
|
258 |
+
}
|
259 |
+
// just compare & exchange
|
260 |
+
if (el->rc_.compare_exchange_weak(
|
261 |
+
cur_rc, epoch_ | static_cast<rc_t>(cc), std::memory_order_release)) {
|
262 |
+
break;
|
263 |
+
}
|
264 |
+
ipc::yield(k);
|
265 |
+
}
|
266 |
+
std::forward<F>(f)(&(el->data_));
|
267 |
+
wt_.fetch_add(1, std::memory_order_release);
|
268 |
+
return true;
|
269 |
+
}
|
270 |
+
|
271 |
+
template <typename W, typename F, typename R, typename E>
|
272 |
+
bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E* elems) {
|
273 |
+
if (cur == cursor()) return false; // acquire
|
274 |
+
auto* el = elems + circ::index_of(cur++);
|
275 |
+
std::forward<F>(f)(&(el->data_));
|
276 |
+
for (unsigned k = 0;;) {
|
277 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
278 |
+
if ((cur_rc & ep_mask) == 0) {
|
279 |
+
std::forward<R>(out)(true);
|
280 |
+
return true;
|
281 |
+
}
|
282 |
+
auto nxt_rc = cur_rc & ~static_cast<rc_t>(wrapper->connected_id());
|
283 |
+
if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
|
284 |
+
std::forward<R>(out)((nxt_rc & ep_mask) == 0);
|
285 |
+
return true;
|
286 |
+
}
|
287 |
+
ipc::yield(k);
|
288 |
+
}
|
289 |
+
}
|
290 |
+
};
|
291 |
+
|
292 |
+
template <>
|
293 |
+
struct prod_cons_impl<wr<relat::multi, relat::multi, trans::broadcast>> {
|
294 |
+
|
295 |
+
using rc_t = std::uint64_t;
|
296 |
+
using flag_t = std::uint64_t;
|
297 |
+
|
298 |
+
enum : rc_t {
|
299 |
+
rc_mask = 0x00000000ffffffffull,
|
300 |
+
ep_mask = 0x00ffffffffffffffull,
|
301 |
+
ep_incr = 0x0100000000000000ull,
|
302 |
+
ic_mask = 0xff000000ffffffffull,
|
303 |
+
ic_incr = 0x0000000100000000ull
|
304 |
+
};
|
305 |
+
|
306 |
+
template <std::size_t DataSize, std::size_t AlignSize>
|
307 |
+
struct elem_t {
|
308 |
+
std::aligned_storage_t<DataSize, AlignSize> data_ {};
|
309 |
+
std::atomic<rc_t > rc_ { 0 }; // read-counter
|
310 |
+
std::atomic<flag_t> f_ct_ { 0 }; // commit flag
|
311 |
+
};
|
312 |
+
|
313 |
+
alignas(cache_line_size) std::atomic<circ::u2_t> ct_; // commit index
|
314 |
+
alignas(cache_line_size) std::atomic<rc_t> epoch_ { 0 };
|
315 |
+
|
316 |
+
circ::u2_t cursor() const noexcept {
|
317 |
+
return ct_.load(std::memory_order_acquire);
|
318 |
+
}
|
319 |
+
|
320 |
+
constexpr static rc_t inc_rc(rc_t rc) noexcept {
|
321 |
+
return (rc & ic_mask) | ((rc + ic_incr) & ~ic_mask);
|
322 |
+
}
|
323 |
+
|
324 |
+
constexpr static rc_t inc_mask(rc_t rc) noexcept {
|
325 |
+
return inc_rc(rc) & ~rc_mask;
|
326 |
+
}
|
327 |
+
|
328 |
+
template <typename W, typename F, typename E>
|
329 |
+
bool push(W* wrapper, F&& f, E* elems) {
|
330 |
+
E* el;
|
331 |
+
circ::u2_t cur_ct;
|
332 |
+
rc_t epoch = epoch_.load(std::memory_order_acquire);
|
333 |
+
for (unsigned k = 0;;) {
|
334 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
335 |
+
if (cc == 0) return false; // no reader
|
336 |
+
el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
|
337 |
+
// check all consumers have finished reading this element
|
338 |
+
auto cur_rc = el->rc_.load(std::memory_order_relaxed);
|
339 |
+
circ::cc_t rem_cc = cur_rc & rc_mask;
|
340 |
+
if ((cc & rem_cc) && ((cur_rc & ~ep_mask) == epoch)) {
|
341 |
+
return false; // has not finished yet
|
342 |
+
}
|
343 |
+
else if (!rem_cc) {
|
344 |
+
auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
|
345 |
+
if ((cur_fl != cur_ct) && cur_fl) {
|
346 |
+
return false; // full
|
347 |
+
}
|
348 |
+
}
|
349 |
+
// consider rem_cc to be 0 here
|
350 |
+
if (el->rc_.compare_exchange_weak(
|
351 |
+
cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed) &&
|
352 |
+
epoch_.compare_exchange_weak(epoch, epoch, std::memory_order_acq_rel)) {
|
353 |
+
break;
|
354 |
+
}
|
355 |
+
ipc::yield(k);
|
356 |
+
}
|
357 |
+
// only one thread/process would touch here at one time
|
358 |
+
ct_.store(cur_ct + 1, std::memory_order_release);
|
359 |
+
std::forward<F>(f)(&(el->data_));
|
360 |
+
// set flag & try update wt
|
361 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
362 |
+
return true;
|
363 |
+
}
|
364 |
+
|
365 |
+
template <typename W, typename F, typename E>
|
366 |
+
bool force_push(W* wrapper, F&& f, E* elems) {
|
367 |
+
E* el;
|
368 |
+
circ::u2_t cur_ct;
|
369 |
+
rc_t epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
|
370 |
+
for (unsigned k = 0;;) {
|
371 |
+
circ::cc_t cc = wrapper->elems()->connections(std::memory_order_relaxed);
|
372 |
+
if (cc == 0) return false; // no reader
|
373 |
+
el = elems + circ::index_of(cur_ct = ct_.load(std::memory_order_relaxed));
|
374 |
+
// check all consumers have finished reading this element
|
375 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
376 |
+
circ::cc_t rem_cc = cur_rc & rc_mask;
|
377 |
+
if (cc & rem_cc) {
|
378 |
+
ipc::log("force_push: k = %u, cc = %u, rem_cc = %u\n", k, cc, rem_cc);
|
379 |
+
cc = wrapper->elems()->disconnect_receiver(rem_cc); // disconnect all invalid readers
|
380 |
+
if (cc == 0) return false; // no reader
|
381 |
+
}
|
382 |
+
// just compare & exchange
|
383 |
+
if (el->rc_.compare_exchange_weak(
|
384 |
+
cur_rc, inc_mask(epoch | (cur_rc & ep_mask)) | static_cast<rc_t>(cc), std::memory_order_relaxed)) {
|
385 |
+
if (epoch == epoch_.load(std::memory_order_acquire)) {
|
386 |
+
break;
|
387 |
+
}
|
388 |
+
else if (push(wrapper, std::forward<F>(f), elems)) {
|
389 |
+
return true;
|
390 |
+
}
|
391 |
+
epoch = epoch_.fetch_add(ep_incr, std::memory_order_release) + ep_incr;
|
392 |
+
}
|
393 |
+
ipc::yield(k);
|
394 |
+
}
|
395 |
+
// only one thread/process would touch here at one time
|
396 |
+
ct_.store(cur_ct + 1, std::memory_order_release);
|
397 |
+
std::forward<F>(f)(&(el->data_));
|
398 |
+
// set flag & try update wt
|
399 |
+
el->f_ct_.store(~static_cast<flag_t>(cur_ct), std::memory_order_release);
|
400 |
+
return true;
|
401 |
+
}
|
402 |
+
|
403 |
+
template <typename W, typename F, typename R, typename E, std::size_t N>
|
404 |
+
bool pop(W* wrapper, circ::u2_t& cur, F&& f, R&& out, E(& elems)[N]) {
|
405 |
+
auto* el = elems + circ::index_of(cur);
|
406 |
+
auto cur_fl = el->f_ct_.load(std::memory_order_acquire);
|
407 |
+
if (cur_fl != ~static_cast<flag_t>(cur)) {
|
408 |
+
return false; // empty
|
409 |
+
}
|
410 |
+
++cur;
|
411 |
+
std::forward<F>(f)(&(el->data_));
|
412 |
+
for (unsigned k = 0;;) {
|
413 |
+
auto cur_rc = el->rc_.load(std::memory_order_acquire);
|
414 |
+
if ((cur_rc & rc_mask) == 0) {
|
415 |
+
std::forward<R>(out)(true);
|
416 |
+
el->f_ct_.store(cur + N - 1, std::memory_order_release);
|
417 |
+
return true;
|
418 |
+
}
|
419 |
+
auto nxt_rc = inc_rc(cur_rc) & ~static_cast<rc_t>(wrapper->connected_id());
|
420 |
+
bool last_one = false;
|
421 |
+
if ((last_one = (nxt_rc & rc_mask) == 0)) {
|
422 |
+
el->f_ct_.store(cur + N - 1, std::memory_order_release);
|
423 |
+
}
|
424 |
+
if (el->rc_.compare_exchange_weak(cur_rc, nxt_rc, std::memory_order_release)) {
|
425 |
+
std::forward<R>(out)(last_one);
|
426 |
+
return true;
|
427 |
+
}
|
428 |
+
ipc::yield(k);
|
429 |
+
}
|
430 |
+
}
|
431 |
+
};
|
432 |
+
|
433 |
+
} // namespace ipc
|
crazy_functions/test_project/latex/attention/background.tex
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
The goal of reducing sequential computation also forms the foundation of the Extended Neural GPU \citep{extendedngpu}, ByteNet \citep{NalBytenet2017} and ConvS2S \citep{JonasFaceNet2017}, all of which use convolutional neural networks as basic building block, computing hidden representations in parallel for all input and output positions. In these models, the number of operations required to relate signals from two arbitrary input or output positions grows in the distance between positions, linearly for ConvS2S and logarithmically for ByteNet. This makes it more difficult to learn dependencies between distant positions \citep{hochreiter2001gradient}. In the Transformer this is reduced to a constant number of operations, albeit at the cost of reduced effective resolution due to averaging attention-weighted positions, an effect we counteract with Multi-Head Attention as described in section~\ref{sec:attention}.
|
2 |
+
|
3 |
+
Self-attention, sometimes called intra-attention is an attention mechanism relating different positions of a single sequence in order to compute a representation of the sequence. Self-attention has been used successfully in a variety of tasks including reading comprehension, abstractive summarization, textual entailment and learning task-independent sentence representations \citep{cheng2016long, decomposableAttnModel, paulus2017deep, lin2017structured}.
|
4 |
+
|
5 |
+
End-to-end memory networks are based on a recurrent attention mechanism instead of sequence-aligned recurrence and have been shown to perform well on simple-language question answering and language modeling tasks \citep{sukhbaatar2015}.
|
6 |
+
|
7 |
+
To the best of our knowledge, however, the Transformer is the first transduction model relying entirely on self-attention to compute representations of its input and output without using sequence-aligned RNNs or convolution.
|
8 |
+
In the following sections, we will describe the Transformer, motivate self-attention and discuss its advantages over models such as \citep{neural_gpu, NalBytenet2017} and \citep{JonasFaceNet2017}.
|
9 |
+
|
10 |
+
|
11 |
+
%\citep{JonasFaceNet2017} report new SOTA on machine translation for English-to-German (EnDe), Enlish-to-French (EnFr) and English-to-Romanian language pairs.
|
12 |
+
|
13 |
+
%For example,! in MT, we must draw information from both input and previous output words to translate an output word accurately. An attention layer \citep{bahdanau2014neural} can connect a very large number of positions at low computation cost, making it an essential ingredient in competitive recurrent models for machine translation.
|
14 |
+
|
15 |
+
%A natural question to ask then is, "Could we replace recurrence with attention?". \marginpar{Don't know if it's the most natural question to ask given the previous statements. Also, need to say that the complexity table summarizes these statements} Such a model would be blessed with the computational efficiency of attention and the power of cross-positional communication. In this work, show that pure attention models work remarkably well for MT, achieving new SOTA results on EnDe and EnFr, and can be trained in under $2$ days on xyz architecture.
|
16 |
+
|
17 |
+
%After the seminal models introduced in \citep{sutskever14, bahdanau2014neural, cho2014learning}, recurrent models have become the dominant solution for both sequence modeling and sequence-to-sequence transduction. Many efforts such as \citep{wu2016google,luong2015effective,jozefowicz2016exploring} have pushed the boundaries of machine translation (MT) and language modeling with recurrent endoder-decoder and recurrent language models. Recent effort \citep{shazeer2017outrageously} has successfully combined the power of conditional computation with sequence models to train very large models for MT, pushing SOTA at lower computational cost.
|
18 |
+
|
19 |
+
%Recurrent models compute a vector of hidden states $h_t$, for each time step $t$ of computation. $h_t$ is a function of both the input at time $t$ and the previous hidden state $h_t$. This dependence on the previous hidden state precludes processing all timesteps at once, instead requiring long sequences of sequential operations. In practice, this results in greatly reduced computational efficiency, as on modern computing hardware, a single operation on a large batch is much faster than a large number of operations on small batches. The problem gets worse at longer sequence lengths. Although sequential computation is not a severe bottleneck at inference time, as autoregressively generating each output requires all previous outputs, the inability to compute scores at all output positions at once hinders us from rapidly training our models over large datasets. Although impressive work such as \citep{Kuchaiev2017Factorization} is able to significantly accelerate the training of LSTMs with factorization tricks, we are still bound by the linear dependence on sequence length.
|
20 |
+
|
21 |
+
%If the model could compute hidden states at each time step using only the inputs and outputs, it would be liberated from the dependence on results from previous time steps during training. This line of thought is the foundation of recent efforts such as the Markovian neural GPU \citep{neural_gpu}, ByteNet \citep{NalBytenet2017} and ConvS2S \citep{JonasFaceNet2017}, all of which use convolutional neural networks as a building block to compute hidden representations simultaneously for all timesteps, resulting in $O(1)$ sequential time complexity. \citep{JonasFaceNet2017} report new SOTA on machine translation for English-to-German (EnDe), Enlish-to-French (EnFr) and English-to-Romanian language pairs.
|
22 |
+
|
23 |
+
%A crucial component for accurate sequence prediction is modeling cross-positional communication. For example, in MT, we must draw information from both input and previous output words to translate an output word accurately. An attention layer \citep{bahdanau2014neural} can connect a very large number of positions at a low computation cost, also $O(1)$ sequential time complexity, making it an essential ingredient in recurrent encoder-decoder architectures for MT. A natural question to ask then is, "Could we replace recurrence with attention?". \marginpar{Don't know if it's the most natural question to ask given the previous statements. Also, need to say that the complexity table summarizes these statements} Such a model would be blessed with the computational efficiency of attention and the power of cross-positional communication. In this work, show that pure attention models work remarkably well for MT, achieving new SOTA results on EnDe and EnFr, and can be trained in under $2$ days on xyz architecture.
|
24 |
+
|
25 |
+
|
26 |
+
|
27 |
+
%Note: Facebook model is no better than RNNs in this regard, since it requires a number of layers proportional to the distance you want to communicate. Bytenet is more promising, since it requires a logarithmnic number of layers (does bytenet have SOTA results)?
|
28 |
+
|
29 |
+
%Note: An attention layer can connect a very large number of positions at a low computation cost in O(1) sequential operations. This is why encoder-decoder attention has been so successful in seq-to-seq models so far. It is only natural, then, to also use attention to connect the timesteps of the same sequence.
|
30 |
+
|
31 |
+
%Note: I wouldn't say that long sequences are not a problem during inference. It would be great if we could infer with no long sequences. We could just say later on that, while our training graph is constant-depth, our model still requires sequential operations in the decoder part during inference due to the autoregressive nature of the model.
|
32 |
+
|
33 |
+
%\begin{table}[h!]
|
34 |
+
%\caption{Attention models are quite efficient for cross-positional communications when sequence length is smaller than channel depth. $n$ represents the sequence length and $d$ represents the channel depth.}
|
35 |
+
%\label{tab:op_complexities}
|
36 |
+
%\begin{center}
|
37 |
+
%\vspace{-5pt}
|
38 |
+
%\scalebox{0.75}{
|
39 |
+
|
40 |
+
%\begin{tabular}{l|c|c|c}
|
41 |
+
%\hline \hline
|
42 |
+
%Layer Type & Receptive & Complexity & Sequential \\
|
43 |
+
% & Field & & Operations \\
|
44 |
+
%\hline
|
45 |
+
%Pointwise Feed-Forward & $1$ & $O(n \cdot d^2)$ & $O(1)$ \\
|
46 |
+
%\hline
|
47 |
+
%Recurrent & $n$ & $O(n \cdot d^2)$ & $O(n)$ \\
|
48 |
+
%\hline
|
49 |
+
%Convolutional & $r$ & $O(r \cdot n \cdot d^2)$ & $O(1)$ \\
|
50 |
+
%\hline
|
51 |
+
%Convolutional (separable) & $r$ & $O(r \cdot n \cdot d + n %\cdot d^2)$ & $O(1)$ \\
|
52 |
+
%\hline
|
53 |
+
%Attention & $r$ & $O(r \cdot n \cdot d)$ & $O(1)$ \\
|
54 |
+
%\hline \hline
|
55 |
+
%\end{tabular}
|
56 |
+
%}
|
57 |
+
%\end{center}
|
58 |
+
%\end{table}
|
crazy_functions/test_project/latex/attention/introduction.tex
ADDED
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Recurrent neural networks, long short-term memory \citep{hochreiter1997} and gated recurrent \citep{gruEval14} neural networks in particular, have been firmly established as state of the art approaches in sequence modeling and transduction problems such as language modeling and machine translation \citep{sutskever14, bahdanau2014neural, cho2014learning}. Numerous efforts have since continued to push the boundaries of recurrent language models and encoder-decoder architectures \citep{wu2016google,luong2015effective,jozefowicz2016exploring}.
|
2 |
+
|
3 |
+
Recurrent models typically factor computation along the symbol positions of the input and output sequences. Aligning the positions to steps in computation time, they generate a sequence of hidden states $h_t$, as a function of the previous hidden state $h_{t-1}$ and the input for position $t$. This inherently sequential nature precludes parallelization within training examples, which becomes critical at longer sequence lengths, as memory constraints limit batching across examples.
|
4 |
+
%\marginpar{not sure if the memory constraints are understandable here}
|
5 |
+
Recent work has achieved significant improvements in computational efficiency through factorization tricks \citep{Kuchaiev2017Factorization} and conditional computation \citep{shazeer2017outrageously}, while also improving model performance in case of the latter. The fundamental constraint of sequential computation, however, remains.
|
6 |
+
|
7 |
+
%\marginpar{@all: there is work on analyzing what attention really does in seq2seq models, couldn't find it right away}
|
8 |
+
|
9 |
+
Attention mechanisms have become an integral part of compelling sequence modeling and transduction models in various tasks, allowing modeling of dependencies without regard to their distance in the input or output sequences \citep{bahdanau2014neural, structuredAttentionNetworks}. In all but a few cases \citep{decomposableAttnModel}, however, such attention mechanisms are used in conjunction with a recurrent network.
|
10 |
+
|
11 |
+
%\marginpar{not sure if "cross-positional communication" is understandable without explanation}
|
12 |
+
%\marginpar{insert exact training times and stats for the model that reaches sota earliest, maybe even a single GPU model?}
|
13 |
+
|
14 |
+
In this work we propose the Transformer, a model architecture eschewing recurrence and instead relying entirely on an attention mechanism to draw global dependencies between input and output. The Transformer allows for significantly more parallelization and can reach a new state of the art in translation quality after being trained for as little as twelve hours on eight P100 GPUs.
|
15 |
+
%\marginpar{you removed the constant number of repetitions part. I wrote it because I wanted to make it clear that the model does not only perform attention once, while it's also not recurrent. I thought that might be important to get across early.}
|
16 |
+
|
17 |
+
% Just a standard paragraph with citations, rewrite.
|
18 |
+
%After the seminal papers of \citep{sutskever14}, \citep{bahdanau2014neural}, and \citep{cho2014learning}, recurrent models have become the dominant solution for both sequence modeling and sequence-to-sequence transduction. Many efforts such as \citep{wu2016google,luong2015effective,jozefowicz2016exploring} have pushed the boundaries of machine translation and language modeling with recurrent sequence models. Recent effort \citep{shazeer2017outrageously} has combined the power of conditional computation with sequence models to train very large models for machine translation, pushing SOTA at lower computational cost. Recurrent models compute a vector of hidden states $h_t$, for each time step $t$ of computation. $h_t$ is a function of both the input at time $t$ and the previous hidden state $h_t$. This dependence on the previous hidden state encumbers recurrnet models to process multiple inputs at once, and their time complexity is a linear function of the length of the input and output, both during training and inference. [What I want to say here is that although this is fine during decoding, at training time, we are given both input and output and this linear nature does not allow the RNN to process all inputs and outputs simultaneously and haven't been used on datasets that are the of the scale of the web. What's the largest dataset we have ? . Talk about Nividia and possibly other's effors to speed up things, and possibly other efforts that alleviate this, but are still limited by it's comptuational nature]. Rest of the intro: What if you could construct the state based on the actual inputs and outputs, then you could construct them all at once. This has been the foundation of many promising recent efforts, bytenet,facenet (Also talk about quasi rnn here). Now we talk about attention!! Along with cell architectures such as long short-term meory (LSTM) \citep{hochreiter1997}, and gated recurrent units (GRUs) \citep{cho2014learning}, attention has emerged as an essential ingredient in successful sequence models, in particular for machine translation. In recent years, many, if not all, state-of-the-art (SOTA) results in machine translation have been achieved with attention-based sequence models \citep{wu2016google,luong2015effective,jozefowicz2016exploring}. Talk about the neon work on how it played with attention to do self attention! Then talk about what we do.
|
crazy_functions/test_project/latex/attention/model_architecture.tex
ADDED
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
\begin{figure}
|
3 |
+
\centering
|
4 |
+
\includegraphics[scale=0.6]{Figures/ModalNet-21}
|
5 |
+
\caption{The Transformer - model architecture.}
|
6 |
+
\label{fig:model-arch}
|
7 |
+
\end{figure}
|
8 |
+
|
9 |
+
% Although the primary workhorse of our model is attention,
|
10 |
+
%Our model maintains the encoder-decoder structure that is common to many so-called sequence-to-sequence models \citep{bahdanau2014neural,sutskever14}. As in all such architectures, the encoder computes a representation of the input sequence, and the decoder consumes these representations along with the output tokens to autoregressively produce the output sequence. Where, traditionally, the encoder and decoder contain stacks of recurrent or convolutional layers, our encoder and decoder stacks are composed of attention layers and position-wise feed-forward layers (Figure~\ref{fig:model-arch}). The following sections describe the gross architecture and these particular components in detail.
|
11 |
+
|
12 |
+
Most competitive neural sequence transduction models have an encoder-decoder structure \citep{cho2014learning,bahdanau2014neural,sutskever14}. Here, the encoder maps an input sequence of symbol representations $(x_1, ..., x_n)$ to a sequence of continuous representations $\mathbf{z} = (z_1, ..., z_n)$. Given $\mathbf{z}$, the decoder then generates an output sequence $(y_1,...,y_m)$ of symbols one element at a time. At each step the model is auto-regressive \citep{graves2013generating}, consuming the previously generated symbols as additional input when generating the next.
|
13 |
+
|
14 |
+
The Transformer follows this overall architecture using stacked self-attention and point-wise, fully connected layers for both the encoder and decoder, shown in the left and right halves of Figure~\ref{fig:model-arch}, respectively.
|
15 |
+
|
16 |
+
\subsection{Encoder and Decoder Stacks}
|
17 |
+
|
18 |
+
\paragraph{Encoder:}The encoder is composed of a stack of $N=6$ identical layers. Each layer has two sub-layers. The first is a multi-head self-attention mechanism, and the second is a simple, position-wise fully connected feed-forward network. We employ a residual connection \citep{he2016deep} around each of the two sub-layers, followed by layer normalization \cite{layernorm2016}. That is, the output of each sub-layer is $\mathrm{LayerNorm}(x + \mathrm{Sublayer}(x))$, where $\mathrm{Sublayer}(x)$ is the function implemented by the sub-layer itself. To facilitate these residual connections, all sub-layers in the model, as well as the embedding layers, produce outputs of dimension $\dmodel=512$.
|
19 |
+
|
20 |
+
\paragraph{Decoder:}The decoder is also composed of a stack of $N=6$ identical layers. In addition to the two sub-layers in each encoder layer, the decoder inserts a third sub-layer, which performs multi-head attention over the output of the encoder stack. Similar to the encoder, we employ residual connections around each of the sub-layers, followed by layer normalization. We also modify the self-attention sub-layer in the decoder stack to prevent positions from attending to subsequent positions. This masking, combined with fact that the output embeddings are offset by one position, ensures that the predictions for position $i$ can depend only on the known outputs at positions less than $i$.
|
21 |
+
|
22 |
+
% In our model (Figure~\ref{fig:model-arch}), the encoder and decoder are composed of stacks of alternating self-attention layers (for cross-positional communication) and position-wise feed-forward layers (for in-place computation). In addition, the decoder stack contains encoder-decoder attention layers. Since attention is agnostic to the distances between words, our model requires a "positional encoding" to be added to the encoder and decoder input. The following sections describe all of these components in detail.
|
23 |
+
|
24 |
+
\subsection{Attention} \label{sec:attention}
|
25 |
+
An attention function can be described as mapping a query and a set of key-value pairs to an output, where the query, keys, values, and output are all vectors. The output is computed as a weighted sum of the values, where the weight assigned to each value is computed by a compatibility function of the query with the corresponding key.
|
26 |
+
|
27 |
+
\subsubsection{Scaled Dot-Product Attention} \label{sec:scaled-dot-prod}
|
28 |
+
|
29 |
+
% \begin{figure}
|
30 |
+
% \centering
|
31 |
+
% \includegraphics[scale=0.6]{Figures/ModalNet-19}
|
32 |
+
% \caption{Scaled Dot-Product Attention.}
|
33 |
+
% \label{fig:multi-head-att}
|
34 |
+
% \end{figure}
|
35 |
+
|
36 |
+
We call our particular attention "Scaled Dot-Product Attention" (Figure~\ref{fig:multi-head-att}). The input consists of queries and keys of dimension $d_k$, and values of dimension $d_v$. We compute the dot products of the query with all keys, divide each by $\sqrt{d_k}$, and apply a softmax function to obtain the weights on the values.
|
37 |
+
|
38 |
+
In practice, we compute the attention function on a set of queries simultaneously, packed together into a matrix $Q$. The keys and values are also packed together into matrices $K$ and $V$. We compute the matrix of outputs as:
|
39 |
+
|
40 |
+
\begin{equation}
|
41 |
+
\mathrm{Attention}(Q, K, V) = \mathrm{softmax}(\frac{QK^T}{\sqrt{d_k}})V
|
42 |
+
\end{equation}
|
43 |
+
|
44 |
+
The two most commonly used attention functions are additive attention \citep{bahdanau2014neural}, and dot-product (multiplicative) attention. Dot-product attention is identical to our algorithm, except for the scaling factor of $\frac{1}{\sqrt{d_k}}$. Additive attention computes the compatibility function using a feed-forward network with a single hidden layer. While the two are similar in theoretical complexity, dot-product attention is much faster and more space-efficient in practice, since it can be implemented using highly optimized matrix multiplication code.
|
45 |
+
|
46 |
+
%We scale the dot products by $1/\sqrt{d_k}$ to limit the magnitude of the dot products, which works well in practice. Otherwise, we found applying the softmax to often result in weights very close to 0 or 1, and hence minuscule gradients.
|
47 |
+
|
48 |
+
% Already described in the subsequent section
|
49 |
+
%When used as part of decoder self-attention, an optional mask function is applied just before the softmax to prevent positions from attending to subsequent positions. This mask simply sets the logits corresponding to all illegal connections (those outside of the lower triangle) to $-\infty$.
|
50 |
+
|
51 |
+
%\paragraph{Comparison to Additive Attention: } We choose dot product attention over additive attention \citep{bahdanau2014neural} since it can be computed using highly optimized matrix multiplication code. This optimization is particularly important to us, as we employ many attention layers in our model.
|
52 |
+
|
53 |
+
While for small values of $d_k$ the two mechanisms perform similarly, additive attention outperforms dot product attention without scaling for larger values of $d_k$ \citep{DBLP:journals/corr/BritzGLL17}. We suspect that for large values of $d_k$, the dot products grow large in magnitude, pushing the softmax function into regions where it has extremely small gradients \footnote{To illustrate why the dot products get large, assume that the components of $q$ and $k$ are independent random variables with mean $0$ and variance $1$. Then their dot product, $q \cdot k = \sum_{i=1}^{d_k} q_ik_i$, has mean $0$ and variance $d_k$.}. To counteract this effect, we scale the dot products by $\frac{1}{\sqrt{d_k}}$.
|
54 |
+
|
55 |
+
|
56 |
+
%We suspect this to be caused by the dot products growing too large in magnitude to result in useful gradients after applying the softmax function. To counteract this, we scale the dot product by $1/\sqrt{d_k}$.
|
57 |
+
|
58 |
+
|
59 |
+
\subsubsection{Multi-Head Attention} \label{sec:multihead}
|
60 |
+
|
61 |
+
\begin{figure}
|
62 |
+
\begin{minipage}[t]{0.5\textwidth}
|
63 |
+
\centering
|
64 |
+
Scaled Dot-Product Attention \\
|
65 |
+
\vspace{0.5cm}
|
66 |
+
\includegraphics[scale=0.6]{Figures/ModalNet-19}
|
67 |
+
\end{minipage}
|
68 |
+
\begin{minipage}[t]{0.5\textwidth}
|
69 |
+
\centering
|
70 |
+
Multi-Head Attention \\
|
71 |
+
\vspace{0.1cm}
|
72 |
+
\includegraphics[scale=0.6]{Figures/ModalNet-20}
|
73 |
+
\end{minipage}
|
74 |
+
|
75 |
+
|
76 |
+
% \centering
|
77 |
+
|
78 |
+
\caption{(left) Scaled Dot-Product Attention. (right) Multi-Head Attention consists of several attention layers running in parallel.}
|
79 |
+
\label{fig:multi-head-att}
|
80 |
+
\end{figure}
|
81 |
+
|
82 |
+
Instead of performing a single attention function with $\dmodel$-dimensional keys, values and queries, we found it beneficial to linearly project the queries, keys and values $h$ times with different, learned linear projections to $d_k$, $d_k$ and $d_v$ dimensions, respectively.
|
83 |
+
On each of these projected versions of queries, keys and values we then perform the attention function in parallel, yielding $d_v$-dimensional output values. These are concatenated and once again projected, resulting in the final values, as depicted in Figure~\ref{fig:multi-head-att}.
|
84 |
+
|
85 |
+
Multi-head attention allows the model to jointly attend to information from different representation subspaces at different positions. With a single attention head, averaging inhibits this.
|
86 |
+
|
87 |
+
\begin{align*}
|
88 |
+
\mathrm{MultiHead}(Q, K, V) &= \mathrm{Concat}(\mathrm{head_1}, ..., \mathrm{head_h})W^O\\
|
89 |
+
% \mathrm{where} \mathrm{head_i} &= \mathrm{Attention}(QW_Q_i^{\dmodel \times d_q}, KW_K_i^{\dmodel \times d_k}, VW^V_i^{\dmodel \times d_v})\\
|
90 |
+
\text{where}~\mathrm{head_i} &= \mathrm{Attention}(QW^Q_i, KW^K_i, VW^V_i)\\
|
91 |
+
\end{align*}
|
92 |
+
|
93 |
+
Where the projections are parameter matrices $W^Q_i \in \mathbb{R}^{\dmodel \times d_k}$, $W^K_i \in \mathbb{R}^{\dmodel \times d_k}$, $W^V_i \in \mathbb{R}^{\dmodel \times d_v}$ and $W^O \in \mathbb{R}^{hd_v \times \dmodel}$.
|
94 |
+
|
95 |
+
|
96 |
+
%find it better (and no more expensive) to have multiple parallel attention layers (each over the full set of positions) with proportionally lower-dimensional keys, values and queries. We call this "Multi-Head Attention" (Figure~\ref{fig:multi-head-att}). The keys, values, and queries for each of these parallel attention layers are computed by learned linear transformations of the inputs to the multi-head attention. We use different linear transformations across different parallel attention layers. The output of the parallel attention layers are concatenated, and then passed through a final learned linear transformation.
|
97 |
+
|
98 |
+
In this work we employ $h=8$ parallel attention layers, or heads. For each of these we use $d_k=d_v=\dmodel/h=64$.
|
99 |
+
Due to the reduced dimension of each head, the total computational cost is similar to that of single-head attention with full dimensionality.
|
100 |
+
|
101 |
+
\subsubsection{Applications of Attention in our Model}
|
102 |
+
|
103 |
+
The Transformer uses multi-head attention in three different ways:
|
104 |
+
\begin{itemize}
|
105 |
+
\item In "encoder-decoder attention" layers, the queries come from the previous decoder layer, and the memory keys and values come from the output of the encoder. This allows every position in the decoder to attend over all positions in the input sequence. This mimics the typical encoder-decoder attention mechanisms in sequence-to-sequence models such as \citep{wu2016google, bahdanau2014neural,JonasFaceNet2017}.
|
106 |
+
|
107 |
+
\item The encoder contains self-attention layers. In a self-attention layer all of the keys, values and queries come from the same place, in this case, the output of the previous layer in the encoder. Each position in the encoder can attend to all positions in the previous layer of the encoder.
|
108 |
+
|
109 |
+
\item Similarly, self-attention layers in the decoder allow each position in the decoder to attend to all positions in the decoder up to and including that position. We need to prevent leftward information flow in the decoder to preserve the auto-regressive property. We implement this inside of scaled dot-product attention by masking out (setting to $-\infty$) all values in the input of the softmax which correspond to illegal connections. See Figure~\ref{fig:multi-head-att}.
|
110 |
+
|
111 |
+
\end{itemize}
|
112 |
+
|
113 |
+
\subsection{Position-wise Feed-Forward Networks}\label{sec:ffn}
|
114 |
+
|
115 |
+
In addition to attention sub-layers, each of the layers in our encoder and decoder contains a fully connected feed-forward network, which is applied to each position separately and identically. This consists of two linear transformations with a ReLU activation in between.
|
116 |
+
|
117 |
+
\begin{equation}
|
118 |
+
\mathrm{FFN}(x)=\max(0, xW_1 + b_1) W_2 + b_2
|
119 |
+
\end{equation}
|
120 |
+
|
121 |
+
While the linear transformations are the same across different positions, they use different parameters from layer to layer. Another way of describing this is as two convolutions with kernel size 1. The dimensionality of input and output is $\dmodel=512$, and the inner-layer has dimensionality $d_{ff}=2048$.
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
%In the appendix, we describe how the position-wise feed-forward network can also be seen as a form of attention.
|
126 |
+
|
127 |
+
%from Jakob: The number of operations required for the model to relate signals from two arbitrary input or output positions grows in the distance between positions in input or output, linearly for ConvS2S and logarithmically for ByteNet, making it harder to learn dependencies between these positions \citep{hochreiter2001gradient}. In the transformer this is reduced to a constant number of operations, albeit at the cost of effective resolution caused by averaging attention-weighted positions, an effect we aim to counteract with multi-headed attention.
|
128 |
+
|
129 |
+
|
130 |
+
%Figure~\ref{fig:simple-att} presents a simple attention function, $A$, with a single head, that forms the basis of our multi-head attention. $A$ takes a query key vector $\kq$, matrices of memory keys $\km$ and memory values $\vm$ ,and produces a query value vector $\vq$ as
|
131 |
+
%\begin{equation*} \label{eq:attention}
|
132 |
+
% A(\kq, \km, \vm) = {\vm}^T (Softmax(\km \kq).
|
133 |
+
%\end{equation*}
|
134 |
+
%We linearly transform $\kq,\,\km$, and $\vm$ with learned matrices ${\Wkq \text{,} \, \Wkm}$, and ${\Wvm}$ before calling the attention function, and transform the output query with $\Wvq$ before handing it to the feed forward layer. Each attention layer has it's own set of transformation matrices, which are shared across all query positions. $A$ is applied in parallel for each query position, and is implemented very efficiently as a batch of matrix multiplies. The self-attention and encoder-decoder attention layers use $A$, but with different arguments. For example, in encdoder self-attention, queries in encoder layer $i$ attention to memories in encoder layer $i-1$. To ensure that decoder self-attention layers do not look at future words, we add $- \inf$ to the softmax logits in positions $j+1$ to query length for query position $l$.
|
135 |
+
|
136 |
+
%In simple attention, the query value is a weighted combination of the memory values where the attention weights sum to one. Although this function performs well in practice, the constraint on attention weights can restrict the amount of information that flows from memories to queries because the query cannot focus on multiple memory positions at once, which might be desirable when translating long sequences. \marginpar{@usz, could you think of an example of this ?} We remedy this by maintaining multiple attention heads at each query position that attend to all memory positions in parallel, with a different set of parameters per attention head $h$.
|
137 |
+
%\marginpar{}
|
138 |
+
|
139 |
+
\subsection{Embeddings and Softmax}
|
140 |
+
Similarly to other sequence transduction models, we use learned embeddings to convert the input tokens and output tokens to vectors of dimension $\dmodel$. We also use the usual learned linear transformation and softmax function to convert the decoder output to predicted next-token probabilities. In our model, we share the same weight matrix between the two embedding layers and the pre-softmax linear transformation, similar to \citep{press2016using}. In the embedding layers, we multiply those weights by $\sqrt{\dmodel}$.
|
141 |
+
|
142 |
+
|
143 |
+
\subsection{Positional Encoding}
|
144 |
+
Since our model contains no recurrence and no convolution, in order for the model to make use of the order of the sequence, we must inject some information about the relative or absolute position of the tokens in the sequence. To this end, we add "positional encodings" to the input embeddings at the bottoms of the encoder and decoder stacks. The positional encodings have the same dimension $\dmodel$ as the embeddings, so that the two can be summed. There are many choices of positional encodings, learned and fixed \citep{JonasFaceNet2017}.
|
145 |
+
|
146 |
+
In this work, we use sine and cosine functions of different frequencies:
|
147 |
+
|
148 |
+
\begin{align*}
|
149 |
+
PE_{(pos,2i)} = sin(pos / 10000^{2i/\dmodel}) \\
|
150 |
+
PE_{(pos,2i+1)} = cos(pos / 10000^{2i/\dmodel})
|
151 |
+
\end{align*}
|
152 |
+
|
153 |
+
where $pos$ is the position and $i$ is the dimension. That is, each dimension of the positional encoding corresponds to a sinusoid. The wavelengths form a geometric progression from $2\pi$ to $10000 \cdot 2\pi$. We chose this function because we hypothesized it would allow the model to easily learn to attend by relative positions, since for any fixed offset $k$, $PE_{pos+k}$ can be represented as a linear function of $PE_{pos}$.
|
154 |
+
|
155 |
+
We also experimented with using learned positional embeddings \citep{JonasFaceNet2017} instead, and found that the two versions produced nearly identical results (see Table~\ref{tab:variations} row (E)). We chose the sinusoidal version because it may allow the model to extrapolate to sequence lengths longer than the ones encountered during training.
|
crazy_functions/test_project/latex/attention/parameter_attention.tex
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
\pagebreak
|
2 |
+
\section*{Two Feed-Forward Layers = Attention over Parameters}\label{sec:parameter_attention}
|
3 |
+
|
4 |
+
In addition to attention layers, our model contains position-wise feed-forward networks (Section \ref{sec:ffn}), which consist of two linear transformations with a ReLU activation in between. In fact, these networks too can be seen as a form of attention. Compare the formula for such a network with the formula for a simple dot-product attention layer (biases and scaling factors omitted):
|
5 |
+
|
6 |
+
\begin{align*}
|
7 |
+
FFN(x, W_1, W_2) = ReLU(xW_1)W_2 \\
|
8 |
+
A(q, K, V) = Softmax(qK^T)V
|
9 |
+
\end{align*}
|
10 |
+
|
11 |
+
Based on the similarity of these formulae, the two-layer feed-forward network can be seen as a kind of attention, where the keys and values are the rows of the trainable parameter matrices $W_1$ and $W_2$, and where we use ReLU instead of Softmax in the compatibility function.
|
12 |
+
|
13 |
+
%the compatablity function is $compat(q, k_i) = ReLU(q \cdot k_i)$ instead of $Softmax(qK_T)_i$.
|
14 |
+
|
15 |
+
Given this similarity, we experimented with replacing the position-wise feed-forward networks with attention layers similar to the ones we use everywhere else our model. The multi-head-attention-over-parameters sublayer is identical to the multi-head attention described in \ref{sec:multihead}, except that the "keys" and "values" inputs to each attention head are trainable model parameters, as opposed to being linear projections of a previous layer. These parameters are scaled up by a factor of $\sqrt{d_{model}}$ in order to be more similar to activations.
|
16 |
+
|
17 |
+
In our first experiment, we replaced each position-wise feed-forward network with a multi-head-attention-over-parameters sublayer with $h_p=8$ heads, key-dimensionality $d_{pk}=64$, and value-dimensionality $d_{pv}=64$, using $n_p=1536$ key-value pairs for each attention head. The sublayer has a total of $2097152$ parameters, including the parameters in the query projection and the output projection. This matches the number of parameters in the position-wise feed-forward network that we replaced. While the theoretical amount of computation is also the same, in practice, the attention version caused the step times to be about 30\% longer.
|
18 |
+
|
19 |
+
In our second experiment, we used $h_p=8$ heads, and $n_p=512$ key-value pairs for each attention head, again matching the total number of parameters in the base model.
|
20 |
+
|
21 |
+
Results for the first experiment were slightly worse than for the base model, and results for the second experiment were slightly better, see Table~\ref{tab:parameter_attention}.
|
22 |
+
|
23 |
+
\begin{table}[h]
|
24 |
+
\caption{Replacing the position-wise feed-forward networks with multihead-attention-over-parameters produces similar results to the base model. All metrics are on the English-to-German translation development set, newstest2013.}
|
25 |
+
\label{tab:parameter_attention}
|
26 |
+
\begin{center}
|
27 |
+
\vspace{-2mm}
|
28 |
+
%\scalebox{1.0}{
|
29 |
+
\begin{tabular}{c|cccccc|cccc}
|
30 |
+
\hline\rule{0pt}{2.0ex}
|
31 |
+
& \multirow{2}{*}{$\dmodel$} & \multirow{2}{*}{$\dff$} &
|
32 |
+
\multirow{2}{*}{$h_p$} & \multirow{2}{*}{$d_{pk}$} & \multirow{2}{*}{$d_{pv}$} &
|
33 |
+
\multirow{2}{*}{$n_p$} &
|
34 |
+
PPL & BLEU & params & training\\
|
35 |
+
& & & & & & & (dev) & (dev) & $\times10^6$ & time \\
|
36 |
+
\hline\rule{0pt}{2.0ex}
|
37 |
+
base & 512 & 2048 & & & & & 4.92 & 25.8 & 65 & 12 hours\\
|
38 |
+
\hline\rule{0pt}{2.0ex}
|
39 |
+
AOP$_1$ & 512 & & 8 & 64 & 64 & 1536 & 4.92& 25.5 & 65 & 16 hours\\
|
40 |
+
AOP$_2$ & 512 & & 16 & 64 & 64 & 512 & \textbf{4.86} & \textbf{25.9} & 65 & 16 hours \\
|
41 |
+
\hline
|
42 |
+
\end{tabular}
|
43 |
+
%}
|
44 |
+
\end{center}
|
45 |
+
\end{table}
|
crazy_functions/test_project/latex/attention/来源
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
chatgpt的老祖宗《Attention is all you need》
|
2 |
+
|
3 |
+
Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N. Gomez, Lukasz Kaiser, Illia Polosukhin
|
4 |
+
|
5 |
+
真实的摘要如下
|
6 |
+
The dominant sequence transduction models are based on complex recurrent or convolutional neural networks in an encoder-decoder configuration. The best performing models also connect the encoder and decoder through an attention mechanism. We propose a new simple network architecture, the Transformer, based solely on attention mechanisms, dispensing with recurrence and convolutions entirely. Experiments on two machine translation tasks show these models to be superior in quality while being more parallelizable and requiring significantly less time to train. Our model achieves 28.4 BLEU on the WMT 2014 English-to-German translation task, improving over the existing best results, including ensembles by over 2 BLEU. On the WMT 2014 English-to-French translation task, our model establishes a new single-model state-of-the-art BLEU score of 41.8 after training for 3.5 days on eight GPUs, a small fraction of the training costs of the best models from the literature. We show that the Transformer generalizes well to other tasks by applying it successfully to English constituency parsing both with large and limited training data.
|
7 |
+
|
8 |
+
https://arxiv.org/abs/1706.03762
|
crazy_functions/test_project/python/dqn/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from stable_baselines3.dqn.dqn import DQN
|
2 |
+
from stable_baselines3.dqn.policies import CnnPolicy, MlpPolicy
|
crazy_functions/test_project/python/dqn/dqn.py
ADDED
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, List, Optional, Tuple, Type, Union
|
2 |
+
|
3 |
+
import gym
|
4 |
+
import numpy as np
|
5 |
+
import torch as th
|
6 |
+
from torch.nn import functional as F
|
7 |
+
|
8 |
+
from stable_baselines3.common import logger
|
9 |
+
from stable_baselines3.common.off_policy_algorithm import OffPolicyAlgorithm
|
10 |
+
from stable_baselines3.common.preprocessing import maybe_transpose
|
11 |
+
from stable_baselines3.common.type_aliases import GymEnv, MaybeCallback, Schedule
|
12 |
+
from stable_baselines3.common.utils import get_linear_fn, is_vectorized_observation, polyak_update
|
13 |
+
from stable_baselines3.dqn.policies import DQNPolicy
|
14 |
+
|
15 |
+
|
16 |
+
class DQN(OffPolicyAlgorithm):
|
17 |
+
"""
|
18 |
+
Deep Q-Network (DQN)
|
19 |
+
|
20 |
+
Paper: https://arxiv.org/abs/1312.5602, https://www.nature.com/articles/nature14236
|
21 |
+
Default hyperparameters are taken from the nature paper,
|
22 |
+
except for the optimizer and learning rate that were taken from Stable Baselines defaults.
|
23 |
+
|
24 |
+
:param policy: The policy model to use (MlpPolicy, CnnPolicy, ...)
|
25 |
+
:param env: The environment to learn from (if registered in Gym, can be str)
|
26 |
+
:param learning_rate: The learning rate, it can be a function
|
27 |
+
of the current progress remaining (from 1 to 0)
|
28 |
+
:param buffer_size: size of the replay buffer
|
29 |
+
:param learning_starts: how many steps of the model to collect transitions for before learning starts
|
30 |
+
:param batch_size: Minibatch size for each gradient update
|
31 |
+
:param tau: the soft update coefficient ("Polyak update", between 0 and 1) default 1 for hard update
|
32 |
+
:param gamma: the discount factor
|
33 |
+
:param train_freq: Update the model every ``train_freq`` steps. Alternatively pass a tuple of frequency and unit
|
34 |
+
like ``(5, "step")`` or ``(2, "episode")``.
|
35 |
+
:param gradient_steps: How many gradient steps to do after each rollout (see ``train_freq``)
|
36 |
+
Set to ``-1`` means to do as many gradient steps as steps done in the environment
|
37 |
+
during the rollout.
|
38 |
+
:param optimize_memory_usage: Enable a memory efficient variant of the replay buffer
|
39 |
+
at a cost of more complexity.
|
40 |
+
See https://github.com/DLR-RM/stable-baselines3/issues/37#issuecomment-637501195
|
41 |
+
:param target_update_interval: update the target network every ``target_update_interval``
|
42 |
+
environment steps.
|
43 |
+
:param exploration_fraction: fraction of entire training period over which the exploration rate is reduced
|
44 |
+
:param exploration_initial_eps: initial value of random action probability
|
45 |
+
:param exploration_final_eps: final value of random action probability
|
46 |
+
:param max_grad_norm: The maximum value for the gradient clipping
|
47 |
+
:param tensorboard_log: the log location for tensorboard (if None, no logging)
|
48 |
+
:param create_eval_env: Whether to create a second environment that will be
|
49 |
+
used for evaluating the agent periodically. (Only available when passing string for the environment)
|
50 |
+
:param policy_kwargs: additional arguments to be passed to the policy on creation
|
51 |
+
:param verbose: the verbosity level: 0 no output, 1 info, 2 debug
|
52 |
+
:param seed: Seed for the pseudo random generators
|
53 |
+
:param device: Device (cpu, cuda, ...) on which the code should be run.
|
54 |
+
Setting it to auto, the code will be run on the GPU if possible.
|
55 |
+
:param _init_setup_model: Whether or not to build the network at the creation of the instance
|
56 |
+
"""
|
57 |
+
|
58 |
+
def __init__(
|
59 |
+
self,
|
60 |
+
policy: Union[str, Type[DQNPolicy]],
|
61 |
+
env: Union[GymEnv, str],
|
62 |
+
learning_rate: Union[float, Schedule] = 1e-4,
|
63 |
+
buffer_size: int = 1000000,
|
64 |
+
learning_starts: int = 50000,
|
65 |
+
batch_size: Optional[int] = 32,
|
66 |
+
tau: float = 1.0,
|
67 |
+
gamma: float = 0.99,
|
68 |
+
train_freq: Union[int, Tuple[int, str]] = 4,
|
69 |
+
gradient_steps: int = 1,
|
70 |
+
optimize_memory_usage: bool = False,
|
71 |
+
target_update_interval: int = 10000,
|
72 |
+
exploration_fraction: float = 0.1,
|
73 |
+
exploration_initial_eps: float = 1.0,
|
74 |
+
exploration_final_eps: float = 0.05,
|
75 |
+
max_grad_norm: float = 10,
|
76 |
+
tensorboard_log: Optional[str] = None,
|
77 |
+
create_eval_env: bool = False,
|
78 |
+
policy_kwargs: Optional[Dict[str, Any]] = None,
|
79 |
+
verbose: int = 0,
|
80 |
+
seed: Optional[int] = None,
|
81 |
+
device: Union[th.device, str] = "auto",
|
82 |
+
_init_setup_model: bool = True,
|
83 |
+
):
|
84 |
+
|
85 |
+
super(DQN, self).__init__(
|
86 |
+
policy,
|
87 |
+
env,
|
88 |
+
DQNPolicy,
|
89 |
+
learning_rate,
|
90 |
+
buffer_size,
|
91 |
+
learning_starts,
|
92 |
+
batch_size,
|
93 |
+
tau,
|
94 |
+
gamma,
|
95 |
+
train_freq,
|
96 |
+
gradient_steps,
|
97 |
+
action_noise=None, # No action noise
|
98 |
+
policy_kwargs=policy_kwargs,
|
99 |
+
tensorboard_log=tensorboard_log,
|
100 |
+
verbose=verbose,
|
101 |
+
device=device,
|
102 |
+
create_eval_env=create_eval_env,
|
103 |
+
seed=seed,
|
104 |
+
sde_support=False,
|
105 |
+
optimize_memory_usage=optimize_memory_usage,
|
106 |
+
supported_action_spaces=(gym.spaces.Discrete,),
|
107 |
+
)
|
108 |
+
|
109 |
+
self.exploration_initial_eps = exploration_initial_eps
|
110 |
+
self.exploration_final_eps = exploration_final_eps
|
111 |
+
self.exploration_fraction = exploration_fraction
|
112 |
+
self.target_update_interval = target_update_interval
|
113 |
+
self.max_grad_norm = max_grad_norm
|
114 |
+
# "epsilon" for the epsilon-greedy exploration
|
115 |
+
self.exploration_rate = 0.0
|
116 |
+
# Linear schedule will be defined in `_setup_model()`
|
117 |
+
self.exploration_schedule = None
|
118 |
+
self.q_net, self.q_net_target = None, None
|
119 |
+
|
120 |
+
if _init_setup_model:
|
121 |
+
self._setup_model()
|
122 |
+
|
123 |
+
def _setup_model(self) -> None:
|
124 |
+
super(DQN, self)._setup_model()
|
125 |
+
self._create_aliases()
|
126 |
+
self.exploration_schedule = get_linear_fn(
|
127 |
+
self.exploration_initial_eps, self.exploration_final_eps, self.exploration_fraction
|
128 |
+
)
|
129 |
+
|
130 |
+
def _create_aliases(self) -> None:
|
131 |
+
self.q_net = self.policy.q_net
|
132 |
+
self.q_net_target = self.policy.q_net_target
|
133 |
+
|
134 |
+
def _on_step(self) -> None:
|
135 |
+
"""
|
136 |
+
Update the exploration rate and target network if needed.
|
137 |
+
This method is called in ``collect_rollouts()`` after each step in the environment.
|
138 |
+
"""
|
139 |
+
if self.num_timesteps % self.target_update_interval == 0:
|
140 |
+
polyak_update(self.q_net.parameters(), self.q_net_target.parameters(), self.tau)
|
141 |
+
|
142 |
+
self.exploration_rate = self.exploration_schedule(self._current_progress_remaining)
|
143 |
+
logger.record("rollout/exploration rate", self.exploration_rate)
|
144 |
+
|
145 |
+
def train(self, gradient_steps: int, batch_size: int = 100) -> None:
|
146 |
+
# Update learning rate according to schedule
|
147 |
+
self._update_learning_rate(self.policy.optimizer)
|
148 |
+
|
149 |
+
losses = []
|
150 |
+
for _ in range(gradient_steps):
|
151 |
+
# Sample replay buffer
|
152 |
+
replay_data = self.replay_buffer.sample(batch_size, env=self._vec_normalize_env)
|
153 |
+
|
154 |
+
with th.no_grad():
|
155 |
+
# Compute the next Q-values using the target network
|
156 |
+
next_q_values = self.q_net_target(replay_data.next_observations)
|
157 |
+
# Follow greedy policy: use the one with the highest value
|
158 |
+
next_q_values, _ = next_q_values.max(dim=1)
|
159 |
+
# Avoid potential broadcast issue
|
160 |
+
next_q_values = next_q_values.reshape(-1, 1)
|
161 |
+
# 1-step TD target
|
162 |
+
target_q_values = replay_data.rewards + (1 - replay_data.dones) * self.gamma * next_q_values
|
163 |
+
|
164 |
+
# Get current Q-values estimates
|
165 |
+
current_q_values = self.q_net(replay_data.observations)
|
166 |
+
|
167 |
+
# Retrieve the q-values for the actions from the replay buffer
|
168 |
+
current_q_values = th.gather(current_q_values, dim=1, index=replay_data.actions.long())
|
169 |
+
|
170 |
+
# Compute Huber loss (less sensitive to outliers)
|
171 |
+
loss = F.smooth_l1_loss(current_q_values, target_q_values)
|
172 |
+
losses.append(loss.item())
|
173 |
+
|
174 |
+
# Optimize the policy
|
175 |
+
self.policy.optimizer.zero_grad()
|
176 |
+
loss.backward()
|
177 |
+
# Clip gradient norm
|
178 |
+
th.nn.utils.clip_grad_norm_(self.policy.parameters(), self.max_grad_norm)
|
179 |
+
self.policy.optimizer.step()
|
180 |
+
|
181 |
+
# Increase update counter
|
182 |
+
self._n_updates += gradient_steps
|
183 |
+
|
184 |
+
logger.record("train/n_updates", self._n_updates, exclude="tensorboard")
|
185 |
+
logger.record("train/loss", np.mean(losses))
|
186 |
+
|
187 |
+
def predict(
|
188 |
+
self,
|
189 |
+
observation: np.ndarray,
|
190 |
+
state: Optional[np.ndarray] = None,
|
191 |
+
mask: Optional[np.ndarray] = None,
|
192 |
+
deterministic: bool = False,
|
193 |
+
) -> Tuple[np.ndarray, Optional[np.ndarray]]:
|
194 |
+
"""
|
195 |
+
Overrides the base_class predict function to include epsilon-greedy exploration.
|
196 |
+
|
197 |
+
:param observation: the input observation
|
198 |
+
:param state: The last states (can be None, used in recurrent policies)
|
199 |
+
:param mask: The last masks (can be None, used in recurrent policies)
|
200 |
+
:param deterministic: Whether or not to return deterministic actions.
|
201 |
+
:return: the model's action and the next state
|
202 |
+
(used in recurrent policies)
|
203 |
+
"""
|
204 |
+
if not deterministic and np.random.rand() < self.exploration_rate:
|
205 |
+
if is_vectorized_observation(maybe_transpose(observation, self.observation_space), self.observation_space):
|
206 |
+
n_batch = observation.shape[0]
|
207 |
+
action = np.array([self.action_space.sample() for _ in range(n_batch)])
|
208 |
+
else:
|
209 |
+
action = np.array(self.action_space.sample())
|
210 |
+
else:
|
211 |
+
action, state = self.policy.predict(observation, state, mask, deterministic)
|
212 |
+
return action, state
|
213 |
+
|
214 |
+
def learn(
|
215 |
+
self,
|
216 |
+
total_timesteps: int,
|
217 |
+
callback: MaybeCallback = None,
|
218 |
+
log_interval: int = 4,
|
219 |
+
eval_env: Optional[GymEnv] = None,
|
220 |
+
eval_freq: int = -1,
|
221 |
+
n_eval_episodes: int = 5,
|
222 |
+
tb_log_name: str = "DQN",
|
223 |
+
eval_log_path: Optional[str] = None,
|
224 |
+
reset_num_timesteps: bool = True,
|
225 |
+
) -> OffPolicyAlgorithm:
|
226 |
+
|
227 |
+
return super(DQN, self).learn(
|
228 |
+
total_timesteps=total_timesteps,
|
229 |
+
callback=callback,
|
230 |
+
log_interval=log_interval,
|
231 |
+
eval_env=eval_env,
|
232 |
+
eval_freq=eval_freq,
|
233 |
+
n_eval_episodes=n_eval_episodes,
|
234 |
+
tb_log_name=tb_log_name,
|
235 |
+
eval_log_path=eval_log_path,
|
236 |
+
reset_num_timesteps=reset_num_timesteps,
|
237 |
+
)
|
238 |
+
|
239 |
+
def _excluded_save_params(self) -> List[str]:
|
240 |
+
return super(DQN, self)._excluded_save_params() + ["q_net", "q_net_target"]
|
241 |
+
|
242 |
+
def _get_torch_save_params(self) -> Tuple[List[str], List[str]]:
|
243 |
+
state_dicts = ["policy", "policy.optimizer"]
|
244 |
+
|
245 |
+
return state_dicts, []
|
crazy_functions/test_project/python/dqn/policies.py
ADDED
@@ -0,0 +1,237 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Dict, List, Optional, Type
|
2 |
+
|
3 |
+
import gym
|
4 |
+
import torch as th
|
5 |
+
from torch import nn
|
6 |
+
|
7 |
+
from stable_baselines3.common.policies import BasePolicy, register_policy
|
8 |
+
from stable_baselines3.common.torch_layers import BaseFeaturesExtractor, FlattenExtractor, NatureCNN, create_mlp
|
9 |
+
from stable_baselines3.common.type_aliases import Schedule
|
10 |
+
|
11 |
+
|
12 |
+
class QNetwork(BasePolicy):
|
13 |
+
"""
|
14 |
+
Action-Value (Q-Value) network for DQN
|
15 |
+
|
16 |
+
:param observation_space: Observation space
|
17 |
+
:param action_space: Action space
|
18 |
+
:param net_arch: The specification of the policy and value networks.
|
19 |
+
:param activation_fn: Activation function
|
20 |
+
:param normalize_images: Whether to normalize images or not,
|
21 |
+
dividing by 255.0 (True by default)
|
22 |
+
"""
|
23 |
+
|
24 |
+
def __init__(
|
25 |
+
self,
|
26 |
+
observation_space: gym.spaces.Space,
|
27 |
+
action_space: gym.spaces.Space,
|
28 |
+
features_extractor: nn.Module,
|
29 |
+
features_dim: int,
|
30 |
+
net_arch: Optional[List[int]] = None,
|
31 |
+
activation_fn: Type[nn.Module] = nn.ReLU,
|
32 |
+
normalize_images: bool = True,
|
33 |
+
):
|
34 |
+
super(QNetwork, self).__init__(
|
35 |
+
observation_space,
|
36 |
+
action_space,
|
37 |
+
features_extractor=features_extractor,
|
38 |
+
normalize_images=normalize_images,
|
39 |
+
)
|
40 |
+
|
41 |
+
if net_arch is None:
|
42 |
+
net_arch = [64, 64]
|
43 |
+
|
44 |
+
self.net_arch = net_arch
|
45 |
+
self.activation_fn = activation_fn
|
46 |
+
self.features_extractor = features_extractor
|
47 |
+
self.features_dim = features_dim
|
48 |
+
self.normalize_images = normalize_images
|
49 |
+
action_dim = self.action_space.n # number of actions
|
50 |
+
q_net = create_mlp(self.features_dim, action_dim, self.net_arch, self.activation_fn)
|
51 |
+
self.q_net = nn.Sequential(*q_net)
|
52 |
+
|
53 |
+
def forward(self, obs: th.Tensor) -> th.Tensor:
|
54 |
+
"""
|
55 |
+
Predict the q-values.
|
56 |
+
|
57 |
+
:param obs: Observation
|
58 |
+
:return: The estimated Q-Value for each action.
|
59 |
+
"""
|
60 |
+
return self.q_net(self.extract_features(obs))
|
61 |
+
|
62 |
+
def _predict(self, observation: th.Tensor, deterministic: bool = True) -> th.Tensor:
|
63 |
+
q_values = self.forward(observation)
|
64 |
+
# Greedy action
|
65 |
+
action = q_values.argmax(dim=1).reshape(-1)
|
66 |
+
return action
|
67 |
+
|
68 |
+
def _get_constructor_parameters(self) -> Dict[str, Any]:
|
69 |
+
data = super()._get_constructor_parameters()
|
70 |
+
|
71 |
+
data.update(
|
72 |
+
dict(
|
73 |
+
net_arch=self.net_arch,
|
74 |
+
features_dim=self.features_dim,
|
75 |
+
activation_fn=self.activation_fn,
|
76 |
+
features_extractor=self.features_extractor,
|
77 |
+
)
|
78 |
+
)
|
79 |
+
return data
|
80 |
+
|
81 |
+
|
82 |
+
class DQNPolicy(BasePolicy):
|
83 |
+
"""
|
84 |
+
Policy class with Q-Value Net and target net for DQN
|
85 |
+
|
86 |
+
:param observation_space: Observation space
|
87 |
+
:param action_space: Action space
|
88 |
+
:param lr_schedule: Learning rate schedule (could be constant)
|
89 |
+
:param net_arch: The specification of the policy and value networks.
|
90 |
+
:param activation_fn: Activation function
|
91 |
+
:param features_extractor_class: Features extractor to use.
|
92 |
+
:param features_extractor_kwargs: Keyword arguments
|
93 |
+
to pass to the features extractor.
|
94 |
+
:param normalize_images: Whether to normalize images or not,
|
95 |
+
dividing by 255.0 (True by default)
|
96 |
+
:param optimizer_class: The optimizer to use,
|
97 |
+
``th.optim.Adam`` by default
|
98 |
+
:param optimizer_kwargs: Additional keyword arguments,
|
99 |
+
excluding the learning rate, to pass to the optimizer
|
100 |
+
"""
|
101 |
+
|
102 |
+
def __init__(
|
103 |
+
self,
|
104 |
+
observation_space: gym.spaces.Space,
|
105 |
+
action_space: gym.spaces.Space,
|
106 |
+
lr_schedule: Schedule,
|
107 |
+
net_arch: Optional[List[int]] = None,
|
108 |
+
activation_fn: Type[nn.Module] = nn.ReLU,
|
109 |
+
features_extractor_class: Type[BaseFeaturesExtractor] = FlattenExtractor,
|
110 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
111 |
+
normalize_images: bool = True,
|
112 |
+
optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,
|
113 |
+
optimizer_kwargs: Optional[Dict[str, Any]] = None,
|
114 |
+
):
|
115 |
+
super(DQNPolicy, self).__init__(
|
116 |
+
observation_space,
|
117 |
+
action_space,
|
118 |
+
features_extractor_class,
|
119 |
+
features_extractor_kwargs,
|
120 |
+
optimizer_class=optimizer_class,
|
121 |
+
optimizer_kwargs=optimizer_kwargs,
|
122 |
+
)
|
123 |
+
|
124 |
+
if net_arch is None:
|
125 |
+
if features_extractor_class == FlattenExtractor:
|
126 |
+
net_arch = [64, 64]
|
127 |
+
else:
|
128 |
+
net_arch = []
|
129 |
+
|
130 |
+
self.net_arch = net_arch
|
131 |
+
self.activation_fn = activation_fn
|
132 |
+
self.normalize_images = normalize_images
|
133 |
+
|
134 |
+
self.net_args = {
|
135 |
+
"observation_space": self.observation_space,
|
136 |
+
"action_space": self.action_space,
|
137 |
+
"net_arch": self.net_arch,
|
138 |
+
"activation_fn": self.activation_fn,
|
139 |
+
"normalize_images": normalize_images,
|
140 |
+
}
|
141 |
+
|
142 |
+
self.q_net, self.q_net_target = None, None
|
143 |
+
self._build(lr_schedule)
|
144 |
+
|
145 |
+
def _build(self, lr_schedule: Schedule) -> None:
|
146 |
+
"""
|
147 |
+
Create the network and the optimizer.
|
148 |
+
|
149 |
+
:param lr_schedule: Learning rate schedule
|
150 |
+
lr_schedule(1) is the initial learning rate
|
151 |
+
"""
|
152 |
+
|
153 |
+
self.q_net = self.make_q_net()
|
154 |
+
self.q_net_target = self.make_q_net()
|
155 |
+
self.q_net_target.load_state_dict(self.q_net.state_dict())
|
156 |
+
|
157 |
+
# Setup optimizer with initial learning rate
|
158 |
+
self.optimizer = self.optimizer_class(self.parameters(), lr=lr_schedule(1), **self.optimizer_kwargs)
|
159 |
+
|
160 |
+
def make_q_net(self) -> QNetwork:
|
161 |
+
# Make sure we always have separate networks for features extractors etc
|
162 |
+
net_args = self._update_features_extractor(self.net_args, features_extractor=None)
|
163 |
+
return QNetwork(**net_args).to(self.device)
|
164 |
+
|
165 |
+
def forward(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor:
|
166 |
+
return self._predict(obs, deterministic=deterministic)
|
167 |
+
|
168 |
+
def _predict(self, obs: th.Tensor, deterministic: bool = True) -> th.Tensor:
|
169 |
+
return self.q_net._predict(obs, deterministic=deterministic)
|
170 |
+
|
171 |
+
def _get_constructor_parameters(self) -> Dict[str, Any]:
|
172 |
+
data = super()._get_constructor_parameters()
|
173 |
+
|
174 |
+
data.update(
|
175 |
+
dict(
|
176 |
+
net_arch=self.net_args["net_arch"],
|
177 |
+
activation_fn=self.net_args["activation_fn"],
|
178 |
+
lr_schedule=self._dummy_schedule, # dummy lr schedule, not needed for loading policy alone
|
179 |
+
optimizer_class=self.optimizer_class,
|
180 |
+
optimizer_kwargs=self.optimizer_kwargs,
|
181 |
+
features_extractor_class=self.features_extractor_class,
|
182 |
+
features_extractor_kwargs=self.features_extractor_kwargs,
|
183 |
+
)
|
184 |
+
)
|
185 |
+
return data
|
186 |
+
|
187 |
+
|
188 |
+
MlpPolicy = DQNPolicy
|
189 |
+
|
190 |
+
|
191 |
+
class CnnPolicy(DQNPolicy):
|
192 |
+
"""
|
193 |
+
Policy class for DQN when using images as input.
|
194 |
+
|
195 |
+
:param observation_space: Observation space
|
196 |
+
:param action_space: Action space
|
197 |
+
:param lr_schedule: Learning rate schedule (could be constant)
|
198 |
+
:param net_arch: The specification of the policy and value networks.
|
199 |
+
:param activation_fn: Activation function
|
200 |
+
:param features_extractor_class: Features extractor to use.
|
201 |
+
:param normalize_images: Whether to normalize images or not,
|
202 |
+
dividing by 255.0 (True by default)
|
203 |
+
:param optimizer_class: The optimizer to use,
|
204 |
+
``th.optim.Adam`` by default
|
205 |
+
:param optimizer_kwargs: Additional keyword arguments,
|
206 |
+
excluding the learning rate, to pass to the optimizer
|
207 |
+
"""
|
208 |
+
|
209 |
+
def __init__(
|
210 |
+
self,
|
211 |
+
observation_space: gym.spaces.Space,
|
212 |
+
action_space: gym.spaces.Space,
|
213 |
+
lr_schedule: Schedule,
|
214 |
+
net_arch: Optional[List[int]] = None,
|
215 |
+
activation_fn: Type[nn.Module] = nn.ReLU,
|
216 |
+
features_extractor_class: Type[BaseFeaturesExtractor] = NatureCNN,
|
217 |
+
features_extractor_kwargs: Optional[Dict[str, Any]] = None,
|
218 |
+
normalize_images: bool = True,
|
219 |
+
optimizer_class: Type[th.optim.Optimizer] = th.optim.Adam,
|
220 |
+
optimizer_kwargs: Optional[Dict[str, Any]] = None,
|
221 |
+
):
|
222 |
+
super(CnnPolicy, self).__init__(
|
223 |
+
observation_space,
|
224 |
+
action_space,
|
225 |
+
lr_schedule,
|
226 |
+
net_arch,
|
227 |
+
activation_fn,
|
228 |
+
features_extractor_class,
|
229 |
+
features_extractor_kwargs,
|
230 |
+
normalize_images,
|
231 |
+
optimizer_class,
|
232 |
+
optimizer_kwargs,
|
233 |
+
)
|
234 |
+
|
235 |
+
|
236 |
+
register_policy("MlpPolicy", MlpPolicy)
|
237 |
+
register_policy("CnnPolicy", CnnPolicy)
|
crazy_functions/test_project/python/dqn/来源
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
github stablebaseline3
|
2 |
+
https://github.com/DLR-RM/stable-baselines3
|
crazy_functions/test_project/其他测试
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"In practice, we found that a high-entropy initial state is more likely to increase the speed of training.
|
2 |
+
The entropy is calculated by:
|
3 |
+
$$H=-\sum_{k= 1}^{n_k} p(k) \cdot \log p(k), p(k)=\frac{|A_k|}{|\mathcal{A}|}$$
|
4 |
+
where $H$ is the entropy, $|A_k|$ is the number of agent nodes in $k$-th cluster, $|\mathcal{A}|$ is the total number of agents.
|
5 |
+
To ensure the Cooperation Graph initialization has higher entropy,
|
6 |
+
we will randomly generate multiple initial states,
|
7 |
+
rank by their entropy and then pick the one with maximum $H$."
|
8 |
+
|
9 |
+
```
|
10 |
+
FROM ubuntu:latest
|
11 |
+
|
12 |
+
RUN apt-get update && \
|
13 |
+
apt-get install -y python3 python3-pip && \
|
14 |
+
rm -rf /var/lib/apt/lists/*
|
15 |
+
|
16 |
+
RUN echo '[global]' > /etc/pip.conf && \
|
17 |
+
echo 'index-url = https://mirrors.aliyun.com/pypi/simple/' >> /etc/pip.conf && \
|
18 |
+
echo 'trusted-host = mirrors.aliyun.com' >> /etc/pip.conf
|
19 |
+
|
20 |
+
RUN pip3 install gradio requests[socks] mdtex2html
|
21 |
+
|
22 |
+
COPY . /gpt
|
23 |
+
WORKDIR /gpt
|
24 |
+
|
25 |
+
|
26 |
+
CMD ["python3", "main.py"]
|
27 |
+
```
|
crazy_functions/下载arxiv论文翻译摘要.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file, get_conf
|
3 |
+
import re, requests, unicodedata, os
|
4 |
+
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
5 |
+
def download_arxiv_(url_pdf):
|
6 |
+
if 'arxiv.org' not in url_pdf:
|
7 |
+
if ('.' in url_pdf) and ('/' not in url_pdf):
|
8 |
+
new_url = 'https://arxiv.org/abs/'+url_pdf
|
9 |
+
print('下载编号:', url_pdf, '自动定位:', new_url)
|
10 |
+
# download_arxiv_(new_url)
|
11 |
+
return download_arxiv_(new_url)
|
12 |
+
else:
|
13 |
+
print('不能识别的URL!')
|
14 |
+
return None
|
15 |
+
if 'abs' in url_pdf:
|
16 |
+
url_pdf = url_pdf.replace('abs', 'pdf')
|
17 |
+
url_pdf = url_pdf + '.pdf'
|
18 |
+
|
19 |
+
url_abs = url_pdf.replace('.pdf', '').replace('pdf', 'abs')
|
20 |
+
title, other_info = get_name(_url_=url_abs)
|
21 |
+
|
22 |
+
paper_id = title.split()[0] # '[1712.00559]'
|
23 |
+
if '2' in other_info['year']:
|
24 |
+
title = other_info['year'] + ' ' + title
|
25 |
+
|
26 |
+
known_conf = ['NeurIPS', 'NIPS', 'Nature', 'Science', 'ICLR', 'AAAI']
|
27 |
+
for k in known_conf:
|
28 |
+
if k in other_info['comment']:
|
29 |
+
title = k + ' ' + title
|
30 |
+
|
31 |
+
download_dir = './gpt_log/arxiv/'
|
32 |
+
os.makedirs(download_dir, exist_ok=True)
|
33 |
+
|
34 |
+
title_str = title.replace('?', '?')\
|
35 |
+
.replace(':', ':')\
|
36 |
+
.replace('\"', '“')\
|
37 |
+
.replace('\n', '')\
|
38 |
+
.replace(' ', ' ')\
|
39 |
+
.replace(' ', ' ')
|
40 |
+
|
41 |
+
requests_pdf_url = url_pdf
|
42 |
+
file_path = download_dir+title_str
|
43 |
+
# if os.path.exists(file_path):
|
44 |
+
# print('返回缓存文件')
|
45 |
+
# return './gpt_log/arxiv/'+title_str
|
46 |
+
|
47 |
+
print('下载中')
|
48 |
+
proxies, = get_conf('proxies')
|
49 |
+
r = requests.get(requests_pdf_url, proxies=proxies)
|
50 |
+
with open(file_path, 'wb+') as f:
|
51 |
+
f.write(r.content)
|
52 |
+
print('下载完成')
|
53 |
+
|
54 |
+
# print('输出下载命令:','aria2c -o \"%s\" %s'%(title_str,url_pdf))
|
55 |
+
# subprocess.call('aria2c --all-proxy=\"172.18.116.150:11084\" -o \"%s\" %s'%(download_dir+title_str,url_pdf), shell=True)
|
56 |
+
|
57 |
+
x = "%s %s %s.bib" % (paper_id, other_info['year'], other_info['authors'])
|
58 |
+
x = x.replace('?', '?')\
|
59 |
+
.replace(':', ':')\
|
60 |
+
.replace('\"', '“')\
|
61 |
+
.replace('\n', '')\
|
62 |
+
.replace(' ', ' ')\
|
63 |
+
.replace(' ', ' ')
|
64 |
+
return './gpt_log/arxiv/'+title_str, other_info
|
65 |
+
|
66 |
+
|
67 |
+
def get_name(_url_):
|
68 |
+
import os
|
69 |
+
from bs4 import BeautifulSoup
|
70 |
+
print('正在获取文献名!')
|
71 |
+
print(_url_)
|
72 |
+
|
73 |
+
# arxiv_recall = {}
|
74 |
+
# if os.path.exists('./arxiv_recall.pkl'):
|
75 |
+
# with open('./arxiv_recall.pkl', 'rb') as f:
|
76 |
+
# arxiv_recall = pickle.load(f)
|
77 |
+
|
78 |
+
# if _url_ in arxiv_recall:
|
79 |
+
# print('在缓存中')
|
80 |
+
# return arxiv_recall[_url_]
|
81 |
+
|
82 |
+
proxies, = get_conf('proxies')
|
83 |
+
res = requests.get(_url_, proxies=proxies)
|
84 |
+
|
85 |
+
bs = BeautifulSoup(res.text, 'html.parser')
|
86 |
+
other_details = {}
|
87 |
+
|
88 |
+
# get year
|
89 |
+
try:
|
90 |
+
year = bs.find_all(class_='dateline')[0].text
|
91 |
+
year = re.search(r'(\d{4})', year, re.M | re.I).group(1)
|
92 |
+
other_details['year'] = year
|
93 |
+
abstract = bs.find_all(class_='abstract mathjax')[0].text
|
94 |
+
other_details['abstract'] = abstract
|
95 |
+
except:
|
96 |
+
other_details['year'] = ''
|
97 |
+
print('年份获取失败')
|
98 |
+
|
99 |
+
# get author
|
100 |
+
try:
|
101 |
+
authors = bs.find_all(class_='authors')[0].text
|
102 |
+
authors = authors.split('Authors:')[1]
|
103 |
+
other_details['authors'] = authors
|
104 |
+
except:
|
105 |
+
other_details['authors'] = ''
|
106 |
+
print('authors获取失败')
|
107 |
+
|
108 |
+
# get comment
|
109 |
+
try:
|
110 |
+
comment = bs.find_all(class_='metatable')[0].text
|
111 |
+
real_comment = None
|
112 |
+
for item in comment.replace('\n', ' ').split(' '):
|
113 |
+
if 'Comments' in item:
|
114 |
+
real_comment = item
|
115 |
+
if real_comment is not None:
|
116 |
+
other_details['comment'] = real_comment
|
117 |
+
else:
|
118 |
+
other_details['comment'] = ''
|
119 |
+
except:
|
120 |
+
other_details['comment'] = ''
|
121 |
+
print('年份获取失败')
|
122 |
+
|
123 |
+
title_str = BeautifulSoup(
|
124 |
+
res.text, 'html.parser').find('title').contents[0]
|
125 |
+
print('获取成功:', title_str)
|
126 |
+
# arxiv_recall[_url_] = (title_str+'.pdf', other_details)
|
127 |
+
# with open('./arxiv_recall.pkl', 'wb') as f:
|
128 |
+
# pickle.dump(arxiv_recall, f)
|
129 |
+
|
130 |
+
return title_str+'.pdf', other_details
|
131 |
+
|
132 |
+
|
133 |
+
|
134 |
+
@CatchException
|
135 |
+
def 下载arxiv论文并翻译摘要(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
136 |
+
|
137 |
+
CRAZY_FUNCTION_INFO = "下载arxiv论文并翻译摘要,函数插件作者[binary-husky]。正在提取摘要并下载PDF文档……"
|
138 |
+
import glob
|
139 |
+
import os
|
140 |
+
|
141 |
+
# 基本信息:功能、贡献者
|
142 |
+
chatbot.append(["函数插件功能?", CRAZY_FUNCTION_INFO])
|
143 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
144 |
+
|
145 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
146 |
+
try:
|
147 |
+
import pdfminer, bs4
|
148 |
+
except:
|
149 |
+
report_execption(chatbot, history,
|
150 |
+
a = f"解析项目: {txt}",
|
151 |
+
b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pdfminer beautifulsoup4```。")
|
152 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
153 |
+
return
|
154 |
+
|
155 |
+
# 清空历史,以免输入溢出
|
156 |
+
history = []
|
157 |
+
|
158 |
+
# 提取摘要,下载PDF文档
|
159 |
+
try:
|
160 |
+
pdf_path, info = download_arxiv_(txt)
|
161 |
+
except:
|
162 |
+
report_execption(chatbot, history,
|
163 |
+
a = f"解析项目: {txt}",
|
164 |
+
b = f"下载pdf文件未成功")
|
165 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
166 |
+
return
|
167 |
+
|
168 |
+
# 翻译摘要等
|
169 |
+
i_say = f"请你阅读以下学术论文相关的材料,提取摘要,翻译为中文。材料如下:{str(info)}"
|
170 |
+
i_say_show_user = f'请你阅读以下学术论文相关的材料,提取摘要,翻译为中文。论文:{pdf_path}'
|
171 |
+
chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
|
172 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
173 |
+
msg = '正常'
|
174 |
+
# ** gpt request **
|
175 |
+
# 单线,获取文章meta信息
|
176 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
177 |
+
inputs=i_say,
|
178 |
+
inputs_show_user=i_say_show_user,
|
179 |
+
llm_kwargs=llm_kwargs,
|
180 |
+
chatbot=chatbot, history=[],
|
181 |
+
sys_prompt="Your job is to collect information from materials and translate to Chinese。",
|
182 |
+
)
|
183 |
+
|
184 |
+
chatbot[-1] = (i_say_show_user, gpt_say)
|
185 |
+
history.append(i_say_show_user); history.append(gpt_say)
|
186 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
187 |
+
# 写入文件
|
188 |
+
import shutil
|
189 |
+
# 重置文件的创建时间
|
190 |
+
shutil.copyfile(pdf_path, f'./gpt_log/{os.path.basename(pdf_path)}'); os.remove(pdf_path)
|
191 |
+
res = write_results_to_file(history)
|
192 |
+
chatbot.append(("完成了吗?", res + "\n\nPDF文件也已经下载"))
|
193 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
194 |
+
|
crazy_functions/代码重写为全英文_多线程.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import threading
|
2 |
+
from request_llm.bridge_all import predict_no_ui_long_connection
|
3 |
+
from toolbox import update_ui
|
4 |
+
from toolbox import CatchException, write_results_to_file, report_execption
|
5 |
+
from .crazy_utils import breakdown_txt_to_satisfy_token_limit
|
6 |
+
|
7 |
+
def extract_code_block_carefully(txt):
|
8 |
+
splitted = txt.split('```')
|
9 |
+
n_code_block_seg = len(splitted) - 1
|
10 |
+
if n_code_block_seg <= 1: return txt
|
11 |
+
# 剩下的情况都开头除去 ``` 结尾除去一次 ```
|
12 |
+
txt_out = '```'.join(splitted[1:-1])
|
13 |
+
return txt_out
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
def break_txt_into_half_at_some_linebreak(txt):
|
18 |
+
lines = txt.split('\n')
|
19 |
+
n_lines = len(lines)
|
20 |
+
pre = lines[:(n_lines//2)]
|
21 |
+
post = lines[(n_lines//2):]
|
22 |
+
return "\n".join(pre), "\n".join(post)
|
23 |
+
|
24 |
+
|
25 |
+
@CatchException
|
26 |
+
def 全项目切换英文(txt, llm_kwargs, plugin_kwargs, chatbot, history, sys_prompt, web_port):
|
27 |
+
# 第1步:清空历史,以免输入溢出
|
28 |
+
history = []
|
29 |
+
|
30 |
+
# 第2步:尝试导入依赖,如果缺少依赖,则给出安装建议
|
31 |
+
try:
|
32 |
+
import tiktoken
|
33 |
+
except:
|
34 |
+
report_execption(chatbot, history,
|
35 |
+
a = f"解析项目: {txt}",
|
36 |
+
b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
37 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
38 |
+
return
|
39 |
+
|
40 |
+
# 第3步:集合文件
|
41 |
+
import time, glob, os, shutil, re
|
42 |
+
os.makedirs('gpt_log/generated_english_version', exist_ok=True)
|
43 |
+
os.makedirs('gpt_log/generated_english_version/crazy_functions', exist_ok=True)
|
44 |
+
file_manifest = [f for f in glob.glob('./*.py') if ('test_project' not in f) and ('gpt_log' not in f)] + \
|
45 |
+
[f for f in glob.glob('./crazy_functions/*.py') if ('test_project' not in f) and ('gpt_log' not in f)]
|
46 |
+
# file_manifest = ['./toolbox.py']
|
47 |
+
i_say_show_user_buffer = []
|
48 |
+
|
49 |
+
# 第4步:随便显示点什么防止卡顿的感觉
|
50 |
+
for index, fp in enumerate(file_manifest):
|
51 |
+
# if 'test_project' in fp: continue
|
52 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
53 |
+
file_content = f.read()
|
54 |
+
i_say_show_user =f'[{index}/{len(file_manifest)}] 接下来请将以下代码中包含的所有中文转化为英文,只输出转化后的英文代码,请用代码块输出代码: {os.path.abspath(fp)}'
|
55 |
+
i_say_show_user_buffer.append(i_say_show_user)
|
56 |
+
chatbot.append((i_say_show_user, "[Local Message] 等待多线程操作,中间过程不予显示."))
|
57 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
58 |
+
|
59 |
+
|
60 |
+
# 第5步:Token限制下的截断与处理
|
61 |
+
MAX_TOKEN = 3000
|
62 |
+
from request_llm.bridge_all import model_info
|
63 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
64 |
+
def get_token_fn(txt): return len(enc.encode(txt, disallowed_special=()))
|
65 |
+
|
66 |
+
|
67 |
+
# 第6步:任务函数
|
68 |
+
mutable_return = [None for _ in file_manifest]
|
69 |
+
observe_window = [[""] for _ in file_manifest]
|
70 |
+
def thread_worker(fp,index):
|
71 |
+
if index > 10:
|
72 |
+
time.sleep(60)
|
73 |
+
print('Openai 限制免费用户每分钟20次请求,降低请求频率中。')
|
74 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
75 |
+
file_content = f.read()
|
76 |
+
i_say_template = lambda fp, file_content: f'接下来请将以下代码中包含的所有中文转化为英文,只输出代码,文件名是{fp},文件代码是 ```{file_content}```'
|
77 |
+
try:
|
78 |
+
gpt_say = ""
|
79 |
+
# 分解代码文件
|
80 |
+
file_content_breakdown = breakdown_txt_to_satisfy_token_limit(file_content, get_token_fn, MAX_TOKEN)
|
81 |
+
for file_content_partial in file_content_breakdown:
|
82 |
+
i_say = i_say_template(fp, file_content_partial)
|
83 |
+
# # ** gpt request **
|
84 |
+
gpt_say_partial = predict_no_ui_long_connection(inputs=i_say, llm_kwargs=llm_kwargs, history=[], sys_prompt=sys_prompt, observe_window=observe_window[index])
|
85 |
+
gpt_say_partial = extract_code_block_carefully(gpt_say_partial)
|
86 |
+
gpt_say += gpt_say_partial
|
87 |
+
mutable_return[index] = gpt_say
|
88 |
+
except ConnectionAbortedError as token_exceed_err:
|
89 |
+
print('至少一个线程任务Token溢出而失败', e)
|
90 |
+
except Exception as e:
|
91 |
+
print('至少一个线程任务意外失败', e)
|
92 |
+
|
93 |
+
# 第7步:所有线程同时开始执行任务函数
|
94 |
+
handles = [threading.Thread(target=thread_worker, args=(fp,index)) for index, fp in enumerate(file_manifest)]
|
95 |
+
for h in handles:
|
96 |
+
h.daemon = True
|
97 |
+
h.start()
|
98 |
+
chatbot.append(('开始了吗?', f'多线程操作已经开始'))
|
99 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
100 |
+
|
101 |
+
# 第8步:循环轮询各个线程是否执行完毕
|
102 |
+
cnt = 0
|
103 |
+
while True:
|
104 |
+
cnt += 1
|
105 |
+
time.sleep(0.2)
|
106 |
+
th_alive = [h.is_alive() for h in handles]
|
107 |
+
if not any(th_alive): break
|
108 |
+
# 更好��UI视觉效果
|
109 |
+
observe_win = []
|
110 |
+
for thread_index, alive in enumerate(th_alive):
|
111 |
+
observe_win.append("[ ..."+observe_window[thread_index][0][-60:].replace('\n','').replace('```','...').replace(' ','.').replace('<br/>','.....').replace('$','.')+"... ]")
|
112 |
+
stat = [f'执行中: {obs}\n\n' if alive else '已完成\n\n' for alive, obs in zip(th_alive, observe_win)]
|
113 |
+
stat_str = ''.join(stat)
|
114 |
+
chatbot[-1] = (chatbot[-1][0], f'多线程操作已经开始,完成情况: \n\n{stat_str}' + ''.join(['.']*(cnt%10+1)))
|
115 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
116 |
+
|
117 |
+
# 第9步:把结果写入文件
|
118 |
+
for index, h in enumerate(handles):
|
119 |
+
h.join() # 这里其实不需要join了,肯定已经都结束了
|
120 |
+
fp = file_manifest[index]
|
121 |
+
gpt_say = mutable_return[index]
|
122 |
+
i_say_show_user = i_say_show_user_buffer[index]
|
123 |
+
|
124 |
+
where_to_relocate = f'gpt_log/generated_english_version/{fp}'
|
125 |
+
if gpt_say is not None:
|
126 |
+
with open(where_to_relocate, 'w+', encoding='utf-8') as f:
|
127 |
+
f.write(gpt_say)
|
128 |
+
else: # 失败
|
129 |
+
shutil.copyfile(file_manifest[index], where_to_relocate)
|
130 |
+
chatbot.append((i_say_show_user, f'[Local Message] 已完成{os.path.abspath(fp)}的转化,\n\n存入{os.path.abspath(where_to_relocate)}'))
|
131 |
+
history.append(i_say_show_user); history.append(gpt_say)
|
132 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
133 |
+
time.sleep(1)
|
134 |
+
|
135 |
+
# 第10步:备份一个文件
|
136 |
+
res = write_results_to_file(history)
|
137 |
+
chatbot.append(("生成一份任务执行报告", res))
|
138 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
crazy_functions/总结word文档.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
4 |
+
fast_debug = False
|
5 |
+
|
6 |
+
|
7 |
+
def 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt):
|
8 |
+
import time, os
|
9 |
+
# pip install python-docx 用于docx格式,跨平台
|
10 |
+
# pip install pywin32 用于doc格式,仅支持Win平台
|
11 |
+
for index, fp in enumerate(file_manifest):
|
12 |
+
if fp.split(".")[-1] == "docx":
|
13 |
+
from docx import Document
|
14 |
+
doc = Document(fp)
|
15 |
+
file_content = "\n".join([para.text for para in doc.paragraphs])
|
16 |
+
else:
|
17 |
+
import win32com.client
|
18 |
+
word = win32com.client.Dispatch("Word.Application")
|
19 |
+
word.visible = False
|
20 |
+
# 打开文件
|
21 |
+
print('fp', os.getcwd())
|
22 |
+
doc = word.Documents.Open(os.getcwd() + '/' + fp)
|
23 |
+
# file_content = doc.Content.Text
|
24 |
+
doc = word.ActiveDocument
|
25 |
+
file_content = doc.Range().Text
|
26 |
+
doc.Close()
|
27 |
+
word.Quit()
|
28 |
+
|
29 |
+
print(file_content)
|
30 |
+
# private_upload里面的文件名在解压zip后容易出现乱码(rar和7z格式正常),故可以只分析文章内容,不输入文件名
|
31 |
+
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
32 |
+
from request_llm.bridge_all import model_info
|
33 |
+
max_token = model_info[llm_kwargs['llm_model']]['max_token']
|
34 |
+
TOKEN_LIMIT_PER_FRAGMENT = max_token * 3 // 4
|
35 |
+
paper_fragments = breakdown_txt_to_satisfy_token_limit_for_pdf(
|
36 |
+
txt=file_content,
|
37 |
+
get_token_fn=model_info[llm_kwargs['llm_model']]['token_cnt'],
|
38 |
+
limit=TOKEN_LIMIT_PER_FRAGMENT
|
39 |
+
)
|
40 |
+
this_paper_history = []
|
41 |
+
for i, paper_frag in enumerate(paper_fragments):
|
42 |
+
i_say = f'请对下面的文章片段用中文做概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{paper_frag}```'
|
43 |
+
i_say_show_user = f'请对下面的文章片段做概述: {os.path.abspath(fp)}的第{i+1}/{len(paper_fragments)}个片段。'
|
44 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
45 |
+
inputs=i_say,
|
46 |
+
inputs_show_user=i_say_show_user,
|
47 |
+
llm_kwargs=llm_kwargs,
|
48 |
+
chatbot=chatbot,
|
49 |
+
history=[],
|
50 |
+
sys_prompt="总结文章。"
|
51 |
+
)
|
52 |
+
|
53 |
+
chatbot[-1] = (i_say_show_user, gpt_say)
|
54 |
+
history.extend([i_say_show_user,gpt_say])
|
55 |
+
this_paper_history.extend([i_say_show_user,gpt_say])
|
56 |
+
|
57 |
+
# 已经对该文章的所有片段总结完毕,如果文章被切分了,
|
58 |
+
if len(paper_fragments) > 1:
|
59 |
+
i_say = f"根据以上的对话,总结文章{os.path.abspath(fp)}的主要内容。"
|
60 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
61 |
+
inputs=i_say,
|
62 |
+
inputs_show_user=i_say,
|
63 |
+
llm_kwargs=llm_kwargs,
|
64 |
+
chatbot=chatbot,
|
65 |
+
history=this_paper_history,
|
66 |
+
sys_prompt="总结文章。"
|
67 |
+
)
|
68 |
+
|
69 |
+
history.extend([i_say,gpt_say])
|
70 |
+
this_paper_history.extend([i_say,gpt_say])
|
71 |
+
|
72 |
+
res = write_results_to_file(history)
|
73 |
+
chatbot.append(("完成了吗?", res))
|
74 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
75 |
+
|
76 |
+
res = write_results_to_file(history)
|
77 |
+
chatbot.append(("所有文件都总结完成了吗?", res))
|
78 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
79 |
+
|
80 |
+
|
81 |
+
@CatchException
|
82 |
+
def 总结word文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
83 |
+
import glob, os
|
84 |
+
|
85 |
+
# 基本信息:功能、贡献者
|
86 |
+
chatbot.append([
|
87 |
+
"函数插件功能?",
|
88 |
+
"批量总结Word文档。函数插件贡献者: JasonGuo1"])
|
89 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
90 |
+
|
91 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
92 |
+
try:
|
93 |
+
from docx import Document
|
94 |
+
except:
|
95 |
+
report_execption(chatbot, history,
|
96 |
+
a=f"解析项目: {txt}",
|
97 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade python-docx pywin32```。")
|
98 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
99 |
+
return
|
100 |
+
|
101 |
+
# 清空历史,以免输入溢出
|
102 |
+
history = []
|
103 |
+
|
104 |
+
# 检测输入参数,如没有给定输入参数,直接退出
|
105 |
+
if os.path.exists(txt):
|
106 |
+
project_folder = txt
|
107 |
+
else:
|
108 |
+
if txt == "": txt = '空空如也的输入栏'
|
109 |
+
report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到本地项目或无权访问: {txt}")
|
110 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
111 |
+
return
|
112 |
+
|
113 |
+
# 搜索需要处理的文件清单
|
114 |
+
if txt.endswith('.docx') or txt.endswith('.doc'):
|
115 |
+
file_manifest = [txt]
|
116 |
+
else:
|
117 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.docx', recursive=True)] + \
|
118 |
+
[f for f in glob.glob(f'{project_folder}/**/*.doc', recursive=True)]
|
119 |
+
|
120 |
+
# 如果没找到任何文件
|
121 |
+
if len(file_manifest) == 0:
|
122 |
+
report_execption(chatbot, history, a=f"解析项目: {txt}", b=f"找不到任何.docx或doc文件: {txt}")
|
123 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
124 |
+
return
|
125 |
+
|
126 |
+
# 开始正式执行任务
|
127 |
+
yield from 解析docx(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
|
crazy_functions/批量Markdown翻译.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
fast_debug = False
|
4 |
+
|
5 |
+
class PaperFileGroup():
|
6 |
+
def __init__(self):
|
7 |
+
self.file_paths = []
|
8 |
+
self.file_contents = []
|
9 |
+
self.sp_file_contents = []
|
10 |
+
self.sp_file_index = []
|
11 |
+
self.sp_file_tag = []
|
12 |
+
|
13 |
+
# count_token
|
14 |
+
from request_llm.bridge_all import model_info
|
15 |
+
enc = model_info["gpt-3.5-turbo"]['tokenizer']
|
16 |
+
def get_token_num(txt): return len(enc.encode(txt, disallowed_special=()))
|
17 |
+
self.get_token_num = get_token_num
|
18 |
+
|
19 |
+
def run_file_split(self, max_token_limit=1900):
|
20 |
+
"""
|
21 |
+
将长文本分离开来
|
22 |
+
"""
|
23 |
+
for index, file_content in enumerate(self.file_contents):
|
24 |
+
if self.get_token_num(file_content) < max_token_limit:
|
25 |
+
self.sp_file_contents.append(file_content)
|
26 |
+
self.sp_file_index.append(index)
|
27 |
+
self.sp_file_tag.append(self.file_paths[index])
|
28 |
+
else:
|
29 |
+
from .crazy_utils import breakdown_txt_to_satisfy_token_limit_for_pdf
|
30 |
+
segments = breakdown_txt_to_satisfy_token_limit_for_pdf(file_content, self.get_token_num, max_token_limit)
|
31 |
+
for j, segment in enumerate(segments):
|
32 |
+
self.sp_file_contents.append(segment)
|
33 |
+
self.sp_file_index.append(index)
|
34 |
+
self.sp_file_tag.append(self.file_paths[index] + f".part-{j}.md")
|
35 |
+
|
36 |
+
print('Segmentation: done')
|
37 |
+
|
38 |
+
def 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en'):
|
39 |
+
import time, os, re
|
40 |
+
from .crazy_utils import request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency
|
41 |
+
|
42 |
+
# <-------- 读取Markdown文件,删除其中的所有注释 ---------->
|
43 |
+
pfg = PaperFileGroup()
|
44 |
+
|
45 |
+
for index, fp in enumerate(file_manifest):
|
46 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
47 |
+
file_content = f.read()
|
48 |
+
# 记录删除注释后的文本
|
49 |
+
pfg.file_paths.append(fp)
|
50 |
+
pfg.file_contents.append(file_content)
|
51 |
+
|
52 |
+
# <-------- 拆分过长的Markdown文件 ---------->
|
53 |
+
pfg.run_file_split(max_token_limit=1500)
|
54 |
+
n_split = len(pfg.sp_file_contents)
|
55 |
+
|
56 |
+
# <-------- 多线程润色开始 ---------->
|
57 |
+
if language == 'en->zh':
|
58 |
+
inputs_array = ["This is a Markdown file, translate it into Chinese, do not modify any existing Markdown commands:" +
|
59 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
60 |
+
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
|
61 |
+
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
|
62 |
+
elif language == 'zh->en':
|
63 |
+
inputs_array = [f"This is a Markdown file, translate it into English, do not modify any existing Markdown commands:" +
|
64 |
+
f"\n\n{frag}" for frag in pfg.sp_file_contents]
|
65 |
+
inputs_show_user_array = [f"翻译 {f}" for f in pfg.sp_file_tag]
|
66 |
+
sys_prompt_array = ["You are a professional academic paper translator." for _ in range(n_split)]
|
67 |
+
|
68 |
+
gpt_response_collection = yield from request_gpt_model_multi_threads_with_very_awesome_ui_and_high_efficiency(
|
69 |
+
inputs_array=inputs_array,
|
70 |
+
inputs_show_user_array=inputs_show_user_array,
|
71 |
+
llm_kwargs=llm_kwargs,
|
72 |
+
chatbot=chatbot,
|
73 |
+
history_array=[[""] for _ in range(n_split)],
|
74 |
+
sys_prompt_array=sys_prompt_array,
|
75 |
+
# max_workers=5, # OpenAI所允许的最大并行过载
|
76 |
+
scroller_max_len = 80
|
77 |
+
)
|
78 |
+
|
79 |
+
# <-------- 整理结果,退出 ---------->
|
80 |
+
create_report_file_name = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime()) + f"-chatgpt.polish.md"
|
81 |
+
res = write_results_to_file(gpt_response_collection, file_name=create_report_file_name)
|
82 |
+
history = gpt_response_collection
|
83 |
+
chatbot.append((f"{fp}完成了吗?", res))
|
84 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
85 |
+
|
86 |
+
|
87 |
+
|
88 |
+
|
89 |
+
|
90 |
+
@CatchException
|
91 |
+
def Markdown英译中(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
92 |
+
# 基本信息:功能、贡献者
|
93 |
+
chatbot.append([
|
94 |
+
"函数插件功能?",
|
95 |
+
"对整个Markdown项目进行翻译。函数插件贡献者: Binary-Husky"])
|
96 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
97 |
+
|
98 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
99 |
+
try:
|
100 |
+
import tiktoken
|
101 |
+
except:
|
102 |
+
report_execption(chatbot, history,
|
103 |
+
a=f"解析项目: {txt}",
|
104 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
105 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
106 |
+
return
|
107 |
+
history = [] # 清空历史,以免输入溢出
|
108 |
+
import glob, os
|
109 |
+
if os.path.exists(txt):
|
110 |
+
project_folder = txt
|
111 |
+
else:
|
112 |
+
if txt == "": txt = '空空如也的输入栏'
|
113 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
114 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
115 |
+
return
|
116 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.md', recursive=True)]
|
117 |
+
if len(file_manifest) == 0:
|
118 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.md文件: {txt}")
|
119 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
120 |
+
return
|
121 |
+
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='en->zh')
|
122 |
+
|
123 |
+
|
124 |
+
|
125 |
+
|
126 |
+
|
127 |
+
@CatchException
|
128 |
+
def Markdown中译英(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
129 |
+
# 基本信息:功能、贡献者
|
130 |
+
chatbot.append([
|
131 |
+
"函数插件功能?",
|
132 |
+
"对整个Markdown项目进行翻译。函数插件贡献者: Binary-Husky"])
|
133 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
134 |
+
|
135 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
136 |
+
try:
|
137 |
+
import tiktoken
|
138 |
+
except:
|
139 |
+
report_execption(chatbot, history,
|
140 |
+
a=f"解析项目: {txt}",
|
141 |
+
b=f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade tiktoken```。")
|
142 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
143 |
+
return
|
144 |
+
history = [] # 清空历史,以免输入溢出
|
145 |
+
import glob, os
|
146 |
+
if os.path.exists(txt):
|
147 |
+
project_folder = txt
|
148 |
+
else:
|
149 |
+
if txt == "": txt = '空空如也的输入栏'
|
150 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
151 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
152 |
+
return
|
153 |
+
if txt.endswith('.md'):
|
154 |
+
file_manifest = [txt]
|
155 |
+
else:
|
156 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.md', recursive=True)]
|
157 |
+
if len(file_manifest) == 0:
|
158 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.md文件: {txt}")
|
159 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
160 |
+
return
|
161 |
+
yield from 多文件翻译(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, language='zh->en')
|
crazy_functions/批量总结PDF文档.py
ADDED
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
import re
|
4 |
+
import unicodedata
|
5 |
+
fast_debug = False
|
6 |
+
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
7 |
+
|
8 |
+
def is_paragraph_break(match):
|
9 |
+
"""
|
10 |
+
根据给定的匹配结果来判断换行符是否表示段落分隔。
|
11 |
+
如果换行符前为句子结束标志(句号,感叹号,问号),且下一个字符为大写字母,则换行符更有可能表示段落分隔。
|
12 |
+
也可以根据之前的内容长度来判断段落是否已经足够长。
|
13 |
+
"""
|
14 |
+
prev_char, next_char = match.groups()
|
15 |
+
|
16 |
+
# 句子结束标志
|
17 |
+
sentence_endings = ".!?"
|
18 |
+
|
19 |
+
# 设定一个最小段落长度阈值
|
20 |
+
min_paragraph_length = 140
|
21 |
+
|
22 |
+
if prev_char in sentence_endings and next_char.isupper() and len(match.string[:match.start(1)]) > min_paragraph_length:
|
23 |
+
return "\n\n"
|
24 |
+
else:
|
25 |
+
return " "
|
26 |
+
|
27 |
+
def normalize_text(text):
|
28 |
+
"""
|
29 |
+
通过把连字(ligatures)等文本特殊符号转换为其基本形式来对文本进行归一化处理。
|
30 |
+
例如,将连字 "fi" 转换为 "f" 和 "i"。
|
31 |
+
"""
|
32 |
+
# 对文本进行归一化处理,分解连字
|
33 |
+
normalized_text = unicodedata.normalize("NFKD", text)
|
34 |
+
|
35 |
+
# 替换其他特殊字符
|
36 |
+
cleaned_text = re.sub(r'[^\x00-\x7F]+', '', normalized_text)
|
37 |
+
|
38 |
+
return cleaned_text
|
39 |
+
|
40 |
+
def clean_text(raw_text):
|
41 |
+
"""
|
42 |
+
对从 PDF 提取出的原始文本进行清洗和格式化处理。
|
43 |
+
1. 对原始文本进行归一化处理。
|
44 |
+
2. 替换跨行的连词,例如 “Espe-\ncially” 转换为 “Especially”。
|
45 |
+
3. 根据 heuristic 规则判断换行符是否是段落分隔,并相应地进行替换。
|
46 |
+
"""
|
47 |
+
# 对文本进行归一化处理
|
48 |
+
normalized_text = normalize_text(raw_text)
|
49 |
+
|
50 |
+
# 替换跨行的连词
|
51 |
+
text = re.sub(r'(\w+-\n\w+)', lambda m: m.group(1).replace('-\n', ''), normalized_text)
|
52 |
+
|
53 |
+
# 根据前后相邻字符的特点,找到原文本中的换行符
|
54 |
+
newlines = re.compile(r'(\S)\n(\S)')
|
55 |
+
|
56 |
+
# 根据 heuristic 规则,用空格或段落分隔符替换原换行符
|
57 |
+
final_text = re.sub(newlines, lambda m: m.group(1) + is_paragraph_break(m) + m.group(2), text)
|
58 |
+
|
59 |
+
return final_text.strip()
|
60 |
+
|
61 |
+
def 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt):
|
62 |
+
import time, glob, os, fitz
|
63 |
+
print('begin analysis on:', file_manifest)
|
64 |
+
for index, fp in enumerate(file_manifest):
|
65 |
+
with fitz.open(fp) as doc:
|
66 |
+
file_content = ""
|
67 |
+
for page in doc:
|
68 |
+
file_content += page.get_text()
|
69 |
+
file_content = clean_text(file_content)
|
70 |
+
print(file_content)
|
71 |
+
|
72 |
+
prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else ""
|
73 |
+
i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```'
|
74 |
+
i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}'
|
75 |
+
chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
|
76 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
77 |
+
|
78 |
+
if not fast_debug:
|
79 |
+
msg = '正常'
|
80 |
+
# ** gpt request **
|
81 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
82 |
+
inputs=i_say,
|
83 |
+
inputs_show_user=i_say_show_user,
|
84 |
+
llm_kwargs=llm_kwargs,
|
85 |
+
chatbot=chatbot,
|
86 |
+
history=[],
|
87 |
+
sys_prompt="总结文章。"
|
88 |
+
) # 带超时倒计时
|
89 |
+
|
90 |
+
|
91 |
+
chatbot[-1] = (i_say_show_user, gpt_say)
|
92 |
+
history.append(i_say_show_user); history.append(gpt_say)
|
93 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
94 |
+
if not fast_debug: time.sleep(2)
|
95 |
+
|
96 |
+
all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)])
|
97 |
+
i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。'
|
98 |
+
chatbot.append((i_say, "[Local Message] waiting gpt response."))
|
99 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
100 |
+
|
101 |
+
if not fast_debug:
|
102 |
+
msg = '正常'
|
103 |
+
# ** gpt request **
|
104 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
105 |
+
inputs=i_say,
|
106 |
+
inputs_show_user=i_say,
|
107 |
+
llm_kwargs=llm_kwargs,
|
108 |
+
chatbot=chatbot,
|
109 |
+
history=history,
|
110 |
+
sys_prompt="总结文章。"
|
111 |
+
) # 带超时倒计时
|
112 |
+
|
113 |
+
chatbot[-1] = (i_say, gpt_say)
|
114 |
+
history.append(i_say); history.append(gpt_say)
|
115 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界���
|
116 |
+
res = write_results_to_file(history)
|
117 |
+
chatbot.append(("完成了吗?", res))
|
118 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
119 |
+
|
120 |
+
|
121 |
+
@CatchException
|
122 |
+
def 批量总结PDF文档(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
123 |
+
import glob, os
|
124 |
+
|
125 |
+
# 基本信息:功能、贡献者
|
126 |
+
chatbot.append([
|
127 |
+
"函数插件功能?",
|
128 |
+
"批量总结PDF文档。函数插件贡献者: ValeriaWong,Eralien"])
|
129 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
130 |
+
|
131 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
132 |
+
try:
|
133 |
+
import fitz
|
134 |
+
except:
|
135 |
+
report_execption(chatbot, history,
|
136 |
+
a = f"解析项目: {txt}",
|
137 |
+
b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pymupdf```。")
|
138 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
139 |
+
return
|
140 |
+
|
141 |
+
# 清空历史,以免输入溢出
|
142 |
+
history = []
|
143 |
+
|
144 |
+
# 检测输入参数,如没有给定输入参数,直接退出
|
145 |
+
if os.path.exists(txt):
|
146 |
+
project_folder = txt
|
147 |
+
else:
|
148 |
+
if txt == "": txt = '空空如也的输入栏'
|
149 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
150 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
151 |
+
return
|
152 |
+
|
153 |
+
# 搜索需要处理的文件清单
|
154 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \
|
155 |
+
# [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
|
156 |
+
# [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
|
157 |
+
# [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
|
158 |
+
|
159 |
+
# 如果没找到任何文件
|
160 |
+
if len(file_manifest) == 0:
|
161 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或.pdf文件: {txt}")
|
162 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
163 |
+
return
|
164 |
+
|
165 |
+
# 开始正式执行任务
|
166 |
+
yield from 解析PDF(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
|
crazy_functions/批量总结PDF文档pdfminer.py
ADDED
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from toolbox import update_ui
|
2 |
+
from toolbox import CatchException, report_execption, write_results_to_file
|
3 |
+
from .crazy_utils import request_gpt_model_in_new_thread_with_ui_alive
|
4 |
+
|
5 |
+
fast_debug = False
|
6 |
+
|
7 |
+
def readPdf(pdfPath):
|
8 |
+
"""
|
9 |
+
读取pdf文件,返回文本内容
|
10 |
+
"""
|
11 |
+
import pdfminer
|
12 |
+
from pdfminer.pdfparser import PDFParser
|
13 |
+
from pdfminer.pdfdocument import PDFDocument
|
14 |
+
from pdfminer.pdfpage import PDFPage, PDFTextExtractionNotAllowed
|
15 |
+
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
|
16 |
+
from pdfminer.pdfdevice import PDFDevice
|
17 |
+
from pdfminer.layout import LAParams
|
18 |
+
from pdfminer.converter import PDFPageAggregator
|
19 |
+
|
20 |
+
fp = open(pdfPath, 'rb')
|
21 |
+
|
22 |
+
# Create a PDF parser object associated with the file object
|
23 |
+
parser = PDFParser(fp)
|
24 |
+
|
25 |
+
# Create a PDF document object that stores the document structure.
|
26 |
+
# Password for initialization as 2nd parameter
|
27 |
+
document = PDFDocument(parser)
|
28 |
+
# Check if the document allows text extraction. If not, abort.
|
29 |
+
if not document.is_extractable:
|
30 |
+
raise PDFTextExtractionNotAllowed
|
31 |
+
|
32 |
+
# Create a PDF resource manager object that stores shared resources.
|
33 |
+
rsrcmgr = PDFResourceManager()
|
34 |
+
|
35 |
+
# Create a PDF device object.
|
36 |
+
# device = PDFDevice(rsrcmgr)
|
37 |
+
|
38 |
+
# BEGIN LAYOUT ANALYSIS.
|
39 |
+
# Set parameters for analysis.
|
40 |
+
laparams = LAParams(
|
41 |
+
char_margin=10.0,
|
42 |
+
line_margin=0.2,
|
43 |
+
boxes_flow=0.2,
|
44 |
+
all_texts=False,
|
45 |
+
)
|
46 |
+
# Create a PDF page aggregator object.
|
47 |
+
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
|
48 |
+
# Create a PDF interpreter object.
|
49 |
+
interpreter = PDFPageInterpreter(rsrcmgr, device)
|
50 |
+
|
51 |
+
# loop over all pages in the document
|
52 |
+
outTextList = []
|
53 |
+
for page in PDFPage.create_pages(document):
|
54 |
+
# read the page into a layout object
|
55 |
+
interpreter.process_page(page)
|
56 |
+
layout = device.get_result()
|
57 |
+
for obj in layout._objs:
|
58 |
+
if isinstance(obj, pdfminer.layout.LTTextBoxHorizontal):
|
59 |
+
# print(obj.get_text())
|
60 |
+
outTextList.append(obj.get_text())
|
61 |
+
|
62 |
+
return outTextList
|
63 |
+
|
64 |
+
|
65 |
+
def 解析Paper(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt):
|
66 |
+
import time, glob, os
|
67 |
+
from bs4 import BeautifulSoup
|
68 |
+
print('begin analysis on:', file_manifest)
|
69 |
+
for index, fp in enumerate(file_manifest):
|
70 |
+
if ".tex" in fp:
|
71 |
+
with open(fp, 'r', encoding='utf-8', errors='replace') as f:
|
72 |
+
file_content = f.read()
|
73 |
+
if ".pdf" in fp.lower():
|
74 |
+
file_content = readPdf(fp)
|
75 |
+
file_content = BeautifulSoup(''.join(file_content), features="lxml").body.text.encode('gbk', 'ignore').decode('gbk')
|
76 |
+
|
77 |
+
prefix = "接下来请你逐文件分析下面的论文文件,概括其内容" if index==0 else ""
|
78 |
+
i_say = prefix + f'请对下面的文章片段用中文做一个概述,文件名是{os.path.relpath(fp, project_folder)},文章内容是 ```{file_content}```'
|
79 |
+
i_say_show_user = prefix + f'[{index}/{len(file_manifest)}] 请对下面的文章片段做一个概述: {os.path.abspath(fp)}'
|
80 |
+
chatbot.append((i_say_show_user, "[Local Message] waiting gpt response."))
|
81 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
82 |
+
|
83 |
+
if not fast_debug:
|
84 |
+
msg = '正常'
|
85 |
+
# ** gpt request **
|
86 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
87 |
+
inputs=i_say,
|
88 |
+
inputs_show_user=i_say_show_user,
|
89 |
+
llm_kwargs=llm_kwargs,
|
90 |
+
chatbot=chatbot,
|
91 |
+
history=[],
|
92 |
+
sys_prompt="总结文章。"
|
93 |
+
) # 带超时倒计时
|
94 |
+
chatbot[-1] = (i_say_show_user, gpt_say)
|
95 |
+
history.append(i_say_show_user); history.append(gpt_say)
|
96 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
97 |
+
if not fast_debug: time.sleep(2)
|
98 |
+
|
99 |
+
all_file = ', '.join([os.path.relpath(fp, project_folder) for index, fp in enumerate(file_manifest)])
|
100 |
+
i_say = f'根据以上你自己的分析,对全文进行概括,用学术性语言写一段中文摘要,然后再写一段英文摘要(包括{all_file})。'
|
101 |
+
chatbot.append((i_say, "[Local Message] waiting gpt response."))
|
102 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
103 |
+
|
104 |
+
if not fast_debug:
|
105 |
+
msg = '正常'
|
106 |
+
# ** gpt request **
|
107 |
+
gpt_say = yield from request_gpt_model_in_new_thread_with_ui_alive(
|
108 |
+
inputs=i_say,
|
109 |
+
inputs_show_user=i_say,
|
110 |
+
llm_kwargs=llm_kwargs,
|
111 |
+
chatbot=chatbot,
|
112 |
+
history=history,
|
113 |
+
sys_prompt="总结文章。"
|
114 |
+
) # 带超时倒计时
|
115 |
+
chatbot[-1] = (i_say, gpt_say)
|
116 |
+
history.append(i_say); history.append(gpt_say)
|
117 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
118 |
+
res = write_results_to_file(history)
|
119 |
+
chatbot.append(("完成了吗?", res))
|
120 |
+
yield from update_ui(chatbot=chatbot, history=history, msg=msg) # 刷新界面
|
121 |
+
|
122 |
+
|
123 |
+
|
124 |
+
@CatchException
|
125 |
+
def 批量总结PDF文档pdfminer(txt, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt, web_port):
|
126 |
+
history = [] # 清空历史,以免输入溢出
|
127 |
+
import glob, os
|
128 |
+
|
129 |
+
# 基本信息:功能、贡献者
|
130 |
+
chatbot.append([
|
131 |
+
"函数插件功能?",
|
132 |
+
"批量总结PDF文档,此版本使用pdfminer插件,带token约简功能。函数插件贡献者: Euclid-Jie。"])
|
133 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
134 |
+
|
135 |
+
# 尝试导入依赖,如果缺少依赖,则给出安装建议
|
136 |
+
try:
|
137 |
+
import pdfminer, bs4
|
138 |
+
except:
|
139 |
+
report_execption(chatbot, history,
|
140 |
+
a = f"解析项目: {txt}",
|
141 |
+
b = f"导入软件依赖失败。使用该模块需要额外依赖,安装方法```pip install --upgrade pdfminer beautifulsoup4```。")
|
142 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
143 |
+
return
|
144 |
+
if os.path.exists(txt):
|
145 |
+
project_folder = txt
|
146 |
+
else:
|
147 |
+
if txt == "": txt = '空空如也的输入栏'
|
148 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到本地项目或无权访问: {txt}")
|
149 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
150 |
+
return
|
151 |
+
file_manifest = [f for f in glob.glob(f'{project_folder}/**/*.tex', recursive=True)] + \
|
152 |
+
[f for f in glob.glob(f'{project_folder}/**/*.pdf', recursive=True)] # + \
|
153 |
+
# [f for f in glob.glob(f'{project_folder}/**/*.cpp', recursive=True)] + \
|
154 |
+
# [f for f in glob.glob(f'{project_folder}/**/*.c', recursive=True)]
|
155 |
+
if len(file_manifest) == 0:
|
156 |
+
report_execption(chatbot, history, a = f"解析项目: {txt}", b = f"找不到任何.tex或pdf文件: {txt}")
|
157 |
+
yield from update_ui(chatbot=chatbot, history=history) # 刷新界面
|
158 |
+
return
|
159 |
+
yield from 解析Paper(file_manifest, project_folder, llm_kwargs, plugin_kwargs, chatbot, history, system_prompt)
|
160 |
+
|