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 "media/base/serial_runner.h"
8 #include "base/callback_helpers.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/message_loop/message_loop_proxy.h"
14 // Converts a bound function accepting a Closure into a bound function
15 // accepting a PipelineStatusCB. Since closures have no way of reporting a
16 // status |status_cb| is executed with PIPELINE_OK.
17 static void RunBoundClosure(
18 const SerialRunner::BoundClosure
& bound_closure
,
19 const PipelineStatusCB
& status_cb
) {
20 bound_closure
.Run(base::Bind(status_cb
, PIPELINE_OK
));
23 // Runs |status_cb| with |last_status| on |message_loop|.
24 static void RunOnMessageLoop(
25 const scoped_refptr
<base::MessageLoopProxy
>& message_loop
,
26 const PipelineStatusCB
& status_cb
,
27 PipelineStatus last_status
) {
28 // Force post to permit cancellation of a series in the scenario where all
29 // bound functions run on the same thread.
30 message_loop
->PostTask(FROM_HERE
, base::Bind(status_cb
, last_status
));
33 SerialRunner::Queue::Queue() {}
34 SerialRunner::Queue::~Queue() {}
36 void SerialRunner::Queue::Push(
37 const BoundClosure
& bound_closure
) {
38 bound_fns_
.push(base::Bind(&RunBoundClosure
, bound_closure
));
41 void SerialRunner::Queue::Push(
42 const BoundPipelineStatusCB
& bound_status_cb
) {
43 bound_fns_
.push(bound_status_cb
);
46 SerialRunner::BoundPipelineStatusCB
SerialRunner::Queue::Pop() {
47 BoundPipelineStatusCB bound_fn
= bound_fns_
.front();
52 bool SerialRunner::Queue::empty() {
53 return bound_fns_
.empty();
56 SerialRunner::SerialRunner(
57 const Queue
& bound_fns
, const PipelineStatusCB
& done_cb
)
59 message_loop_(base::MessageLoopProxy::current()),
60 bound_fns_(bound_fns
),
62 // Respect both cancellation and calling stack guarantees for |done_cb|
64 if (bound_fns_
.empty()) {
65 message_loop_
->PostTask(FROM_HERE
, base::Bind(
66 &SerialRunner::RunNextInSeries
, weak_this_
.GetWeakPtr(), PIPELINE_OK
));
70 RunNextInSeries(PIPELINE_OK
);
73 SerialRunner::~SerialRunner() {}
75 scoped_ptr
<SerialRunner
> SerialRunner::Run(
76 const Queue
& bound_fns
, const PipelineStatusCB
& done_cb
) {
77 scoped_ptr
<SerialRunner
> callback_series(
78 new SerialRunner(bound_fns
, done_cb
));
79 return callback_series
.Pass();
82 void SerialRunner::RunNextInSeries(PipelineStatus last_status
) {
83 DCHECK(message_loop_
->BelongsToCurrentThread());
84 DCHECK(!done_cb_
.is_null());
86 if (bound_fns_
.empty() || last_status
!= PIPELINE_OK
) {
87 base::ResetAndReturn(&done_cb_
).Run(last_status
);
91 BoundPipelineStatusCB bound_fn
= bound_fns_
.Pop();
92 bound_fn
.Run(base::Bind(&RunOnMessageLoop
, message_loop_
, base::Bind(
93 &SerialRunner::RunNextInSeries
, weak_this_
.GetWeakPtr())));