1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "base/containers/hash_tables.h"
11 #include "base/lazy_instance.h"
12 #include "base/logging.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string_number_conversions.h"
15 #include "base/strings/string_split.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "net/base/mime_util.h"
19 #include "net/base/platform_mime_util.h"
20 #include "net/http/http_util.h"
22 #if defined(OS_ANDROID)
23 #include "base/android/build_info.h"
32 const char matcher
[13];
35 static const MediaType kIanaMediaTypes
[] = {
36 { "application", "application/" },
37 { "audio", "audio/" },
38 { "example", "example/" },
39 { "image", "image/" },
40 { "message", "message/" },
41 { "model", "model/" },
42 { "multipart", "multipart/" },
44 { "video", "video/" },
51 // Singleton utility class for mime types.
52 class MimeUtil
: public PlatformMimeUtil
{
74 bool GetMimeTypeFromExtension(const base::FilePath::StringType
& ext
,
75 std::string
* mime_type
) const;
77 bool GetMimeTypeFromFile(const base::FilePath
& file_path
,
78 std::string
* mime_type
) const;
80 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType
& ext
,
81 std::string
* mime_type
) const;
83 bool IsSupportedImageMimeType(const std::string
& mime_type
) const;
84 bool IsSupportedMediaMimeType(const std::string
& mime_type
) const;
85 bool IsSupportedNonImageMimeType(const std::string
& mime_type
) const;
86 bool IsUnsupportedTextMimeType(const std::string
& mime_type
) const;
87 bool IsSupportedJavascriptMimeType(const std::string
& mime_type
) const;
89 bool IsSupportedMimeType(const std::string
& mime_type
) const;
91 bool MatchesMimeType(const std::string
&mime_type_pattern
,
92 const std::string
&mime_type
) const;
94 bool ParseMimeTypeWithoutParameter(const std::string
& type_string
,
95 std::string
* top_level_type
,
96 std::string
* subtype
) const;
98 bool IsValidTopLevelMimeType(const std::string
& type_string
) const;
100 bool AreSupportedMediaCodecs(const std::vector
<std::string
>& codecs
) const;
102 void ParseCodecString(const std::string
& codecs
,
103 std::vector
<std::string
>* codecs_out
,
106 bool IsStrictMediaMimeType(const std::string
& mime_type
) const;
107 SupportsType
IsSupportedStrictMediaMimeType(
108 const std::string
& mime_type
,
109 const std::vector
<std::string
>& codecs
) const;
111 void RemoveProprietaryMediaTypesAndCodecsForTests();
114 friend struct base::DefaultLazyInstanceTraits
<MimeUtil
>;
116 typedef base::hash_set
<std::string
> MimeMappings
;
118 typedef base::hash_set
<int> CodecSet
;
119 typedef std::map
<std::string
, CodecSet
> StrictMappings
;
121 CodecEntry() : codec(INVALID_CODEC
), is_ambiguous(true) {}
122 CodecEntry(Codec c
, bool ambiguous
) : codec(c
), is_ambiguous(ambiguous
) {}
126 typedef std::map
<std::string
, CodecEntry
> StringToCodecMappings
;
130 // Returns IsSupported if all codec IDs in |codecs| are unambiguous
131 // and are supported by the platform. MayBeSupported is returned if
132 // at least one codec ID in |codecs| is ambiguous but all the codecs
133 // are supported by the platform. IsNotSupported is returned if at
134 // least one codec ID is not supported by the platform.
135 SupportsType
AreSupportedCodecs(
136 const CodecSet
& supported_codecs
,
137 const std::vector
<std::string
>& codecs
) const;
139 // For faster lookup, keep hash sets.
140 void InitializeMimeTypeMaps();
142 bool GetMimeTypeFromExtensionHelper(const base::FilePath::StringType
& ext
,
143 bool include_platform_types
,
144 std::string
* mime_type
) const;
146 // Converts a codec ID into an Codec enum value and indicates
147 // whether the conversion was ambiguous.
148 // Returns true if this method was able to map |codec_id| to a specific
149 // Codec enum value. |codec| and |is_ambiguous| are only valid if true
150 // is returned. Otherwise their value is undefined after the call.
151 // |is_ambiguous| is true if |codec_id| did not have enough information to
152 // unambiguously determine the proper Codec enum value. If |is_ambiguous|
153 // is true |codec| contains the best guess for the intended Codec enum value.
154 bool StringToCodec(const std::string
& codec_id
,
156 bool* is_ambiguous
) const;
158 // Returns true if |codec| is supported by the platform.
159 // Note: This method will return false if the platform supports proprietary
160 // codecs but |allow_proprietary_codecs_| is set to false.
161 bool IsCodecSupported(Codec codec
) const;
163 // Returns true if |codec| refers to a proprietary codec.
164 bool IsCodecProprietary(Codec codec
) const;
166 // Returns true and sets |*default_codec| if |mime_type| has a
167 // default codec associated with it.
168 // Returns false otherwise and the value of |*default_codec| is undefined.
169 bool GetDefaultCodec(const std::string
& mime_type
,
170 Codec
* default_codec
) const;
172 // Returns true if |mime_type| has a default codec associated with it
173 // and IsCodecSupported() returns true for that particular codec.
174 bool IsDefaultCodecSupported(const std::string
& mime_type
) const;
176 MimeMappings image_map_
;
177 MimeMappings media_map_
;
178 MimeMappings non_image_map_
;
179 MimeMappings unsupported_text_map_
;
180 MimeMappings javascript_map_
;
182 // A map of mime_types and hash map of the supported codecs for the mime_type.
183 StrictMappings strict_format_map_
;
185 // Keeps track of whether proprietary codec support should be
186 // advertised to callers.
187 bool allow_proprietary_codecs_
;
189 // Lookup table for string compare based string -> Codec mappings.
190 StringToCodecMappings string_to_codec_map_
;
193 // This variable is Leaky because we need to access it from WorkerPool threads.
194 static base::LazyInstance
<MimeUtil
>::Leaky g_mime_util
=
195 LAZY_INSTANCE_INITIALIZER
;
198 const char* mime_type
;
199 const char* extensions
; // comma separated list
202 static const MimeInfo primary_mappings
[] = {
203 { "text/html", "html,htm,shtml,shtm" },
204 { "text/css", "css" },
205 { "text/xml", "xml" },
206 { "image/gif", "gif" },
207 { "image/jpeg", "jpeg,jpg" },
208 { "image/webp", "webp" },
209 { "image/png", "png" },
210 { "video/mp4", "mp4,m4v" },
211 { "audio/x-m4a", "m4a" },
212 { "audio/mp3", "mp3" },
213 { "video/ogg", "ogv,ogm" },
214 { "audio/ogg", "ogg,oga,opus" },
215 { "video/webm", "webm" },
216 { "audio/webm", "webm" },
217 { "audio/wav", "wav" },
218 { "application/xhtml+xml", "xhtml,xht,xhtm" },
219 { "application/x-chrome-extension", "crx" },
220 { "multipart/related", "mhtml,mht" }
223 static const MimeInfo secondary_mappings
[] = {
224 { "application/octet-stream", "exe,com,bin" },
225 { "application/gzip", "gz" },
226 { "application/pdf", "pdf" },
227 { "application/postscript", "ps,eps,ai" },
228 { "application/javascript", "js" },
229 { "application/font-woff", "woff" },
230 { "image/bmp", "bmp" },
231 { "image/x-icon", "ico" },
232 { "image/vnd.microsoft.icon", "ico" },
233 { "image/jpeg", "jfif,pjpeg,pjp" },
234 { "image/tiff", "tiff,tif" },
235 { "image/x-xbitmap", "xbm" },
236 { "image/svg+xml", "svg,svgz" },
237 { "image/x-png", "png"},
238 { "message/rfc822", "eml" },
239 { "text/plain", "txt,text" },
240 { "text/html", "ehtml" },
241 { "application/rss+xml", "rss" },
242 { "application/rdf+xml", "rdf" },
243 { "text/xml", "xsl,xbl,xslt" },
244 { "application/vnd.mozilla.xul+xml", "xul" },
245 { "application/x-shockwave-flash", "swf,swl" },
246 { "application/pkcs7-mime", "p7m,p7c,p7z" },
247 { "application/pkcs7-signature", "p7s" },
248 { "application/x-mpegurl", "m3u8" },
251 static const char* FindMimeType(const MimeInfo
* mappings
,
254 size_t ext_len
= strlen(ext
);
256 for (size_t i
= 0; i
< mappings_len
; ++i
) {
257 const char* extensions
= mappings
[i
].extensions
;
259 size_t end_pos
= strcspn(extensions
, ",");
260 if (end_pos
== ext_len
&&
261 base::strncasecmp(extensions
, ext
, ext_len
) == 0)
262 return mappings
[i
].mime_type
;
263 extensions
+= end_pos
;
266 extensions
+= 1; // skip over comma
272 bool MimeUtil::GetMimeTypeFromExtension(const base::FilePath::StringType
& ext
,
273 string
* result
) const {
274 return GetMimeTypeFromExtensionHelper(ext
, true, result
);
277 bool MimeUtil::GetWellKnownMimeTypeFromExtension(
278 const base::FilePath::StringType
& ext
,
279 string
* result
) const {
280 return GetMimeTypeFromExtensionHelper(ext
, false, result
);
283 bool MimeUtil::GetMimeTypeFromFile(const base::FilePath
& file_path
,
284 string
* result
) const {
285 base::FilePath::StringType file_name_str
= file_path
.Extension();
286 if (file_name_str
.empty())
288 return GetMimeTypeFromExtension(file_name_str
.substr(1), result
);
291 bool MimeUtil::GetMimeTypeFromExtensionHelper(
292 const base::FilePath::StringType
& ext
,
293 bool include_platform_types
,
294 string
* result
) const {
295 // Avoids crash when unable to handle a long file path. See crbug.com/48733.
296 const unsigned kMaxFilePathSize
= 65536;
297 if (ext
.length() > kMaxFilePathSize
)
300 // We implement the same algorithm as Mozilla for mapping a file extension to
301 // a mime type. That is, we first check a hard-coded list (that cannot be
302 // overridden), and then if not found there, we defer to the system registry.
303 // Finally, we scan a secondary hard-coded list to catch types that we can
304 // deduce but that we also want to allow the OS to override.
306 base::FilePath
path_ext(ext
);
307 const string ext_narrow_str
= path_ext
.AsUTF8Unsafe();
308 const char* mime_type
= FindMimeType(primary_mappings
,
309 arraysize(primary_mappings
),
310 ext_narrow_str
.c_str());
316 if (include_platform_types
&& GetPlatformMimeTypeFromExtension(ext
, result
))
319 mime_type
= FindMimeType(secondary_mappings
, arraysize(secondary_mappings
),
320 ext_narrow_str
.c_str());
329 // From WebKit's WebCore/platform/MIMETypeRegistry.cpp:
331 static const char* const supported_image_types
[] = {
339 "image/vnd.microsoft.icon", // ico
340 "image/x-icon", // ico
341 "image/x-xbitmap", // xbm
345 // A list of media types: http://en.wikipedia.org/wiki/Internet_media_type
346 // A comprehensive mime type list: http://plugindoc.mozdev.org/winmime.php
347 // This set of codecs is supported by all variations of Chromium.
348 static const char* const common_media_types
[] = {
352 #if !defined(OS_ANDROID) // Android doesn't support Ogg Theora.
364 #if defined(OS_ANDROID)
365 // HLS. Supported by Android ICS and above.
366 "application/vnd.apple.mpegurl",
367 "application/x-mpegurl",
371 // List of proprietary types only supported by Google Chrome.
372 static const char* const proprietary_media_types
[] = {
384 #if defined(ENABLE_MPEG2TS_STREAM_PARSER)
391 // - does not include javascript types list (see supported_javascript_types)
392 // - does not include types starting with "text/" (see
393 // IsSupportedNonImageMimeType())
394 static const char* const supported_non_image_types
[] = {
395 "image/svg+xml", // SVG is text-based XML, even though it has an image/ type
397 "application/atom+xml",
398 "application/rss+xml",
399 "application/xhtml+xml",
401 "multipart/related", // For MHTML support.
402 "multipart/x-mixed-replace"
403 // Note: ADDING a new type here will probably render it AS HTML. This can
404 // result in cross site scripting.
407 // Dictionary of cryptographic file mime types.
408 struct CertificateMimeTypeInfo
{
409 const char* mime_type
;
410 CertificateMimeType cert_type
;
413 static const CertificateMimeTypeInfo supported_certificate_types
[] = {
414 { "application/x-x509-user-cert",
415 CERTIFICATE_MIME_TYPE_X509_USER_CERT
},
416 #if defined(OS_ANDROID)
417 { "application/x-x509-ca-cert", CERTIFICATE_MIME_TYPE_X509_CA_CERT
},
418 { "application/x-pkcs12", CERTIFICATE_MIME_TYPE_PKCS12_ARCHIVE
},
422 // These types are excluded from the logic that allows all text/ types because
423 // while they are technically text, it's very unlikely that a user expects to
424 // see them rendered in text form.
425 static const char* const unsupported_text_types
[] = {
439 "text/comma-separated-values",
441 "text/tab-separated-values",
443 "text/ofx", // http://crbug.com/162238
444 "text/vnd.sun.j2me.app-descriptor" // http://crbug.com/176450
447 // Mozilla 1.8 and WinIE 7 both accept text/javascript and text/ecmascript.
448 // Mozilla 1.8 accepts application/javascript, application/ecmascript, and
449 // application/x-javascript, but WinIE 7 doesn't.
450 // WinIE 7 accepts text/javascript1.1 - text/javascript1.3, text/jscript, and
451 // text/livescript, but Mozilla 1.8 doesn't.
452 // Mozilla 1.8 allows leading and trailing whitespace, but WinIE 7 doesn't.
453 // Mozilla 1.8 and WinIE 7 both accept the empty string, but neither accept a
454 // whitespace-only string.
455 // We want to accept all the values that either of these browsers accept, but
457 static const char* const supported_javascript_types
[] = {
460 "application/javascript",
461 "application/ecmascript",
462 "application/x-javascript",
463 "text/javascript1.1",
464 "text/javascript1.2",
465 "text/javascript1.3",
470 #if defined(OS_ANDROID)
471 static bool IsCodecSupportedOnAndroid(MimeUtil::Codec codec
) {
473 case MimeUtil::INVALID_CODEC
:
478 case MimeUtil::MPEG4_AAC_LC
:
479 case MimeUtil::MPEG4_AAC_SBR_v1
:
480 case MimeUtil::MPEG4_AAC_SBR_PS_v2
:
481 case MimeUtil::H264_BASELINE
:
482 case MimeUtil::H264_MAIN
:
483 case MimeUtil::H264_HIGH
:
485 case MimeUtil::VORBIS
:
488 case MimeUtil::MPEG2_AAC_LC
:
489 case MimeUtil::MPEG2_AAC_MAIN
:
490 case MimeUtil::MPEG2_AAC_SSR
:
491 // MPEG-2 variants of AAC are not supported on Android.
495 // VP9 is supported only in KitKat+ (API Level 19).
496 return base::android::BuildInfo::GetInstance()->sdk_int() >= 19;
499 // TODO(vigneshv): Change this similar to the VP9 check once Opus is
500 // supported on Android (http://crbug.com/318436).
503 case MimeUtil::THEORA
:
510 static bool IsMimeTypeSupportedOnAndroid(const std::string
& mimeType
) {
511 // HLS codecs are supported in ICS and above (API level 14)
512 if ((!mimeType
.compare("application/vnd.apple.mpegurl") ||
513 !mimeType
.compare("application/x-mpegurl")) &&
514 base::android::BuildInfo::GetInstance()->sdk_int() < 14) {
521 struct MediaFormatStrict
{
522 const char* mime_type
;
523 const char* codecs_list
;
526 // Following is the list of RFC 6381 compliant codecs:
527 // mp4a.66 - MPEG-2 AAC MAIN
528 // mp4a.67 - MPEG-2 AAC LC
529 // mp4a.68 - MPEG-2 AAC SSR
530 // mp4a.69 - MPEG-2 extension to MPEG-1
531 // mp4a.6B - MPEG-1 audio
532 // mp4a.40.2 - MPEG-4 AAC LC
533 // mp4a.40.5 - MPEG-4 HE-AAC v1 (AAC LC + SBR)
534 // mp4a.40.29 - MPEG-4 HE-AAC v2 (AAC LC + SBR + PS)
536 // avc1.42E0xx - H.264 Baseline
537 // avc1.4D40xx - H.264 Main
538 // avc1.6400xx - H.264 High
539 static const char kMP4AudioCodecsExpression
[] =
540 "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5,mp4a.40.29";
541 static const char kMP4VideoCodecsExpression
[] =
542 "avc1.42E00A,avc1.4D400A,avc1.64000A," \
543 "mp4a.66,mp4a.67,mp4a.68,mp4a.69,mp4a.6B,mp4a.40.2,mp4a.40.5,mp4a.40.29";
545 static const MediaFormatStrict format_codec_mappings
[] = {
546 { "video/webm", "opus,vorbis,vp8,vp8.0,vp9,vp9.0" },
547 { "audio/webm", "opus,vorbis" },
548 { "audio/wav", "1" },
549 { "audio/x-wav", "1" },
550 { "video/ogg", "opus,theora,vorbis" },
551 { "audio/ogg", "opus,vorbis" },
552 { "application/ogg", "opus,theora,vorbis" },
553 { "audio/mpeg", "mp3" },
555 { "audio/x-mp3", "" },
556 { "audio/mp4", kMP4AudioCodecsExpression
},
557 { "audio/x-m4a", kMP4AudioCodecsExpression
},
558 { "video/mp4", kMP4VideoCodecsExpression
},
559 { "video/x-m4v", kMP4VideoCodecsExpression
},
560 { "application/x-mpegurl", kMP4VideoCodecsExpression
},
561 { "application/vnd.apple.mpegurl", kMP4VideoCodecsExpression
}
564 struct CodecIDMappings
{
565 const char* const codec_id
;
566 MimeUtil::Codec codec
;
569 // List of codec IDs that provide enough information to determine the
570 // codec and profile being requested.
572 // The "mp4a" strings come from RFC 6381.
573 static const CodecIDMappings kUnambiguousCodecIDs
[] = {
574 { "1", MimeUtil::PCM
}, // We only allow this for WAV so it isn't ambiguous.
575 { "mp3", MimeUtil::MP3
},
576 { "mp4a.66", MimeUtil::MPEG2_AAC_MAIN
},
577 { "mp4a.67", MimeUtil::MPEG2_AAC_LC
},
578 { "mp4a.68", MimeUtil::MPEG2_AAC_SSR
},
579 { "mp4a.69", MimeUtil::MP3
},
580 { "mp4a.6B", MimeUtil::MP3
},
581 { "mp4a.40.2", MimeUtil::MPEG4_AAC_LC
},
582 { "mp4a.40.5", MimeUtil::MPEG4_AAC_SBR_v1
},
583 { "mp4a.40.29", MimeUtil::MPEG4_AAC_SBR_PS_v2
},
584 { "vorbis", MimeUtil::VORBIS
},
585 { "opus", MimeUtil::OPUS
},
586 { "vp8", MimeUtil::VP8
},
587 { "vp8.0", MimeUtil::VP8
},
588 { "vp9", MimeUtil::VP9
},
589 { "vp9.0", MimeUtil::VP9
},
590 { "theora", MimeUtil::THEORA
}
593 // List of codec IDs that are ambiguous and don't provide
594 // enough information to determine the codec and profile.
595 // The codec in these entries indicate the codec and profile
596 // we assume the user is trying to indicate.
597 static const CodecIDMappings kAmbiguousCodecIDs
[] = {
598 { "mp4a.40", MimeUtil::MPEG4_AAC_LC
},
599 { "avc1", MimeUtil::H264_BASELINE
},
600 { "avc3", MimeUtil::H264_BASELINE
},
603 MimeUtil::MimeUtil() : allow_proprietary_codecs_(false) {
604 InitializeMimeTypeMaps();
607 SupportsType
MimeUtil::AreSupportedCodecs(
608 const CodecSet
& supported_codecs
,
609 const std::vector
<std::string
>& codecs
) const {
610 DCHECK(!supported_codecs
.empty());
611 DCHECK(!codecs
.empty());
613 SupportsType result
= IsSupported
;
614 for (size_t i
= 0; i
< codecs
.size(); ++i
) {
615 bool is_ambiguous
= true;
616 Codec codec
= INVALID_CODEC
;
617 if (!StringToCodec(codecs
[i
], &codec
, &is_ambiguous
))
618 return IsNotSupported
;
620 if (!IsCodecSupported(codec
) ||
621 supported_codecs
.find(codec
) == supported_codecs
.end()) {
622 return IsNotSupported
;
626 result
= MayBeSupported
;
632 void MimeUtil::InitializeMimeTypeMaps() {
633 for (size_t i
= 0; i
< arraysize(supported_image_types
); ++i
)
634 image_map_
.insert(supported_image_types
[i
]);
636 // Initialize the supported non-image types.
637 for (size_t i
= 0; i
< arraysize(supported_non_image_types
); ++i
)
638 non_image_map_
.insert(supported_non_image_types
[i
]);
639 for (size_t i
= 0; i
< arraysize(supported_certificate_types
); ++i
)
640 non_image_map_
.insert(supported_certificate_types
[i
].mime_type
);
641 for (size_t i
= 0; i
< arraysize(unsupported_text_types
); ++i
)
642 unsupported_text_map_
.insert(unsupported_text_types
[i
]);
643 for (size_t i
= 0; i
< arraysize(supported_javascript_types
); ++i
)
644 non_image_map_
.insert(supported_javascript_types
[i
]);
645 for (size_t i
= 0; i
< arraysize(common_media_types
); ++i
) {
646 #if defined(OS_ANDROID)
647 if (!IsMimeTypeSupportedOnAndroid(common_media_types
[i
]))
650 non_image_map_
.insert(common_media_types
[i
]);
652 #if defined(USE_PROPRIETARY_CODECS)
653 allow_proprietary_codecs_
= true;
655 for (size_t i
= 0; i
< arraysize(proprietary_media_types
); ++i
)
656 non_image_map_
.insert(proprietary_media_types
[i
]);
659 // Initialize the supported media types.
660 for (size_t i
= 0; i
< arraysize(common_media_types
); ++i
) {
661 #if defined(OS_ANDROID)
662 if (!IsMimeTypeSupportedOnAndroid(common_media_types
[i
]))
665 media_map_
.insert(common_media_types
[i
]);
667 #if defined(USE_PROPRIETARY_CODECS)
668 for (size_t i
= 0; i
< arraysize(proprietary_media_types
); ++i
)
669 media_map_
.insert(proprietary_media_types
[i
]);
672 for (size_t i
= 0; i
< arraysize(supported_javascript_types
); ++i
)
673 javascript_map_
.insert(supported_javascript_types
[i
]);
675 for (size_t i
= 0; i
< arraysize(kUnambiguousCodecIDs
); ++i
) {
676 string_to_codec_map_
[kUnambiguousCodecIDs
[i
].codec_id
] =
677 CodecEntry(kUnambiguousCodecIDs
[i
].codec
, false);
680 for (size_t i
= 0; i
< arraysize(kAmbiguousCodecIDs
); ++i
) {
681 string_to_codec_map_
[kAmbiguousCodecIDs
[i
].codec_id
] =
682 CodecEntry(kAmbiguousCodecIDs
[i
].codec
, true);
685 // Initialize the strict supported media types.
686 for (size_t i
= 0; i
< arraysize(format_codec_mappings
); ++i
) {
687 std::vector
<std::string
> mime_type_codecs
;
688 ParseCodecString(format_codec_mappings
[i
].codecs_list
,
693 for (size_t j
= 0; j
< mime_type_codecs
.size(); ++j
) {
694 Codec codec
= INVALID_CODEC
;
695 bool is_ambiguous
= true;
696 CHECK(StringToCodec(mime_type_codecs
[j
], &codec
, &is_ambiguous
));
697 DCHECK(!is_ambiguous
);
698 codecs
.insert(codec
);
701 strict_format_map_
[format_codec_mappings
[i
].mime_type
] = codecs
;
705 bool MimeUtil::IsSupportedImageMimeType(const std::string
& mime_type
) const {
706 return image_map_
.find(mime_type
) != image_map_
.end();
709 bool MimeUtil::IsSupportedMediaMimeType(const std::string
& mime_type
) const {
710 return media_map_
.find(mime_type
) != media_map_
.end();
713 bool MimeUtil::IsSupportedNonImageMimeType(const std::string
& mime_type
) const {
714 return non_image_map_
.find(mime_type
) != non_image_map_
.end() ||
715 (mime_type
.compare(0, 5, "text/") == 0 &&
716 !IsUnsupportedTextMimeType(mime_type
)) ||
717 (mime_type
.compare(0, 12, "application/") == 0 &&
718 MatchesMimeType("application/*+json", mime_type
));
721 bool MimeUtil::IsUnsupportedTextMimeType(const std::string
& mime_type
) const {
722 return unsupported_text_map_
.find(mime_type
) != unsupported_text_map_
.end();
725 bool MimeUtil::IsSupportedJavascriptMimeType(
726 const std::string
& mime_type
) const {
727 return javascript_map_
.find(mime_type
) != javascript_map_
.end();
730 // Mirrors WebViewImpl::CanShowMIMEType()
731 bool MimeUtil::IsSupportedMimeType(const std::string
& mime_type
) const {
732 return (mime_type
.compare(0, 6, "image/") == 0 &&
733 IsSupportedImageMimeType(mime_type
)) ||
734 IsSupportedNonImageMimeType(mime_type
);
737 // Tests for MIME parameter equality. Each parameter in the |mime_type_pattern|
738 // must be matched by a parameter in the |mime_type|. If there are no
739 // parameters in the pattern, the match is a success.
740 bool MatchesMimeTypeParameters(const std::string
& mime_type_pattern
,
741 const std::string
& mime_type
) {
742 const std::string::size_type semicolon
= mime_type_pattern
.find(';');
743 const std::string::size_type test_semicolon
= mime_type
.find(';');
744 if (semicolon
!= std::string::npos
) {
745 if (test_semicolon
== std::string::npos
)
748 std::vector
<std::string
> pattern_parameters
;
749 base::SplitString(mime_type_pattern
.substr(semicolon
+ 1),
750 ';', &pattern_parameters
);
752 std::vector
<std::string
> test_parameters
;
753 base::SplitString(mime_type
.substr(test_semicolon
+ 1),
754 ';', &test_parameters
);
756 sort(pattern_parameters
.begin(), pattern_parameters
.end());
757 sort(test_parameters
.begin(), test_parameters
.end());
758 std::vector
<std::string
> difference
=
759 base::STLSetDifference
<std::vector
<std::string
> >(pattern_parameters
,
761 return difference
.size() == 0;
766 // This comparison handles absolute maching and also basic
767 // wildcards. The plugin mime types could be:
772 // Also tests mime parameters -- all parameters in the pattern must be present
773 // in the tested type for a match to succeed.
774 bool MimeUtil::MatchesMimeType(const std::string
& mime_type_pattern
,
775 const std::string
& mime_type
) const {
776 // Verify caller is passing lowercase strings.
777 DCHECK_EQ(base::StringToLowerASCII(mime_type_pattern
), mime_type_pattern
);
778 DCHECK_EQ(base::StringToLowerASCII(mime_type
), mime_type
);
780 if (mime_type_pattern
.empty())
783 std::string::size_type semicolon
= mime_type_pattern
.find(';');
784 const std::string
base_pattern(mime_type_pattern
.substr(0, semicolon
));
785 semicolon
= mime_type
.find(';');
786 const std::string
base_type(mime_type
.substr(0, semicolon
));
788 if (base_pattern
== "*" || base_pattern
== "*/*")
789 return MatchesMimeTypeParameters(mime_type_pattern
, mime_type
);
791 const std::string::size_type star
= base_pattern
.find('*');
792 if (star
== std::string::npos
) {
793 if (base_pattern
== base_type
)
794 return MatchesMimeTypeParameters(mime_type_pattern
, mime_type
);
799 // Test length to prevent overlap between |left| and |right|.
800 if (base_type
.length() < base_pattern
.length() - 1)
803 const std::string
left(base_pattern
.substr(0, star
));
804 const std::string
right(base_pattern
.substr(star
+ 1));
806 if (base_type
.find(left
) != 0)
809 if (!right
.empty() &&
810 base_type
.rfind(right
) != base_type
.length() - right
.length())
813 return MatchesMimeTypeParameters(mime_type_pattern
, mime_type
);
816 // See http://www.iana.org/assignments/media-types/media-types.xhtml
817 static const char* legal_top_level_types
[] = {
829 bool MimeUtil::ParseMimeTypeWithoutParameter(
830 const std::string
& type_string
,
831 std::string
* top_level_type
,
832 std::string
* subtype
) const {
833 std::vector
<std::string
> components
;
834 base::SplitString(type_string
, '/', &components
);
835 if (components
.size() != 2 ||
836 !HttpUtil::IsToken(components
[0]) ||
837 !HttpUtil::IsToken(components
[1]))
841 *top_level_type
= components
[0];
843 *subtype
= components
[1];
847 bool MimeUtil::IsValidTopLevelMimeType(const std::string
& type_string
) const {
848 std::string lower_type
= base::StringToLowerASCII(type_string
);
849 for (size_t i
= 0; i
< arraysize(legal_top_level_types
); ++i
) {
850 if (lower_type
.compare(legal_top_level_types
[i
]) == 0)
854 return type_string
.size() > 2 && StartsWithASCII(type_string
, "x-", false);
857 bool MimeUtil::AreSupportedMediaCodecs(
858 const std::vector
<std::string
>& codecs
) const {
859 for (size_t i
= 0; i
< codecs
.size(); ++i
) {
860 Codec codec
= INVALID_CODEC
;
861 bool is_ambiguous
= true;
862 if (!StringToCodec(codecs
[i
], &codec
, &is_ambiguous
) ||
863 !IsCodecSupported(codec
)) {
870 void MimeUtil::ParseCodecString(const std::string
& codecs
,
871 std::vector
<std::string
>* codecs_out
,
873 std::string no_quote_codecs
;
874 base::TrimString(codecs
, "\"", &no_quote_codecs
);
875 base::SplitString(no_quote_codecs
, ',', codecs_out
);
880 // Strip everything past the first '.'
881 for (std::vector
<std::string
>::iterator it
= codecs_out
->begin();
882 it
!= codecs_out
->end();
884 size_t found
= it
->find_first_of('.');
885 if (found
!= std::string::npos
)
890 bool MimeUtil::IsStrictMediaMimeType(const std::string
& mime_type
) const {
891 return strict_format_map_
.find(mime_type
) != strict_format_map_
.end();
894 SupportsType
MimeUtil::IsSupportedStrictMediaMimeType(
895 const std::string
& mime_type
,
896 const std::vector
<std::string
>& codecs
) const {
897 StrictMappings::const_iterator it_strict_map
=
898 strict_format_map_
.find(mime_type
);
899 if (it_strict_map
== strict_format_map_
.end())
900 return codecs
.empty() ? MayBeSupported
: IsNotSupported
;
902 if (it_strict_map
->second
.empty()) {
903 // We get here if the mimetype does not expect a codecs parameter.
904 return (codecs
.empty() && IsDefaultCodecSupported(mime_type
)) ?
905 IsSupported
: IsNotSupported
;
908 if (codecs
.empty()) {
909 // We get here if the mimetype expects to get a codecs parameter,
910 // but didn't get one. If |mime_type| does not have a default codec
911 // the best we can do is say "maybe" because we don't have enough
913 Codec default_codec
= INVALID_CODEC
;
914 if (!GetDefaultCodec(mime_type
, &default_codec
))
915 return MayBeSupported
;
917 return IsCodecSupported(default_codec
) ? IsSupported
: IsNotSupported
;
920 return AreSupportedCodecs(it_strict_map
->second
, codecs
);
923 void MimeUtil::RemoveProprietaryMediaTypesAndCodecsForTests() {
924 for (size_t i
= 0; i
< arraysize(proprietary_media_types
); ++i
) {
925 non_image_map_
.erase(proprietary_media_types
[i
]);
926 media_map_
.erase(proprietary_media_types
[i
]);
928 allow_proprietary_codecs_
= false;
931 // Returns true iff |profile_str| conforms to hex string "42y0", where y is one
932 // of [8..F]. Requiring constraint_set0_flag be set and profile_idc be 0x42 is
933 // taken from ISO-14496-10 7.3.2.1, 7.4.2.1, and Annex A.2.1.
935 // |profile_str| is the first four characters of the H.264 suffix string
936 // (ignoring the last 2 characters of the full 6 character suffix that are
937 // level_idc). From ISO-14496-10 7.3.2.1, it consists of:
938 // 8 bits: profile_idc: required to be 0x42 here.
939 // 1 bit: constraint_set0_flag : required to be true here.
940 // 1 bit: constraint_set1_flag : ignored here.
941 // 1 bit: constraint_set2_flag : ignored here.
942 // 1 bit: constraint_set3_flag : ignored here.
943 // 4 bits: reserved : required to be 0 here.
945 // The spec indicates other ways, not implemented here, that a |profile_str|
946 // can indicate a baseline conforming decoder is sufficient for decode in Annex
947 // A.2.1: "[profile_idc not necessarily 0x42] with constraint_set0_flag set and
948 // in which level_idc and constraint_set3_flag represent a level less than or
949 // equal to the specified level."
950 static bool IsValidH264BaselineProfile(const std::string
& profile_str
) {
951 uint32 constraint_set_bits
;
952 if (profile_str
.size() != 4 ||
953 profile_str
[0] != '4' ||
954 profile_str
[1] != '2' ||
955 profile_str
[3] != '0' ||
956 !base::HexStringToUInt(base::StringPiece(profile_str
.c_str() + 2, 1),
957 &constraint_set_bits
)) {
961 return constraint_set_bits
>= 8;
964 static bool IsValidH264Level(const std::string
& level_str
) {
966 if (level_str
.size() != 2 || !base::HexStringToUInt(level_str
, &level
))
969 // Valid levels taken from Table A-1 in ISO-14496-10.
970 // Essentially |level_str| is toHex(10 * level).
971 return ((level
>= 10 && level
<= 13) ||
972 (level
>= 20 && level
<= 22) ||
973 (level
>= 30 && level
<= 32) ||
974 (level
>= 40 && level
<= 42) ||
975 (level
>= 50 && level
<= 51));
978 // Handle parsing H.264 codec IDs as outlined in RFC 6381 and ISO-14496-10.
979 // avc1.42y0xx, y >= 8 - H.264 Baseline
980 // avc1.4D40xx - H.264 Main
981 // avc1.6400xx - H.264 High
983 // avc1.xxxxxx & avc3.xxxxxx are considered ambiguous forms that are trying to
984 // signal H.264 Baseline. For example, the idc_level, profile_idc and
985 // constraint_set3_flag pieces may explicitly require decoder to conform to
986 // baseline profile at the specified level (see Annex A and constraint_set0 in
988 static bool ParseH264CodecID(const std::string
& codec_id
,
989 MimeUtil::Codec
* codec
,
990 bool* is_ambiguous
) {
991 // Make sure we have avc1.xxxxxx or avc3.xxxxxx
992 if (codec_id
.size() != 11 ||
993 (!StartsWithASCII(codec_id
, "avc1.", true) &&
994 !StartsWithASCII(codec_id
, "avc3.", true))) {
998 std::string profile
= StringToUpperASCII(codec_id
.substr(5, 4));
999 if (IsValidH264BaselineProfile(profile
)) {
1000 *codec
= MimeUtil::H264_BASELINE
;
1001 } else if (profile
== "4D40") {
1002 *codec
= MimeUtil::H264_MAIN
;
1003 } else if (profile
== "6400") {
1004 *codec
= MimeUtil::H264_HIGH
;
1006 *codec
= MimeUtil::H264_BASELINE
;
1007 *is_ambiguous
= true;
1011 *is_ambiguous
= !IsValidH264Level(StringToUpperASCII(codec_id
.substr(9)));
1015 bool MimeUtil::StringToCodec(const std::string
& codec_id
,
1017 bool* is_ambiguous
) const {
1018 StringToCodecMappings::const_iterator itr
=
1019 string_to_codec_map_
.find(codec_id
);
1020 if (itr
!= string_to_codec_map_
.end()) {
1021 *codec
= itr
->second
.codec
;
1022 *is_ambiguous
= itr
->second
.is_ambiguous
;
1026 // If |codec_id| is not in |string_to_codec_map_|, then we assume that it is
1027 // an H.264 codec ID because currently those are the only ones that can't be
1028 // stored in the |string_to_codec_map_| and require parsing.
1029 return ParseH264CodecID(codec_id
, codec
, is_ambiguous
);
1032 bool MimeUtil::IsCodecSupported(Codec codec
) const {
1033 DCHECK_NE(codec
, INVALID_CODEC
);
1035 #if defined(OS_ANDROID)
1036 if (!IsCodecSupportedOnAndroid(codec
))
1040 return allow_proprietary_codecs_
|| !IsCodecProprietary(codec
);
1043 bool MimeUtil::IsCodecProprietary(Codec codec
) const {
1048 case MPEG2_AAC_MAIN
:
1051 case MPEG4_AAC_SBR_v1
:
1052 case MPEG4_AAC_SBR_PS_v2
:
1070 bool MimeUtil::GetDefaultCodec(const std::string
& mime_type
,
1071 Codec
* default_codec
) const {
1072 if (mime_type
== "audio/mpeg" ||
1073 mime_type
== "audio/mp3" ||
1074 mime_type
== "audio/x-mp3") {
1075 *default_codec
= MimeUtil::MP3
;
1083 bool MimeUtil::IsDefaultCodecSupported(const std::string
& mime_type
) const {
1084 Codec default_codec
= Codec::INVALID_CODEC
;
1085 if (!GetDefaultCodec(mime_type
, &default_codec
))
1087 return IsCodecSupported(default_codec
);
1090 //----------------------------------------------------------------------------
1091 // Wrappers for the singleton
1092 //----------------------------------------------------------------------------
1094 bool GetMimeTypeFromExtension(const base::FilePath::StringType
& ext
,
1095 std::string
* mime_type
) {
1096 return g_mime_util
.Get().GetMimeTypeFromExtension(ext
, mime_type
);
1099 bool GetMimeTypeFromFile(const base::FilePath
& file_path
,
1100 std::string
* mime_type
) {
1101 return g_mime_util
.Get().GetMimeTypeFromFile(file_path
, mime_type
);
1104 bool GetWellKnownMimeTypeFromExtension(const base::FilePath::StringType
& ext
,
1105 std::string
* mime_type
) {
1106 return g_mime_util
.Get().GetWellKnownMimeTypeFromExtension(ext
, mime_type
);
1109 bool GetPreferredExtensionForMimeType(const std::string
& mime_type
,
1110 base::FilePath::StringType
* extension
) {
1111 return g_mime_util
.Get().GetPreferredExtensionForMimeType(mime_type
,
1115 bool IsSupportedImageMimeType(const std::string
& mime_type
) {
1116 return g_mime_util
.Get().IsSupportedImageMimeType(mime_type
);
1119 bool IsSupportedMediaMimeType(const std::string
& mime_type
) {
1120 return g_mime_util
.Get().IsSupportedMediaMimeType(mime_type
);
1123 bool IsSupportedNonImageMimeType(const std::string
& mime_type
) {
1124 return g_mime_util
.Get().IsSupportedNonImageMimeType(mime_type
);
1127 bool IsUnsupportedTextMimeType(const std::string
& mime_type
) {
1128 return g_mime_util
.Get().IsUnsupportedTextMimeType(mime_type
);
1131 bool IsSupportedJavascriptMimeType(const std::string
& mime_type
) {
1132 return g_mime_util
.Get().IsSupportedJavascriptMimeType(mime_type
);
1135 bool IsSupportedMimeType(const std::string
& mime_type
) {
1136 return g_mime_util
.Get().IsSupportedMimeType(mime_type
);
1139 bool MatchesMimeType(const std::string
& mime_type_pattern
,
1140 const std::string
& mime_type
) {
1141 return g_mime_util
.Get().MatchesMimeType(mime_type_pattern
, mime_type
);
1144 bool ParseMimeTypeWithoutParameter(const std::string
& type_string
,
1145 std::string
* top_level_type
,
1146 std::string
* subtype
) {
1147 return g_mime_util
.Get().ParseMimeTypeWithoutParameter(
1148 type_string
, top_level_type
, subtype
);
1151 bool IsValidTopLevelMimeType(const std::string
& type_string
) {
1152 return g_mime_util
.Get().IsValidTopLevelMimeType(type_string
);
1155 bool AreSupportedMediaCodecs(const std::vector
<std::string
>& codecs
) {
1156 return g_mime_util
.Get().AreSupportedMediaCodecs(codecs
);
1159 bool IsStrictMediaMimeType(const std::string
& mime_type
) {
1160 return g_mime_util
.Get().IsStrictMediaMimeType(mime_type
);
1163 SupportsType
IsSupportedStrictMediaMimeType(
1164 const std::string
& mime_type
,
1165 const std::vector
<std::string
>& codecs
) {
1166 return g_mime_util
.Get().IsSupportedStrictMediaMimeType(mime_type
, codecs
);
1169 void ParseCodecString(const std::string
& codecs
,
1170 std::vector
<std::string
>* codecs_out
,
1172 g_mime_util
.Get().ParseCodecString(codecs
, codecs_out
, strip
);
1177 // From http://www.w3schools.com/media/media_mimeref.asp and
1178 // http://plugindoc.mozdev.org/winmime.php
1179 static const char* const kStandardImageTypes
[] = {
1191 "image/vnd.microsoft.icon",
1192 "image/x-cmu-raster",
1195 "image/x-portable-anymap",
1196 "image/x-portable-bitmap",
1197 "image/x-portable-graymap",
1198 "image/x-portable-pixmap",
1202 "image/x-xwindowdump"
1204 static const char* const kStandardAudioTypes
[] = {
1220 "audio/vnd.rn-realaudio",
1223 static const char* const kStandardVideoTypes
[] = {
1240 struct StandardType
{
1241 const char* leading_mime_type
;
1242 const char* const* standard_types
;
1243 size_t standard_types_len
;
1245 static const StandardType kStandardTypes
[] = {
1246 { "image/", kStandardImageTypes
, arraysize(kStandardImageTypes
) },
1247 { "audio/", kStandardAudioTypes
, arraysize(kStandardAudioTypes
) },
1248 { "video/", kStandardVideoTypes
, arraysize(kStandardVideoTypes
) },
1252 void GetExtensionsFromHardCodedMappings(
1253 const MimeInfo
* mappings
,
1254 size_t mappings_len
,
1255 const std::string
& leading_mime_type
,
1256 base::hash_set
<base::FilePath::StringType
>* extensions
) {
1257 base::FilePath::StringType extension
;
1258 for (size_t i
= 0; i
< mappings_len
; ++i
) {
1259 if (StartsWithASCII(mappings
[i
].mime_type
, leading_mime_type
, false)) {
1260 std::vector
<string
> this_extensions
;
1261 base::SplitString(mappings
[i
].extensions
, ',', &this_extensions
);
1262 for (size_t j
= 0; j
< this_extensions
.size(); ++j
) {
1264 base::FilePath::StringType
extension(
1265 base::UTF8ToWide(this_extensions
[j
]));
1267 base::FilePath::StringType
extension(this_extensions
[j
]);
1269 extensions
->insert(extension
);
1275 void GetExtensionsHelper(
1276 const char* const* standard_types
,
1277 size_t standard_types_len
,
1278 const std::string
& leading_mime_type
,
1279 base::hash_set
<base::FilePath::StringType
>* extensions
) {
1280 for (size_t i
= 0; i
< standard_types_len
; ++i
) {
1281 g_mime_util
.Get().GetPlatformExtensionsForMimeType(standard_types
[i
],
1285 // Also look up the extensions from hard-coded mappings in case that some
1286 // supported extensions are not registered in the system registry, like ogg.
1287 GetExtensionsFromHardCodedMappings(primary_mappings
,
1288 arraysize(primary_mappings
),
1292 GetExtensionsFromHardCodedMappings(secondary_mappings
,
1293 arraysize(secondary_mappings
),
1298 // Note that the elements in the source set will be appended to the target
1301 void HashSetToVector(base::hash_set
<T
>* source
, std::vector
<T
>* target
) {
1302 size_t old_target_size
= target
->size();
1303 target
->resize(old_target_size
+ source
->size());
1305 for (typename
base::hash_set
<T
>::iterator iter
= source
->begin();
1306 iter
!= source
->end(); ++iter
, ++i
)
1307 (*target
)[old_target_size
+ i
] = *iter
;
1311 void GetExtensionsForMimeType(
1312 const std::string
& unsafe_mime_type
,
1313 std::vector
<base::FilePath::StringType
>* extensions
) {
1314 if (unsafe_mime_type
== "*/*" || unsafe_mime_type
== "*")
1317 const std::string mime_type
= base::StringToLowerASCII(unsafe_mime_type
);
1318 base::hash_set
<base::FilePath::StringType
> unique_extensions
;
1320 if (EndsWith(mime_type
, "/*", true)) {
1321 std::string leading_mime_type
= mime_type
.substr(0, mime_type
.length() - 1);
1323 // Find the matching StandardType from within kStandardTypes, or fall
1324 // through to the last (default) StandardType.
1325 const StandardType
* type
= NULL
;
1326 for (size_t i
= 0; i
< arraysize(kStandardTypes
); ++i
) {
1327 type
= &(kStandardTypes
[i
]);
1328 if (type
->leading_mime_type
&&
1329 leading_mime_type
== type
->leading_mime_type
)
1333 GetExtensionsHelper(type
->standard_types
,
1334 type
->standard_types_len
,
1336 &unique_extensions
);
1338 g_mime_util
.Get().GetPlatformExtensionsForMimeType(mime_type
,
1339 &unique_extensions
);
1341 // Also look up the extensions from hard-coded mappings in case that some
1342 // supported extensions are not registered in the system registry, like ogg.
1343 GetExtensionsFromHardCodedMappings(primary_mappings
,
1344 arraysize(primary_mappings
),
1346 &unique_extensions
);
1348 GetExtensionsFromHardCodedMappings(secondary_mappings
,
1349 arraysize(secondary_mappings
),
1351 &unique_extensions
);
1354 HashSetToVector(&unique_extensions
, extensions
);
1357 void RemoveProprietaryMediaTypesAndCodecsForTests() {
1358 g_mime_util
.Get().RemoveProprietaryMediaTypesAndCodecsForTests();
1361 const std::string
GetIANAMediaType(const std::string
& mime_type
) {
1362 for (size_t i
= 0; i
< arraysize(kIanaMediaTypes
); ++i
) {
1363 if (StartsWithASCII(mime_type
, kIanaMediaTypes
[i
].matcher
, true)) {
1364 return kIanaMediaTypes
[i
].name
;
1367 return std::string();
1370 CertificateMimeType
GetCertificateMimeTypeForMimeType(
1371 const std::string
& mime_type
) {
1372 // Don't create a map, there is only one entry in the table,
1373 // except on Android.
1374 for (size_t i
= 0; i
< arraysize(supported_certificate_types
); ++i
) {
1375 if (mime_type
== net::supported_certificate_types
[i
].mime_type
)
1376 return net::supported_certificate_types
[i
].cert_type
;
1378 return CERTIFICATE_MIME_TYPE_UNKNOWN
;
1381 bool IsSupportedCertificateMimeType(const std::string
& mime_type
) {
1382 CertificateMimeType file_type
=
1383 GetCertificateMimeTypeForMimeType(mime_type
);
1384 return file_type
!= CERTIFICATE_MIME_TYPE_UNKNOWN
;
1387 void AddMultipartValueForUpload(const std::string
& value_name
,
1388 const std::string
& value
,
1389 const std::string
& mime_boundary
,
1390 const std::string
& content_type
,
1391 std::string
* post_data
) {
1393 // First line is the boundary.
1394 post_data
->append("--" + mime_boundary
+ "\r\n");
1395 // Next line is the Content-disposition.
1396 post_data
->append("Content-Disposition: form-data; name=\"" +
1397 value_name
+ "\"\r\n");
1398 if (!content_type
.empty()) {
1399 // If Content-type is specified, the next line is that.
1400 post_data
->append("Content-Type: " + content_type
+ "\r\n");
1402 // Leave an empty line and append the value.
1403 post_data
->append("\r\n" + value
+ "\r\n");
1406 void AddMultipartFinalDelimiterForUpload(const std::string
& mime_boundary
,
1407 std::string
* post_data
) {
1409 post_data
->append("--" + mime_boundary
+ "--\r\n");