Unregister from GCM when the only GCM app is removed
[chromium-blink-merge.git] / media / tools / player_x11 / player_x11.cc
blobc1719fa5c6081f0872b31070aeb9ab4202dba5f8
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.
5 #include <signal.h>
7 #include <iostream> // NOLINT
9 #include "base/at_exit.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/files/file_path.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/memory/scoped_vector.h"
15 #include "base/threading/platform_thread.h"
16 #include "base/threading/thread.h"
17 #include "media/audio/audio_manager.h"
18 #include "media/audio/null_audio_sink.h"
19 #include "media/base/audio_hardware_config.h"
20 #include "media/base/bind_to_current_loop.h"
21 #include "media/base/decryptor.h"
22 #include "media/base/media.h"
23 #include "media/base/media_log.h"
24 #include "media/base/media_switches.h"
25 #include "media/base/pipeline.h"
26 #include "media/base/text_track.h"
27 #include "media/base/text_track_config.h"
28 #include "media/base/video_frame.h"
29 #include "media/filters/audio_renderer_impl.h"
30 #include "media/filters/ffmpeg_audio_decoder.h"
31 #include "media/filters/ffmpeg_demuxer.h"
32 #include "media/filters/ffmpeg_video_decoder.h"
33 #include "media/filters/file_data_source.h"
34 #include "media/filters/renderer_impl.h"
35 #include "media/filters/video_renderer_impl.h"
36 #include "media/tools/player_x11/data_source_logger.h"
38 // Include X11 headers here because X11/Xlib.h #define's Status
39 // which causes compiler errors with Status enum declarations
40 // in media::DemuxerStream & media::AudioDecoder.
41 #include <X11/XKBlib.h>
42 #include <X11/Xlib.h>
44 #include "media/tools/player_x11/gl_video_renderer.h"
45 #include "media/tools/player_x11/x11_video_renderer.h"
47 static Display* g_display = NULL;
48 static Window g_window = 0;
49 static bool g_running = false;
51 media::AudioManager* g_audio_manager = NULL;
53 scoped_ptr<media::DataSource> CreateDataSource(const std::string& file_path) {
54 media::FileDataSource* file_data_source = new media::FileDataSource();
55 CHECK(file_data_source->Initialize(base::FilePath(file_path)));
57 scoped_ptr<media::DataSource> data_source(file_data_source);
58 return data_source.Pass();
61 // Initialize X11. Returns true if successful. This method creates the X11
62 // window. Further initialization is done in X11VideoRenderer.
63 bool InitX11() {
64 g_display = XOpenDisplay(NULL);
65 if (!g_display) {
66 std::cout << "Error - cannot open display" << std::endl;
67 return false;
70 // Get properties of the screen.
71 int screen = DefaultScreen(g_display);
72 int root_window = RootWindow(g_display, screen);
74 // Creates the window.
75 g_window = XCreateSimpleWindow(g_display, root_window, 1, 1, 100, 50, 0,
76 BlackPixel(g_display, screen),
77 BlackPixel(g_display, screen));
78 XStoreName(g_display, g_window, "X11 Media Player");
80 XSelectInput(g_display, g_window,
81 ExposureMask | ButtonPressMask | KeyPressMask);
82 XMapWindow(g_display, g_window);
83 return true;
86 static void DoNothing() {}
88 static void OnStatus(media::PipelineStatus status) {}
90 static void OnMetadata(media::PipelineMetadata metadata) {}
92 static void OnBufferingStateChanged(media::BufferingState buffering_state) {}
94 static void OnAddTextTrack(const media::TextTrackConfig& config,
95 const media::AddTextTrackDoneCB& done_cb) {
98 static void OnEncryptedMediaInitData(const std::string& init_data_type,
99 const std::vector<uint8>& init_data) {
100 std::cout << "File is encrypted." << std::endl;
103 static void SaveStatusAndSignal(base::WaitableEvent* event,
104 media::PipelineStatus* status_out,
105 media::PipelineStatus status) {
106 *status_out = status;
107 event->Signal();
110 // TODO(vrk): Re-enabled audio. (crbug.com/112159)
111 void InitPipeline(
112 media::Pipeline* pipeline,
113 const scoped_refptr<base::SingleThreadTaskRunner>& task_runner,
114 media::Demuxer* demuxer,
115 const media::VideoRendererImpl::PaintCB& paint_cb,
116 bool /* enable_audio */) {
117 ScopedVector<media::VideoDecoder> video_decoders;
118 video_decoders.push_back(new media::FFmpegVideoDecoder(task_runner));
119 scoped_ptr<media::VideoRenderer> video_renderer(new media::VideoRendererImpl(
120 task_runner, video_decoders.Pass(), true, new media::MediaLog()));
122 ScopedVector<media::AudioDecoder> audio_decoders;
123 audio_decoders.push_back(new media::FFmpegAudioDecoder(task_runner,
124 media::LogCB()));
125 media::AudioParameters out_params(
126 media::AudioParameters::AUDIO_PCM_LOW_LATENCY,
127 media::CHANNEL_LAYOUT_STEREO,
128 44100,
130 512);
131 media::AudioHardwareConfig hardware_config(out_params, out_params);
133 scoped_ptr<media::AudioRenderer> audio_renderer(new media::AudioRendererImpl(
134 task_runner, new media::NullAudioSink(task_runner), audio_decoders.Pass(),
135 hardware_config, new media::MediaLog()));
137 scoped_ptr<media::Renderer> renderer(new media::RendererImpl(
138 task_runner, audio_renderer.Pass(), video_renderer.Pass()));
140 base::WaitableEvent event(true, false);
141 media::PipelineStatus status;
143 pipeline->Start(demuxer,
144 renderer.Pass(),
145 base::Bind(&DoNothing),
146 base::Bind(&OnStatus),
147 base::Bind(&SaveStatusAndSignal, &event, &status),
148 base::Bind(&OnMetadata),
149 base::Bind(&OnBufferingStateChanged),
150 paint_cb,
151 base::Bind(&DoNothing),
152 base::Bind(&OnAddTextTrack));
154 // Wait until the pipeline is fully initialized.
155 event.Wait();
156 CHECK_EQ(status, media::PIPELINE_OK) << "Pipeline initialization failed";
158 // And start the playback.
159 pipeline->SetPlaybackRate(1.0f);
162 void TerminateHandler(int signal) {
163 g_running = false;
166 void PeriodicalUpdate(
167 media::Pipeline* pipeline,
168 base::MessageLoop* message_loop) {
169 if (!g_running) {
170 // interrupt signal was received during last time period.
171 // Quit message_loop only when pipeline is fully stopped.
172 pipeline->Stop(base::MessageLoop::QuitClosure());
173 return;
176 // Consume all the X events
177 while (XPending(g_display)) {
178 XEvent e;
179 XNextEvent(g_display, &e);
180 switch (e.type) {
181 case ButtonPress:
183 Window window;
184 int x, y;
185 unsigned int width, height, border_width, depth;
186 XGetGeometry(g_display,
187 g_window,
188 &window,
191 &width,
192 &height,
193 &border_width,
194 &depth);
195 base::TimeDelta time = pipeline->GetMediaDuration();
196 pipeline->Seek(time*e.xbutton.x/width, base::Bind(&OnStatus));
198 break;
199 case KeyPress:
201 KeySym key = XkbKeycodeToKeysym(g_display, e.xkey.keycode, 0, 0);
202 if (key == XK_Escape) {
203 g_running = false;
204 // Quit message_loop only when pipeline is fully stopped.
205 pipeline->Stop(base::MessageLoop::QuitClosure());
206 return;
207 } else if (key == XK_space) {
208 if (pipeline->GetPlaybackRate() < 0.01f) // paused
209 pipeline->SetPlaybackRate(1.0f);
210 else
211 pipeline->SetPlaybackRate(0.0f);
214 break;
215 default:
216 break;
220 message_loop->PostDelayedTask(
221 FROM_HERE,
222 base::Bind(&PeriodicalUpdate,
223 base::Unretained(pipeline),
224 message_loop),
225 base::TimeDelta::FromMilliseconds(10));
228 int main(int argc, char** argv) {
229 base::AtExitManager at_exit;
230 media::InitializeMediaLibraryForTesting();
232 base::CommandLine::Init(argc, argv);
233 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
234 std::string filename = command_line->GetSwitchValueASCII("file");
236 if (filename.empty()) {
237 std::cout << "Usage: " << argv[0] << " --file=FILE" << std::endl
238 << std::endl
239 << "Optional arguments:" << std::endl
240 << " [--audio]"
241 << " [--alsa-device=DEVICE]"
242 << " [--use-gl]"
243 << " [--streaming]" << std::endl
244 << " Press [ESC] to stop" << std::endl
245 << " Press [SPACE] to toggle pause/play" << std::endl
246 << " Press mouse left button to seek" << std::endl;
247 return 1;
250 scoped_ptr<media::AudioManager> audio_manager(
251 media::AudioManager::CreateForTesting());
252 g_audio_manager = audio_manager.get();
254 logging::LoggingSettings settings;
255 settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
256 logging::InitLogging(settings);
258 // Install the signal handler.
259 signal(SIGTERM, &TerminateHandler);
260 signal(SIGINT, &TerminateHandler);
262 // Initialize X11.
263 if (!InitX11())
264 return 1;
266 // Initialize the pipeline thread and the pipeline.
267 base::MessageLoop message_loop;
268 base::Thread media_thread("MediaThread");
269 media_thread.Start();
271 media::VideoRendererImpl::PaintCB paint_cb;
272 if (command_line->HasSwitch("use-gl")) {
273 paint_cb = media::BindToCurrentLoop(base::Bind(
274 &GlVideoRenderer::Paint, new GlVideoRenderer(g_display, g_window)));
275 } else {
276 paint_cb = media::BindToCurrentLoop(base::Bind(
277 &X11VideoRenderer::Paint, new X11VideoRenderer(g_display, g_window)));
280 scoped_ptr<media::DataSource> data_source(new DataSourceLogger(
281 CreateDataSource(filename), command_line->HasSwitch("streaming")));
282 scoped_ptr<media::Demuxer> demuxer(new media::FFmpegDemuxer(
283 media_thread.message_loop_proxy(), data_source.get(),
284 base::Bind(&OnEncryptedMediaInitData), new media::MediaLog()));
286 media::Pipeline pipeline(media_thread.message_loop_proxy(),
287 new media::MediaLog());
288 InitPipeline(&pipeline, media_thread.message_loop_proxy(), demuxer.get(),
289 paint_cb, command_line->HasSwitch("audio"));
291 // Main loop of the application.
292 g_running = true;
294 message_loop.PostTask(FROM_HERE, base::Bind(
295 &PeriodicalUpdate, base::Unretained(&pipeline), &message_loop));
296 message_loop.Run();
298 // Cleanup tasks.
299 media_thread.Stop();
301 // Release callback which releases video renderer. Do this before cleaning up
302 // X below since the video renderer has some X cleanup duties as well.
303 paint_cb.Reset();
305 XDestroyWindow(g_display, g_window);
306 XCloseDisplay(g_display);
307 g_audio_manager = NULL;
309 return 0;