1 // Copyright 2014 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 "components/copresence/handlers/audio/audio_directive_list.h"
8 #include "base/logging.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/time/time.h"
12 namespace copresence
{
16 AudioDirective::AudioDirective() {
19 AudioDirective::AudioDirective(const std::string
& op_id
, base::Time end_time
)
20 : op_id(op_id
), end_time(end_time
) {
23 AudioDirectiveList::AudioDirectiveList() {
26 AudioDirectiveList::~AudioDirectiveList() {
29 void AudioDirectiveList::AddDirective(const std::string
& op_id
,
30 base::TimeDelta ttl
) {
31 base::Time end_time
= base::Time::Now() + ttl
;
33 // In case this op is already in the list, update it instead of adding
35 std::vector
<AudioDirective
>::iterator it
= FindDirectiveByOpId(op_id
);
36 if (it
!= active_directives_
.end()) {
37 it
->end_time
= end_time
;
38 std::make_heap(active_directives_
.begin(),
39 active_directives_
.end(),
40 LatestFirstComparator());
44 active_directives_
.push_back(AudioDirective(op_id
, end_time
));
45 std::push_heap(active_directives_
.begin(),
46 active_directives_
.end(),
47 LatestFirstComparator());
50 void AudioDirectiveList::RemoveDirective(const std::string
& op_id
) {
51 std::vector
<AudioDirective
>::iterator it
= FindDirectiveByOpId(op_id
);
52 if (it
!= active_directives_
.end())
53 active_directives_
.erase(it
);
55 std::make_heap(active_directives_
.begin(),
56 active_directives_
.end(),
57 LatestFirstComparator());
60 scoped_ptr
<AudioDirective
> AudioDirectiveList::GetActiveDirective() {
61 // The top is always the instruction that is ending the latest. If that time
62 // has passed, means all our previous instructions have expired too, hence
64 if (!active_directives_
.empty() &&
65 active_directives_
.front().end_time
< base::Time::Now()) {
66 active_directives_
.clear();
69 if (active_directives_
.empty())
70 return make_scoped_ptr
<AudioDirective
>(NULL
);
72 return make_scoped_ptr(new AudioDirective(active_directives_
.front()));
75 std::vector
<AudioDirective
>::iterator
AudioDirectiveList::FindDirectiveByOpId(
76 const std::string
& op_id
) {
77 for (std::vector
<AudioDirective
>::iterator it
= active_directives_
.begin();
78 it
!= active_directives_
.end();
80 if (it
->op_id
== op_id
)
83 return active_directives_
.end();
86 } // namespace copresence