diff options
author | dalecurtis@chromium.org <dalecurtis@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-08-29 08:59:31 +0000 |
---|---|---|
committer | dalecurtis@chromium.org <dalecurtis@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2013-08-29 08:59:31 +0000 |
commit | 4e93e98d8cc8751f6e092edd455e87ee81727491 (patch) | |
tree | db1e00b2d2243d062175a4647db3af4c769be75d /media/tools | |
parent | 866fda545102b4815f80619f4401541b1a7568ae (diff) | |
download | chromium_src-4e93e98d8cc8751f6e092edd455e87ee81727491.zip chromium_src-4e93e98d8cc8751f6e092edd455e87ee81727491.tar.gz chromium_src-4e93e98d8cc8751f6e092edd455e87ee81727491.tar.bz2 |
Summer cleaning, media/ style!
Removes a bunch of unused code and utilities.
BUG=none
TEST=compiles, passes CQ.
Review URL: https://chromiumcodereview.appspot.com/23058004
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@220227 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'media/tools')
-rwxr-xr-x | media/tools/bug_hunter/bug_hunter.py | 380 | ||||
-rw-r--r-- | media/tools/bug_hunter/bug_hunter_test.py | 96 | ||||
-rw-r--r-- | media/tools/bug_hunter/bug_hunter_unittest.py | 182 | ||||
-rw-r--r-- | media/tools/media_bench/media_bench.cc | 588 | ||||
-rw-r--r-- | media/tools/seek_tester/seek_tester.cc | 112 | ||||
-rw-r--r-- | media/tools/shader_bench/cpu_color_painter.cc | 96 | ||||
-rw-r--r-- | media/tools/shader_bench/cpu_color_painter.h | 33 | ||||
-rw-r--r-- | media/tools/shader_bench/gpu_color_painter.cc | 122 | ||||
-rw-r--r-- | media/tools/shader_bench/gpu_color_painter.h | 35 | ||||
-rw-r--r-- | media/tools/shader_bench/gpu_painter.cc | 92 | ||||
-rw-r--r-- | media/tools/shader_bench/gpu_painter.h | 44 | ||||
-rw-r--r-- | media/tools/shader_bench/painter.cc | 26 | ||||
-rw-r--r-- | media/tools/shader_bench/painter.h | 39 | ||||
-rw-r--r-- | media/tools/shader_bench/shader_bench.cc | 162 | ||||
-rw-r--r-- | media/tools/shader_bench/window.cc | 19 | ||||
-rw-r--r-- | media/tools/shader_bench/window.h | 61 | ||||
-rw-r--r-- | media/tools/shader_bench/window_linux.cc | 87 | ||||
-rw-r--r-- | media/tools/shader_bench/window_win.cc | 134 |
18 files changed, 0 insertions, 2308 deletions
diff --git a/media/tools/bug_hunter/bug_hunter.py b/media/tools/bug_hunter/bug_hunter.py deleted file mode 100755 index 19a2f8f..0000000 --- a/media/tools/bug_hunter/bug_hunter.py +++ /dev/null @@ -1,380 +0,0 @@ -#!/usr/bin/env python -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""This script queries the Chromium issue tracker and e-mails the results. - -It queries issue tracker using Issue Tracker API. The query -parameters can be specified by command-line arguments. For example, with the -following command: - - 'python bug_hunter.py -q video Status:Unconfirmed OR audio Status:Unconfirmed - -s sender@chromium.org -r receiver@chromium.org -v 100 -u days' - -You will find all 'Unconfirmed' issues created in the last 100 days containing -'video' or 'audio' in their content/comments. The content of these issues are -sent to receiver@chromium.org. - -TODO(imasaki): users can specify the interval as say: "100d" for "100 days". - -There are two limitations in the current implementation of issue tracker API -and UI: -* only outermost OR is valid. For example, the query - 'video OR audio Status:Unconfirmed' is translated into - 'video OR (audio AND Status:Unconfirmed)' -* brackets are not supported. For example, the query - '(video OR audio) Status:Unconfirmed' does not work. - -You need to install following to run this script - gdata-python-client (http://code.google.com/p/gdata-python-client/) - rfc3339.py (http://henry.precheur.org/projects/rfc3339) - -Links: -* Chromium issue tracker: http://code.google.com/p/chromium/issues/list -* Issue tracker API: http://code.google.com/p/support/wiki/IssueTrackerAPI -* Search tips for the issue tracker: - http://code.google.com/p/chromium/issues/searchtips -""" - -import csv -import datetime -from email.mime.multipart import MIMEMultipart -from email.mime.text import MIMEText -import logging -from operator import itemgetter -import optparse -import re -import smtplib -import socket -import sys -import urllib - -try: - import gdata.data - import gdata.projecthosting.client -except ImportError: - logging.error('gdata-client needs to be installed. Please install\n' - 'and try again (http://code.google.com/p/gdata-python-client/)') - sys.exit(1) - -try: - import rfc3339 -except ImportError: - logging.error('rfc3339 needs to be installed. Please install\n' - 'and try again (http://henry.precheur.org/projects/rfc3339)') - sys.exit(1) - -# A list of default values. -_DEFAULT_INTERVAL_UNIT = 'hours' -_DEFAULT_ISSUE_ELEMENT_IN_EMAIL = ('author', 'status', 'state', 'content', - 'comments', 'labels', 'urls') -_DEFAULT_PROJECT_NAME = 'chromium' -_DEFAULT_QUERY_TITLE = 'potential media bugs' -_DEFAULT_QUERY = ('video -has:Feature -has:Owner -label:nomedia ' - 'status:Unconfirmed OR audio -has:Feature -has:Owner ' - '-label:nomedia status:Unconfirmed') -_DEFAULT_OUTPUT_FILENAME = 'output.csv' -_DETAULT_MAX_COMMENTS = 1000 - -_INTERVAL_UNIT_CHOICES = ('hours', 'days', 'weeks') - -# URLs in this list are excluded from URL extraction from bug -# content/comments. Each list element should not contain the url ending in -# '/'. For example, the element should be 'http://www.google.com' but not -# 'http://www.google.com/' -_URL_EXCLUSION_LIST = ('http://www.youtube.com/html5', - 'http://www.google.com') -_ISSUE_ELEMENT_IN_EMAIL_CHOICES = ('issue_id', 'author', 'status', 'state', - 'content', 'comments', 'labels', 'urls', - 'mstone') - - -def ParseArgs(): - """Returns options dictionary from parsed command line arguments.""" - parser = optparse.OptionParser() - - parser.add_option('-e', '--email-entries', - help=('A comma-separated list of issue entries that are ' - 'sent in the email content. ' - 'Possible strings are %s. Default: %%default.' % - ', '.join(_ISSUE_ELEMENT_IN_EMAIL_CHOICES)), - default=','.join(_DEFAULT_ISSUE_ELEMENT_IN_EMAIL)) - parser.add_option('-l', '--max-comments', - help=('The maximum number of comments returned for each ' - 'issue in a reverse chronological order. ' - 'Default: %default.'), - type='int', default=_DETAULT_MAX_COMMENTS) - parser.add_option('-o', '--output-filename', - help=('Filename for result output in CSV format. ' - 'Default: %default.'), - default=_DEFAULT_OUTPUT_FILENAME, metavar='FILE') - parser.add_option('-p', '--project-name', default=_DEFAULT_PROJECT_NAME, - help='Project name string. Default: %default') - parser.add_option('-q', '--query', default=_DEFAULT_QUERY, - help=('Query to be used to find bugs. The detail can be ' - 'found in Chromium Issue tracker page ' - 'http://code.google.com/p/chromium/issues/searchtips.' - ' Default: "%default".')) - parser.add_option('-r', '--receiver-email-address', - help="Receiver's email address (Required).") - parser.add_option('-s', '--sender-email-address', - help="Sender's email address (Required).") - parser.add_option('-t', '--query-title', - default=_DEFAULT_QUERY_TITLE, dest='query_title', - help=('Query title string used in the subject of the ' - 'result email. Default: %default.')) - parser.add_option('-u', '--interval_unit', default=_DEFAULT_INTERVAL_UNIT, - choices=_INTERVAL_UNIT_CHOICES, - help=('Unit name for |interval_value|. Valid options are ' - '%s. Default: %%default' % ( - ', '.join(_INTERVAL_UNIT_CHOICES)))) - parser.add_option('-v', '--interval-value', type='int', - help=('Interval value to find bugs. ' - 'The script looks for bugs during ' - 'that interval (up to now). This option is used in ' - 'conjunction with |--interval_unit| option. ' - 'The script looks for all bugs if this is not ' - 'specified.')) - - options = parser.parse_args()[0] - - options.email_entries = options.email_entries.split(',') - options.email_entries = [entry for entry in options.email_entries - if entry in _ISSUE_ELEMENT_IN_EMAIL_CHOICES] - if not options.email_entries: - logging.warning('No issue elements in email in option. ' - 'Default email entries will be used.') - options.email_entries = _DEFAULT_ISSUE_ELEMENT_IN_EMAIL - logging.info('The following is the issue elements in email: %s ' + ( - ', '.join(options.email_entries))) - return options - - -class BugHunter(object): - """This class queries issue trackers and e-mails the results.""" - - _ISSUE_SEARCH_LINK_BASE = ('http://code.google.com/p/chromium/issues/list?' - 'can=2&colspec=ID+Pri+Mstone+ReleaseBlock+Area' - '+Feature+Status+Owner+Summary&cells=tiles' - '&sort=-id') - # TODO(imasaki): Convert these into template library. - _EMAIL_ISSUE_TEMPLATE = ('<li><a href="http://crbug.com/%(issue_id)s">' - '%(issue_id)s %(title)s</a> ') - _EMAIL_SUBJECT_TEMPLATE = ('BugHunter found %(n_issues)d %(query_title)s ' - 'bug%(plural)s%(time_msg)s!') - _EMAIL_MSG_TEMPLATE = ('<a href="%(link_base)s&q=%(unquote_query_text)s">' - 'Used Query</a>: %(query_text)s<br><br>' - 'The number of issues : %(n_issues)d<br>' - '<ul>%(issues)s</ul>') - - def __init__(self, options): - """Sets up initial state for Bug Hunter. - - Args: - options: Command-line options. - """ - self._client = gdata.projecthosting.client.ProjectHostingClient() - self._options = options - self._issue_template = BugHunter._EMAIL_ISSUE_TEMPLATE - for entry in options.email_entries: - self._issue_template += '%%(%s)s ' % entry - self._issue_template += '</li>' - - def GetComments(self, issue_id, max_comments): - """Get comments for a issue. - - Args: - issue_id: Issue id for each issue in the issue tracker. - max_comments: The maximum number of comments to be returned. The comments - are returned in a reverse chronological order. - - Returns: - A list of (author name, comments, updated time) tuples. - """ - comments_feed = self._client.get_comments(self._options.project_name, - issue_id) - comment_list = [(comment.content.text, comment.author[0].name.text, - comment.updated.text) - for comment - in list(reversed(comments_feed.entry))[0:max_comments]] - return comment_list - - def GetIssues(self): - """Get issues from issue tracker and return them. - - Returns: - A list of issues in descending order by issue_id. Each element in the - list is a dictionary where the keys are 'issue_id', 'title', 'author', - 'status', 'state', 'content', 'comments', 'labels', 'urls'. - Returns an empty list when there is no matching issue. - """ - min_time = None - if self._options.interval_value: - # Issue Tracker Data API uses RFC 3339 timestamp format, For example: - # 2005-08-09T10:57:00-08:00 - # (http://code.google.com/p/support/wiki/IssueTrackerAPIPython) - delta = datetime.timedelta( - **{self._options.interval_unit: self._options.interval_value}) - dt = datetime.datetime.now() - delta - min_time = rfc3339.rfc3339(dt) - - query = gdata.projecthosting.client.Query(text_query=self._options.query, - max_results=1000, - published_min=min_time) - - feed = self._client.get_issues(self._options.project_name, query=query) - if not feed.entry: - logging.info('No issues available to match query %s.', - self._options.query) - return [] - issues = [] - for entry in feed.entry: - # The fully qualified id is a URL. We just want the number. - issue_id = entry.id.text.split('/')[-1] - if not issue_id.isdigit(): - logging.warning('Issue_id is not correct: %s. Skipping.', issue_id) - continue - label_list = [label.text for label in entry.label] - comments = '' - if 'comments' in self._options.email_entries: - comments = ''.join( - [''.join(comment) if not comment else '' - for comment - in self.GetComments(issue_id, self._options.max_comments)]) - content = BugHunterUtils.StripHTML(entry.content.text) - url_list = list( - set(re.findall(r'(https?://\S+)', content + comments))) - url_list = [url for url in url_list - if not url.rstrip('/') in _URL_EXCLUSION_LIST] - mstone = '' - r = re.compile(r'Mstone-(\d*)') - for label in label_list: - m = r.search(label) - if m: - mstone = m.group(1) - issues.append( - {'issue_id': issue_id, 'title': entry.title.text, - 'author': entry.author[0].name.text, - 'status': entry.status.text if entry.status is not None else '', - 'state': entry.state.text if entry.state is not None else '', - 'content': content, 'mstone': mstone, 'comments': comments, - 'labels': label_list, 'urls': url_list}) - return sorted(issues, key=itemgetter('issue_id'), reverse=True) - - def _SetUpEmailSubjectMsg(self, issues): - """Set up email subject and its content. - - Args: - issues: Please refer to the return value in GetIssues(). - - Returns: - A tuple of two strings (email subject and email content). - """ - time_msg = '' - if self._options.interval_value: - time_msg = ' in the past %s %s%s' % ( - self._options.interval_value, self._options.interval_unit[:-1], - 's' if self._options.interval_value > 1 else '') - subject = BugHunter._EMAIL_SUBJECT_TEMPLATE % { - 'n_issues': len(issues), - 'query_title': self._options.query_title, - 'plural': 's' if len(issues) > 1 else '', - 'time_msg': time_msg} - content = BugHunter._EMAIL_MSG_TEMPLATE % { - 'link_base': BugHunter._ISSUE_SEARCH_LINK_BASE, - 'unquote_query_text': urllib.quote(self._options.query), - 'query_text': self._options.query, - 'n_issues': len(issues), - 'issues': ''.join( - [self._issue_template % issue for issue in issues])} - return (subject, content) - - def SendResultEmail(self, issues): - """Send result email. - - Args: - issues: Please refer to the return value in GetIssues(). - """ - subject, content = self._SetUpEmailSubjectMsg(issues) - BugHunterUtils.SendEmail( - content, self._options.sender_email_address, - self._options.receiver_email_address, subject) - - def WriteIssuesToFileInCSV(self, issues, filename): - """Write issues to a file in CSV format. - - Args: - issues: Please refer to the return value in GetIssues(). - filename: File name for CSV file. - """ - with open(filename, 'w') as f: - writer = csv.writer(f) - # Write header first. - writer.writerow(issues[0].keys()) - for issue in issues: - writer.writerow( - [unicode(value).encode('utf-8') for value in issue.values()]) - - -class BugHunterUtils(object): - """Utility class for Bug Hunter.""" - - @staticmethod - def StripHTML(string_with_html): - """Strip HTML tags from string. - - Args: - string_with_html: A string with HTML tags. - - Returns: - A string without HTML tags. - """ - return re.sub('<[^<]+?>', '', string_with_html) - - @staticmethod - def SendEmail(message, sender_email_address, receivers_email_address, - subject): - """Send email using localhost's mail server. - - Args: - message: Email message to be sent. - sender_email_address: Sender's email address. - receivers_email_address: Receiver's email address. - subject: Email subject. - - Returns: - True if successful; False, otherwise. - """ - try: - html = '<html><head></head><body>%s</body></html>' % message - msg = MIMEMultipart('alternative') - msg['Subject'] = subject - msg['From'] = sender_email_address - msg['To'] = receivers_email_address - msg.attach(MIMEText(html.encode('utf-8'), 'html', _charset='utf-8')) - smtp_obj = smtplib.SMTP('localhost') - smtp_obj.sendmail(sender_email_address, receivers_email_address, - msg.as_string()) - logging.info('Successfully sent email.') - smtp_obj.quit() - return True - except smtplib.SMTPException: - logging.exception('Authentication failed, unable to send email.') - except (socket.gaierror, socket.error, socket.herror): - logging.exception('Unable to send email.') - return False - - -def Main(): - ops = ParseArgs() - bh = BugHunter(ops) - issues = bh.GetIssues() - if issues and ops.sender_email_address and ops.receiver_email_address: - bh.SendResultEmail(issues) - if issues: - bh.WriteIssuesToFileInCSV(issues, ops.output_filename) - - -if __name__ == '__main__': - Main() diff --git a/media/tools/bug_hunter/bug_hunter_test.py b/media/tools/bug_hunter/bug_hunter_test.py deleted file mode 100644 index 0dafd8a..0000000 --- a/media/tools/bug_hunter/bug_hunter_test.py +++ /dev/null @@ -1,96 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Integration tests for bug hunter.""" - -import csv -from optparse import Values -import os -import unittest - -from bug_hunter import BugHunter - -try: - import gdata.data - import gdata.projecthosting.client -except ImportError: - logging.error('gdata-client needs to be installed. Please install\n' - 'and try again (http://code.google.com/p/gdata-python-client/)') - sys.exit(1) - - -class BugHunterTest(unittest.TestCase): - """Unit tests for the Bug Hunter class.""" - _TEST_FILENAME = 'test.csv' - - def _CleanTestFile(self): - if os.path.exists(self._TEST_FILENAME): - os.remove(self._TEST_FILENAME) - - def setUp(self): - self._CleanTestFile() - - def tearDown(self): - self._CleanTestFile() - - def _GetIssue(self): - return [{'issue_id': '0', 'title': 'title', 'author': 'author', - 'status': 'status', 'state': 'state', 'content': 'content', - 'comments': [], 'labels': [], 'urls': []}] - - def _GetDefaultOption(self, set_10_days_ago, query='steps'): - ops = Values() - ops.query = query - if set_10_days_ago: - ops.interval_value = 10 - ops.interval_unit = 'days' - else: - ops.interval_value = None - ops.email_entries = ['comments'] - ops.project_name = 'chromium' - ops.query_title = 'query title' - ops.max_comments = None - return ops - - def testGetIssueReturnedIssue(self): - bh = BugHunter( - self._GetDefaultOption(False, - query=('audio opened-after:2010/10/10' - ' opened-before:2010/10/20'))) - self.assertEquals(len(bh.GetIssues()), 18) - - def testGetIssueReturnedIssueWithStatus(self): - ops = self._GetDefaultOption(False) - ops.query = 'Feature:Media* Status:Unconfirmed' - issues = BugHunter(ops).GetIssues() - for issue in issues: - self.assertEquals(issue['status'], 'Unconfirmed') - - def testGetIssueReturnNoIssue(self): - ops = self._GetDefaultOption(True) - ops.query = 'thisshouldnotmatchpleaseignorethis*' - self.assertFalse(BugHunter(ops).GetIssues()) - - def testGetComments(self): - comments = BugHunter(self._GetDefaultOption(False)).GetComments(100000, 2) - self.assertEquals(len(comments), 2) - expected_comments = [(None, 'rby...@chromium.org', - '2011-10-31T19:54:40.000Z'), - (None, 'backer@chromium.org', - '2011-10-14T13:59:37.000Z')] - self.assertEquals(comments, expected_comments) - - def testWriteIssuesToFileInCSV(self): - ops = self._GetDefaultOption(False) - bh = BugHunter(ops) - bh.WriteIssuesToFileInCSV(self._GetIssue(), self._TEST_FILENAME) - - with open(self._TEST_FILENAME, 'r') as f: - reader = csv.reader(f) - self.assertEquals(reader.next(), ['status', 'content', 'state', - 'issue_id', 'urls', 'title', 'labels', - 'author', 'comments']) - self.assertEquals(reader.next(), ['status', 'content', 'state', '0', - '[]', 'title', '[]', 'author', '[]']) - self.assertRaises(StopIteration, reader.next) diff --git a/media/tools/bug_hunter/bug_hunter_unittest.py b/media/tools/bug_hunter/bug_hunter_unittest.py deleted file mode 100644 index 0cb11b6..0000000 --- a/media/tools/bug_hunter/bug_hunter_unittest.py +++ /dev/null @@ -1,182 +0,0 @@ -# Copyright (c) 2012 The Chromium Authors. All rights reserved. -# Use of this source code is governed by a BSD-style license that can be -# found in the LICENSE file. - -"""Unit Tests for bug hunter.""" - -import logging -from optparse import Values -import smtplib -import sys -import unittest - -from bug_hunter import BugHunter -from bug_hunter import BugHunterUtils - -try: - import atom.data - import gdata.data - import gdata.projecthosting.client -except ImportError: - logging.error('gdata-client needs to be installed. Please install\n' - 'and try again (http://code.google.com/p/gdata-python-client/)') - sys.exit(1) - - -class MockClient(object): - """A mock class for gdata.projecthosting.client.ProjectHostingClient. - - Mocking the very simple method invocations for get_issues() and - get_comments(). - """ - - def _CreateIssues(self, n_issues): - feed = gdata.projecthosting.data.IssuesFeed() - for i in xrange(n_issues): - feed.entry.append(gdata.projecthosting.data.IssueEntry( - title=atom.data.Title(text='title'), - content=atom.data.Content(text='http://www.content.com'), - id=atom.data.Id(text='/' + str(i)), - status=gdata.projecthosting.data.Status(text='Unconfirmed'), - state=gdata.projecthosting.data.State(text='open'), - label=[gdata.projecthosting.data.Label('label1')], - author=[atom.data.Author(name=atom.data.Name(text='author'))])) - return feed - - def get_issues(self, project_name, query): - """Get issues using mock object without calling the issue tracker API. - - Based on query argument, this returns the dummy issues. The number of - dummy issues are specified in query.text_query. - - Args: - project_name: A string for project name in the issue tracker. - query: A query object for querying the issue tracker. - - Returns: - A IssuesFeed object that contains a simple test issue. - """ - n_issues = 1 - if query.text_query.isdigit(): - n_issues = int(query.text_query) - return self._CreateIssues(n_issues) - - def get_comments(self, project_name, issue_id): - """Get comments using mock object without calling the issue tracker API. - - Args: - project_name: A string for project name in the issue tracker. - issue_id: Issue_id string. - - Returns: - A CommentsFeed object that contains a simple test comment. - """ - feed = gdata.projecthosting.data.CommentsFeed() - feed.entry = [gdata.projecthosting.data.CommentEntry( - id=atom.data.Id(text='/0'), - content=atom.data.Content(text='http://www.comments.com'), - updated=atom.data.Updated(text='Updated'), - author=[atom.data.Author(name=atom.data.Name(text='cauthor'))])] - return feed - - -class BugHunterUnitTest(unittest.TestCase): - """Unit tests for the Bug Hunter class.""" - - def setUp(self): - self._old_client = gdata.projecthosting.client.ProjectHostingClient - gdata.projecthosting.client.ProjectHostingClient = MockClient - - def tearDown(self): - gdata.projecthosting.client.ProjectHostingClient = self._old_client - - def _GetDefaultOption(self, set_10_days_ago, query='steps'): - ops = Values() - ops.query = query - if set_10_days_ago: - ops.interval_value = 10 - ops.interval_unit = 'days' - else: - ops.interval_value = None - ops.email_entries = ['comments'] - ops.project_name = 'chromium' - ops.query_title = 'query title' - ops.max_comments = None - return ops - - def _GetIssue(self, n_issues): - issues = [] - for i in xrange(n_issues): - issues.append({'issue_id': str(i), 'title': 'title', 'author': 'author', - 'status': 'status', 'state': 'state', - 'content': 'content', 'comments': [], - 'labels': [], 'urls': []}) - return issues - - def testSetUpEmailSubjectMsg(self): - bh = BugHunter(self._GetDefaultOption(False)) - subject, content = bh._SetUpEmailSubjectMsg(self._GetIssue(1)) - self.assertEquals(subject, - 'BugHunter found 1 query title bug!') - self.assertEquals(content, - ('<a href="http://code.google.com/p/chromium/issues/' - 'list?can=2&colspec=ID+Pri+Mstone+ReleaseBlock+Area+' - 'Feature+Status+Owner+Summary&cells=tiles&sort=-id&' - 'q=steps">Used Query</a>: steps<br><br>The number of ' - 'issues : 1<br><ul><li><a href="http://crbug.com/0">0 ' - 'title</a> [] </li></ul>')) - - def testSetUpEmailSubjectMsgMultipleIssues(self): - bh = BugHunter(self._GetDefaultOption(False)) - subject, content = bh._SetUpEmailSubjectMsg(self._GetIssue(2)) - self.assertEquals(subject, - 'BugHunter found 2 query title bugs!') - - def testSetUpEmailSubjectMsgWith10DaysAgoAndAssertSubject(self): - bh = BugHunter(self._GetDefaultOption(True)) - subject, _ = bh._SetUpEmailSubjectMsg(self._GetIssue(1)) - self.assertEquals(subject, - ('BugHunter found 1 query title bug in the past 10 ' - 'days!')) - - def testGetIssuesWithMockClient(self): - bh = BugHunter(self._GetDefaultOption(False, - query=('dummy'))) - expected_issues = [{'issue_id': '0', 'title': 'title', 'author': 'author', - 'status': 'Unconfirmed', 'state': 'open', - 'content': 'http://www.content.com', - 'comments': '', 'labels': ['label1'], - 'urls': ['http://www.content.com']}] - self.assertEquals(expected_issues, bh.GetIssues()) - - -class MockSmtp(object): - """A mock class for SMTP.""" - - def __init__(self, server): - pass - - def sendmail(self, sender_email_address, receivers_email_addresses, - msg): - # TODO(imasaki): Do something here. - return True - - def quit(self): - pass - - -class BugHunterUtilsTest(unittest.TestCase): - """Unit tests for the Bug Hunter utility.""" - - def testStripHTML(self): - self.assertEquals(BugHunterUtils.StripHTML('<p>X</p>'), 'X') - - def testStripHTMLEmpty(self): - self.assertEquals(BugHunterUtils.StripHTML(''), '') - - def testSendEmail(self): - smtplib.SMTP = MockSmtp - self.assertEqual(BugHunterUtils.SendEmail('message', 'sender_email_address', - 'receivers_email_addresses', - 'subject'), - True) diff --git a/media/tools/media_bench/media_bench.cc b/media/tools/media_bench/media_bench.cc deleted file mode 100644 index 4214988..0000000 --- a/media/tools/media_bench/media_bench.cc +++ /dev/null @@ -1,588 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -// Standalone benchmarking application based on FFmpeg. This tool is used to -// measure decoding performance between different FFmpeg compile and run-time -// options. We also use this tool to measure performance regressions when -// testing newer builds of FFmpeg from trunk. - -#include <iomanip> -#include <iostream> -#include <string> - -#include "base/at_exit.h" -#include "base/basictypes.h" -#include "base/command_line.h" -#include "base/file_util.h" -#include "base/files/file_path.h" -#include "base/files/memory_mapped_file.h" -#include "base/logging.h" -#include "base/md5.h" -#include "base/path_service.h" -#include "base/strings/string_number_conversions.h" -#include "base/strings/string_util.h" -#include "base/strings/utf_string_conversions.h" -#include "base/time/time.h" -#include "build/build_config.h" -#include "media/base/djb2.h" -#include "media/base/media.h" -#include "media/ffmpeg/ffmpeg_common.h" -#include "media/filters/ffmpeg_glue.h" -#include "media/filters/ffmpeg_video_decoder.h" -#include "media/filters/in_memory_url_protocol.h" - -// For pipe _setmode to binary -#if defined(OS_WIN) -#include <fcntl.h> -#include <io.h> -#endif - -namespace switches { -const char kStream[] = "stream"; -const char kVideoThreads[] = "video-threads"; -const char kFast2[] = "fast2"; -const char kErrorCorrection[] = "error-correction"; -const char kSkip[] = "skip"; -const char kFlush[] = "flush"; -const char kDjb2[] = "djb2"; -const char kMd5[] = "md5"; -const char kFrames[] = "frames"; -const char kLoop[] = "loop"; - -} // namespace switches - -#if defined(OS_WIN) - -// Enable to build with exception handler -// #define ENABLE_WINDOWS_EXCEPTIONS 1 - -#ifdef ENABLE_WINDOWS_EXCEPTIONS -// warning: disable warning about exception handler. -#pragma warning(disable:4509) -#endif - -// Thread priorities to make benchmark more stable. - -void EnterTimingSection() { - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); -} - -void LeaveTimingSection() { - SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_NORMAL); -} -#else -void EnterTimingSection() { - pthread_attr_t pta; - struct sched_param param; - - pthread_attr_init(&pta); - memset(¶m, 0, sizeof(param)); - param.sched_priority = 78; - pthread_attr_setschedparam(&pta, ¶m); - pthread_attr_destroy(&pta); -} - -void LeaveTimingSection() { -} -#endif - -int main(int argc, const char** argv) { - base::AtExitManager exit_manager; - - CommandLine::Init(argc, argv); - - logging::LoggingSettings settings; - settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG; - logging::InitLogging(settings); - - const CommandLine* cmd_line = CommandLine::ForCurrentProcess(); - const CommandLine::StringVector& filenames = cmd_line->GetArgs(); - if (filenames.empty()) { - std::cerr << "Usage: " << argv[0] << " [OPTIONS] FILE [DUMPFILE]\n" - << " --stream=[audio|video] " - << "Benchmark either the audio or video stream\n" - << " --video-threads=N " - << "Decode video using N threads\n" - << " --frames=N " - << "Decode N frames\n" - << " --loop=N " - << "Loop N times\n" - << " --fast2 " - << "Enable fast2 flag\n" - << " --error-correction " - << "Enable ffmpeg error correction\n" - << " --flush " - << "Flush last frame\n" - << " --djb2 (aka --hash) " - << "Hash decoded buffers (DJB2)\n" - << " --md5 " - << "Hash decoded buffers (MD5)\n" - << " --skip=[1|2|3] " - << "1=loop nonref, 2=loop, 3= frame nonref\n" << std::endl; - return 1; - } - - // Initialize our media library (try loading DLLs, etc.) before continuing. - base::FilePath media_path; - PathService::Get(base::DIR_MODULE, &media_path); - if (!media::InitializeMediaLibrary(media_path)) { - std::cerr << "Unable to initialize the media library." << std::endl; - return 1; - } - - // Retrieve command line options. - base::FilePath in_path(filenames[0]); - base::FilePath out_path; - if (filenames.size() > 1) - out_path = base::FilePath(filenames[1]); - AVMediaType target_codec = AVMEDIA_TYPE_UNKNOWN; - - // Determine whether to benchmark audio or video decoding. - std::string stream(cmd_line->GetSwitchValueASCII(switches::kStream)); - if (!stream.empty()) { - if (stream.compare("audio") == 0) { - target_codec = AVMEDIA_TYPE_AUDIO; - } else if (stream.compare("video") == 0) { - target_codec = AVMEDIA_TYPE_VIDEO; - } else { - std::cerr << "Unknown --stream option " << stream << std::endl; - return 1; - } - } - - // Determine number of threads to use for video decoding (optional). - int video_threads = 0; - std::string threads(cmd_line->GetSwitchValueASCII(switches::kVideoThreads)); - if (!threads.empty() && - !base::StringToInt(threads, &video_threads)) { - video_threads = 0; - } - - // Determine number of frames to decode (optional). - int max_frames = 0; - std::string frames_opt(cmd_line->GetSwitchValueASCII(switches::kFrames)); - if (!frames_opt.empty() && - !base::StringToInt(frames_opt, &max_frames)) { - max_frames = 0; - } - - // Determine number of times to loop (optional). - int max_loops = 0; - std::string loop_opt(cmd_line->GetSwitchValueASCII(switches::kLoop)); - if (!loop_opt.empty() && - !base::StringToInt(loop_opt, &max_loops)) { - max_loops = 0; - } - - bool fast2 = false; - if (cmd_line->HasSwitch(switches::kFast2)) { - fast2 = true; - } - - bool error_correction = false; - if (cmd_line->HasSwitch(switches::kErrorCorrection)) { - error_correction = true; - } - - bool flush = false; - if (cmd_line->HasSwitch(switches::kFlush)) { - flush = true; - } - - unsigned int hash_value = 5381u; // Seed for DJB2. - bool hash_djb2 = false; - if (cmd_line->HasSwitch(switches::kDjb2)) { - hash_djb2 = true; - } - - base::MD5Context ctx; // Intermediate MD5 data: do not use - base::MD5Init(&ctx); - bool hash_md5 = false; - if (cmd_line->HasSwitch(switches::kMd5)) - hash_md5 = true; - - int skip = 0; - if (cmd_line->HasSwitch(switches::kSkip)) { - std::string skip_opt(cmd_line->GetSwitchValueASCII(switches::kSkip)); - if (!base::StringToInt(skip_opt, &skip)) { - skip = 0; - } - } - - std::ostream* log_out = &std::cout; -#if defined(ENABLE_WINDOWS_EXCEPTIONS) - // Catch exceptions so this tool can be used in automated testing. - __try { -#endif - - base::MemoryMappedFile file_data; - file_data.Initialize(in_path); - media::InMemoryUrlProtocol protocol( - file_data.data(), file_data.length(), false); - - // Register FFmpeg and attempt to open file. - media::FFmpegGlue glue(&protocol); - if (!glue.OpenContext()) { - std::cerr << "Error: Could not open input for " - << in_path.value() << std::endl; - return 1; - } - - AVFormatContext* format_context = glue.format_context(); - - // Open output file. - FILE *output = NULL; - if (!out_path.empty()) { - // TODO(fbarchard): Add pipe:1 for piping to stderr. - if (out_path.value().substr(0, 5) == FILE_PATH_LITERAL("pipe:") || - out_path.value() == FILE_PATH_LITERAL("-")) { - output = stdout; - log_out = &std::cerr; -#if defined(OS_WIN) - _setmode(_fileno(stdout), _O_BINARY); -#endif - } else { - output = file_util::OpenFile(out_path, "wb"); - } - if (!output) { - std::cerr << "Error: Could not open output " - << out_path.value() << std::endl; - return 1; - } - } - - // Parse a little bit of the stream to fill out the format context. - if (avformat_find_stream_info(format_context, NULL) < 0) { - std::cerr << "Error: Could not find stream info for " - << in_path.value() << std::endl; - return 1; - } - - // Find our target stream. - int target_stream = -1; - for (size_t i = 0; i < format_context->nb_streams; ++i) { - AVCodecContext* codec_context = format_context->streams[i]->codec; - AVCodec* codec = avcodec_find_decoder(codec_context->codec_id); - - // See if we found our target codec. - if (codec_context->codec_type == target_codec && target_stream < 0) { - *log_out << "* "; - target_stream = i; - } else { - *log_out << " "; - } - - if (!codec || (codec_context->codec_type == AVMEDIA_TYPE_UNKNOWN)) { - *log_out << "Stream #" << i << ": Unknown" << std::endl; - } else { - // Print out stream information - *log_out << "Stream #" << i << ": " << codec->name << " (" - << codec->long_name << ")" << std::endl; - } - } - - // Only continue if we found our target stream. - if (target_stream < 0) { - std::cerr << "Error: Could not find target stream " - << target_stream << " for " << in_path.value() << std::endl; - return 1; - } - - // Prepare FFmpeg structures. - AVPacket packet; - AVCodecContext* codec_context = format_context->streams[target_stream]->codec; - AVCodec* codec = avcodec_find_decoder(codec_context->codec_id); - - // Only continue if we found our codec. - if (!codec) { - std::cerr << "Error: Could not find codec for " - << in_path.value() << std::endl; - return 1; - } - - if (skip == 1) { - codec_context->skip_loop_filter = AVDISCARD_NONREF; - } else if (skip == 2) { - codec_context->skip_loop_filter = AVDISCARD_ALL; - } else if (skip == 3) { - codec_context->skip_loop_filter = AVDISCARD_ALL; - codec_context->skip_frame = AVDISCARD_NONREF; - } - if (fast2) { - // Note this flag is no longer necessary for H264 multithreading. - codec_context->flags2 |= CODEC_FLAG2_FAST; - } - if (error_correction) { - codec_context->error_concealment = FF_EC_GUESS_MVS | FF_EC_DEBLOCK; - } - - // Initialize threaded decode. - if (target_codec == AVMEDIA_TYPE_VIDEO && video_threads > 0) { - codec_context->thread_count = video_threads; - } - - // Initialize our codec. - if (avcodec_open2(codec_context, codec, NULL) < 0) { - std::cerr << "Error: Could not open codec " - << (codec_context->codec ? codec_context->codec->name : "(NULL)") - << " for " << in_path.value() << std::endl; - return 1; - } - - // Buffer used for audio decoding. - scoped_ptr_malloc<AVFrame, media::ScopedPtrAVFree> audio_frame( - avcodec_alloc_frame()); - if (!audio_frame) { - std::cerr << "Error: avcodec_alloc_frame for " - << in_path.value() << std::endl; - return 1; - } - - // Buffer used for video decoding. - scoped_ptr_malloc<AVFrame, media::ScopedPtrAVFree> video_frame( - avcodec_alloc_frame()); - if (!video_frame) { - std::cerr << "Error: avcodec_alloc_frame for " - << in_path.value() << std::endl; - return 1; - } - - // Remember size of video. - int video_width = codec_context->width; - int video_height = codec_context->height; - - // Stats collector. - EnterTimingSection(); - std::vector<double> decode_times; - decode_times.reserve(4096); - // Parse through the entire stream until we hit EOF. - base::TimeTicks start = base::TimeTicks::HighResNow(); - int frames = 0; - int read_result = 0; - do { - read_result = av_read_frame(format_context, &packet); - - if (read_result < 0) { - if (max_loops) { - --max_loops; - } - if (max_loops > 0) { - av_seek_frame(format_context, -1, 0, AVSEEK_FLAG_BACKWARD); - read_result = 0; - continue; - } - if (flush) { - packet.stream_index = target_stream; - packet.size = 0; - } else { - break; - } - } - - // Only decode packets from our target stream. - if (packet.stream_index == target_stream) { - int result = -1; - if (target_codec == AVMEDIA_TYPE_AUDIO) { - int size_out = 0; - int got_audio = 0; - - avcodec_get_frame_defaults(audio_frame.get()); - - base::TimeTicks decode_start = base::TimeTicks::HighResNow(); - result = avcodec_decode_audio4(codec_context, audio_frame.get(), - &got_audio, &packet); - base::TimeDelta delta = base::TimeTicks::HighResNow() - decode_start; - - if (got_audio) { - size_out = av_samples_get_buffer_size( - NULL, codec_context->channels, audio_frame->nb_samples, - codec_context->sample_fmt, 1); - } - - if (got_audio && size_out) { - decode_times.push_back(delta.InMillisecondsF()); - ++frames; - read_result = 0; // Force continuation. - - if (output) { - if (fwrite(audio_frame->data[0], 1, size_out, output) != - static_cast<size_t>(size_out)) { - std::cerr << "Error: Could not write " - << size_out << " bytes for " << in_path.value() - << std::endl; - return 1; - } - } - - const uint8* u8_samples = - reinterpret_cast<const uint8*>(audio_frame->data[0]); - if (hash_djb2) { - hash_value = DJB2Hash(u8_samples, size_out, hash_value); - } - if (hash_md5) { - base::MD5Update( - &ctx, - base::StringPiece(reinterpret_cast<const char*>(u8_samples), - size_out)); - } - } - } else if (target_codec == AVMEDIA_TYPE_VIDEO) { - int got_picture = 0; - - avcodec_get_frame_defaults(video_frame.get()); - - base::TimeTicks decode_start = base::TimeTicks::HighResNow(); - result = avcodec_decode_video2(codec_context, video_frame.get(), - &got_picture, &packet); - base::TimeDelta delta = base::TimeTicks::HighResNow() - decode_start; - - if (got_picture) { - decode_times.push_back(delta.InMillisecondsF()); - ++frames; - read_result = 0; // Force continuation. - - for (int plane = 0; plane < 3; ++plane) { - const uint8* source = video_frame->data[plane]; - const size_t source_stride = video_frame->linesize[plane]; - size_t bytes_per_line = codec_context->width; - size_t copy_lines = codec_context->height; - if (plane != 0) { - switch (codec_context->pix_fmt) { - case PIX_FMT_YUV420P: - case PIX_FMT_YUVJ420P: - bytes_per_line /= 2; - copy_lines = (copy_lines + 1) / 2; - break; - case PIX_FMT_YUV422P: - case PIX_FMT_YUVJ422P: - bytes_per_line /= 2; - break; - case PIX_FMT_YUV444P: - case PIX_FMT_YUVJ444P: - break; - default: - std::cerr << "Error: Unknown video format " - << codec_context->pix_fmt; - return 1; - } - } - if (output) { - for (size_t i = 0; i < copy_lines; ++i) { - if (fwrite(source, 1, bytes_per_line, output) != - bytes_per_line) { - std::cerr << "Error: Could not write data after " - << copy_lines << " lines for " - << in_path.value() << std::endl; - return 1; - } - source += source_stride; - } - } - if (hash_djb2) { - for (size_t i = 0; i < copy_lines; ++i) { - hash_value = DJB2Hash(source, bytes_per_line, hash_value); - source += source_stride; - } - } - if (hash_md5) { - for (size_t i = 0; i < copy_lines; ++i) { - base::MD5Update( - &ctx, - base::StringPiece(reinterpret_cast<const char*>(source), - bytes_per_line)); - source += source_stride; - } - } - } - } - } else { - NOTREACHED(); - } - - // Make sure our decoding went OK. - if (result < 0) { - std::cerr << "Error: avcodec_decode returned " - << result << " for " << in_path.value() << std::endl; - return 1; - } - } - // Free our packet. - av_free_packet(&packet); - - if (max_frames && (frames >= max_frames)) - break; - } while (read_result >= 0); - base::TimeDelta total = base::TimeTicks::HighResNow() - start; - LeaveTimingSection(); - - // Clean up. - if (output) - file_util::CloseFile(output); - - // Calculate the sum of times. Note that some of these may be zero. - double sum = 0; - for (size_t i = 0; i < decode_times.size(); ++i) { - sum += decode_times[i]; - } - - double average = 0; - double stddev = 0; - double fps = 0; - if (frames > 0) { - // Calculate the average time per frame. - average = sum / frames; - - // Calculate the sum of the squared differences. - // Standard deviation will only be accurate if no threads are used. - // TODO(fbarchard): Rethink standard deviation calculation. - double squared_sum = 0; - for (int i = 0; i < frames; ++i) { - double difference = decode_times[i] - average; - squared_sum += difference * difference; - } - - // Calculate the standard deviation (jitter). - stddev = sqrt(squared_sum / frames); - - // Calculate frames per second. - fps = frames * 1000.0 / sum; - } - - // Print our results. - log_out->setf(std::ios::fixed); - log_out->precision(2); - *log_out << std::endl; - *log_out << " Frames:" << std::setw(11) << frames << std::endl; - *log_out << " Width:" << std::setw(11) << video_width << std::endl; - *log_out << " Height:" << std::setw(11) << video_height << std::endl; - *log_out << " Total:" << std::setw(11) << total.InMillisecondsF() - << " ms" << std::endl; - *log_out << " Summation:" << std::setw(11) << sum - << " ms" << std::endl; - *log_out << " Average:" << std::setw(11) << average - << " ms" << std::endl; - *log_out << " StdDev:" << std::setw(11) << stddev - << " ms" << std::endl; - *log_out << " FPS:" << std::setw(11) << fps - << std::endl; - if (hash_djb2) { - *log_out << " DJB2 Hash:" << std::setw(11) << hash_value - << " " << in_path.value() << std::endl; - } - if (hash_md5) { - base::MD5Digest digest; // The result of the computation. - base::MD5Final(&digest, &ctx); - *log_out << " MD5 Hash: " << base::MD5DigestToBase16(digest) - << " " << in_path.value() << std::endl; - } -#if defined(ENABLE_WINDOWS_EXCEPTIONS) - } __except(EXCEPTION_EXECUTE_HANDLER) { - *log_out << " Exception:" << std::setw(11) << GetExceptionCode() - << " " << in_path.value() << std::endl; - return 1; - } -#endif - CommandLine::Reset(); - return 0; -} diff --git a/media/tools/seek_tester/seek_tester.cc b/media/tools/seek_tester/seek_tester.cc deleted file mode 100644 index ca54aa8..0000000 --- a/media/tools/seek_tester/seek_tester.cc +++ /dev/null @@ -1,112 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. -// -// This standalone binary is a helper for diagnosing seek behavior of the -// demuxer setup in media/ code. It answers the question: "if I ask the demuxer -// to Seek to X ms, where will it actually seek to? (necessitating -// frame-dropping until the original seek target is reached)". Sample run: -// -// $ ./out/Debug/seek_tester .../LayoutTests/media/content/test.ogv 6300 -// [0207/130327:INFO:seek_tester.cc(63)] Requested: 6123ms -// [0207/130327:INFO:seek_tester.cc(68)] audio seeked to: 5526ms -// [0207/130327:INFO:seek_tester.cc(74)] video seeked to: 5577ms - - -#include "base/at_exit.h" -#include "base/bind.h" -#include "base/files/file_path.h" -#include "base/logging.h" -#include "base/message_loop/message_loop.h" -#include "base/strings/string_number_conversions.h" -#include "media/base/media.h" -#include "media/base/media_log.h" -#include "media/filters/ffmpeg_demuxer.h" -#include "media/filters/file_data_source.h" - -class DemuxerHostImpl : public media::DemuxerHost { - public: - // DataSourceHost implementation. - virtual void SetTotalBytes(int64 total_bytes) OVERRIDE {} - virtual void AddBufferedByteRange(int64 start, int64 end) OVERRIDE {} - virtual void AddBufferedTimeRange(base::TimeDelta start, - base::TimeDelta end) OVERRIDE {} - - // DemuxerHost implementation. - virtual void SetDuration(base::TimeDelta duration) OVERRIDE {} - virtual void OnDemuxerError(media::PipelineStatus error) OVERRIDE {} -}; - -void QuitMessageLoop(base::MessageLoop* loop, media::PipelineStatus status) { - CHECK_EQ(status, media::PIPELINE_OK); - loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure()); -} - -void TimestampExtractor(uint64* timestamp_ms, - base::MessageLoop* loop, - media::DemuxerStream::Status status, - const scoped_refptr<media::DecoderBuffer>& buffer) { - CHECK_EQ(status, media::DemuxerStream::kOk); - if (buffer->timestamp() == media::kNoTimestamp()) - *timestamp_ms = -1; - else - *timestamp_ms = buffer->timestamp().InMillisecondsF(); - loop->PostTask(FROM_HERE, base::MessageLoop::QuitClosure()); -} - -static void NeedKey(const std::string& type, - const std::vector<uint8>& init_data) { - LOG(INFO) << "File is encrypted."; -} - -int main(int argc, char** argv) { - base::AtExitManager at_exit; - media::InitializeMediaLibraryForTesting(); - - CHECK_EQ(argc, 3) << "\nUsage: " << argv[0] << " <file> <seekTimeInMs>"; - uint64 seek_target_ms; - CHECK(base::StringToUint64(argv[2], &seek_target_ms)); - scoped_ptr<media::FileDataSource> file_data_source( - new media::FileDataSource()); - CHECK(file_data_source->Initialize(base::FilePath::FromUTF8Unsafe(argv[1]))); - - DemuxerHostImpl host; - base::MessageLoop loop; - media::PipelineStatusCB quitter = base::Bind(&QuitMessageLoop, &loop); - media::Demuxer::NeedKeyCB need_key_cb = base::Bind(&NeedKey); - scoped_ptr<media::FFmpegDemuxer> demuxer( - new media::FFmpegDemuxer(loop.message_loop_proxy(), - file_data_source.get(), - need_key_cb, - new media::MediaLog())); - demuxer->Initialize(&host, quitter); - loop.Run(); - - demuxer->Seek(base::TimeDelta::FromMilliseconds(seek_target_ms), quitter); - loop.Run(); - - uint64 audio_seeked_to_ms; - uint64 video_seeked_to_ms; - media::DemuxerStream* audio_stream = - demuxer->GetStream(media::DemuxerStream::AUDIO); - media::DemuxerStream* video_stream = - demuxer->GetStream(media::DemuxerStream::VIDEO); - LOG(INFO) << "Requested: " << seek_target_ms << "ms"; - if (audio_stream) { - audio_stream->Read(base::Bind( - &TimestampExtractor, &audio_seeked_to_ms, &loop)); - loop.Run(); - LOG(INFO) << " audio seeked to: " << audio_seeked_to_ms << "ms"; - } - if (video_stream) { - video_stream->Read( - base::Bind(&TimestampExtractor, &video_seeked_to_ms, &loop)); - loop.Run(); - LOG(INFO) << " video seeked to: " << video_seeked_to_ms << "ms"; - } - - demuxer->Stop(base::Bind(&base::MessageLoop::Quit, base::Unretained(&loop))); - loop.Run(); - - return 0; -} diff --git a/media/tools/shader_bench/cpu_color_painter.cc b/media/tools/shader_bench/cpu_color_painter.cc deleted file mode 100644 index a7cb570..0000000 --- a/media/tools/shader_bench/cpu_color_painter.cc +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/base/yuv_convert.h" -#include "media/tools/shader_bench/cpu_color_painter.h" - -enum { kNumRGBPlanes = 1 }; - -// Pass-through vertex shader. -static const char kVertexShader[] = - "precision highp float;\n" - "precision highp int;\n" - "varying vec2 interp_tc;\n" - "\n" - "attribute vec4 in_pos;\n" - "attribute vec2 in_tc;\n" - "\n" - "void main() {\n" - " interp_tc = in_tc;\n" - " gl_Position = in_pos;\n" - "}\n"; - -// RGB pixel shader. -static const char kFragmentShader[] = - "precision mediump float;\n" - "precision mediump int;\n" - "varying vec2 interp_tc;\n" - "\n" - "uniform sampler2D rgba_tex;\n" - "\n" - "void main() {\n" - " vec4 texColor = texture2D(rgba_tex, interp_tc);" - " gl_FragColor = vec4(texColor.z, texColor.y, texColor.x, texColor.w);\n" - "}\n"; - -CPUColorPainter::CPUColorPainter() - : program_id_(-1) { -} - -CPUColorPainter::~CPUColorPainter() { - if (program_id_) { - glDeleteProgram(program_id_); - glDeleteTextures(kNumRGBPlanes, textures_); - } -} - -void CPUColorPainter::Initialize(int width, int height) { - glGenTextures(kNumRGBPlanes, textures_); - glActiveTexture(GL_TEXTURE0); - glBindTexture(GL_TEXTURE_2D, textures_[0]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, - GL_RGBA, GL_UNSIGNED_BYTE, 0); - - GLuint program = CreateShaderProgram(kVertexShader, kFragmentShader); - - // Bind parameters. - glUniform1i(glGetUniformLocation(program, "rgba_tex"), 0); - program_id_ = program; -} - -void CPUColorPainter::Paint(scoped_refptr<media::VideoFrame> video_frame) { - // Convert to RGB32 frame. - scoped_refptr<media::VideoFrame> rgba_frame = - media::VideoFrame::CreateFrame(media::VideoFrame::RGB32, - video_frame->coded_size(), - video_frame->visible_rect(), - video_frame->natural_size(), - base::TimeDelta()); - - media::ConvertYUVToRGB32(video_frame->data(media::VideoFrame::kYPlane), - video_frame->data(media::VideoFrame::kUPlane), - video_frame->data(media::VideoFrame::kVPlane), - rgba_frame->data(0), - video_frame->coded_size().width(), - video_frame->coded_size().height(), - video_frame->stride(media::VideoFrame::kYPlane), - video_frame->stride(media::VideoFrame::kUPlane), - rgba_frame->stride(0), - media::YV12); - - glBindTexture(GL_TEXTURE_2D, textures_[0]); - // Not accounting for x/y offset presently. - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, - rgba_frame->visible_rect().width(), - rgba_frame->visible_rect().height(), - GL_RGBA, GL_UNSIGNED_BYTE, - rgba_frame->data(0)); - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - surface()->SwapBuffers(); -} diff --git a/media/tools/shader_bench/cpu_color_painter.h b/media/tools/shader_bench/cpu_color_painter.h deleted file mode 100644 index 7aba3cd..0000000 --- a/media/tools/shader_bench/cpu_color_painter.h +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_TOOLS_SHADER_BENCH_CPU_COLOR_PAINTER_H_ -#define MEDIA_TOOLS_SHADER_BENCH_CPU_COLOR_PAINTER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "media/base/video_frame.h" -#include "media/tools/shader_bench/gpu_painter.h" - -// Does color conversion using CPU, rendering on GPU. -class CPUColorPainter : public GPUPainter { - public: - CPUColorPainter(); - virtual ~CPUColorPainter(); - - // Painter interface. - virtual void Initialize(int width, int height) OVERRIDE; - virtual void Paint(scoped_refptr<media::VideoFrame> video_frame) OVERRIDE; - - private: - // Shader program id. - GLuint program_id_; - - // ID of rgba texture. - GLuint textures_[1]; - - DISALLOW_COPY_AND_ASSIGN(CPUColorPainter); -}; - -#endif // MEDIA_TOOLS_SHADER_BENCH_CPU_COLOR_PAINTER_H_ diff --git a/media/tools/shader_bench/gpu_color_painter.cc b/media/tools/shader_bench/gpu_color_painter.cc deleted file mode 100644 index 17155ee..0000000 --- a/media/tools/shader_bench/gpu_color_painter.cc +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/tools/shader_bench/gpu_color_painter.h" -#include "ui/gl/gl_context.h" - -enum { kNumYUVPlanes = 3 }; - -// Matrix used for the YUV to RGB conversion. -static const float kYUV2RGB[9] = { - 1.f, 0.f, 1.403f, - 1.f, -.344f, -.714f, - 1.f, 1.772f, 0.f, -}; - -static const float kYUV2RGB_TRANS[9] = { - 1.f, 1.f, 1.f, - 0.f, -.344f, 1.772f, - 1.403f, -.714f, 0.f, -}; - -// Pass-through vertex shader. -static const char kVertexShader[] = - "precision highp float;\n" - "precision highp int;\n" - "varying vec2 interp_tc;\n" - "\n" - "attribute vec4 in_pos;\n" - "attribute vec2 in_tc;\n" - "\n" - "void main() {\n" - " interp_tc = in_tc;\n" - " gl_Position = in_pos;\n" - "}\n"; - -// YUV to RGB pixel shader. Loads a pixel from each plane and pass through the -// matrix. -static const char kFragmentShader[] = - "precision mediump float;\n" - "precision mediump int;\n" - "varying vec2 interp_tc;\n" - "\n" - "uniform sampler2D y_tex;\n" - "uniform sampler2D u_tex;\n" - "uniform sampler2D v_tex;\n" - "uniform mat3 yuv2rgb;\n" - "\n" - "void main() {\n" - " float y = texture2D(y_tex, interp_tc).x;\n" - " float u = texture2D(u_tex, interp_tc).r - .5;\n" - " float v = texture2D(v_tex, interp_tc).r - .5;\n" - " vec3 rgb = yuv2rgb * vec3(y, u, v);\n" - " gl_FragColor = vec4(rgb, 1);\n" - "}\n"; - -GPUColorWithLuminancePainter::GPUColorWithLuminancePainter() - : program_id_(-1) { -} - -GPUColorWithLuminancePainter::~GPUColorWithLuminancePainter() { - if (program_id_) { - glDeleteProgram(program_id_); - glDeleteTextures(kNumYUVPlanes, textures_); - } -} - -void GPUColorWithLuminancePainter::Initialize(int width, int height) { - // Create 3 textures, one for each plane, and bind them to different - // texture units. - glGenTextures(kNumYUVPlanes, textures_); - - for (unsigned int i = 0; i < kNumYUVPlanes; ++i) { - unsigned int texture_width = (i == media::VideoFrame::kYPlane) ? - width : width / 2; - unsigned int texture_height = (i == media::VideoFrame::kYPlane) ? - height : height / 2; - glActiveTexture(GL_TEXTURE0 + i); - glBindTexture(GL_TEXTURE_2D, textures_[i]); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, texture_width, texture_height, - 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, 0); - } - - GLuint program = CreateShaderProgram(kVertexShader, kFragmentShader); - - // Bind parameters. - glUniform1i(glGetUniformLocation(program, "y_tex"), 0); - glUniform1i(glGetUniformLocation(program, "u_tex"), 1); - glUniform1i(glGetUniformLocation(program, "v_tex"), 2); - int yuv2rgb_location = glGetUniformLocation(program, "yuv2rgb"); - - // DesktopGL supports transpose matrices. - if (gfx::GetGLImplementation() == gfx::kGLImplementationDesktopGL) - glUniformMatrix3fv(yuv2rgb_location, 1, GL_TRUE, kYUV2RGB); - else - glUniformMatrix3fv(yuv2rgb_location, 1, GL_FALSE, kYUV2RGB_TRANS); - - program_id_ = program; -} - -void GPUColorWithLuminancePainter::Paint( - scoped_refptr<media::VideoFrame> video_frame) { - // Not accounting for x/y offset presently. - int width = video_frame->visible_rect().width(); - int height = video_frame->visible_rect().height(); - for (unsigned int i = 0; i < kNumYUVPlanes; ++i) { - unsigned int plane_width = - (i == media::VideoFrame::kYPlane) ? width : width / 2; - unsigned int plane_height = - (i == media::VideoFrame::kYPlane) ? height : height / 2; - glBindTexture(GL_TEXTURE_2D, textures_[i]); - glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, plane_width, plane_height, - GL_LUMINANCE, GL_UNSIGNED_BYTE, video_frame->data(i)); - } - - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - surface()->SwapBuffers(); -} diff --git a/media/tools/shader_bench/gpu_color_painter.h b/media/tools/shader_bench/gpu_color_painter.h deleted file mode 100644 index 63c6f52..0000000 --- a/media/tools/shader_bench/gpu_color_painter.h +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_TOOLS_SHADER_BENCH_GPU_COLOR_PAINTER_H_ -#define MEDIA_TOOLS_SHADER_BENCH_GPU_COLOR_PAINTER_H_ - -#include "base/compiler_specific.h" -#include "base/memory/ref_counted.h" -#include "media/base/video_frame.h" -#include "media/tools/shader_bench/gpu_painter.h" -#include "ui/gl/gl_context.h" - -// Does color space conversion using luminance textures on GPU, -// renders using GPU. -class GPUColorWithLuminancePainter : public GPUPainter { - public: - GPUColorWithLuminancePainter(); - virtual ~GPUColorWithLuminancePainter(); - - // Painter interface. - virtual void Initialize(int width, int height) OVERRIDE; - virtual void Paint(scoped_refptr<media::VideoFrame> video_frame) OVERRIDE; - - private: - // Shader program id. - GLuint program_id_; - - // IDs of 3 luminance textures. - GLuint textures_[3]; - - DISALLOW_COPY_AND_ASSIGN(GPUColorWithLuminancePainter); -}; - -#endif // MEDIA_TOOLS_SHADER_BENCH_GPU_COLOR_PAINTER_H_ diff --git a/media/tools/shader_bench/gpu_painter.cc b/media/tools/shader_bench/gpu_painter.cc deleted file mode 100644 index e6350119..0000000 --- a/media/tools/shader_bench/gpu_painter.cc +++ /dev/null @@ -1,92 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "base/logging.h" -#include "media/tools/shader_bench/gpu_painter.h" - -// Vertices for a full screen quad. -static const float kVertices[8] = { - -1.f, 1.f, - -1.f, -1.f, - 1.f, 1.f, - 1.f, -1.f, -}; - -// Texture Coordinates mapping the entire texture. -static const float kTextureCoords[8] = { - 0, 0, - 0, 1, - 1, 0, - 1, 1, -}; - -// Buffer size for compile errors. -static const unsigned int kErrorSize = 4096; - -GPUPainter::GPUPainter() - : surface_(NULL), - context_(NULL) { -} - -GPUPainter::~GPUPainter() { -} - -void GPUPainter::SetGLContext(gfx::GLSurface* surface, - gfx::GLContext* context) { - surface_ = surface; - context_ = context; -} - -GLuint GPUPainter::LoadShader(unsigned type, const char* shader_source) { - GLuint shader = glCreateShader(type); - glShaderSource(shader, 1, &shader_source, NULL); - glCompileShader(shader); - int result = GL_FALSE; - glGetShaderiv(shader, GL_COMPILE_STATUS, &result); - if (!result) { - char log[kErrorSize]; - int len; - glGetShaderInfoLog(shader, kErrorSize - 1, &len, log); - log[kErrorSize - 1] = 0; - LOG(FATAL) << "Shader did not compile: " << log; - } - return shader; -} - -GLuint GPUPainter::CreateShaderProgram(const char* vertex_shader_source, - const char* fragment_shader_source) { - - // Create vertex and pixel shaders. - GLuint vertex_shader = LoadShader(GL_VERTEX_SHADER, vertex_shader_source); - GLuint fragment_shader = - LoadShader(GL_FRAGMENT_SHADER, fragment_shader_source); - - // Create program and attach shaders. - GLuint program = glCreateProgram(); - glAttachShader(program, vertex_shader); - glAttachShader(program, fragment_shader); - glDeleteShader(vertex_shader); - glDeleteShader(fragment_shader); - glLinkProgram(program); - int result = GL_FALSE; - glGetProgramiv(program, GL_LINK_STATUS, &result); - if (!result) { - char log[kErrorSize]; - int len; - glGetProgramInfoLog(program, kErrorSize - 1, &len, log); - log[kErrorSize - 1] = 0; - LOG(FATAL) << "Program did not link: " << log; - } - glUseProgram(program); - - // Set common vertex parameters. - int pos_location = glGetAttribLocation(program, "in_pos"); - glEnableVertexAttribArray(pos_location); - glVertexAttribPointer(pos_location, 2, GL_FLOAT, GL_FALSE, 0, kVertices); - - int tc_location = glGetAttribLocation(program, "in_tc"); - glEnableVertexAttribArray(tc_location); - glVertexAttribPointer(tc_location, 2, GL_FLOAT, GL_FALSE, 0, kTextureCoords); - return program; -} diff --git a/media/tools/shader_bench/gpu_painter.h b/media/tools/shader_bench/gpu_painter.h deleted file mode 100644 index e68305b..0000000 --- a/media/tools/shader_bench/gpu_painter.h +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_TOOLS_SHADER_BENCH_GPU_PAINTER_H_ -#define MEDIA_TOOLS_SHADER_BENCH_GPU_PAINTER_H_ - -#include "media/tools/shader_bench/painter.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_surface.h" - -// Class that renders video frames to a window via GPU. -class GPUPainter : public Painter { - public: - GPUPainter(); - virtual ~GPUPainter(); - - // Returns a reference to the GL context. - gfx::GLSurface* surface() const { return surface_; } - - // Sets context for subsequent gl calls in this painter. - virtual void SetGLContext(gfx::GLSurface* surface, gfx::GLContext* context); - - // Creates shader program into given context, from the vertex and fragment - // shader source code. Returns the id of the shader program. - virtual GLuint CreateShaderProgram(const char* vertex_shader_source, - const char* fragment_shader_source); - - private: - // Loads shader into given context, from the source code of the - // shader. type refers to the shader type, either GL_VERTEX_SHADER or - // GL_FRAGMENT_SHADER. Returns id of shader. - GLuint LoadShader(unsigned type, const char* shader_source); - - // Reference to the gl context. - gfx::GLSurface* surface_; - gfx::GLContext* context_; - - DISALLOW_COPY_AND_ASSIGN(GPUPainter); -}; - -#endif // MEDIA_TOOLS_SHADER_BENCH_GPU_PAINTER_H_ diff --git a/media/tools/shader_bench/painter.cc b/media/tools/shader_bench/painter.cc deleted file mode 100644 index ab8fc59..0000000 --- a/media/tools/shader_bench/painter.cc +++ /dev/null @@ -1,26 +0,0 @@ -// Copyright (c) 2010 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/tools/shader_bench/painter.h" - -Painter::Painter() - : frames_(NULL) { -} - -Painter::~Painter() { -} - -void Painter::OnPaint() { - if (frames_ && !frames_->empty()) { - scoped_refptr<media::VideoFrame> cur_frame = frames_->front(); - Paint(cur_frame); - frames_->pop_front(); - frames_->push_back(cur_frame); - } -} - -void Painter::LoadFrames( - std::deque<scoped_refptr<media::VideoFrame> >* frames) { - frames_ = frames; -} diff --git a/media/tools/shader_bench/painter.h b/media/tools/shader_bench/painter.h deleted file mode 100644 index 2dd92ab..0000000 --- a/media/tools/shader_bench/painter.h +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_TOOLS_SHADER_BENCH_PAINTER_H_ -#define MEDIA_TOOLS_SHADER_BENCH_PAINTER_H_ - -#include <deque> - -#include "base/memory/ref_counted.h" -#include "media/base/video_frame.h" - -// Class that paints video frames to a window. -class Painter { - public: - Painter(); - virtual ~Painter(); - - // Loads frames into Painter. Painter does not take ownership of frames. - virtual void LoadFrames( - std::deque<scoped_refptr<media::VideoFrame> >* frames); - - // Called window is ready to be painted. - virtual void OnPaint(); - - // Initialize a Painter class with a width and a height - virtual void Initialize(int width, int height) = 0; - - // Paint a single frame to a window. - virtual void Paint(scoped_refptr<media::VideoFrame> video_frame) = 0; - - private: - // Frames that the Painter will paint. - std::deque<scoped_refptr<media::VideoFrame> >* frames_; - - DISALLOW_COPY_AND_ASSIGN(Painter); -}; - -#endif // MEDIA_TOOLS_SHADER_BENCH_PAINTER_H_ diff --git a/media/tools/shader_bench/shader_bench.cc b/media/tools/shader_bench/shader_bench.cc deleted file mode 100644 index 0b4236f..0000000 --- a/media/tools/shader_bench/shader_bench.cc +++ /dev/null @@ -1,162 +0,0 @@ -// Copyright (c) 2012 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include <stdio.h> -#include <stdlib.h> -#include <deque> -#include <ostream> - -#include "base/at_exit.h" -#include "base/bind.h" -#include "base/command_line.h" -#include "base/memory/scoped_ptr.h" -#include "base/strings/string_number_conversions.h" -#include "base/time/time.h" -#include "media/base/media.h" -#include "media/base/video_frame.h" -#include "media/tools/shader_bench/cpu_color_painter.h" -#include "media/tools/shader_bench/gpu_color_painter.h" -#include "media/tools/shader_bench/painter.h" -#include "media/tools/shader_bench/window.h" -#include "ui/gfx/native_widget_types.h" -#include "ui/gl/gl_bindings.h" -#include "ui/gl/gl_context.h" -#include "ui/gl/gl_implementation.h" -#include "ui/gl/gl_surface.h" - -#if defined(TOOLKIT_GTK) -#include <gtk/gtk.h> -#endif - -static const int kNumFramesToPaint = 500; -static base::TimeTicks g_start_; -static base::TimeTicks g_end_; - -long CalculateYUVFrameSize(FILE* file_handle, int num_frames) { - fseek(file_handle, 0, SEEK_END); - long file_size = (long) ftell(file_handle); - rewind(file_handle); - return file_size / num_frames; -} - -void GetFrames(std::string file_name, - int width, int height, int num_frames, - std::deque<scoped_refptr<media::VideoFrame> >& out_frames) { - FILE* file_handle = fopen(file_name.c_str(), "rb"); - if (!file_handle) { - printf("Could not open %s\n", file_name.c_str()); - exit(1); - } - - long frame_size = CalculateYUVFrameSize(file_handle, num_frames); - - gfx::Size size(width, height); - for (int i = 0; i < num_frames; i++) { - scoped_refptr<media::VideoFrame> video_frame = - media::VideoFrame::CreateFrame(media::VideoFrame::YV12, size, - gfx::Rect(size), size, - base::TimeDelta()); - long bytes_read = - fread(video_frame->data(0), 1, frame_size, file_handle); - - if (bytes_read != frame_size) { - printf("Could not read %s\n", file_name.c_str()); - fclose(file_handle); - exit(1); - } - out_frames.push_back(video_frame); - } - - fclose(file_handle); -} - -void TestFinished() { - g_end_ = base::TimeTicks::HighResNow(); - double time_in_seconds = - static_cast<double>((g_end_ - g_start_).InMilliseconds()) / 1000; - double fps = kNumFramesToPaint / time_in_seconds; - printf("Printed %f frames per second.\n", fps); -} - -void RunTest(media::Window* window, Painter* painter) { - g_start_ = base::TimeTicks::HighResNow(); - window->Start(kNumFramesToPaint, base::Bind(&TestFinished), painter); -} - -int main(int argc, char** argv) { - // Read arguments. - if (argc == 1) { - printf("Usage: %s --file=FILE --wxh=DIMENSIONS --frames=NUM_FRAMES\n" - "FILE is a raw .yuv file with 1+ frames in it\n" - "DIMENSIONS is the width and height of the frame in pixels\n" - "NUM_FRAMES is the number of frames in FILE\n", argv[0]); - return 1; - } - - // Read command line. -#if defined(TOOLKIT_GTK) - gtk_init(&argc, &argv); -#endif - CommandLine::Init(argc, argv); - - // Determine file name. - std::string file_name = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII("file"); - - // Determine number of frames. - int num_frames = 0; - std::string str_num_frames = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII("frames"); - base::StringToInt(str_num_frames, &num_frames); - - // Determine video dimensions. - int width = 0; - int height = 0; - std::string dimensions = - CommandLine::ForCurrentProcess()->GetSwitchValueASCII("wxh"); - int x_index = dimensions.find('x'); - std::string str_width = dimensions.substr(0, x_index); - std::string str_height = - dimensions.substr(x_index + 1, dimensions.length() - x_index - 1); - base::StringToInt(str_width, &width); - base::StringToInt(str_height, &height); - - // Process files. - std::deque<scoped_refptr<media::VideoFrame> > frames; - GetFrames(file_name, width, height, num_frames, frames); - - // Initialize window and graphics context. - base::AtExitManager at_exit_manager; - media::InitializeMediaLibraryForTesting(); - gfx::GLSurface::InitializeOneOff(); - scoped_ptr<media::Window> window(new media::Window(width, height)); - scoped_refptr<gfx::GLSurface> surface = - gfx::GLSurface::CreateViewGLSurface(window->PluginWindow()); - scoped_refptr<gfx::GLContext> context = gfx::GLContext::CreateGLContext( - NULL, surface.get(), gfx::PreferDiscreteGpu); - context->MakeCurrent(surface.get()); - // This sets D3DPRESENT_INTERVAL_IMMEDIATE on Windows. - context->SetSwapInterval(0); - - // Initialize and name GPU painters. - const struct { - const char* name; - GPUPainter* painter; - } painters[] = { - { "CPU CSC + GPU Render", new CPUColorPainter() }, - { "GPU CSC/Render", new GPUColorWithLuminancePainter() }, - }; - - // Run GPU painter tests. - for (size_t i = 0; i < ARRAYSIZE_UNSAFE(painters); i++) { - scoped_ptr<GPUPainter> painter(painters[i].painter); - painter->LoadFrames(&frames); - painter->SetGLContext(surface, context); - painter->Initialize(width, height); - printf("Running %s tests...", painters[i].name); - RunTest(window.get(), painter.get()); - } - - return 0; -} diff --git a/media/tools/shader_bench/window.cc b/media/tools/shader_bench/window.cc deleted file mode 100644 index 3eb26f4..0000000 --- a/media/tools/shader_bench/window.cc +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/tools/shader_bench/window.h" - -namespace media { - -Window::Window(int width, int height) - : painter_(NULL), - limit_(0), - count_(0), - running_(false) { - window_handle_ = CreateNativeWindow(width, height); -} - -Window::~Window() {} - -} // namespace media diff --git a/media/tools/shader_bench/window.h b/media/tools/shader_bench/window.h deleted file mode 100644 index d66e849..0000000 --- a/media/tools/shader_bench/window.h +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#ifndef MEDIA_TOOLS_SHADER_BENCH_WINDOW_H_ -#define MEDIA_TOOLS_SHADER_BENCH_WINDOW_H_ - -#include "base/callback.h" -#include "ui/gfx/native_widget_types.h" - -class Painter; - -namespace media { - -class Window { - public: - Window(int width, int height); - ~Window(); - - // Creates and returns a handle to a native window of the given dimensions. - gfx::NativeWindow CreateNativeWindow(int width, int height); - - // Returns the NPAPI plugin window handle of the window. - gfx::PluginWindowHandle PluginWindow(); - - // Kicks off frame painting with the given limit, painter, and - // callback to run when painting task is complete. - void Start(int limit, const base::Closure& callback, Painter* painter); - - // Called when window is expected to paint self. - void OnPaint(); - - // Main loop for window. - void MainLoop(); - - private: - // Closure to run when frame painting is completed. Will be reset after - // running. - base::Closure callback_; - - // Reference to painter Window uses to paint frames. - Painter* painter_; - - // Number of frames to paint before closing the window. - int limit_; - - // Number of frames currently painted. - int count_; - - // True if the window is painting video frames to the screen, false otherwise. - bool running_; - - // This window's native handle. - gfx::NativeWindow window_handle_; - - DISALLOW_COPY_AND_ASSIGN(Window); -}; - -} // namespace media - -#endif // MEDIA_TOOLS_SHADER_BENCH_WINDOW_H_ diff --git a/media/tools/shader_bench/window_linux.cc b/media/tools/shader_bench/window_linux.cc deleted file mode 100644 index a0a3493..0000000 --- a/media/tools/shader_bench/window_linux.cc +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/tools/shader_bench/window.h" - -#include "media/tools/shader_bench/painter.h" - -#include <gdk/gdkx.h> -#include <gtk/gtk.h> - -namespace media { - -static gboolean OnDelete(GtkWidget* widget, GdkEventExpose* event) { - gtk_main_quit(); - return FALSE; -} - -static gboolean OnExpose(GtkWidget* widget, - GdkEventExpose* event, - gpointer data) { - Window* window = reinterpret_cast<Window*>(data); - if (window) - window->OnPaint(); - return FALSE; -} - -gfx::NativeWindow Window::CreateNativeWindow(int width, int height) { - GtkWidget* hwnd = gtk_window_new(GTK_WINDOW_TOPLEVEL); - - gtk_window_set_default_size(GTK_WINDOW(hwnd), width, height); - gtk_widget_set_double_buffered(hwnd, FALSE); - gtk_widget_set_app_paintable(hwnd, TRUE); - gtk_widget_show(hwnd); - - return GTK_WINDOW(hwnd); -} - -gfx::PluginWindowHandle Window::PluginWindow() { - return GDK_WINDOW_XWINDOW(GTK_WIDGET(window_handle_)->window); -} - -void Window::Start(int limit, const base::Closure& callback, - Painter* painter) { - running_ = true; - count_ = 0; - limit_ = limit; - callback_ = callback; - painter_ = painter; - - gtk_signal_connect(GTK_OBJECT(window_handle_), - "delete_event", - reinterpret_cast<GtkSignalFunc>(OnDelete), - NULL); - - gtk_signal_connect(GTK_OBJECT(window_handle_), - "expose_event", - reinterpret_cast<GtkSignalFunc>(OnExpose), - this); - - gtk_widget_queue_draw(GTK_WIDGET(window_handle_)); - MainLoop(); -} - -void Window::OnPaint() { - if (!running_) - return; - - if (count_ < limit_) { - painter_->OnPaint(); - count_++; - gtk_widget_queue_draw(GTK_WIDGET(window_handle_)); - } else { - running_ = false; - if (!callback_.is_null()) { - callback_.Run(); - callback_.Reset(); - } - gtk_main_quit(); - } -} - -void Window::MainLoop() { - gtk_main(); -} - -} // namespace media diff --git a/media/tools/shader_bench/window_win.cc b/media/tools/shader_bench/window_win.cc deleted file mode 100644 index abc6fc4..0000000 --- a/media/tools/shader_bench/window_win.cc +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright (c) 2011 The Chromium Authors. All rights reserved. -// Use of this source code is governed by a BSD-style license that can be -// found in the LICENSE file. - -#include "media/tools/shader_bench/window.h" - -#include "media/tools/shader_bench/painter.h" - -namespace media { - -static LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, - WPARAM w_param, LPARAM l_param) { - LRESULT result = 0; - switch (msg) { - case WM_CLOSE: - ::DestroyWindow(hwnd); - break; - case WM_DESTROY: - ::PostQuitMessage(0); - break; - case WM_ERASEBKGND: - // Return a non-zero value to indicate that the background has been - // erased. - result = 1; - break; - case WM_PAINT: { - Window* window = - reinterpret_cast<Window*>(GetWindowLongPtr(hwnd, GWLP_USERDATA)); - if (window != NULL) - window->OnPaint(); - ::ValidateRect(hwnd, NULL); - break; - } - default: - result = ::DefWindowProc(hwnd, msg, w_param, l_param); - break; - } - return result; -} - -gfx::NativeWindow Window::CreateNativeWindow(int width, int height) { - WNDCLASS wnd_class = {0}; - HINSTANCE instance = GetModuleHandle(NULL); - wnd_class.style = CS_OWNDC; - wnd_class.lpfnWndProc = WindowProc; - wnd_class.hInstance = instance; - wnd_class.hbrBackground = - reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)); - wnd_class.lpszClassName = L"gpu_demo"; - if (!RegisterClass(&wnd_class)) - return NULL; - - DWORD wnd_style = WS_OVERLAPPED | WS_SYSMENU; - RECT wnd_rect; - wnd_rect.left = 0; - wnd_rect.top = 0; - wnd_rect.right = width; - wnd_rect.bottom = height; - AdjustWindowRect(&wnd_rect, wnd_style, FALSE); - - HWND hwnd = CreateWindow( - wnd_class.lpszClassName, - L"", - wnd_style, - 0, - 0, - wnd_rect.right - wnd_rect.left, - wnd_rect.bottom - wnd_rect.top, - NULL, - NULL, - instance, - NULL); - if (hwnd == NULL) - return NULL; - - return hwnd; -} - -gfx::PluginWindowHandle Window::PluginWindow() { - return window_handle_; -} - -void Window::Start(int limit, const base::Closure& callback, - Painter* painter) { - running_ = true; - count_ = 0; - limit_ = limit; - callback_ = callback; - painter_ = painter; - - SetWindowLongPtr(window_handle_, GWLP_USERDATA, - reinterpret_cast<LONG_PTR>(this)); - - ShowWindow(window_handle_, SW_SHOWNORMAL); - - // Post first invalidate call to kick off painting. - ::InvalidateRect(window_handle_, NULL, FALSE); - - MainLoop(); -} - -void Window::OnPaint() { - if (!running_) - return; - - if (count_ < limit_) { - painter_->OnPaint(); - count_++; - } else { - running_ = false; - if (!callback_.is_null()) { - ShowWindow(window_handle_, SW_HIDE); - callback_.Run(); - callback_.Reset(); - } - } -} - -void Window::MainLoop() { - MSG msg; - bool done = false; - while (!done) { - while (::PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { - if (msg.message == WM_QUIT || !running_) - done = true; - ::TranslateMessage(&msg); - ::DispatchMessage(&msg); - if (!done) - ::InvalidateRect(window_handle_, NULL, FALSE); - } - } -} - -} // namespace media |