MM-10417 Add local image proxy and enable by default (#9967)
* MM-10417 Add local image proxy and enable by default * Remove unused function * Add dependencies for willnorris/imageproxy * Fixed compilation errors * Lock to the master version of willnorris/imageproxy * Fix atmos/camo proxy when no SiteURL is specified * Re-add default values for deprecated settings * Fix unit tests added by merge * Pass imageproxy to App struct * Remove unneeded locking when creating the image proxy * Remove empty test file
Этот коммит содержится в:
коммит произвёл
GitHub
родитель
e961b4cd0d
Коммит
ba5566d1a0
52
Gopkg.lock
сгенерированный
52
Gopkg.lock
сгенерированный
@@ -212,6 +212,14 @@
|
||||
revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d"
|
||||
version = "v1.4.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:c3cbd7046b40723107a9a31232846de2e5de8c2e6ff6890b453d5920d6fff193"
|
||||
name = "github.com/gregjones/httpcache"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c63ab54fda8f77302f8d414e19933f2b6026a089"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:09970bb8daf100bdf11b48b72c71ef980cd2b50efbd903989b3d182956be0b83"
|
||||
name = "github.com/hako/durafmt"
|
||||
@@ -492,6 +500,22 @@
|
||||
revision = "3536a929edddb9a5b34bd6861dc4a9647cb459fe"
|
||||
version = "v1.1.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:9daa18c7506ff0e740eae69fa293b1047301e54ecd4ac89550eb6610115cfe96"
|
||||
name = "github.com/muesli/smartcrop"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "c6b1bf08b297d053c1b0bb5b964311b3b74fa49e"
|
||||
version = "v0.2.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:34534b73e925d20cc72cf202f8b482fdcbe3a1b113e19375f31aadabd0f0f97d"
|
||||
name = "github.com/nfnt/resize"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "83c6a9932646f83e3267f353373d47347b6036b2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:07140002dbf37da92090f731b46fa47be4820b82fe5c14a035203b0e813d0ec2"
|
||||
name = "github.com/nicksnyder/go-i18n"
|
||||
@@ -799,14 +823,20 @@
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:8aabc191fd00a92f1880d1ee3383ee57b44df6e55d6e682d0a8f994309f58e36"
|
||||
digest = "1:98a6b94e615d35032ac0df5b783455db7ad09a0effd888953fc20c81652571a5"
|
||||
name = "golang.org/x/image"
|
||||
packages = [
|
||||
"bmp",
|
||||
"draw",
|
||||
"font",
|
||||
"math/f64",
|
||||
"math/fixed",
|
||||
"riff",
|
||||
"tiff",
|
||||
"tiff/lzw",
|
||||
"vp8",
|
||||
"vp8l",
|
||||
"webp",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "cd38e8056d9b27bb2f265effa37fb0ea6b8a7f0f"
|
||||
@@ -987,6 +1017,25 @@
|
||||
revision = "51d6538a90f86fe93ac480b35f37b2be17fef232"
|
||||
version = "v2.2.2"
|
||||
|
||||
[[projects]]
|
||||
digest = "1:69c924347099fa89c7067b2d3cd41cf783f445ca4c1425144471a46383c7c2da"
|
||||
name = "willnorris.com/go/gifresize"
|
||||
packages = ["."]
|
||||
pruneopts = "UT"
|
||||
revision = "2593306bba2b31e43cf3d7b65d63489f356994b6"
|
||||
version = "v1.0.0"
|
||||
|
||||
[[projects]]
|
||||
branch = "master"
|
||||
digest = "1:7779169c828b767159228ce500f3c96c43672f43a9540e0ddda164de743cb1da"
|
||||
name = "willnorris.com/go/imageproxy"
|
||||
packages = [
|
||||
".",
|
||||
"third_party/http",
|
||||
]
|
||||
pruneopts = "UT"
|
||||
revision = "a903995ee7a34913f548592f7215d8a8a2a99d7e"
|
||||
|
||||
[solve-meta]
|
||||
analyzer-name = "dep"
|
||||
analyzer-version = 1
|
||||
@@ -1051,6 +1100,7 @@
|
||||
"gopkg.in/natefinch/lumberjack.v2",
|
||||
"gopkg.in/olivere/elastic.v5",
|
||||
"gopkg.in/yaml.v2",
|
||||
"willnorris.com/go/imageproxy",
|
||||
]
|
||||
solver-name = "gps-cdcl"
|
||||
solver-version = 1
|
||||
|
||||
@@ -45,6 +45,11 @@
|
||||
name = "github.com/segmentio/analytics-go"
|
||||
version = "2.1.1"
|
||||
|
||||
# Use latest master since we rely on some security features that don't exist in latest release
|
||||
[[constraint]]
|
||||
name = "willnorris.com/go/imageproxy"
|
||||
branch = "master"
|
||||
|
||||
# Lock to control when plugins use new versions
|
||||
[[constraint]]
|
||||
name = "github.com/hashicorp/go-hclog"
|
||||
|
||||
@@ -12,12 +12,10 @@ func (api *API) InitImage() {
|
||||
}
|
||||
|
||||
func getImage(c *Context, w http.ResponseWriter, r *http.Request) {
|
||||
// Only redirect to our image proxy if one is enabled. Arbitrary redirects are not allowed for
|
||||
// security reasons.
|
||||
if transform := c.App.ImageProxyAdder(); transform != nil {
|
||||
http.Redirect(w, r, transform(r.URL.Query().Get("url")), http.StatusFound)
|
||||
if !*c.App.Config().ImageProxySettings.Enable {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
http.NotFound(w, r)
|
||||
c.App.ImageProxy.GetImage(w, r, r.URL.Query().Get("url"))
|
||||
}
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
package api4
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
@@ -18,45 +20,75 @@ func TestGetImage(t *testing.T) {
|
||||
th := Setup().InitBasic()
|
||||
defer th.TearDown()
|
||||
|
||||
// Prevent the test client from following a redirect
|
||||
th.Client.HttpClient.CheckRedirect = func(*http.Request, []*http.Request) error {
|
||||
return http.ErrUseLastResponse
|
||||
}
|
||||
|
||||
originURL := "http://foo.bar/baz.gif"
|
||||
t.Run("proxy disabled", func(t *testing.T) {
|
||||
imageURL := "http://foo.bar/baz.gif"
|
||||
|
||||
r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(originURL), nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken)
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ImageProxySettings.Enable = model.NewBool(false)
|
||||
})
|
||||
|
||||
imageProxyType := th.App.Config().ServiceSettings.ImageProxyType
|
||||
imageProxyOptions := th.App.Config().ServiceSettings.ImageProxyOptions
|
||||
imageProxyURL := th.App.Config().ServiceSettings.ImageProxyURL
|
||||
defer func() {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.ImageProxyType = imageProxyType })
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.ImageProxyOptions = imageProxyOptions })
|
||||
th.App.UpdateConfig(func(cfg *model.Config) { cfg.ServiceSettings.ImageProxyOptions = imageProxyURL })
|
||||
}()
|
||||
r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken)
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ServiceSettings.ImageProxyType = nil
|
||||
resp, err := th.Client.HttpClient.Do(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
})
|
||||
|
||||
resp, err := th.Client.HttpClient.Do(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
t.Run("atmos/camo", func(t *testing.T) {
|
||||
imageURL := "http://foo.bar/baz.gif"
|
||||
proxiedURL := "https://proxy.foo.bar/004afe2ef382eb5f30c4490f793f8a8c5b33d8a2/687474703a2f2f666f6f2e6261722f62617a2e676966"
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ServiceSettings.ImageProxyType = model.NewString("atmos/camo")
|
||||
cfg.ServiceSettings.ImageProxyOptions = model.NewString("foo")
|
||||
cfg.ServiceSettings.ImageProxyURL = model.NewString("https://proxy.foo.bar")
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ImageProxySettings.Enable = model.NewBool(true)
|
||||
cfg.ImageProxySettings.ImageProxyType = model.NewString("atmos/camo")
|
||||
cfg.ImageProxySettings.RemoteImageProxyOptions = model.NewString("foo")
|
||||
cfg.ImageProxySettings.RemoteImageProxyURL = model.NewString("https://proxy.foo.bar")
|
||||
})
|
||||
|
||||
r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageURL), nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken)
|
||||
|
||||
resp, err := th.Client.HttpClient.Do(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusFound, resp.StatusCode)
|
||||
assert.Equal(t, proxiedURL, resp.Header.Get("Location"))
|
||||
})
|
||||
|
||||
r, err = http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+originURL, nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken)
|
||||
t.Run("local", func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ImageProxySettings.Enable = model.NewBool(true)
|
||||
cfg.ImageProxySettings.ImageProxyType = model.NewString("local")
|
||||
|
||||
resp, err = th.Client.HttpClient.Do(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusFound, resp.StatusCode)
|
||||
assert.Equal(t, "https://proxy.foo.bar/004afe2ef382eb5f30c4490f793f8a8c5b33d8a2/687474703a2f2f666f6f2e6261722f62617a2e676966", resp.Header.Get("Location"))
|
||||
// Allow requests to the "remote" image
|
||||
cfg.ServiceSettings.AllowedUntrustedInternalConnections = model.NewString("127.0.0.1")
|
||||
})
|
||||
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Write([]byte("success"))
|
||||
})
|
||||
|
||||
imageServer := httptest.NewServer(handler)
|
||||
defer imageServer.Close()
|
||||
|
||||
r, err := http.NewRequest("GET", th.Client.ApiUrl+"/image?url="+url.QueryEscape(imageServer.URL+"/image.png"), nil)
|
||||
require.NoError(t, err)
|
||||
r.Header.Set(model.HEADER_AUTH, th.Client.AuthType+" "+th.Client.AuthToken)
|
||||
|
||||
resp, err := th.Client.HttpClient.Do(r)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
|
||||
respBody, err := ioutil.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "success", string(respBody))
|
||||
})
|
||||
}
|
||||
|
||||
@@ -19,8 +19,10 @@ func (api *API) InitOpenGraph() {
|
||||
|
||||
// Dump the image cache if the proxy settings have changed. (need switch URLs to the correct proxy)
|
||||
api.ConfigService.AddConfigListener(func(before, after *model.Config) {
|
||||
if (before.ServiceSettings.ImageProxyType != after.ServiceSettings.ImageProxyType) ||
|
||||
(before.ServiceSettings.ImageProxyURL != after.ServiceSettings.ImageProxyType) {
|
||||
if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) ||
|
||||
(before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) ||
|
||||
(before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) ||
|
||||
(before.ImageProxySettings.RemoteImageProxyOptions != after.ImageProxySettings.RemoteImageProxyOptions) {
|
||||
openGraphDataCache.Purge()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/mattermost/mattermost-server/mlog"
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/services/httpservice"
|
||||
"github.com/mattermost/mattermost-server/services/imageproxy"
|
||||
"github.com/mattermost/mattermost-server/services/timezones"
|
||||
"github.com/mattermost/mattermost-server/utils"
|
||||
goi18n "github.com/nicksnyder/go-i18n/i18n"
|
||||
@@ -43,6 +44,7 @@ type App struct {
|
||||
Saml einterfaces.SamlInterface
|
||||
|
||||
HTTPService httpservice.HTTPService
|
||||
ImageProxy *imageproxy.ImageProxy
|
||||
Timezones *timezones.Timezones
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,7 @@ const (
|
||||
TRACK_CONFIG_MESSAGE_EXPORT = "config_message_export"
|
||||
TRACK_CONFIG_DISPLAY = "config_display"
|
||||
TRACK_CONFIG_TIMEZONE = "config_timezone"
|
||||
TRACK_CONFIG_IMAGE_PROXY = "config_image_proxy"
|
||||
TRACK_PERMISSIONS_GENERAL = "permissions_general"
|
||||
TRACK_PERMISSIONS_SYSTEM_SCHEME = "permissions_system_scheme"
|
||||
TRACK_PERMISSIONS_TEAM_SCHEMES = "permissions_team_schemes"
|
||||
@@ -255,9 +256,6 @@ func (a *App) trackConfig() {
|
||||
"enable_tutorial": *cfg.ServiceSettings.EnableTutorial,
|
||||
"experimental_enable_default_channel_leave_join_messages": *cfg.ServiceSettings.ExperimentalEnableDefaultChannelLeaveJoinMessages,
|
||||
"experimental_group_unread_channels": *cfg.ServiceSettings.ExperimentalGroupUnreadChannels,
|
||||
"isdefault_image_proxy_type": isDefault(*cfg.ServiceSettings.ImageProxyType, ""),
|
||||
"isdefault_image_proxy_url": isDefault(*cfg.ServiceSettings.ImageProxyURL, ""),
|
||||
"isdefault_image_proxy_options": isDefault(*cfg.ServiceSettings.ImageProxyOptions, ""),
|
||||
"websocket_url": isDefault(*cfg.ServiceSettings.WebsocketURL, ""),
|
||||
"allow_cookies_for_subdomains": *cfg.ServiceSettings.AllowCookiesForSubdomains,
|
||||
"enable_api_team_deletion": *cfg.ServiceSettings.EnableAPITeamDeletion,
|
||||
@@ -561,6 +559,13 @@ func (a *App) trackConfig() {
|
||||
a.SendDiagnostic(TRACK_CONFIG_TIMEZONE, map[string]interface{}{
|
||||
"isdefault_supported_timezones_path": isDefault(*cfg.TimezoneSettings.SupportedTimezonesPath, model.TIMEZONE_SETTINGS_DEFAULT_SUPPORTED_TIMEZONES_PATH),
|
||||
})
|
||||
|
||||
a.SendDiagnostic(TRACK_CONFIG_IMAGE_PROXY, map[string]interface{}{
|
||||
"enable": *cfg.ImageProxySettings.Enable,
|
||||
"image_proxy_type": *cfg.ImageProxySettings.ImageProxyType,
|
||||
"isdefault_remote_image_proxy_url": isDefault(*cfg.ImageProxySettings.RemoteImageProxyURL, ""),
|
||||
"isdefault_remote_image_proxy_options": isDefault(*cfg.ImageProxySettings.RemoteImageProxyOptions, ""),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *App) trackLicense() {
|
||||
|
||||
@@ -76,6 +76,7 @@ func ServerConnector(s *Server) AppOption {
|
||||
a.Saml = s.Saml
|
||||
|
||||
a.HTTPService = s.HTTPService
|
||||
a.ImageProxy = s.ImageProxy
|
||||
a.Timezones = s.timezones
|
||||
}
|
||||
}
|
||||
|
||||
66
app/post.go
66
app/post.go
@@ -4,9 +4,6 @@
|
||||
package app
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
@@ -916,78 +913,23 @@ func (a *App) PostPatchWithProxyRemovedFromImageURLs(patch *model.PostPatch) *mo
|
||||
return patch
|
||||
}
|
||||
|
||||
func (a *App) imageProxyConfig() (proxyType, proxyURL, options, siteURL string) {
|
||||
cfg := a.Config()
|
||||
|
||||
if cfg.ServiceSettings.ImageProxyURL == nil || cfg.ServiceSettings.ImageProxyType == nil || cfg.ServiceSettings.SiteURL == nil {
|
||||
return
|
||||
}
|
||||
|
||||
proxyURL = *cfg.ServiceSettings.ImageProxyURL
|
||||
proxyType = *cfg.ServiceSettings.ImageProxyType
|
||||
siteURL = *cfg.ServiceSettings.SiteURL
|
||||
|
||||
if proxyURL == "" || proxyType == "" {
|
||||
return "", "", "", ""
|
||||
}
|
||||
|
||||
if proxyURL[len(proxyURL)-1] != '/' {
|
||||
proxyURL += "/"
|
||||
}
|
||||
|
||||
if siteURL == "" || siteURL[len(siteURL)-1] != '/' {
|
||||
siteURL += "/"
|
||||
}
|
||||
|
||||
if cfg.ServiceSettings.ImageProxyOptions != nil {
|
||||
options = *cfg.ServiceSettings.ImageProxyOptions
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (a *App) ImageProxyAdder() func(string) string {
|
||||
proxyType, proxyURL, options, siteURL := a.imageProxyConfig()
|
||||
if proxyType == "" {
|
||||
if !*a.Config().ImageProxySettings.Enable {
|
||||
return nil
|
||||
}
|
||||
|
||||
return func(url string) string {
|
||||
if url == "" || url[0] == '/' || strings.HasPrefix(url, siteURL) || strings.HasPrefix(url, proxyURL) {
|
||||
return url
|
||||
}
|
||||
|
||||
switch proxyType {
|
||||
case "atmos/camo":
|
||||
mac := hmac.New(sha1.New, []byte(options))
|
||||
mac.Write([]byte(url))
|
||||
digest := hex.EncodeToString(mac.Sum(nil))
|
||||
return proxyURL + digest + "/" + hex.EncodeToString([]byte(url))
|
||||
}
|
||||
|
||||
return url
|
||||
return a.Srv.ImageProxy.GetProxiedImageURL(url)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) ImageProxyRemover() (f func(string) string) {
|
||||
proxyType, proxyURL, _, _ := a.imageProxyConfig()
|
||||
if proxyType == "" {
|
||||
if !*a.Config().ImageProxySettings.Enable {
|
||||
return nil
|
||||
}
|
||||
|
||||
return func(url string) string {
|
||||
switch proxyType {
|
||||
case "atmos/camo":
|
||||
if strings.HasPrefix(url, proxyURL) {
|
||||
if slash := strings.IndexByte(url[len(proxyURL):], '/'); slash >= 0 {
|
||||
if decoded, err := hex.DecodeString(url[len(proxyURL)+slash+1:]); err == nil {
|
||||
return string(decoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return url
|
||||
return a.Srv.ImageProxy.GetUnproxiedImageURL(url)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,8 +25,10 @@ var linkCache = utils.NewLru(LINK_CACHE_SIZE)
|
||||
func (a *App) InitPostMetadata() {
|
||||
// Dump any cached links if the proxy settings have changed so image URLs can be updated
|
||||
a.AddConfigListener(func(before, after *model.Config) {
|
||||
if (before.ServiceSettings.ImageProxyType != after.ServiceSettings.ImageProxyType) ||
|
||||
(before.ServiceSettings.ImageProxyURL != after.ServiceSettings.ImageProxyURL) {
|
||||
if (before.ImageProxySettings.Enable != after.ImageProxySettings.Enable) ||
|
||||
(before.ImageProxySettings.ImageProxyType != after.ImageProxySettings.ImageProxyType) ||
|
||||
(before.ImageProxySettings.RemoteImageProxyURL != after.ImageProxySettings.RemoteImageProxyURL) ||
|
||||
(before.ImageProxySettings.RemoteImageProxyOptions != after.ImageProxySettings.RemoteImageProxyOptions) {
|
||||
linkCache.Purge()
|
||||
}
|
||||
})
|
||||
|
||||
@@ -58,9 +58,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
th := Setup().InitBasic()
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.ImageProxyType = ""
|
||||
*cfg.ServiceSettings.ImageProxyURL = ""
|
||||
*cfg.ServiceSettings.ImageProxyOptions = ""
|
||||
*cfg.ImageProxySettings.Enable = false
|
||||
*cfg.ExperimentalSettings.EnablePostMetadata = true
|
||||
})
|
||||
|
||||
@@ -248,7 +246,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
|
||||
t.Run("populates image dimensions", func(t *testing.T) {
|
||||
imageDimensions := clientPost.Metadata.Images
|
||||
assert.Len(t, imageDimensions, 2)
|
||||
require.Len(t, imageDimensions, 2)
|
||||
assert.Equal(t, &model.PostImage{
|
||||
Width: 1068,
|
||||
Height: 552,
|
||||
@@ -301,7 +299,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
|
||||
t.Run("populates image dimensions", func(t *testing.T) {
|
||||
imageDimensions := clientPost.Metadata.Images
|
||||
assert.Len(t, imageDimensions, 1)
|
||||
require.Len(t, imageDimensions, 1)
|
||||
assert.Equal(t, &model.PostImage{
|
||||
Width: 1068,
|
||||
Height: 552,
|
||||
@@ -345,7 +343,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
|
||||
t.Run("populates image dimensions", func(t *testing.T) {
|
||||
imageDimensions := clientPost.Metadata.Images
|
||||
assert.Len(t, imageDimensions, 1)
|
||||
require.Len(t, imageDimensions, 1)
|
||||
assert.Equal(t, &model.PostImage{
|
||||
Width: 420,
|
||||
Height: 420,
|
||||
@@ -382,7 +380,7 @@ func TestPreparePostForClient(t *testing.T) {
|
||||
|
||||
t.Run("populates image dimensions", func(t *testing.T) {
|
||||
imageDimensions := clientPost.Metadata.Images
|
||||
assert.Len(t, imageDimensions, 1)
|
||||
require.Len(t, imageDimensions, 1)
|
||||
assert.Equal(t, &model.PostImage{
|
||||
Width: 501,
|
||||
Height: 501,
|
||||
@@ -415,9 +413,10 @@ func TestPreparePostForClientWithImageProxy(t *testing.T) {
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ServiceSettings.SiteURL = "http://mymattermost.com"
|
||||
*cfg.ServiceSettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ServiceSettings.ImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ServiceSettings.ImageProxyOptions = "foo"
|
||||
*cfg.ImageProxySettings.Enable = true
|
||||
*cfg.ImageProxySettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
|
||||
*cfg.ExperimentalSettings.EnablePostMetadata = true
|
||||
})
|
||||
|
||||
@@ -453,10 +452,10 @@ func testProxyLinkedImage(t *testing.T, th *TestHelper, shouldProxy bool) {
|
||||
clientPost := th.App.PreparePostForClient(post)
|
||||
|
||||
if shouldProxy {
|
||||
assert.Equal(t, post.Message, fmt.Sprintf(postTemplate, imageURL), "should not have mutated original post")
|
||||
assert.Equal(t, clientPost.Message, fmt.Sprintf(postTemplate, proxiedImageURL), "should've replaced linked image URLs")
|
||||
assert.Equal(t, fmt.Sprintf(postTemplate, imageURL), post.Message, "should not have mutated original post")
|
||||
assert.Equal(t, fmt.Sprintf(postTemplate, proxiedImageURL), clientPost.Message, "should've replaced linked image URLs")
|
||||
} else {
|
||||
assert.Equal(t, clientPost.Message, fmt.Sprintf(postTemplate, imageURL), "shouldn't have replaced linked image URLs")
|
||||
assert.Equal(t, fmt.Sprintf(postTemplate, imageURL), clientPost.Message, "shouldn't have replaced linked image URLs")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,29 +467,27 @@ func testProxyOpenGraphImage(t *testing.T, th *TestHelper, shouldProxy bool) {
|
||||
}, th.BasicChannel, false)
|
||||
require.Nil(t, err)
|
||||
|
||||
clientPost := th.App.PreparePostForClient(post)
|
||||
embeds := th.App.PreparePostForClient(post).Metadata.Embeds
|
||||
require.Len(t, embeds, 1, "should have one embed")
|
||||
|
||||
image := &opengraph.Image{}
|
||||
embed := embeds[0]
|
||||
assert.Equal(t, model.POST_EMBED_OPENGRAPH, embed.Type, "embed type should be OpenGraph")
|
||||
assert.Equal(t, "https://github.com/hmhealey/test-files", embed.URL, "embed URL should be correct")
|
||||
|
||||
og, ok := embed.Data.(*opengraph.OpenGraph)
|
||||
assert.Equal(t, true, ok, "data should be non-nil OpenGraph data")
|
||||
assert.Equal(t, "GitHub", og.SiteName, "OpenGraph data should be correctly populated")
|
||||
|
||||
require.Len(t, og.Images, 1, "OpenGraph data should have one image")
|
||||
|
||||
image := og.Images[0]
|
||||
if shouldProxy {
|
||||
image.SecureURL = "https://127.0.0.1/b2ef6ef4890a0107aa80ba33b3011fd51f668303/68747470733a2f2f61766174617273312e67697468756275736572636f6e74656e742e636f6d2f752f333237373331303f733d34303026763d34"
|
||||
assert.Equal(t, "", image.URL, "image URL should not be set with proxy")
|
||||
assert.Equal(t, "https://127.0.0.1/b2ef6ef4890a0107aa80ba33b3011fd51f668303/68747470733a2f2f61766174617273312e67697468756275736572636f6e74656e742e636f6d2f752f333237373331303f733d34303026763d34", image.SecureURL, "secure image URL should be sent through proxy")
|
||||
} else {
|
||||
image.URL = "https://avatars1.githubusercontent.com/u/3277310?s=400&v=4"
|
||||
assert.Equal(t, "https://avatars1.githubusercontent.com/u/3277310?s=400&v=4", image.URL, "image URL should be set")
|
||||
assert.Equal(t, "", image.SecureURL, "secure image URL should not be set")
|
||||
}
|
||||
|
||||
assert.ElementsMatch(t, []*model.PostEmbed{
|
||||
{
|
||||
Type: model.POST_EMBED_OPENGRAPH,
|
||||
URL: "https://github.com/hmhealey/test-files",
|
||||
Data: &opengraph.OpenGraph{
|
||||
Description: "Contribute to hmhealey/test-files development by creating an account on GitHub.",
|
||||
SiteName: "GitHub",
|
||||
Title: "hmhealey/test-files",
|
||||
Type: "object",
|
||||
URL: "https://github.com/hmhealey/test-files",
|
||||
Images: []*opengraph.Image{image},
|
||||
},
|
||||
},
|
||||
}, clientPost.Metadata.Embeds)
|
||||
}
|
||||
|
||||
func TestGetEmojiNamesForString(t *testing.T) {
|
||||
|
||||
@@ -406,39 +406,60 @@ func TestImageProxy(t *testing.T) {
|
||||
ProxiedImageURL string
|
||||
}{
|
||||
"atmos/camo": {
|
||||
ProxyType: "atmos/camo",
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
ProxyURL: "https://127.0.0.1",
|
||||
ProxyOptions: "foo",
|
||||
ImageURL: "http://mydomain.com/myimage",
|
||||
ProxiedImageURL: "https://127.0.0.1/f8dace906d23689e8d5b12c3cefbedbf7b9b72f5/687474703a2f2f6d79646f6d61696e2e636f6d2f6d79696d616765",
|
||||
},
|
||||
"atmos/camo_SameSite": {
|
||||
ProxyType: "atmos/camo",
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
ProxyURL: "https://127.0.0.1",
|
||||
ProxyOptions: "foo",
|
||||
ImageURL: "http://mymattermost.com/myimage",
|
||||
ProxiedImageURL: "http://mymattermost.com/myimage",
|
||||
},
|
||||
"atmos/camo_PathOnly": {
|
||||
ProxyType: "atmos/camo",
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
ProxyURL: "https://127.0.0.1",
|
||||
ProxyOptions: "foo",
|
||||
ImageURL: "/myimage",
|
||||
ProxiedImageURL: "/myimage",
|
||||
},
|
||||
"atmos/camo_EmptyImageURL": {
|
||||
ProxyType: "atmos/camo",
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
ProxyURL: "https://127.0.0.1",
|
||||
ProxyOptions: "foo",
|
||||
ImageURL: "",
|
||||
ProxiedImageURL: "",
|
||||
},
|
||||
"local": {
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
|
||||
ImageURL: "http://mydomain.com/myimage",
|
||||
ProxiedImageURL: "http://mymattermost.com/api/v4/image?url=http%3A%2F%2Fmydomain.com%2Fmyimage",
|
||||
},
|
||||
"local_SameSite": {
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
|
||||
ImageURL: "http://mymattermost.com/myimage",
|
||||
ProxiedImageURL: "http://mymattermost.com/myimage",
|
||||
},
|
||||
"local_PathOnly": {
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
|
||||
ImageURL: "/myimage",
|
||||
ProxiedImageURL: "/myimage",
|
||||
},
|
||||
"local_EmptyImageURL": {
|
||||
ProxyType: model.IMAGE_PROXY_TYPE_LOCAL,
|
||||
ImageURL: "",
|
||||
ProxiedImageURL: "",
|
||||
},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
cfg.ServiceSettings.ImageProxyType = model.NewString(tc.ProxyType)
|
||||
cfg.ServiceSettings.ImageProxyOptions = model.NewString(tc.ProxyOptions)
|
||||
cfg.ServiceSettings.ImageProxyURL = model.NewString(tc.ProxyURL)
|
||||
cfg.ImageProxySettings.Enable = model.NewBool(true)
|
||||
cfg.ImageProxySettings.ImageProxyType = model.NewString(tc.ProxyType)
|
||||
cfg.ImageProxySettings.RemoteImageProxyOptions = model.NewString(tc.ProxyOptions)
|
||||
cfg.ImageProxySettings.RemoteImageProxyURL = model.NewString(tc.ProxyURL)
|
||||
})
|
||||
|
||||
post := &model.Post{
|
||||
@@ -574,9 +595,10 @@ func TestCreatePost(t *testing.T) {
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ExperimentalSettings.EnablePostMetadata = false
|
||||
*cfg.ServiceSettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ServiceSettings.ImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ServiceSettings.ImageProxyOptions = "foo"
|
||||
*cfg.ImageProxySettings.Enable = true
|
||||
*cfg.ImageProxySettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
|
||||
})
|
||||
|
||||
imageURL := "http://mydomain.com/myimage"
|
||||
@@ -601,9 +623,10 @@ func TestPatchPost(t *testing.T) {
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ExperimentalSettings.EnablePostMetadata = false
|
||||
*cfg.ServiceSettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ServiceSettings.ImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ServiceSettings.ImageProxyOptions = "foo"
|
||||
*cfg.ImageProxySettings.Enable = true
|
||||
*cfg.ImageProxySettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
|
||||
})
|
||||
|
||||
imageURL := "http://mydomain.com/myimage"
|
||||
@@ -636,9 +659,10 @@ func TestUpdatePost(t *testing.T) {
|
||||
|
||||
th.App.UpdateConfig(func(cfg *model.Config) {
|
||||
*cfg.ExperimentalSettings.EnablePostMetadata = false
|
||||
*cfg.ServiceSettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ServiceSettings.ImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ServiceSettings.ImageProxyOptions = "foo"
|
||||
*cfg.ImageProxySettings.Enable = true
|
||||
*cfg.ImageProxySettings.ImageProxyType = "atmos/camo"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyURL = "https://127.0.0.1"
|
||||
*cfg.ImageProxySettings.RemoteImageProxyOptions = "foo"
|
||||
})
|
||||
|
||||
imageURL := "http://mydomain.com/myimage"
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/plugin"
|
||||
"github.com/mattermost/mattermost-server/services/httpservice"
|
||||
"github.com/mattermost/mattermost-server/services/imageproxy"
|
||||
"github.com/mattermost/mattermost-server/services/timezones"
|
||||
"github.com/mattermost/mattermost-server/store"
|
||||
"github.com/mattermost/mattermost-server/utils"
|
||||
@@ -110,6 +111,8 @@ type Server struct {
|
||||
|
||||
HTTPService httpservice.HTTPService
|
||||
|
||||
ImageProxy *imageproxy.ImageProxy
|
||||
|
||||
Log *mlog.Logger
|
||||
|
||||
joinCluster bool
|
||||
@@ -165,6 +168,8 @@ func NewServer(options ...Option) (*Server, error) {
|
||||
|
||||
s.HTTPService = httpservice.MakeHTTPService(s.FakeApp())
|
||||
|
||||
s.ImageProxy = imageproxy.MakeImageProxy(s, s.HTTPService)
|
||||
|
||||
if utils.T == nil {
|
||||
if err := utils.TranslationsPreInit(); err != nil {
|
||||
return nil, errors.Wrapf(err, "unable to load Mattermost translation files")
|
||||
|
||||
@@ -71,9 +71,6 @@
|
||||
"ExperimentalEnableDefaultChannelLeaveJoinMessages": true,
|
||||
"ExperimentalGroupUnreadChannels": "disabled",
|
||||
"ExperimentalChannelOrganization": false,
|
||||
"ImageProxyType": "",
|
||||
"ImageProxyOptions": "",
|
||||
"ImageProxyURL": "",
|
||||
"EnableAPITeamDeletion": false,
|
||||
"ExperimentalEnableHardenedMode": false,
|
||||
"EnableEmailInvitations": false,
|
||||
@@ -413,5 +410,11 @@
|
||||
"ClientDirectory": "./client/plugins",
|
||||
"Plugins": {},
|
||||
"PluginStates": {}
|
||||
},
|
||||
"ImageProxySettings": {
|
||||
"Enable": true,
|
||||
"ImageProxyType": "local",
|
||||
"RemoteImageProxyURL": "",
|
||||
"RemoteImageProxyOptions": ""
|
||||
}
|
||||
}
|
||||
@@ -4084,7 +4084,11 @@
|
||||
},
|
||||
{
|
||||
"id": "model.config.is_valid.atmos_camo_image_proxy_options.app_error",
|
||||
"translation": "Invalid atmos/camo image proxy options for service settings. Must be set to your shared key."
|
||||
"translation": "Invalid RemoteImageProxyOptions for atmos/camo. Must be set to your shared key."
|
||||
},
|
||||
{
|
||||
"id": "model.config.is_valid.atmos_camo_image_proxy_url.app_error",
|
||||
"translation": "Invalid RemoteImageProxyURL for atmos/camo. Must be set to your shared key."
|
||||
},
|
||||
{
|
||||
"id": "model.config.is_valid.cluster_email_batching.app_error",
|
||||
@@ -4172,7 +4176,7 @@
|
||||
},
|
||||
{
|
||||
"id": "model.config.is_valid.image_proxy_type.app_error",
|
||||
"translation": "Invalid image proxy type for service settings."
|
||||
"translation": "Invalid image proxy type. Must be 'local' or 'atmos/camo'."
|
||||
},
|
||||
{
|
||||
"id": "model.config.is_valid.ldap_basedn",
|
||||
|
||||
@@ -174,6 +174,9 @@ const (
|
||||
|
||||
CLIENT_SIDE_CERT_CHECK_PRIMARY_AUTH = "primary"
|
||||
CLIENT_SIDE_CERT_CHECK_SECONDARY_AUTH = "secondary"
|
||||
|
||||
IMAGE_PROXY_TYPE_LOCAL = "local"
|
||||
IMAGE_PROXY_TYPE_ATMOS_CAMO = "atmos/camo"
|
||||
)
|
||||
|
||||
var ServerTLSSupportedCiphers = map[string]uint16{
|
||||
@@ -272,9 +275,9 @@ type ServiceSettings struct {
|
||||
ExperimentalEnableDefaultChannelLeaveJoinMessages *bool
|
||||
ExperimentalGroupUnreadChannels *string
|
||||
ExperimentalChannelOrganization *bool
|
||||
ImageProxyType *string
|
||||
ImageProxyURL *string
|
||||
ImageProxyOptions *string
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyType *string `json:"ImageProxyType"` // This field is deprecated and must not be used.
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyURL *string `json:"ImageProxyURL"` // This field is deprecated and must not be used.
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyOptions *string `json:"ImageProxyOptions"` // This field is deprecated and must not be used.
|
||||
EnableAPITeamDeletion *bool
|
||||
ExperimentalEnableHardenedMode *bool
|
||||
EnableEmailInvitations *bool
|
||||
@@ -550,16 +553,16 @@ func (s *ServiceSettings) SetDefaults() {
|
||||
s.ExperimentalChannelOrganization = NewBool(experimentalUnreadEnabled)
|
||||
}
|
||||
|
||||
if s.ImageProxyType == nil {
|
||||
s.ImageProxyType = NewString("")
|
||||
if s.DEPRECATED_DO_NOT_USE_ImageProxyType == nil {
|
||||
s.DEPRECATED_DO_NOT_USE_ImageProxyType = NewString("")
|
||||
}
|
||||
|
||||
if s.ImageProxyURL == nil {
|
||||
s.ImageProxyURL = NewString("")
|
||||
if s.DEPRECATED_DO_NOT_USE_ImageProxyURL == nil {
|
||||
s.DEPRECATED_DO_NOT_USE_ImageProxyURL = NewString("")
|
||||
}
|
||||
|
||||
if s.ImageProxyOptions == nil {
|
||||
s.ImageProxyOptions = NewString("")
|
||||
if s.DEPRECATED_DO_NOT_USE_ImageProxyOptions == nil {
|
||||
s.DEPRECATED_DO_NOT_USE_ImageProxyOptions = NewString("")
|
||||
}
|
||||
|
||||
if s.EnableAPITeamDeletion == nil {
|
||||
@@ -1931,6 +1934,43 @@ func (s *TimezoneSettings) SetDefaults() {
|
||||
}
|
||||
}
|
||||
|
||||
type ImageProxySettings struct {
|
||||
Enable *bool
|
||||
ImageProxyType *string
|
||||
RemoteImageProxyURL *string
|
||||
RemoteImageProxyOptions *string
|
||||
}
|
||||
|
||||
func (ips *ImageProxySettings) SetDefaults(ss ServiceSettings) {
|
||||
if ips.Enable == nil {
|
||||
ips.Enable = NewBool(true)
|
||||
}
|
||||
|
||||
if ips.ImageProxyType == nil {
|
||||
if ss.DEPRECATED_DO_NOT_USE_ImageProxyType == nil || *ss.DEPRECATED_DO_NOT_USE_ImageProxyType == "" {
|
||||
ips.ImageProxyType = NewString(IMAGE_PROXY_TYPE_LOCAL)
|
||||
} else {
|
||||
ips.ImageProxyType = ss.DEPRECATED_DO_NOT_USE_ImageProxyType
|
||||
}
|
||||
}
|
||||
|
||||
if ips.RemoteImageProxyURL == nil {
|
||||
if ss.DEPRECATED_DO_NOT_USE_ImageProxyURL == nil {
|
||||
ips.RemoteImageProxyURL = NewString("")
|
||||
} else {
|
||||
ips.RemoteImageProxyURL = ss.DEPRECATED_DO_NOT_USE_ImageProxyURL
|
||||
}
|
||||
}
|
||||
|
||||
if ips.RemoteImageProxyOptions == nil {
|
||||
if ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions == nil {
|
||||
ips.RemoteImageProxyOptions = NewString("")
|
||||
} else {
|
||||
ips.RemoteImageProxyOptions = ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigFunc func() *Config
|
||||
|
||||
type Config struct {
|
||||
@@ -1966,6 +2006,7 @@ type Config struct {
|
||||
PluginSettings PluginSettings
|
||||
DisplaySettings DisplaySettings
|
||||
TimezoneSettings TimezoneSettings
|
||||
ImageProxySettings ImageProxySettings
|
||||
}
|
||||
|
||||
func (o *Config) Clone() *Config {
|
||||
@@ -2037,6 +2078,7 @@ func (o *Config) SetDefaults() {
|
||||
o.MessageExportSettings.SetDefaults()
|
||||
o.TimezoneSettings.SetDefaults()
|
||||
o.DisplaySettings.SetDefaults()
|
||||
o.ImageProxySettings.SetDefaults(o.ServiceSettings)
|
||||
}
|
||||
|
||||
func (o *Config) IsValid() *AppError {
|
||||
@@ -2108,6 +2150,10 @@ func (o *Config) IsValid() *AppError {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := o.ImageProxySettings.isValid(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2392,16 +2438,6 @@ func (ss *ServiceSettings) isValid() *AppError {
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.group_unread_channels.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
switch *ss.ImageProxyType {
|
||||
case "":
|
||||
case "atmos/camo":
|
||||
if *ss.ImageProxyOptions == "" {
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_options.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
default:
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.image_proxy_type.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -2521,6 +2557,27 @@ func (ds *DisplaySettings) isValid() *AppError {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (ips *ImageProxySettings) isValid() *AppError {
|
||||
if *ips.Enable {
|
||||
switch *ips.ImageProxyType {
|
||||
case IMAGE_PROXY_TYPE_LOCAL:
|
||||
// No other settings to validate
|
||||
case IMAGE_PROXY_TYPE_ATMOS_CAMO:
|
||||
if *ips.RemoteImageProxyURL == "" {
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_url.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
|
||||
if *ips.RemoteImageProxyOptions == "" {
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.atmos_camo_image_proxy_options.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
default:
|
||||
return NewAppError("Config.IsValid", "model.config.is_valid.image_proxy_type.app_error", nil, "", http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (o *Config) GetSanitizeOptions() map[string]bool {
|
||||
options := map[string]bool{}
|
||||
options["fullname"] = o.PrivacySettings.ShowFullName
|
||||
|
||||
@@ -564,3 +564,128 @@ func TestListenAddressIsValidated(t *testing.T) {
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestImageProxySettingsSetDefaults(t *testing.T) {
|
||||
ss := ServiceSettings{
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyType: NewString(IMAGE_PROXY_TYPE_ATMOS_CAMO),
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyURL: NewString("http://images.example.com"),
|
||||
DEPRECATED_DO_NOT_USE_ImageProxyOptions: NewString("1234abcd"),
|
||||
}
|
||||
|
||||
t.Run("default, no old settings", func(t *testing.T) {
|
||||
ips := ImageProxySettings{}
|
||||
ips.SetDefaults(ServiceSettings{})
|
||||
|
||||
assert.Equal(t, true, *ips.Enable)
|
||||
assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType)
|
||||
assert.Equal(t, "", *ips.RemoteImageProxyURL)
|
||||
assert.Equal(t, "", *ips.RemoteImageProxyOptions)
|
||||
})
|
||||
|
||||
t.Run("default, old settings", func(t *testing.T) {
|
||||
ips := ImageProxySettings{}
|
||||
ips.SetDefaults(ss)
|
||||
|
||||
assert.Equal(t, true, *ips.Enable)
|
||||
assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyType, *ips.ImageProxyType)
|
||||
assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyURL, *ips.RemoteImageProxyURL)
|
||||
assert.Equal(t, *ss.DEPRECATED_DO_NOT_USE_ImageProxyOptions, *ips.RemoteImageProxyOptions)
|
||||
})
|
||||
|
||||
t.Run("not default, old settings", func(t *testing.T) {
|
||||
url := "http://images.mattermost.com"
|
||||
options := "aaaaaaaa"
|
||||
|
||||
ips := ImageProxySettings{
|
||||
Enable: NewBool(false),
|
||||
ImageProxyType: NewString(IMAGE_PROXY_TYPE_LOCAL),
|
||||
RemoteImageProxyURL: &url,
|
||||
RemoteImageProxyOptions: &options,
|
||||
}
|
||||
ips.SetDefaults(ss)
|
||||
|
||||
assert.Equal(t, false, *ips.Enable)
|
||||
assert.Equal(t, IMAGE_PROXY_TYPE_LOCAL, *ips.ImageProxyType)
|
||||
assert.Equal(t, url, *ips.RemoteImageProxyURL)
|
||||
assert.Equal(t, options, *ips.RemoteImageProxyOptions)
|
||||
})
|
||||
}
|
||||
|
||||
func TestImageProxySettingsIsValid(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
Name string
|
||||
Enable bool
|
||||
ImageProxyType string
|
||||
RemoteImageProxyURL string
|
||||
RemoteImageProxyOptions string
|
||||
ExpectError bool
|
||||
}{
|
||||
{
|
||||
Name: "disabled",
|
||||
Enable: false,
|
||||
ExpectError: false,
|
||||
},
|
||||
{
|
||||
Name: "disabled with bad values",
|
||||
Enable: false,
|
||||
ImageProxyType: "garbage",
|
||||
RemoteImageProxyURL: "garbage",
|
||||
RemoteImageProxyOptions: "garbage",
|
||||
ExpectError: false,
|
||||
},
|
||||
{
|
||||
Name: "missing type",
|
||||
Enable: true,
|
||||
ImageProxyType: "",
|
||||
ExpectError: true,
|
||||
},
|
||||
{
|
||||
Name: "local",
|
||||
Enable: true,
|
||||
ImageProxyType: "local",
|
||||
RemoteImageProxyURL: "garbage",
|
||||
RemoteImageProxyOptions: "garbage",
|
||||
ExpectError: false,
|
||||
},
|
||||
{
|
||||
Name: "atmos/camo",
|
||||
Enable: true,
|
||||
ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
RemoteImageProxyURL: "someurl",
|
||||
RemoteImageProxyOptions: "someoptions",
|
||||
ExpectError: false,
|
||||
},
|
||||
{
|
||||
Name: "atmos/camo, missing url",
|
||||
Enable: true,
|
||||
ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
RemoteImageProxyURL: "",
|
||||
RemoteImageProxyOptions: "garbage",
|
||||
ExpectError: true,
|
||||
},
|
||||
{
|
||||
Name: "atmos/camo, missing options",
|
||||
Enable: true,
|
||||
ImageProxyType: IMAGE_PROXY_TYPE_ATMOS_CAMO,
|
||||
RemoteImageProxyURL: "someurl",
|
||||
RemoteImageProxyOptions: "",
|
||||
ExpectError: true,
|
||||
},
|
||||
} {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
ips := &ImageProxySettings{
|
||||
Enable: &test.Enable,
|
||||
ImageProxyType: &test.ImageProxyType,
|
||||
RemoteImageProxyURL: &test.RemoteImageProxyURL,
|
||||
RemoteImageProxyOptions: &test.RemoteImageProxyOptions,
|
||||
}
|
||||
|
||||
err := ips.isValid()
|
||||
if test.ExpectError {
|
||||
assert.NotNil(t, err)
|
||||
} else {
|
||||
assert.Nil(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
70
services/imageproxy/atmos_camo.go
Обычный файл
70
services/imageproxy/atmos_camo.go
Обычный файл
@@ -0,0 +1,70 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha1"
|
||||
"encoding/hex"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type AtmosCamoBackend struct {
|
||||
proxy *ImageProxy
|
||||
}
|
||||
|
||||
func makeAtmosCamoBackend(proxy *ImageProxy) *AtmosCamoBackend {
|
||||
return &AtmosCamoBackend{
|
||||
proxy: proxy,
|
||||
}
|
||||
}
|
||||
|
||||
func (backend *AtmosCamoBackend) GetImage(w http.ResponseWriter, r *http.Request, imageURL string) {
|
||||
http.Redirect(w, r, backend.GetProxiedImageURL(imageURL), http.StatusFound)
|
||||
}
|
||||
|
||||
func (backend *AtmosCamoBackend) GetProxiedImageURL(imageURL string) string {
|
||||
cfg := *backend.proxy.ConfigService.Config()
|
||||
siteURL := *cfg.ServiceSettings.SiteURL
|
||||
proxyURL := *cfg.ImageProxySettings.RemoteImageProxyURL
|
||||
options := *cfg.ImageProxySettings.RemoteImageProxyOptions
|
||||
|
||||
return getAtmosCamoImageURL(imageURL, siteURL, proxyURL, options)
|
||||
}
|
||||
|
||||
func getAtmosCamoImageURL(imageURL, siteURL, proxyURL, options string) string {
|
||||
// Don't proxy blank images, relative URLs, absolute URLs on this server, or URLs that are already going through the proxy
|
||||
if imageURL == "" || imageURL[0] == '/' || (siteURL != "" && strings.HasPrefix(imageURL, siteURL)) || strings.HasPrefix(imageURL, proxyURL) {
|
||||
return imageURL
|
||||
}
|
||||
|
||||
mac := hmac.New(sha1.New, []byte(options))
|
||||
mac.Write([]byte(imageURL))
|
||||
digest := hex.EncodeToString(mac.Sum(nil))
|
||||
|
||||
return proxyURL + "/" + digest + "/" + hex.EncodeToString([]byte(imageURL))
|
||||
}
|
||||
|
||||
func (backend *AtmosCamoBackend) GetUnproxiedImageURL(proxiedURL string) string {
|
||||
proxyURL := *backend.proxy.ConfigService.Config().ImageProxySettings.RemoteImageProxyURL + "/"
|
||||
|
||||
if !strings.HasPrefix(proxiedURL, proxyURL) {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
path := proxiedURL[len(proxyURL):]
|
||||
|
||||
slash := strings.IndexByte(path, '/')
|
||||
if slash == -1 {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
decoded, err := hex.DecodeString(path[slash+1:])
|
||||
if err != nil {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
return string(decoded)
|
||||
}
|
||||
159
services/imageproxy/atmos_camo_test.go
Обычный файл
159
services/imageproxy/atmos_camo_test.go
Обычный файл
@@ -0,0 +1,159 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/utils/testutils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func makeTestAtmosCamoProxy() *ImageProxy {
|
||||
configService := &testutils.StaticConfigService{
|
||||
Cfg: &model.Config{
|
||||
ServiceSettings: model.ServiceSettings{
|
||||
SiteURL: model.NewString("https://mattermost.example.com"),
|
||||
},
|
||||
ImageProxySettings: model.ImageProxySettings{
|
||||
Enable: model.NewBool(true),
|
||||
ImageProxyType: model.NewString(model.IMAGE_PROXY_TYPE_ATMOS_CAMO),
|
||||
RemoteImageProxyURL: model.NewString("http://images.example.com"),
|
||||
RemoteImageProxyOptions: model.NewString("7e5f3fab20b94782b43cdb022a66985ef28ba355df2c5d5da3c9a05e4b697bac"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return MakeImageProxy(configService, nil)
|
||||
}
|
||||
|
||||
func TestAtmosCamoBackend_GetImage(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontalWhite.png"
|
||||
proxiedURL := "http://images.example.com/62183a1cf0a4927c3b56d249366c2745e34ffe63/687474703a2f2f7777772e6d61747465726d6f73742e6f72672f77702d636f6e74656e742f75706c6f6164732f323031362f30332f6c6f676f486f72697a6f6e74616c57686974652e706e67"
|
||||
|
||||
proxy := makeTestAtmosCamoProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, imageURL)
|
||||
resp := recorder.Result()
|
||||
|
||||
assert.Equal(t, http.StatusFound, resp.StatusCode)
|
||||
assert.Equal(t, proxiedURL, resp.Header.Get("Location"))
|
||||
}
|
||||
|
||||
func TestAtmosCamoBackend_GetProxiedImageURL(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontal.png"
|
||||
proxiedURL := "http://images.example.com/5b6f6661516bc837b89b54566eb619d14a5c3eca/687474703a2f2f7777772e6d61747465726d6f73742e6f72672f77702d636f6e74656e742f75706c6f6164732f323031362f30332f6c6f676f486f72697a6f6e74616c2e706e67"
|
||||
|
||||
proxy := makeTestAtmosCamoProxy()
|
||||
|
||||
// Most of this logic is tested in TestGetAtmosCamoImageURL
|
||||
assert.Equal(t, proxiedURL, proxy.GetProxiedImageURL(imageURL))
|
||||
}
|
||||
|
||||
func TestGetAtmosCamoImageURL(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontal.png"
|
||||
proxiedURL := "http://images.example.com/5b6f6661516bc837b89b54566eb619d14a5c3eca/687474703a2f2f7777772e6d61747465726d6f73742e6f72672f77702d636f6e74656e742f75706c6f6164732f323031362f30332f6c6f676f486f72697a6f6e74616c2e706e67"
|
||||
|
||||
defaultSiteURL := "https://mattermost.example.com"
|
||||
proxyURL := "http://images.example.com"
|
||||
options := "7e5f3fab20b94782b43cdb022a66985ef28ba355df2c5d5da3c9a05e4b697bac"
|
||||
|
||||
for _, test := range []struct {
|
||||
Name string
|
||||
Input string
|
||||
SiteURL string
|
||||
Expected string
|
||||
}{
|
||||
{
|
||||
Name: "should proxy image",
|
||||
Input: imageURL,
|
||||
SiteURL: defaultSiteURL,
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
{
|
||||
Name: "should proxy image when no site URL is set",
|
||||
Input: imageURL,
|
||||
SiteURL: "",
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
{
|
||||
Name: "should proxy image when a site URL with a subpath is set",
|
||||
Input: imageURL,
|
||||
SiteURL: proxyURL + "/subpath",
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
{
|
||||
Name: "should not proxy a relative image",
|
||||
Input: "/static/logo.png",
|
||||
SiteURL: defaultSiteURL,
|
||||
Expected: "/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not proxy an image on the Mattermost server",
|
||||
Input: "https://mattermost.example.com/static/logo.png",
|
||||
SiteURL: defaultSiteURL,
|
||||
Expected: "https://mattermost.example.com/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not proxy an image on the Mattermost server when a subpath is set",
|
||||
Input: "https://mattermost.example.com/static/logo.png",
|
||||
SiteURL: defaultSiteURL + "/static",
|
||||
Expected: "https://mattermost.example.com/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not proxy an image that has already been proxied",
|
||||
Input: proxiedURL,
|
||||
SiteURL: defaultSiteURL,
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
} {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
assert.Equal(t, test.Expected, getAtmosCamoImageURL(test.Input, test.SiteURL, proxyURL, options))
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestAtmosCamoBackend_GetUnproxiedImageURL(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontal.png"
|
||||
proxiedURL := "http://images.example.com/5b6f6661516bc837b89b54566eb619d14a5c3eca/687474703a2f2f7777772e6d61747465726d6f73742e6f72672f77702d636f6e74656e742f75706c6f6164732f323031362f30332f6c6f676f486f72697a6f6e74616c2e706e67"
|
||||
|
||||
proxy := makeTestAtmosCamoProxy()
|
||||
|
||||
for _, test := range []struct {
|
||||
Name string
|
||||
Input string
|
||||
Expected string
|
||||
}{
|
||||
{
|
||||
Name: "should remove proxy",
|
||||
Input: proxiedURL,
|
||||
Expected: imageURL,
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from a relative image",
|
||||
Input: "/static/logo.png",
|
||||
Expected: "/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from an image on the Mattermost server",
|
||||
Input: "https://mattermost.example.com/static/logo.png",
|
||||
Expected: "https://mattermost.example.com/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from a non-proxied image",
|
||||
Input: imageURL,
|
||||
Expected: imageURL,
|
||||
},
|
||||
} {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
assert.Equal(t, test.Expected, proxy.GetUnproxiedImageURL(test.Input))
|
||||
})
|
||||
}
|
||||
}
|
||||
123
services/imageproxy/imageproxy.go
Обычный файл
123
services/imageproxy/imageproxy.go
Обычный файл
@@ -0,0 +1,123 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/services/configservice"
|
||||
"github.com/mattermost/mattermost-server/services/httpservice"
|
||||
)
|
||||
|
||||
// An ImageProxy is the public interface for Mattermost's image proxy. An instance of ImageProxy should be created
|
||||
// using MakeImageProxy which requires a configService and an HTTPService provided by the server.
|
||||
type ImageProxy struct {
|
||||
ConfigService configservice.ConfigService
|
||||
configListenerId string
|
||||
|
||||
HTTPService httpservice.HTTPService
|
||||
|
||||
lock sync.RWMutex
|
||||
backend ImageProxyBackend
|
||||
}
|
||||
|
||||
// An ImageProxyBackend provides the functionality for different types of image proxies. An ImageProxy will construct
|
||||
// the required backend depending on the ImageProxySettings provided by the ConfigService.
|
||||
type ImageProxyBackend interface {
|
||||
// GetImage provides a proxied image in response to an HTTP request.
|
||||
GetImage(w http.ResponseWriter, r *http.Request, imageURL string)
|
||||
|
||||
// GetProxiedImageURL returns the URL to access a given image through the image proxy, whether the image proxy is
|
||||
// running externally or as part of the Mattermost server itself.
|
||||
GetProxiedImageURL(imageURL string) string
|
||||
|
||||
// GetUnproxiedImageURL returns the original URL of an image from one that has been directed at the image proxy.
|
||||
GetUnproxiedImageURL(proxiedURL string) string
|
||||
}
|
||||
|
||||
func MakeImageProxy(configService configservice.ConfigService, httpService httpservice.HTTPService) *ImageProxy {
|
||||
proxy := &ImageProxy{
|
||||
ConfigService: configService,
|
||||
HTTPService: httpService,
|
||||
}
|
||||
|
||||
proxy.configListenerId = proxy.ConfigService.AddConfigListener(proxy.OnConfigChange)
|
||||
|
||||
config := proxy.ConfigService.Config()
|
||||
proxy.backend = proxy.makeBackend(*config.ImageProxySettings.Enable, *config.ImageProxySettings.ImageProxyType)
|
||||
|
||||
return proxy
|
||||
}
|
||||
|
||||
func (proxy *ImageProxy) makeBackend(enable bool, proxyType string) ImageProxyBackend {
|
||||
if !enable {
|
||||
return nil
|
||||
}
|
||||
|
||||
switch proxyType {
|
||||
case model.IMAGE_PROXY_TYPE_LOCAL:
|
||||
return makeLocalBackend(proxy)
|
||||
case model.IMAGE_PROXY_TYPE_ATMOS_CAMO:
|
||||
return makeAtmosCamoBackend(proxy)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func (proxy *ImageProxy) Close() {
|
||||
proxy.lock.Lock()
|
||||
defer proxy.lock.Unlock()
|
||||
|
||||
proxy.ConfigService.RemoveConfigListener(proxy.configListenerId)
|
||||
}
|
||||
|
||||
func (proxy *ImageProxy) OnConfigChange(oldConfig, newConfig *model.Config) {
|
||||
if *oldConfig.ImageProxySettings.Enable != *newConfig.ImageProxySettings.Enable ||
|
||||
*oldConfig.ImageProxySettings.ImageProxyType != *newConfig.ImageProxySettings.ImageProxyType {
|
||||
proxy.lock.Lock()
|
||||
defer proxy.lock.Unlock()
|
||||
|
||||
proxy.backend = proxy.makeBackend(*newConfig.ImageProxySettings.Enable, *newConfig.ImageProxySettings.ImageProxyType)
|
||||
}
|
||||
}
|
||||
|
||||
// GetImage takes an HTTP request for an image and requests that image using the image proxy.
|
||||
func (proxy *ImageProxy) GetImage(w http.ResponseWriter, r *http.Request, imageURL string) {
|
||||
proxy.lock.RLock()
|
||||
defer proxy.lock.RUnlock()
|
||||
|
||||
if proxy.backend == nil {
|
||||
w.WriteHeader(http.StatusNotImplemented)
|
||||
return
|
||||
}
|
||||
|
||||
proxy.backend.GetImage(w, r, imageURL)
|
||||
}
|
||||
|
||||
// GetProxiedImageURL takes the URL of an image and returns a URL that can be used to view that image through the
|
||||
// image proxy.
|
||||
func (proxy *ImageProxy) GetProxiedImageURL(imageURL string) string {
|
||||
proxy.lock.RLock()
|
||||
defer proxy.lock.RUnlock()
|
||||
|
||||
if proxy.backend == nil {
|
||||
return imageURL
|
||||
}
|
||||
|
||||
return proxy.backend.GetProxiedImageURL(imageURL)
|
||||
}
|
||||
|
||||
// GetUnproxiedImageURL takes the URL of an image on the image proxy and returns the original URL of the image.
|
||||
func (proxy *ImageProxy) GetUnproxiedImageURL(proxiedURL string) string {
|
||||
proxy.lock.RLock()
|
||||
defer proxy.lock.RUnlock()
|
||||
|
||||
if proxy.backend == nil {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
return proxy.backend.GetUnproxiedImageURL(proxiedURL)
|
||||
}
|
||||
99
services/imageproxy/local.go
Обычный файл
99
services/imageproxy/local.go
Обычный файл
@@ -0,0 +1,99 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/mlog"
|
||||
"github.com/mattermost/mattermost-server/services/httpservice"
|
||||
"willnorris.com/go/imageproxy"
|
||||
)
|
||||
|
||||
var imageContentTypes = []string{
|
||||
"image/bmp", "image/cgm", "image/g3fax", "image/gif", "image/ief", "image/jp2",
|
||||
"image/jpeg", "image/jpg", "image/pict", "image/png", "image/prs.btif", "image/svg+xml",
|
||||
"image/tiff", "image/vnd.adobe.photoshop", "image/vnd.djvu", "image/vnd.dwg",
|
||||
"image/vnd.dxf", "image/vnd.fastbidsheet", "image/vnd.fpx", "image/vnd.fst",
|
||||
"image/vnd.fujixerox.edmics-mmr", "image/vnd.fujixerox.edmics-rlc",
|
||||
"image/vnd.microsoft.icon", "image/vnd.ms-modi", "image/vnd.net-fpx", "image/vnd.wap.wbmp",
|
||||
"image/vnd.xiff", "image/webp", "image/x-cmu-raster", "image/x-cmx", "image/x-icon",
|
||||
"image/x-macpaint", "image/x-pcx", "image/x-pict", "image/x-portable-anymap",
|
||||
"image/x-portable-bitmap", "image/x-portable-graymap", "image/x-portable-pixmap",
|
||||
"image/x-quicktime", "image/x-rgb", "image/x-xbitmap", "image/x-xpixmap", "image/x-xwindowdump",
|
||||
}
|
||||
|
||||
type LocalBackend struct {
|
||||
proxy *ImageProxy
|
||||
|
||||
// The underlying image proxy implementation provided by the third party library
|
||||
impl *imageproxy.Proxy
|
||||
}
|
||||
|
||||
func makeLocalBackend(proxy *ImageProxy) *LocalBackend {
|
||||
impl := imageproxy.NewProxy(proxy.HTTPService.MakeTransport(false), nil)
|
||||
|
||||
baseURL, err := url.Parse(*proxy.ConfigService.Config().ServiceSettings.SiteURL)
|
||||
if err != nil {
|
||||
mlog.Error("Failed to set base URL for image proxy. Relative image links may not work.", mlog.Err(err))
|
||||
} else {
|
||||
impl.DefaultBaseURL = baseURL
|
||||
}
|
||||
|
||||
impl.Timeout = time.Duration(httpservice.RequestTimeout)
|
||||
impl.ContentTypes = imageContentTypes
|
||||
|
||||
return &LocalBackend{
|
||||
proxy: proxy,
|
||||
impl: impl,
|
||||
}
|
||||
}
|
||||
|
||||
func (backend *LocalBackend) GetImage(w http.ResponseWriter, r *http.Request, imageURL string) {
|
||||
// The interface to the proxy only exposes a ServeHTTP method, so fake a request to it
|
||||
req, err := http.NewRequest(http.MethodGet, "/"+imageURL, nil)
|
||||
if err != nil {
|
||||
// http.NewRequest should only return an error on an invalid URL
|
||||
mlog.Error("Failed to create request for proxied image", mlog.String("url", imageURL), mlog.Err(err))
|
||||
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte{})
|
||||
return
|
||||
}
|
||||
|
||||
backend.impl.ServeHTTP(w, req)
|
||||
}
|
||||
|
||||
func (backend *LocalBackend) GetProxiedImageURL(imageURL string) string {
|
||||
siteURL := *backend.proxy.ConfigService.Config().ServiceSettings.SiteURL
|
||||
|
||||
if imageURL == "" || imageURL[0] == '/' || strings.HasPrefix(imageURL, siteURL) {
|
||||
return imageURL
|
||||
}
|
||||
|
||||
return siteURL + "/api/v4/image?url=" + url.QueryEscape(imageURL)
|
||||
}
|
||||
|
||||
func (backend *LocalBackend) GetUnproxiedImageURL(proxiedURL string) string {
|
||||
siteURL := *backend.proxy.ConfigService.Config().ServiceSettings.SiteURL
|
||||
|
||||
if !strings.HasPrefix(proxiedURL, siteURL+"/api/v4/image?url=") {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
parsed, err := url.Parse(proxiedURL)
|
||||
if err != nil {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
u := parsed.Query()["url"]
|
||||
if len(u) == 0 {
|
||||
return proxiedURL
|
||||
}
|
||||
|
||||
return u[0]
|
||||
}
|
||||
243
services/imageproxy/local_test.go
Обычный файл
243
services/imageproxy/local_test.go
Обычный файл
@@ -0,0 +1,243 @@
|
||||
// Copyright (c) 2017-present Mattermost, Inc. All Rights Reserved.
|
||||
// See License.txt for license information.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/mattermost/mattermost-server/model"
|
||||
"github.com/mattermost/mattermost-server/services/httpservice"
|
||||
"github.com/mattermost/mattermost-server/utils/testutils"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func makeTestLocalProxy() *ImageProxy {
|
||||
configService := &testutils.StaticConfigService{
|
||||
Cfg: &model.Config{
|
||||
ServiceSettings: model.ServiceSettings{
|
||||
SiteURL: model.NewString("https://mattermost.example.com"),
|
||||
AllowedUntrustedInternalConnections: model.NewString("127.0.0.1"),
|
||||
},
|
||||
ImageProxySettings: model.ImageProxySettings{
|
||||
Enable: model.NewBool(true),
|
||||
ImageProxyType: model.NewString(model.IMAGE_PROXY_TYPE_LOCAL),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
return MakeImageProxy(configService, httpservice.MakeHTTPService(configService))
|
||||
}
|
||||
|
||||
func TestLocalBackend_GetImage(t *testing.T) {
|
||||
t.Run("image", func(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "max-age=2592000, private")
|
||||
w.Header().Set("Content-Type", "image/png")
|
||||
w.Header().Set("Content-Length", "10")
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("1111111111"))
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/image.png")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
assert.Equal(t, "max-age=2592000, private", resp.Header.Get("Cache-Control"))
|
||||
assert.Equal(t, "10", resp.Header.Get("Content-Length"))
|
||||
|
||||
respBody, _ := ioutil.ReadAll(resp.Body)
|
||||
assert.Equal(t, []byte("1111111111"), respBody)
|
||||
})
|
||||
|
||||
t.Run("not an image", func(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotAcceptable)
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/file.pdf")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusNotAcceptable, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("not an image, but remote server ignores accept header", func(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Cache-Control", "max-age=2592000, private")
|
||||
w.Header().Set("Content-Type", "application/pdf")
|
||||
w.Header().Set("Content-Length", "10")
|
||||
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte("1111111111"))
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/file.pdf")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusForbidden, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("not found", func(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/image.png")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusNotFound, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("other server error", func(t *testing.T) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/image.png")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusInternalServerError, resp.StatusCode)
|
||||
})
|
||||
|
||||
t.Run("timeout", func(t *testing.T) {
|
||||
wait := make(chan bool, 1)
|
||||
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
<-wait
|
||||
})
|
||||
|
||||
mock := httptest.NewServer(handler)
|
||||
defer mock.Close()
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
// Modify the timeout to be much shorter than the default 30 seconds
|
||||
proxy.backend.(*LocalBackend).impl.Timeout = time.Millisecond
|
||||
|
||||
recorder := httptest.NewRecorder()
|
||||
request, _ := http.NewRequest(http.MethodGet, "", nil)
|
||||
proxy.GetImage(recorder, request, mock.URL+"/image.png")
|
||||
resp := recorder.Result()
|
||||
|
||||
require.Equal(t, http.StatusGatewayTimeout, resp.StatusCode)
|
||||
|
||||
wait <- true
|
||||
})
|
||||
}
|
||||
|
||||
func TestLocalBackend_GetProxiedImageURL(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontal.png"
|
||||
proxiedURL := "https://mattermost.example.com/api/v4/image?url=http%3A%2F%2Fwww.mattermost.org%2Fwp-content%2Fuploads%2F2016%2F03%2FlogoHorizontal.png"
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
for _, test := range []struct {
|
||||
Name string
|
||||
Input string
|
||||
Expected string
|
||||
}{
|
||||
{
|
||||
Name: "should proxy image",
|
||||
Input: imageURL,
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
{
|
||||
Name: "should not proxy a relative image",
|
||||
Input: "/static/logo.png",
|
||||
Expected: "/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not proxy an image on the Mattermost server",
|
||||
Input: "https://mattermost.example.com/static/logo.png",
|
||||
Expected: "https://mattermost.example.com/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not proxy an image that has already been proxied",
|
||||
Input: proxiedURL,
|
||||
Expected: proxiedURL,
|
||||
},
|
||||
} {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
assert.Equal(t, test.Expected, proxy.GetProxiedImageURL(test.Input))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalBackend_GetUnproxiedImageURL(t *testing.T) {
|
||||
imageURL := "http://www.mattermost.org/wp-content/uploads/2016/03/logoHorizontal.png"
|
||||
proxiedURL := "https://mattermost.example.com/api/v4/image?url=http%3A%2F%2Fwww.mattermost.org%2Fwp-content%2Fuploads%2F2016%2F03%2FlogoHorizontal.png"
|
||||
|
||||
proxy := makeTestLocalProxy()
|
||||
|
||||
for _, test := range []struct {
|
||||
Name string
|
||||
Input string
|
||||
Expected string
|
||||
}{
|
||||
{
|
||||
Name: "should remove proxy",
|
||||
Input: proxiedURL,
|
||||
Expected: imageURL,
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from a relative image",
|
||||
Input: "/static/logo.png",
|
||||
Expected: "/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from an image on the Mattermost server",
|
||||
Input: "https://mattermost.example.com/static/logo.png",
|
||||
Expected: "https://mattermost.example.com/static/logo.png",
|
||||
},
|
||||
{
|
||||
Name: "should not remove proxy from a non-proxied image",
|
||||
Input: imageURL,
|
||||
Expected: imageURL,
|
||||
},
|
||||
} {
|
||||
t.Run(test.Name, func(t *testing.T) {
|
||||
assert.Equal(t, test.Expected, proxy.GetUnproxiedImageURL(test.Input))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -648,8 +648,7 @@ func GenerateLimitedClientConfig(c *model.Config, diagnosticId string, license *
|
||||
props["DiagnosticId"] = diagnosticId
|
||||
props["DiagnosticsEnabled"] = strconv.FormatBool(*c.LogSettings.EnableDiagnostics)
|
||||
|
||||
hasImageProxy := c.ServiceSettings.ImageProxyType != nil && *c.ServiceSettings.ImageProxyType != "" && c.ServiceSettings.ImageProxyURL != nil && *c.ServiceSettings.ImageProxyURL != ""
|
||||
props["HasImageProxy"] = strconv.FormatBool(hasImageProxy)
|
||||
props["HasImageProxy"] = strconv.FormatBool(*c.ImageProxySettings.Enable)
|
||||
|
||||
props["PluginsEnabled"] = strconv.FormatBool(*c.PluginSettings.Enable)
|
||||
|
||||
|
||||
19
vendor/github.com/gregjones/httpcache/.travis.yml
сгенерированный
поставляемый
Обычный файл
19
vendor/github.com/gregjones/httpcache/.travis.yml
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,19 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.6.x
|
||||
- 1.7.x
|
||||
- 1.8.x
|
||||
- 1.9.x
|
||||
- master
|
||||
matrix:
|
||||
allow_failures:
|
||||
- go: master
|
||||
fast_finish: true
|
||||
install:
|
||||
- # Do nothing. This is needed to prevent default install action "go get -t -v ./..." from happening here (we want it to happen inside script step).
|
||||
script:
|
||||
- go get -t -v ./...
|
||||
- diff -u <(echo -n) <(gofmt -d .)
|
||||
- go tool vet .
|
||||
- go test -v -race ./...
|
||||
7
vendor/github.com/gregjones/httpcache/LICENSE.txt
сгенерированный
поставляемый
Обычный файл
7
vendor/github.com/gregjones/httpcache/LICENSE.txt
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,7 @@
|
||||
Copyright © 2012 Greg Jones (greg.jones@gmail.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
25
vendor/github.com/gregjones/httpcache/README.md
сгенерированный
поставляемый
Обычный файл
25
vendor/github.com/gregjones/httpcache/README.md
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,25 @@
|
||||
httpcache
|
||||
=========
|
||||
|
||||
[](https://travis-ci.org/gregjones/httpcache) [](https://godoc.org/github.com/gregjones/httpcache)
|
||||
|
||||
Package httpcache provides a http.RoundTripper implementation that works as a mostly [RFC 7234](https://tools.ietf.org/html/rfc7234) compliant cache for http responses.
|
||||
|
||||
It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client and not for a shared proxy).
|
||||
|
||||
Cache Backends
|
||||
--------------
|
||||
|
||||
- The built-in 'memory' cache stores responses in an in-memory map.
|
||||
- [`github.com/gregjones/httpcache/diskcache`](https://github.com/gregjones/httpcache/tree/master/diskcache) provides a filesystem-backed cache using the [diskv](https://github.com/peterbourgon/diskv) library.
|
||||
- [`github.com/gregjones/httpcache/memcache`](https://github.com/gregjones/httpcache/tree/master/memcache) provides memcache implementations, for both App Engine and 'normal' memcache servers.
|
||||
- [`sourcegraph.com/sourcegraph/s3cache`](https://sourcegraph.com/github.com/sourcegraph/s3cache) uses Amazon S3 for storage.
|
||||
- [`github.com/gregjones/httpcache/leveldbcache`](https://github.com/gregjones/httpcache/tree/master/leveldbcache) provides a filesystem-backed cache using [leveldb](https://github.com/syndtr/goleveldb/leveldb).
|
||||
- [`github.com/die-net/lrucache`](https://github.com/die-net/lrucache) provides an in-memory cache that will evict least-recently used entries.
|
||||
- [`github.com/die-net/lrucache/twotier`](https://github.com/die-net/lrucache/tree/master/twotier) allows caches to be combined, for example to use lrucache above with a persistent disk-cache.
|
||||
- [`github.com/birkelund/boltdbcache`](https://github.com/birkelund/boltdbcache) provides a BoltDB implementation (based on the [bbolt](https://github.com/coreos/bbolt) fork).
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
- [MIT License](LICENSE.txt)
|
||||
551
vendor/github.com/gregjones/httpcache/httpcache.go
сгенерированный
поставляемый
Обычный файл
551
vendor/github.com/gregjones/httpcache/httpcache.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,551 @@
|
||||
// Package httpcache provides a http.RoundTripper implementation that works as a
|
||||
// mostly RFC-compliant cache for http responses.
|
||||
//
|
||||
// It is only suitable for use as a 'private' cache (i.e. for a web-browser or an API-client
|
||||
// and not for a shared proxy).
|
||||
//
|
||||
package httpcache
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net/http"
|
||||
"net/http/httputil"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
stale = iota
|
||||
fresh
|
||||
transparent
|
||||
// XFromCache is the header added to responses that are returned from the cache
|
||||
XFromCache = "X-From-Cache"
|
||||
)
|
||||
|
||||
// A Cache interface is used by the Transport to store and retrieve responses.
|
||||
type Cache interface {
|
||||
// Get returns the []byte representation of a cached response and a bool
|
||||
// set to true if the value isn't empty
|
||||
Get(key string) (responseBytes []byte, ok bool)
|
||||
// Set stores the []byte representation of a response against a key
|
||||
Set(key string, responseBytes []byte)
|
||||
// Delete removes the value associated with the key
|
||||
Delete(key string)
|
||||
}
|
||||
|
||||
// cacheKey returns the cache key for req.
|
||||
func cacheKey(req *http.Request) string {
|
||||
if req.Method == http.MethodGet {
|
||||
return req.URL.String()
|
||||
} else {
|
||||
return req.Method + " " + req.URL.String()
|
||||
}
|
||||
}
|
||||
|
||||
// CachedResponse returns the cached http.Response for req if present, and nil
|
||||
// otherwise.
|
||||
func CachedResponse(c Cache, req *http.Request) (resp *http.Response, err error) {
|
||||
cachedVal, ok := c.Get(cacheKey(req))
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
b := bytes.NewBuffer(cachedVal)
|
||||
return http.ReadResponse(bufio.NewReader(b), req)
|
||||
}
|
||||
|
||||
// MemoryCache is an implemtation of Cache that stores responses in an in-memory map.
|
||||
type MemoryCache struct {
|
||||
mu sync.RWMutex
|
||||
items map[string][]byte
|
||||
}
|
||||
|
||||
// Get returns the []byte representation of the response and true if present, false if not
|
||||
func (c *MemoryCache) Get(key string) (resp []byte, ok bool) {
|
||||
c.mu.RLock()
|
||||
resp, ok = c.items[key]
|
||||
c.mu.RUnlock()
|
||||
return resp, ok
|
||||
}
|
||||
|
||||
// Set saves response resp to the cache with key
|
||||
func (c *MemoryCache) Set(key string, resp []byte) {
|
||||
c.mu.Lock()
|
||||
c.items[key] = resp
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// Delete removes key from the cache
|
||||
func (c *MemoryCache) Delete(key string) {
|
||||
c.mu.Lock()
|
||||
delete(c.items, key)
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
// NewMemoryCache returns a new Cache that will store items in an in-memory map
|
||||
func NewMemoryCache() *MemoryCache {
|
||||
c := &MemoryCache{items: map[string][]byte{}}
|
||||
return c
|
||||
}
|
||||
|
||||
// Transport is an implementation of http.RoundTripper that will return values from a cache
|
||||
// where possible (avoiding a network request) and will additionally add validators (etag/if-modified-since)
|
||||
// to repeated requests allowing servers to return 304 / Not Modified
|
||||
type Transport struct {
|
||||
// The RoundTripper interface actually used to make requests
|
||||
// If nil, http.DefaultTransport is used
|
||||
Transport http.RoundTripper
|
||||
Cache Cache
|
||||
// If true, responses returned from the cache will be given an extra header, X-From-Cache
|
||||
MarkCachedResponses bool
|
||||
}
|
||||
|
||||
// NewTransport returns a new Transport with the
|
||||
// provided Cache implementation and MarkCachedResponses set to true
|
||||
func NewTransport(c Cache) *Transport {
|
||||
return &Transport{Cache: c, MarkCachedResponses: true}
|
||||
}
|
||||
|
||||
// Client returns an *http.Client that caches responses.
|
||||
func (t *Transport) Client() *http.Client {
|
||||
return &http.Client{Transport: t}
|
||||
}
|
||||
|
||||
// varyMatches will return false unless all of the cached values for the headers listed in Vary
|
||||
// match the new request
|
||||
func varyMatches(cachedResp *http.Response, req *http.Request) bool {
|
||||
for _, header := range headerAllCommaSepValues(cachedResp.Header, "vary") {
|
||||
header = http.CanonicalHeaderKey(header)
|
||||
if header != "" && req.Header.Get(header) != cachedResp.Header.Get("X-Varied-"+header) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// RoundTrip takes a Request and returns a Response
|
||||
//
|
||||
// If there is a fresh Response already in cache, then it will be returned without connecting to
|
||||
// the server.
|
||||
//
|
||||
// If there is a stale Response, then any validators it contains will be set on the new request
|
||||
// to give the server a chance to respond with NotModified. If this happens, then the cached Response
|
||||
// will be returned.
|
||||
func (t *Transport) RoundTrip(req *http.Request) (resp *http.Response, err error) {
|
||||
cacheKey := cacheKey(req)
|
||||
cacheable := (req.Method == "GET" || req.Method == "HEAD") && req.Header.Get("range") == ""
|
||||
var cachedResp *http.Response
|
||||
if cacheable {
|
||||
cachedResp, err = CachedResponse(t.Cache, req)
|
||||
} else {
|
||||
// Need to invalidate an existing value
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
|
||||
transport := t.Transport
|
||||
if transport == nil {
|
||||
transport = http.DefaultTransport
|
||||
}
|
||||
|
||||
if cacheable && cachedResp != nil && err == nil {
|
||||
if t.MarkCachedResponses {
|
||||
cachedResp.Header.Set(XFromCache, "1")
|
||||
}
|
||||
|
||||
if varyMatches(cachedResp, req) {
|
||||
// Can only use cached value if the new request doesn't Vary significantly
|
||||
freshness := getFreshness(cachedResp.Header, req.Header)
|
||||
if freshness == fresh {
|
||||
return cachedResp, nil
|
||||
}
|
||||
|
||||
if freshness == stale {
|
||||
var req2 *http.Request
|
||||
// Add validators if caller hasn't already done so
|
||||
etag := cachedResp.Header.Get("etag")
|
||||
if etag != "" && req.Header.Get("etag") == "" {
|
||||
req2 = cloneRequest(req)
|
||||
req2.Header.Set("if-none-match", etag)
|
||||
}
|
||||
lastModified := cachedResp.Header.Get("last-modified")
|
||||
if lastModified != "" && req.Header.Get("last-modified") == "" {
|
||||
if req2 == nil {
|
||||
req2 = cloneRequest(req)
|
||||
}
|
||||
req2.Header.Set("if-modified-since", lastModified)
|
||||
}
|
||||
if req2 != nil {
|
||||
req = req2
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
resp, err = transport.RoundTrip(req)
|
||||
if err == nil && req.Method == "GET" && resp.StatusCode == http.StatusNotModified {
|
||||
// Replace the 304 response with the one from cache, but update with some new headers
|
||||
endToEndHeaders := getEndToEndHeaders(resp.Header)
|
||||
for _, header := range endToEndHeaders {
|
||||
cachedResp.Header[header] = resp.Header[header]
|
||||
}
|
||||
resp = cachedResp
|
||||
} else if (err != nil || (cachedResp != nil && resp.StatusCode >= 500)) &&
|
||||
req.Method == "GET" && canStaleOnError(cachedResp.Header, req.Header) {
|
||||
// In case of transport failure and stale-if-error activated, returns cached content
|
||||
// when available
|
||||
return cachedResp, nil
|
||||
} else {
|
||||
if err != nil || resp.StatusCode != http.StatusOK {
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
} else {
|
||||
reqCacheControl := parseCacheControl(req.Header)
|
||||
if _, ok := reqCacheControl["only-if-cached"]; ok {
|
||||
resp = newGatewayTimeoutResponse(req)
|
||||
} else {
|
||||
resp, err = transport.RoundTrip(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if cacheable && canStore(parseCacheControl(req.Header), parseCacheControl(resp.Header)) {
|
||||
for _, varyKey := range headerAllCommaSepValues(resp.Header, "vary") {
|
||||
varyKey = http.CanonicalHeaderKey(varyKey)
|
||||
fakeHeader := "X-Varied-" + varyKey
|
||||
reqValue := req.Header.Get(varyKey)
|
||||
if reqValue != "" {
|
||||
resp.Header.Set(fakeHeader, reqValue)
|
||||
}
|
||||
}
|
||||
switch req.Method {
|
||||
case "GET":
|
||||
// Delay caching until EOF is reached.
|
||||
resp.Body = &cachingReadCloser{
|
||||
R: resp.Body,
|
||||
OnEOF: func(r io.Reader) {
|
||||
resp := *resp
|
||||
resp.Body = ioutil.NopCloser(r)
|
||||
respBytes, err := httputil.DumpResponse(&resp, true)
|
||||
if err == nil {
|
||||
t.Cache.Set(cacheKey, respBytes)
|
||||
}
|
||||
},
|
||||
}
|
||||
default:
|
||||
respBytes, err := httputil.DumpResponse(resp, true)
|
||||
if err == nil {
|
||||
t.Cache.Set(cacheKey, respBytes)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
t.Cache.Delete(cacheKey)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ErrNoDateHeader indicates that the HTTP headers contained no Date header.
|
||||
var ErrNoDateHeader = errors.New("no Date header")
|
||||
|
||||
// Date parses and returns the value of the Date header.
|
||||
func Date(respHeaders http.Header) (date time.Time, err error) {
|
||||
dateHeader := respHeaders.Get("date")
|
||||
if dateHeader == "" {
|
||||
err = ErrNoDateHeader
|
||||
return
|
||||
}
|
||||
|
||||
return time.Parse(time.RFC1123, dateHeader)
|
||||
}
|
||||
|
||||
type realClock struct{}
|
||||
|
||||
func (c *realClock) since(d time.Time) time.Duration {
|
||||
return time.Since(d)
|
||||
}
|
||||
|
||||
type timer interface {
|
||||
since(d time.Time) time.Duration
|
||||
}
|
||||
|
||||
var clock timer = &realClock{}
|
||||
|
||||
// getFreshness will return one of fresh/stale/transparent based on the cache-control
|
||||
// values of the request and the response
|
||||
//
|
||||
// fresh indicates the response can be returned
|
||||
// stale indicates that the response needs validating before it is returned
|
||||
// transparent indicates the response should not be used to fulfil the request
|
||||
//
|
||||
// Because this is only a private cache, 'public' and 'private' in cache-control aren't
|
||||
// signficant. Similarly, smax-age isn't used.
|
||||
func getFreshness(respHeaders, reqHeaders http.Header) (freshness int) {
|
||||
respCacheControl := parseCacheControl(respHeaders)
|
||||
reqCacheControl := parseCacheControl(reqHeaders)
|
||||
if _, ok := reqCacheControl["no-cache"]; ok {
|
||||
return transparent
|
||||
}
|
||||
if _, ok := respCacheControl["no-cache"]; ok {
|
||||
return stale
|
||||
}
|
||||
if _, ok := reqCacheControl["only-if-cached"]; ok {
|
||||
return fresh
|
||||
}
|
||||
|
||||
date, err := Date(respHeaders)
|
||||
if err != nil {
|
||||
return stale
|
||||
}
|
||||
currentAge := clock.since(date)
|
||||
|
||||
var lifetime time.Duration
|
||||
var zeroDuration time.Duration
|
||||
|
||||
// If a response includes both an Expires header and a max-age directive,
|
||||
// the max-age directive overrides the Expires header, even if the Expires header is more restrictive.
|
||||
if maxAge, ok := respCacheControl["max-age"]; ok {
|
||||
lifetime, err = time.ParseDuration(maxAge + "s")
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
}
|
||||
} else {
|
||||
expiresHeader := respHeaders.Get("Expires")
|
||||
if expiresHeader != "" {
|
||||
expires, err := time.Parse(time.RFC1123, expiresHeader)
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
} else {
|
||||
lifetime = expires.Sub(date)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if maxAge, ok := reqCacheControl["max-age"]; ok {
|
||||
// the client is willing to accept a response whose age is no greater than the specified time in seconds
|
||||
lifetime, err = time.ParseDuration(maxAge + "s")
|
||||
if err != nil {
|
||||
lifetime = zeroDuration
|
||||
}
|
||||
}
|
||||
if minfresh, ok := reqCacheControl["min-fresh"]; ok {
|
||||
// the client wants a response that will still be fresh for at least the specified number of seconds.
|
||||
minfreshDuration, err := time.ParseDuration(minfresh + "s")
|
||||
if err == nil {
|
||||
currentAge = time.Duration(currentAge + minfreshDuration)
|
||||
}
|
||||
}
|
||||
|
||||
if maxstale, ok := reqCacheControl["max-stale"]; ok {
|
||||
// Indicates that the client is willing to accept a response that has exceeded its expiration time.
|
||||
// If max-stale is assigned a value, then the client is willing to accept a response that has exceeded
|
||||
// its expiration time by no more than the specified number of seconds.
|
||||
// If no value is assigned to max-stale, then the client is willing to accept a stale response of any age.
|
||||
//
|
||||
// Responses served only because of a max-stale value are supposed to have a Warning header added to them,
|
||||
// but that seems like a hassle, and is it actually useful? If so, then there needs to be a different
|
||||
// return-value available here.
|
||||
if maxstale == "" {
|
||||
return fresh
|
||||
}
|
||||
maxstaleDuration, err := time.ParseDuration(maxstale + "s")
|
||||
if err == nil {
|
||||
currentAge = time.Duration(currentAge - maxstaleDuration)
|
||||
}
|
||||
}
|
||||
|
||||
if lifetime > currentAge {
|
||||
return fresh
|
||||
}
|
||||
|
||||
return stale
|
||||
}
|
||||
|
||||
// Returns true if either the request or the response includes the stale-if-error
|
||||
// cache control extension: https://tools.ietf.org/html/rfc5861
|
||||
func canStaleOnError(respHeaders, reqHeaders http.Header) bool {
|
||||
respCacheControl := parseCacheControl(respHeaders)
|
||||
reqCacheControl := parseCacheControl(reqHeaders)
|
||||
|
||||
var err error
|
||||
lifetime := time.Duration(-1)
|
||||
|
||||
if staleMaxAge, ok := respCacheControl["stale-if-error"]; ok {
|
||||
if staleMaxAge != "" {
|
||||
lifetime, err = time.ParseDuration(staleMaxAge + "s")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
if staleMaxAge, ok := reqCacheControl["stale-if-error"]; ok {
|
||||
if staleMaxAge != "" {
|
||||
lifetime, err = time.ParseDuration(staleMaxAge + "s")
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
} else {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if lifetime >= 0 {
|
||||
date, err := Date(respHeaders)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
currentAge := clock.since(date)
|
||||
if lifetime > currentAge {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func getEndToEndHeaders(respHeaders http.Header) []string {
|
||||
// These headers are always hop-by-hop
|
||||
hopByHopHeaders := map[string]struct{}{
|
||||
"Connection": struct{}{},
|
||||
"Keep-Alive": struct{}{},
|
||||
"Proxy-Authenticate": struct{}{},
|
||||
"Proxy-Authorization": struct{}{},
|
||||
"Te": struct{}{},
|
||||
"Trailers": struct{}{},
|
||||
"Transfer-Encoding": struct{}{},
|
||||
"Upgrade": struct{}{},
|
||||
}
|
||||
|
||||
for _, extra := range strings.Split(respHeaders.Get("connection"), ",") {
|
||||
// any header listed in connection, if present, is also considered hop-by-hop
|
||||
if strings.Trim(extra, " ") != "" {
|
||||
hopByHopHeaders[http.CanonicalHeaderKey(extra)] = struct{}{}
|
||||
}
|
||||
}
|
||||
endToEndHeaders := []string{}
|
||||
for respHeader, _ := range respHeaders {
|
||||
if _, ok := hopByHopHeaders[respHeader]; !ok {
|
||||
endToEndHeaders = append(endToEndHeaders, respHeader)
|
||||
}
|
||||
}
|
||||
return endToEndHeaders
|
||||
}
|
||||
|
||||
func canStore(reqCacheControl, respCacheControl cacheControl) (canStore bool) {
|
||||
if _, ok := respCacheControl["no-store"]; ok {
|
||||
return false
|
||||
}
|
||||
if _, ok := reqCacheControl["no-store"]; ok {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func newGatewayTimeoutResponse(req *http.Request) *http.Response {
|
||||
var braw bytes.Buffer
|
||||
braw.WriteString("HTTP/1.1 504 Gateway Timeout\r\n\r\n")
|
||||
resp, err := http.ReadResponse(bufio.NewReader(&braw), req)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
// cloneRequest returns a clone of the provided *http.Request.
|
||||
// The clone is a shallow copy of the struct and its Header map.
|
||||
// (This function copyright goauth2 authors: https://code.google.com/p/goauth2)
|
||||
func cloneRequest(r *http.Request) *http.Request {
|
||||
// shallow copy of the struct
|
||||
r2 := new(http.Request)
|
||||
*r2 = *r
|
||||
// deep copy of the Header
|
||||
r2.Header = make(http.Header)
|
||||
for k, s := range r.Header {
|
||||
r2.Header[k] = s
|
||||
}
|
||||
return r2
|
||||
}
|
||||
|
||||
type cacheControl map[string]string
|
||||
|
||||
func parseCacheControl(headers http.Header) cacheControl {
|
||||
cc := cacheControl{}
|
||||
ccHeader := headers.Get("Cache-Control")
|
||||
for _, part := range strings.Split(ccHeader, ",") {
|
||||
part = strings.Trim(part, " ")
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
if strings.ContainsRune(part, '=') {
|
||||
keyval := strings.Split(part, "=")
|
||||
cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",")
|
||||
} else {
|
||||
cc[part] = ""
|
||||
}
|
||||
}
|
||||
return cc
|
||||
}
|
||||
|
||||
// headerAllCommaSepValues returns all comma-separated values (each
|
||||
// with whitespace trimmed) for header name in headers. According to
|
||||
// Section 4.2 of the HTTP/1.1 spec
|
||||
// (http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2),
|
||||
// values from multiple occurrences of a header should be concatenated, if
|
||||
// the header's value is a comma-separated list.
|
||||
func headerAllCommaSepValues(headers http.Header, name string) []string {
|
||||
var vals []string
|
||||
for _, val := range headers[http.CanonicalHeaderKey(name)] {
|
||||
fields := strings.Split(val, ",")
|
||||
for i, f := range fields {
|
||||
fields[i] = strings.TrimSpace(f)
|
||||
}
|
||||
vals = append(vals, fields...)
|
||||
}
|
||||
return vals
|
||||
}
|
||||
|
||||
// cachingReadCloser is a wrapper around ReadCloser R that calls OnEOF
|
||||
// handler with a full copy of the content read from R when EOF is
|
||||
// reached.
|
||||
type cachingReadCloser struct {
|
||||
// Underlying ReadCloser.
|
||||
R io.ReadCloser
|
||||
// OnEOF is called with a copy of the content of R when EOF is reached.
|
||||
OnEOF func(io.Reader)
|
||||
|
||||
buf bytes.Buffer // buf stores a copy of the content of R.
|
||||
}
|
||||
|
||||
// Read reads the next len(p) bytes from R or until R is drained. The
|
||||
// return value n is the number of bytes read. If R has no data to
|
||||
// return, err is io.EOF and OnEOF is called with a full copy of what
|
||||
// has been read so far.
|
||||
func (r *cachingReadCloser) Read(p []byte) (n int, err error) {
|
||||
n, err = r.R.Read(p)
|
||||
r.buf.Write(p[:n])
|
||||
if err == io.EOF {
|
||||
r.OnEOF(bytes.NewReader(r.buf.Bytes()))
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
|
||||
func (r *cachingReadCloser) Close() error {
|
||||
return r.R.Close()
|
||||
}
|
||||
|
||||
// NewMemoryCacheTransport returns a new Transport using the in-memory cache implementation
|
||||
func NewMemoryCacheTransport() *Transport {
|
||||
c := NewMemoryCache()
|
||||
t := NewTransport(c)
|
||||
return t
|
||||
}
|
||||
25
vendor/github.com/muesli/smartcrop/.gitignore
сгенерированный
поставляемый
Обычный файл
25
vendor/github.com/muesli/smartcrop/.gitignore
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,25 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
*.test
|
||||
|
||||
*~
|
||||
29
vendor/github.com/muesli/smartcrop/.travis.yml
сгенерированный
поставляемый
Обычный файл
29
vendor/github.com/muesli/smartcrop/.travis.yml
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,29 @@
|
||||
language: go
|
||||
|
||||
os:
|
||||
- linux
|
||||
- osx
|
||||
|
||||
go:
|
||||
- 1.4
|
||||
- 1.5
|
||||
- 1.6
|
||||
- 1.7
|
||||
- 1.8
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
- go get github.com/axw/gocov/gocov
|
||||
- go get github.com/mattn/goveralls
|
||||
# - sudo add-apt-repository -y ppa:kubuntu-ppa/backports
|
||||
# - sudo apt-get update -qq
|
||||
# - sudo apt-get install libcv-dev libopencv-dev libopencv-contrib-dev libhighgui-dev libopencv-photo-dev libopencv-imgproc-dev libopencv-stitching-dev libopencv-superres-dev libopencv-ts-dev libopencv-videostab-dev
|
||||
|
||||
script:
|
||||
- go test -v -tags ci ./...
|
||||
- $GOPATH/bin/goveralls -service=travis-ci
|
||||
|
||||
notifications:
|
||||
email:
|
||||
on_success: change
|
||||
on_failure: always
|
||||
21
vendor/github.com/muesli/smartcrop/LICENSE
сгенерированный
поставляемый
Обычный файл
21
vendor/github.com/muesli/smartcrop/LICENSE
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,21 @@
|
||||
The MIT License (MIT)
|
||||
|
||||
Copyright (c) 2014 Christian Muehlhaeuser
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
69
vendor/github.com/muesli/smartcrop/README.md
сгенерированный
поставляемый
Обычный файл
69
vendor/github.com/muesli/smartcrop/README.md
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,69 @@
|
||||
smartcrop
|
||||
=========
|
||||
|
||||
smartcrop finds good image crops for arbitrary sizes. It is a pure Go implementation, based on Jonas Wagner's [smartcrop.js](https://github.com/jwagner/smartcrop.js)
|
||||
|
||||

|
||||
Image: [https://www.flickr.com/photos/usfwspacific/8182486789](https://www.flickr.com/photos/usfwspacific/8182486789) CC BY U.S. Fish & Wildlife
|
||||
|
||||

|
||||
Image: [https://www.flickr.com/photos/endogamia/5682480447](https://www.flickr.com/photos/endogamia/5682480447) by N. Feans
|
||||
|
||||
## Installation
|
||||
|
||||
Make sure you have a working Go environment. See the [install instructions](http://golang.org/doc/install.html).
|
||||
|
||||
To install smartcrop, simply run:
|
||||
|
||||
go get github.com/muesli/smartcrop
|
||||
|
||||
To compile it from source:
|
||||
|
||||
cd $GOPATH/src/github.com/muesli/smartcrop
|
||||
go get -u -v
|
||||
go build && go test -v
|
||||
|
||||
## Example
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/png"
|
||||
"os"
|
||||
|
||||
"github.com/muesli/smartcrop"
|
||||
)
|
||||
|
||||
func main() {
|
||||
f, _ := os.Open("image.png")
|
||||
img, _, _ := image.Decode(f)
|
||||
|
||||
analyzer := smartcrop.NewAnalyzer()
|
||||
topCrop, _ := analyzer.FindBestCrop(img, 250, 250)
|
||||
|
||||
// The crop will have the requested aspect ratio, but you need to copy/scale it yourself
|
||||
fmt.Printf("Top crop: %+v\n", topCrop)
|
||||
|
||||
type SubImager interface {
|
||||
SubImage(r image.Rectangle) image.Image
|
||||
}
|
||||
croppedimg := img.(SubImager).SubImage(topCrop)
|
||||
...
|
||||
}
|
||||
```
|
||||
|
||||
Also see the test cases in crop_test.go for further working examples.
|
||||
|
||||
## Sample Data
|
||||
You can find a bunch of test images for the algorithm [here](https://github.com/muesli/smartcrop-samples).
|
||||
|
||||
## Development
|
||||
API docs can be found [here](http://godoc.org/github.com/muesli/smartcrop).
|
||||
|
||||
Join us on IRC: irc.freenode.net/#smartcrop
|
||||
|
||||
[](http://travis-ci.org/muesli/smartcrop)
|
||||
[](https://coveralls.io/github/muesli/smartcrop?branch=master)
|
||||
[](http://goreportcard.com/report/muesli/smartcrop)
|
||||
107
vendor/github.com/muesli/smartcrop/debug.go
сгенерированный
поставляемый
Обычный файл
107
vendor/github.com/muesli/smartcrop/debug.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,107 @@
|
||||
/*
|
||||
* Copyright (c) 2014 Christian Muehlhaeuser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* Authors:
|
||||
* Christian Muehlhaeuser <muesli@gmail.com>
|
||||
* Michael Wendland <michael@michiwend.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
Package smartcrop implements a content aware image cropping library based on
|
||||
Jonas Wagner's smartcrop.js https://github.com/jwagner/smartcrop.js
|
||||
*/
|
||||
package smartcrop
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
func debugOutput(debug bool, img *image.RGBA, debugType string) {
|
||||
if debug {
|
||||
writeImage("png", img, "./smartcrop_"+debugType+".png")
|
||||
}
|
||||
}
|
||||
|
||||
func writeImage(imgtype string, img image.Image, name string) error {
|
||||
if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
switch imgtype {
|
||||
case "png":
|
||||
return writeImageToPng(img, name)
|
||||
case "jpeg":
|
||||
return writeImageToJpeg(img, name)
|
||||
}
|
||||
|
||||
return errors.New("Unknown image type")
|
||||
}
|
||||
|
||||
func writeImageToJpeg(img image.Image, name string) error {
|
||||
fso, err := os.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fso.Close()
|
||||
|
||||
return jpeg.Encode(fso, img, &jpeg.Options{Quality: 100})
|
||||
}
|
||||
|
||||
func writeImageToPng(img image.Image, name string) error {
|
||||
fso, err := os.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer fso.Close()
|
||||
|
||||
return png.Encode(fso, img)
|
||||
}
|
||||
|
||||
func drawDebugCrop(topCrop Crop, o *image.RGBA) {
|
||||
width := o.Bounds().Dx()
|
||||
height := o.Bounds().Dy()
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
r, g, b, _ := o.At(x, y).RGBA()
|
||||
r8 := float64(r >> 8)
|
||||
g8 := float64(g >> 8)
|
||||
b8 := uint8(b >> 8)
|
||||
|
||||
imp := importance(topCrop, x, y)
|
||||
|
||||
if imp > 0 {
|
||||
g8 += imp * 32
|
||||
} else if imp < 0 {
|
||||
r8 += imp * -64
|
||||
}
|
||||
|
||||
nc := color.RGBA{uint8(bounds(r8)), uint8(bounds(g8)), b8, 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
}
|
||||
}
|
||||
}
|
||||
482
vendor/github.com/muesli/smartcrop/smartcrop.go
сгенерированный
поставляемый
Обычный файл
482
vendor/github.com/muesli/smartcrop/smartcrop.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,482 @@
|
||||
/*
|
||||
* Copyright (c) 2014-2017 Christian Muehlhaeuser
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to deal
|
||||
* in the Software without restriction, including without limitation the rights
|
||||
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
* copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
* SOFTWARE.
|
||||
*
|
||||
* Authors:
|
||||
* Christian Muehlhaeuser <muesli@gmail.com>
|
||||
* Michael Wendland <michael@michiwend.com>
|
||||
*/
|
||||
|
||||
/*
|
||||
Package smartcrop implements a content aware image cropping library based on
|
||||
Jonas Wagner's smartcrop.js https://github.com/jwagner/smartcrop.js
|
||||
*/
|
||||
package smartcrop
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"math"
|
||||
"time"
|
||||
|
||||
"golang.org/x/image/draw"
|
||||
|
||||
"github.com/nfnt/resize"
|
||||
)
|
||||
|
||||
var (
|
||||
// ErrInvalidDimensions gets returned when the supplied dimensions are invalid
|
||||
ErrInvalidDimensions = errors.New("Expect either a height or width")
|
||||
|
||||
skinColor = [3]float64{0.78, 0.57, 0.44}
|
||||
)
|
||||
|
||||
const (
|
||||
detailWeight = 0.2
|
||||
skinBias = 0.01
|
||||
skinBrightnessMin = 0.2
|
||||
skinBrightnessMax = 1.0
|
||||
skinThreshold = 0.8
|
||||
skinWeight = 1.8
|
||||
saturationBrightnessMin = 0.05
|
||||
saturationBrightnessMax = 0.9
|
||||
saturationThreshold = 0.4
|
||||
saturationBias = 0.2
|
||||
saturationWeight = 0.3
|
||||
scoreDownSample = 8 // step * minscale rounded down to the next power of two should be good
|
||||
step = 8
|
||||
scaleStep = 0.1
|
||||
minScale = 0.9
|
||||
maxScale = 1.0
|
||||
edgeRadius = 0.4
|
||||
edgeWeight = -20.0
|
||||
outsideImportance = -0.5
|
||||
ruleOfThirds = true
|
||||
prescale = true
|
||||
prescaleMin = 400.00
|
||||
)
|
||||
|
||||
// Analyzer interface analyzes its struct and returns the best possible crop with the given
|
||||
// width and height returns an error if invalid
|
||||
type Analyzer interface {
|
||||
FindBestCrop(img image.Image, width, height int) (image.Rectangle, error)
|
||||
}
|
||||
|
||||
// Score contains values that classify matches
|
||||
type Score struct {
|
||||
Detail float64
|
||||
Saturation float64
|
||||
Skin float64
|
||||
}
|
||||
|
||||
// Crop contains results
|
||||
type Crop struct {
|
||||
image.Rectangle
|
||||
Score Score
|
||||
}
|
||||
|
||||
// CropSettings contains options to change cropping behaviour
|
||||
type CropSettings struct {
|
||||
InterpolationType resize.InterpolationFunction
|
||||
DebugMode bool
|
||||
Log *log.Logger
|
||||
}
|
||||
|
||||
type smartcropAnalyzer struct {
|
||||
cropSettings CropSettings
|
||||
}
|
||||
|
||||
// NewAnalyzer returns a new analyzer with default settings
|
||||
func NewAnalyzer() Analyzer {
|
||||
cropSettings := CropSettings{
|
||||
InterpolationType: resize.Bicubic,
|
||||
DebugMode: false,
|
||||
}
|
||||
|
||||
return NewAnalyzerWithCropSettings(cropSettings)
|
||||
}
|
||||
|
||||
// NewAnalyzerWithCropSettings returns a new analyzer with the given settings
|
||||
func NewAnalyzerWithCropSettings(cropSettings CropSettings) Analyzer {
|
||||
if cropSettings.Log == nil {
|
||||
cropSettings.Log = log.New(ioutil.Discard, "", 0)
|
||||
}
|
||||
return &smartcropAnalyzer{cropSettings: cropSettings}
|
||||
}
|
||||
|
||||
func (o smartcropAnalyzer) FindBestCrop(img image.Image, width, height int) (image.Rectangle, error) {
|
||||
if width == 0 && height == 0 {
|
||||
return image.Rectangle{}, ErrInvalidDimensions
|
||||
}
|
||||
|
||||
// resize image for faster processing
|
||||
scale := math.Min(float64(img.Bounds().Dx())/float64(width), float64(img.Bounds().Dy())/float64(height))
|
||||
var lowimg *image.RGBA
|
||||
var prescalefactor = 1.0
|
||||
|
||||
if prescale {
|
||||
// if f := 1.0 / scale / minScale; f < 1.0 {
|
||||
// prescalefactor = f
|
||||
// }
|
||||
if f := prescaleMin / math.Min(float64(img.Bounds().Dx()), float64(img.Bounds().Dy())); f < 1.0 {
|
||||
prescalefactor = f
|
||||
}
|
||||
o.cropSettings.Log.Println(prescalefactor)
|
||||
|
||||
smallimg := resize.Resize(
|
||||
uint(float64(img.Bounds().Dx())*prescalefactor),
|
||||
0,
|
||||
img,
|
||||
o.cropSettings.InterpolationType)
|
||||
lowimg = toRGBA(smallimg)
|
||||
} else {
|
||||
lowimg = toRGBA(img)
|
||||
}
|
||||
|
||||
if o.cropSettings.DebugMode {
|
||||
writeImage("png", lowimg, "./smartcrop_prescale.png")
|
||||
}
|
||||
|
||||
cropWidth, cropHeight := chop(float64(width)*scale*prescalefactor), chop(float64(height)*scale*prescalefactor)
|
||||
realMinScale := math.Min(maxScale, math.Max(1.0/scale, minScale))
|
||||
|
||||
o.cropSettings.Log.Printf("original resolution: %dx%d\n", img.Bounds().Dx(), img.Bounds().Dy())
|
||||
o.cropSettings.Log.Printf("scale: %f, cropw: %f, croph: %f, minscale: %f\n", scale, cropWidth, cropHeight, realMinScale)
|
||||
|
||||
topCrop, err := analyse(o.cropSettings, lowimg, cropWidth, cropHeight, realMinScale)
|
||||
if err != nil {
|
||||
return topCrop, err
|
||||
}
|
||||
|
||||
if prescale == true {
|
||||
topCrop.Min.X = int(chop(float64(topCrop.Min.X) / prescalefactor))
|
||||
topCrop.Min.Y = int(chop(float64(topCrop.Min.Y) / prescalefactor))
|
||||
topCrop.Max.X = int(chop(float64(topCrop.Max.X) / prescalefactor))
|
||||
topCrop.Max.Y = int(chop(float64(topCrop.Max.Y) / prescalefactor))
|
||||
}
|
||||
|
||||
return topCrop.Canon(), nil
|
||||
}
|
||||
|
||||
func (c Crop) totalScore() float64 {
|
||||
return (c.Score.Detail*detailWeight + c.Score.Skin*skinWeight + c.Score.Saturation*saturationWeight) / float64(c.Dx()) / float64(c.Dy())
|
||||
}
|
||||
|
||||
func chop(x float64) float64 {
|
||||
if x < 0 {
|
||||
return math.Ceil(x)
|
||||
}
|
||||
return math.Floor(x)
|
||||
}
|
||||
|
||||
func thirds(x float64) float64 {
|
||||
x = (math.Mod(x-(1.0/3.0)+1.0, 2.0)*0.5 - 0.5) * 16.0
|
||||
return math.Max(1.0-x*x, 0.0)
|
||||
}
|
||||
|
||||
func bounds(l float64) float64 {
|
||||
return math.Min(math.Max(l, 0.0), 255)
|
||||
}
|
||||
|
||||
func importance(crop Crop, x, y int) float64 {
|
||||
if crop.Min.X > x || x >= crop.Max.X || crop.Min.Y > y || y >= crop.Max.Y {
|
||||
return outsideImportance
|
||||
}
|
||||
|
||||
xf := float64(x-crop.Min.X) / float64(crop.Dx())
|
||||
yf := float64(y-crop.Min.Y) / float64(crop.Dy())
|
||||
|
||||
px := math.Abs(0.5-xf) * 2.0
|
||||
py := math.Abs(0.5-yf) * 2.0
|
||||
|
||||
dx := math.Max(px-1.0+edgeRadius, 0.0)
|
||||
dy := math.Max(py-1.0+edgeRadius, 0.0)
|
||||
d := (dx*dx + dy*dy) * edgeWeight
|
||||
|
||||
s := 1.41 - math.Sqrt(px*px+py*py)
|
||||
if ruleOfThirds {
|
||||
s += (math.Max(0.0, s+d+0.5) * 1.2) * (thirds(px) + thirds(py))
|
||||
}
|
||||
|
||||
return s + d
|
||||
}
|
||||
|
||||
func score(output *image.RGBA, crop Crop) Score {
|
||||
width := output.Bounds().Dx()
|
||||
height := output.Bounds().Dy()
|
||||
score := Score{}
|
||||
|
||||
// same loops but with downsampling
|
||||
//for y := 0; y < height; y++ {
|
||||
//for x := 0; x < width; x++ {
|
||||
for y := 0; y <= height-scoreDownSample; y += scoreDownSample {
|
||||
for x := 0; x <= width-scoreDownSample; x += scoreDownSample {
|
||||
|
||||
c := output.RGBAAt(x, y)
|
||||
r8 := float64(c.R)
|
||||
g8 := float64(c.G)
|
||||
b8 := float64(c.B)
|
||||
|
||||
imp := importance(crop, int(x), int(y))
|
||||
det := g8 / 255.0
|
||||
|
||||
score.Skin += r8 / 255.0 * (det + skinBias) * imp
|
||||
score.Detail += det * imp
|
||||
score.Saturation += b8 / 255.0 * (det + saturationBias) * imp
|
||||
}
|
||||
}
|
||||
|
||||
return score
|
||||
}
|
||||
|
||||
func analyse(settings CropSettings, img *image.RGBA, cropWidth, cropHeight, realMinScale float64) (image.Rectangle, error) {
|
||||
o := image.NewRGBA(img.Bounds())
|
||||
|
||||
now := time.Now()
|
||||
edgeDetect(img, o)
|
||||
settings.Log.Println("Time elapsed edge:", time.Since(now))
|
||||
debugOutput(settings.DebugMode, o, "edge")
|
||||
|
||||
now = time.Now()
|
||||
skinDetect(img, o)
|
||||
settings.Log.Println("Time elapsed skin:", time.Since(now))
|
||||
debugOutput(settings.DebugMode, o, "skin")
|
||||
|
||||
now = time.Now()
|
||||
saturationDetect(img, o)
|
||||
settings.Log.Println("Time elapsed sat:", time.Since(now))
|
||||
debugOutput(settings.DebugMode, o, "saturation")
|
||||
|
||||
now = time.Now()
|
||||
var topCrop Crop
|
||||
topScore := -1.0
|
||||
cs := crops(o, cropWidth, cropHeight, realMinScale)
|
||||
settings.Log.Println("Time elapsed crops:", time.Since(now), len(cs))
|
||||
|
||||
now = time.Now()
|
||||
for _, crop := range cs {
|
||||
nowIn := time.Now()
|
||||
crop.Score = score(o, crop)
|
||||
settings.Log.Println("Time elapsed single-score:", time.Since(nowIn))
|
||||
if crop.totalScore() > topScore {
|
||||
topCrop = crop
|
||||
topScore = crop.totalScore()
|
||||
}
|
||||
}
|
||||
settings.Log.Println("Time elapsed score:", time.Since(now))
|
||||
|
||||
if settings.DebugMode {
|
||||
drawDebugCrop(topCrop, o)
|
||||
debugOutput(true, o, "final")
|
||||
}
|
||||
|
||||
return topCrop.Rectangle, nil
|
||||
}
|
||||
|
||||
func saturation(c color.RGBA) float64 {
|
||||
cMax, cMin := uint8(0), uint8(255)
|
||||
if c.R > cMax {
|
||||
cMax = c.R
|
||||
}
|
||||
if c.R < cMin {
|
||||
cMin = c.R
|
||||
}
|
||||
if c.G > cMax {
|
||||
cMax = c.G
|
||||
}
|
||||
if c.G < cMin {
|
||||
cMin = c.G
|
||||
}
|
||||
if c.B > cMax {
|
||||
cMax = c.B
|
||||
}
|
||||
if c.B < cMin {
|
||||
cMin = c.B
|
||||
}
|
||||
|
||||
if cMax == cMin {
|
||||
return 0
|
||||
}
|
||||
maximum := float64(cMax) / 255.0
|
||||
minimum := float64(cMin) / 255.0
|
||||
|
||||
l := (maximum + minimum) / 2.0
|
||||
d := maximum - minimum
|
||||
|
||||
if l > 0.5 {
|
||||
return d / (2.0 - maximum - minimum)
|
||||
}
|
||||
|
||||
return d / (maximum + minimum)
|
||||
}
|
||||
|
||||
func cie(c color.RGBA) float64 {
|
||||
return 0.5126*float64(c.B) + 0.7152*float64(c.G) + 0.0722*float64(c.R)
|
||||
}
|
||||
|
||||
func skinCol(c color.RGBA) float64 {
|
||||
r8, g8, b8 := float64(c.R), float64(c.G), float64(c.B)
|
||||
|
||||
mag := math.Sqrt(r8*r8 + g8*g8 + b8*b8)
|
||||
rd := r8/mag - skinColor[0]
|
||||
gd := g8/mag - skinColor[1]
|
||||
bd := b8/mag - skinColor[2]
|
||||
|
||||
d := math.Sqrt(rd*rd + gd*gd + bd*bd)
|
||||
return 1.0 - d
|
||||
}
|
||||
|
||||
func makeCies(img *image.RGBA) []float64 {
|
||||
width := img.Bounds().Dx()
|
||||
height := img.Bounds().Dy()
|
||||
cies := make([]float64, width*height, width*height)
|
||||
i := 0
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
cies[i] = cie(img.RGBAAt(x, y))
|
||||
i++
|
||||
}
|
||||
}
|
||||
|
||||
return cies
|
||||
}
|
||||
|
||||
func edgeDetect(i *image.RGBA, o *image.RGBA) {
|
||||
width := i.Bounds().Dx()
|
||||
height := i.Bounds().Dy()
|
||||
cies := makeCies(i)
|
||||
|
||||
var lightness float64
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
if x == 0 || x >= width-1 || y == 0 || y >= height-1 {
|
||||
//lightness = cie((*i).At(x, y))
|
||||
lightness = 0
|
||||
} else {
|
||||
lightness = cies[y*width+x]*4.0 -
|
||||
cies[x+(y-1)*width] -
|
||||
cies[x-1+y*width] -
|
||||
cies[x+1+y*width] -
|
||||
cies[x+(y+1)*width]
|
||||
}
|
||||
|
||||
nc := color.RGBA{0, uint8(bounds(lightness)), 0, 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func skinDetect(i *image.RGBA, o *image.RGBA) {
|
||||
width := i.Bounds().Dx()
|
||||
height := i.Bounds().Dy()
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
lightness := cie(i.RGBAAt(x, y)) / 255.0
|
||||
skin := skinCol(i.RGBAAt(x, y))
|
||||
|
||||
c := o.RGBAAt(x, y)
|
||||
if skin > skinThreshold && lightness >= skinBrightnessMin && lightness <= skinBrightnessMax {
|
||||
r := (skin - skinThreshold) * (255.0 / (1.0 - skinThreshold))
|
||||
nc := color.RGBA{uint8(bounds(r)), c.G, c.B, 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
} else {
|
||||
nc := color.RGBA{0, c.G, c.B, 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func saturationDetect(i *image.RGBA, o *image.RGBA) {
|
||||
width := i.Bounds().Dx()
|
||||
height := i.Bounds().Dy()
|
||||
|
||||
for y := 0; y < height; y++ {
|
||||
for x := 0; x < width; x++ {
|
||||
lightness := cie(i.RGBAAt(x, y)) / 255.0
|
||||
saturation := saturation(i.RGBAAt(x, y))
|
||||
|
||||
c := o.RGBAAt(x, y)
|
||||
if saturation > saturationThreshold && lightness >= saturationBrightnessMin && lightness <= saturationBrightnessMax {
|
||||
b := (saturation - saturationThreshold) * (255.0 / (1.0 - saturationThreshold))
|
||||
nc := color.RGBA{c.R, c.G, uint8(bounds(b)), 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
} else {
|
||||
nc := color.RGBA{c.R, c.G, 0, 255}
|
||||
o.SetRGBA(x, y, nc)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func crops(i image.Image, cropWidth, cropHeight, realMinScale float64) []Crop {
|
||||
res := []Crop{}
|
||||
width := i.Bounds().Dx()
|
||||
height := i.Bounds().Dy()
|
||||
|
||||
minDimension := math.Min(float64(width), float64(height))
|
||||
var cropW, cropH float64
|
||||
|
||||
if cropWidth != 0.0 {
|
||||
cropW = cropWidth
|
||||
} else {
|
||||
cropW = minDimension
|
||||
}
|
||||
if cropHeight != 0.0 {
|
||||
cropH = cropHeight
|
||||
} else {
|
||||
cropH = minDimension
|
||||
}
|
||||
|
||||
for scale := maxScale; scale >= realMinScale; scale -= scaleStep {
|
||||
for y := 0; float64(y)+cropH*scale <= float64(height); y += step {
|
||||
for x := 0; float64(x)+cropW*scale <= float64(width); x += step {
|
||||
res = append(res, Crop{
|
||||
Rectangle: image.Rect(x, y, x+int(cropW*scale), y+int(cropH*scale)),
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return res
|
||||
}
|
||||
|
||||
// toRGBA converts an image.Image to an image.RGBA
|
||||
func toRGBA(img image.Image) *image.RGBA {
|
||||
switch img.(type) {
|
||||
case *image.RGBA:
|
||||
return img.(*image.RGBA)
|
||||
}
|
||||
out := image.NewRGBA(img.Bounds())
|
||||
draw.Copy(out, image.Pt(0, 0), img, img.Bounds(), draw.Src, nil)
|
||||
return out
|
||||
}
|
||||
|
||||
// SmartCrop applies the smartcrop algorithms on the the given image and returns
|
||||
// the top crop or an error if something went wrong.
|
||||
// This is still here for legacy/backwards-compat reasons
|
||||
func SmartCrop(img image.Image, width, height int) (image.Rectangle, error) {
|
||||
analyzer := NewAnalyzer()
|
||||
return analyzer.FindBestCrop(img, width, height)
|
||||
}
|
||||
7
vendor/github.com/nfnt/resize/.travis.yml
сгенерированный
поставляемый
Обычный файл
7
vendor/github.com/nfnt/resize/.travis.yml
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,7 @@
|
||||
language: go
|
||||
|
||||
go:
|
||||
- "1.x"
|
||||
- "1.1"
|
||||
- "1.4"
|
||||
- "1.10"
|
||||
13
vendor/github.com/nfnt/resize/LICENSE
сгенерированный
поставляемый
Обычный файл
13
vendor/github.com/nfnt/resize/LICENSE
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,13 @@
|
||||
Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
151
vendor/github.com/nfnt/resize/README.md
сгенерированный
поставляемый
Обычный файл
151
vendor/github.com/nfnt/resize/README.md
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,151 @@
|
||||
# This package is no longer being updated! Please look for alternatives if that bothers you.
|
||||
|
||||
Resize
|
||||
======
|
||||
|
||||
Image resizing for the [Go programming language](http://golang.org) with common interpolation methods.
|
||||
|
||||
[](https://travis-ci.org/nfnt/resize)
|
||||
|
||||
Installation
|
||||
------------
|
||||
|
||||
```bash
|
||||
$ go get github.com/nfnt/resize
|
||||
```
|
||||
|
||||
It's that easy!
|
||||
|
||||
Usage
|
||||
-----
|
||||
|
||||
This package needs at least Go 1.1. Import package with
|
||||
|
||||
```go
|
||||
import "github.com/nfnt/resize"
|
||||
```
|
||||
|
||||
The resize package provides 2 functions:
|
||||
|
||||
* `resize.Resize` creates a scaled image with new dimensions (`width`, `height`) using the interpolation function `interp`.
|
||||
If either `width` or `height` is set to 0, it will be set to an aspect ratio preserving value.
|
||||
* `resize.Thumbnail` downscales an image preserving its aspect ratio to the maximum dimensions (`maxWidth`, `maxHeight`).
|
||||
It will return the original image if original sizes are smaller than the provided dimensions.
|
||||
|
||||
```go
|
||||
resize.Resize(width, height uint, img image.Image, interp resize.InterpolationFunction) image.Image
|
||||
resize.Thumbnail(maxWidth, maxHeight uint, img image.Image, interp resize.InterpolationFunction) image.Image
|
||||
```
|
||||
|
||||
The provided interpolation functions are (from fast to slow execution time)
|
||||
|
||||
- `NearestNeighbor`: [Nearest-neighbor interpolation](http://en.wikipedia.org/wiki/Nearest-neighbor_interpolation)
|
||||
- `Bilinear`: [Bilinear interpolation](http://en.wikipedia.org/wiki/Bilinear_interpolation)
|
||||
- `Bicubic`: [Bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation)
|
||||
- `MitchellNetravali`: [Mitchell-Netravali interpolation](http://dl.acm.org/citation.cfm?id=378514)
|
||||
- `Lanczos2`: [Lanczos resampling](http://en.wikipedia.org/wiki/Lanczos_resampling) with a=2
|
||||
- `Lanczos3`: [Lanczos resampling](http://en.wikipedia.org/wiki/Lanczos_resampling) with a=3
|
||||
|
||||
Which of these methods gives the best results depends on your use case.
|
||||
|
||||
Sample usage:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/nfnt/resize"
|
||||
"image/jpeg"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// open "test.jpg"
|
||||
file, err := os.Open("test.jpg")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
// decode jpeg into image.Image
|
||||
img, err := jpeg.Decode(file)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
file.Close()
|
||||
|
||||
// resize to width 1000 using Lanczos resampling
|
||||
// and preserve aspect ratio
|
||||
m := resize.Resize(1000, 0, img, resize.Lanczos3)
|
||||
|
||||
out, err := os.Create("test_resized.jpg")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
defer out.Close()
|
||||
|
||||
// write new image to file
|
||||
jpeg.Encode(out, m, nil)
|
||||
}
|
||||
```
|
||||
|
||||
Caveats
|
||||
-------
|
||||
|
||||
* Optimized access routines are used for `image.RGBA`, `image.NRGBA`, `image.RGBA64`, `image.NRGBA64`, `image.YCbCr`, `image.Gray`, and `image.Gray16` types. All other image types are accessed in a generic way that will result in slow processing speed.
|
||||
* JPEG images are stored in `image.YCbCr`. This image format stores data in a way that will decrease processing speed. A resize may be up to 2 times slower than with `image.RGBA`.
|
||||
|
||||
|
||||
Downsizing Samples
|
||||
-------
|
||||
|
||||
Downsizing is not as simple as it might look like. Images have to be filtered before they are scaled down, otherwise aliasing might occur.
|
||||
Filtering is highly subjective: Applying too much will blur the whole image, too little will make aliasing become apparent.
|
||||
Resize tries to provide sane defaults that should suffice in most cases.
|
||||
|
||||
### Artificial sample
|
||||
|
||||
Original image
|
||||

|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_NearestNeighbor.png" /><br>Nearest-Neighbor</th>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_Bilinear.png" /><br>Bilinear</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_Bicubic.png" /><br>Bicubic</th>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_MitchellNetravali.png" /><br>Mitchell-Netravali</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_Lanczos2.png" /><br>Lanczos2</th>
|
||||
<th><img src="http://nfnt.github.com/img/rings_300_Lanczos3.png" /><br>Lanczos3</th>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
### Real-Life sample
|
||||
|
||||
Original image
|
||||

|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_NearestNeighbor.png" /><br>Nearest-Neighbor</th>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_Bilinear.png" /><br>Bilinear</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_Bicubic.png" /><br>Bicubic</th>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_MitchellNetravali.png" /><br>Mitchell-Netravali</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_Lanczos2.png" /><br>Lanczos2</th>
|
||||
<th><img src="http://nfnt.github.com/img/IMG_3694_300_Lanczos3.png" /><br>Lanczos3</th>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
Copyright (c) 2012 Jan Schlicht <janschlicht@gmail.com>
|
||||
Resize is released under a MIT style license.
|
||||
438
vendor/github.com/nfnt/resize/converter.go
сгенерированный
поставляемый
Обычный файл
438
vendor/github.com/nfnt/resize/converter.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,438 @@
|
||||
/*
|
||||
Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package resize
|
||||
|
||||
import "image"
|
||||
|
||||
// Keep value in [0,255] range.
|
||||
func clampUint8(in int32) uint8 {
|
||||
// casting a negative int to an uint will result in an overflown
|
||||
// large uint. this behavior will be exploited here and in other functions
|
||||
// to achieve a higher performance.
|
||||
if uint32(in) < 256 {
|
||||
return uint8(in)
|
||||
}
|
||||
if in > 255 {
|
||||
return 255
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// Keep value in [0,65535] range.
|
||||
func clampUint16(in int64) uint16 {
|
||||
if uint64(in) < 65536 {
|
||||
return uint16(in)
|
||||
}
|
||||
if in > 65535 {
|
||||
return 65535
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func resizeGeneric(in image.Image, out *image.RGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]int64
|
||||
var sum int64
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case xi < 0:
|
||||
xi = 0
|
||||
case xi >= maxX:
|
||||
xi = maxX
|
||||
}
|
||||
|
||||
r, g, b, a := in.At(xi+in.Bounds().Min.X, x+in.Bounds().Min.Y).RGBA()
|
||||
|
||||
rgba[0] += int64(coeff) * int64(r)
|
||||
rgba[1] += int64(coeff) * int64(g)
|
||||
rgba[2] += int64(coeff) * int64(b)
|
||||
rgba[3] += int64(coeff) * int64(a)
|
||||
sum += int64(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
|
||||
value := clampUint16(rgba[0] / sum)
|
||||
out.Pix[offset+0] = uint8(value >> 8)
|
||||
out.Pix[offset+1] = uint8(value)
|
||||
value = clampUint16(rgba[1] / sum)
|
||||
out.Pix[offset+2] = uint8(value >> 8)
|
||||
out.Pix[offset+3] = uint8(value)
|
||||
value = clampUint16(rgba[2] / sum)
|
||||
out.Pix[offset+4] = uint8(value >> 8)
|
||||
out.Pix[offset+5] = uint8(value)
|
||||
value = clampUint16(rgba[3] / sum)
|
||||
out.Pix[offset+6] = uint8(value >> 8)
|
||||
out.Pix[offset+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeRGBA(in *image.RGBA, out *image.RGBA, scale float64, coeffs []int16, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]int32
|
||||
var sum int32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 4
|
||||
case xi >= maxX:
|
||||
xi = 4 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
|
||||
rgba[0] += int32(coeff) * int32(row[xi+0])
|
||||
rgba[1] += int32(coeff) * int32(row[xi+1])
|
||||
rgba[2] += int32(coeff) * int32(row[xi+2])
|
||||
rgba[3] += int32(coeff) * int32(row[xi+3])
|
||||
sum += int32(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
|
||||
|
||||
out.Pix[xo+0] = clampUint8(rgba[0] / sum)
|
||||
out.Pix[xo+1] = clampUint8(rgba[1] / sum)
|
||||
out.Pix[xo+2] = clampUint8(rgba[2] / sum)
|
||||
out.Pix[xo+3] = clampUint8(rgba[3] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeNRGBA(in *image.NRGBA, out *image.RGBA, scale float64, coeffs []int16, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]int32
|
||||
var sum int32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 4
|
||||
case xi >= maxX:
|
||||
xi = 4 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
|
||||
// Forward alpha-premultiplication
|
||||
a := int32(row[xi+3])
|
||||
r := int32(row[xi+0]) * a
|
||||
r /= 0xff
|
||||
g := int32(row[xi+1]) * a
|
||||
g /= 0xff
|
||||
b := int32(row[xi+2]) * a
|
||||
b /= 0xff
|
||||
|
||||
rgba[0] += int32(coeff) * r
|
||||
rgba[1] += int32(coeff) * g
|
||||
rgba[2] += int32(coeff) * b
|
||||
rgba[3] += int32(coeff) * a
|
||||
sum += int32(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
|
||||
|
||||
out.Pix[xo+0] = clampUint8(rgba[0] / sum)
|
||||
out.Pix[xo+1] = clampUint8(rgba[1] / sum)
|
||||
out.Pix[xo+2] = clampUint8(rgba[2] / sum)
|
||||
out.Pix[xo+3] = clampUint8(rgba[3] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeRGBA64(in *image.RGBA64, out *image.RGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]int64
|
||||
var sum int64
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 8
|
||||
case xi >= maxX:
|
||||
xi = 8 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
|
||||
rgba[0] += int64(coeff) * (int64(row[xi+0])<<8 | int64(row[xi+1]))
|
||||
rgba[1] += int64(coeff) * (int64(row[xi+2])<<8 | int64(row[xi+3]))
|
||||
rgba[2] += int64(coeff) * (int64(row[xi+4])<<8 | int64(row[xi+5]))
|
||||
rgba[3] += int64(coeff) * (int64(row[xi+6])<<8 | int64(row[xi+7]))
|
||||
sum += int64(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
|
||||
value := clampUint16(rgba[0] / sum)
|
||||
out.Pix[xo+0] = uint8(value >> 8)
|
||||
out.Pix[xo+1] = uint8(value)
|
||||
value = clampUint16(rgba[1] / sum)
|
||||
out.Pix[xo+2] = uint8(value >> 8)
|
||||
out.Pix[xo+3] = uint8(value)
|
||||
value = clampUint16(rgba[2] / sum)
|
||||
out.Pix[xo+4] = uint8(value >> 8)
|
||||
out.Pix[xo+5] = uint8(value)
|
||||
value = clampUint16(rgba[3] / sum)
|
||||
out.Pix[xo+6] = uint8(value >> 8)
|
||||
out.Pix[xo+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeNRGBA64(in *image.NRGBA64, out *image.RGBA64, scale float64, coeffs []int32, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]int64
|
||||
var sum int64
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 8
|
||||
case xi >= maxX:
|
||||
xi = 8 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
|
||||
// Forward alpha-premultiplication
|
||||
a := int64(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
|
||||
r := int64(uint16(row[xi+0])<<8|uint16(row[xi+1])) * a
|
||||
r /= 0xffff
|
||||
g := int64(uint16(row[xi+2])<<8|uint16(row[xi+3])) * a
|
||||
g /= 0xffff
|
||||
b := int64(uint16(row[xi+4])<<8|uint16(row[xi+5])) * a
|
||||
b /= 0xffff
|
||||
|
||||
rgba[0] += int64(coeff) * r
|
||||
rgba[1] += int64(coeff) * g
|
||||
rgba[2] += int64(coeff) * b
|
||||
rgba[3] += int64(coeff) * a
|
||||
sum += int64(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
|
||||
value := clampUint16(rgba[0] / sum)
|
||||
out.Pix[xo+0] = uint8(value >> 8)
|
||||
out.Pix[xo+1] = uint8(value)
|
||||
value = clampUint16(rgba[1] / sum)
|
||||
out.Pix[xo+2] = uint8(value >> 8)
|
||||
out.Pix[xo+3] = uint8(value)
|
||||
value = clampUint16(rgba[2] / sum)
|
||||
out.Pix[xo+4] = uint8(value >> 8)
|
||||
out.Pix[xo+5] = uint8(value)
|
||||
value = clampUint16(rgba[3] / sum)
|
||||
out.Pix[xo+6] = uint8(value >> 8)
|
||||
out.Pix[xo+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeGray(in *image.Gray, out *image.Gray, scale float64, coeffs []int16, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[(x-newBounds.Min.X)*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var gray int32
|
||||
var sum int32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case xi < 0:
|
||||
xi = 0
|
||||
case xi >= maxX:
|
||||
xi = maxX
|
||||
}
|
||||
gray += int32(coeff) * int32(row[xi])
|
||||
sum += int32(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x - newBounds.Min.X)
|
||||
out.Pix[offset] = clampUint8(gray / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeGray16(in *image.Gray16, out *image.Gray16, scale float64, coeffs []int32, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var gray int64
|
||||
var sum int64
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 2
|
||||
case xi >= maxX:
|
||||
xi = 2 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
gray += int64(coeff) * int64(uint16(row[xi+0])<<8|uint16(row[xi+1]))
|
||||
sum += int64(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*2
|
||||
value := clampUint16(gray / sum)
|
||||
out.Pix[offset+0] = uint8(value >> 8)
|
||||
out.Pix[offset+1] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func resizeYCbCr(in *ycc, out *ycc, scale float64, coeffs []int16, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var p [3]int32
|
||||
var sum int32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
coeff := coeffs[ci+i]
|
||||
if coeff != 0 {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 3
|
||||
case xi >= maxX:
|
||||
xi = 3 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
p[0] += int32(coeff) * int32(row[xi+0])
|
||||
p[1] += int32(coeff) * int32(row[xi+1])
|
||||
p[2] += int32(coeff) * int32(row[xi+2])
|
||||
sum += int32(coeff)
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*3
|
||||
out.Pix[xo+0] = clampUint8(p[0] / sum)
|
||||
out.Pix[xo+1] = clampUint8(p[1] / sum)
|
||||
out.Pix[xo+2] = clampUint8(p[2] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestYCbCr(in *ycc, out *ycc, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var p [3]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 3
|
||||
case xi >= maxX:
|
||||
xi = 3 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
p[0] += float32(row[xi+0])
|
||||
p[1] += float32(row[xi+1])
|
||||
p[2] += float32(row[xi+2])
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*3
|
||||
out.Pix[xo+0] = floatToUint8(p[0] / sum)
|
||||
out.Pix[xo+1] = floatToUint8(p[1] / sum)
|
||||
out.Pix[xo+2] = floatToUint8(p[2] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
143
vendor/github.com/nfnt/resize/filters.go
сгенерированный
поставляемый
Обычный файл
143
vendor/github.com/nfnt/resize/filters.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package resize
|
||||
|
||||
import (
|
||||
"math"
|
||||
)
|
||||
|
||||
func nearest(in float64) float64 {
|
||||
if in >= -0.5 && in < 0.5 {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func linear(in float64) float64 {
|
||||
in = math.Abs(in)
|
||||
if in <= 1 {
|
||||
return 1 - in
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func cubic(in float64) float64 {
|
||||
in = math.Abs(in)
|
||||
if in <= 1 {
|
||||
return in*in*(1.5*in-2.5) + 1.0
|
||||
}
|
||||
if in <= 2 {
|
||||
return in*(in*(2.5-0.5*in)-4.0) + 2.0
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func mitchellnetravali(in float64) float64 {
|
||||
in = math.Abs(in)
|
||||
if in <= 1 {
|
||||
return (7.0*in*in*in - 12.0*in*in + 5.33333333333) * 0.16666666666
|
||||
}
|
||||
if in <= 2 {
|
||||
return (-2.33333333333*in*in*in + 12.0*in*in - 20.0*in + 10.6666666667) * 0.16666666666
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func sinc(x float64) float64 {
|
||||
x = math.Abs(x) * math.Pi
|
||||
if x >= 1.220703e-4 {
|
||||
return math.Sin(x) / x
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
func lanczos2(in float64) float64 {
|
||||
if in > -2 && in < 2 {
|
||||
return sinc(in) * sinc(in*0.5)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func lanczos3(in float64) float64 {
|
||||
if in > -3 && in < 3 {
|
||||
return sinc(in) * sinc(in*0.3333333333333333)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// range [-256,256]
|
||||
func createWeights8(dy, filterLength int, blur, scale float64, kernel func(float64) float64) ([]int16, []int, int) {
|
||||
filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
|
||||
filterFactor := math.Min(1./(blur*scale), 1)
|
||||
|
||||
coeffs := make([]int16, dy*filterLength)
|
||||
start := make([]int, dy)
|
||||
for y := 0; y < dy; y++ {
|
||||
interpX := scale*(float64(y)+0.5) - 0.5
|
||||
start[y] = int(interpX) - filterLength/2 + 1
|
||||
interpX -= float64(start[y])
|
||||
for i := 0; i < filterLength; i++ {
|
||||
in := (interpX - float64(i)) * filterFactor
|
||||
coeffs[y*filterLength+i] = int16(kernel(in) * 256)
|
||||
}
|
||||
}
|
||||
|
||||
return coeffs, start, filterLength
|
||||
}
|
||||
|
||||
// range [-65536,65536]
|
||||
func createWeights16(dy, filterLength int, blur, scale float64, kernel func(float64) float64) ([]int32, []int, int) {
|
||||
filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
|
||||
filterFactor := math.Min(1./(blur*scale), 1)
|
||||
|
||||
coeffs := make([]int32, dy*filterLength)
|
||||
start := make([]int, dy)
|
||||
for y := 0; y < dy; y++ {
|
||||
interpX := scale*(float64(y)+0.5) - 0.5
|
||||
start[y] = int(interpX) - filterLength/2 + 1
|
||||
interpX -= float64(start[y])
|
||||
for i := 0; i < filterLength; i++ {
|
||||
in := (interpX - float64(i)) * filterFactor
|
||||
coeffs[y*filterLength+i] = int32(kernel(in) * 65536)
|
||||
}
|
||||
}
|
||||
|
||||
return coeffs, start, filterLength
|
||||
}
|
||||
|
||||
func createWeightsNearest(dy, filterLength int, blur, scale float64) ([]bool, []int, int) {
|
||||
filterLength = filterLength * int(math.Max(math.Ceil(blur*scale), 1))
|
||||
filterFactor := math.Min(1./(blur*scale), 1)
|
||||
|
||||
coeffs := make([]bool, dy*filterLength)
|
||||
start := make([]int, dy)
|
||||
for y := 0; y < dy; y++ {
|
||||
interpX := scale*(float64(y)+0.5) - 0.5
|
||||
start[y] = int(interpX) - filterLength/2 + 1
|
||||
interpX -= float64(start[y])
|
||||
for i := 0; i < filterLength; i++ {
|
||||
in := (interpX - float64(i)) * filterFactor
|
||||
if in >= -0.5 && in < 0.5 {
|
||||
coeffs[y*filterLength+i] = true
|
||||
} else {
|
||||
coeffs[y*filterLength+i] = false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return coeffs, start, filterLength
|
||||
}
|
||||
318
vendor/github.com/nfnt/resize/nearest.go
сгенерированный
поставляемый
Обычный файл
318
vendor/github.com/nfnt/resize/nearest.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,318 @@
|
||||
/*
|
||||
Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package resize
|
||||
|
||||
import "image"
|
||||
|
||||
func floatToUint8(x float32) uint8 {
|
||||
// Nearest-neighbor values are always
|
||||
// positive no need to check lower-bound.
|
||||
if x > 0xfe {
|
||||
return 0xff
|
||||
}
|
||||
return uint8(x)
|
||||
}
|
||||
|
||||
func floatToUint16(x float32) uint16 {
|
||||
if x > 0xfffe {
|
||||
return 0xffff
|
||||
}
|
||||
return uint16(x)
|
||||
}
|
||||
|
||||
func nearestGeneric(in image.Image, out *image.RGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case xi < 0:
|
||||
xi = 0
|
||||
case xi >= maxX:
|
||||
xi = maxX
|
||||
}
|
||||
r, g, b, a := in.At(xi+in.Bounds().Min.X, x+in.Bounds().Min.Y).RGBA()
|
||||
rgba[0] += float32(r)
|
||||
rgba[1] += float32(g)
|
||||
rgba[2] += float32(b)
|
||||
rgba[3] += float32(a)
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
value := floatToUint16(rgba[0] / sum)
|
||||
out.Pix[offset+0] = uint8(value >> 8)
|
||||
out.Pix[offset+1] = uint8(value)
|
||||
value = floatToUint16(rgba[1] / sum)
|
||||
out.Pix[offset+2] = uint8(value >> 8)
|
||||
out.Pix[offset+3] = uint8(value)
|
||||
value = floatToUint16(rgba[2] / sum)
|
||||
out.Pix[offset+4] = uint8(value >> 8)
|
||||
out.Pix[offset+5] = uint8(value)
|
||||
value = floatToUint16(rgba[3] / sum)
|
||||
out.Pix[offset+6] = uint8(value >> 8)
|
||||
out.Pix[offset+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestRGBA(in *image.RGBA, out *image.RGBA, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 4
|
||||
case xi >= maxX:
|
||||
xi = 4 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
rgba[0] += float32(row[xi+0])
|
||||
rgba[1] += float32(row[xi+1])
|
||||
rgba[2] += float32(row[xi+2])
|
||||
rgba[3] += float32(row[xi+3])
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
|
||||
out.Pix[xo+0] = floatToUint8(rgba[0] / sum)
|
||||
out.Pix[xo+1] = floatToUint8(rgba[1] / sum)
|
||||
out.Pix[xo+2] = floatToUint8(rgba[2] / sum)
|
||||
out.Pix[xo+3] = floatToUint8(rgba[3] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestNRGBA(in *image.NRGBA, out *image.NRGBA, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 4
|
||||
case xi >= maxX:
|
||||
xi = 4 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
rgba[0] += float32(row[xi+0])
|
||||
rgba[1] += float32(row[xi+1])
|
||||
rgba[2] += float32(row[xi+2])
|
||||
rgba[3] += float32(row[xi+3])
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*4
|
||||
out.Pix[xo+0] = floatToUint8(rgba[0] / sum)
|
||||
out.Pix[xo+1] = floatToUint8(rgba[1] / sum)
|
||||
out.Pix[xo+2] = floatToUint8(rgba[2] / sum)
|
||||
out.Pix[xo+3] = floatToUint8(rgba[3] / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestRGBA64(in *image.RGBA64, out *image.RGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 8
|
||||
case xi >= maxX:
|
||||
xi = 8 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
rgba[0] += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
|
||||
rgba[1] += float32(uint16(row[xi+2])<<8 | uint16(row[xi+3]))
|
||||
rgba[2] += float32(uint16(row[xi+4])<<8 | uint16(row[xi+5]))
|
||||
rgba[3] += float32(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
value := floatToUint16(rgba[0] / sum)
|
||||
out.Pix[xo+0] = uint8(value >> 8)
|
||||
out.Pix[xo+1] = uint8(value)
|
||||
value = floatToUint16(rgba[1] / sum)
|
||||
out.Pix[xo+2] = uint8(value >> 8)
|
||||
out.Pix[xo+3] = uint8(value)
|
||||
value = floatToUint16(rgba[2] / sum)
|
||||
out.Pix[xo+4] = uint8(value >> 8)
|
||||
out.Pix[xo+5] = uint8(value)
|
||||
value = floatToUint16(rgba[3] / sum)
|
||||
out.Pix[xo+6] = uint8(value >> 8)
|
||||
out.Pix[xo+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestNRGBA64(in *image.NRGBA64, out *image.NRGBA64, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var rgba [4]float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 8
|
||||
case xi >= maxX:
|
||||
xi = 8 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
rgba[0] += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
|
||||
rgba[1] += float32(uint16(row[xi+2])<<8 | uint16(row[xi+3]))
|
||||
rgba[2] += float32(uint16(row[xi+4])<<8 | uint16(row[xi+5]))
|
||||
rgba[3] += float32(uint16(row[xi+6])<<8 | uint16(row[xi+7]))
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
xo := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*8
|
||||
value := floatToUint16(rgba[0] / sum)
|
||||
out.Pix[xo+0] = uint8(value >> 8)
|
||||
out.Pix[xo+1] = uint8(value)
|
||||
value = floatToUint16(rgba[1] / sum)
|
||||
out.Pix[xo+2] = uint8(value >> 8)
|
||||
out.Pix[xo+3] = uint8(value)
|
||||
value = floatToUint16(rgba[2] / sum)
|
||||
out.Pix[xo+4] = uint8(value >> 8)
|
||||
out.Pix[xo+5] = uint8(value)
|
||||
value = floatToUint16(rgba[3] / sum)
|
||||
out.Pix[xo+6] = uint8(value >> 8)
|
||||
out.Pix[xo+7] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestGray(in *image.Gray, out *image.Gray, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var gray float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case xi < 0:
|
||||
xi = 0
|
||||
case xi >= maxX:
|
||||
xi = maxX
|
||||
}
|
||||
gray += float32(row[xi])
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x - newBounds.Min.X)
|
||||
out.Pix[offset] = floatToUint8(gray / sum)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nearestGray16(in *image.Gray16, out *image.Gray16, scale float64, coeffs []bool, offset []int, filterLength int) {
|
||||
newBounds := out.Bounds()
|
||||
maxX := in.Bounds().Dx() - 1
|
||||
|
||||
for x := newBounds.Min.X; x < newBounds.Max.X; x++ {
|
||||
row := in.Pix[x*in.Stride:]
|
||||
for y := newBounds.Min.Y; y < newBounds.Max.Y; y++ {
|
||||
var gray float32
|
||||
var sum float32
|
||||
start := offset[y]
|
||||
ci := y * filterLength
|
||||
for i := 0; i < filterLength; i++ {
|
||||
if coeffs[ci+i] {
|
||||
xi := start + i
|
||||
switch {
|
||||
case uint(xi) < uint(maxX):
|
||||
xi *= 2
|
||||
case xi >= maxX:
|
||||
xi = 2 * maxX
|
||||
default:
|
||||
xi = 0
|
||||
}
|
||||
gray += float32(uint16(row[xi+0])<<8 | uint16(row[xi+1]))
|
||||
sum++
|
||||
}
|
||||
}
|
||||
|
||||
offset := (y-newBounds.Min.Y)*out.Stride + (x-newBounds.Min.X)*2
|
||||
value := floatToUint16(gray / sum)
|
||||
out.Pix[offset+0] = uint8(value >> 8)
|
||||
out.Pix[offset+1] = uint8(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
620
vendor/github.com/nfnt/resize/resize.go
сгенерированный
поставляемый
Обычный файл
620
vendor/github.com/nfnt/resize/resize.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,620 @@
|
||||
/*
|
||||
Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
// Package resize implements various image resizing methods.
|
||||
//
|
||||
// The package works with the Image interface described in the image package.
|
||||
// Various interpolation methods are provided and multiple processors may be
|
||||
// utilized in the computations.
|
||||
//
|
||||
// Example:
|
||||
// imgResized := resize.Resize(1000, 0, imgOld, resize.MitchellNetravali)
|
||||
package resize
|
||||
|
||||
import (
|
||||
"image"
|
||||
"runtime"
|
||||
"sync"
|
||||
)
|
||||
|
||||
// An InterpolationFunction provides the parameters that describe an
|
||||
// interpolation kernel. It returns the number of samples to take
|
||||
// and the kernel function to use for sampling.
|
||||
type InterpolationFunction int
|
||||
|
||||
// InterpolationFunction constants
|
||||
const (
|
||||
// Nearest-neighbor interpolation
|
||||
NearestNeighbor InterpolationFunction = iota
|
||||
// Bilinear interpolation
|
||||
Bilinear
|
||||
// Bicubic interpolation (with cubic hermite spline)
|
||||
Bicubic
|
||||
// Mitchell-Netravali interpolation
|
||||
MitchellNetravali
|
||||
// Lanczos interpolation (a=2)
|
||||
Lanczos2
|
||||
// Lanczos interpolation (a=3)
|
||||
Lanczos3
|
||||
)
|
||||
|
||||
// kernal, returns an InterpolationFunctions taps and kernel.
|
||||
func (i InterpolationFunction) kernel() (int, func(float64) float64) {
|
||||
switch i {
|
||||
case Bilinear:
|
||||
return 2, linear
|
||||
case Bicubic:
|
||||
return 4, cubic
|
||||
case MitchellNetravali:
|
||||
return 4, mitchellnetravali
|
||||
case Lanczos2:
|
||||
return 4, lanczos2
|
||||
case Lanczos3:
|
||||
return 6, lanczos3
|
||||
default:
|
||||
// Default to NearestNeighbor.
|
||||
return 2, nearest
|
||||
}
|
||||
}
|
||||
|
||||
// values <1 will sharpen the image
|
||||
var blur = 1.0
|
||||
|
||||
// Resize scales an image to new width and height using the interpolation function interp.
|
||||
// A new image with the given dimensions will be returned.
|
||||
// If one of the parameters width or height is set to 0, its size will be calculated so that
|
||||
// the aspect ratio is that of the originating image.
|
||||
// The resizing algorithm uses channels for parallel computation.
|
||||
// If the input image has width or height of 0, it is returned unchanged.
|
||||
func Resize(width, height uint, img image.Image, interp InterpolationFunction) image.Image {
|
||||
scaleX, scaleY := calcFactors(width, height, float64(img.Bounds().Dx()), float64(img.Bounds().Dy()))
|
||||
if width == 0 {
|
||||
width = uint(0.7 + float64(img.Bounds().Dx())/scaleX)
|
||||
}
|
||||
if height == 0 {
|
||||
height = uint(0.7 + float64(img.Bounds().Dy())/scaleY)
|
||||
}
|
||||
|
||||
// Trivial case: return input image
|
||||
if int(width) == img.Bounds().Dx() && int(height) == img.Bounds().Dy() {
|
||||
return img
|
||||
}
|
||||
|
||||
// Input image has no pixels
|
||||
if img.Bounds().Dx() <= 0 || img.Bounds().Dy() <= 0 {
|
||||
return img
|
||||
}
|
||||
|
||||
if interp == NearestNeighbor {
|
||||
return resizeNearest(width, height, scaleX, scaleY, img, interp)
|
||||
}
|
||||
|
||||
taps, kernel := interp.kernel()
|
||||
cpus := runtime.GOMAXPROCS(0)
|
||||
wg := sync.WaitGroup{}
|
||||
|
||||
// Generic access to image.Image is slow in tight loops.
|
||||
// The optimal access has to be determined from the concrete image type.
|
||||
switch input := img.(type) {
|
||||
case *image.RGBA:
|
||||
// 8-bit precision
|
||||
temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.NRGBA:
|
||||
// 8-bit precision
|
||||
temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeNRGBA(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
|
||||
case *image.YCbCr:
|
||||
// 8-bit precision
|
||||
// accessing the YCbCr arrays in a tight loop is slow.
|
||||
// converting the image to ycc increases performance by 2x.
|
||||
temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio)
|
||||
result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444)
|
||||
|
||||
coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
in := imageYCbCrToYCC(input)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*ycc)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeYCbCr(in, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*ycc)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeYCbCr(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result.YCbCr()
|
||||
case *image.RGBA64:
|
||||
// 16-bit precision
|
||||
temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.NRGBA64:
|
||||
// 16-bit precision
|
||||
temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeNRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.Gray:
|
||||
// 8-bit precision
|
||||
temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewGray(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights8(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.Gray)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeGray(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights8(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.Gray)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeGray(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.Gray16:
|
||||
// 16-bit precision
|
||||
temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewGray16(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.Gray16)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeGray16(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.Gray16)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeGray16(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
default:
|
||||
// 16-bit precision
|
||||
temp := image.NewRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeights16(temp.Bounds().Dy(), taps, blur, scaleX, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeGeneric(img, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeights16(result.Bounds().Dy(), taps, blur, scaleY, kernel)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
resizeRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
func resizeNearest(width, height uint, scaleX, scaleY float64, img image.Image, interp InterpolationFunction) image.Image {
|
||||
taps, _ := interp.kernel()
|
||||
cpus := runtime.GOMAXPROCS(0)
|
||||
wg := sync.WaitGroup{}
|
||||
|
||||
switch input := img.(type) {
|
||||
case *image.RGBA:
|
||||
// 8-bit precision
|
||||
temp := image.NewRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestRGBA(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.NRGBA:
|
||||
// 8-bit precision
|
||||
temp := image.NewNRGBA(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewNRGBA(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.NRGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestNRGBA(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.NRGBA)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestNRGBA(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.YCbCr:
|
||||
// 8-bit precision
|
||||
// accessing the YCbCr arrays in a tight loop is slow.
|
||||
// converting the image to ycc increases performance by 2x.
|
||||
temp := newYCC(image.Rect(0, 0, input.Bounds().Dy(), int(width)), input.SubsampleRatio)
|
||||
result := newYCC(image.Rect(0, 0, int(width), int(height)), image.YCbCrSubsampleRatio444)
|
||||
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
in := imageYCbCrToYCC(input)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*ycc)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestYCbCr(in, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*ycc)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestYCbCr(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result.YCbCr()
|
||||
case *image.RGBA64:
|
||||
// 16-bit precision
|
||||
temp := image.NewRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.NRGBA64:
|
||||
// 16-bit precision
|
||||
temp := image.NewNRGBA64(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewNRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.NRGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestNRGBA64(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.NRGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestNRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.Gray:
|
||||
// 8-bit precision
|
||||
temp := image.NewGray(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewGray(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.Gray)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestGray(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.Gray)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestGray(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
case *image.Gray16:
|
||||
// 16-bit precision
|
||||
temp := image.NewGray16(image.Rect(0, 0, input.Bounds().Dy(), int(width)))
|
||||
result := image.NewGray16(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.Gray16)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestGray16(input, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.Gray16)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestGray16(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
default:
|
||||
// 16-bit precision
|
||||
temp := image.NewRGBA64(image.Rect(0, 0, img.Bounds().Dy(), int(width)))
|
||||
result := image.NewRGBA64(image.Rect(0, 0, int(width), int(height)))
|
||||
|
||||
// horizontal filter, results in transposed temporary image
|
||||
coeffs, offset, filterLength := createWeightsNearest(temp.Bounds().Dy(), taps, blur, scaleX)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(temp, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestGeneric(img, slice, scaleX, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// horizontal filter on transposed image, result is not transposed
|
||||
coeffs, offset, filterLength = createWeightsNearest(result.Bounds().Dy(), taps, blur, scaleY)
|
||||
wg.Add(cpus)
|
||||
for i := 0; i < cpus; i++ {
|
||||
slice := makeSlice(result, i, cpus).(*image.RGBA64)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
nearestRGBA64(temp, slice, scaleY, coeffs, offset, filterLength)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return result
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Calculates scaling factors using old and new image dimensions.
|
||||
func calcFactors(width, height uint, oldWidth, oldHeight float64) (scaleX, scaleY float64) {
|
||||
if width == 0 {
|
||||
if height == 0 {
|
||||
scaleX = 1.0
|
||||
scaleY = 1.0
|
||||
} else {
|
||||
scaleY = oldHeight / float64(height)
|
||||
scaleX = scaleY
|
||||
}
|
||||
} else {
|
||||
scaleX = oldWidth / float64(width)
|
||||
if height == 0 {
|
||||
scaleY = scaleX
|
||||
} else {
|
||||
scaleY = oldHeight / float64(height)
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
type imageWithSubImage interface {
|
||||
image.Image
|
||||
SubImage(image.Rectangle) image.Image
|
||||
}
|
||||
|
||||
func makeSlice(img imageWithSubImage, i, n int) image.Image {
|
||||
return img.SubImage(image.Rect(img.Bounds().Min.X, img.Bounds().Min.Y+i*img.Bounds().Dy()/n, img.Bounds().Max.X, img.Bounds().Min.Y+(i+1)*img.Bounds().Dy()/n))
|
||||
}
|
||||
55
vendor/github.com/nfnt/resize/thumbnail.go
сгенерированный
поставляемый
Обычный файл
55
vendor/github.com/nfnt/resize/thumbnail.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,55 @@
|
||||
/*
|
||||
Copyright (c) 2012, Jan Schlicht <jan.schlicht@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package resize
|
||||
|
||||
import (
|
||||
"image"
|
||||
)
|
||||
|
||||
// Thumbnail will downscale provided image to max width and height preserving
|
||||
// original aspect ratio and using the interpolation function interp.
|
||||
// It will return original image, without processing it, if original sizes
|
||||
// are already smaller than provided constraints.
|
||||
func Thumbnail(maxWidth, maxHeight uint, img image.Image, interp InterpolationFunction) image.Image {
|
||||
origBounds := img.Bounds()
|
||||
origWidth := uint(origBounds.Dx())
|
||||
origHeight := uint(origBounds.Dy())
|
||||
newWidth, newHeight := origWidth, origHeight
|
||||
|
||||
// Return original image if it have same or smaller size as constraints
|
||||
if maxWidth >= origWidth && maxHeight >= origHeight {
|
||||
return img
|
||||
}
|
||||
|
||||
// Preserve aspect ratio
|
||||
if origWidth > maxWidth {
|
||||
newHeight = uint(origHeight * maxWidth / origWidth)
|
||||
if newHeight < 1 {
|
||||
newHeight = 1
|
||||
}
|
||||
newWidth = maxWidth
|
||||
}
|
||||
|
||||
if newHeight > maxHeight {
|
||||
newWidth = uint(newWidth * maxHeight / newHeight)
|
||||
if newWidth < 1 {
|
||||
newWidth = 1
|
||||
}
|
||||
newHeight = maxHeight
|
||||
}
|
||||
return Resize(newWidth, newHeight, img, interp)
|
||||
}
|
||||
387
vendor/github.com/nfnt/resize/ycc.go
сгенерированный
поставляемый
Обычный файл
387
vendor/github.com/nfnt/resize/ycc.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,387 @@
|
||||
/*
|
||||
Copyright (c) 2014, Charlie Vieth <charlie.vieth@gmail.com>
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any purpose
|
||||
with or without fee is hereby granted, provided that the above copyright notice
|
||||
and this permission notice appear in all copies.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
|
||||
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
|
||||
OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
|
||||
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
|
||||
THIS SOFTWARE.
|
||||
*/
|
||||
|
||||
package resize
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
)
|
||||
|
||||
// ycc is an in memory YCbCr image. The Y, Cb and Cr samples are held in a
|
||||
// single slice to increase resizing performance.
|
||||
type ycc struct {
|
||||
// Pix holds the image's pixels, in Y, Cb, Cr order. The pixel at
|
||||
// (x, y) starts at Pix[(y-Rect.Min.Y)*Stride + (x-Rect.Min.X)*3].
|
||||
Pix []uint8
|
||||
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
|
||||
Stride int
|
||||
// Rect is the image's bounds.
|
||||
Rect image.Rectangle
|
||||
// SubsampleRatio is the subsample ratio of the original YCbCr image.
|
||||
SubsampleRatio image.YCbCrSubsampleRatio
|
||||
}
|
||||
|
||||
// PixOffset returns the index of the first element of Pix that corresponds to
|
||||
// the pixel at (x, y).
|
||||
func (p *ycc) PixOffset(x, y int) int {
|
||||
return (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)*3
|
||||
}
|
||||
|
||||
func (p *ycc) Bounds() image.Rectangle {
|
||||
return p.Rect
|
||||
}
|
||||
|
||||
func (p *ycc) ColorModel() color.Model {
|
||||
return color.YCbCrModel
|
||||
}
|
||||
|
||||
func (p *ycc) At(x, y int) color.Color {
|
||||
if !(image.Point{x, y}.In(p.Rect)) {
|
||||
return color.YCbCr{}
|
||||
}
|
||||
i := p.PixOffset(x, y)
|
||||
return color.YCbCr{
|
||||
p.Pix[i+0],
|
||||
p.Pix[i+1],
|
||||
p.Pix[i+2],
|
||||
}
|
||||
}
|
||||
|
||||
func (p *ycc) Opaque() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// SubImage returns an image representing the portion of the image p visible
|
||||
// through r. The returned value shares pixels with the original image.
|
||||
func (p *ycc) SubImage(r image.Rectangle) image.Image {
|
||||
r = r.Intersect(p.Rect)
|
||||
if r.Empty() {
|
||||
return &ycc{SubsampleRatio: p.SubsampleRatio}
|
||||
}
|
||||
i := p.PixOffset(r.Min.X, r.Min.Y)
|
||||
return &ycc{
|
||||
Pix: p.Pix[i:],
|
||||
Stride: p.Stride,
|
||||
Rect: r,
|
||||
SubsampleRatio: p.SubsampleRatio,
|
||||
}
|
||||
}
|
||||
|
||||
// newYCC returns a new ycc with the given bounds and subsample ratio.
|
||||
func newYCC(r image.Rectangle, s image.YCbCrSubsampleRatio) *ycc {
|
||||
w, h := r.Dx(), r.Dy()
|
||||
buf := make([]uint8, 3*w*h)
|
||||
return &ycc{Pix: buf, Stride: 3 * w, Rect: r, SubsampleRatio: s}
|
||||
}
|
||||
|
||||
// Copy of image.YCbCrSubsampleRatio constants - this allows us to support
|
||||
// older versions of Go where these constants are not defined (i.e. Go 1.4)
|
||||
const (
|
||||
ycbcrSubsampleRatio444 image.YCbCrSubsampleRatio = iota
|
||||
ycbcrSubsampleRatio422
|
||||
ycbcrSubsampleRatio420
|
||||
ycbcrSubsampleRatio440
|
||||
ycbcrSubsampleRatio411
|
||||
ycbcrSubsampleRatio410
|
||||
)
|
||||
|
||||
// YCbCr converts ycc to a YCbCr image with the same subsample ratio
|
||||
// as the YCbCr image that ycc was generated from.
|
||||
func (p *ycc) YCbCr() *image.YCbCr {
|
||||
ycbcr := image.NewYCbCr(p.Rect, p.SubsampleRatio)
|
||||
switch ycbcr.SubsampleRatio {
|
||||
case ycbcrSubsampleRatio422:
|
||||
return p.ycbcr422(ycbcr)
|
||||
case ycbcrSubsampleRatio420:
|
||||
return p.ycbcr420(ycbcr)
|
||||
case ycbcrSubsampleRatio440:
|
||||
return p.ycbcr440(ycbcr)
|
||||
case ycbcrSubsampleRatio444:
|
||||
return p.ycbcr444(ycbcr)
|
||||
case ycbcrSubsampleRatio411:
|
||||
return p.ycbcr411(ycbcr)
|
||||
case ycbcrSubsampleRatio410:
|
||||
return p.ycbcr410(ycbcr)
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
// imageYCbCrToYCC converts a YCbCr image to a ycc image for resizing.
|
||||
func imageYCbCrToYCC(in *image.YCbCr) *ycc {
|
||||
w, h := in.Rect.Dx(), in.Rect.Dy()
|
||||
p := ycc{
|
||||
Pix: make([]uint8, 3*w*h),
|
||||
Stride: 3 * w,
|
||||
Rect: image.Rect(0, 0, w, h),
|
||||
SubsampleRatio: in.SubsampleRatio,
|
||||
}
|
||||
switch in.SubsampleRatio {
|
||||
case ycbcrSubsampleRatio422:
|
||||
return convertToYCC422(in, &p)
|
||||
case ycbcrSubsampleRatio420:
|
||||
return convertToYCC420(in, &p)
|
||||
case ycbcrSubsampleRatio440:
|
||||
return convertToYCC440(in, &p)
|
||||
case ycbcrSubsampleRatio444:
|
||||
return convertToYCC444(in, &p)
|
||||
case ycbcrSubsampleRatio411:
|
||||
return convertToYCC411(in, &p)
|
||||
case ycbcrSubsampleRatio410:
|
||||
return convertToYCC410(in, &p)
|
||||
}
|
||||
return &p
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr422(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := y * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x/2
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr420(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := (y / 2) * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x/2
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr440(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := (y / 2) * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr444(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := y * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr411(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := y * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x/4
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func (p *ycc) ycbcr410(ycbcr *image.YCbCr) *image.YCbCr {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := ycbcr.Y
|
||||
Cb := ycbcr.Cb
|
||||
Cr := ycbcr.Cr
|
||||
for y := 0; y < ycbcr.Rect.Max.Y-ycbcr.Rect.Min.Y; y++ {
|
||||
yy := y * ycbcr.YStride
|
||||
cy := (y / 2) * ycbcr.CStride
|
||||
for x := 0; x < ycbcr.Rect.Max.X-ycbcr.Rect.Min.X; x++ {
|
||||
ci := cy + x/4
|
||||
Y[yy+x] = Pix[off+0]
|
||||
Cb[ci] = Pix[off+1]
|
||||
Cr[ci] = Pix[off+2]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return ycbcr
|
||||
}
|
||||
|
||||
func convertToYCC422(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := y * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x/2
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func convertToYCC420(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := (y / 2) * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x/2
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func convertToYCC440(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := (y / 2) * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func convertToYCC444(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := y * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func convertToYCC411(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := y * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x/4
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func convertToYCC410(in *image.YCbCr, p *ycc) *ycc {
|
||||
var off int
|
||||
Pix := p.Pix
|
||||
Y := in.Y
|
||||
Cb := in.Cb
|
||||
Cr := in.Cr
|
||||
for y := 0; y < in.Rect.Max.Y-in.Rect.Min.Y; y++ {
|
||||
yy := y * in.YStride
|
||||
cy := (y / 2) * in.CStride
|
||||
for x := 0; x < in.Rect.Max.X-in.Rect.Min.X; x++ {
|
||||
ci := cy + x/4
|
||||
Pix[off+0] = Y[yy+x]
|
||||
Pix[off+1] = Cb[ci]
|
||||
Pix[off+2] = Cr[ci]
|
||||
off += 3
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
61
vendor/golang.org/x/image/draw/draw.go
сгенерированный
поставляемый
Обычный файл
61
vendor/golang.org/x/image/draw/draw.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,61 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package draw provides image composition functions.
|
||||
//
|
||||
// See "The Go image/draw package" for an introduction to this package:
|
||||
// http://golang.org/doc/articles/image_draw.html
|
||||
//
|
||||
// This package is a superset of and a drop-in replacement for the image/draw
|
||||
// package in the standard library.
|
||||
package draw
|
||||
|
||||
// This file just contains the API exported by the image/draw package in the
|
||||
// standard library. Other files in this package provide additional features.
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/draw"
|
||||
)
|
||||
|
||||
// Draw calls DrawMask with a nil mask.
|
||||
func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op) {
|
||||
draw.Draw(dst, r, src, sp, draw.Op(op))
|
||||
}
|
||||
|
||||
// DrawMask aligns r.Min in dst with sp in src and mp in mask and then
|
||||
// replaces the rectangle r in dst with the result of a Porter-Duff
|
||||
// composition. A nil mask is treated as opaque.
|
||||
func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point, mask image.Image, mp image.Point, op Op) {
|
||||
draw.DrawMask(dst, r, src, sp, mask, mp, draw.Op(op))
|
||||
}
|
||||
|
||||
// Drawer contains the Draw method.
|
||||
type Drawer = draw.Drawer
|
||||
|
||||
// FloydSteinberg is a Drawer that is the Src Op with Floyd-Steinberg error
|
||||
// diffusion.
|
||||
var FloydSteinberg Drawer = floydSteinberg{}
|
||||
|
||||
type floydSteinberg struct{}
|
||||
|
||||
func (floydSteinberg) Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point) {
|
||||
draw.FloydSteinberg.Draw(dst, r, src, sp)
|
||||
}
|
||||
|
||||
// Image is an image.Image with a Set method to change a single pixel.
|
||||
type Image = draw.Image
|
||||
|
||||
// Op is a Porter-Duff compositing operator.
|
||||
type Op = draw.Op
|
||||
|
||||
const (
|
||||
// Over specifies ``(src in mask) over dst''.
|
||||
Over Op = draw.Over
|
||||
// Src specifies ``src in mask''.
|
||||
Src Op = draw.Src
|
||||
)
|
||||
|
||||
// Quantizer produces a palette for an image.
|
||||
type Quantizer = draw.Quantizer
|
||||
1404
vendor/golang.org/x/image/draw/gen.go
сгенерированный
поставляемый
Обычный файл
1404
vendor/golang.org/x/image/draw/gen.go
сгенерированный
поставляемый
Обычный файл
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
6670
vendor/golang.org/x/image/draw/impl.go
сгенерированный
поставляемый
Обычный файл
6670
vendor/golang.org/x/image/draw/impl.go
сгенерированный
поставляемый
Обычный файл
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
525
vendor/golang.org/x/image/draw/scale.go
сгенерированный
поставляемый
Обычный файл
525
vendor/golang.org/x/image/draw/scale.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,525 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
//go:generate go run gen.go
|
||||
|
||||
package draw
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"math"
|
||||
"sync"
|
||||
|
||||
"golang.org/x/image/math/f64"
|
||||
)
|
||||
|
||||
// Copy copies the part of the source image defined by src and sr and writes
|
||||
// the result of a Porter-Duff composition to the part of the destination image
|
||||
// defined by dst and the translation of sr so that sr.Min translates to dp.
|
||||
func Copy(dst Image, dp image.Point, src image.Image, sr image.Rectangle, op Op, opts *Options) {
|
||||
var o Options
|
||||
if opts != nil {
|
||||
o = *opts
|
||||
}
|
||||
dr := sr.Add(dp.Sub(sr.Min))
|
||||
if o.DstMask == nil {
|
||||
DrawMask(dst, dr, src, sr.Min, o.SrcMask, o.SrcMaskP.Add(sr.Min), op)
|
||||
} else {
|
||||
NearestNeighbor.Scale(dst, dr, src, sr, op, opts)
|
||||
}
|
||||
}
|
||||
|
||||
// Scaler scales the part of the source image defined by src and sr and writes
|
||||
// the result of a Porter-Duff composition to the part of the destination image
|
||||
// defined by dst and dr.
|
||||
//
|
||||
// A Scaler is safe to use concurrently.
|
||||
type Scaler interface {
|
||||
Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options)
|
||||
}
|
||||
|
||||
// Transformer transforms the part of the source image defined by src and sr
|
||||
// and writes the result of a Porter-Duff composition to the part of the
|
||||
// destination image defined by dst and the affine transform m applied to sr.
|
||||
//
|
||||
// For example, if m is the matrix
|
||||
//
|
||||
// m00 m01 m02
|
||||
// m10 m11 m12
|
||||
//
|
||||
// then the src-space point (sx, sy) maps to the dst-space point
|
||||
// (m00*sx + m01*sy + m02, m10*sx + m11*sy + m12).
|
||||
//
|
||||
// A Transformer is safe to use concurrently.
|
||||
type Transformer interface {
|
||||
Transform(dst Image, m f64.Aff3, src image.Image, sr image.Rectangle, op Op, opts *Options)
|
||||
}
|
||||
|
||||
// Options are optional parameters to Copy, Scale and Transform.
|
||||
//
|
||||
// A nil *Options means to use the default (zero) values of each field.
|
||||
type Options struct {
|
||||
// Masks limit what parts of the dst image are drawn to and what parts of
|
||||
// the src image are drawn from.
|
||||
//
|
||||
// A dst or src mask image having a zero alpha (transparent) pixel value in
|
||||
// the respective coordinate space means that dst pixel is entirely
|
||||
// unaffected or that src pixel is considered transparent black. A full
|
||||
// alpha (opaque) value means that the dst pixel is maximally affected or
|
||||
// the src pixel contributes maximally. The default values, nil, are
|
||||
// equivalent to fully opaque, infinitely large mask images.
|
||||
//
|
||||
// The DstMask is otherwise known as a clip mask, and its pixels map 1:1 to
|
||||
// the dst image's pixels. DstMaskP in DstMask space corresponds to
|
||||
// image.Point{X:0, Y:0} in dst space. For example, when limiting
|
||||
// repainting to a 'dirty rectangle', use that image.Rectangle and a zero
|
||||
// image.Point as the DstMask and DstMaskP.
|
||||
//
|
||||
// The SrcMask's pixels map 1:1 to the src image's pixels. SrcMaskP in
|
||||
// SrcMask space corresponds to image.Point{X:0, Y:0} in src space. For
|
||||
// example, when drawing font glyphs in a uniform color, use an
|
||||
// *image.Uniform as the src, and use the glyph atlas image and the
|
||||
// per-glyph offset as SrcMask and SrcMaskP:
|
||||
// Copy(dst, dp, image.NewUniform(color), image.Rect(0, 0, glyphWidth, glyphHeight), &Options{
|
||||
// SrcMask: glyphAtlas,
|
||||
// SrcMaskP: glyphOffset,
|
||||
// })
|
||||
DstMask image.Image
|
||||
DstMaskP image.Point
|
||||
SrcMask image.Image
|
||||
SrcMaskP image.Point
|
||||
|
||||
// TODO: a smooth vs sharp edges option, for arbitrary rotations?
|
||||
}
|
||||
|
||||
// Interpolator is an interpolation algorithm, when dst and src pixels don't
|
||||
// have a 1:1 correspondence.
|
||||
//
|
||||
// Of the interpolators provided by this package:
|
||||
// - NearestNeighbor is fast but usually looks worst.
|
||||
// - CatmullRom is slow but usually looks best.
|
||||
// - ApproxBiLinear has reasonable speed and quality.
|
||||
//
|
||||
// The time taken depends on the size of dr. For kernel interpolators, the
|
||||
// speed also depends on the size of sr, and so are often slower than
|
||||
// non-kernel interpolators, especially when scaling down.
|
||||
type Interpolator interface {
|
||||
Scaler
|
||||
Transformer
|
||||
}
|
||||
|
||||
// Kernel is an interpolator that blends source pixels weighted by a symmetric
|
||||
// kernel function.
|
||||
type Kernel struct {
|
||||
// Support is the kernel support and must be >= 0. At(t) is assumed to be
|
||||
// zero when t >= Support.
|
||||
Support float64
|
||||
// At is the kernel function. It will only be called with t in the
|
||||
// range [0, Support).
|
||||
At func(t float64) float64
|
||||
}
|
||||
|
||||
// Scale implements the Scaler interface.
|
||||
func (q *Kernel) Scale(dst Image, dr image.Rectangle, src image.Image, sr image.Rectangle, op Op, opts *Options) {
|
||||
q.newScaler(dr.Dx(), dr.Dy(), sr.Dx(), sr.Dy(), false).Scale(dst, dr, src, sr, op, opts)
|
||||
}
|
||||
|
||||
// NewScaler returns a Scaler that is optimized for scaling multiple times with
|
||||
// the same fixed destination and source width and height.
|
||||
func (q *Kernel) NewScaler(dw, dh, sw, sh int) Scaler {
|
||||
return q.newScaler(dw, dh, sw, sh, true)
|
||||
}
|
||||
|
||||
func (q *Kernel) newScaler(dw, dh, sw, sh int, usePool bool) Scaler {
|
||||
z := &kernelScaler{
|
||||
kernel: q,
|
||||
dw: int32(dw),
|
||||
dh: int32(dh),
|
||||
sw: int32(sw),
|
||||
sh: int32(sh),
|
||||
horizontal: newDistrib(q, int32(dw), int32(sw)),
|
||||
vertical: newDistrib(q, int32(dh), int32(sh)),
|
||||
}
|
||||
if usePool {
|
||||
z.pool.New = func() interface{} {
|
||||
tmp := z.makeTmpBuf()
|
||||
return &tmp
|
||||
}
|
||||
}
|
||||
return z
|
||||
}
|
||||
|
||||
var (
|
||||
// NearestNeighbor is the nearest neighbor interpolator. It is very fast,
|
||||
// but usually gives very low quality results. When scaling up, the result
|
||||
// will look 'blocky'.
|
||||
NearestNeighbor = Interpolator(nnInterpolator{})
|
||||
|
||||
// ApproxBiLinear is a mixture of the nearest neighbor and bi-linear
|
||||
// interpolators. It is fast, but usually gives medium quality results.
|
||||
//
|
||||
// It implements bi-linear interpolation when upscaling and a bi-linear
|
||||
// blend of the 4 nearest neighbor pixels when downscaling. This yields
|
||||
// nicer quality than nearest neighbor interpolation when upscaling, but
|
||||
// the time taken is independent of the number of source pixels, unlike the
|
||||
// bi-linear interpolator. When downscaling a large image, the performance
|
||||
// difference can be significant.
|
||||
ApproxBiLinear = Interpolator(ablInterpolator{})
|
||||
|
||||
// BiLinear is the tent kernel. It is slow, but usually gives high quality
|
||||
// results.
|
||||
BiLinear = &Kernel{1, func(t float64) float64 {
|
||||
return 1 - t
|
||||
}}
|
||||
|
||||
// CatmullRom is the Catmull-Rom kernel. It is very slow, but usually gives
|
||||
// very high quality results.
|
||||
//
|
||||
// It is an instance of the more general cubic BC-spline kernel with parameters
|
||||
// B=0 and C=0.5. See Mitchell and Netravali, "Reconstruction Filters in
|
||||
// Computer Graphics", Computer Graphics, Vol. 22, No. 4, pp. 221-228.
|
||||
CatmullRom = &Kernel{2, func(t float64) float64 {
|
||||
if t < 1 {
|
||||
return (1.5*t-2.5)*t*t + 1
|
||||
}
|
||||
return ((-0.5*t+2.5)*t-4)*t + 2
|
||||
}}
|
||||
|
||||
// TODO: a Kaiser-Bessel kernel?
|
||||
)
|
||||
|
||||
type nnInterpolator struct{}
|
||||
|
||||
type ablInterpolator struct{}
|
||||
|
||||
type kernelScaler struct {
|
||||
kernel *Kernel
|
||||
dw, dh, sw, sh int32
|
||||
horizontal, vertical distrib
|
||||
pool sync.Pool
|
||||
}
|
||||
|
||||
func (z *kernelScaler) makeTmpBuf() [][4]float64 {
|
||||
return make([][4]float64, z.dw*z.sh)
|
||||
}
|
||||
|
||||
// source is a range of contribs, their inverse total weight, and that ITW
|
||||
// divided by 0xffff.
|
||||
type source struct {
|
||||
i, j int32
|
||||
invTotalWeight float64
|
||||
invTotalWeightFFFF float64
|
||||
}
|
||||
|
||||
// contrib is the weight of a column or row.
|
||||
type contrib struct {
|
||||
coord int32
|
||||
weight float64
|
||||
}
|
||||
|
||||
// distrib measures how source pixels are distributed over destination pixels.
|
||||
type distrib struct {
|
||||
// sources are what contribs each column or row in the source image owns,
|
||||
// and the total weight of those contribs.
|
||||
sources []source
|
||||
// contribs are the contributions indexed by sources[s].i and sources[s].j.
|
||||
contribs []contrib
|
||||
}
|
||||
|
||||
// newDistrib returns a distrib that distributes sw source columns (or rows)
|
||||
// over dw destination columns (or rows).
|
||||
func newDistrib(q *Kernel, dw, sw int32) distrib {
|
||||
scale := float64(sw) / float64(dw)
|
||||
halfWidth, kernelArgScale := q.Support, 1.0
|
||||
// When shrinking, broaden the effective kernel support so that we still
|
||||
// visit every source pixel.
|
||||
if scale > 1 {
|
||||
halfWidth *= scale
|
||||
kernelArgScale = 1 / scale
|
||||
}
|
||||
|
||||
// Make the sources slice, one source for each column or row, and temporarily
|
||||
// appropriate its elements' fields so that invTotalWeight is the scaled
|
||||
// coordinate of the source column or row, and i and j are the lower and
|
||||
// upper bounds of the range of destination columns or rows affected by the
|
||||
// source column or row.
|
||||
n, sources := int32(0), make([]source, dw)
|
||||
for x := range sources {
|
||||
center := (float64(x)+0.5)*scale - 0.5
|
||||
i := int32(math.Floor(center - halfWidth))
|
||||
if i < 0 {
|
||||
i = 0
|
||||
}
|
||||
j := int32(math.Ceil(center + halfWidth))
|
||||
if j > sw {
|
||||
j = sw
|
||||
if j < i {
|
||||
j = i
|
||||
}
|
||||
}
|
||||
sources[x] = source{i: i, j: j, invTotalWeight: center}
|
||||
n += j - i
|
||||
}
|
||||
|
||||
contribs := make([]contrib, 0, n)
|
||||
for k, b := range sources {
|
||||
totalWeight := 0.0
|
||||
l := int32(len(contribs))
|
||||
for coord := b.i; coord < b.j; coord++ {
|
||||
t := abs((b.invTotalWeight - float64(coord)) * kernelArgScale)
|
||||
if t >= q.Support {
|
||||
continue
|
||||
}
|
||||
weight := q.At(t)
|
||||
if weight == 0 {
|
||||
continue
|
||||
}
|
||||
totalWeight += weight
|
||||
contribs = append(contribs, contrib{coord, weight})
|
||||
}
|
||||
totalWeight = 1 / totalWeight
|
||||
sources[k] = source{
|
||||
i: l,
|
||||
j: int32(len(contribs)),
|
||||
invTotalWeight: totalWeight,
|
||||
invTotalWeightFFFF: totalWeight / 0xffff,
|
||||
}
|
||||
}
|
||||
|
||||
return distrib{sources, contribs}
|
||||
}
|
||||
|
||||
// abs is like math.Abs, but it doesn't care about negative zero, infinities or
|
||||
// NaNs.
|
||||
func abs(f float64) float64 {
|
||||
if f < 0 {
|
||||
f = -f
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// ftou converts the range [0.0, 1.0] to [0, 0xffff].
|
||||
func ftou(f float64) uint16 {
|
||||
i := int32(0xffff*f + 0.5)
|
||||
if i > 0xffff {
|
||||
return 0xffff
|
||||
}
|
||||
if i > 0 {
|
||||
return uint16(i)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// fffftou converts the range [0.0, 65535.0] to [0, 0xffff].
|
||||
func fffftou(f float64) uint16 {
|
||||
i := int32(f + 0.5)
|
||||
if i > 0xffff {
|
||||
return 0xffff
|
||||
}
|
||||
if i > 0 {
|
||||
return uint16(i)
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// invert returns the inverse of m.
|
||||
//
|
||||
// TODO: move this into the f64 package, once we work out the convention for
|
||||
// matrix methods in that package: do they modify the receiver, take a dst
|
||||
// pointer argument, or return a new value?
|
||||
func invert(m *f64.Aff3) f64.Aff3 {
|
||||
m00 := +m[3*1+1]
|
||||
m01 := -m[3*0+1]
|
||||
m02 := +m[3*1+2]*m[3*0+1] - m[3*1+1]*m[3*0+2]
|
||||
m10 := -m[3*1+0]
|
||||
m11 := +m[3*0+0]
|
||||
m12 := +m[3*1+0]*m[3*0+2] - m[3*1+2]*m[3*0+0]
|
||||
|
||||
det := m00*m11 - m10*m01
|
||||
|
||||
return f64.Aff3{
|
||||
m00 / det,
|
||||
m01 / det,
|
||||
m02 / det,
|
||||
m10 / det,
|
||||
m11 / det,
|
||||
m12 / det,
|
||||
}
|
||||
}
|
||||
|
||||
func matMul(p, q *f64.Aff3) f64.Aff3 {
|
||||
return f64.Aff3{
|
||||
p[3*0+0]*q[3*0+0] + p[3*0+1]*q[3*1+0],
|
||||
p[3*0+0]*q[3*0+1] + p[3*0+1]*q[3*1+1],
|
||||
p[3*0+0]*q[3*0+2] + p[3*0+1]*q[3*1+2] + p[3*0+2],
|
||||
p[3*1+0]*q[3*0+0] + p[3*1+1]*q[3*1+0],
|
||||
p[3*1+0]*q[3*0+1] + p[3*1+1]*q[3*1+1],
|
||||
p[3*1+0]*q[3*0+2] + p[3*1+1]*q[3*1+2] + p[3*1+2],
|
||||
}
|
||||
}
|
||||
|
||||
// transformRect returns a rectangle dr that contains sr transformed by s2d.
|
||||
func transformRect(s2d *f64.Aff3, sr *image.Rectangle) (dr image.Rectangle) {
|
||||
ps := [...]image.Point{
|
||||
{sr.Min.X, sr.Min.Y},
|
||||
{sr.Max.X, sr.Min.Y},
|
||||
{sr.Min.X, sr.Max.Y},
|
||||
{sr.Max.X, sr.Max.Y},
|
||||
}
|
||||
for i, p := range ps {
|
||||
sxf := float64(p.X)
|
||||
syf := float64(p.Y)
|
||||
dx := int(math.Floor(s2d[0]*sxf + s2d[1]*syf + s2d[2]))
|
||||
dy := int(math.Floor(s2d[3]*sxf + s2d[4]*syf + s2d[5]))
|
||||
|
||||
// The +1 adjustments below are because an image.Rectangle is inclusive
|
||||
// on the low end but exclusive on the high end.
|
||||
|
||||
if i == 0 {
|
||||
dr = image.Rectangle{
|
||||
Min: image.Point{dx + 0, dy + 0},
|
||||
Max: image.Point{dx + 1, dy + 1},
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
if dr.Min.X > dx {
|
||||
dr.Min.X = dx
|
||||
}
|
||||
dx++
|
||||
if dr.Max.X < dx {
|
||||
dr.Max.X = dx
|
||||
}
|
||||
|
||||
if dr.Min.Y > dy {
|
||||
dr.Min.Y = dy
|
||||
}
|
||||
dy++
|
||||
if dr.Max.Y < dy {
|
||||
dr.Max.Y = dy
|
||||
}
|
||||
}
|
||||
return dr
|
||||
}
|
||||
|
||||
func clipAffectedDestRect(adr image.Rectangle, dstMask image.Image, dstMaskP image.Point) (image.Rectangle, image.Image) {
|
||||
if dstMask == nil {
|
||||
return adr, nil
|
||||
}
|
||||
if r, ok := dstMask.(image.Rectangle); ok {
|
||||
return adr.Intersect(r.Sub(dstMaskP)), nil
|
||||
}
|
||||
// TODO: clip to dstMask.Bounds() if the color model implies that out-of-bounds means 0 alpha?
|
||||
return adr, dstMask
|
||||
}
|
||||
|
||||
func transform_Uniform(dst Image, dr, adr image.Rectangle, d2s *f64.Aff3, src *image.Uniform, sr image.Rectangle, bias image.Point, op Op) {
|
||||
switch op {
|
||||
case Over:
|
||||
switch dst := dst.(type) {
|
||||
case *image.RGBA:
|
||||
pr, pg, pb, pa := src.C.RGBA()
|
||||
pa1 := (0xffff - pa) * 0x101
|
||||
|
||||
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
|
||||
dyf := float64(dr.Min.Y+int(dy)) + 0.5
|
||||
d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy))
|
||||
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
|
||||
dxf := float64(dr.Min.X+int(dx)) + 0.5
|
||||
sx0 := int(d2s[0]*dxf+d2s[1]*dyf+d2s[2]) + bias.X
|
||||
sy0 := int(d2s[3]*dxf+d2s[4]*dyf+d2s[5]) + bias.Y
|
||||
if !(image.Point{sx0, sy0}).In(sr) {
|
||||
continue
|
||||
}
|
||||
dst.Pix[d+0] = uint8((uint32(dst.Pix[d+0])*pa1/0xffff + pr) >> 8)
|
||||
dst.Pix[d+1] = uint8((uint32(dst.Pix[d+1])*pa1/0xffff + pg) >> 8)
|
||||
dst.Pix[d+2] = uint8((uint32(dst.Pix[d+2])*pa1/0xffff + pb) >> 8)
|
||||
dst.Pix[d+3] = uint8((uint32(dst.Pix[d+3])*pa1/0xffff + pa) >> 8)
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
pr, pg, pb, pa := src.C.RGBA()
|
||||
pa1 := 0xffff - pa
|
||||
dstColorRGBA64 := &color.RGBA64{}
|
||||
dstColor := color.Color(dstColorRGBA64)
|
||||
|
||||
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
|
||||
dyf := float64(dr.Min.Y+int(dy)) + 0.5
|
||||
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
|
||||
dxf := float64(dr.Min.X+int(dx)) + 0.5
|
||||
sx0 := int(d2s[0]*dxf+d2s[1]*dyf+d2s[2]) + bias.X
|
||||
sy0 := int(d2s[3]*dxf+d2s[4]*dyf+d2s[5]) + bias.Y
|
||||
if !(image.Point{sx0, sy0}).In(sr) {
|
||||
continue
|
||||
}
|
||||
qr, qg, qb, qa := dst.At(dr.Min.X+int(dx), dr.Min.Y+int(dy)).RGBA()
|
||||
dstColorRGBA64.R = uint16(qr*pa1/0xffff + pr)
|
||||
dstColorRGBA64.G = uint16(qg*pa1/0xffff + pg)
|
||||
dstColorRGBA64.B = uint16(qb*pa1/0xffff + pb)
|
||||
dstColorRGBA64.A = uint16(qa*pa1/0xffff + pa)
|
||||
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
case Src:
|
||||
switch dst := dst.(type) {
|
||||
case *image.RGBA:
|
||||
pr, pg, pb, pa := src.C.RGBA()
|
||||
pr8 := uint8(pr >> 8)
|
||||
pg8 := uint8(pg >> 8)
|
||||
pb8 := uint8(pb >> 8)
|
||||
pa8 := uint8(pa >> 8)
|
||||
|
||||
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
|
||||
dyf := float64(dr.Min.Y+int(dy)) + 0.5
|
||||
d := dst.PixOffset(dr.Min.X+adr.Min.X, dr.Min.Y+int(dy))
|
||||
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx, d = dx+1, d+4 {
|
||||
dxf := float64(dr.Min.X+int(dx)) + 0.5
|
||||
sx0 := int(d2s[0]*dxf+d2s[1]*dyf+d2s[2]) + bias.X
|
||||
sy0 := int(d2s[3]*dxf+d2s[4]*dyf+d2s[5]) + bias.Y
|
||||
if !(image.Point{sx0, sy0}).In(sr) {
|
||||
continue
|
||||
}
|
||||
dst.Pix[d+0] = pr8
|
||||
dst.Pix[d+1] = pg8
|
||||
dst.Pix[d+2] = pb8
|
||||
dst.Pix[d+3] = pa8
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
pr, pg, pb, pa := src.C.RGBA()
|
||||
dstColorRGBA64 := &color.RGBA64{
|
||||
uint16(pr),
|
||||
uint16(pg),
|
||||
uint16(pb),
|
||||
uint16(pa),
|
||||
}
|
||||
dstColor := color.Color(dstColorRGBA64)
|
||||
|
||||
for dy := int32(adr.Min.Y); dy < int32(adr.Max.Y); dy++ {
|
||||
dyf := float64(dr.Min.Y+int(dy)) + 0.5
|
||||
for dx := int32(adr.Min.X); dx < int32(adr.Max.X); dx++ {
|
||||
dxf := float64(dr.Min.X+int(dx)) + 0.5
|
||||
sx0 := int(d2s[0]*dxf+d2s[1]*dyf+d2s[2]) + bias.X
|
||||
sy0 := int(d2s[3]*dxf+d2s[4]*dyf+d2s[5]) + bias.Y
|
||||
if !(image.Point{sx0, sy0}).In(sr) {
|
||||
continue
|
||||
}
|
||||
dst.Set(dr.Min.X+int(dx), dr.Min.Y+int(dy), dstColor)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func opaque(m image.Image) bool {
|
||||
o, ok := m.(interface {
|
||||
Opaque() bool
|
||||
})
|
||||
return ok && o.Opaque()
|
||||
}
|
||||
37
vendor/golang.org/x/image/math/f64/f64.go
сгенерированный
поставляемый
Обычный файл
37
vendor/golang.org/x/image/math/f64/f64.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,37 @@
|
||||
// Copyright 2015 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package f64 implements float64 vector and matrix types.
|
||||
package f64 // import "golang.org/x/image/math/f64"
|
||||
|
||||
// Vec2 is a 2-element vector.
|
||||
type Vec2 [2]float64
|
||||
|
||||
// Vec3 is a 3-element vector.
|
||||
type Vec3 [3]float64
|
||||
|
||||
// Vec4 is a 4-element vector.
|
||||
type Vec4 [4]float64
|
||||
|
||||
// Mat3 is a 3x3 matrix in row major order.
|
||||
//
|
||||
// m[3*r + c] is the element in the r'th row and c'th column.
|
||||
type Mat3 [9]float64
|
||||
|
||||
// Mat4 is a 4x4 matrix in row major order.
|
||||
//
|
||||
// m[4*r + c] is the element in the r'th row and c'th column.
|
||||
type Mat4 [16]float64
|
||||
|
||||
// Aff3 is a 3x3 affine transformation matrix in row major order, where the
|
||||
// bottom row is implicitly [0 0 1].
|
||||
//
|
||||
// m[3*r + c] is the element in the r'th row and c'th column.
|
||||
type Aff3 [6]float64
|
||||
|
||||
// Aff4 is a 4x4 affine transformation matrix in row major order, where the
|
||||
// bottom row is implicitly [0 0 0 1].
|
||||
//
|
||||
// m[4*r + c] is the element in the r'th row and c'th column.
|
||||
type Aff4 [12]float64
|
||||
193
vendor/golang.org/x/image/riff/riff.go
сгенерированный
поставляемый
Обычный файл
193
vendor/golang.org/x/image/riff/riff.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,193 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package riff implements the Resource Interchange File Format, used by media
|
||||
// formats such as AVI, WAVE and WEBP.
|
||||
//
|
||||
// A RIFF stream contains a sequence of chunks. Each chunk consists of an 8-byte
|
||||
// header (containing a 4-byte chunk type and a 4-byte chunk length), the chunk
|
||||
// data (presented as an io.Reader), and some padding bytes.
|
||||
//
|
||||
// A detailed description of the format is at
|
||||
// http://www.tactilemedia.com/info/MCI_Control_Info.html
|
||||
package riff // import "golang.org/x/image/riff"
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
)
|
||||
|
||||
var (
|
||||
errMissingPaddingByte = errors.New("riff: missing padding byte")
|
||||
errMissingRIFFChunkHeader = errors.New("riff: missing RIFF chunk header")
|
||||
errListSubchunkTooLong = errors.New("riff: list subchunk too long")
|
||||
errShortChunkData = errors.New("riff: short chunk data")
|
||||
errShortChunkHeader = errors.New("riff: short chunk header")
|
||||
errStaleReader = errors.New("riff: stale reader")
|
||||
)
|
||||
|
||||
// u32 decodes the first four bytes of b as a little-endian integer.
|
||||
func u32(b []byte) uint32 {
|
||||
return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24
|
||||
}
|
||||
|
||||
const chunkHeaderSize = 8
|
||||
|
||||
// FourCC is a four character code.
|
||||
type FourCC [4]byte
|
||||
|
||||
// LIST is the "LIST" FourCC.
|
||||
var LIST = FourCC{'L', 'I', 'S', 'T'}
|
||||
|
||||
// NewReader returns the RIFF stream's form type, such as "AVI " or "WAVE", and
|
||||
// its chunks as a *Reader.
|
||||
func NewReader(r io.Reader) (formType FourCC, data *Reader, err error) {
|
||||
var buf [chunkHeaderSize]byte
|
||||
if _, err := io.ReadFull(r, buf[:]); err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
err = errMissingRIFFChunkHeader
|
||||
}
|
||||
return FourCC{}, nil, err
|
||||
}
|
||||
if buf[0] != 'R' || buf[1] != 'I' || buf[2] != 'F' || buf[3] != 'F' {
|
||||
return FourCC{}, nil, errMissingRIFFChunkHeader
|
||||
}
|
||||
return NewListReader(u32(buf[4:]), r)
|
||||
}
|
||||
|
||||
// NewListReader returns a LIST chunk's list type, such as "movi" or "wavl",
|
||||
// and its chunks as a *Reader.
|
||||
func NewListReader(chunkLen uint32, chunkData io.Reader) (listType FourCC, data *Reader, err error) {
|
||||
if chunkLen < 4 {
|
||||
return FourCC{}, nil, errShortChunkData
|
||||
}
|
||||
z := &Reader{r: chunkData}
|
||||
if _, err := io.ReadFull(chunkData, z.buf[:4]); err != nil {
|
||||
if err == io.EOF || err == io.ErrUnexpectedEOF {
|
||||
err = errShortChunkData
|
||||
}
|
||||
return FourCC{}, nil, err
|
||||
}
|
||||
z.totalLen = chunkLen - 4
|
||||
return FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]}, z, nil
|
||||
}
|
||||
|
||||
// Reader reads chunks from an underlying io.Reader.
|
||||
type Reader struct {
|
||||
r io.Reader
|
||||
err error
|
||||
|
||||
totalLen uint32
|
||||
chunkLen uint32
|
||||
|
||||
chunkReader *chunkReader
|
||||
buf [chunkHeaderSize]byte
|
||||
padded bool
|
||||
}
|
||||
|
||||
// Next returns the next chunk's ID, length and data. It returns io.EOF if there
|
||||
// are no more chunks. The io.Reader returned becomes stale after the next Next
|
||||
// call, and should no longer be used.
|
||||
//
|
||||
// It is valid to call Next even if all of the previous chunk's data has not
|
||||
// been read.
|
||||
func (z *Reader) Next() (chunkID FourCC, chunkLen uint32, chunkData io.Reader, err error) {
|
||||
if z.err != nil {
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
|
||||
// Drain the rest of the previous chunk.
|
||||
if z.chunkLen != 0 {
|
||||
want := z.chunkLen
|
||||
var got int64
|
||||
got, z.err = io.Copy(ioutil.Discard, z.chunkReader)
|
||||
if z.err == nil && uint32(got) != want {
|
||||
z.err = errShortChunkData
|
||||
}
|
||||
if z.err != nil {
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
}
|
||||
z.chunkReader = nil
|
||||
if z.padded {
|
||||
if z.totalLen == 0 {
|
||||
z.err = errListSubchunkTooLong
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
z.totalLen--
|
||||
_, z.err = io.ReadFull(z.r, z.buf[:1])
|
||||
if z.err != nil {
|
||||
if z.err == io.EOF {
|
||||
z.err = errMissingPaddingByte
|
||||
}
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
}
|
||||
|
||||
// We are done if we have no more data.
|
||||
if z.totalLen == 0 {
|
||||
z.err = io.EOF
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
|
||||
// Read the next chunk header.
|
||||
if z.totalLen < chunkHeaderSize {
|
||||
z.err = errShortChunkHeader
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
z.totalLen -= chunkHeaderSize
|
||||
if _, z.err = io.ReadFull(z.r, z.buf[:chunkHeaderSize]); z.err != nil {
|
||||
if z.err == io.EOF || z.err == io.ErrUnexpectedEOF {
|
||||
z.err = errShortChunkHeader
|
||||
}
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
chunkID = FourCC{z.buf[0], z.buf[1], z.buf[2], z.buf[3]}
|
||||
z.chunkLen = u32(z.buf[4:])
|
||||
if z.chunkLen > z.totalLen {
|
||||
z.err = errListSubchunkTooLong
|
||||
return FourCC{}, 0, nil, z.err
|
||||
}
|
||||
z.padded = z.chunkLen&1 == 1
|
||||
z.chunkReader = &chunkReader{z}
|
||||
return chunkID, z.chunkLen, z.chunkReader, nil
|
||||
}
|
||||
|
||||
type chunkReader struct {
|
||||
z *Reader
|
||||
}
|
||||
|
||||
func (c *chunkReader) Read(p []byte) (int, error) {
|
||||
if c != c.z.chunkReader {
|
||||
return 0, errStaleReader
|
||||
}
|
||||
z := c.z
|
||||
if z.err != nil {
|
||||
if z.err == io.EOF {
|
||||
return 0, errStaleReader
|
||||
}
|
||||
return 0, z.err
|
||||
}
|
||||
|
||||
n := int(z.chunkLen)
|
||||
if n == 0 {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if n < 0 {
|
||||
// Converting uint32 to int overflowed.
|
||||
n = math.MaxInt32
|
||||
}
|
||||
if n > len(p) {
|
||||
n = len(p)
|
||||
}
|
||||
n, err := z.r.Read(p[:n])
|
||||
z.totalLen -= uint32(n)
|
||||
z.chunkLen -= uint32(n)
|
||||
if err != io.EOF {
|
||||
z.err = err
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
403
vendor/golang.org/x/image/vp8/decode.go
сгенерированный
поставляемый
Обычный файл
403
vendor/golang.org/x/image/vp8/decode.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,403 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package vp8 implements a decoder for the VP8 lossy image format.
|
||||
//
|
||||
// The VP8 specification is RFC 6386.
|
||||
package vp8 // import "golang.org/x/image/vp8"
|
||||
|
||||
// This file implements the top-level decoding algorithm.
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"image"
|
||||
"io"
|
||||
)
|
||||
|
||||
// limitReader wraps an io.Reader to read at most n bytes from it.
|
||||
type limitReader struct {
|
||||
r io.Reader
|
||||
n int
|
||||
}
|
||||
|
||||
// ReadFull reads exactly len(p) bytes into p.
|
||||
func (r *limitReader) ReadFull(p []byte) error {
|
||||
if len(p) > r.n {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
n, err := io.ReadFull(r.r, p)
|
||||
r.n -= n
|
||||
return err
|
||||
}
|
||||
|
||||
// FrameHeader is a frame header, as specified in section 9.1.
|
||||
type FrameHeader struct {
|
||||
KeyFrame bool
|
||||
VersionNumber uint8
|
||||
ShowFrame bool
|
||||
FirstPartitionLen uint32
|
||||
Width int
|
||||
Height int
|
||||
XScale uint8
|
||||
YScale uint8
|
||||
}
|
||||
|
||||
const (
|
||||
nSegment = 4
|
||||
nSegmentProb = 3
|
||||
)
|
||||
|
||||
// segmentHeader holds segment-related header information.
|
||||
type segmentHeader struct {
|
||||
useSegment bool
|
||||
updateMap bool
|
||||
relativeDelta bool
|
||||
quantizer [nSegment]int8
|
||||
filterStrength [nSegment]int8
|
||||
prob [nSegmentProb]uint8
|
||||
}
|
||||
|
||||
const (
|
||||
nRefLFDelta = 4
|
||||
nModeLFDelta = 4
|
||||
)
|
||||
|
||||
// filterHeader holds filter-related header information.
|
||||
type filterHeader struct {
|
||||
simple bool
|
||||
level int8
|
||||
sharpness uint8
|
||||
useLFDelta bool
|
||||
refLFDelta [nRefLFDelta]int8
|
||||
modeLFDelta [nModeLFDelta]int8
|
||||
perSegmentLevel [nSegment]int8
|
||||
}
|
||||
|
||||
// mb is the per-macroblock decode state. A decoder maintains mbw+1 of these
|
||||
// as it is decoding macroblocks left-to-right and top-to-bottom: mbw for the
|
||||
// macroblocks in the row above, and one for the macroblock to the left.
|
||||
type mb struct {
|
||||
// pred is the predictor mode for the 4 bottom or right 4x4 luma regions.
|
||||
pred [4]uint8
|
||||
// nzMask is a mask of 8 bits: 4 for the bottom or right 4x4 luma regions,
|
||||
// and 2 + 2 for the bottom or right 4x4 chroma regions. A 1 bit indicates
|
||||
// that region has non-zero coefficients.
|
||||
nzMask uint8
|
||||
// nzY16 is a 0/1 value that is 1 if the macroblock used Y16 prediction and
|
||||
// had non-zero coefficients.
|
||||
nzY16 uint8
|
||||
}
|
||||
|
||||
// Decoder decodes VP8 bitstreams into frames. Decoding one frame consists of
|
||||
// calling Init, DecodeFrameHeader and then DecodeFrame in that order.
|
||||
// A Decoder can be re-used to decode multiple frames.
|
||||
type Decoder struct {
|
||||
// r is the input bitsream.
|
||||
r limitReader
|
||||
// scratch is a scratch buffer.
|
||||
scratch [8]byte
|
||||
// img is the YCbCr image to decode into.
|
||||
img *image.YCbCr
|
||||
// mbw and mbh are the number of 16x16 macroblocks wide and high the image is.
|
||||
mbw, mbh int
|
||||
// frameHeader is the frame header. When decoding multiple frames,
|
||||
// frames that aren't key frames will inherit the Width, Height,
|
||||
// XScale and YScale of the most recent key frame.
|
||||
frameHeader FrameHeader
|
||||
// Other headers.
|
||||
segmentHeader segmentHeader
|
||||
filterHeader filterHeader
|
||||
// The image data is divided into a number of independent partitions.
|
||||
// There is 1 "first partition" and between 1 and 8 "other partitions"
|
||||
// for coefficient data.
|
||||
fp partition
|
||||
op [8]partition
|
||||
nOP int
|
||||
// Quantization factors.
|
||||
quant [nSegment]quant
|
||||
// DCT/WHT coefficient decoding probabilities.
|
||||
tokenProb [nPlane][nBand][nContext][nProb]uint8
|
||||
useSkipProb bool
|
||||
skipProb uint8
|
||||
// Loop filter parameters.
|
||||
filterParams [nSegment][2]filterParam
|
||||
perMBFilterParams []filterParam
|
||||
|
||||
// The eight fields below relate to the current macroblock being decoded.
|
||||
//
|
||||
// Segment-based adjustments.
|
||||
segment int
|
||||
// Per-macroblock state for the macroblock immediately left of and those
|
||||
// macroblocks immediately above the current macroblock.
|
||||
leftMB mb
|
||||
upMB []mb
|
||||
// Bitmasks for which 4x4 regions of coeff contain non-zero coefficients.
|
||||
nzDCMask, nzACMask uint32
|
||||
// Predictor modes.
|
||||
usePredY16 bool // The libwebp C code calls this !is_i4x4_.
|
||||
predY16 uint8
|
||||
predC8 uint8
|
||||
predY4 [4][4]uint8
|
||||
|
||||
// The two fields below form a workspace for reconstructing a macroblock.
|
||||
// Their specific sizes are documented in reconstruct.go.
|
||||
coeff [1*16*16 + 2*8*8 + 1*4*4]int16
|
||||
ybr [1 + 16 + 1 + 8][32]uint8
|
||||
}
|
||||
|
||||
// NewDecoder returns a new Decoder.
|
||||
func NewDecoder() *Decoder {
|
||||
return &Decoder{}
|
||||
}
|
||||
|
||||
// Init initializes the decoder to read at most n bytes from r.
|
||||
func (d *Decoder) Init(r io.Reader, n int) {
|
||||
d.r = limitReader{r, n}
|
||||
}
|
||||
|
||||
// DecodeFrameHeader decodes the frame header.
|
||||
func (d *Decoder) DecodeFrameHeader() (fh FrameHeader, err error) {
|
||||
// All frame headers are at least 3 bytes long.
|
||||
b := d.scratch[:3]
|
||||
if err = d.r.ReadFull(b); err != nil {
|
||||
return
|
||||
}
|
||||
d.frameHeader.KeyFrame = (b[0] & 1) == 0
|
||||
d.frameHeader.VersionNumber = (b[0] >> 1) & 7
|
||||
d.frameHeader.ShowFrame = (b[0]>>4)&1 == 1
|
||||
d.frameHeader.FirstPartitionLen = uint32(b[0])>>5 | uint32(b[1])<<3 | uint32(b[2])<<11
|
||||
if !d.frameHeader.KeyFrame {
|
||||
return d.frameHeader, nil
|
||||
}
|
||||
// Frame headers for key frames are an additional 7 bytes long.
|
||||
b = d.scratch[:7]
|
||||
if err = d.r.ReadFull(b); err != nil {
|
||||
return
|
||||
}
|
||||
// Check the magic sync code.
|
||||
if b[0] != 0x9d || b[1] != 0x01 || b[2] != 0x2a {
|
||||
err = errors.New("vp8: invalid format")
|
||||
return
|
||||
}
|
||||
d.frameHeader.Width = int(b[4]&0x3f)<<8 | int(b[3])
|
||||
d.frameHeader.Height = int(b[6]&0x3f)<<8 | int(b[5])
|
||||
d.frameHeader.XScale = b[4] >> 6
|
||||
d.frameHeader.YScale = b[6] >> 6
|
||||
d.mbw = (d.frameHeader.Width + 0x0f) >> 4
|
||||
d.mbh = (d.frameHeader.Height + 0x0f) >> 4
|
||||
d.segmentHeader = segmentHeader{
|
||||
prob: [3]uint8{0xff, 0xff, 0xff},
|
||||
}
|
||||
d.tokenProb = defaultTokenProb
|
||||
d.segment = 0
|
||||
return d.frameHeader, nil
|
||||
}
|
||||
|
||||
// ensureImg ensures that d.img is large enough to hold the decoded frame.
|
||||
func (d *Decoder) ensureImg() {
|
||||
if d.img != nil {
|
||||
p0, p1 := d.img.Rect.Min, d.img.Rect.Max
|
||||
if p0.X == 0 && p0.Y == 0 && p1.X >= 16*d.mbw && p1.Y >= 16*d.mbh {
|
||||
return
|
||||
}
|
||||
}
|
||||
m := image.NewYCbCr(image.Rect(0, 0, 16*d.mbw, 16*d.mbh), image.YCbCrSubsampleRatio420)
|
||||
d.img = m.SubImage(image.Rect(0, 0, d.frameHeader.Width, d.frameHeader.Height)).(*image.YCbCr)
|
||||
d.perMBFilterParams = make([]filterParam, d.mbw*d.mbh)
|
||||
d.upMB = make([]mb, d.mbw)
|
||||
}
|
||||
|
||||
// parseSegmentHeader parses the segment header, as specified in section 9.3.
|
||||
func (d *Decoder) parseSegmentHeader() {
|
||||
d.segmentHeader.useSegment = d.fp.readBit(uniformProb)
|
||||
if !d.segmentHeader.useSegment {
|
||||
d.segmentHeader.updateMap = false
|
||||
return
|
||||
}
|
||||
d.segmentHeader.updateMap = d.fp.readBit(uniformProb)
|
||||
if d.fp.readBit(uniformProb) {
|
||||
d.segmentHeader.relativeDelta = !d.fp.readBit(uniformProb)
|
||||
for i := range d.segmentHeader.quantizer {
|
||||
d.segmentHeader.quantizer[i] = int8(d.fp.readOptionalInt(uniformProb, 7))
|
||||
}
|
||||
for i := range d.segmentHeader.filterStrength {
|
||||
d.segmentHeader.filterStrength[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
|
||||
}
|
||||
}
|
||||
if !d.segmentHeader.updateMap {
|
||||
return
|
||||
}
|
||||
for i := range d.segmentHeader.prob {
|
||||
if d.fp.readBit(uniformProb) {
|
||||
d.segmentHeader.prob[i] = uint8(d.fp.readUint(uniformProb, 8))
|
||||
} else {
|
||||
d.segmentHeader.prob[i] = 0xff
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parseFilterHeader parses the filter header, as specified in section 9.4.
|
||||
func (d *Decoder) parseFilterHeader() {
|
||||
d.filterHeader.simple = d.fp.readBit(uniformProb)
|
||||
d.filterHeader.level = int8(d.fp.readUint(uniformProb, 6))
|
||||
d.filterHeader.sharpness = uint8(d.fp.readUint(uniformProb, 3))
|
||||
d.filterHeader.useLFDelta = d.fp.readBit(uniformProb)
|
||||
if d.filterHeader.useLFDelta && d.fp.readBit(uniformProb) {
|
||||
for i := range d.filterHeader.refLFDelta {
|
||||
d.filterHeader.refLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
|
||||
}
|
||||
for i := range d.filterHeader.modeLFDelta {
|
||||
d.filterHeader.modeLFDelta[i] = int8(d.fp.readOptionalInt(uniformProb, 6))
|
||||
}
|
||||
}
|
||||
if d.filterHeader.level == 0 {
|
||||
return
|
||||
}
|
||||
if d.segmentHeader.useSegment {
|
||||
for i := range d.filterHeader.perSegmentLevel {
|
||||
strength := d.segmentHeader.filterStrength[i]
|
||||
if d.segmentHeader.relativeDelta {
|
||||
strength += d.filterHeader.level
|
||||
}
|
||||
d.filterHeader.perSegmentLevel[i] = strength
|
||||
}
|
||||
} else {
|
||||
d.filterHeader.perSegmentLevel[0] = d.filterHeader.level
|
||||
}
|
||||
d.computeFilterParams()
|
||||
}
|
||||
|
||||
// parseOtherPartitions parses the other partitions, as specified in section 9.5.
|
||||
func (d *Decoder) parseOtherPartitions() error {
|
||||
const maxNOP = 1 << 3
|
||||
var partLens [maxNOP]int
|
||||
d.nOP = 1 << d.fp.readUint(uniformProb, 2)
|
||||
|
||||
// The final partition length is implied by the remaining chunk data
|
||||
// (d.r.n) and the other d.nOP-1 partition lengths. Those d.nOP-1 partition
|
||||
// lengths are stored as 24-bit uints, i.e. up to 16 MiB per partition.
|
||||
n := 3 * (d.nOP - 1)
|
||||
partLens[d.nOP-1] = d.r.n - n
|
||||
if partLens[d.nOP-1] < 0 {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
if n > 0 {
|
||||
buf := make([]byte, n)
|
||||
if err := d.r.ReadFull(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := 0; i < d.nOP-1; i++ {
|
||||
pl := int(buf[3*i+0]) | int(buf[3*i+1])<<8 | int(buf[3*i+2])<<16
|
||||
if pl > partLens[d.nOP-1] {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
partLens[i] = pl
|
||||
partLens[d.nOP-1] -= pl
|
||||
}
|
||||
}
|
||||
|
||||
// We check if the final partition length can also fit into a 24-bit uint.
|
||||
// Strictly speaking, this isn't part of the spec, but it guards against a
|
||||
// malicious WEBP image that is too large to ReadFull the encoded DCT
|
||||
// coefficients into memory, whether that's because the actual WEBP file is
|
||||
// too large, or whether its RIFF metadata lists too large a chunk.
|
||||
if 1<<24 <= partLens[d.nOP-1] {
|
||||
return errors.New("vp8: too much data to decode")
|
||||
}
|
||||
|
||||
buf := make([]byte, d.r.n)
|
||||
if err := d.r.ReadFull(buf); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, pl := range partLens {
|
||||
if i == d.nOP {
|
||||
break
|
||||
}
|
||||
d.op[i].init(buf[:pl])
|
||||
buf = buf[pl:]
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseOtherHeaders parses header information other than the frame header.
|
||||
func (d *Decoder) parseOtherHeaders() error {
|
||||
// Initialize and parse the first partition.
|
||||
firstPartition := make([]byte, d.frameHeader.FirstPartitionLen)
|
||||
if err := d.r.ReadFull(firstPartition); err != nil {
|
||||
return err
|
||||
}
|
||||
d.fp.init(firstPartition)
|
||||
if d.frameHeader.KeyFrame {
|
||||
// Read and ignore the color space and pixel clamp values. They are
|
||||
// specified in section 9.2, but are unimplemented.
|
||||
d.fp.readBit(uniformProb)
|
||||
d.fp.readBit(uniformProb)
|
||||
}
|
||||
d.parseSegmentHeader()
|
||||
d.parseFilterHeader()
|
||||
if err := d.parseOtherPartitions(); err != nil {
|
||||
return err
|
||||
}
|
||||
d.parseQuant()
|
||||
if !d.frameHeader.KeyFrame {
|
||||
// Golden and AltRef frames are specified in section 9.7.
|
||||
// TODO(nigeltao): implement. Note that they are only used for video, not still images.
|
||||
return errors.New("vp8: Golden / AltRef frames are not implemented")
|
||||
}
|
||||
// Read and ignore the refreshLastFrameBuffer bit, specified in section 9.8.
|
||||
// It applies only to video, and not still images.
|
||||
d.fp.readBit(uniformProb)
|
||||
d.parseTokenProb()
|
||||
d.useSkipProb = d.fp.readBit(uniformProb)
|
||||
if d.useSkipProb {
|
||||
d.skipProb = uint8(d.fp.readUint(uniformProb, 8))
|
||||
}
|
||||
if d.fp.unexpectedEOF {
|
||||
return io.ErrUnexpectedEOF
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// DecodeFrame decodes the frame and returns it as an YCbCr image.
|
||||
// The image's contents are valid up until the next call to Decoder.Init.
|
||||
func (d *Decoder) DecodeFrame() (*image.YCbCr, error) {
|
||||
d.ensureImg()
|
||||
if err := d.parseOtherHeaders(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Reconstruct the rows.
|
||||
for mbx := 0; mbx < d.mbw; mbx++ {
|
||||
d.upMB[mbx] = mb{}
|
||||
}
|
||||
for mby := 0; mby < d.mbh; mby++ {
|
||||
d.leftMB = mb{}
|
||||
for mbx := 0; mbx < d.mbw; mbx++ {
|
||||
skip := d.reconstruct(mbx, mby)
|
||||
fs := d.filterParams[d.segment][btou(!d.usePredY16)]
|
||||
fs.inner = fs.inner || !skip
|
||||
d.perMBFilterParams[d.mbw*mby+mbx] = fs
|
||||
}
|
||||
}
|
||||
if d.fp.unexpectedEOF {
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
for i := 0; i < d.nOP; i++ {
|
||||
if d.op[i].unexpectedEOF {
|
||||
return nil, io.ErrUnexpectedEOF
|
||||
}
|
||||
}
|
||||
// Apply the loop filter.
|
||||
//
|
||||
// Even if we are using per-segment levels, section 15 says that "loop
|
||||
// filtering must be skipped entirely if loop_filter_level at either the
|
||||
// frame header level or macroblock override level is 0".
|
||||
if d.filterHeader.level != 0 {
|
||||
if d.filterHeader.simple {
|
||||
d.simpleFilter()
|
||||
} else {
|
||||
d.normalFilter()
|
||||
}
|
||||
}
|
||||
return d.img, nil
|
||||
}
|
||||
273
vendor/golang.org/x/image/vp8/filter.go
сгенерированный
поставляемый
Обычный файл
273
vendor/golang.org/x/image/vp8/filter.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,273 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// filter2 modifies a 2-pixel wide or 2-pixel high band along an edge.
|
||||
func filter2(pix []byte, level, index, iStep, jStep int) {
|
||||
for n := 16; n > 0; n, index = n-1, index+iStep {
|
||||
p1 := int(pix[index-2*jStep])
|
||||
p0 := int(pix[index-1*jStep])
|
||||
q0 := int(pix[index+0*jStep])
|
||||
q1 := int(pix[index+1*jStep])
|
||||
if abs(p0-q0)<<1+abs(p1-q1)>>1 > level {
|
||||
continue
|
||||
}
|
||||
a := 3*(q0-p0) + clamp127(p1-q1)
|
||||
a1 := clamp15((a + 4) >> 3)
|
||||
a2 := clamp15((a + 3) >> 3)
|
||||
pix[index-1*jStep] = clamp255(p0 + a2)
|
||||
pix[index+0*jStep] = clamp255(q0 - a1)
|
||||
}
|
||||
}
|
||||
|
||||
// filter246 modifies a 2-, 4- or 6-pixel wide or high band along an edge.
|
||||
func filter246(pix []byte, n, level, ilevel, hlevel, index, iStep, jStep int, fourNotSix bool) {
|
||||
for ; n > 0; n, index = n-1, index+iStep {
|
||||
p3 := int(pix[index-4*jStep])
|
||||
p2 := int(pix[index-3*jStep])
|
||||
p1 := int(pix[index-2*jStep])
|
||||
p0 := int(pix[index-1*jStep])
|
||||
q0 := int(pix[index+0*jStep])
|
||||
q1 := int(pix[index+1*jStep])
|
||||
q2 := int(pix[index+2*jStep])
|
||||
q3 := int(pix[index+3*jStep])
|
||||
if abs(p0-q0)<<1+abs(p1-q1)>>1 > level {
|
||||
continue
|
||||
}
|
||||
if abs(p3-p2) > ilevel ||
|
||||
abs(p2-p1) > ilevel ||
|
||||
abs(p1-p0) > ilevel ||
|
||||
abs(q1-q0) > ilevel ||
|
||||
abs(q2-q1) > ilevel ||
|
||||
abs(q3-q2) > ilevel {
|
||||
continue
|
||||
}
|
||||
if abs(p1-p0) > hlevel || abs(q1-q0) > hlevel {
|
||||
// Filter 2 pixels.
|
||||
a := 3*(q0-p0) + clamp127(p1-q1)
|
||||
a1 := clamp15((a + 4) >> 3)
|
||||
a2 := clamp15((a + 3) >> 3)
|
||||
pix[index-1*jStep] = clamp255(p0 + a2)
|
||||
pix[index+0*jStep] = clamp255(q0 - a1)
|
||||
} else if fourNotSix {
|
||||
// Filter 4 pixels.
|
||||
a := 3 * (q0 - p0)
|
||||
a1 := clamp15((a + 4) >> 3)
|
||||
a2 := clamp15((a + 3) >> 3)
|
||||
a3 := (a1 + 1) >> 1
|
||||
pix[index-2*jStep] = clamp255(p1 + a3)
|
||||
pix[index-1*jStep] = clamp255(p0 + a2)
|
||||
pix[index+0*jStep] = clamp255(q0 - a1)
|
||||
pix[index+1*jStep] = clamp255(q1 - a3)
|
||||
} else {
|
||||
// Filter 6 pixels.
|
||||
a := clamp127(3*(q0-p0) + clamp127(p1-q1))
|
||||
a1 := (27*a + 63) >> 7
|
||||
a2 := (18*a + 63) >> 7
|
||||
a3 := (9*a + 63) >> 7
|
||||
pix[index-3*jStep] = clamp255(p2 + a3)
|
||||
pix[index-2*jStep] = clamp255(p1 + a2)
|
||||
pix[index-1*jStep] = clamp255(p0 + a1)
|
||||
pix[index+0*jStep] = clamp255(q0 - a1)
|
||||
pix[index+1*jStep] = clamp255(q1 - a2)
|
||||
pix[index+2*jStep] = clamp255(q2 - a3)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// simpleFilter implements the simple filter, as specified in section 15.2.
|
||||
func (d *Decoder) simpleFilter() {
|
||||
for mby := 0; mby < d.mbh; mby++ {
|
||||
for mbx := 0; mbx < d.mbw; mbx++ {
|
||||
f := d.perMBFilterParams[d.mbw*mby+mbx]
|
||||
if f.level == 0 {
|
||||
continue
|
||||
}
|
||||
l := int(f.level)
|
||||
yIndex := (mby*d.img.YStride + mbx) * 16
|
||||
if mbx > 0 {
|
||||
filter2(d.img.Y, l+4, yIndex, d.img.YStride, 1)
|
||||
}
|
||||
if f.inner {
|
||||
filter2(d.img.Y, l, yIndex+0x4, d.img.YStride, 1)
|
||||
filter2(d.img.Y, l, yIndex+0x8, d.img.YStride, 1)
|
||||
filter2(d.img.Y, l, yIndex+0xc, d.img.YStride, 1)
|
||||
}
|
||||
if mby > 0 {
|
||||
filter2(d.img.Y, l+4, yIndex, 1, d.img.YStride)
|
||||
}
|
||||
if f.inner {
|
||||
filter2(d.img.Y, l, yIndex+d.img.YStride*0x4, 1, d.img.YStride)
|
||||
filter2(d.img.Y, l, yIndex+d.img.YStride*0x8, 1, d.img.YStride)
|
||||
filter2(d.img.Y, l, yIndex+d.img.YStride*0xc, 1, d.img.YStride)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// normalFilter implements the normal filter, as specified in section 15.3.
|
||||
func (d *Decoder) normalFilter() {
|
||||
for mby := 0; mby < d.mbh; mby++ {
|
||||
for mbx := 0; mbx < d.mbw; mbx++ {
|
||||
f := d.perMBFilterParams[d.mbw*mby+mbx]
|
||||
if f.level == 0 {
|
||||
continue
|
||||
}
|
||||
l, il, hl := int(f.level), int(f.ilevel), int(f.hlevel)
|
||||
yIndex := (mby*d.img.YStride + mbx) * 16
|
||||
cIndex := (mby*d.img.CStride + mbx) * 8
|
||||
if mbx > 0 {
|
||||
filter246(d.img.Y, 16, l+4, il, hl, yIndex, d.img.YStride, 1, false)
|
||||
filter246(d.img.Cb, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false)
|
||||
filter246(d.img.Cr, 8, l+4, il, hl, cIndex, d.img.CStride, 1, false)
|
||||
}
|
||||
if f.inner {
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+0x4, d.img.YStride, 1, true)
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+0x8, d.img.YStride, 1, true)
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+0xc, d.img.YStride, 1, true)
|
||||
filter246(d.img.Cb, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true)
|
||||
filter246(d.img.Cr, 8, l, il, hl, cIndex+0x4, d.img.CStride, 1, true)
|
||||
}
|
||||
if mby > 0 {
|
||||
filter246(d.img.Y, 16, l+4, il, hl, yIndex, 1, d.img.YStride, false)
|
||||
filter246(d.img.Cb, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false)
|
||||
filter246(d.img.Cr, 8, l+4, il, hl, cIndex, 1, d.img.CStride, false)
|
||||
}
|
||||
if f.inner {
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x4, 1, d.img.YStride, true)
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0x8, 1, d.img.YStride, true)
|
||||
filter246(d.img.Y, 16, l, il, hl, yIndex+d.img.YStride*0xc, 1, d.img.YStride, true)
|
||||
filter246(d.img.Cb, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true)
|
||||
filter246(d.img.Cr, 8, l, il, hl, cIndex+d.img.CStride*0x4, 1, d.img.CStride, true)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// filterParam holds the loop filter parameters for a macroblock.
|
||||
type filterParam struct {
|
||||
// The first three fields are thresholds used by the loop filter to smooth
|
||||
// over the edges and interior of a macroblock. level is used by both the
|
||||
// simple and normal filters. The inner level and high edge variance level
|
||||
// are only used by the normal filter.
|
||||
level, ilevel, hlevel uint8
|
||||
// inner is whether the inner loop filter cannot be optimized out as a
|
||||
// no-op for this particular macroblock.
|
||||
inner bool
|
||||
}
|
||||
|
||||
// computeFilterParams computes the loop filter parameters, as specified in
|
||||
// section 15.4.
|
||||
func (d *Decoder) computeFilterParams() {
|
||||
for i := range d.filterParams {
|
||||
baseLevel := d.filterHeader.level
|
||||
if d.segmentHeader.useSegment {
|
||||
baseLevel = d.segmentHeader.filterStrength[i]
|
||||
if d.segmentHeader.relativeDelta {
|
||||
baseLevel += d.filterHeader.level
|
||||
}
|
||||
}
|
||||
|
||||
for j := range d.filterParams[i] {
|
||||
p := &d.filterParams[i][j]
|
||||
p.inner = j != 0
|
||||
level := baseLevel
|
||||
if d.filterHeader.useLFDelta {
|
||||
// The libwebp C code has a "TODO: only CURRENT is handled for now."
|
||||
level += d.filterHeader.refLFDelta[0]
|
||||
if j != 0 {
|
||||
level += d.filterHeader.modeLFDelta[0]
|
||||
}
|
||||
}
|
||||
if level <= 0 {
|
||||
p.level = 0
|
||||
continue
|
||||
}
|
||||
if level > 63 {
|
||||
level = 63
|
||||
}
|
||||
ilevel := level
|
||||
if d.filterHeader.sharpness > 0 {
|
||||
if d.filterHeader.sharpness > 4 {
|
||||
ilevel >>= 2
|
||||
} else {
|
||||
ilevel >>= 1
|
||||
}
|
||||
if x := int8(9 - d.filterHeader.sharpness); ilevel > x {
|
||||
ilevel = x
|
||||
}
|
||||
}
|
||||
if ilevel < 1 {
|
||||
ilevel = 1
|
||||
}
|
||||
p.ilevel = uint8(ilevel)
|
||||
p.level = uint8(2*level + ilevel)
|
||||
if d.frameHeader.KeyFrame {
|
||||
if level < 15 {
|
||||
p.hlevel = 0
|
||||
} else if level < 40 {
|
||||
p.hlevel = 1
|
||||
} else {
|
||||
p.hlevel = 2
|
||||
}
|
||||
} else {
|
||||
if level < 15 {
|
||||
p.hlevel = 0
|
||||
} else if level < 20 {
|
||||
p.hlevel = 1
|
||||
} else if level < 40 {
|
||||
p.hlevel = 2
|
||||
} else {
|
||||
p.hlevel = 3
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// intSize is either 32 or 64.
|
||||
const intSize = 32 << (^uint(0) >> 63)
|
||||
|
||||
func abs(x int) int {
|
||||
// m := -1 if x < 0. m := 0 otherwise.
|
||||
m := x >> (intSize - 1)
|
||||
|
||||
// In two's complement representation, the negative number
|
||||
// of any number (except the smallest one) can be computed
|
||||
// by flipping all the bits and add 1. This is faster than
|
||||
// code with a branch.
|
||||
// See Hacker's Delight, section 2-4.
|
||||
return (x ^ m) - m
|
||||
}
|
||||
|
||||
func clamp15(x int) int {
|
||||
if x < -16 {
|
||||
return -16
|
||||
}
|
||||
if x > 15 {
|
||||
return 15
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func clamp127(x int) int {
|
||||
if x < -128 {
|
||||
return -128
|
||||
}
|
||||
if x > 127 {
|
||||
return 127
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func clamp255(x int) uint8 {
|
||||
if x < 0 {
|
||||
return 0
|
||||
}
|
||||
if x > 255 {
|
||||
return 255
|
||||
}
|
||||
return uint8(x)
|
||||
}
|
||||
98
vendor/golang.org/x/image/vp8/idct.go
сгенерированный
поставляемый
Обычный файл
98
vendor/golang.org/x/image/vp8/idct.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,98 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file implements the inverse Discrete Cosine Transform and the inverse
|
||||
// Walsh Hadamard Transform (WHT), as specified in sections 14.3 and 14.4.
|
||||
|
||||
func clip8(i int32) uint8 {
|
||||
if i < 0 {
|
||||
return 0
|
||||
}
|
||||
if i > 255 {
|
||||
return 255
|
||||
}
|
||||
return uint8(i)
|
||||
}
|
||||
|
||||
func (z *Decoder) inverseDCT4(y, x, coeffBase int) {
|
||||
const (
|
||||
c1 = 85627 // 65536 * cos(pi/8) * sqrt(2).
|
||||
c2 = 35468 // 65536 * sin(pi/8) * sqrt(2).
|
||||
)
|
||||
var m [4][4]int32
|
||||
for i := 0; i < 4; i++ {
|
||||
a := int32(z.coeff[coeffBase+0]) + int32(z.coeff[coeffBase+8])
|
||||
b := int32(z.coeff[coeffBase+0]) - int32(z.coeff[coeffBase+8])
|
||||
c := (int32(z.coeff[coeffBase+4])*c2)>>16 - (int32(z.coeff[coeffBase+12])*c1)>>16
|
||||
d := (int32(z.coeff[coeffBase+4])*c1)>>16 + (int32(z.coeff[coeffBase+12])*c2)>>16
|
||||
m[i][0] = a + d
|
||||
m[i][1] = b + c
|
||||
m[i][2] = b - c
|
||||
m[i][3] = a - d
|
||||
coeffBase++
|
||||
}
|
||||
for j := 0; j < 4; j++ {
|
||||
dc := m[0][j] + 4
|
||||
a := dc + m[2][j]
|
||||
b := dc - m[2][j]
|
||||
c := (m[1][j]*c2)>>16 - (m[3][j]*c1)>>16
|
||||
d := (m[1][j]*c1)>>16 + (m[3][j]*c2)>>16
|
||||
z.ybr[y+j][x+0] = clip8(int32(z.ybr[y+j][x+0]) + (a+d)>>3)
|
||||
z.ybr[y+j][x+1] = clip8(int32(z.ybr[y+j][x+1]) + (b+c)>>3)
|
||||
z.ybr[y+j][x+2] = clip8(int32(z.ybr[y+j][x+2]) + (b-c)>>3)
|
||||
z.ybr[y+j][x+3] = clip8(int32(z.ybr[y+j][x+3]) + (a-d)>>3)
|
||||
}
|
||||
}
|
||||
|
||||
func (z *Decoder) inverseDCT4DCOnly(y, x, coeffBase int) {
|
||||
dc := (int32(z.coeff[coeffBase+0]) + 4) >> 3
|
||||
for j := 0; j < 4; j++ {
|
||||
for i := 0; i < 4; i++ {
|
||||
z.ybr[y+j][x+i] = clip8(int32(z.ybr[y+j][x+i]) + dc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (z *Decoder) inverseDCT8(y, x, coeffBase int) {
|
||||
z.inverseDCT4(y+0, x+0, coeffBase+0*16)
|
||||
z.inverseDCT4(y+0, x+4, coeffBase+1*16)
|
||||
z.inverseDCT4(y+4, x+0, coeffBase+2*16)
|
||||
z.inverseDCT4(y+4, x+4, coeffBase+3*16)
|
||||
}
|
||||
|
||||
func (z *Decoder) inverseDCT8DCOnly(y, x, coeffBase int) {
|
||||
z.inverseDCT4DCOnly(y+0, x+0, coeffBase+0*16)
|
||||
z.inverseDCT4DCOnly(y+0, x+4, coeffBase+1*16)
|
||||
z.inverseDCT4DCOnly(y+4, x+0, coeffBase+2*16)
|
||||
z.inverseDCT4DCOnly(y+4, x+4, coeffBase+3*16)
|
||||
}
|
||||
|
||||
func (d *Decoder) inverseWHT16() {
|
||||
var m [16]int32
|
||||
for i := 0; i < 4; i++ {
|
||||
a0 := int32(d.coeff[384+0+i]) + int32(d.coeff[384+12+i])
|
||||
a1 := int32(d.coeff[384+4+i]) + int32(d.coeff[384+8+i])
|
||||
a2 := int32(d.coeff[384+4+i]) - int32(d.coeff[384+8+i])
|
||||
a3 := int32(d.coeff[384+0+i]) - int32(d.coeff[384+12+i])
|
||||
m[0+i] = a0 + a1
|
||||
m[8+i] = a0 - a1
|
||||
m[4+i] = a3 + a2
|
||||
m[12+i] = a3 - a2
|
||||
}
|
||||
out := 0
|
||||
for i := 0; i < 4; i++ {
|
||||
dc := m[0+i*4] + 3
|
||||
a0 := dc + m[3+i*4]
|
||||
a1 := m[1+i*4] + m[2+i*4]
|
||||
a2 := m[1+i*4] - m[2+i*4]
|
||||
a3 := dc - m[3+i*4]
|
||||
d.coeff[out+0] = int16((a0 + a1) >> 3)
|
||||
d.coeff[out+16] = int16((a3 + a2) >> 3)
|
||||
d.coeff[out+32] = int16((a0 - a1) >> 3)
|
||||
d.coeff[out+48] = int16((a3 - a2) >> 3)
|
||||
out += 64
|
||||
}
|
||||
}
|
||||
129
vendor/golang.org/x/image/vp8/partition.go
сгенерированный
поставляемый
Обычный файл
129
vendor/golang.org/x/image/vp8/partition.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,129 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// Each VP8 frame consists of between 2 and 9 bitstream partitions.
|
||||
// Each partition is byte-aligned and is independently arithmetic-encoded.
|
||||
//
|
||||
// This file implements decoding a partition's bitstream, as specified in
|
||||
// chapter 7. The implementation follows libwebp's approach instead of the
|
||||
// specification's reference C implementation. For example, we use a look-up
|
||||
// table instead of a for loop to recalibrate the encoded range.
|
||||
|
||||
var (
|
||||
lutShift = [127]uint8{
|
||||
7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
|
||||
3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
|
||||
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
|
||||
2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
|
||||
}
|
||||
lutRangeM1 = [127]uint8{
|
||||
127,
|
||||
127, 191,
|
||||
127, 159, 191, 223,
|
||||
127, 143, 159, 175, 191, 207, 223, 239,
|
||||
127, 135, 143, 151, 159, 167, 175, 183, 191, 199, 207, 215, 223, 231, 239, 247,
|
||||
127, 131, 135, 139, 143, 147, 151, 155, 159, 163, 167, 171, 175, 179, 183, 187,
|
||||
191, 195, 199, 203, 207, 211, 215, 219, 223, 227, 231, 235, 239, 243, 247, 251,
|
||||
127, 129, 131, 133, 135, 137, 139, 141, 143, 145, 147, 149, 151, 153, 155, 157,
|
||||
159, 161, 163, 165, 167, 169, 171, 173, 175, 177, 179, 181, 183, 185, 187, 189,
|
||||
191, 193, 195, 197, 199, 201, 203, 205, 207, 209, 211, 213, 215, 217, 219, 221,
|
||||
223, 225, 227, 229, 231, 233, 235, 237, 239, 241, 243, 245, 247, 249, 251, 253,
|
||||
}
|
||||
)
|
||||
|
||||
// uniformProb represents a 50% probability that the next bit is 0.
|
||||
const uniformProb = 128
|
||||
|
||||
// partition holds arithmetic-coded bits.
|
||||
type partition struct {
|
||||
// buf is the input bytes.
|
||||
buf []byte
|
||||
// r is how many of buf's bytes have been consumed.
|
||||
r int
|
||||
// rangeM1 is range minus 1, where range is in the arithmetic coding sense,
|
||||
// not the Go language sense.
|
||||
rangeM1 uint32
|
||||
// bits and nBits hold those bits shifted out of buf but not yet consumed.
|
||||
bits uint32
|
||||
nBits uint8
|
||||
// unexpectedEOF tells whether we tried to read past buf.
|
||||
unexpectedEOF bool
|
||||
}
|
||||
|
||||
// init initializes the partition.
|
||||
func (p *partition) init(buf []byte) {
|
||||
p.buf = buf
|
||||
p.r = 0
|
||||
p.rangeM1 = 254
|
||||
p.bits = 0
|
||||
p.nBits = 0
|
||||
p.unexpectedEOF = false
|
||||
}
|
||||
|
||||
// readBit returns the next bit.
|
||||
func (p *partition) readBit(prob uint8) bool {
|
||||
if p.nBits < 8 {
|
||||
if p.r >= len(p.buf) {
|
||||
p.unexpectedEOF = true
|
||||
return false
|
||||
}
|
||||
// Expression split for 386 compiler.
|
||||
x := uint32(p.buf[p.r])
|
||||
p.bits |= x << (8 - p.nBits)
|
||||
p.r++
|
||||
p.nBits += 8
|
||||
}
|
||||
split := (p.rangeM1*uint32(prob))>>8 + 1
|
||||
bit := p.bits >= split<<8
|
||||
if bit {
|
||||
p.rangeM1 -= split
|
||||
p.bits -= split << 8
|
||||
} else {
|
||||
p.rangeM1 = split - 1
|
||||
}
|
||||
if p.rangeM1 < 127 {
|
||||
shift := lutShift[p.rangeM1]
|
||||
p.rangeM1 = uint32(lutRangeM1[p.rangeM1])
|
||||
p.bits <<= shift
|
||||
p.nBits -= shift
|
||||
}
|
||||
return bit
|
||||
}
|
||||
|
||||
// readUint returns the next n-bit unsigned integer.
|
||||
func (p *partition) readUint(prob, n uint8) uint32 {
|
||||
var u uint32
|
||||
for n > 0 {
|
||||
n--
|
||||
if p.readBit(prob) {
|
||||
u |= 1 << n
|
||||
}
|
||||
}
|
||||
return u
|
||||
}
|
||||
|
||||
// readInt returns the next n-bit signed integer.
|
||||
func (p *partition) readInt(prob, n uint8) int32 {
|
||||
u := p.readUint(prob, n)
|
||||
b := p.readBit(prob)
|
||||
if b {
|
||||
return -int32(u)
|
||||
}
|
||||
return int32(u)
|
||||
}
|
||||
|
||||
// readOptionalInt returns the next n-bit signed integer in an encoding
|
||||
// where the likely result is zero.
|
||||
func (p *partition) readOptionalInt(prob, n uint8) int32 {
|
||||
if !p.readBit(prob) {
|
||||
return 0
|
||||
}
|
||||
return p.readInt(prob, n)
|
||||
}
|
||||
201
vendor/golang.org/x/image/vp8/pred.go
сгенерированный
поставляемый
Обычный файл
201
vendor/golang.org/x/image/vp8/pred.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,201 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file implements parsing the predictor modes, as specified in chapter
|
||||
// 11.
|
||||
|
||||
func (d *Decoder) parsePredModeY16(mbx int) {
|
||||
var p uint8
|
||||
if !d.fp.readBit(156) {
|
||||
if !d.fp.readBit(163) {
|
||||
p = predDC
|
||||
} else {
|
||||
p = predVE
|
||||
}
|
||||
} else if !d.fp.readBit(128) {
|
||||
p = predHE
|
||||
} else {
|
||||
p = predTM
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
d.upMB[mbx].pred[i] = p
|
||||
d.leftMB.pred[i] = p
|
||||
}
|
||||
d.predY16 = p
|
||||
}
|
||||
|
||||
func (d *Decoder) parsePredModeC8() {
|
||||
if !d.fp.readBit(142) {
|
||||
d.predC8 = predDC
|
||||
} else if !d.fp.readBit(114) {
|
||||
d.predC8 = predVE
|
||||
} else if !d.fp.readBit(183) {
|
||||
d.predC8 = predHE
|
||||
} else {
|
||||
d.predC8 = predTM
|
||||
}
|
||||
}
|
||||
|
||||
func (d *Decoder) parsePredModeY4(mbx int) {
|
||||
for j := 0; j < 4; j++ {
|
||||
p := d.leftMB.pred[j]
|
||||
for i := 0; i < 4; i++ {
|
||||
prob := &predProb[d.upMB[mbx].pred[i]][p]
|
||||
if !d.fp.readBit(prob[0]) {
|
||||
p = predDC
|
||||
} else if !d.fp.readBit(prob[1]) {
|
||||
p = predTM
|
||||
} else if !d.fp.readBit(prob[2]) {
|
||||
p = predVE
|
||||
} else if !d.fp.readBit(prob[3]) {
|
||||
if !d.fp.readBit(prob[4]) {
|
||||
p = predHE
|
||||
} else if !d.fp.readBit(prob[5]) {
|
||||
p = predRD
|
||||
} else {
|
||||
p = predVR
|
||||
}
|
||||
} else if !d.fp.readBit(prob[6]) {
|
||||
p = predLD
|
||||
} else if !d.fp.readBit(prob[7]) {
|
||||
p = predVL
|
||||
} else if !d.fp.readBit(prob[8]) {
|
||||
p = predHD
|
||||
} else {
|
||||
p = predHU
|
||||
}
|
||||
d.predY4[j][i] = p
|
||||
d.upMB[mbx].pred[i] = p
|
||||
}
|
||||
d.leftMB.pred[j] = p
|
||||
}
|
||||
}
|
||||
|
||||
// predProb are the probabilities to decode a 4x4 region's predictor mode given
|
||||
// the predictor modes of the regions above and left of it.
|
||||
// These values are specified in section 11.5.
|
||||
var predProb = [nPred][nPred][9]uint8{
|
||||
{
|
||||
{231, 120, 48, 89, 115, 113, 120, 152, 112},
|
||||
{152, 179, 64, 126, 170, 118, 46, 70, 95},
|
||||
{175, 69, 143, 80, 85, 82, 72, 155, 103},
|
||||
{56, 58, 10, 171, 218, 189, 17, 13, 152},
|
||||
{114, 26, 17, 163, 44, 195, 21, 10, 173},
|
||||
{121, 24, 80, 195, 26, 62, 44, 64, 85},
|
||||
{144, 71, 10, 38, 171, 213, 144, 34, 26},
|
||||
{170, 46, 55, 19, 136, 160, 33, 206, 71},
|
||||
{63, 20, 8, 114, 114, 208, 12, 9, 226},
|
||||
{81, 40, 11, 96, 182, 84, 29, 16, 36},
|
||||
},
|
||||
{
|
||||
{134, 183, 89, 137, 98, 101, 106, 165, 148},
|
||||
{72, 187, 100, 130, 157, 111, 32, 75, 80},
|
||||
{66, 102, 167, 99, 74, 62, 40, 234, 128},
|
||||
{41, 53, 9, 178, 241, 141, 26, 8, 107},
|
||||
{74, 43, 26, 146, 73, 166, 49, 23, 157},
|
||||
{65, 38, 105, 160, 51, 52, 31, 115, 128},
|
||||
{104, 79, 12, 27, 217, 255, 87, 17, 7},
|
||||
{87, 68, 71, 44, 114, 51, 15, 186, 23},
|
||||
{47, 41, 14, 110, 182, 183, 21, 17, 194},
|
||||
{66, 45, 25, 102, 197, 189, 23, 18, 22},
|
||||
},
|
||||
{
|
||||
{88, 88, 147, 150, 42, 46, 45, 196, 205},
|
||||
{43, 97, 183, 117, 85, 38, 35, 179, 61},
|
||||
{39, 53, 200, 87, 26, 21, 43, 232, 171},
|
||||
{56, 34, 51, 104, 114, 102, 29, 93, 77},
|
||||
{39, 28, 85, 171, 58, 165, 90, 98, 64},
|
||||
{34, 22, 116, 206, 23, 34, 43, 166, 73},
|
||||
{107, 54, 32, 26, 51, 1, 81, 43, 31},
|
||||
{68, 25, 106, 22, 64, 171, 36, 225, 114},
|
||||
{34, 19, 21, 102, 132, 188, 16, 76, 124},
|
||||
{62, 18, 78, 95, 85, 57, 50, 48, 51},
|
||||
},
|
||||
{
|
||||
{193, 101, 35, 159, 215, 111, 89, 46, 111},
|
||||
{60, 148, 31, 172, 219, 228, 21, 18, 111},
|
||||
{112, 113, 77, 85, 179, 255, 38, 120, 114},
|
||||
{40, 42, 1, 196, 245, 209, 10, 25, 109},
|
||||
{88, 43, 29, 140, 166, 213, 37, 43, 154},
|
||||
{61, 63, 30, 155, 67, 45, 68, 1, 209},
|
||||
{100, 80, 8, 43, 154, 1, 51, 26, 71},
|
||||
{142, 78, 78, 16, 255, 128, 34, 197, 171},
|
||||
{41, 40, 5, 102, 211, 183, 4, 1, 221},
|
||||
{51, 50, 17, 168, 209, 192, 23, 25, 82},
|
||||
},
|
||||
{
|
||||
{138, 31, 36, 171, 27, 166, 38, 44, 229},
|
||||
{67, 87, 58, 169, 82, 115, 26, 59, 179},
|
||||
{63, 59, 90, 180, 59, 166, 93, 73, 154},
|
||||
{40, 40, 21, 116, 143, 209, 34, 39, 175},
|
||||
{47, 15, 16, 183, 34, 223, 49, 45, 183},
|
||||
{46, 17, 33, 183, 6, 98, 15, 32, 183},
|
||||
{57, 46, 22, 24, 128, 1, 54, 17, 37},
|
||||
{65, 32, 73, 115, 28, 128, 23, 128, 205},
|
||||
{40, 3, 9, 115, 51, 192, 18, 6, 223},
|
||||
{87, 37, 9, 115, 59, 77, 64, 21, 47},
|
||||
},
|
||||
{
|
||||
{104, 55, 44, 218, 9, 54, 53, 130, 226},
|
||||
{64, 90, 70, 205, 40, 41, 23, 26, 57},
|
||||
{54, 57, 112, 184, 5, 41, 38, 166, 213},
|
||||
{30, 34, 26, 133, 152, 116, 10, 32, 134},
|
||||
{39, 19, 53, 221, 26, 114, 32, 73, 255},
|
||||
{31, 9, 65, 234, 2, 15, 1, 118, 73},
|
||||
{75, 32, 12, 51, 192, 255, 160, 43, 51},
|
||||
{88, 31, 35, 67, 102, 85, 55, 186, 85},
|
||||
{56, 21, 23, 111, 59, 205, 45, 37, 192},
|
||||
{55, 38, 70, 124, 73, 102, 1, 34, 98},
|
||||
},
|
||||
{
|
||||
{125, 98, 42, 88, 104, 85, 117, 175, 82},
|
||||
{95, 84, 53, 89, 128, 100, 113, 101, 45},
|
||||
{75, 79, 123, 47, 51, 128, 81, 171, 1},
|
||||
{57, 17, 5, 71, 102, 57, 53, 41, 49},
|
||||
{38, 33, 13, 121, 57, 73, 26, 1, 85},
|
||||
{41, 10, 67, 138, 77, 110, 90, 47, 114},
|
||||
{115, 21, 2, 10, 102, 255, 166, 23, 6},
|
||||
{101, 29, 16, 10, 85, 128, 101, 196, 26},
|
||||
{57, 18, 10, 102, 102, 213, 34, 20, 43},
|
||||
{117, 20, 15, 36, 163, 128, 68, 1, 26},
|
||||
},
|
||||
{
|
||||
{102, 61, 71, 37, 34, 53, 31, 243, 192},
|
||||
{69, 60, 71, 38, 73, 119, 28, 222, 37},
|
||||
{68, 45, 128, 34, 1, 47, 11, 245, 171},
|
||||
{62, 17, 19, 70, 146, 85, 55, 62, 70},
|
||||
{37, 43, 37, 154, 100, 163, 85, 160, 1},
|
||||
{63, 9, 92, 136, 28, 64, 32, 201, 85},
|
||||
{75, 15, 9, 9, 64, 255, 184, 119, 16},
|
||||
{86, 6, 28, 5, 64, 255, 25, 248, 1},
|
||||
{56, 8, 17, 132, 137, 255, 55, 116, 128},
|
||||
{58, 15, 20, 82, 135, 57, 26, 121, 40},
|
||||
},
|
||||
{
|
||||
{164, 50, 31, 137, 154, 133, 25, 35, 218},
|
||||
{51, 103, 44, 131, 131, 123, 31, 6, 158},
|
||||
{86, 40, 64, 135, 148, 224, 45, 183, 128},
|
||||
{22, 26, 17, 131, 240, 154, 14, 1, 209},
|
||||
{45, 16, 21, 91, 64, 222, 7, 1, 197},
|
||||
{56, 21, 39, 155, 60, 138, 23, 102, 213},
|
||||
{83, 12, 13, 54, 192, 255, 68, 47, 28},
|
||||
{85, 26, 85, 85, 128, 128, 32, 146, 171},
|
||||
{18, 11, 7, 63, 144, 171, 4, 4, 246},
|
||||
{35, 27, 10, 146, 174, 171, 12, 26, 128},
|
||||
},
|
||||
{
|
||||
{190, 80, 35, 99, 180, 80, 126, 54, 45},
|
||||
{85, 126, 47, 87, 176, 51, 41, 20, 32},
|
||||
{101, 75, 128, 139, 118, 146, 116, 128, 85},
|
||||
{56, 41, 15, 176, 236, 85, 37, 9, 62},
|
||||
{71, 30, 17, 119, 118, 255, 17, 18, 138},
|
||||
{101, 38, 60, 138, 55, 70, 43, 26, 142},
|
||||
{146, 36, 19, 30, 171, 255, 97, 27, 20},
|
||||
{138, 45, 61, 62, 219, 1, 81, 188, 64},
|
||||
{32, 41, 20, 117, 151, 142, 20, 21, 163},
|
||||
{112, 19, 12, 61, 195, 128, 48, 4, 24},
|
||||
},
|
||||
}
|
||||
553
vendor/golang.org/x/image/vp8/predfunc.go
сгенерированный
поставляемый
Обычный файл
553
vendor/golang.org/x/image/vp8/predfunc.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,553 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file implements the predicition functions, as specified in chapter 12.
|
||||
//
|
||||
// For each macroblock (of 1x16x16 luma and 2x8x8 chroma coefficients), the
|
||||
// luma values are either predicted as one large 16x16 region or 16 separate
|
||||
// 4x4 regions. The chroma values are always predicted as one 8x8 region.
|
||||
//
|
||||
// For 4x4 regions, the target block's predicted values (Xs) are a function of
|
||||
// its previously-decoded top and left border values, as well as a number of
|
||||
// pixels from the top-right:
|
||||
//
|
||||
// a b c d e f g h
|
||||
// p X X X X
|
||||
// q X X X X
|
||||
// r X X X X
|
||||
// s X X X X
|
||||
//
|
||||
// The predictor modes are:
|
||||
// - DC: all Xs = (b + c + d + e + p + q + r + s + 4) / 8.
|
||||
// - TM: the first X = (b + p - a), the second X = (c + p - a), and so on.
|
||||
// - VE: each X = the weighted average of its column's top value and that
|
||||
// value's neighbors, i.e. averages of abc, bcd, cde or def.
|
||||
// - HE: similar to VE except rows instead of columns, and the final row is
|
||||
// an average of r, s and s.
|
||||
// - RD, VR, LD, VL, HD, HU: these diagonal modes ("Right Down", "Vertical
|
||||
// Right", etc) are more complicated and are described in section 12.3.
|
||||
// All Xs are clipped to the range [0, 255].
|
||||
//
|
||||
// For 8x8 and 16x16 regions, the target block's predicted values are a
|
||||
// function of the top and left border values without the top-right overhang,
|
||||
// i.e. without the 8x8 or 16x16 equivalent of f, g and h. Furthermore:
|
||||
// - There are no diagonal predictor modes, only DC, TM, VE and HE.
|
||||
// - The DC mode has variants for macroblocks in the top row and/or left
|
||||
// column, i.e. for macroblocks with mby == 0 || mbx == 0.
|
||||
// - The VE and HE modes take only the column top or row left values; they do
|
||||
// not smooth that top/left value with its neighbors.
|
||||
|
||||
// nPred is the number of predictor modes, not including the Top/Left versions
|
||||
// of the DC predictor mode.
|
||||
const nPred = 10
|
||||
|
||||
const (
|
||||
predDC = iota
|
||||
predTM
|
||||
predVE
|
||||
predHE
|
||||
predRD
|
||||
predVR
|
||||
predLD
|
||||
predVL
|
||||
predHD
|
||||
predHU
|
||||
predDCTop
|
||||
predDCLeft
|
||||
predDCTopLeft
|
||||
)
|
||||
|
||||
func checkTopLeftPred(mbx, mby int, p uint8) uint8 {
|
||||
if p != predDC {
|
||||
return p
|
||||
}
|
||||
if mbx == 0 {
|
||||
if mby == 0 {
|
||||
return predDCTopLeft
|
||||
}
|
||||
return predDCLeft
|
||||
}
|
||||
if mby == 0 {
|
||||
return predDCTop
|
||||
}
|
||||
return predDC
|
||||
}
|
||||
|
||||
var predFunc4 = [...]func(*Decoder, int, int){
|
||||
predFunc4DC,
|
||||
predFunc4TM,
|
||||
predFunc4VE,
|
||||
predFunc4HE,
|
||||
predFunc4RD,
|
||||
predFunc4VR,
|
||||
predFunc4LD,
|
||||
predFunc4VL,
|
||||
predFunc4HD,
|
||||
predFunc4HU,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
}
|
||||
|
||||
var predFunc8 = [...]func(*Decoder, int, int){
|
||||
predFunc8DC,
|
||||
predFunc8TM,
|
||||
predFunc8VE,
|
||||
predFunc8HE,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
predFunc8DCTop,
|
||||
predFunc8DCLeft,
|
||||
predFunc8DCTopLeft,
|
||||
}
|
||||
|
||||
var predFunc16 = [...]func(*Decoder, int, int){
|
||||
predFunc16DC,
|
||||
predFunc16TM,
|
||||
predFunc16VE,
|
||||
predFunc16HE,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
nil,
|
||||
predFunc16DCTop,
|
||||
predFunc16DCLeft,
|
||||
predFunc16DCTopLeft,
|
||||
}
|
||||
|
||||
func predFunc4DC(z *Decoder, y, x int) {
|
||||
sum := uint32(4)
|
||||
for i := 0; i < 4; i++ {
|
||||
sum += uint32(z.ybr[y-1][x+i])
|
||||
}
|
||||
for j := 0; j < 4; j++ {
|
||||
sum += uint32(z.ybr[y+j][x-1])
|
||||
}
|
||||
avg := uint8(sum / 8)
|
||||
for j := 0; j < 4; j++ {
|
||||
for i := 0; i < 4; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc4TM(z *Decoder, y, x int) {
|
||||
delta0 := -int32(z.ybr[y-1][x-1])
|
||||
for j := 0; j < 4; j++ {
|
||||
delta1 := delta0 + int32(z.ybr[y+j][x-1])
|
||||
for i := 0; i < 4; i++ {
|
||||
delta2 := delta1 + int32(z.ybr[y-1][x+i])
|
||||
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc4VE(z *Decoder, y, x int) {
|
||||
a := int32(z.ybr[y-1][x-1])
|
||||
b := int32(z.ybr[y-1][x+0])
|
||||
c := int32(z.ybr[y-1][x+1])
|
||||
d := int32(z.ybr[y-1][x+2])
|
||||
e := int32(z.ybr[y-1][x+3])
|
||||
f := int32(z.ybr[y-1][x+4])
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
cde := uint8((c + 2*d + e + 2) / 4)
|
||||
def := uint8((d + 2*e + f + 2) / 4)
|
||||
for j := 0; j < 4; j++ {
|
||||
z.ybr[y+j][x+0] = abc
|
||||
z.ybr[y+j][x+1] = bcd
|
||||
z.ybr[y+j][x+2] = cde
|
||||
z.ybr[y+j][x+3] = def
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc4HE(z *Decoder, y, x int) {
|
||||
s := int32(z.ybr[y+3][x-1])
|
||||
r := int32(z.ybr[y+2][x-1])
|
||||
q := int32(z.ybr[y+1][x-1])
|
||||
p := int32(z.ybr[y+0][x-1])
|
||||
a := int32(z.ybr[y-1][x-1])
|
||||
ssr := uint8((s + 2*s + r + 2) / 4)
|
||||
srq := uint8((s + 2*r + q + 2) / 4)
|
||||
rqp := uint8((r + 2*q + p + 2) / 4)
|
||||
apq := uint8((a + 2*p + q + 2) / 4)
|
||||
for i := 0; i < 4; i++ {
|
||||
z.ybr[y+0][x+i] = apq
|
||||
z.ybr[y+1][x+i] = rqp
|
||||
z.ybr[y+2][x+i] = srq
|
||||
z.ybr[y+3][x+i] = ssr
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc4RD(z *Decoder, y, x int) {
|
||||
s := int32(z.ybr[y+3][x-1])
|
||||
r := int32(z.ybr[y+2][x-1])
|
||||
q := int32(z.ybr[y+1][x-1])
|
||||
p := int32(z.ybr[y+0][x-1])
|
||||
a := int32(z.ybr[y-1][x-1])
|
||||
b := int32(z.ybr[y-1][x+0])
|
||||
c := int32(z.ybr[y-1][x+1])
|
||||
d := int32(z.ybr[y-1][x+2])
|
||||
e := int32(z.ybr[y-1][x+3])
|
||||
srq := uint8((s + 2*r + q + 2) / 4)
|
||||
rqp := uint8((r + 2*q + p + 2) / 4)
|
||||
qpa := uint8((q + 2*p + a + 2) / 4)
|
||||
pab := uint8((p + 2*a + b + 2) / 4)
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
cde := uint8((c + 2*d + e + 2) / 4)
|
||||
z.ybr[y+0][x+0] = pab
|
||||
z.ybr[y+0][x+1] = abc
|
||||
z.ybr[y+0][x+2] = bcd
|
||||
z.ybr[y+0][x+3] = cde
|
||||
z.ybr[y+1][x+0] = qpa
|
||||
z.ybr[y+1][x+1] = pab
|
||||
z.ybr[y+1][x+2] = abc
|
||||
z.ybr[y+1][x+3] = bcd
|
||||
z.ybr[y+2][x+0] = rqp
|
||||
z.ybr[y+2][x+1] = qpa
|
||||
z.ybr[y+2][x+2] = pab
|
||||
z.ybr[y+2][x+3] = abc
|
||||
z.ybr[y+3][x+0] = srq
|
||||
z.ybr[y+3][x+1] = rqp
|
||||
z.ybr[y+3][x+2] = qpa
|
||||
z.ybr[y+3][x+3] = pab
|
||||
}
|
||||
|
||||
func predFunc4VR(z *Decoder, y, x int) {
|
||||
r := int32(z.ybr[y+2][x-1])
|
||||
q := int32(z.ybr[y+1][x-1])
|
||||
p := int32(z.ybr[y+0][x-1])
|
||||
a := int32(z.ybr[y-1][x-1])
|
||||
b := int32(z.ybr[y-1][x+0])
|
||||
c := int32(z.ybr[y-1][x+1])
|
||||
d := int32(z.ybr[y-1][x+2])
|
||||
e := int32(z.ybr[y-1][x+3])
|
||||
ab := uint8((a + b + 1) / 2)
|
||||
bc := uint8((b + c + 1) / 2)
|
||||
cd := uint8((c + d + 1) / 2)
|
||||
de := uint8((d + e + 1) / 2)
|
||||
rqp := uint8((r + 2*q + p + 2) / 4)
|
||||
qpa := uint8((q + 2*p + a + 2) / 4)
|
||||
pab := uint8((p + 2*a + b + 2) / 4)
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
cde := uint8((c + 2*d + e + 2) / 4)
|
||||
z.ybr[y+0][x+0] = ab
|
||||
z.ybr[y+0][x+1] = bc
|
||||
z.ybr[y+0][x+2] = cd
|
||||
z.ybr[y+0][x+3] = de
|
||||
z.ybr[y+1][x+0] = pab
|
||||
z.ybr[y+1][x+1] = abc
|
||||
z.ybr[y+1][x+2] = bcd
|
||||
z.ybr[y+1][x+3] = cde
|
||||
z.ybr[y+2][x+0] = qpa
|
||||
z.ybr[y+2][x+1] = ab
|
||||
z.ybr[y+2][x+2] = bc
|
||||
z.ybr[y+2][x+3] = cd
|
||||
z.ybr[y+3][x+0] = rqp
|
||||
z.ybr[y+3][x+1] = pab
|
||||
z.ybr[y+3][x+2] = abc
|
||||
z.ybr[y+3][x+3] = bcd
|
||||
}
|
||||
|
||||
func predFunc4LD(z *Decoder, y, x int) {
|
||||
a := int32(z.ybr[y-1][x+0])
|
||||
b := int32(z.ybr[y-1][x+1])
|
||||
c := int32(z.ybr[y-1][x+2])
|
||||
d := int32(z.ybr[y-1][x+3])
|
||||
e := int32(z.ybr[y-1][x+4])
|
||||
f := int32(z.ybr[y-1][x+5])
|
||||
g := int32(z.ybr[y-1][x+6])
|
||||
h := int32(z.ybr[y-1][x+7])
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
cde := uint8((c + 2*d + e + 2) / 4)
|
||||
def := uint8((d + 2*e + f + 2) / 4)
|
||||
efg := uint8((e + 2*f + g + 2) / 4)
|
||||
fgh := uint8((f + 2*g + h + 2) / 4)
|
||||
ghh := uint8((g + 2*h + h + 2) / 4)
|
||||
z.ybr[y+0][x+0] = abc
|
||||
z.ybr[y+0][x+1] = bcd
|
||||
z.ybr[y+0][x+2] = cde
|
||||
z.ybr[y+0][x+3] = def
|
||||
z.ybr[y+1][x+0] = bcd
|
||||
z.ybr[y+1][x+1] = cde
|
||||
z.ybr[y+1][x+2] = def
|
||||
z.ybr[y+1][x+3] = efg
|
||||
z.ybr[y+2][x+0] = cde
|
||||
z.ybr[y+2][x+1] = def
|
||||
z.ybr[y+2][x+2] = efg
|
||||
z.ybr[y+2][x+3] = fgh
|
||||
z.ybr[y+3][x+0] = def
|
||||
z.ybr[y+3][x+1] = efg
|
||||
z.ybr[y+3][x+2] = fgh
|
||||
z.ybr[y+3][x+3] = ghh
|
||||
}
|
||||
|
||||
func predFunc4VL(z *Decoder, y, x int) {
|
||||
a := int32(z.ybr[y-1][x+0])
|
||||
b := int32(z.ybr[y-1][x+1])
|
||||
c := int32(z.ybr[y-1][x+2])
|
||||
d := int32(z.ybr[y-1][x+3])
|
||||
e := int32(z.ybr[y-1][x+4])
|
||||
f := int32(z.ybr[y-1][x+5])
|
||||
g := int32(z.ybr[y-1][x+6])
|
||||
h := int32(z.ybr[y-1][x+7])
|
||||
ab := uint8((a + b + 1) / 2)
|
||||
bc := uint8((b + c + 1) / 2)
|
||||
cd := uint8((c + d + 1) / 2)
|
||||
de := uint8((d + e + 1) / 2)
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
cde := uint8((c + 2*d + e + 2) / 4)
|
||||
def := uint8((d + 2*e + f + 2) / 4)
|
||||
efg := uint8((e + 2*f + g + 2) / 4)
|
||||
fgh := uint8((f + 2*g + h + 2) / 4)
|
||||
z.ybr[y+0][x+0] = ab
|
||||
z.ybr[y+0][x+1] = bc
|
||||
z.ybr[y+0][x+2] = cd
|
||||
z.ybr[y+0][x+3] = de
|
||||
z.ybr[y+1][x+0] = abc
|
||||
z.ybr[y+1][x+1] = bcd
|
||||
z.ybr[y+1][x+2] = cde
|
||||
z.ybr[y+1][x+3] = def
|
||||
z.ybr[y+2][x+0] = bc
|
||||
z.ybr[y+2][x+1] = cd
|
||||
z.ybr[y+2][x+2] = de
|
||||
z.ybr[y+2][x+3] = efg
|
||||
z.ybr[y+3][x+0] = bcd
|
||||
z.ybr[y+3][x+1] = cde
|
||||
z.ybr[y+3][x+2] = def
|
||||
z.ybr[y+3][x+3] = fgh
|
||||
}
|
||||
|
||||
func predFunc4HD(z *Decoder, y, x int) {
|
||||
s := int32(z.ybr[y+3][x-1])
|
||||
r := int32(z.ybr[y+2][x-1])
|
||||
q := int32(z.ybr[y+1][x-1])
|
||||
p := int32(z.ybr[y+0][x-1])
|
||||
a := int32(z.ybr[y-1][x-1])
|
||||
b := int32(z.ybr[y-1][x+0])
|
||||
c := int32(z.ybr[y-1][x+1])
|
||||
d := int32(z.ybr[y-1][x+2])
|
||||
sr := uint8((s + r + 1) / 2)
|
||||
rq := uint8((r + q + 1) / 2)
|
||||
qp := uint8((q + p + 1) / 2)
|
||||
pa := uint8((p + a + 1) / 2)
|
||||
srq := uint8((s + 2*r + q + 2) / 4)
|
||||
rqp := uint8((r + 2*q + p + 2) / 4)
|
||||
qpa := uint8((q + 2*p + a + 2) / 4)
|
||||
pab := uint8((p + 2*a + b + 2) / 4)
|
||||
abc := uint8((a + 2*b + c + 2) / 4)
|
||||
bcd := uint8((b + 2*c + d + 2) / 4)
|
||||
z.ybr[y+0][x+0] = pa
|
||||
z.ybr[y+0][x+1] = pab
|
||||
z.ybr[y+0][x+2] = abc
|
||||
z.ybr[y+0][x+3] = bcd
|
||||
z.ybr[y+1][x+0] = qp
|
||||
z.ybr[y+1][x+1] = qpa
|
||||
z.ybr[y+1][x+2] = pa
|
||||
z.ybr[y+1][x+3] = pab
|
||||
z.ybr[y+2][x+0] = rq
|
||||
z.ybr[y+2][x+1] = rqp
|
||||
z.ybr[y+2][x+2] = qp
|
||||
z.ybr[y+2][x+3] = qpa
|
||||
z.ybr[y+3][x+0] = sr
|
||||
z.ybr[y+3][x+1] = srq
|
||||
z.ybr[y+3][x+2] = rq
|
||||
z.ybr[y+3][x+3] = rqp
|
||||
}
|
||||
|
||||
func predFunc4HU(z *Decoder, y, x int) {
|
||||
s := int32(z.ybr[y+3][x-1])
|
||||
r := int32(z.ybr[y+2][x-1])
|
||||
q := int32(z.ybr[y+1][x-1])
|
||||
p := int32(z.ybr[y+0][x-1])
|
||||
pq := uint8((p + q + 1) / 2)
|
||||
qr := uint8((q + r + 1) / 2)
|
||||
rs := uint8((r + s + 1) / 2)
|
||||
pqr := uint8((p + 2*q + r + 2) / 4)
|
||||
qrs := uint8((q + 2*r + s + 2) / 4)
|
||||
rss := uint8((r + 2*s + s + 2) / 4)
|
||||
sss := uint8(s)
|
||||
z.ybr[y+0][x+0] = pq
|
||||
z.ybr[y+0][x+1] = pqr
|
||||
z.ybr[y+0][x+2] = qr
|
||||
z.ybr[y+0][x+3] = qrs
|
||||
z.ybr[y+1][x+0] = qr
|
||||
z.ybr[y+1][x+1] = qrs
|
||||
z.ybr[y+1][x+2] = rs
|
||||
z.ybr[y+1][x+3] = rss
|
||||
z.ybr[y+2][x+0] = rs
|
||||
z.ybr[y+2][x+1] = rss
|
||||
z.ybr[y+2][x+2] = sss
|
||||
z.ybr[y+2][x+3] = sss
|
||||
z.ybr[y+3][x+0] = sss
|
||||
z.ybr[y+3][x+1] = sss
|
||||
z.ybr[y+3][x+2] = sss
|
||||
z.ybr[y+3][x+3] = sss
|
||||
}
|
||||
|
||||
func predFunc8DC(z *Decoder, y, x int) {
|
||||
sum := uint32(8)
|
||||
for i := 0; i < 8; i++ {
|
||||
sum += uint32(z.ybr[y-1][x+i])
|
||||
}
|
||||
for j := 0; j < 8; j++ {
|
||||
sum += uint32(z.ybr[y+j][x-1])
|
||||
}
|
||||
avg := uint8(sum / 16)
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8TM(z *Decoder, y, x int) {
|
||||
delta0 := -int32(z.ybr[y-1][x-1])
|
||||
for j := 0; j < 8; j++ {
|
||||
delta1 := delta0 + int32(z.ybr[y+j][x-1])
|
||||
for i := 0; i < 8; i++ {
|
||||
delta2 := delta1 + int32(z.ybr[y-1][x+i])
|
||||
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8VE(z *Decoder, y, x int) {
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = z.ybr[y-1][x+i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8HE(z *Decoder, y, x int) {
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = z.ybr[y+j][x-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8DCTop(z *Decoder, y, x int) {
|
||||
sum := uint32(4)
|
||||
for j := 0; j < 8; j++ {
|
||||
sum += uint32(z.ybr[y+j][x-1])
|
||||
}
|
||||
avg := uint8(sum / 8)
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8DCLeft(z *Decoder, y, x int) {
|
||||
sum := uint32(4)
|
||||
for i := 0; i < 8; i++ {
|
||||
sum += uint32(z.ybr[y-1][x+i])
|
||||
}
|
||||
avg := uint8(sum / 8)
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc8DCTopLeft(z *Decoder, y, x int) {
|
||||
for j := 0; j < 8; j++ {
|
||||
for i := 0; i < 8; i++ {
|
||||
z.ybr[y+j][x+i] = 0x80
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16DC(z *Decoder, y, x int) {
|
||||
sum := uint32(16)
|
||||
for i := 0; i < 16; i++ {
|
||||
sum += uint32(z.ybr[y-1][x+i])
|
||||
}
|
||||
for j := 0; j < 16; j++ {
|
||||
sum += uint32(z.ybr[y+j][x-1])
|
||||
}
|
||||
avg := uint8(sum / 32)
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16TM(z *Decoder, y, x int) {
|
||||
delta0 := -int32(z.ybr[y-1][x-1])
|
||||
for j := 0; j < 16; j++ {
|
||||
delta1 := delta0 + int32(z.ybr[y+j][x-1])
|
||||
for i := 0; i < 16; i++ {
|
||||
delta2 := delta1 + int32(z.ybr[y-1][x+i])
|
||||
z.ybr[y+j][x+i] = uint8(clip(delta2, 0, 255))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16VE(z *Decoder, y, x int) {
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = z.ybr[y-1][x+i]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16HE(z *Decoder, y, x int) {
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = z.ybr[y+j][x-1]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16DCTop(z *Decoder, y, x int) {
|
||||
sum := uint32(8)
|
||||
for j := 0; j < 16; j++ {
|
||||
sum += uint32(z.ybr[y+j][x-1])
|
||||
}
|
||||
avg := uint8(sum / 16)
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16DCLeft(z *Decoder, y, x int) {
|
||||
sum := uint32(8)
|
||||
for i := 0; i < 16; i++ {
|
||||
sum += uint32(z.ybr[y-1][x+i])
|
||||
}
|
||||
avg := uint8(sum / 16)
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = avg
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func predFunc16DCTopLeft(z *Decoder, y, x int) {
|
||||
for j := 0; j < 16; j++ {
|
||||
for i := 0; i < 16; i++ {
|
||||
z.ybr[y+j][x+i] = 0x80
|
||||
}
|
||||
}
|
||||
}
|
||||
98
vendor/golang.org/x/image/vp8/quant.go
сгенерированный
поставляемый
Обычный файл
98
vendor/golang.org/x/image/vp8/quant.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,98 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file implements parsing the quantization factors.
|
||||
|
||||
// quant are DC/AC quantization factors.
|
||||
type quant struct {
|
||||
y1 [2]uint16
|
||||
y2 [2]uint16
|
||||
uv [2]uint16
|
||||
}
|
||||
|
||||
// clip clips x to the range [min, max] inclusive.
|
||||
func clip(x, min, max int32) int32 {
|
||||
if x < min {
|
||||
return min
|
||||
}
|
||||
if x > max {
|
||||
return max
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
// parseQuant parses the quantization factors, as specified in section 9.6.
|
||||
func (d *Decoder) parseQuant() {
|
||||
baseQ0 := d.fp.readUint(uniformProb, 7)
|
||||
dqy1DC := d.fp.readOptionalInt(uniformProb, 4)
|
||||
const dqy1AC = 0
|
||||
dqy2DC := d.fp.readOptionalInt(uniformProb, 4)
|
||||
dqy2AC := d.fp.readOptionalInt(uniformProb, 4)
|
||||
dquvDC := d.fp.readOptionalInt(uniformProb, 4)
|
||||
dquvAC := d.fp.readOptionalInt(uniformProb, 4)
|
||||
for i := 0; i < nSegment; i++ {
|
||||
q := int32(baseQ0)
|
||||
if d.segmentHeader.useSegment {
|
||||
if d.segmentHeader.relativeDelta {
|
||||
q += int32(d.segmentHeader.quantizer[i])
|
||||
} else {
|
||||
q = int32(d.segmentHeader.quantizer[i])
|
||||
}
|
||||
}
|
||||
d.quant[i].y1[0] = dequantTableDC[clip(q+dqy1DC, 0, 127)]
|
||||
d.quant[i].y1[1] = dequantTableAC[clip(q+dqy1AC, 0, 127)]
|
||||
d.quant[i].y2[0] = dequantTableDC[clip(q+dqy2DC, 0, 127)] * 2
|
||||
d.quant[i].y2[1] = dequantTableAC[clip(q+dqy2AC, 0, 127)] * 155 / 100
|
||||
if d.quant[i].y2[1] < 8 {
|
||||
d.quant[i].y2[1] = 8
|
||||
}
|
||||
// The 117 is not a typo. The dequant_init function in the spec's Reference
|
||||
// Decoder Source Code (http://tools.ietf.org/html/rfc6386#section-9.6 Page 145)
|
||||
// says to clamp the LHS value at 132, which is equal to dequantTableDC[117].
|
||||
d.quant[i].uv[0] = dequantTableDC[clip(q+dquvDC, 0, 117)]
|
||||
d.quant[i].uv[1] = dequantTableAC[clip(q+dquvAC, 0, 127)]
|
||||
}
|
||||
}
|
||||
|
||||
// The dequantization tables are specified in section 14.1.
|
||||
var (
|
||||
dequantTableDC = [128]uint16{
|
||||
4, 5, 6, 7, 8, 9, 10, 10,
|
||||
11, 12, 13, 14, 15, 16, 17, 17,
|
||||
18, 19, 20, 20, 21, 21, 22, 22,
|
||||
23, 23, 24, 25, 25, 26, 27, 28,
|
||||
29, 30, 31, 32, 33, 34, 35, 36,
|
||||
37, 37, 38, 39, 40, 41, 42, 43,
|
||||
44, 45, 46, 46, 47, 48, 49, 50,
|
||||
51, 52, 53, 54, 55, 56, 57, 58,
|
||||
59, 60, 61, 62, 63, 64, 65, 66,
|
||||
67, 68, 69, 70, 71, 72, 73, 74,
|
||||
75, 76, 76, 77, 78, 79, 80, 81,
|
||||
82, 83, 84, 85, 86, 87, 88, 89,
|
||||
91, 93, 95, 96, 98, 100, 101, 102,
|
||||
104, 106, 108, 110, 112, 114, 116, 118,
|
||||
122, 124, 126, 128, 130, 132, 134, 136,
|
||||
138, 140, 143, 145, 148, 151, 154, 157,
|
||||
}
|
||||
dequantTableAC = [128]uint16{
|
||||
4, 5, 6, 7, 8, 9, 10, 11,
|
||||
12, 13, 14, 15, 16, 17, 18, 19,
|
||||
20, 21, 22, 23, 24, 25, 26, 27,
|
||||
28, 29, 30, 31, 32, 33, 34, 35,
|
||||
36, 37, 38, 39, 40, 41, 42, 43,
|
||||
44, 45, 46, 47, 48, 49, 50, 51,
|
||||
52, 53, 54, 55, 56, 57, 58, 60,
|
||||
62, 64, 66, 68, 70, 72, 74, 76,
|
||||
78, 80, 82, 84, 86, 88, 90, 92,
|
||||
94, 96, 98, 100, 102, 104, 106, 108,
|
||||
110, 112, 114, 116, 119, 122, 125, 128,
|
||||
131, 134, 137, 140, 143, 146, 149, 152,
|
||||
155, 158, 161, 164, 167, 170, 173, 177,
|
||||
181, 185, 189, 193, 197, 201, 205, 209,
|
||||
213, 217, 221, 225, 229, 234, 239, 245,
|
||||
249, 254, 259, 264, 269, 274, 279, 284,
|
||||
}
|
||||
)
|
||||
442
vendor/golang.org/x/image/vp8/reconstruct.go
сгенерированный
поставляемый
Обычный файл
442
vendor/golang.org/x/image/vp8/reconstruct.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,442 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file implements decoding DCT/WHT residual coefficients and
|
||||
// reconstructing YCbCr data equal to predicted values plus residuals.
|
||||
//
|
||||
// There are 1*16*16 + 2*8*8 + 1*4*4 coefficients per macroblock:
|
||||
// - 1*16*16 luma DCT coefficients,
|
||||
// - 2*8*8 chroma DCT coefficients, and
|
||||
// - 1*4*4 luma WHT coefficients.
|
||||
// Coefficients are read in lots of 16, and the later coefficients in each lot
|
||||
// are often zero.
|
||||
//
|
||||
// The YCbCr data consists of 1*16*16 luma values and 2*8*8 chroma values,
|
||||
// plus previously decoded values along the top and left borders. The combined
|
||||
// values are laid out as a [1+16+1+8][32]uint8 so that vertically adjacent
|
||||
// samples are 32 bytes apart. In detail, the layout is:
|
||||
//
|
||||
// 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
|
||||
// . . . . . . . a b b b b b b b b b b b b b b b b c c c c . . . . 0
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 1
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 2
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 3
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 4
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 5
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 6
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 7
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 8
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 9
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 10
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 11
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y c c c c . . . . 12
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 13
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 14
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 15
|
||||
// . . . . . . . d Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y Y . . . . . . . . 16
|
||||
// . . . . . . . e f f f f f f f f . . . . . . . g h h h h h h h h 17
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 18
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 19
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 20
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 21
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 22
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 23
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 24
|
||||
// . . . . . . . i B B B B B B B B . . . . . . . j R R R R R R R R 25
|
||||
//
|
||||
// Y, B and R are the reconstructed luma (Y) and chroma (B, R) values.
|
||||
// The Y values are predicted (either as one 16x16 region or 16 4x4 regions)
|
||||
// based on the row above's Y values (some combination of {abc} or {dYC}) and
|
||||
// the column left's Y values (either {ad} or {bY}). Similarly, B and R values
|
||||
// are predicted on the row above and column left of their respective 8x8
|
||||
// region: {efi} for B, {ghj} for R.
|
||||
//
|
||||
// For uppermost macroblocks (i.e. those with mby == 0), the {abcefgh} values
|
||||
// are initialized to 0x81. Otherwise, they are copied from the bottom row of
|
||||
// the macroblock above. The {c} values are then duplicated from row 0 to rows
|
||||
// 4, 8 and 12 of the ybr workspace.
|
||||
// Similarly, for leftmost macroblocks (i.e. those with mbx == 0), the {adeigj}
|
||||
// values are initialized to 0x7f. Otherwise, they are copied from the right
|
||||
// column of the macroblock to the left.
|
||||
// For the top-left macroblock (with mby == 0 && mbx == 0), {aeg} is 0x81.
|
||||
//
|
||||
// When moving from one macroblock to the next horizontally, the {adeigj}
|
||||
// values can simply be copied from the workspace to itself, shifted by 8 or
|
||||
// 16 columns. When moving from one macroblock to the next vertically,
|
||||
// filtering can occur and hence the row values have to be copied from the
|
||||
// post-filtered image instead of the pre-filtered workspace.
|
||||
|
||||
const (
|
||||
bCoeffBase = 1*16*16 + 0*8*8
|
||||
rCoeffBase = 1*16*16 + 1*8*8
|
||||
whtCoeffBase = 1*16*16 + 2*8*8
|
||||
)
|
||||
|
||||
const (
|
||||
ybrYX = 8
|
||||
ybrYY = 1
|
||||
ybrBX = 8
|
||||
ybrBY = 18
|
||||
ybrRX = 24
|
||||
ybrRY = 18
|
||||
)
|
||||
|
||||
// prepareYBR prepares the {abcdefghij} elements of ybr.
|
||||
func (d *Decoder) prepareYBR(mbx, mby int) {
|
||||
if mbx == 0 {
|
||||
for y := 0; y < 17; y++ {
|
||||
d.ybr[y][7] = 0x81
|
||||
}
|
||||
for y := 17; y < 26; y++ {
|
||||
d.ybr[y][7] = 0x81
|
||||
d.ybr[y][23] = 0x81
|
||||
}
|
||||
} else {
|
||||
for y := 0; y < 17; y++ {
|
||||
d.ybr[y][7] = d.ybr[y][7+16]
|
||||
}
|
||||
for y := 17; y < 26; y++ {
|
||||
d.ybr[y][7] = d.ybr[y][15]
|
||||
d.ybr[y][23] = d.ybr[y][31]
|
||||
}
|
||||
}
|
||||
if mby == 0 {
|
||||
for x := 7; x < 28; x++ {
|
||||
d.ybr[0][x] = 0x7f
|
||||
}
|
||||
for x := 7; x < 16; x++ {
|
||||
d.ybr[17][x] = 0x7f
|
||||
}
|
||||
for x := 23; x < 32; x++ {
|
||||
d.ybr[17][x] = 0x7f
|
||||
}
|
||||
} else {
|
||||
for i := 0; i < 16; i++ {
|
||||
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i]
|
||||
}
|
||||
for i := 0; i < 8; i++ {
|
||||
d.ybr[17][8+i] = d.img.Cb[(8*mby-1)*d.img.CStride+8*mbx+i]
|
||||
}
|
||||
for i := 0; i < 8; i++ {
|
||||
d.ybr[17][24+i] = d.img.Cr[(8*mby-1)*d.img.CStride+8*mbx+i]
|
||||
}
|
||||
if mbx == d.mbw-1 {
|
||||
for i := 16; i < 20; i++ {
|
||||
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+15]
|
||||
}
|
||||
} else {
|
||||
for i := 16; i < 20; i++ {
|
||||
d.ybr[0][8+i] = d.img.Y[(16*mby-1)*d.img.YStride+16*mbx+i]
|
||||
}
|
||||
}
|
||||
}
|
||||
for y := 4; y < 16; y += 4 {
|
||||
d.ybr[y][24] = d.ybr[0][24]
|
||||
d.ybr[y][25] = d.ybr[0][25]
|
||||
d.ybr[y][26] = d.ybr[0][26]
|
||||
d.ybr[y][27] = d.ybr[0][27]
|
||||
}
|
||||
}
|
||||
|
||||
// btou converts a bool to a 0/1 value.
|
||||
func btou(b bool) uint8 {
|
||||
if b {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// pack packs four 0/1 values into four bits of a uint32.
|
||||
func pack(x [4]uint8, shift int) uint32 {
|
||||
u := uint32(x[0])<<0 | uint32(x[1])<<1 | uint32(x[2])<<2 | uint32(x[3])<<3
|
||||
return u << uint(shift)
|
||||
}
|
||||
|
||||
// unpack unpacks four 0/1 values from a four-bit value.
|
||||
var unpack = [16][4]uint8{
|
||||
{0, 0, 0, 0},
|
||||
{1, 0, 0, 0},
|
||||
{0, 1, 0, 0},
|
||||
{1, 1, 0, 0},
|
||||
{0, 0, 1, 0},
|
||||
{1, 0, 1, 0},
|
||||
{0, 1, 1, 0},
|
||||
{1, 1, 1, 0},
|
||||
{0, 0, 0, 1},
|
||||
{1, 0, 0, 1},
|
||||
{0, 1, 0, 1},
|
||||
{1, 1, 0, 1},
|
||||
{0, 0, 1, 1},
|
||||
{1, 0, 1, 1},
|
||||
{0, 1, 1, 1},
|
||||
{1, 1, 1, 1},
|
||||
}
|
||||
|
||||
var (
|
||||
// The mapping from 4x4 region position to band is specified in section 13.3.
|
||||
bands = [17]uint8{0, 1, 2, 3, 6, 4, 5, 6, 6, 6, 6, 6, 6, 6, 6, 7, 0}
|
||||
// Category probabilties are specified in section 13.2.
|
||||
// Decoding categories 1 and 2 are done inline.
|
||||
cat3456 = [4][12]uint8{
|
||||
{173, 148, 140, 0, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||
{176, 155, 140, 135, 0, 0, 0, 0, 0, 0, 0, 0},
|
||||
{180, 157, 141, 134, 130, 0, 0, 0, 0, 0, 0, 0},
|
||||
{254, 254, 243, 230, 196, 177, 153, 140, 133, 130, 129, 0},
|
||||
}
|
||||
// The zigzag order is:
|
||||
// 0 1 5 6
|
||||
// 2 4 7 12
|
||||
// 3 8 11 13
|
||||
// 9 10 14 15
|
||||
zigzag = [16]uint8{0, 1, 4, 8, 5, 2, 3, 6, 9, 12, 13, 10, 7, 11, 14, 15}
|
||||
)
|
||||
|
||||
// parseResiduals4 parses a 4x4 region of residual coefficients, as specified
|
||||
// in section 13.3, and returns a 0/1 value indicating whether there was at
|
||||
// least one non-zero coefficient.
|
||||
// r is the partition to read bits from.
|
||||
// plane and context describe which token probability table to use. context is
|
||||
// either 0, 1 or 2, and equals how many of the macroblock left and macroblock
|
||||
// above have non-zero coefficients.
|
||||
// quant are the DC/AC quantization factors.
|
||||
// skipFirstCoeff is whether the DC coefficient has already been parsed.
|
||||
// coeffBase is the base index of d.coeff to write to.
|
||||
func (d *Decoder) parseResiduals4(r *partition, plane int, context uint8, quant [2]uint16, skipFirstCoeff bool, coeffBase int) uint8 {
|
||||
prob, n := &d.tokenProb[plane], 0
|
||||
if skipFirstCoeff {
|
||||
n = 1
|
||||
}
|
||||
p := prob[bands[n]][context]
|
||||
if !r.readBit(p[0]) {
|
||||
return 0
|
||||
}
|
||||
for n != 16 {
|
||||
n++
|
||||
if !r.readBit(p[1]) {
|
||||
p = prob[bands[n]][0]
|
||||
continue
|
||||
}
|
||||
var v uint32
|
||||
if !r.readBit(p[2]) {
|
||||
v = 1
|
||||
p = prob[bands[n]][1]
|
||||
} else {
|
||||
if !r.readBit(p[3]) {
|
||||
if !r.readBit(p[4]) {
|
||||
v = 2
|
||||
} else {
|
||||
v = 3 + r.readUint(p[5], 1)
|
||||
}
|
||||
} else if !r.readBit(p[6]) {
|
||||
if !r.readBit(p[7]) {
|
||||
// Category 1.
|
||||
v = 5 + r.readUint(159, 1)
|
||||
} else {
|
||||
// Category 2.
|
||||
v = 7 + 2*r.readUint(165, 1) + r.readUint(145, 1)
|
||||
}
|
||||
} else {
|
||||
// Categories 3, 4, 5 or 6.
|
||||
b1 := r.readUint(p[8], 1)
|
||||
b0 := r.readUint(p[9+b1], 1)
|
||||
cat := 2*b1 + b0
|
||||
tab := &cat3456[cat]
|
||||
v = 0
|
||||
for i := 0; tab[i] != 0; i++ {
|
||||
v *= 2
|
||||
v += r.readUint(tab[i], 1)
|
||||
}
|
||||
v += 3 + (8 << cat)
|
||||
}
|
||||
p = prob[bands[n]][2]
|
||||
}
|
||||
z := zigzag[n-1]
|
||||
c := int32(v) * int32(quant[btou(z > 0)])
|
||||
if r.readBit(uniformProb) {
|
||||
c = -c
|
||||
}
|
||||
d.coeff[coeffBase+int(z)] = int16(c)
|
||||
if n == 16 || !r.readBit(p[0]) {
|
||||
return 1
|
||||
}
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// parseResiduals parses the residuals and returns whether inner loop filtering
|
||||
// should be skipped for this macroblock.
|
||||
func (d *Decoder) parseResiduals(mbx, mby int) (skip bool) {
|
||||
partition := &d.op[mby&(d.nOP-1)]
|
||||
plane := planeY1SansY2
|
||||
quant := &d.quant[d.segment]
|
||||
|
||||
// Parse the DC coefficient of each 4x4 luma region.
|
||||
if d.usePredY16 {
|
||||
nz := d.parseResiduals4(partition, planeY2, d.leftMB.nzY16+d.upMB[mbx].nzY16, quant.y2, false, whtCoeffBase)
|
||||
d.leftMB.nzY16 = nz
|
||||
d.upMB[mbx].nzY16 = nz
|
||||
d.inverseWHT16()
|
||||
plane = planeY1WithY2
|
||||
}
|
||||
|
||||
var (
|
||||
nzDC, nzAC [4]uint8
|
||||
nzDCMask, nzACMask uint32
|
||||
coeffBase int
|
||||
)
|
||||
|
||||
// Parse the luma coefficients.
|
||||
lnz := unpack[d.leftMB.nzMask&0x0f]
|
||||
unz := unpack[d.upMB[mbx].nzMask&0x0f]
|
||||
for y := 0; y < 4; y++ {
|
||||
nz := lnz[y]
|
||||
for x := 0; x < 4; x++ {
|
||||
nz = d.parseResiduals4(partition, plane, nz+unz[x], quant.y1, d.usePredY16, coeffBase)
|
||||
unz[x] = nz
|
||||
nzAC[x] = nz
|
||||
nzDC[x] = btou(d.coeff[coeffBase] != 0)
|
||||
coeffBase += 16
|
||||
}
|
||||
lnz[y] = nz
|
||||
nzDCMask |= pack(nzDC, y*4)
|
||||
nzACMask |= pack(nzAC, y*4)
|
||||
}
|
||||
lnzMask := pack(lnz, 0)
|
||||
unzMask := pack(unz, 0)
|
||||
|
||||
// Parse the chroma coefficients.
|
||||
lnz = unpack[d.leftMB.nzMask>>4]
|
||||
unz = unpack[d.upMB[mbx].nzMask>>4]
|
||||
for c := 0; c < 4; c += 2 {
|
||||
for y := 0; y < 2; y++ {
|
||||
nz := lnz[y+c]
|
||||
for x := 0; x < 2; x++ {
|
||||
nz = d.parseResiduals4(partition, planeUV, nz+unz[x+c], quant.uv, false, coeffBase)
|
||||
unz[x+c] = nz
|
||||
nzAC[y*2+x] = nz
|
||||
nzDC[y*2+x] = btou(d.coeff[coeffBase] != 0)
|
||||
coeffBase += 16
|
||||
}
|
||||
lnz[y+c] = nz
|
||||
}
|
||||
nzDCMask |= pack(nzDC, 16+c*2)
|
||||
nzACMask |= pack(nzAC, 16+c*2)
|
||||
}
|
||||
lnzMask |= pack(lnz, 4)
|
||||
unzMask |= pack(unz, 4)
|
||||
|
||||
// Save decoder state.
|
||||
d.leftMB.nzMask = uint8(lnzMask)
|
||||
d.upMB[mbx].nzMask = uint8(unzMask)
|
||||
d.nzDCMask = nzDCMask
|
||||
d.nzACMask = nzACMask
|
||||
|
||||
// Section 15.1 of the spec says that "Steps 2 and 4 [of the loop filter]
|
||||
// are skipped... [if] there is no DCT coefficient coded for the whole
|
||||
// macroblock."
|
||||
return nzDCMask == 0 && nzACMask == 0
|
||||
}
|
||||
|
||||
// reconstructMacroblock applies the predictor functions and adds the inverse-
|
||||
// DCT transformed residuals to recover the YCbCr data.
|
||||
func (d *Decoder) reconstructMacroblock(mbx, mby int) {
|
||||
if d.usePredY16 {
|
||||
p := checkTopLeftPred(mbx, mby, d.predY16)
|
||||
predFunc16[p](d, 1, 8)
|
||||
for j := 0; j < 4; j++ {
|
||||
for i := 0; i < 4; i++ {
|
||||
n := 4*j + i
|
||||
y := 4*j + 1
|
||||
x := 4*i + 8
|
||||
mask := uint32(1) << uint(n)
|
||||
if d.nzACMask&mask != 0 {
|
||||
d.inverseDCT4(y, x, 16*n)
|
||||
} else if d.nzDCMask&mask != 0 {
|
||||
d.inverseDCT4DCOnly(y, x, 16*n)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
for j := 0; j < 4; j++ {
|
||||
for i := 0; i < 4; i++ {
|
||||
n := 4*j + i
|
||||
y := 4*j + 1
|
||||
x := 4*i + 8
|
||||
predFunc4[d.predY4[j][i]](d, y, x)
|
||||
mask := uint32(1) << uint(n)
|
||||
if d.nzACMask&mask != 0 {
|
||||
d.inverseDCT4(y, x, 16*n)
|
||||
} else if d.nzDCMask&mask != 0 {
|
||||
d.inverseDCT4DCOnly(y, x, 16*n)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
p := checkTopLeftPred(mbx, mby, d.predC8)
|
||||
predFunc8[p](d, ybrBY, ybrBX)
|
||||
if d.nzACMask&0x0f0000 != 0 {
|
||||
d.inverseDCT8(ybrBY, ybrBX, bCoeffBase)
|
||||
} else if d.nzDCMask&0x0f0000 != 0 {
|
||||
d.inverseDCT8DCOnly(ybrBY, ybrBX, bCoeffBase)
|
||||
}
|
||||
predFunc8[p](d, ybrRY, ybrRX)
|
||||
if d.nzACMask&0xf00000 != 0 {
|
||||
d.inverseDCT8(ybrRY, ybrRX, rCoeffBase)
|
||||
} else if d.nzDCMask&0xf00000 != 0 {
|
||||
d.inverseDCT8DCOnly(ybrRY, ybrRX, rCoeffBase)
|
||||
}
|
||||
}
|
||||
|
||||
// reconstruct reconstructs one macroblock and returns whether inner loop
|
||||
// filtering should be skipped for it.
|
||||
func (d *Decoder) reconstruct(mbx, mby int) (skip bool) {
|
||||
if d.segmentHeader.updateMap {
|
||||
if !d.fp.readBit(d.segmentHeader.prob[0]) {
|
||||
d.segment = int(d.fp.readUint(d.segmentHeader.prob[1], 1))
|
||||
} else {
|
||||
d.segment = int(d.fp.readUint(d.segmentHeader.prob[2], 1)) + 2
|
||||
}
|
||||
}
|
||||
if d.useSkipProb {
|
||||
skip = d.fp.readBit(d.skipProb)
|
||||
}
|
||||
// Prepare the workspace.
|
||||
for i := range d.coeff {
|
||||
d.coeff[i] = 0
|
||||
}
|
||||
d.prepareYBR(mbx, mby)
|
||||
// Parse the predictor modes.
|
||||
d.usePredY16 = d.fp.readBit(145)
|
||||
if d.usePredY16 {
|
||||
d.parsePredModeY16(mbx)
|
||||
} else {
|
||||
d.parsePredModeY4(mbx)
|
||||
}
|
||||
d.parsePredModeC8()
|
||||
// Parse the residuals.
|
||||
if !skip {
|
||||
skip = d.parseResiduals(mbx, mby)
|
||||
} else {
|
||||
if d.usePredY16 {
|
||||
d.leftMB.nzY16 = 0
|
||||
d.upMB[mbx].nzY16 = 0
|
||||
}
|
||||
d.leftMB.nzMask = 0
|
||||
d.upMB[mbx].nzMask = 0
|
||||
d.nzDCMask = 0
|
||||
d.nzACMask = 0
|
||||
}
|
||||
// Reconstruct the YCbCr data and copy it to the image.
|
||||
d.reconstructMacroblock(mbx, mby)
|
||||
for i, y := (mby*d.img.YStride+mbx)*16, 0; y < 16; i, y = i+d.img.YStride, y+1 {
|
||||
copy(d.img.Y[i:i+16], d.ybr[ybrYY+y][ybrYX:ybrYX+16])
|
||||
}
|
||||
for i, y := (mby*d.img.CStride+mbx)*8, 0; y < 8; i, y = i+d.img.CStride, y+1 {
|
||||
copy(d.img.Cb[i:i+8], d.ybr[ybrBY+y][ybrBX:ybrBX+8])
|
||||
copy(d.img.Cr[i:i+8], d.ybr[ybrRY+y][ybrRX:ybrRX+8])
|
||||
}
|
||||
return skip
|
||||
}
|
||||
381
vendor/golang.org/x/image/vp8/token.go
сгенерированный
поставляемый
Обычный файл
381
vendor/golang.org/x/image/vp8/token.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,381 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8
|
||||
|
||||
// This file contains token probabilities for decoding DCT/WHT coefficients, as
|
||||
// specified in chapter 13.
|
||||
|
||||
func (d *Decoder) parseTokenProb() {
|
||||
for i := range d.tokenProb {
|
||||
for j := range d.tokenProb[i] {
|
||||
for k := range d.tokenProb[i][j] {
|
||||
for l := range d.tokenProb[i][j][k] {
|
||||
if d.fp.readBit(tokenProbUpdateProb[i][j][k][l]) {
|
||||
d.tokenProb[i][j][k][l] = uint8(d.fp.readUint(uniformProb, 8))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The plane enumeration is specified in section 13.3.
|
||||
const (
|
||||
planeY1WithY2 = iota
|
||||
planeY2
|
||||
planeUV
|
||||
planeY1SansY2
|
||||
nPlane
|
||||
)
|
||||
|
||||
const (
|
||||
nBand = 8
|
||||
nContext = 3
|
||||
nProb = 11
|
||||
)
|
||||
|
||||
// Token probability update probabilities are specified in section 13.4.
|
||||
var tokenProbUpdateProb = [nPlane][nBand][nContext][nProb]uint8{
|
||||
{
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{176, 246, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{223, 241, 252, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{249, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 244, 252, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{234, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 246, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{239, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{251, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{251, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 253, 255, 254, 255, 255, 255, 255, 255, 255},
|
||||
{250, 255, 254, 255, 254, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{217, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{225, 252, 241, 253, 255, 255, 254, 255, 255, 255, 255},
|
||||
{234, 250, 241, 250, 253, 255, 253, 254, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{223, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{238, 253, 254, 254, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 248, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{249, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 253, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{247, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{252, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{253, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{186, 251, 250, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{234, 251, 244, 254, 255, 255, 255, 255, 255, 255, 255},
|
||||
{251, 251, 243, 253, 254, 255, 254, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{236, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{251, 253, 253, 254, 254, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 254, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{248, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{250, 254, 252, 254, 255, 255, 255, 255, 255, 255, 255},
|
||||
{248, 254, 249, 253, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{246, 253, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{252, 254, 251, 254, 254, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 254, 252, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{248, 254, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{253, 255, 254, 254, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{245, 251, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{253, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 251, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{252, 253, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 254, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 252, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{249, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 254, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 253, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{250, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
{
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{254, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
{255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Default token probabilities are specified in section 13.5.
|
||||
var defaultTokenProb = [nPlane][nBand][nContext][nProb]uint8{
|
||||
{
|
||||
{
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{253, 136, 254, 255, 228, 219, 128, 128, 128, 128, 128},
|
||||
{189, 129, 242, 255, 227, 213, 255, 219, 128, 128, 128},
|
||||
{106, 126, 227, 252, 214, 209, 255, 255, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 98, 248, 255, 236, 226, 255, 255, 128, 128, 128},
|
||||
{181, 133, 238, 254, 221, 234, 255, 154, 128, 128, 128},
|
||||
{78, 134, 202, 247, 198, 180, 255, 219, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 185, 249, 255, 243, 255, 128, 128, 128, 128, 128},
|
||||
{184, 150, 247, 255, 236, 224, 128, 128, 128, 128, 128},
|
||||
{77, 110, 216, 255, 236, 230, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 101, 251, 255, 241, 255, 128, 128, 128, 128, 128},
|
||||
{170, 139, 241, 252, 236, 209, 255, 255, 128, 128, 128},
|
||||
{37, 116, 196, 243, 228, 255, 255, 255, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 204, 254, 255, 245, 255, 128, 128, 128, 128, 128},
|
||||
{207, 160, 250, 255, 238, 128, 128, 128, 128, 128, 128},
|
||||
{102, 103, 231, 255, 211, 171, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 152, 252, 255, 240, 255, 128, 128, 128, 128, 128},
|
||||
{177, 135, 243, 255, 234, 225, 128, 128, 128, 128, 128},
|
||||
{80, 129, 211, 255, 194, 224, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{246, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{255, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{198, 35, 237, 223, 193, 187, 162, 160, 145, 155, 62},
|
||||
{131, 45, 198, 221, 172, 176, 220, 157, 252, 221, 1},
|
||||
{68, 47, 146, 208, 149, 167, 221, 162, 255, 223, 128},
|
||||
},
|
||||
{
|
||||
{1, 149, 241, 255, 221, 224, 255, 255, 128, 128, 128},
|
||||
{184, 141, 234, 253, 222, 220, 255, 199, 128, 128, 128},
|
||||
{81, 99, 181, 242, 176, 190, 249, 202, 255, 255, 128},
|
||||
},
|
||||
{
|
||||
{1, 129, 232, 253, 214, 197, 242, 196, 255, 255, 128},
|
||||
{99, 121, 210, 250, 201, 198, 255, 202, 128, 128, 128},
|
||||
{23, 91, 163, 242, 170, 187, 247, 210, 255, 255, 128},
|
||||
},
|
||||
{
|
||||
{1, 200, 246, 255, 234, 255, 128, 128, 128, 128, 128},
|
||||
{109, 178, 241, 255, 231, 245, 255, 255, 128, 128, 128},
|
||||
{44, 130, 201, 253, 205, 192, 255, 255, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 132, 239, 251, 219, 209, 255, 165, 128, 128, 128},
|
||||
{94, 136, 225, 251, 218, 190, 255, 255, 128, 128, 128},
|
||||
{22, 100, 174, 245, 186, 161, 255, 199, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 182, 249, 255, 232, 235, 128, 128, 128, 128, 128},
|
||||
{124, 143, 241, 255, 227, 234, 128, 128, 128, 128, 128},
|
||||
{35, 77, 181, 251, 193, 211, 255, 205, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 157, 247, 255, 236, 231, 255, 255, 128, 128, 128},
|
||||
{121, 141, 235, 255, 225, 227, 255, 255, 128, 128, 128},
|
||||
{45, 99, 188, 251, 195, 217, 255, 224, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 1, 251, 255, 213, 255, 128, 128, 128, 128, 128},
|
||||
{203, 1, 248, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
{137, 1, 177, 255, 224, 255, 128, 128, 128, 128, 128},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{253, 9, 248, 251, 207, 208, 255, 192, 128, 128, 128},
|
||||
{175, 13, 224, 243, 193, 185, 249, 198, 255, 255, 128},
|
||||
{73, 17, 171, 221, 161, 179, 236, 167, 255, 234, 128},
|
||||
},
|
||||
{
|
||||
{1, 95, 247, 253, 212, 183, 255, 255, 128, 128, 128},
|
||||
{239, 90, 244, 250, 211, 209, 255, 255, 128, 128, 128},
|
||||
{155, 77, 195, 248, 188, 195, 255, 255, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 24, 239, 251, 218, 219, 255, 205, 128, 128, 128},
|
||||
{201, 51, 219, 255, 196, 186, 128, 128, 128, 128, 128},
|
||||
{69, 46, 190, 239, 201, 218, 255, 228, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 191, 251, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
{223, 165, 249, 255, 213, 255, 128, 128, 128, 128, 128},
|
||||
{141, 124, 248, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 16, 248, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
{190, 36, 230, 255, 236, 255, 128, 128, 128, 128, 128},
|
||||
{149, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 226, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{247, 192, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{240, 128, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 134, 252, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
{213, 62, 250, 255, 255, 128, 128, 128, 128, 128, 128},
|
||||
{55, 93, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{128, 128, 128, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
},
|
||||
{
|
||||
{
|
||||
{202, 24, 213, 235, 186, 191, 220, 160, 240, 175, 255},
|
||||
{126, 38, 182, 232, 169, 184, 228, 174, 255, 187, 128},
|
||||
{61, 46, 138, 219, 151, 178, 240, 170, 255, 216, 128},
|
||||
},
|
||||
{
|
||||
{1, 112, 230, 250, 199, 191, 247, 159, 255, 255, 128},
|
||||
{166, 109, 228, 252, 211, 215, 255, 174, 128, 128, 128},
|
||||
{39, 77, 162, 232, 172, 180, 245, 178, 255, 255, 128},
|
||||
},
|
||||
{
|
||||
{1, 52, 220, 246, 198, 199, 249, 220, 255, 255, 128},
|
||||
{124, 74, 191, 243, 183, 193, 250, 221, 255, 255, 128},
|
||||
{24, 71, 130, 219, 154, 170, 243, 182, 255, 255, 128},
|
||||
},
|
||||
{
|
||||
{1, 182, 225, 249, 219, 240, 255, 224, 128, 128, 128},
|
||||
{149, 150, 226, 252, 216, 205, 255, 171, 128, 128, 128},
|
||||
{28, 108, 170, 242, 183, 194, 254, 223, 255, 255, 128},
|
||||
},
|
||||
{
|
||||
{1, 81, 230, 252, 204, 203, 255, 192, 128, 128, 128},
|
||||
{123, 102, 209, 247, 188, 196, 255, 233, 128, 128, 128},
|
||||
{20, 95, 153, 243, 164, 173, 255, 203, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 222, 248, 255, 216, 213, 128, 128, 128, 128, 128},
|
||||
{168, 175, 246, 252, 235, 205, 255, 255, 128, 128, 128},
|
||||
{47, 116, 215, 255, 211, 212, 255, 255, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 121, 236, 253, 212, 214, 255, 255, 128, 128, 128},
|
||||
{141, 84, 213, 252, 201, 202, 255, 219, 128, 128, 128},
|
||||
{42, 80, 160, 240, 162, 185, 255, 205, 128, 128, 128},
|
||||
},
|
||||
{
|
||||
{1, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{244, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
{238, 1, 255, 128, 128, 128, 128, 128, 128, 128, 128},
|
||||
},
|
||||
},
|
||||
}
|
||||
603
vendor/golang.org/x/image/vp8l/decode.go
сгенерированный
поставляемый
Обычный файл
603
vendor/golang.org/x/image/vp8l/decode.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,603 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package vp8l implements a decoder for the VP8L lossless image format.
|
||||
//
|
||||
// The VP8L specification is at:
|
||||
// https://developers.google.com/speed/webp/docs/riff_container
|
||||
package vp8l // import "golang.org/x/image/vp8l"
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"io"
|
||||
)
|
||||
|
||||
var (
|
||||
errInvalidCodeLengths = errors.New("vp8l: invalid code lengths")
|
||||
errInvalidHuffmanTree = errors.New("vp8l: invalid Huffman tree")
|
||||
)
|
||||
|
||||
// colorCacheMultiplier is the multiplier used for the color cache hash
|
||||
// function, specified in section 4.2.3.
|
||||
const colorCacheMultiplier = 0x1e35a7bd
|
||||
|
||||
// distanceMapTable is the look-up table for distanceMap.
|
||||
var distanceMapTable = [120]uint8{
|
||||
0x18, 0x07, 0x17, 0x19, 0x28, 0x06, 0x27, 0x29, 0x16, 0x1a,
|
||||
0x26, 0x2a, 0x38, 0x05, 0x37, 0x39, 0x15, 0x1b, 0x36, 0x3a,
|
||||
0x25, 0x2b, 0x48, 0x04, 0x47, 0x49, 0x14, 0x1c, 0x35, 0x3b,
|
||||
0x46, 0x4a, 0x24, 0x2c, 0x58, 0x45, 0x4b, 0x34, 0x3c, 0x03,
|
||||
0x57, 0x59, 0x13, 0x1d, 0x56, 0x5a, 0x23, 0x2d, 0x44, 0x4c,
|
||||
0x55, 0x5b, 0x33, 0x3d, 0x68, 0x02, 0x67, 0x69, 0x12, 0x1e,
|
||||
0x66, 0x6a, 0x22, 0x2e, 0x54, 0x5c, 0x43, 0x4d, 0x65, 0x6b,
|
||||
0x32, 0x3e, 0x78, 0x01, 0x77, 0x79, 0x53, 0x5d, 0x11, 0x1f,
|
||||
0x64, 0x6c, 0x42, 0x4e, 0x76, 0x7a, 0x21, 0x2f, 0x75, 0x7b,
|
||||
0x31, 0x3f, 0x63, 0x6d, 0x52, 0x5e, 0x00, 0x74, 0x7c, 0x41,
|
||||
0x4f, 0x10, 0x20, 0x62, 0x6e, 0x30, 0x73, 0x7d, 0x51, 0x5f,
|
||||
0x40, 0x72, 0x7e, 0x61, 0x6f, 0x50, 0x71, 0x7f, 0x60, 0x70,
|
||||
}
|
||||
|
||||
// distanceMap maps a LZ77 backwards reference distance to a two-dimensional
|
||||
// pixel offset, specified in section 4.2.2.
|
||||
func distanceMap(w int32, code uint32) int32 {
|
||||
if int32(code) > int32(len(distanceMapTable)) {
|
||||
return int32(code) - int32(len(distanceMapTable))
|
||||
}
|
||||
distCode := int32(distanceMapTable[code-1])
|
||||
yOffset := distCode >> 4
|
||||
xOffset := 8 - distCode&0xf
|
||||
if d := yOffset*w + xOffset; d >= 1 {
|
||||
return d
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// decoder holds the bit-stream for a VP8L image.
|
||||
type decoder struct {
|
||||
r io.ByteReader
|
||||
bits uint32
|
||||
nBits uint32
|
||||
}
|
||||
|
||||
// read reads the next n bits from the decoder's bit-stream.
|
||||
func (d *decoder) read(n uint32) (uint32, error) {
|
||||
for d.nBits < n {
|
||||
c, err := d.r.ReadByte()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
d.bits |= uint32(c) << d.nBits
|
||||
d.nBits += 8
|
||||
}
|
||||
u := d.bits & (1<<n - 1)
|
||||
d.bits >>= n
|
||||
d.nBits -= n
|
||||
return u, nil
|
||||
}
|
||||
|
||||
// decodeTransform decodes the next transform and the width of the image after
|
||||
// transformation (or equivalently, before inverse transformation), specified
|
||||
// in section 3.
|
||||
func (d *decoder) decodeTransform(w int32, h int32) (t transform, newWidth int32, err error) {
|
||||
t.oldWidth = w
|
||||
t.transformType, err = d.read(2)
|
||||
if err != nil {
|
||||
return transform{}, 0, err
|
||||
}
|
||||
switch t.transformType {
|
||||
case transformTypePredictor, transformTypeCrossColor:
|
||||
t.bits, err = d.read(3)
|
||||
if err != nil {
|
||||
return transform{}, 0, err
|
||||
}
|
||||
t.bits += 2
|
||||
t.pix, err = d.decodePix(nTiles(w, t.bits), nTiles(h, t.bits), 0, false)
|
||||
if err != nil {
|
||||
return transform{}, 0, err
|
||||
}
|
||||
case transformTypeSubtractGreen:
|
||||
// No-op.
|
||||
case transformTypeColorIndexing:
|
||||
nColors, err := d.read(8)
|
||||
if err != nil {
|
||||
return transform{}, 0, err
|
||||
}
|
||||
nColors++
|
||||
t.bits = 0
|
||||
switch {
|
||||
case nColors <= 2:
|
||||
t.bits = 3
|
||||
case nColors <= 4:
|
||||
t.bits = 2
|
||||
case nColors <= 16:
|
||||
t.bits = 1
|
||||
}
|
||||
w = nTiles(w, t.bits)
|
||||
pix, err := d.decodePix(int32(nColors), 1, 4*256, false)
|
||||
if err != nil {
|
||||
return transform{}, 0, err
|
||||
}
|
||||
for p := 4; p < len(pix); p += 4 {
|
||||
pix[p+0] += pix[p-4]
|
||||
pix[p+1] += pix[p-3]
|
||||
pix[p+2] += pix[p-2]
|
||||
pix[p+3] += pix[p-1]
|
||||
}
|
||||
// The spec says that "if the index is equal or larger than color_table_size,
|
||||
// the argb color value should be set to 0x00000000 (transparent black)."
|
||||
// We re-slice up to 256 4-byte pixels.
|
||||
t.pix = pix[:4*256]
|
||||
}
|
||||
return t, w, nil
|
||||
}
|
||||
|
||||
// repeatsCodeLength is the minimum code length for repeated codes.
|
||||
const repeatsCodeLength = 16
|
||||
|
||||
// These magic numbers are specified at the end of section 5.2.2.
|
||||
// The 3-length arrays apply to code lengths >= repeatsCodeLength.
|
||||
var (
|
||||
codeLengthCodeOrder = [19]uint8{
|
||||
17, 18, 0, 1, 2, 3, 4, 5, 16, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
|
||||
}
|
||||
repeatBits = [3]uint8{2, 3, 7}
|
||||
repeatOffsets = [3]uint8{3, 3, 11}
|
||||
)
|
||||
|
||||
// decodeCodeLengths decodes a Huffman tree's code lengths which are themselves
|
||||
// encoded via a Huffman tree, specified in section 5.2.2.
|
||||
func (d *decoder) decodeCodeLengths(dst []uint32, codeLengthCodeLengths []uint32) error {
|
||||
h := hTree{}
|
||||
if err := h.build(codeLengthCodeLengths); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
maxSymbol := len(dst)
|
||||
useLength, err := d.read(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if useLength != 0 {
|
||||
n, err := d.read(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n = 2 + 2*n
|
||||
ms, err := d.read(n)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
maxSymbol = int(ms) + 2
|
||||
if maxSymbol > len(dst) {
|
||||
return errInvalidCodeLengths
|
||||
}
|
||||
}
|
||||
|
||||
// The spec says that "if code 16 [meaning repeat] is used before
|
||||
// a non-zero value has been emitted, a value of 8 is repeated."
|
||||
prevCodeLength := uint32(8)
|
||||
|
||||
for symbol := 0; symbol < len(dst); {
|
||||
if maxSymbol == 0 {
|
||||
break
|
||||
}
|
||||
maxSymbol--
|
||||
codeLength, err := h.next(d)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if codeLength < repeatsCodeLength {
|
||||
dst[symbol] = codeLength
|
||||
symbol++
|
||||
if codeLength != 0 {
|
||||
prevCodeLength = codeLength
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
repeat, err := d.read(uint32(repeatBits[codeLength-repeatsCodeLength]))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repeat += uint32(repeatOffsets[codeLength-repeatsCodeLength])
|
||||
if symbol+int(repeat) > len(dst) {
|
||||
return errInvalidCodeLengths
|
||||
}
|
||||
// A code length of 16 repeats the previous non-zero code.
|
||||
// A code length of 17 or 18 repeats zeroes.
|
||||
cl := uint32(0)
|
||||
if codeLength == 16 {
|
||||
cl = prevCodeLength
|
||||
}
|
||||
for ; repeat > 0; repeat-- {
|
||||
dst[symbol] = cl
|
||||
symbol++
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeHuffmanTree decodes a Huffman tree into h.
|
||||
func (d *decoder) decodeHuffmanTree(h *hTree, alphabetSize uint32) error {
|
||||
useSimple, err := d.read(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if useSimple != 0 {
|
||||
nSymbols, err := d.read(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nSymbols++
|
||||
firstSymbolLengthCode, err := d.read(1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
firstSymbolLengthCode = 7*firstSymbolLengthCode + 1
|
||||
var symbols [2]uint32
|
||||
symbols[0], err = d.read(firstSymbolLengthCode)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if nSymbols == 2 {
|
||||
symbols[1], err = d.read(8)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return h.buildSimple(nSymbols, symbols, alphabetSize)
|
||||
}
|
||||
|
||||
nCodes, err := d.read(4)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nCodes += 4
|
||||
if int(nCodes) > len(codeLengthCodeOrder) {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
codeLengthCodeLengths := [len(codeLengthCodeOrder)]uint32{}
|
||||
for i := uint32(0); i < nCodes; i++ {
|
||||
codeLengthCodeLengths[codeLengthCodeOrder[i]], err = d.read(3)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
codeLengths := make([]uint32, alphabetSize)
|
||||
if err = d.decodeCodeLengths(codeLengths, codeLengthCodeLengths[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
return h.build(codeLengths)
|
||||
}
|
||||
|
||||
const (
|
||||
huffGreen = 0
|
||||
huffRed = 1
|
||||
huffBlue = 2
|
||||
huffAlpha = 3
|
||||
huffDistance = 4
|
||||
nHuff = 5
|
||||
)
|
||||
|
||||
// hGroup is an array of 5 Huffman trees.
|
||||
type hGroup [nHuff]hTree
|
||||
|
||||
// decodeHuffmanGroups decodes the one or more hGroups used to decode the pixel
|
||||
// data. If one hGroup is used for the entire image, then hPix and hBits will
|
||||
// be zero. If more than one hGroup is used, then hPix contains the meta-image
|
||||
// that maps tiles to hGroup index, and hBits contains the log-2 tile size.
|
||||
func (d *decoder) decodeHuffmanGroups(w int32, h int32, topLevel bool, ccBits uint32) (
|
||||
hGroups []hGroup, hPix []byte, hBits uint32, err error) {
|
||||
|
||||
maxHGroupIndex := 0
|
||||
if topLevel {
|
||||
useMeta, err := d.read(1)
|
||||
if err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
if useMeta != 0 {
|
||||
hBits, err = d.read(3)
|
||||
if err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
hBits += 2
|
||||
hPix, err = d.decodePix(nTiles(w, hBits), nTiles(h, hBits), 0, false)
|
||||
if err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
for p := 0; p < len(hPix); p += 4 {
|
||||
i := int(hPix[p])<<8 | int(hPix[p+1])
|
||||
if maxHGroupIndex < i {
|
||||
maxHGroupIndex = i
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
hGroups = make([]hGroup, maxHGroupIndex+1)
|
||||
for i := range hGroups {
|
||||
for j, alphabetSize := range alphabetSizes {
|
||||
if j == 0 && ccBits > 0 {
|
||||
alphabetSize += 1 << ccBits
|
||||
}
|
||||
if err := d.decodeHuffmanTree(&hGroups[i][j], alphabetSize); err != nil {
|
||||
return nil, nil, 0, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return hGroups, hPix, hBits, nil
|
||||
}
|
||||
|
||||
const (
|
||||
nLiteralCodes = 256
|
||||
nLengthCodes = 24
|
||||
nDistanceCodes = 40
|
||||
)
|
||||
|
||||
var alphabetSizes = [nHuff]uint32{
|
||||
nLiteralCodes + nLengthCodes,
|
||||
nLiteralCodes,
|
||||
nLiteralCodes,
|
||||
nLiteralCodes,
|
||||
nDistanceCodes,
|
||||
}
|
||||
|
||||
// decodePix decodes pixel data, specified in section 5.2.2.
|
||||
func (d *decoder) decodePix(w int32, h int32, minCap int32, topLevel bool) ([]byte, error) {
|
||||
// Decode the color cache parameters.
|
||||
ccBits, ccShift, ccEntries := uint32(0), uint32(0), ([]uint32)(nil)
|
||||
useColorCache, err := d.read(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if useColorCache != 0 {
|
||||
ccBits, err = d.read(4)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if ccBits < 1 || 11 < ccBits {
|
||||
return nil, errors.New("vp8l: invalid color cache parameters")
|
||||
}
|
||||
ccShift = 32 - ccBits
|
||||
ccEntries = make([]uint32, 1<<ccBits)
|
||||
}
|
||||
|
||||
// Decode the Huffman groups.
|
||||
hGroups, hPix, hBits, err := d.decodeHuffmanGroups(w, h, topLevel, ccBits)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
hMask, tilesPerRow := int32(0), int32(0)
|
||||
if hBits != 0 {
|
||||
hMask, tilesPerRow = 1<<hBits-1, nTiles(w, hBits)
|
||||
}
|
||||
|
||||
// Decode the pixels.
|
||||
if minCap < 4*w*h {
|
||||
minCap = 4 * w * h
|
||||
}
|
||||
pix := make([]byte, 4*w*h, minCap)
|
||||
p, cachedP := 0, 0
|
||||
x, y := int32(0), int32(0)
|
||||
hg, lookupHG := &hGroups[0], hMask != 0
|
||||
for p < len(pix) {
|
||||
if lookupHG {
|
||||
i := 4 * (tilesPerRow*(y>>hBits) + (x >> hBits))
|
||||
hg = &hGroups[uint32(hPix[i])<<8|uint32(hPix[i+1])]
|
||||
}
|
||||
|
||||
green, err := hg[huffGreen].next(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch {
|
||||
case green < nLiteralCodes:
|
||||
// We have a literal pixel.
|
||||
red, err := hg[huffRed].next(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
blue, err := hg[huffBlue].next(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
alpha, err := hg[huffAlpha].next(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
pix[p+0] = uint8(red)
|
||||
pix[p+1] = uint8(green)
|
||||
pix[p+2] = uint8(blue)
|
||||
pix[p+3] = uint8(alpha)
|
||||
p += 4
|
||||
|
||||
x++
|
||||
if x == w {
|
||||
x, y = 0, y+1
|
||||
}
|
||||
lookupHG = hMask != 0 && x&hMask == 0
|
||||
|
||||
case green < nLiteralCodes+nLengthCodes:
|
||||
// We have a LZ77 backwards reference.
|
||||
length, err := d.lz77Param(green - nLiteralCodes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
distSym, err := hg[huffDistance].next(d)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
distCode, err := d.lz77Param(distSym)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dist := distanceMap(w, distCode)
|
||||
pEnd := p + 4*int(length)
|
||||
q := p - 4*int(dist)
|
||||
qEnd := pEnd - 4*int(dist)
|
||||
if p < 0 || len(pix) < pEnd || q < 0 || len(pix) < qEnd {
|
||||
return nil, errors.New("vp8l: invalid LZ77 parameters")
|
||||
}
|
||||
for ; p < pEnd; p, q = p+1, q+1 {
|
||||
pix[p] = pix[q]
|
||||
}
|
||||
|
||||
x += int32(length)
|
||||
for x >= w {
|
||||
x, y = x-w, y+1
|
||||
}
|
||||
lookupHG = hMask != 0
|
||||
|
||||
default:
|
||||
// We have a color cache lookup. First, insert previous pixels
|
||||
// into the cache. Note that VP8L assumes ARGB order, but the
|
||||
// Go image.RGBA type is in RGBA order.
|
||||
for ; cachedP < p; cachedP += 4 {
|
||||
argb := uint32(pix[cachedP+0])<<16 |
|
||||
uint32(pix[cachedP+1])<<8 |
|
||||
uint32(pix[cachedP+2])<<0 |
|
||||
uint32(pix[cachedP+3])<<24
|
||||
ccEntries[(argb*colorCacheMultiplier)>>ccShift] = argb
|
||||
}
|
||||
green -= nLiteralCodes + nLengthCodes
|
||||
if int(green) >= len(ccEntries) {
|
||||
return nil, errors.New("vp8l: invalid color cache index")
|
||||
}
|
||||
argb := ccEntries[green]
|
||||
pix[p+0] = uint8(argb >> 16)
|
||||
pix[p+1] = uint8(argb >> 8)
|
||||
pix[p+2] = uint8(argb >> 0)
|
||||
pix[p+3] = uint8(argb >> 24)
|
||||
p += 4
|
||||
|
||||
x++
|
||||
if x == w {
|
||||
x, y = 0, y+1
|
||||
}
|
||||
lookupHG = hMask != 0 && x&hMask == 0
|
||||
}
|
||||
}
|
||||
return pix, nil
|
||||
}
|
||||
|
||||
// lz77Param returns the next LZ77 parameter: a length or a distance, specified
|
||||
// in section 4.2.2.
|
||||
func (d *decoder) lz77Param(symbol uint32) (uint32, error) {
|
||||
if symbol < 4 {
|
||||
return symbol + 1, nil
|
||||
}
|
||||
extraBits := (symbol - 2) >> 1
|
||||
offset := (2 + symbol&1) << extraBits
|
||||
n, err := d.read(extraBits)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return offset + n + 1, nil
|
||||
}
|
||||
|
||||
// decodeHeader decodes the VP8L header from r.
|
||||
func decodeHeader(r io.Reader) (d *decoder, w int32, h int32, err error) {
|
||||
rr, ok := r.(io.ByteReader)
|
||||
if !ok {
|
||||
rr = bufio.NewReader(r)
|
||||
}
|
||||
d = &decoder{r: rr}
|
||||
magic, err := d.read(8)
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
if magic != 0x2f {
|
||||
return nil, 0, 0, errors.New("vp8l: invalid header")
|
||||
}
|
||||
width, err := d.read(14)
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
width++
|
||||
height, err := d.read(14)
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
height++
|
||||
_, err = d.read(1) // Read and ignore the hasAlpha hint.
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
version, err := d.read(3)
|
||||
if err != nil {
|
||||
return nil, 0, 0, err
|
||||
}
|
||||
if version != 0 {
|
||||
return nil, 0, 0, errors.New("vp8l: invalid version")
|
||||
}
|
||||
return d, int32(width), int32(height), nil
|
||||
}
|
||||
|
||||
// DecodeConfig decodes the color model and dimensions of a VP8L image from r.
|
||||
func DecodeConfig(r io.Reader) (image.Config, error) {
|
||||
_, w, h, err := decodeHeader(r)
|
||||
if err != nil {
|
||||
return image.Config{}, err
|
||||
}
|
||||
return image.Config{
|
||||
ColorModel: color.NRGBAModel,
|
||||
Width: int(w),
|
||||
Height: int(h),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Decode decodes a VP8L image from r.
|
||||
func Decode(r io.Reader) (image.Image, error) {
|
||||
d, w, h, err := decodeHeader(r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Decode the transforms.
|
||||
var (
|
||||
nTransforms int
|
||||
transforms [nTransformTypes]transform
|
||||
transformsSeen [nTransformTypes]bool
|
||||
originalW = w
|
||||
)
|
||||
for {
|
||||
more, err := d.read(1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if more == 0 {
|
||||
break
|
||||
}
|
||||
var t transform
|
||||
t, w, err = d.decodeTransform(w, h)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if transformsSeen[t.transformType] {
|
||||
return nil, errors.New("vp8l: repeated transform")
|
||||
}
|
||||
transformsSeen[t.transformType] = true
|
||||
transforms[nTransforms] = t
|
||||
nTransforms++
|
||||
}
|
||||
// Decode the transformed pixels.
|
||||
pix, err := d.decodePix(w, h, 0, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Apply the inverse transformations.
|
||||
for i := nTransforms - 1; i >= 0; i-- {
|
||||
t := &transforms[i]
|
||||
pix = inverseTransforms[t.transformType](t, pix, h)
|
||||
}
|
||||
return &image.NRGBA{
|
||||
Pix: pix,
|
||||
Stride: 4 * int(originalW),
|
||||
Rect: image.Rect(0, 0, int(originalW), int(h)),
|
||||
}, nil
|
||||
}
|
||||
245
vendor/golang.org/x/image/vp8l/huffman.go
сгенерированный
поставляемый
Обычный файл
245
vendor/golang.org/x/image/vp8l/huffman.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,245 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8l
|
||||
|
||||
import (
|
||||
"io"
|
||||
)
|
||||
|
||||
// reverseBits reverses the bits in a byte.
|
||||
var reverseBits = [256]uint8{
|
||||
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
|
||||
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
|
||||
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
|
||||
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
|
||||
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
|
||||
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
|
||||
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
|
||||
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
|
||||
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
|
||||
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
|
||||
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
|
||||
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
|
||||
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
|
||||
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
|
||||
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
|
||||
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
|
||||
}
|
||||
|
||||
// hNode is a node in a Huffman tree.
|
||||
type hNode struct {
|
||||
// symbol is the symbol held by this node.
|
||||
symbol uint32
|
||||
// children, if positive, is the hTree.nodes index of the first of
|
||||
// this node's two children. Zero means an uninitialized node,
|
||||
// and -1 means a leaf node.
|
||||
children int32
|
||||
}
|
||||
|
||||
const leafNode = -1
|
||||
|
||||
// lutSize is the log-2 size of an hTree's look-up table.
|
||||
const lutSize, lutMask = 7, 1<<7 - 1
|
||||
|
||||
// hTree is a Huffman tree.
|
||||
type hTree struct {
|
||||
// nodes are the nodes of the Huffman tree. During construction,
|
||||
// len(nodes) grows from 1 up to cap(nodes) by steps of two.
|
||||
// After construction, len(nodes) == cap(nodes), and both equal
|
||||
// 2*theNumberOfSymbols - 1.
|
||||
nodes []hNode
|
||||
// lut is a look-up table for walking the nodes. The x in lut[x] is
|
||||
// the next lutSize bits in the bit-stream. The low 8 bits of lut[x]
|
||||
// equals 1 plus the number of bits in the next code, or 0 if the
|
||||
// next code requires more than lutSize bits. The high 24 bits are:
|
||||
// - the symbol, if the code requires lutSize or fewer bits, or
|
||||
// - the hTree.nodes index to start the tree traversal from, if
|
||||
// the next code requires more than lutSize bits.
|
||||
lut [1 << lutSize]uint32
|
||||
}
|
||||
|
||||
// insert inserts into the hTree a symbol whose encoding is the least
|
||||
// significant codeLength bits of code.
|
||||
func (h *hTree) insert(symbol uint32, code uint32, codeLength uint32) error {
|
||||
if symbol > 0xffff || codeLength > 0xfe {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
baseCode := uint32(0)
|
||||
if codeLength > lutSize {
|
||||
baseCode = uint32(reverseBits[(code>>(codeLength-lutSize))&0xff]) >> (8 - lutSize)
|
||||
} else {
|
||||
baseCode = uint32(reverseBits[code&0xff]) >> (8 - codeLength)
|
||||
for i := 0; i < 1<<(lutSize-codeLength); i++ {
|
||||
h.lut[baseCode|uint32(i)<<codeLength] = symbol<<8 | (codeLength + 1)
|
||||
}
|
||||
}
|
||||
|
||||
n := uint32(0)
|
||||
for jump := lutSize; codeLength > 0; {
|
||||
codeLength--
|
||||
if int(n) > len(h.nodes) {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
switch h.nodes[n].children {
|
||||
case leafNode:
|
||||
return errInvalidHuffmanTree
|
||||
case 0:
|
||||
if len(h.nodes) == cap(h.nodes) {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
// Create two empty child nodes.
|
||||
h.nodes[n].children = int32(len(h.nodes))
|
||||
h.nodes = h.nodes[:len(h.nodes)+2]
|
||||
}
|
||||
n = uint32(h.nodes[n].children) + 1&(code>>codeLength)
|
||||
jump--
|
||||
if jump == 0 && h.lut[baseCode] == 0 {
|
||||
h.lut[baseCode] = n << 8
|
||||
}
|
||||
}
|
||||
|
||||
switch h.nodes[n].children {
|
||||
case leafNode:
|
||||
// No-op.
|
||||
case 0:
|
||||
// Turn the uninitialized node into a leaf.
|
||||
h.nodes[n].children = leafNode
|
||||
default:
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
h.nodes[n].symbol = symbol
|
||||
return nil
|
||||
}
|
||||
|
||||
// codeLengthsToCodes returns the canonical Huffman codes implied by the
|
||||
// sequence of code lengths.
|
||||
func codeLengthsToCodes(codeLengths []uint32) ([]uint32, error) {
|
||||
maxCodeLength := uint32(0)
|
||||
for _, cl := range codeLengths {
|
||||
if maxCodeLength < cl {
|
||||
maxCodeLength = cl
|
||||
}
|
||||
}
|
||||
const maxAllowedCodeLength = 15
|
||||
if len(codeLengths) == 0 || maxCodeLength > maxAllowedCodeLength {
|
||||
return nil, errInvalidHuffmanTree
|
||||
}
|
||||
histogram := [maxAllowedCodeLength + 1]uint32{}
|
||||
for _, cl := range codeLengths {
|
||||
histogram[cl]++
|
||||
}
|
||||
currCode, nextCodes := uint32(0), [maxAllowedCodeLength + 1]uint32{}
|
||||
for cl := 1; cl < len(nextCodes); cl++ {
|
||||
currCode = (currCode + histogram[cl-1]) << 1
|
||||
nextCodes[cl] = currCode
|
||||
}
|
||||
codes := make([]uint32, len(codeLengths))
|
||||
for symbol, cl := range codeLengths {
|
||||
if cl > 0 {
|
||||
codes[symbol] = nextCodes[cl]
|
||||
nextCodes[cl]++
|
||||
}
|
||||
}
|
||||
return codes, nil
|
||||
}
|
||||
|
||||
// build builds a canonical Huffman tree from the given code lengths.
|
||||
func (h *hTree) build(codeLengths []uint32) error {
|
||||
// Calculate the number of symbols.
|
||||
var nSymbols, lastSymbol uint32
|
||||
for symbol, cl := range codeLengths {
|
||||
if cl != 0 {
|
||||
nSymbols++
|
||||
lastSymbol = uint32(symbol)
|
||||
}
|
||||
}
|
||||
if nSymbols == 0 {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
h.nodes = make([]hNode, 1, 2*nSymbols-1)
|
||||
// Handle the trivial case.
|
||||
if nSymbols == 1 {
|
||||
if len(codeLengths) <= int(lastSymbol) {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
return h.insert(lastSymbol, 0, 0)
|
||||
}
|
||||
// Handle the non-trivial case.
|
||||
codes, err := codeLengthsToCodes(codeLengths)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for symbol, cl := range codeLengths {
|
||||
if cl > 0 {
|
||||
if err := h.insert(uint32(symbol), codes[symbol], cl); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// buildSimple builds a Huffman tree with 1 or 2 symbols.
|
||||
func (h *hTree) buildSimple(nSymbols uint32, symbols [2]uint32, alphabetSize uint32) error {
|
||||
h.nodes = make([]hNode, 1, 2*nSymbols-1)
|
||||
for i := uint32(0); i < nSymbols; i++ {
|
||||
if symbols[i] >= alphabetSize {
|
||||
return errInvalidHuffmanTree
|
||||
}
|
||||
if err := h.insert(symbols[i], i, nSymbols-1); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// next returns the next Huffman-encoded symbol from the bit-stream d.
|
||||
func (h *hTree) next(d *decoder) (uint32, error) {
|
||||
var n uint32
|
||||
// Read enough bits so that we can use the look-up table.
|
||||
if d.nBits < lutSize {
|
||||
c, err := d.r.ReadByte()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
// There are no more bytes of data, but we may still be able
|
||||
// to read the next symbol out of the previously read bits.
|
||||
goto slowPath
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
d.bits |= uint32(c) << d.nBits
|
||||
d.nBits += 8
|
||||
}
|
||||
// Use the look-up table.
|
||||
n = h.lut[d.bits&lutMask]
|
||||
if b := n & 0xff; b != 0 {
|
||||
b--
|
||||
d.bits >>= b
|
||||
d.nBits -= b
|
||||
return n >> 8, nil
|
||||
}
|
||||
n >>= 8
|
||||
d.bits >>= lutSize
|
||||
d.nBits -= lutSize
|
||||
|
||||
slowPath:
|
||||
for h.nodes[n].children != leafNode {
|
||||
if d.nBits == 0 {
|
||||
c, err := d.r.ReadByte()
|
||||
if err != nil {
|
||||
if err == io.EOF {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
d.bits = uint32(c)
|
||||
d.nBits = 8
|
||||
}
|
||||
n = uint32(h.nodes[n].children) + 1&d.bits
|
||||
d.bits >>= 1
|
||||
d.nBits--
|
||||
}
|
||||
return h.nodes[n].symbol, nil
|
||||
}
|
||||
299
vendor/golang.org/x/image/vp8l/transform.go
сгенерированный
поставляемый
Обычный файл
299
vendor/golang.org/x/image/vp8l/transform.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,299 @@
|
||||
// Copyright 2014 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package vp8l
|
||||
|
||||
// This file deals with image transforms, specified in section 3.
|
||||
|
||||
// nTiles returns the number of tiles needed to cover size pixels, where each
|
||||
// tile's side is 1<<bits pixels long.
|
||||
func nTiles(size int32, bits uint32) int32 {
|
||||
return (size + 1<<bits - 1) >> bits
|
||||
}
|
||||
|
||||
const (
|
||||
transformTypePredictor = 0
|
||||
transformTypeCrossColor = 1
|
||||
transformTypeSubtractGreen = 2
|
||||
transformTypeColorIndexing = 3
|
||||
nTransformTypes = 4
|
||||
)
|
||||
|
||||
// transform holds the parameters for an invertible transform.
|
||||
type transform struct {
|
||||
// transformType is the type of the transform.
|
||||
transformType uint32
|
||||
// oldWidth is the width of the image before transformation (or
|
||||
// equivalently, after inverse transformation). The color-indexing
|
||||
// transform can reduce the width. For example, a 50-pixel-wide
|
||||
// image that only needs 4 bits (half a byte) per color index can
|
||||
// be transformed into a 25-pixel-wide image.
|
||||
oldWidth int32
|
||||
// bits is the log-2 size of the transform's tiles, for the predictor
|
||||
// and cross-color transforms. 8>>bits is the number of bits per
|
||||
// color index, for the color-index transform.
|
||||
bits uint32
|
||||
// pix is the tile values, for the predictor and cross-color
|
||||
// transforms, and the color palette, for the color-index transform.
|
||||
pix []byte
|
||||
}
|
||||
|
||||
var inverseTransforms = [nTransformTypes]func(*transform, []byte, int32) []byte{
|
||||
transformTypePredictor: inversePredictor,
|
||||
transformTypeCrossColor: inverseCrossColor,
|
||||
transformTypeSubtractGreen: inverseSubtractGreen,
|
||||
transformTypeColorIndexing: inverseColorIndexing,
|
||||
}
|
||||
|
||||
func inversePredictor(t *transform, pix []byte, h int32) []byte {
|
||||
if t.oldWidth == 0 || h == 0 {
|
||||
return pix
|
||||
}
|
||||
// The first pixel's predictor is mode 0 (opaque black).
|
||||
pix[3] += 0xff
|
||||
p, mask := int32(4), int32(1)<<t.bits-1
|
||||
for x := int32(1); x < t.oldWidth; x++ {
|
||||
// The rest of the first row's predictor is mode 1 (L).
|
||||
pix[p+0] += pix[p-4]
|
||||
pix[p+1] += pix[p-3]
|
||||
pix[p+2] += pix[p-2]
|
||||
pix[p+3] += pix[p-1]
|
||||
p += 4
|
||||
}
|
||||
top, tilesPerRow := 0, nTiles(t.oldWidth, t.bits)
|
||||
for y := int32(1); y < h; y++ {
|
||||
// The first column's predictor is mode 2 (T).
|
||||
pix[p+0] += pix[top+0]
|
||||
pix[p+1] += pix[top+1]
|
||||
pix[p+2] += pix[top+2]
|
||||
pix[p+3] += pix[top+3]
|
||||
p, top = p+4, top+4
|
||||
|
||||
q := 4 * (y >> t.bits) * tilesPerRow
|
||||
predictorMode := t.pix[q+1] & 0x0f
|
||||
q += 4
|
||||
for x := int32(1); x < t.oldWidth; x++ {
|
||||
if x&mask == 0 {
|
||||
predictorMode = t.pix[q+1] & 0x0f
|
||||
q += 4
|
||||
}
|
||||
switch predictorMode {
|
||||
case 0: // Opaque black.
|
||||
pix[p+3] += 0xff
|
||||
|
||||
case 1: // L.
|
||||
pix[p+0] += pix[p-4]
|
||||
pix[p+1] += pix[p-3]
|
||||
pix[p+2] += pix[p-2]
|
||||
pix[p+3] += pix[p-1]
|
||||
|
||||
case 2: // T.
|
||||
pix[p+0] += pix[top+0]
|
||||
pix[p+1] += pix[top+1]
|
||||
pix[p+2] += pix[top+2]
|
||||
pix[p+3] += pix[top+3]
|
||||
|
||||
case 3: // TR.
|
||||
pix[p+0] += pix[top+4]
|
||||
pix[p+1] += pix[top+5]
|
||||
pix[p+2] += pix[top+6]
|
||||
pix[p+3] += pix[top+7]
|
||||
|
||||
case 4: // TL.
|
||||
pix[p+0] += pix[top-4]
|
||||
pix[p+1] += pix[top-3]
|
||||
pix[p+2] += pix[top-2]
|
||||
pix[p+3] += pix[top-1]
|
||||
|
||||
case 5: // Average2(Average2(L, TR), T).
|
||||
pix[p+0] += avg2(avg2(pix[p-4], pix[top+4]), pix[top+0])
|
||||
pix[p+1] += avg2(avg2(pix[p-3], pix[top+5]), pix[top+1])
|
||||
pix[p+2] += avg2(avg2(pix[p-2], pix[top+6]), pix[top+2])
|
||||
pix[p+3] += avg2(avg2(pix[p-1], pix[top+7]), pix[top+3])
|
||||
|
||||
case 6: // Average2(L, TL).
|
||||
pix[p+0] += avg2(pix[p-4], pix[top-4])
|
||||
pix[p+1] += avg2(pix[p-3], pix[top-3])
|
||||
pix[p+2] += avg2(pix[p-2], pix[top-2])
|
||||
pix[p+3] += avg2(pix[p-1], pix[top-1])
|
||||
|
||||
case 7: // Average2(L, T).
|
||||
pix[p+0] += avg2(pix[p-4], pix[top+0])
|
||||
pix[p+1] += avg2(pix[p-3], pix[top+1])
|
||||
pix[p+2] += avg2(pix[p-2], pix[top+2])
|
||||
pix[p+3] += avg2(pix[p-1], pix[top+3])
|
||||
|
||||
case 8: // Average2(TL, T).
|
||||
pix[p+0] += avg2(pix[top-4], pix[top+0])
|
||||
pix[p+1] += avg2(pix[top-3], pix[top+1])
|
||||
pix[p+2] += avg2(pix[top-2], pix[top+2])
|
||||
pix[p+3] += avg2(pix[top-1], pix[top+3])
|
||||
|
||||
case 9: // Average2(T, TR).
|
||||
pix[p+0] += avg2(pix[top+0], pix[top+4])
|
||||
pix[p+1] += avg2(pix[top+1], pix[top+5])
|
||||
pix[p+2] += avg2(pix[top+2], pix[top+6])
|
||||
pix[p+3] += avg2(pix[top+3], pix[top+7])
|
||||
|
||||
case 10: // Average2(Average2(L, TL), Average2(T, TR)).
|
||||
pix[p+0] += avg2(avg2(pix[p-4], pix[top-4]), avg2(pix[top+0], pix[top+4]))
|
||||
pix[p+1] += avg2(avg2(pix[p-3], pix[top-3]), avg2(pix[top+1], pix[top+5]))
|
||||
pix[p+2] += avg2(avg2(pix[p-2], pix[top-2]), avg2(pix[top+2], pix[top+6]))
|
||||
pix[p+3] += avg2(avg2(pix[p-1], pix[top-1]), avg2(pix[top+3], pix[top+7]))
|
||||
|
||||
case 11: // Select(L, T, TL).
|
||||
l0 := int32(pix[p-4])
|
||||
l1 := int32(pix[p-3])
|
||||
l2 := int32(pix[p-2])
|
||||
l3 := int32(pix[p-1])
|
||||
c0 := int32(pix[top-4])
|
||||
c1 := int32(pix[top-3])
|
||||
c2 := int32(pix[top-2])
|
||||
c3 := int32(pix[top-1])
|
||||
t0 := int32(pix[top+0])
|
||||
t1 := int32(pix[top+1])
|
||||
t2 := int32(pix[top+2])
|
||||
t3 := int32(pix[top+3])
|
||||
l := abs(c0-t0) + abs(c1-t1) + abs(c2-t2) + abs(c3-t3)
|
||||
t := abs(c0-l0) + abs(c1-l1) + abs(c2-l2) + abs(c3-l3)
|
||||
if l < t {
|
||||
pix[p+0] += uint8(l0)
|
||||
pix[p+1] += uint8(l1)
|
||||
pix[p+2] += uint8(l2)
|
||||
pix[p+3] += uint8(l3)
|
||||
} else {
|
||||
pix[p+0] += uint8(t0)
|
||||
pix[p+1] += uint8(t1)
|
||||
pix[p+2] += uint8(t2)
|
||||
pix[p+3] += uint8(t3)
|
||||
}
|
||||
|
||||
case 12: // ClampAddSubtractFull(L, T, TL).
|
||||
pix[p+0] += clampAddSubtractFull(pix[p-4], pix[top+0], pix[top-4])
|
||||
pix[p+1] += clampAddSubtractFull(pix[p-3], pix[top+1], pix[top-3])
|
||||
pix[p+2] += clampAddSubtractFull(pix[p-2], pix[top+2], pix[top-2])
|
||||
pix[p+3] += clampAddSubtractFull(pix[p-1], pix[top+3], pix[top-1])
|
||||
|
||||
case 13: // ClampAddSubtractHalf(Average2(L, T), TL).
|
||||
pix[p+0] += clampAddSubtractHalf(avg2(pix[p-4], pix[top+0]), pix[top-4])
|
||||
pix[p+1] += clampAddSubtractHalf(avg2(pix[p-3], pix[top+1]), pix[top-3])
|
||||
pix[p+2] += clampAddSubtractHalf(avg2(pix[p-2], pix[top+2]), pix[top-2])
|
||||
pix[p+3] += clampAddSubtractHalf(avg2(pix[p-1], pix[top+3]), pix[top-1])
|
||||
}
|
||||
p, top = p+4, top+4
|
||||
}
|
||||
}
|
||||
return pix
|
||||
}
|
||||
|
||||
func inverseCrossColor(t *transform, pix []byte, h int32) []byte {
|
||||
var greenToRed, greenToBlue, redToBlue int32
|
||||
p, mask, tilesPerRow := int32(0), int32(1)<<t.bits-1, nTiles(t.oldWidth, t.bits)
|
||||
for y := int32(0); y < h; y++ {
|
||||
q := 4 * (y >> t.bits) * tilesPerRow
|
||||
for x := int32(0); x < t.oldWidth; x++ {
|
||||
if x&mask == 0 {
|
||||
redToBlue = int32(int8(t.pix[q+0]))
|
||||
greenToBlue = int32(int8(t.pix[q+1]))
|
||||
greenToRed = int32(int8(t.pix[q+2]))
|
||||
q += 4
|
||||
}
|
||||
red := pix[p+0]
|
||||
green := pix[p+1]
|
||||
blue := pix[p+2]
|
||||
red += uint8(uint32(greenToRed*int32(int8(green))) >> 5)
|
||||
blue += uint8(uint32(greenToBlue*int32(int8(green))) >> 5)
|
||||
blue += uint8(uint32(redToBlue*int32(int8(red))) >> 5)
|
||||
pix[p+0] = red
|
||||
pix[p+2] = blue
|
||||
p += 4
|
||||
}
|
||||
}
|
||||
return pix
|
||||
}
|
||||
|
||||
func inverseSubtractGreen(t *transform, pix []byte, h int32) []byte {
|
||||
for p := 0; p < len(pix); p += 4 {
|
||||
green := pix[p+1]
|
||||
pix[p+0] += green
|
||||
pix[p+2] += green
|
||||
}
|
||||
return pix
|
||||
}
|
||||
|
||||
func inverseColorIndexing(t *transform, pix []byte, h int32) []byte {
|
||||
if t.bits == 0 {
|
||||
for p := 0; p < len(pix); p += 4 {
|
||||
i := 4 * uint32(pix[p+1])
|
||||
pix[p+0] = t.pix[i+0]
|
||||
pix[p+1] = t.pix[i+1]
|
||||
pix[p+2] = t.pix[i+2]
|
||||
pix[p+3] = t.pix[i+3]
|
||||
}
|
||||
return pix
|
||||
}
|
||||
|
||||
vMask, xMask, bitsPerPixel := uint32(0), int32(0), uint32(8>>t.bits)
|
||||
switch t.bits {
|
||||
case 1:
|
||||
vMask, xMask = 0x0f, 0x01
|
||||
case 2:
|
||||
vMask, xMask = 0x03, 0x03
|
||||
case 3:
|
||||
vMask, xMask = 0x01, 0x07
|
||||
}
|
||||
|
||||
d, p, v, dst := 0, 0, uint32(0), make([]byte, 4*t.oldWidth*h)
|
||||
for y := int32(0); y < h; y++ {
|
||||
for x := int32(0); x < t.oldWidth; x++ {
|
||||
if x&xMask == 0 {
|
||||
v = uint32(pix[p+1])
|
||||
p += 4
|
||||
}
|
||||
|
||||
i := 4 * (v & vMask)
|
||||
dst[d+0] = t.pix[i+0]
|
||||
dst[d+1] = t.pix[i+1]
|
||||
dst[d+2] = t.pix[i+2]
|
||||
dst[d+3] = t.pix[i+3]
|
||||
d += 4
|
||||
|
||||
v >>= bitsPerPixel
|
||||
}
|
||||
}
|
||||
return dst
|
||||
}
|
||||
|
||||
func abs(x int32) int32 {
|
||||
if x < 0 {
|
||||
return -x
|
||||
}
|
||||
return x
|
||||
}
|
||||
|
||||
func avg2(a, b uint8) uint8 {
|
||||
return uint8((int32(a) + int32(b)) / 2)
|
||||
}
|
||||
|
||||
func clampAddSubtractFull(a, b, c uint8) uint8 {
|
||||
x := int32(a) + int32(b) - int32(c)
|
||||
if x < 0 {
|
||||
return 0
|
||||
}
|
||||
if x > 255 {
|
||||
return 255
|
||||
}
|
||||
return uint8(x)
|
||||
}
|
||||
|
||||
func clampAddSubtractHalf(a, b uint8) uint8 {
|
||||
x := int32(a) + (int32(a)-int32(b))/2
|
||||
if x < 0 {
|
||||
return 0
|
||||
}
|
||||
if x > 255 {
|
||||
return 255
|
||||
}
|
||||
return uint8(x)
|
||||
}
|
||||
270
vendor/golang.org/x/image/webp/decode.go
сгенерированный
поставляемый
Обычный файл
270
vendor/golang.org/x/image/webp/decode.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,270 @@
|
||||
// Copyright 2011 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package webp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"io"
|
||||
|
||||
"golang.org/x/image/riff"
|
||||
"golang.org/x/image/vp8"
|
||||
"golang.org/x/image/vp8l"
|
||||
)
|
||||
|
||||
var errInvalidFormat = errors.New("webp: invalid format")
|
||||
|
||||
var (
|
||||
fccALPH = riff.FourCC{'A', 'L', 'P', 'H'}
|
||||
fccVP8 = riff.FourCC{'V', 'P', '8', ' '}
|
||||
fccVP8L = riff.FourCC{'V', 'P', '8', 'L'}
|
||||
fccVP8X = riff.FourCC{'V', 'P', '8', 'X'}
|
||||
fccWEBP = riff.FourCC{'W', 'E', 'B', 'P'}
|
||||
)
|
||||
|
||||
func decode(r io.Reader, configOnly bool) (image.Image, image.Config, error) {
|
||||
formType, riffReader, err := riff.NewReader(r)
|
||||
if err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
if formType != fccWEBP {
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
|
||||
var (
|
||||
alpha []byte
|
||||
alphaStride int
|
||||
wantAlpha bool
|
||||
widthMinusOne uint32
|
||||
heightMinusOne uint32
|
||||
buf [10]byte
|
||||
)
|
||||
for {
|
||||
chunkID, chunkLen, chunkData, err := riffReader.Next()
|
||||
if err == io.EOF {
|
||||
err = errInvalidFormat
|
||||
}
|
||||
if err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
|
||||
switch chunkID {
|
||||
case fccALPH:
|
||||
if !wantAlpha {
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
wantAlpha = false
|
||||
// Read the Pre-processing | Filter | Compression byte.
|
||||
if _, err := io.ReadFull(chunkData, buf[:1]); err != nil {
|
||||
if err == io.EOF {
|
||||
err = errInvalidFormat
|
||||
}
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
alpha, alphaStride, err = readAlpha(chunkData, widthMinusOne, heightMinusOne, buf[0]&0x03)
|
||||
if err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
unfilterAlpha(alpha, alphaStride, (buf[0]>>2)&0x03)
|
||||
|
||||
case fccVP8:
|
||||
if wantAlpha || int32(chunkLen) < 0 {
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
d := vp8.NewDecoder()
|
||||
d.Init(chunkData, int(chunkLen))
|
||||
fh, err := d.DecodeFrameHeader()
|
||||
if err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
if configOnly {
|
||||
return nil, image.Config{
|
||||
ColorModel: color.YCbCrModel,
|
||||
Width: fh.Width,
|
||||
Height: fh.Height,
|
||||
}, nil
|
||||
}
|
||||
m, err := d.DecodeFrame()
|
||||
if err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
if alpha != nil {
|
||||
return &image.NYCbCrA{
|
||||
YCbCr: *m,
|
||||
A: alpha,
|
||||
AStride: alphaStride,
|
||||
}, image.Config{}, nil
|
||||
}
|
||||
return m, image.Config{}, nil
|
||||
|
||||
case fccVP8L:
|
||||
if wantAlpha || alpha != nil {
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
if configOnly {
|
||||
c, err := vp8l.DecodeConfig(chunkData)
|
||||
return nil, c, err
|
||||
}
|
||||
m, err := vp8l.Decode(chunkData)
|
||||
return m, image.Config{}, err
|
||||
|
||||
case fccVP8X:
|
||||
if chunkLen != 10 {
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
if _, err := io.ReadFull(chunkData, buf[:10]); err != nil {
|
||||
return nil, image.Config{}, err
|
||||
}
|
||||
const (
|
||||
animationBit = 1 << 1
|
||||
xmpMetadataBit = 1 << 2
|
||||
exifMetadataBit = 1 << 3
|
||||
alphaBit = 1 << 4
|
||||
iccProfileBit = 1 << 5
|
||||
)
|
||||
if buf[0] != alphaBit {
|
||||
return nil, image.Config{}, errors.New("webp: non-Alpha VP8X is not implemented")
|
||||
}
|
||||
widthMinusOne = uint32(buf[4]) | uint32(buf[5])<<8 | uint32(buf[6])<<16
|
||||
heightMinusOne = uint32(buf[7]) | uint32(buf[8])<<8 | uint32(buf[9])<<16
|
||||
if configOnly {
|
||||
return nil, image.Config{
|
||||
ColorModel: color.NYCbCrAModel,
|
||||
Width: int(widthMinusOne) + 1,
|
||||
Height: int(heightMinusOne) + 1,
|
||||
}, nil
|
||||
}
|
||||
wantAlpha = true
|
||||
|
||||
default:
|
||||
return nil, image.Config{}, errInvalidFormat
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readAlpha(chunkData io.Reader, widthMinusOne, heightMinusOne uint32, compression byte) (
|
||||
alpha []byte, alphaStride int, err error) {
|
||||
|
||||
switch compression {
|
||||
case 0:
|
||||
w := int(widthMinusOne) + 1
|
||||
h := int(heightMinusOne) + 1
|
||||
alpha = make([]byte, w*h)
|
||||
if _, err := io.ReadFull(chunkData, alpha); err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return alpha, w, nil
|
||||
|
||||
case 1:
|
||||
// Read the VP8L-compressed alpha values. First, synthesize a 5-byte VP8L header:
|
||||
// a 1-byte magic number, a 14-bit widthMinusOne, a 14-bit heightMinusOne,
|
||||
// a 1-bit (ignored, zero) alphaIsUsed and a 3-bit (zero) version.
|
||||
// TODO(nigeltao): be more efficient than decoding an *image.NRGBA just to
|
||||
// extract the green values to a separately allocated []byte. Fixing this
|
||||
// will require changes to the vp8l package's API.
|
||||
if widthMinusOne > 0x3fff || heightMinusOne > 0x3fff {
|
||||
return nil, 0, errors.New("webp: invalid format")
|
||||
}
|
||||
alphaImage, err := vp8l.Decode(io.MultiReader(
|
||||
bytes.NewReader([]byte{
|
||||
0x2f, // VP8L magic number.
|
||||
uint8(widthMinusOne),
|
||||
uint8(widthMinusOne>>8) | uint8(heightMinusOne<<6),
|
||||
uint8(heightMinusOne >> 2),
|
||||
uint8(heightMinusOne >> 10),
|
||||
}),
|
||||
chunkData,
|
||||
))
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
// The green values of the inner NRGBA image are the alpha values of the
|
||||
// outer NYCbCrA image.
|
||||
pix := alphaImage.(*image.NRGBA).Pix
|
||||
alpha = make([]byte, len(pix)/4)
|
||||
for i := range alpha {
|
||||
alpha[i] = pix[4*i+1]
|
||||
}
|
||||
return alpha, int(widthMinusOne) + 1, nil
|
||||
}
|
||||
return nil, 0, errInvalidFormat
|
||||
}
|
||||
|
||||
func unfilterAlpha(alpha []byte, alphaStride int, filter byte) {
|
||||
if len(alpha) == 0 || alphaStride == 0 {
|
||||
return
|
||||
}
|
||||
switch filter {
|
||||
case 1: // Horizontal filter.
|
||||
for i := 1; i < alphaStride; i++ {
|
||||
alpha[i] += alpha[i-1]
|
||||
}
|
||||
for i := alphaStride; i < len(alpha); i += alphaStride {
|
||||
// The first column is equivalent to the vertical filter.
|
||||
alpha[i] += alpha[i-alphaStride]
|
||||
|
||||
for j := 1; j < alphaStride; j++ {
|
||||
alpha[i+j] += alpha[i+j-1]
|
||||
}
|
||||
}
|
||||
|
||||
case 2: // Vertical filter.
|
||||
// The first row is equivalent to the horizontal filter.
|
||||
for i := 1; i < alphaStride; i++ {
|
||||
alpha[i] += alpha[i-1]
|
||||
}
|
||||
|
||||
for i := alphaStride; i < len(alpha); i++ {
|
||||
alpha[i] += alpha[i-alphaStride]
|
||||
}
|
||||
|
||||
case 3: // Gradient filter.
|
||||
// The first row is equivalent to the horizontal filter.
|
||||
for i := 1; i < alphaStride; i++ {
|
||||
alpha[i] += alpha[i-1]
|
||||
}
|
||||
|
||||
for i := alphaStride; i < len(alpha); i += alphaStride {
|
||||
// The first column is equivalent to the vertical filter.
|
||||
alpha[i] += alpha[i-alphaStride]
|
||||
|
||||
// The interior is predicted on the three top/left pixels.
|
||||
for j := 1; j < alphaStride; j++ {
|
||||
c := int(alpha[i+j-alphaStride-1])
|
||||
b := int(alpha[i+j-alphaStride])
|
||||
a := int(alpha[i+j-1])
|
||||
x := a + b - c
|
||||
if x < 0 {
|
||||
x = 0
|
||||
} else if x > 255 {
|
||||
x = 255
|
||||
}
|
||||
alpha[i+j] += uint8(x)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Decode reads a WEBP image from r and returns it as an image.Image.
|
||||
func Decode(r io.Reader) (image.Image, error) {
|
||||
m, _, err := decode(r, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, err
|
||||
}
|
||||
|
||||
// DecodeConfig returns the color model and dimensions of a WEBP image without
|
||||
// decoding the entire image.
|
||||
func DecodeConfig(r io.Reader) (image.Config, error) {
|
||||
_, c, err := decode(r, true)
|
||||
return c, err
|
||||
}
|
||||
|
||||
func init() {
|
||||
image.RegisterFormat("webp", "RIFF????WEBPVP8", Decode, DecodeConfig)
|
||||
}
|
||||
9
vendor/golang.org/x/image/webp/doc.go
сгенерированный
поставляемый
Обычный файл
9
vendor/golang.org/x/image/webp/doc.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,9 @@
|
||||
// Copyright 2016 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package webp implements a decoder for WEBP images.
|
||||
//
|
||||
// WEBP is defined at:
|
||||
// https://developers.google.com/speed/webp/docs/riff_container
|
||||
package webp // import "golang.org/x/image/webp"
|
||||
202
vendor/willnorris.com/go/gifresize/LICENSE
сгенерированный
поставляемый
Обычный файл
202
vendor/willnorris.com/go/gifresize/LICENSE
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
15
vendor/willnorris.com/go/gifresize/README.md
сгенерированный
поставляемый
Обычный файл
15
vendor/willnorris.com/go/gifresize/README.md
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,15 @@
|
||||
# gifresize [](https://godoc.org/willnorris.com/go/gifresize) [](LICENSE)
|
||||
|
||||
gifresize is a simple go package for transforming animated GIFs.
|
||||
|
||||
Import using:
|
||||
|
||||
```go
|
||||
import "willnorris.com/go/gifresize"
|
||||
```
|
||||
|
||||
Then call `gifresize.Process` with the source io.Reader and destination
|
||||
io.Writer as well as the transformation to be applied to each frame in the GIF.
|
||||
See [example/main.go][] for a simple example.
|
||||
|
||||
[example/main.go]: ./example/main.go
|
||||
85
vendor/willnorris.com/go/gifresize/gifresize.go
сгенерированный
поставляемый
Обычный файл
85
vendor/willnorris.com/go/gifresize/gifresize.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,85 @@
|
||||
// Copyright 2013 Daniel Pupius. All rights reserved.
|
||||
// Copyright 2015 Google. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package gifresize resizes animated gifs.
|
||||
//
|
||||
// Frames in an animated gif aren't necessarily the same size, subsequent
|
||||
// frames are overlayed on previous frames. Therefore, resizing the frames
|
||||
// individually may cause problems due to aliasing of transparent pixels. This
|
||||
// package tries to avoid this by building frames from all previous frames and
|
||||
// resizing the frames as RGB.
|
||||
package gifresize // import "willnorris.com/go/gifresize"
|
||||
|
||||
import (
|
||||
"image"
|
||||
"image/color"
|
||||
"image/draw"
|
||||
"image/gif"
|
||||
"io"
|
||||
)
|
||||
|
||||
// TransformFunc is a function that transforms an image.
|
||||
type TransformFunc func(image.Image) image.Image
|
||||
|
||||
// Process the GIF read from r, applying transform to each frame, and writing
|
||||
// the result to w.
|
||||
func Process(w io.Writer, r io.Reader, transform TransformFunc) error {
|
||||
if transform == nil {
|
||||
_, err := io.Copy(w, r)
|
||||
return err
|
||||
}
|
||||
|
||||
// Decode the original gif.
|
||||
im, err := gif.DecodeAll(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Create a new RGBA image to hold the incremental frames.
|
||||
firstFrame := im.Image[0].Bounds()
|
||||
b := image.Rect(0, 0, firstFrame.Dx(), firstFrame.Dy())
|
||||
img := image.NewRGBA(b)
|
||||
|
||||
// Resize each frame.
|
||||
for index, frame := range im.Image {
|
||||
bounds := frame.Bounds()
|
||||
previous := img
|
||||
draw.Draw(img, bounds, frame, bounds.Min, draw.Over)
|
||||
im.Image[index] = imageToPaletted(transform(img), frame.Palette)
|
||||
|
||||
switch im.Disposal[index] {
|
||||
case gif.DisposalBackground:
|
||||
// I'm just assuming that the gif package will apply the appropriate
|
||||
// background here, since there doesn't seem to be an easy way to
|
||||
// access the global color table
|
||||
img = image.NewRGBA(b)
|
||||
case gif.DisposalPrevious:
|
||||
img = previous
|
||||
}
|
||||
}
|
||||
|
||||
// Set image.Config to new height and width
|
||||
im.Config.Width = im.Image[0].Bounds().Max.X
|
||||
im.Config.Height = im.Image[0].Bounds().Max.Y
|
||||
|
||||
return gif.EncodeAll(w, im)
|
||||
}
|
||||
|
||||
func imageToPaletted(img image.Image, p color.Palette) *image.Paletted {
|
||||
b := img.Bounds()
|
||||
pm := image.NewPaletted(b, p)
|
||||
draw.FloydSteinberg.Draw(pm, b, img, image.ZP)
|
||||
return pm
|
||||
}
|
||||
1
vendor/willnorris.com/go/gifresize/go.mod
сгенерированный
поставляемый
Обычный файл
1
vendor/willnorris.com/go/gifresize/go.mod
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1 @@
|
||||
module willnorris.com/go/gifresize
|
||||
12
vendor/willnorris.com/go/imageproxy/.gitignore
сгенерированный
поставляемый
Обычный файл
12
vendor/willnorris.com/go/imageproxy/.gitignore
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,12 @@
|
||||
build
|
||||
.goxc.local.json
|
||||
*.test
|
||||
|
||||
vendor/**/.travis.yml
|
||||
vendor/**/.gitignore
|
||||
vendor/**/.goxc.json
|
||||
vendor/**/AUTHORS
|
||||
vendor/**/CONTRIBUTORS
|
||||
vendor/**/Makefile
|
||||
vendor/**/*_ZH.md
|
||||
vendor/**/*.sh
|
||||
16
vendor/willnorris.com/go/imageproxy/.travis.yml
сгенерированный
поставляемый
Обычный файл
16
vendor/willnorris.com/go/imageproxy/.travis.yml
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,16 @@
|
||||
language: go
|
||||
sudo: false
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- go: "1.10.x"
|
||||
script: go test -v ./...
|
||||
- go: "1.11.x"
|
||||
script: go test -v -mod=vendor ./...
|
||||
|
||||
go_import_path: willnorris.com/go/imageproxy
|
||||
|
||||
env:
|
||||
- GO111MODULE=on
|
||||
|
||||
install: true
|
||||
22
vendor/willnorris.com/go/imageproxy/Dockerfile
сгенерированный
поставляемый
Обычный файл
22
vendor/willnorris.com/go/imageproxy/Dockerfile
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,22 @@
|
||||
FROM golang:1.9 as build
|
||||
MAINTAINER Will Norris <will@willnorris.com>
|
||||
|
||||
WORKDIR /go/src/willnorris.com/go/imageproxy
|
||||
ADD . .
|
||||
|
||||
WORKDIR /go/src/willnorris.com/go/imageproxy/cmd/imageproxy
|
||||
RUN go-wrapper download
|
||||
RUN CGO_ENABLED=0 GOOS=linux go-wrapper install
|
||||
|
||||
FROM scratch
|
||||
|
||||
WORKDIR /go/bin
|
||||
|
||||
COPY --from=build /usr/share/zoneinfo /usr/share/zoneinfo
|
||||
COPY --from=build /etc/ssl/certs /etc/ssl/certs
|
||||
COPY --from=build /go/bin/imageproxy .
|
||||
|
||||
CMD ["-addr", "0.0.0.0:8080"]
|
||||
ENTRYPOINT ["/go/bin/imageproxy"]
|
||||
|
||||
EXPOSE 8080
|
||||
178
vendor/willnorris.com/go/imageproxy/LICENSE
сгенерированный
поставляемый
Обычный файл
178
vendor/willnorris.com/go/imageproxy/LICENSE
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,178 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
310
vendor/willnorris.com/go/imageproxy/README.md
сгенерированный
поставляемый
Обычный файл
310
vendor/willnorris.com/go/imageproxy/README.md
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,310 @@
|
||||
# imageproxy
|
||||
|
||||
[](https://godoc.org/willnorris.com/go/imageproxy)
|
||||
[](https://travis-ci.org/willnorris/imageproxy)
|
||||
[](LICENSE)
|
||||
|
||||
imageproxy is a caching image proxy server written in go. It features:
|
||||
|
||||
- basic image adjustments like resizing, cropping, and rotation
|
||||
- access control using allowed hosts list or request signing (HMAC-SHA256)
|
||||
- support for jpeg, png, webp (decode only), tiff, and gif image formats
|
||||
(including animated gifs)
|
||||
- caching in-memory, on disk, or with Amazon S3, Google Cloud Storage, Azure
|
||||
Storage, or Redis
|
||||
- easy deployment, since it's pure go
|
||||
|
||||
Personally, I use it primarily to dynamically resize images hosted on my own
|
||||
site (read more in [this post][]). But you can also enable request signing and
|
||||
use it as an SSL proxy for remote images, similar to [atmos/camo][] but with
|
||||
additional image adjustment options.
|
||||
|
||||
[this post]: https://willnorris.com/2014/01/a-self-hosted-alternative-to-jetpacks-photon-service
|
||||
[atmos/camo]: https://github.com/atmos/camo
|
||||
|
||||
|
||||
## URL Structure ##
|
||||
|
||||
imageproxy URLs are of the form `http://localhost/{options}/{remote_url}`.
|
||||
|
||||
### Options ###
|
||||
|
||||
Options are available for cropping, resizing, rotation, flipping, and digital
|
||||
signatures among a few others. Options for are specified as a comma delimited
|
||||
list of parameters, which can be supplied in any order. Duplicate parameters
|
||||
overwrite previous values.
|
||||
|
||||
See the full list of available options at
|
||||
<https://godoc.org/willnorris.com/go/imageproxy#ParseOptions>.
|
||||
|
||||
### Remote URL ###
|
||||
|
||||
The URL of the original image to load is specified as the remainder of the
|
||||
path, without any encoding. For example,
|
||||
`http://localhost/200/https://willnorris.com/logo.jpg`.
|
||||
|
||||
In order to [optimize caching][], it is recommended that URLs not contain query
|
||||
strings.
|
||||
|
||||
[optimize caching]: http://www.stevesouders.com/blog/2008/08/23/revving-filenames-dont-use-querystring/
|
||||
|
||||
### Examples ###
|
||||
|
||||
The following live examples demonstrate setting different options on [this
|
||||
source image][small-things], which measures 1024 by 678 pixels.
|
||||
|
||||
[small-things]: https://willnorris.com/2013/12/small-things.jpg
|
||||
|
||||
Options | Meaning | Image
|
||||
--------|------------------------------------------|------
|
||||
200x | 200px wide, proportional height | <a href="https://willnorris.com/api/imageproxy/200x/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/200x/https://willnorris.com/2013/12/small-things.jpg" alt="200x"></a>
|
||||
x0.15 | 15% original height, proportional width | <a href="https://willnorris.com/api/imageproxy/x0.15/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/x0.15/https://willnorris.com/2013/12/small-things.jpg" alt="x0.15"></a>
|
||||
100x150 | 100 by 150 pixels, cropping as needed | <a href="https://willnorris.com/api/imageproxy/100x150/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/100x150/https://willnorris.com/2013/12/small-things.jpg" alt="100x150"></a>
|
||||
100 | 100px square, cropping as needed | <a href="https://willnorris.com/api/imageproxy/100/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/100/https://willnorris.com/2013/12/small-things.jpg" alt="100"></a>
|
||||
150,fit | scale to fit 150px square, no cropping | <a href="https://willnorris.com/api/imageproxy/150,fit/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/150,fit/https://willnorris.com/2013/12/small-things.jpg" alt="150,fit"></a>
|
||||
100,r90 | 100px square, rotated 90 degrees | <a href="https://willnorris.com/api/imageproxy/100,r90/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/100,r90/https://willnorris.com/2013/12/small-things.jpg" alt="100,r90"></a>
|
||||
100,fv,fh | 100px square, flipped horizontal and vertical | <a href="https://willnorris.com/api/imageproxy/100,fv,fh/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/100,fv,fh/https://willnorris.com/2013/12/small-things.jpg" alt="100,fv,fh"></a>
|
||||
200x,q60 | 200px wide, proportional height, 60% quality | <a href="https://willnorris.com/api/imageproxy/200x,q60/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/200x,q60/https://willnorris.com/2013/12/small-things.jpg" alt="200x,q60"></a>
|
||||
200x,png | 200px wide, converted to PNG format | <a href="https://willnorris.com/api/imageproxy/200x,png/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/200x,png/https://willnorris.com/2013/12/small-things.jpg" alt="200x,png"></a>
|
||||
cx175,cw400,ch300,100x | crop to 400x300px starting at (175,0), scale to 100px wide | <a href="https://willnorris.com/api/imageproxy/cx175,cw400,ch300,100x/https://willnorris.com/2013/12/small-things.jpg"><img src="https://willnorris.com/api/imageproxy/cx175,cw400,ch300,100x/https://willnorris.com/2013/12/small-things.jpg" alt="cx175,cw400,ch300,100x"></a>
|
||||
|
||||
Transformation also works on animated gifs. Here is [this source
|
||||
image][material-animation] resized to 200px square and rotated 270 degrees:
|
||||
|
||||
[material-animation]: https://willnorris.com/2015/05/material-animations.gif
|
||||
|
||||
<a href="https://willnorris.com/api/imageproxy/200,r270/https://willnorris.com/2015/05/material-animations.gif"><img src="https://willnorris.com/api/imageproxy/200,r270/https://willnorris.com/2015/05/material-animations.gif" alt="200,r270"></a>
|
||||
|
||||
The smart crop feature can best be seen by comparing the following images, with and without smart crop.
|
||||
|
||||
<a href="https://willnorris.com/api/imageproxy/150x300,sc/https://judahnorris.com/images/judah-sheets.jpg"><img src="https://willnorris.com/api/imageproxy/150x300,sc/https://judahnorris.com/images/judah-sheets.jpg" alt="200x400,sc"></a>
|
||||
<a href="https://willnorris.com/api/imageproxy/150x300/https://judahnorris.com/images/judah-sheets.jpg"><img src="https://willnorris.com/api/imageproxy/150x300/https://judahnorris.com/images/judah-sheets.jpg" alt="200x400"></a>
|
||||
|
||||
## Getting Started ##
|
||||
|
||||
Install the package using:
|
||||
|
||||
go get willnorris.com/go/imageproxy/cmd/imageproxy
|
||||
|
||||
Once installed, ensure `$GOPATH/bin` is in your `$PATH`, then run the proxy
|
||||
using:
|
||||
|
||||
imageproxy
|
||||
|
||||
This will start the proxy on port 8080, without any caching and with no allowed
|
||||
host list (meaning any remote URL can be proxied). Test this by navigating to
|
||||
<http://localhost:8080/500/https://octodex.github.com/images/codercat.jpg> and
|
||||
you should see a 500px square coder octocat.
|
||||
|
||||
### Cache ###
|
||||
|
||||
By default, the imageproxy command does not cache responses, but caching can be
|
||||
enabled using the `-cache` flag. It supports the following values:
|
||||
|
||||
- `memory` - uses an in-memory LRU cache. By default, this is limited to
|
||||
100mb. To customize the size of the cache or the max age for cached items,
|
||||
use the format `memory:size:age` where size is measured in mb and age is a
|
||||
duration. For example, `memory:200:4h` will create a 200mb cache that will
|
||||
cache items no longer than 4 hours.
|
||||
- directory on local disk (e.g. `/tmp/imageproxy`) - will cache images
|
||||
on disk
|
||||
- s3 URL (e.g. `s3://region/bucket-name/optional-path-prefix`) - will cache
|
||||
images on Amazon S3. This requires either an IAM role and instance profile
|
||||
with access to your your bucket or `AWS_ACCESS_KEY_ID` and `AWS_SECRET_KEY`
|
||||
environmental variables be set. (Additional methods of loading credentials
|
||||
are documented in the [aws-sdk-go session
|
||||
package](https://docs.aws.amazon.com/sdk-for-go/api/aws/session/)).
|
||||
- gcs URL (e.g. `gcs://bucket-name/optional-path-prefix`) - will cache images
|
||||
on Google Cloud Storage. Authentication is documented in Google's
|
||||
[Application Default Credentials
|
||||
docs](https://cloud.google.com/docs/authentication/production#providing_credentials_to_your_application).
|
||||
- azure URL (e.g. `azure://container-name/`) - will cache images on
|
||||
Azure Storage. This requires `AZURESTORAGE_ACCOUNT_NAME` and
|
||||
`AZURESTORAGE_ACCESS_KEY` environment variables to bet set.
|
||||
- redis URL (e.g. `redis://hostname/`) - will cache images on
|
||||
the specified redis host. The full URL syntax is defined by the [redis URI
|
||||
registration](https://www.iana.org/assignments/uri-schemes/prov/redis).
|
||||
Rather than specify password in the URI, use the `REDIS_PASSWORD`
|
||||
environment variable.
|
||||
|
||||
For example, to cache files on disk in the `/tmp/imageproxy` directory:
|
||||
|
||||
imageproxy -cache /tmp/imageproxy
|
||||
|
||||
Reload the [codercat URL][], and then inspect the contents of
|
||||
`/tmp/imageproxy`. Within the subdirectories, there should be two files, one
|
||||
for the original full-size codercat image, and one for the resized 500px
|
||||
version.
|
||||
|
||||
[codercat URL]: http://localhost:8080/500/https://octodex.github.com/images/codercat.jpg
|
||||
|
||||
If the `-cache` flag is specified multiple times, multiple caches will be
|
||||
created in a [tiered fashion][]. Typically this is used to put a smaller and
|
||||
faster in-memory cache in front of a larger but slower on-disk cache. For
|
||||
example, the following will first check an in-memory cache for an image,
|
||||
followed by a gcs bucket:
|
||||
|
||||
imageproxy -cache memory -cache gcs://my-bucket/
|
||||
|
||||
[tiered fashion]: https://godoc.org/github.com/die-net/lrucache/twotier
|
||||
|
||||
### Allowed Referrer List ###
|
||||
|
||||
You can limit images to only be accessible for certain hosts in the HTTP
|
||||
referrer header, which can help prevent others from hotlinking to images. It can
|
||||
be enabled by running:
|
||||
|
||||
imageproxy -referrers example.com
|
||||
|
||||
|
||||
Reload the [codercat URL][], and you should now get an error message. You can
|
||||
specify multiple hosts as a comma separated list, or prefix a host value with
|
||||
`*.` to allow all sub-domains as well.
|
||||
|
||||
### Allowed Hosts List ###
|
||||
|
||||
You can limit the remote hosts that the proxy will fetch images from using the
|
||||
`remoteHosts` flag. This is useful, for example, for locking the proxy down to
|
||||
your own hosts to prevent others from abusing it. Of course if you want to
|
||||
support fetching from any host, leave off the remoteHosts flag. Try it out by
|
||||
running:
|
||||
|
||||
imageproxy -remoteHosts example.com
|
||||
|
||||
Reload the [codercat URL][], and you should now get an error message. You can
|
||||
specify multiple hosts as a comma separated list, or prefix a host value with
|
||||
`*.` to allow all sub-domains as well.
|
||||
|
||||
### Allowed Content-Type List ###
|
||||
|
||||
You can limit what content types can be proxied by using the `contentTypes`
|
||||
flag. By default, this is set to `image/*`, meaning that imageproxy will
|
||||
process any image types. You can specify multiple content types as a comma
|
||||
separated list, and suffix values with `*` to perform a wildcard match. Set the
|
||||
flag to an empty string to proxy all requests, regardless of content type.
|
||||
|
||||
### Signed Requests ###
|
||||
|
||||
Instead of an allowed host list, you can require that requests be signed. This
|
||||
is useful in preventing abuse when you don't have just a static list of hosts
|
||||
you want to allow. Signatures are generated using HMAC-SHA256 against the
|
||||
remote URL, and url-safe base64 encoding the result:
|
||||
|
||||
base64urlencode(hmac.New(sha256, <key>).digest(<remote_url>))
|
||||
|
||||
The HMAC key is specified using the `signatureKey` flag. If this flag
|
||||
begins with an "@", the remainder of the value is interpreted as a file on disk
|
||||
which contains the HMAC key.
|
||||
|
||||
Try it out by running:
|
||||
|
||||
imageproxy -signatureKey "secret key"
|
||||
|
||||
Reload the [codercat URL][], and you should see an error message. Now load a
|
||||
[signed codercat URL][] and verify that it loads properly.
|
||||
|
||||
[signed codercat URL]: http://localhost:8080/500,sXyMwWKIC5JPCtlYOQ2f4yMBTqpjtUsfI67Sp7huXIYY=/https://octodex.github.com/images/codercat.jpg
|
||||
|
||||
Some simple code samples for generating signatures in various languages can be
|
||||
found in [URL Signing](https://github.com/willnorris/imageproxy/wiki/URL-signing).
|
||||
|
||||
If both a whiltelist and signatureKey are specified, requests can match either.
|
||||
In other words, requests that match one of the allowed hosts don't necessarily
|
||||
need to be signed, though they can be.
|
||||
|
||||
### Default Base URL ###
|
||||
|
||||
Typically, remote images to be proxied are specified as absolute URLs.
|
||||
However, if you commonly proxy images from a single source, you can provide a
|
||||
base URL and then specify remote images relative to that base. Try it out by
|
||||
running:
|
||||
|
||||
imageproxy -baseURL https://octodex.github.com/
|
||||
|
||||
Then load the codercat image, specified as a URL relative to that base:
|
||||
<http://localhost:8080/500/images/codercat.jpg>. Note that this is not an
|
||||
effective method to mask the true source of the images being proxied; it is
|
||||
trivial to discover the base URL being used. Even when a base URL is
|
||||
specified, you can always provide the absolute URL of the image to be proxied.
|
||||
|
||||
### Scaling beyond original size ###
|
||||
|
||||
By default, the imageproxy won't scale images beyond their original size.
|
||||
However, you can use the `scaleUp` command-line flag to allow this to happen:
|
||||
|
||||
imageproxy -scaleUp true
|
||||
|
||||
### WebP and TIFF support ###
|
||||
|
||||
Imageproxy can proxy remote webp images, but they will be served in either jpeg
|
||||
or png format (this is because the golang webp library only supports webp
|
||||
decoding) if any transformation is requested. If no format is specified,
|
||||
imageproxy will use jpeg by default. If no transformation is requested (for
|
||||
example, if you are just using imageproxy as an SSL proxy) then the original
|
||||
webp image will be served as-is without any format conversion.
|
||||
|
||||
Because so few browsers support tiff images, they will be converted to jpeg by
|
||||
default if any transformation is requested. To force encoding as tiff, pass the
|
||||
"tiff" option. Like webp, tiff images will be served as-is without any format
|
||||
conversion if no transformation is requested.
|
||||
|
||||
|
||||
Run `imageproxy -help` for a complete list of flags the command accepts. If
|
||||
you want to use a different caching implementation, it's probably easiest to
|
||||
just make a copy of `cmd/imageproxy/main.go` and customize it to fit your
|
||||
needs... it's a very simple command.
|
||||
|
||||
## Deploying ##
|
||||
|
||||
In most cases, you can follow the normal procedure for building a deploying any
|
||||
go application. For example, I build it directly on my production debian server
|
||||
using:
|
||||
|
||||
- `go build willnorris.com/go/imageproxy/cmd/imageproxy`
|
||||
- copy resulting binary to `/usr/local/bin`
|
||||
- copy [`etc/imageproxy.service`](etc/imageproxy.service) to
|
||||
`/lib/systemd/system` and enable using `systemctl`.
|
||||
|
||||
Instructions have been contributed below for running on other platforms, but I
|
||||
don't have much experience with them personally.
|
||||
|
||||
### Heroku ###
|
||||
|
||||
It's easy to vendorize the dependencies with `Godep` and deploy to Heroku. Take
|
||||
a look at [this GitHub repo](https://github.com/oreillymedia/prototype-imageproxy)
|
||||
|
||||
### Docker ###
|
||||
|
||||
A docker image is available at [`willnorris/imageproxy`](https://registry.hub.docker.com/u/willnorris/imageproxy/dockerfile/).
|
||||
|
||||
You can run it by
|
||||
```
|
||||
docker run -p 8080:8080 willnorris/imageproxy -addr 0.0.0.0:8080
|
||||
```
|
||||
|
||||
Or in your Dockerfile:
|
||||
|
||||
```
|
||||
ENTRYPOINT ["/go/bin/imageproxy", "-addr 0.0.0.0:8080"]
|
||||
```
|
||||
|
||||
### nginx ###
|
||||
|
||||
You can use follow config to prevent URL overwritting:
|
||||
|
||||
```
|
||||
location ~ ^/api/imageproxy/ {
|
||||
# pattern match to capture the original URL to prevent URL
|
||||
# canonicalization, which would strip double slashes
|
||||
if ($request_uri ~ "/api/imageproxy/(.+)") {
|
||||
set $path $1;
|
||||
rewrite .* /$path break;
|
||||
}
|
||||
proxy_pass http://localhost:8080;
|
||||
}
|
||||
```
|
||||
|
||||
## License ##
|
||||
|
||||
imageproxy is copyright Google, but is not an official Google product. It is
|
||||
available under the [Apache 2.0 License](./LICENSE).
|
||||
37
vendor/willnorris.com/go/imageproxy/cache.go
сгенерированный
поставляемый
Обычный файл
37
vendor/willnorris.com/go/imageproxy/cache.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,37 @@
|
||||
// Copyright 2013 Google Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package imageproxy
|
||||
|
||||
// The Cache interface defines a cache for storing arbitrary data. The
|
||||
// interface is designed to align with httpcache.Cache.
|
||||
type Cache interface {
|
||||
// Get retrieves the cached data for the provided key.
|
||||
Get(key string) (data []byte, ok bool)
|
||||
|
||||
// Set caches the provided data.
|
||||
Set(key string, data []byte)
|
||||
|
||||
// Delete deletes the cached data at the specified key.
|
||||
Delete(key string)
|
||||
}
|
||||
|
||||
// NopCache provides a no-op cache implementation that doesn't actually cache anything.
|
||||
var NopCache = new(nopCache)
|
||||
|
||||
type nopCache struct{}
|
||||
|
||||
func (c nopCache) Get(string) ([]byte, bool) { return nil, false }
|
||||
func (c nopCache) Set(string, []byte) {}
|
||||
func (c nopCache) Delete(string) {}
|
||||
378
vendor/willnorris.com/go/imageproxy/data.go
сгенерированный
поставляемый
Обычный файл
378
vendor/willnorris.com/go/imageproxy/data.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,378 @@
|
||||
// Copyright 2013 Google Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const (
|
||||
optFit = "fit"
|
||||
optFlipVertical = "fv"
|
||||
optFlipHorizontal = "fh"
|
||||
optFormatJPEG = "jpeg"
|
||||
optFormatPNG = "png"
|
||||
optFormatTIFF = "tiff"
|
||||
optRotatePrefix = "r"
|
||||
optQualityPrefix = "q"
|
||||
optSignaturePrefix = "s"
|
||||
optSizeDelimiter = "x"
|
||||
optScaleUp = "scaleUp"
|
||||
optCropX = "cx"
|
||||
optCropY = "cy"
|
||||
optCropWidth = "cw"
|
||||
optCropHeight = "ch"
|
||||
optSmartCrop = "sc"
|
||||
)
|
||||
|
||||
// URLError reports a malformed URL error.
|
||||
type URLError struct {
|
||||
Message string
|
||||
URL *url.URL
|
||||
}
|
||||
|
||||
func (e URLError) Error() string {
|
||||
return fmt.Sprintf("malformed URL %q: %s", e.URL, e.Message)
|
||||
}
|
||||
|
||||
// Options specifies transformations to be performed on the requested image.
|
||||
type Options struct {
|
||||
// See ParseOptions for interpretation of Width and Height values
|
||||
Width float64
|
||||
Height float64
|
||||
|
||||
// If true, resize the image to fit in the specified dimensions. Image
|
||||
// will not be cropped, and aspect ratio will be maintained.
|
||||
Fit bool
|
||||
|
||||
// Rotate image the specified degrees counter-clockwise. Valid values
|
||||
// are 90, 180, 270.
|
||||
Rotate int
|
||||
|
||||
FlipVertical bool
|
||||
FlipHorizontal bool
|
||||
|
||||
// Quality of output image
|
||||
Quality int
|
||||
|
||||
// HMAC Signature for signed requests.
|
||||
Signature string
|
||||
|
||||
// Allow image to scale beyond its original dimensions. This value
|
||||
// will always be overwritten by the value of Proxy.ScaleUp.
|
||||
ScaleUp bool
|
||||
|
||||
// Desired image format. Valid values are "jpeg", "png", "tiff".
|
||||
Format string
|
||||
|
||||
// Crop rectangle params
|
||||
CropX float64
|
||||
CropY float64
|
||||
CropWidth float64
|
||||
CropHeight float64
|
||||
|
||||
// Automatically find good crop points based on image content.
|
||||
SmartCrop bool
|
||||
}
|
||||
|
||||
func (o Options) String() string {
|
||||
opts := []string{fmt.Sprintf("%v%s%v", o.Width, optSizeDelimiter, o.Height)}
|
||||
if o.Fit {
|
||||
opts = append(opts, optFit)
|
||||
}
|
||||
if o.Rotate != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%d", string(optRotatePrefix), o.Rotate))
|
||||
}
|
||||
if o.FlipVertical {
|
||||
opts = append(opts, optFlipVertical)
|
||||
}
|
||||
if o.FlipHorizontal {
|
||||
opts = append(opts, optFlipHorizontal)
|
||||
}
|
||||
if o.Quality != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%d", string(optQualityPrefix), o.Quality))
|
||||
}
|
||||
if o.Signature != "" {
|
||||
opts = append(opts, fmt.Sprintf("%s%s", string(optSignaturePrefix), o.Signature))
|
||||
}
|
||||
if o.ScaleUp {
|
||||
opts = append(opts, optScaleUp)
|
||||
}
|
||||
if o.Format != "" {
|
||||
opts = append(opts, o.Format)
|
||||
}
|
||||
if o.CropX != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%v", string(optCropX), o.CropX))
|
||||
}
|
||||
if o.CropY != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%v", string(optCropY), o.CropY))
|
||||
}
|
||||
if o.CropWidth != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%v", string(optCropWidth), o.CropWidth))
|
||||
}
|
||||
if o.CropHeight != 0 {
|
||||
opts = append(opts, fmt.Sprintf("%s%v", string(optCropHeight), o.CropHeight))
|
||||
}
|
||||
if o.SmartCrop {
|
||||
opts = append(opts, optSmartCrop)
|
||||
}
|
||||
return strings.Join(opts, ",")
|
||||
}
|
||||
|
||||
// transform returns whether o includes transformation options. Some fields
|
||||
// are not transform related at all (like Signature), and others only apply in
|
||||
// the presence of other fields (like Fit). A non-empty Format value is
|
||||
// assumed to involve a transformation.
|
||||
func (o Options) transform() bool {
|
||||
return o.Width != 0 || o.Height != 0 || o.Rotate != 0 || o.FlipHorizontal || o.FlipVertical || o.Quality != 0 || o.Format != "" || o.CropX != 0 || o.CropY != 0 || o.CropWidth != 0 || o.CropHeight != 0
|
||||
}
|
||||
|
||||
// ParseOptions parses str as a list of comma separated transformation options.
|
||||
// The options can be specified in in order, with duplicate options overwriting
|
||||
// previous values.
|
||||
//
|
||||
// Rectangle Crop
|
||||
//
|
||||
// There are four options controlling rectangle crop:
|
||||
//
|
||||
// cx{x} - X coordinate of top left rectangle corner (default: 0)
|
||||
// cy{y} - Y coordinate of top left rectangle corner (default: 0)
|
||||
// cw{width} - rectangle width (default: image width)
|
||||
// ch{height} - rectangle height (default: image height)
|
||||
//
|
||||
// For all options, integer values are interpreted as exact pixel values and
|
||||
// floats between 0 and 1 are interpreted as percentages of the original image
|
||||
// size. Negative values for cx and cy are measured from the right and bottom
|
||||
// edges of the image, respectively.
|
||||
//
|
||||
// If the crop width or height exceed the width or height of the image, the
|
||||
// crop width or height will be adjusted, preserving the specified cx and cy
|
||||
// values. Rectangular crop is applied before any other transformations.
|
||||
//
|
||||
// Smart Crop
|
||||
//
|
||||
// The "sc" option will perform a content-aware smart crop to fit the
|
||||
// requested image width and height dimensions (see Size and Cropping below).
|
||||
// The smart crop option will override any requested rectangular crop.
|
||||
//
|
||||
// Size and Cropping
|
||||
//
|
||||
// The size option takes the general form "{width}x{height}", where width and
|
||||
// height are numbers. Integer values greater than 1 are interpreted as exact
|
||||
// pixel values. Floats between 0 and 1 are interpreted as percentages of the
|
||||
// original image size. If either value is omitted or set to 0, it will be
|
||||
// automatically set to preserve the aspect ratio based on the other dimension.
|
||||
// If a single number is provided (with no "x" separator), it will be used for
|
||||
// both height and width.
|
||||
//
|
||||
// Depending on the size options specified, an image may be cropped to fit the
|
||||
// requested size. In all cases, the original aspect ratio of the image will be
|
||||
// preserved; imageproxy will never stretch the original image.
|
||||
//
|
||||
// When no explicit crop mode is specified, the following rules are followed:
|
||||
//
|
||||
// - If both width and height values are specified, the image will be scaled to
|
||||
// fill the space, cropping if necessary to fit the exact dimension.
|
||||
//
|
||||
// - If only one of the width or height values is specified, the image will be
|
||||
// resized to fit the specified dimension, scaling the other dimension as
|
||||
// needed to maintain the aspect ratio.
|
||||
//
|
||||
// If the "fit" option is specified together with a width and height value, the
|
||||
// image will be resized to fit within a containing box of the specified size.
|
||||
// As always, the original aspect ratio will be preserved. Specifying the "fit"
|
||||
// option with only one of either width or height does the same thing as if
|
||||
// "fit" had not been specified.
|
||||
//
|
||||
// Rotation and Flips
|
||||
//
|
||||
// The "r{degrees}" option will rotate the image the specified number of
|
||||
// degrees, counter-clockwise. Valid degrees values are 90, 180, and 270.
|
||||
//
|
||||
// The "fv" option will flip the image vertically. The "fh" option will flip
|
||||
// the image horizontally. Images are flipped after being rotated.
|
||||
//
|
||||
// Quality
|
||||
//
|
||||
// The "q{qualityPercentage}" option can be used to specify the quality of the
|
||||
// output file (JPEG only). If not specified, the default value of "95" is used.
|
||||
//
|
||||
// Format
|
||||
//
|
||||
// The "jpeg", "png", and "tiff" options can be used to specify the desired
|
||||
// image format of the proxied image.
|
||||
//
|
||||
// Signature
|
||||
//
|
||||
// The "s{signature}" option specifies an optional base64 encoded HMAC used to
|
||||
// sign the remote URL in the request. The HMAC key used to verify signatures is
|
||||
// provided to the imageproxy server on startup.
|
||||
//
|
||||
// See https://github.com/willnorris/imageproxy/wiki/URL-signing
|
||||
// for examples of generating signatures.
|
||||
//
|
||||
// Examples
|
||||
//
|
||||
// 0x0 - no resizing
|
||||
// 200x - 200 pixels wide, proportional height
|
||||
// x0.15 - 15% original height, proportional width
|
||||
// 100x150 - 100 by 150 pixels, cropping as needed
|
||||
// 100 - 100 pixels square, cropping as needed
|
||||
// 150,fit - scale to fit 150 pixels square, no cropping
|
||||
// 100,r90 - 100 pixels square, rotated 90 degrees
|
||||
// 100,fv,fh - 100 pixels square, flipped horizontal and vertical
|
||||
// 200x,q60 - 200 pixels wide, proportional height, 60% quality
|
||||
// 200x,png - 200 pixels wide, converted to PNG format
|
||||
// cw100,ch100 - crop image to 100px square, starting at (0,0)
|
||||
// cx10,cy20,cw100,ch200 - crop image starting at (10,20) is 100px wide and 200px tall
|
||||
func ParseOptions(str string) Options {
|
||||
var options Options
|
||||
|
||||
for _, opt := range strings.Split(str, ",") {
|
||||
switch {
|
||||
case len(opt) == 0:
|
||||
break
|
||||
case opt == optFit:
|
||||
options.Fit = true
|
||||
case opt == optFlipVertical:
|
||||
options.FlipVertical = true
|
||||
case opt == optFlipHorizontal:
|
||||
options.FlipHorizontal = true
|
||||
case opt == optScaleUp: // this option is intentionally not documented above
|
||||
options.ScaleUp = true
|
||||
case opt == optFormatJPEG, opt == optFormatPNG, opt == optFormatTIFF:
|
||||
options.Format = opt
|
||||
case opt == optSmartCrop:
|
||||
options.SmartCrop = true
|
||||
case strings.HasPrefix(opt, optRotatePrefix):
|
||||
value := strings.TrimPrefix(opt, optRotatePrefix)
|
||||
options.Rotate, _ = strconv.Atoi(value)
|
||||
case strings.HasPrefix(opt, optQualityPrefix):
|
||||
value := strings.TrimPrefix(opt, optQualityPrefix)
|
||||
options.Quality, _ = strconv.Atoi(value)
|
||||
case strings.HasPrefix(opt, optSignaturePrefix):
|
||||
options.Signature = strings.TrimPrefix(opt, optSignaturePrefix)
|
||||
case strings.HasPrefix(opt, optCropX):
|
||||
value := strings.TrimPrefix(opt, optCropX)
|
||||
options.CropX, _ = strconv.ParseFloat(value, 64)
|
||||
case strings.HasPrefix(opt, optCropY):
|
||||
value := strings.TrimPrefix(opt, optCropY)
|
||||
options.CropY, _ = strconv.ParseFloat(value, 64)
|
||||
case strings.HasPrefix(opt, optCropWidth):
|
||||
value := strings.TrimPrefix(opt, optCropWidth)
|
||||
options.CropWidth, _ = strconv.ParseFloat(value, 64)
|
||||
case strings.HasPrefix(opt, optCropHeight):
|
||||
value := strings.TrimPrefix(opt, optCropHeight)
|
||||
options.CropHeight, _ = strconv.ParseFloat(value, 64)
|
||||
case strings.Contains(opt, optSizeDelimiter):
|
||||
size := strings.SplitN(opt, optSizeDelimiter, 2)
|
||||
if w := size[0]; w != "" {
|
||||
options.Width, _ = strconv.ParseFloat(w, 64)
|
||||
}
|
||||
if h := size[1]; h != "" {
|
||||
options.Height, _ = strconv.ParseFloat(h, 64)
|
||||
}
|
||||
default:
|
||||
if size, err := strconv.ParseFloat(opt, 64); err == nil {
|
||||
options.Width = size
|
||||
options.Height = size
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return options
|
||||
}
|
||||
|
||||
// Request is an imageproxy request which includes a remote URL of an image to
|
||||
// proxy, and an optional set of transformations to perform.
|
||||
type Request struct {
|
||||
URL *url.URL // URL of the image to proxy
|
||||
Options Options // Image transformation to perform
|
||||
Original *http.Request // The original HTTP request
|
||||
}
|
||||
|
||||
// String returns the request URL as a string, with r.Options encoded in the
|
||||
// URL fragment.
|
||||
func (r Request) String() string {
|
||||
u := *r.URL
|
||||
u.Fragment = r.Options.String()
|
||||
return u.String()
|
||||
}
|
||||
|
||||
// NewRequest parses an http.Request into an imageproxy Request. Options and
|
||||
// the remote image URL are specified in the request path, formatted as:
|
||||
// /{options}/{remote_url}. Options may be omitted, so a request path may
|
||||
// simply contain /{remote_url}. The remote URL must be an absolute "http" or
|
||||
// "https" URL, should not be URL encoded, and may contain a query string.
|
||||
//
|
||||
// Assuming an imageproxy server running on localhost, the following are all
|
||||
// valid imageproxy requests:
|
||||
//
|
||||
// http://localhost/100x200/http://example.com/image.jpg
|
||||
// http://localhost/100x200,r90/http://example.com/image.jpg?foo=bar
|
||||
// http://localhost//http://example.com/image.jpg
|
||||
// http://localhost/http://example.com/image.jpg
|
||||
func NewRequest(r *http.Request, baseURL *url.URL) (*Request, error) {
|
||||
var err error
|
||||
req := &Request{Original: r}
|
||||
|
||||
path := r.URL.EscapedPath()[1:] // strip leading slash
|
||||
req.URL, err = parseURL(path)
|
||||
if err != nil || !req.URL.IsAbs() {
|
||||
// first segment should be options
|
||||
parts := strings.SplitN(path, "/", 2)
|
||||
if len(parts) != 2 {
|
||||
return nil, URLError{"too few path segments", r.URL}
|
||||
}
|
||||
|
||||
var err error
|
||||
req.URL, err = parseURL(parts[1])
|
||||
if err != nil {
|
||||
return nil, URLError{fmt.Sprintf("unable to parse remote URL: %v", err), r.URL}
|
||||
}
|
||||
|
||||
req.Options = ParseOptions(parts[0])
|
||||
}
|
||||
|
||||
if baseURL != nil {
|
||||
req.URL = baseURL.ResolveReference(req.URL)
|
||||
}
|
||||
|
||||
if !req.URL.IsAbs() {
|
||||
return nil, URLError{"must provide absolute remote URL", r.URL}
|
||||
}
|
||||
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return nil, URLError{"remote URL must have http or https scheme", r.URL}
|
||||
}
|
||||
|
||||
// query string is always part of the remote URL
|
||||
req.URL.RawQuery = r.URL.RawQuery
|
||||
return req, nil
|
||||
}
|
||||
|
||||
var reCleanedURL = regexp.MustCompile(`^(https?):/+([^/])`)
|
||||
|
||||
// parseURL parses s as a URL, handling URLs that have been munged by
|
||||
// path.Clean or a webserver that collapses multiple slashes.
|
||||
func parseURL(s string) (*url.URL, error) {
|
||||
s = reCleanedURL.ReplaceAllString(s, "$1://$2")
|
||||
return url.Parse(s)
|
||||
}
|
||||
46
vendor/willnorris.com/go/imageproxy/go.mod
сгенерированный
поставляемый
Обычный файл
46
vendor/willnorris.com/go/imageproxy/go.mod
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,46 @@
|
||||
module willnorris.com/go/imageproxy
|
||||
|
||||
require (
|
||||
cloud.google.com/go v0.0.0-20180131234750-2de512d2700d
|
||||
github.com/Azure/azure-sdk-for-go v12.3.0-beta+incompatible // indirect
|
||||
github.com/Azure/go-autorest v9.9.0+incompatible // indirect
|
||||
github.com/PaulARoy/azurestoragecache v0.0.0-20170906084534-3c249a3ba788
|
||||
github.com/aws/aws-sdk-go v1.15.35
|
||||
github.com/davecgh/go-spew v1.1.1 // indirect
|
||||
github.com/dgrijalva/jwt-go v3.1.0+incompatible // indirect
|
||||
github.com/die-net/lrucache v0.0.0-20171111232917-04b9315ab7a6
|
||||
github.com/disintegration/imaging v1.3.0
|
||||
github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2 // indirect
|
||||
github.com/garyburd/redigo v1.5.0
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b // indirect
|
||||
github.com/golang/protobuf v1.0.0 // indirect
|
||||
github.com/google/btree v0.0.0-20180124185431-e89373fe6b4a // indirect
|
||||
github.com/google/go-cmp v0.2.0 // indirect
|
||||
github.com/googleapis/gax-go v2.0.0+incompatible // indirect
|
||||
github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c // indirect
|
||||
github.com/gregjones/httpcache v0.0.0-20171119193500-2bcd89a1743f
|
||||
github.com/jtolds/gls v4.2.1+incompatible // indirect
|
||||
github.com/kr/pretty v0.1.0 // indirect
|
||||
github.com/marstr/guid v0.0.0-20170427235115-8bdf7d1a087c // indirect
|
||||
github.com/muesli/smartcrop v0.0.0-20171215203440-9032446b30f6
|
||||
github.com/nfnt/resize v0.0.0-20160724205520-891127d8d1b5 // indirect
|
||||
github.com/peterbourgon/diskv v0.0.0-20171120014656-2973218375c3
|
||||
github.com/pmezard/go-difflib v1.0.0 // indirect
|
||||
github.com/rwcarlsen/goexif v0.0.0-20141222211634-41dad3aa0833
|
||||
github.com/satori/go.uuid v0.0.0-20180103174451-36e9d2ebbde5 // indirect
|
||||
github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf // indirect
|
||||
github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a // indirect
|
||||
github.com/stretchr/testify v1.2.2 // indirect
|
||||
golang.org/x/image v0.0.0-20171214225156-12117c17ca67
|
||||
golang.org/x/net v0.0.0-20180201232540-b417086c80e9 // indirect
|
||||
golang.org/x/oauth2 v0.0.0-20180126164932-a032972e2806 // indirect
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f // indirect
|
||||
golang.org/x/text v0.0.0-20171227012246-e19ae1496984 // indirect
|
||||
google.golang.org/api v0.0.0-20180202000329-f7618f4b41ca // indirect
|
||||
google.golang.org/appengine v0.0.0-20171212223047-5bee14b453b4 // indirect
|
||||
google.golang.org/genproto v0.0.0-20180125080656-4eb30f4778ee // indirect
|
||||
google.golang.org/grpc v0.0.0-20180201193814-f9628db66d14 // indirect
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
|
||||
gopkg.in/yaml.v2 v2.2.1 // indirect
|
||||
willnorris.com/go/gifresize v1.0.0
|
||||
)
|
||||
92
vendor/willnorris.com/go/imageproxy/go.sum
сгенерированный
поставляемый
Обычный файл
92
vendor/willnorris.com/go/imageproxy/go.sum
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,92 @@
|
||||
cloud.google.com/go v0.0.0-20180131234750-2de512d2700d h1:Wj6Dk68uwFxqLKT1lV03UFLcfh5+HTLs+YCGlUc06M8=
|
||||
cloud.google.com/go v0.0.0-20180131234750-2de512d2700d/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw=
|
||||
github.com/Azure/azure-sdk-for-go v12.3.0-beta+incompatible h1:rrdWQEPInXBEqI10Nfu7FCp7BDdLSLWvkHwDWiXOEjw=
|
||||
github.com/Azure/azure-sdk-for-go v12.3.0-beta+incompatible/go.mod h1:9XXNKU+eRnpl9moKnB4QOLf1HestfXbmab5FXxiDBjc=
|
||||
github.com/Azure/go-autorest v9.9.0+incompatible h1:U3u8yuM3dZPg6vjJ/Hl2hQlaP+WNOeSHY6Fk4g1e6Ps=
|
||||
github.com/Azure/go-autorest v9.9.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
|
||||
github.com/PaulARoy/azurestoragecache v0.0.0-20170906084534-3c249a3ba788 h1:OxWBmk9BZqWOHVs+hrElt/BiexDGcStcsADt0f4cUx8=
|
||||
github.com/PaulARoy/azurestoragecache v0.0.0-20170906084534-3c249a3ba788/go.mod h1:lY1dZd8HBzJ10eqKERHn3CU59tfhzcAVb2c0ZhIWSOk=
|
||||
github.com/aws/aws-sdk-go v1.15.35 h1:roOTR0eOeCgYwrz3NXmrneLFBYdnK8epLedaRMm1kQg=
|
||||
github.com/aws/aws-sdk-go v1.15.35/go.mod h1:mFuSZ37Z9YOHbQEwBWztmVzqXrEkub65tZoCYDt7FT0=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/dgrijalva/jwt-go v3.1.0+incompatible h1:FFziAwDQQ2dz1XClWMkwvukur3evtZx7x/wMHKM1i20=
|
||||
github.com/dgrijalva/jwt-go v3.1.0+incompatible/go.mod h1:E3ru+11k8xSBh+hMPgOLZmtrrCbhqsmaPHjLKYnJCaQ=
|
||||
github.com/die-net/lrucache v0.0.0-20171111232917-04b9315ab7a6 h1:UhONZXj9L+pdHs+qUEPMsQkG3BdhMHSCQk8KXRm83ho=
|
||||
github.com/die-net/lrucache v0.0.0-20171111232917-04b9315ab7a6/go.mod h1:ew0MSjCVDdtGMjF3kzLK9hwdgF5mOE8SbYVF3Rc7mkU=
|
||||
github.com/disintegration/imaging v1.3.0 h1:AihaBC+K3RHP7JL8scqq2GgNQhVzMcCYh7gJbAjAvpo=
|
||||
github.com/disintegration/imaging v1.3.0/go.mod h1:9B/deIUIrliYkyMTuXJd6OUFLcrZ2tf+3Qlwnaf/CjU=
|
||||
github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2 h1:G9/PqfhOrt8JXnw0DGTfVoOkKHDhOlEZqhE/cu+NvQM=
|
||||
github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E=
|
||||
github.com/garyburd/redigo v1.5.0 h1:OcZhiwwjKtBe7TO4TlXpj/1E3I2RVg1uLxwMT4VFF5w=
|
||||
github.com/garyburd/redigo v1.5.0/go.mod h1:NR3MbYisc3/PwhQ00EMzDiPmrwpPxAn5GI05/YaO1SY=
|
||||
github.com/go-ini/ini v1.25.4 h1:Mujh4R/dH6YL8bxuISne3xX2+qcQ9p0IxKAP6ExWoUo=
|
||||
github.com/go-ini/ini v1.25.4/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58=
|
||||
github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q=
|
||||
github.com/golang/protobuf v1.0.0 h1:lsek0oXi8iFE9L+EXARyHIjU5rlWIhhTkjDz3vHhWWQ=
|
||||
github.com/golang/protobuf v1.0.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
|
||||
github.com/google/btree v0.0.0-20180124185431-e89373fe6b4a h1:ZJu5NB1Bk5ms4vw0Xu4i+jD32SE9jQXyfnOvwhHqlT0=
|
||||
github.com/google/btree v0.0.0-20180124185431-e89373fe6b4a/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ=
|
||||
github.com/google/go-cmp v0.2.0 h1:+dTQ8DZQJz0Mb/HjFlkptS1FeQ4cWSnN941F8aEG4SQ=
|
||||
github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M=
|
||||
github.com/googleapis/gax-go v2.0.0+incompatible h1:j0GKcs05QVmm7yesiZq2+9cxHkNK9YM6zKx4D2qucQU=
|
||||
github.com/googleapis/gax-go v2.0.0+incompatible/go.mod h1:SFVmujtThgffbyetf+mdk2eWhX2bMyUtNHzFKcPA9HY=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c h1:16eHWuMGvCjSfgRJKqIzapE78onvvTbdi1rMkU00lZw=
|
||||
github.com/gopherjs/gopherjs v0.0.0-20180825215210-0210a2f0f73c/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
|
||||
github.com/gregjones/httpcache v0.0.0-20171119193500-2bcd89a1743f h1:kOkUP6rcVVqC+KlKKENKtgfFfJyDySYhqL9srXooghY=
|
||||
github.com/gregjones/httpcache v0.0.0-20171119193500-2bcd89a1743f/go.mod h1:FecbI9+v66THATjSRHfNgh1IVFe/9kFxbXtjV0ctIMA=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8 h1:12VvqtR6Aowv3l/EQUlocDHW2Cp4G9WJVH7uyH8QFJE=
|
||||
github.com/jmespath/go-jmespath v0.0.0-20160202185014-0b12d6b521d8/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k=
|
||||
github.com/jtolds/gls v4.2.1+incompatible h1:fSuqC+Gmlu6l/ZYAoZzx2pyucC8Xza35fpRVWLVmUEE=
|
||||
github.com/jtolds/gls v4.2.1+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
|
||||
github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI=
|
||||
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
|
||||
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
|
||||
github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE=
|
||||
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
|
||||
github.com/marstr/guid v0.0.0-20170427235115-8bdf7d1a087c h1:N7uWGS2fTwH/4BwxbHiJZNAFTSJ5yPU0emHsQWvkxEY=
|
||||
github.com/marstr/guid v0.0.0-20170427235115-8bdf7d1a087c/go.mod h1:74gB1z2wpxxInTG6yaqA7KrtM0NZ+RbrcqDvYHefzho=
|
||||
github.com/muesli/smartcrop v0.0.0-20171215203440-9032446b30f6 h1:m5kCp2hHRMu7z95f+aIK80l8N1tx+UXAqNoYpRS9v3o=
|
||||
github.com/muesli/smartcrop v0.0.0-20171215203440-9032446b30f6/go.mod h1:i2fCI/UorTfgEpPPLWiFBv4pye+YAG78RwcQLUkocpI=
|
||||
github.com/nfnt/resize v0.0.0-20160724205520-891127d8d1b5 h1:BvoENQQU+fZ9uukda/RzCAL/191HHwJA5b13R6diVlY=
|
||||
github.com/nfnt/resize v0.0.0-20160724205520-891127d8d1b5/go.mod h1:jpp1/29i3P1S/RLdc7JQKbRpFeM1dOBd8T9ki5s+AY8=
|
||||
github.com/peterbourgon/diskv v0.0.0-20171120014656-2973218375c3 h1:ZKRE3mqKoxObHs5oWjLnA1WxXhmlDDAVuE0VsuLIoNk=
|
||||
github.com/peterbourgon/diskv v0.0.0-20171120014656-2973218375c3/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20141222211634-41dad3aa0833 h1:jwa1bSL1nx8Yz7pOXkjXJCbKAffj5i2Rrl9ALRqSy6Y=
|
||||
github.com/rwcarlsen/goexif v0.0.0-20141222211634-41dad3aa0833/go.mod h1:hPqNNc0+uJM6H+SuU8sEs5K5IQeKccPqeSjfgcKGgPk=
|
||||
github.com/satori/go.uuid v0.0.0-20180103174451-36e9d2ebbde5 h1:tfcGHuraNSEY9xRb9ckCMqMD7xAjzrYI1WpD7DA+nz8=
|
||||
github.com/satori/go.uuid v0.0.0-20180103174451-36e9d2ebbde5/go.mod h1:dA0hQrYB0VpLJoorglMZABFdXlWrHn1NEOzdhQKdks0=
|
||||
github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf h1:6V1qxN6Usn4jy8unvggSJz/NC790tefw8Zdy6OZS5co=
|
||||
github.com/smartystreets/assertions v0.0.0-20180820201707-7c9eb446e3cf/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
|
||||
github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a h1:JSvGDIbmil4Ui/dDdFBExb7/cmkNjyX5F97oglmvCDo=
|
||||
github.com/smartystreets/goconvey v0.0.0-20180222194500-ef6db91d284a/go.mod h1:XDJAKZRPZ1CvBcN2aX5YOUTYGHki24fSF0Iv48Ibg0s=
|
||||
github.com/stretchr/testify v1.2.2 h1:bSDNvY7ZPG5RlJ8otE/7V6gMiyenm9RtJ7IUVIAoJ1w=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
golang.org/x/image v0.0.0-20171214225156-12117c17ca67 h1:L8S612DBEq9tpLTxczHuhrf5il+KEdSha8b5A5njQMc=
|
||||
golang.org/x/image v0.0.0-20171214225156-12117c17ca67/go.mod h1:ux5Hcp/YLpHSI86hEcLt0YII63i6oz57MZXIpbrjZUs=
|
||||
golang.org/x/net v0.0.0-20180201232540-b417086c80e9 h1:2srMuQrhUnBbRCQTYMFbAtec0kzANvdPwGdfLIXUodw=
|
||||
golang.org/x/net v0.0.0-20180201232540-b417086c80e9/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/oauth2 v0.0.0-20180126164932-a032972e2806 h1:KZrxuLRRjPt8IU4XrMl45WQaER+p8WGu9cN8EekYVzM=
|
||||
golang.org/x/oauth2 v0.0.0-20180126164932-a032972e2806/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/text v0.0.0-20171227012246-e19ae1496984 h1:ulYJn/BqO4fMRe1xAQzWjokgjsQLPpb21GltxXHI3fQ=
|
||||
golang.org/x/text v0.0.0-20171227012246-e19ae1496984/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
||||
google.golang.org/api v0.0.0-20180202000329-f7618f4b41ca h1:bPw62MiF+sPyq2Apz3MT+qTY+hEgfVEUfkO4dVCK5oo=
|
||||
google.golang.org/api v0.0.0-20180202000329-f7618f4b41ca/go.mod h1:4mhQ8q/RsB7i+udVvVy5NUi08OU8ZlA0gRVgrF7VFY0=
|
||||
google.golang.org/appengine v0.0.0-20171212223047-5bee14b453b4 h1:gggB/NnRSjJj9dpMAaxm4mMTFai1QLGL39CGXmQvr+s=
|
||||
google.golang.org/appengine v0.0.0-20171212223047-5bee14b453b4/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM=
|
||||
google.golang.org/genproto v0.0.0-20180125080656-4eb30f4778ee h1:z84t4XBifcyxT9HA96QiKwGaWYiO7vfoqu7vWoa6lQk=
|
||||
google.golang.org/genproto v0.0.0-20180125080656-4eb30f4778ee/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc=
|
||||
google.golang.org/grpc v0.0.0-20180201193814-f9628db66d14 h1:y8LqgDoOxiN/KHkwtrvzgzZtDvk5EAQCGBeWgpRUt1Q=
|
||||
google.golang.org/grpc v0.0.0-20180201193814-f9628db66d14/go.mod h1:yo6s7OP7yaDglbqo1J04qKzAhqBH6lvTonzMVmEdcZw=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY=
|
||||
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v2 v2.2.1 h1:mUhvW9EsL+naU5Q3cakzfE91YhliOondGd6ZrsDBHQE=
|
||||
gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
willnorris.com/go/gifresize v1.0.0 h1:KkdTSrFE1mhzAgTO8/ukK6ZP4SVptL4G3d1lx5X5qMw=
|
||||
willnorris.com/go/gifresize v1.0.0/go.mod h1:eBM8gogBGCcaH603vxSpnfjwXIpq6nmnj/jauBDKtAk=
|
||||
387
vendor/willnorris.com/go/imageproxy/imageproxy.go
сгенерированный
поставляемый
Обычный файл
387
vendor/willnorris.com/go/imageproxy/imageproxy.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,387 @@
|
||||
// Copyright 2013 Google Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
// Package imageproxy provides an image proxy server. For typical use of
|
||||
// creating and using a Proxy, see cmd/imageproxy/main.go.
|
||||
package imageproxy // import "willnorris.com/go/imageproxy"
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gregjones/httpcache"
|
||||
tphttp "willnorris.com/go/imageproxy/third_party/http"
|
||||
)
|
||||
|
||||
// Proxy serves image requests.
|
||||
type Proxy struct {
|
||||
Client *http.Client // client used to fetch remote URLs
|
||||
Cache Cache // cache used to cache responses
|
||||
|
||||
// RemoteHosts specifies a list of remote hosts that images can be
|
||||
// proxied from. An empty list means all hosts are allowed.
|
||||
RemoteHosts []string
|
||||
|
||||
// Whitelist should no longer be used. Use "RemoteHosts" instead.
|
||||
Whitelist []string
|
||||
|
||||
// Referrers, when given, requires that requests to the image
|
||||
// proxy come from a referring host. An empty list means all
|
||||
// hosts are allowed.
|
||||
Referrers []string
|
||||
|
||||
// DefaultBaseURL is the URL that relative remote URLs are resolved in
|
||||
// reference to. If nil, all remote URLs specified in requests must be
|
||||
// absolute.
|
||||
DefaultBaseURL *url.URL
|
||||
|
||||
// SignatureKey is the HMAC key used to verify signed requests.
|
||||
SignatureKey []byte
|
||||
|
||||
// Allow images to scale beyond their original dimensions.
|
||||
ScaleUp bool
|
||||
|
||||
// Timeout specifies a time limit for requests served by this Proxy.
|
||||
// If a call runs for longer than its time limit, a 504 Gateway Timeout
|
||||
// response is returned. A Timeout of zero means no timeout.
|
||||
Timeout time.Duration
|
||||
|
||||
// If true, log additional debug messages
|
||||
Verbose bool
|
||||
|
||||
// ContentTypes specifies a list of content types to allow. An empty
|
||||
// list means all content types are allowed.
|
||||
ContentTypes []string
|
||||
}
|
||||
|
||||
// NewProxy constructs a new proxy. The provided http RoundTripper will be
|
||||
// used to fetch remote URLs. If nil is provided, http.DefaultTransport will
|
||||
// be used.
|
||||
func NewProxy(transport http.RoundTripper, cache Cache) *Proxy {
|
||||
if transport == nil {
|
||||
transport = http.DefaultTransport
|
||||
}
|
||||
if cache == nil {
|
||||
cache = NopCache
|
||||
}
|
||||
|
||||
proxy := &Proxy{
|
||||
Cache: cache,
|
||||
}
|
||||
|
||||
client := new(http.Client)
|
||||
client.Transport = &httpcache.Transport{
|
||||
Transport: &TransformingTransport{
|
||||
Transport: transport,
|
||||
CachingClient: client,
|
||||
log: func(format string, v ...interface{}) {
|
||||
if proxy.Verbose {
|
||||
log.Printf(format, v...)
|
||||
}
|
||||
},
|
||||
},
|
||||
Cache: cache,
|
||||
MarkCachedResponses: true,
|
||||
}
|
||||
|
||||
proxy.Client = client
|
||||
|
||||
return proxy
|
||||
}
|
||||
|
||||
// ServeHTTP handles incoming requests.
|
||||
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/favicon.ico" {
|
||||
return // ignore favicon requests
|
||||
}
|
||||
|
||||
if r.URL.Path == "/" || r.URL.Path == "/health-check" {
|
||||
fmt.Fprint(w, "OK")
|
||||
return
|
||||
}
|
||||
|
||||
var h http.Handler = http.HandlerFunc(p.serveImage)
|
||||
if p.Timeout > 0 {
|
||||
h = tphttp.TimeoutHandler(h, p.Timeout, "Gateway timeout waiting for remote resource.")
|
||||
}
|
||||
h.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// serveImage handles incoming requests for proxied images.
|
||||
func (p *Proxy) serveImage(w http.ResponseWriter, r *http.Request) {
|
||||
req, err := NewRequest(r, p.DefaultBaseURL)
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("invalid request URL: %v", err)
|
||||
log.Print(msg)
|
||||
http.Error(w, msg, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// assign static settings from proxy to req.Options
|
||||
req.Options.ScaleUp = p.ScaleUp
|
||||
|
||||
if err := p.allowed(req); err != nil {
|
||||
log.Print(err)
|
||||
http.Error(w, err.Error(), http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := p.Client.Get(req.String())
|
||||
if err != nil {
|
||||
msg := fmt.Sprintf("error fetching remote image: %v", err)
|
||||
log.Print(msg)
|
||||
http.Error(w, msg, http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
|
||||
cached := resp.Header.Get(httpcache.XFromCache)
|
||||
if p.Verbose {
|
||||
log.Printf("request: %v (served from cache: %v)", *req, cached == "1")
|
||||
}
|
||||
|
||||
copyHeader(w.Header(), resp.Header, "Cache-Control", "Last-Modified", "Expires", "Etag", "Link")
|
||||
|
||||
if should304(r, resp) {
|
||||
w.WriteHeader(http.StatusNotModified)
|
||||
return
|
||||
}
|
||||
|
||||
contentType, _, _ := mime.ParseMediaType(resp.Header.Get("Content-Type"))
|
||||
if resp.ContentLength != 0 && !validContentType(p.ContentTypes, contentType) {
|
||||
msg := fmt.Sprintf("forbidden content-type: %q", contentType)
|
||||
log.Print(msg)
|
||||
http.Error(w, msg, http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
|
||||
copyHeader(w.Header(), resp.Header, "Content-Length")
|
||||
|
||||
//Enable CORS for 3rd party applications
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
|
||||
w.WriteHeader(resp.StatusCode)
|
||||
io.Copy(w, resp.Body)
|
||||
}
|
||||
|
||||
// copyHeader copies header values from src to dst, adding to any existing
|
||||
// values with the same header name. If keys is not empty, only those header
|
||||
// keys will be copied.
|
||||
func copyHeader(dst, src http.Header, keys ...string) {
|
||||
if len(keys) == 0 {
|
||||
for k, _ := range src {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
for _, key := range keys {
|
||||
k := http.CanonicalHeaderKey(key)
|
||||
for _, v := range src[k] {
|
||||
dst.Add(k, v)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// allowed determines whether the specified request contains an allowed
|
||||
// referrer, host, and signature. It returns an error if the request is not
|
||||
// allowed.
|
||||
func (p *Proxy) allowed(r *Request) error {
|
||||
if p.RemoteHosts == nil {
|
||||
// backwards compatible with old naming of the field
|
||||
p.RemoteHosts = p.Whitelist
|
||||
}
|
||||
if len(p.Referrers) > 0 && !validReferrer(p.Referrers, r.Original) {
|
||||
return fmt.Errorf("request does not contain an allowed referrer: %v", r)
|
||||
}
|
||||
|
||||
if len(p.RemoteHosts) == 0 && len(p.SignatureKey) == 0 {
|
||||
return nil // no allowed hosts or signature key, all requests accepted
|
||||
}
|
||||
|
||||
if len(p.RemoteHosts) > 0 && validHost(p.RemoteHosts, r.URL) {
|
||||
return nil
|
||||
}
|
||||
|
||||
if len(p.SignatureKey) > 0 && validSignature(p.SignatureKey, r) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("request does not contain an allowed host or valid signature: %v", r)
|
||||
}
|
||||
|
||||
// validContentType returns whether contentType matches one of the allowed patterns.
|
||||
func validContentType(patterns []string, contentType string) bool {
|
||||
if len(patterns) == 0 {
|
||||
return true
|
||||
}
|
||||
|
||||
for _, pattern := range patterns {
|
||||
if ok, err := filepath.Match(pattern, contentType); ok && err == nil {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// validHost returns whether the host in u matches one of hosts.
|
||||
func validHost(hosts []string, u *url.URL) bool {
|
||||
for _, host := range hosts {
|
||||
if u.Host == host {
|
||||
return true
|
||||
}
|
||||
if strings.HasPrefix(host, "*.") && strings.HasSuffix(u.Host, host[2:]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// returns whether the referrer from the request is in the host list.
|
||||
func validReferrer(hosts []string, r *http.Request) bool {
|
||||
u, err := url.Parse(r.Header.Get("Referer"))
|
||||
if err != nil { // malformed or blank header, just deny
|
||||
return false
|
||||
}
|
||||
|
||||
return validHost(hosts, u)
|
||||
}
|
||||
|
||||
// validSignature returns whether the request signature is valid.
|
||||
func validSignature(key []byte, r *Request) bool {
|
||||
sig := r.Options.Signature
|
||||
if m := len(sig) % 4; m != 0 { // add padding if missing
|
||||
sig += strings.Repeat("=", 4-m)
|
||||
}
|
||||
|
||||
got, err := base64.URLEncoding.DecodeString(sig)
|
||||
if err != nil {
|
||||
log.Printf("error base64 decoding signature %q", r.Options.Signature)
|
||||
return false
|
||||
}
|
||||
|
||||
mac := hmac.New(sha256.New, key)
|
||||
mac.Write([]byte(r.URL.String()))
|
||||
want := mac.Sum(nil)
|
||||
|
||||
return hmac.Equal(got, want)
|
||||
}
|
||||
|
||||
// should304 returns whether we should send a 304 Not Modified in response to
|
||||
// req, based on the response resp. This is determined using the last modified
|
||||
// time and the entity tag of resp.
|
||||
func should304(req *http.Request, resp *http.Response) bool {
|
||||
// TODO(willnorris): if-none-match header can be a comma separated list
|
||||
// of multiple tags to be matched, or the special value "*" which
|
||||
// matches all etags
|
||||
etag := resp.Header.Get("Etag")
|
||||
if etag != "" && etag == req.Header.Get("If-None-Match") {
|
||||
return true
|
||||
}
|
||||
|
||||
lastModified, err := time.Parse(time.RFC1123, resp.Header.Get("Last-Modified"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
ifModSince, err := time.Parse(time.RFC1123, req.Header.Get("If-Modified-Since"))
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if lastModified.Before(ifModSince) || lastModified.Equal(ifModSince) {
|
||||
return true
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// TransformingTransport is an implementation of http.RoundTripper that
|
||||
// optionally transforms images using the options specified in the request URL
|
||||
// fragment.
|
||||
type TransformingTransport struct {
|
||||
// Transport is the underlying http.RoundTripper used to satisfy
|
||||
// non-transform requests (those that do not include a URL fragment).
|
||||
Transport http.RoundTripper
|
||||
|
||||
// CachingClient is used to fetch images to be resized. This client is
|
||||
// used rather than Transport directly in order to ensure that
|
||||
// responses are properly cached.
|
||||
CachingClient *http.Client
|
||||
|
||||
log func(format string, v ...interface{})
|
||||
}
|
||||
|
||||
// RoundTrip implements the http.RoundTripper interface.
|
||||
func (t *TransformingTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
if req.URL.Fragment == "" {
|
||||
// normal requests pass through
|
||||
if t.log != nil {
|
||||
t.log("fetching remote URL: %v", req.URL)
|
||||
}
|
||||
return t.Transport.RoundTrip(req)
|
||||
}
|
||||
|
||||
u := *req.URL
|
||||
u.Fragment = ""
|
||||
resp, err := t.CachingClient.Get(u.String())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
defer resp.Body.Close()
|
||||
|
||||
if should304(req, resp) {
|
||||
// bare 304 response, full response will be used from cache
|
||||
return &http.Response{StatusCode: http.StatusNotModified}, nil
|
||||
}
|
||||
|
||||
b, err := ioutil.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
opt := ParseOptions(req.URL.Fragment)
|
||||
|
||||
img, err := Transform(b, opt)
|
||||
if err != nil {
|
||||
log.Printf("error transforming image %s: %v", u.String(), err)
|
||||
img = b
|
||||
}
|
||||
|
||||
// replay response with transformed image and updated content length
|
||||
buf := new(bytes.Buffer)
|
||||
fmt.Fprintf(buf, "%s %s\n", resp.Proto, resp.Status)
|
||||
resp.Header.WriteSubset(buf, map[string]bool{
|
||||
"Content-Length": true,
|
||||
// exclude Content-Type header if the format may have changed during transformation
|
||||
"Content-Type": opt.Format != "" || resp.Header.Get("Content-Type") == "image/webp" || resp.Header.Get("Content-Type") == "image/tiff",
|
||||
})
|
||||
fmt.Fprintf(buf, "Content-Length: %d\n\n", len(img))
|
||||
buf.Write(img)
|
||||
|
||||
return http.ReadResponse(bufio.NewReader(buf), req)
|
||||
}
|
||||
27
vendor/willnorris.com/go/imageproxy/third_party/http/LICENSE
сгенерированный
поставляемый
Обычный файл
27
vendor/willnorris.com/go/imageproxy/third_party/http/LICENSE
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,27 @@
|
||||
Copyright (c) 2009 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
1
vendor/willnorris.com/go/imageproxy/third_party/http/README
сгенерированный
поставляемый
Обычный файл
1
vendor/willnorris.com/go/imageproxy/third_party/http/README
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1 @@
|
||||
Package http is based on a copy of net/http.
|
||||
136
vendor/willnorris.com/go/imageproxy/third_party/http/server.go
сгенерированный
поставляемый
Обычный файл
136
vendor/willnorris.com/go/imageproxy/third_party/http/server.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,136 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package http provides helpers for HTTP servers.
|
||||
package http
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TimeoutHandler returns a Handler that runs h with the given time limit.
|
||||
//
|
||||
// The new Handler calls h.ServeHTTP to handle each request, but if a
|
||||
// call runs for longer than its time limit, the handler responds with
|
||||
// a 504 Gateway Timeout error and the given message in its body.
|
||||
// (If msg is empty, a suitable default message will be sent.)
|
||||
// After such a timeout, writes by h to its ResponseWriter will return
|
||||
// ErrHandlerTimeout.
|
||||
//
|
||||
// TimeoutHandler buffers all Handler writes to memory and does not
|
||||
// support the Hijacker or Flusher interfaces.
|
||||
func TimeoutHandler(h http.Handler, dt time.Duration, msg string) http.Handler {
|
||||
return &timeoutHandler{
|
||||
handler: h,
|
||||
body: msg,
|
||||
dt: dt,
|
||||
}
|
||||
}
|
||||
|
||||
// ErrHandlerTimeout is returned on ResponseWriter Write calls
|
||||
// in handlers which have timed out.
|
||||
var ErrHandlerTimeout = errors.New("http: Handler timeout")
|
||||
|
||||
type timeoutHandler struct {
|
||||
handler http.Handler
|
||||
body string
|
||||
dt time.Duration
|
||||
|
||||
// When set, no timer will be created and this channel will
|
||||
// be used instead.
|
||||
testTimeout <-chan time.Time
|
||||
}
|
||||
|
||||
func (h *timeoutHandler) errorBody() string {
|
||||
if h.body != "" {
|
||||
return h.body
|
||||
}
|
||||
return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
|
||||
}
|
||||
|
||||
func (h *timeoutHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
var t *time.Timer
|
||||
timeout := h.testTimeout
|
||||
if timeout == nil {
|
||||
t = time.NewTimer(h.dt)
|
||||
timeout = t.C
|
||||
}
|
||||
done := make(chan struct{})
|
||||
tw := &timeoutWriter{
|
||||
w: w,
|
||||
h: make(http.Header),
|
||||
}
|
||||
go func() {
|
||||
h.handler.ServeHTTP(tw, r)
|
||||
close(done)
|
||||
}()
|
||||
select {
|
||||
case <-done:
|
||||
tw.mu.Lock()
|
||||
defer tw.mu.Unlock()
|
||||
dst := w.Header()
|
||||
for k, vv := range tw.h {
|
||||
dst[k] = vv
|
||||
}
|
||||
if !tw.wroteHeader {
|
||||
tw.code = http.StatusOK
|
||||
}
|
||||
w.WriteHeader(tw.code)
|
||||
w.Write(tw.wbuf.Bytes())
|
||||
if t != nil {
|
||||
t.Stop()
|
||||
}
|
||||
case <-timeout:
|
||||
tw.mu.Lock()
|
||||
defer tw.mu.Unlock()
|
||||
w.WriteHeader(http.StatusGatewayTimeout)
|
||||
io.WriteString(w, h.errorBody())
|
||||
tw.timedOut = true
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
type timeoutWriter struct {
|
||||
w http.ResponseWriter
|
||||
h http.Header
|
||||
wbuf bytes.Buffer
|
||||
|
||||
mu sync.Mutex
|
||||
timedOut bool
|
||||
wroteHeader bool
|
||||
code int
|
||||
}
|
||||
|
||||
func (tw *timeoutWriter) Header() http.Header { return tw.h }
|
||||
|
||||
func (tw *timeoutWriter) Write(p []byte) (int, error) {
|
||||
tw.mu.Lock()
|
||||
defer tw.mu.Unlock()
|
||||
if tw.timedOut {
|
||||
return 0, ErrHandlerTimeout
|
||||
}
|
||||
if !tw.wroteHeader {
|
||||
tw.writeHeader(http.StatusOK)
|
||||
}
|
||||
return tw.wbuf.Write(p)
|
||||
}
|
||||
|
||||
func (tw *timeoutWriter) WriteHeader(code int) {
|
||||
tw.mu.Lock()
|
||||
defer tw.mu.Unlock()
|
||||
if tw.timedOut || tw.wroteHeader {
|
||||
return
|
||||
}
|
||||
tw.writeHeader(code)
|
||||
}
|
||||
|
||||
func (tw *timeoutWriter) writeHeader(code int) {
|
||||
tw.wroteHeader = true
|
||||
tw.code = code
|
||||
}
|
||||
312
vendor/willnorris.com/go/imageproxy/transform.go
сгенерированный
поставляемый
Обычный файл
312
vendor/willnorris.com/go/imageproxy/transform.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,312 @@
|
||||
// Copyright 2013 Google Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package imageproxy
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"image"
|
||||
_ "image/gif" // register gif format
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"io"
|
||||
"log"
|
||||
"math"
|
||||
|
||||
"github.com/disintegration/imaging"
|
||||
"github.com/muesli/smartcrop"
|
||||
"github.com/rwcarlsen/goexif/exif"
|
||||
"golang.org/x/image/tiff" // register tiff format
|
||||
_ "golang.org/x/image/webp" // register webp format
|
||||
"willnorris.com/go/gifresize"
|
||||
)
|
||||
|
||||
// default compression quality of resized jpegs
|
||||
const defaultQuality = 95
|
||||
|
||||
// maximum distance into image to look for EXIF tags
|
||||
const maxExifSize = 1 << 20
|
||||
|
||||
// resample filter used when resizing images
|
||||
var resampleFilter = imaging.Lanczos
|
||||
|
||||
// Transform the provided image. img should contain the raw bytes of an
|
||||
// encoded image in one of the supported formats (gif, jpeg, or png). The
|
||||
// bytes of a similarly encoded image is returned.
|
||||
func Transform(img []byte, opt Options) ([]byte, error) {
|
||||
if !opt.transform() {
|
||||
// bail if no transformation was requested
|
||||
return img, nil
|
||||
}
|
||||
|
||||
// decode image
|
||||
m, format, err := image.Decode(bytes.NewReader(img))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// apply EXIF orientation for jpeg and tiff source images. Read at most
|
||||
// up to maxExifSize looking for EXIF tags.
|
||||
if format == "jpeg" || format == "tiff" {
|
||||
r := io.LimitReader(bytes.NewReader(img), maxExifSize)
|
||||
if exifOpt := exifOrientation(r); exifOpt.transform() {
|
||||
m = transformImage(m, exifOpt)
|
||||
}
|
||||
}
|
||||
|
||||
// encode webp and tiff as jpeg by default
|
||||
if format == "tiff" || format == "webp" {
|
||||
format = "jpeg"
|
||||
}
|
||||
|
||||
if opt.Format != "" {
|
||||
format = opt.Format
|
||||
}
|
||||
|
||||
// transform and encode image
|
||||
buf := new(bytes.Buffer)
|
||||
switch format {
|
||||
case "gif":
|
||||
fn := func(img image.Image) image.Image {
|
||||
return transformImage(img, opt)
|
||||
}
|
||||
err = gifresize.Process(buf, bytes.NewReader(img), fn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "jpeg":
|
||||
quality := opt.Quality
|
||||
if quality == 0 {
|
||||
quality = defaultQuality
|
||||
}
|
||||
|
||||
m = transformImage(m, opt)
|
||||
err = jpeg.Encode(buf, m, &jpeg.Options{Quality: quality})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "png":
|
||||
m = transformImage(m, opt)
|
||||
err = png.Encode(buf, m)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
case "tiff":
|
||||
m = transformImage(m, opt)
|
||||
err = tiff.Encode(buf, m, &tiff.Options{tiff.Deflate, true})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
default:
|
||||
return nil, fmt.Errorf("unsupported format: %v", format)
|
||||
}
|
||||
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// evaluateFloat interprets the option value f. If f is between 0 and 1, it is
|
||||
// interpreted as a percentage of max, otherwise it is treated as an absolute
|
||||
// value. If f is less than 0, 0 is returned.
|
||||
func evaluateFloat(f float64, max int) int {
|
||||
if 0 < f && f < 1 {
|
||||
return int(float64(max) * f)
|
||||
}
|
||||
if f < 0 {
|
||||
return 0
|
||||
}
|
||||
return int(f)
|
||||
}
|
||||
|
||||
// resizeParams determines if the image needs to be resized, and if so, the
|
||||
// dimensions to resize to.
|
||||
func resizeParams(m image.Image, opt Options) (w, h int, resize bool) {
|
||||
// convert percentage width and height values to absolute values
|
||||
imgW := m.Bounds().Dx()
|
||||
imgH := m.Bounds().Dy()
|
||||
w = evaluateFloat(opt.Width, imgW)
|
||||
h = evaluateFloat(opt.Height, imgH)
|
||||
|
||||
// never resize larger than the original image unless specifically allowed
|
||||
if !opt.ScaleUp {
|
||||
if w > imgW {
|
||||
w = imgW
|
||||
}
|
||||
if h > imgH {
|
||||
h = imgH
|
||||
}
|
||||
}
|
||||
|
||||
// if requested width and height match the original, skip resizing
|
||||
if (w == imgW || w == 0) && (h == imgH || h == 0) {
|
||||
return 0, 0, false
|
||||
}
|
||||
|
||||
return w, h, true
|
||||
}
|
||||
|
||||
// cropParams calculates crop rectangle parameters to keep it in image bounds
|
||||
func cropParams(m image.Image, opt Options) image.Rectangle {
|
||||
if !opt.SmartCrop && opt.CropX == 0 && opt.CropY == 0 && opt.CropWidth == 0 && opt.CropHeight == 0 {
|
||||
return m.Bounds()
|
||||
}
|
||||
|
||||
// width and height of image
|
||||
imgW := m.Bounds().Dx()
|
||||
imgH := m.Bounds().Dy()
|
||||
|
||||
if opt.SmartCrop {
|
||||
w := evaluateFloat(opt.Width, imgW)
|
||||
h := evaluateFloat(opt.Height, imgH)
|
||||
log.Printf("smartcrop input: %dx%d", w, h)
|
||||
r, err := smartcrop.SmartCrop(m, w, h)
|
||||
if err != nil {
|
||||
log.Printf("error with smartcrop: %v", err)
|
||||
} else {
|
||||
log.Printf("smartcrop rectangle: %v", r)
|
||||
return r
|
||||
}
|
||||
}
|
||||
|
||||
// top left coordinate of crop
|
||||
x0 := evaluateFloat(math.Abs(opt.CropX), imgW)
|
||||
if opt.CropX < 0 {
|
||||
x0 = imgW - x0 // measure from right
|
||||
}
|
||||
y0 := evaluateFloat(math.Abs(opt.CropY), imgH)
|
||||
if opt.CropY < 0 {
|
||||
y0 = imgH - y0 // measure from bottom
|
||||
}
|
||||
|
||||
// width and height of crop
|
||||
w := evaluateFloat(opt.CropWidth, imgW)
|
||||
if w == 0 {
|
||||
w = imgW
|
||||
}
|
||||
h := evaluateFloat(opt.CropHeight, imgH)
|
||||
if h == 0 {
|
||||
h = imgH
|
||||
}
|
||||
|
||||
// bottom right coordinate of crop
|
||||
x1 := x0 + w
|
||||
if x1 > imgW {
|
||||
x1 = imgW
|
||||
}
|
||||
y1 := y0 + h
|
||||
if y1 > imgH {
|
||||
y1 = imgH
|
||||
}
|
||||
|
||||
return image.Rect(x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
// read EXIF orientation tag from r and adjust opt to orient image correctly.
|
||||
func exifOrientation(r io.Reader) (opt Options) {
|
||||
// Exif Orientation Tag values
|
||||
// http://sylvana.net/jpegcrop/exif_orientation.html
|
||||
const (
|
||||
topLeftSide = 1
|
||||
topRightSide = 2
|
||||
bottomRightSide = 3
|
||||
bottomLeftSide = 4
|
||||
leftSideTop = 5
|
||||
rightSideTop = 6
|
||||
rightSideBottom = 7
|
||||
leftSideBottom = 8
|
||||
)
|
||||
|
||||
ex, err := exif.Decode(r)
|
||||
if err != nil {
|
||||
return opt
|
||||
}
|
||||
tag, err := ex.Get(exif.Orientation)
|
||||
if err != nil {
|
||||
return opt
|
||||
}
|
||||
orient, err := tag.Int(0)
|
||||
if err != nil {
|
||||
return opt
|
||||
}
|
||||
|
||||
switch orient {
|
||||
case topLeftSide:
|
||||
// do nothing
|
||||
case topRightSide:
|
||||
opt.FlipHorizontal = true
|
||||
case bottomRightSide:
|
||||
opt.Rotate = 180
|
||||
case bottomLeftSide:
|
||||
opt.FlipVertical = true
|
||||
case leftSideTop:
|
||||
opt.Rotate = 90
|
||||
opt.FlipVertical = true
|
||||
case rightSideTop:
|
||||
opt.Rotate = -90
|
||||
case rightSideBottom:
|
||||
opt.Rotate = 90
|
||||
opt.FlipHorizontal = true
|
||||
case leftSideBottom:
|
||||
opt.Rotate = 90
|
||||
}
|
||||
return opt
|
||||
}
|
||||
|
||||
// transformImage modifies the image m based on the transformations specified
|
||||
// in opt.
|
||||
func transformImage(m image.Image, opt Options) image.Image {
|
||||
// Parse crop and resize parameters before applying any transforms.
|
||||
// This is to ensure that any percentage-based values are based off the
|
||||
// size of the original image.
|
||||
rect := cropParams(m, opt)
|
||||
w, h, resize := resizeParams(m, opt)
|
||||
|
||||
// crop if needed
|
||||
if !m.Bounds().Eq(rect) {
|
||||
m = imaging.Crop(m, rect)
|
||||
}
|
||||
// resize if needed
|
||||
if resize {
|
||||
if opt.Fit {
|
||||
m = imaging.Fit(m, w, h, resampleFilter)
|
||||
} else {
|
||||
if w == 0 || h == 0 {
|
||||
m = imaging.Resize(m, w, h, resampleFilter)
|
||||
} else {
|
||||
m = imaging.Thumbnail(m, w, h, resampleFilter)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// rotate
|
||||
rotate := float64(opt.Rotate) - math.Floor(float64(opt.Rotate)/360)*360
|
||||
switch rotate {
|
||||
case 90:
|
||||
m = imaging.Rotate90(m)
|
||||
case 180:
|
||||
m = imaging.Rotate180(m)
|
||||
case 270:
|
||||
m = imaging.Rotate270(m)
|
||||
}
|
||||
|
||||
// flip
|
||||
if opt.FlipVertical {
|
||||
m = imaging.FlipV(m)
|
||||
}
|
||||
if opt.FlipHorizontal {
|
||||
m = imaging.FlipH(m)
|
||||
}
|
||||
|
||||
return m
|
||||
}
|
||||
Ссылка в новой задаче
Block a user