File: RandomBySlot.cs

package info (click to toggle)
banshee 2.6.2-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 47,208 kB
  • sloc: xml: 163,694; cs: 137,409; sh: 11,650; ansic: 4,790; makefile: 2,922; python: 38
file content (156 lines) | stat: -rw-r--r-- 5,412 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
//
// RandomBySlot.cs
//
// Authors:
//   Elena Grassi <grassi.e@gmail.com>
//   Alexander Kojevnikov <alexander@kojevnikov.com>
//   Gabriel Burt <gburt@novell.com>
//
// Copyright (C) 2008 Elena Grassi
// Copyright (C) 2009 Alexander Kojevnikov
// Copyright (C) 2009 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

using System;
using System.Collections.Generic;
using System.Linq;

using Hyena;
using Hyena.Data;
using Hyena.Data.Sqlite;

using Banshee.ServiceStack;
using Banshee.PlaybackController;

namespace Banshee.Collection.Database
{
    public abstract class RandomBySlot : RandomBy
    {
        private static Random random = new Random ();

        private HyenaSqliteCommand query;
        protected int slot;

        public RandomBySlot (string id) : base (id)
        {
        }

        protected override void OnModelAndCacheUpdated ()
        {
            query = null;
        }

        public override void Reset ()
        {
            slot = -1;
        }

        public override bool IsReady { get { return slot != -1; } }

        public override bool Next (DateTime after)
        {
            Reset ();

            // counts[x] = number of tracks in slot x.
            int[] counts = new int[Slots];
            int default_slot = (Slots - 1) / 2;

            // Get the distribution for tracks that haven't been played since stamp.
            var reader = Shuffler == Shuffler.Playback
                ? ServiceManager.DbConnection.Query (SlotQuery, after, after)
                : ServiceManager.DbConnection.Query (SlotQuery, after);

            using (reader) {
                while (reader.Read ()) {
                    int s = Convert.ToInt32 (reader[0]);
                    int count = Convert.ToInt32 (reader[1]);

                    if (s < 0 || s >= Slots) {
                        s = default_slot;
                    }

                    counts[s] += count;
                }
            }

            if (counts.Sum () == 0) {
                slot = -1;
                return false;
            }

            // We will use powers of phi as weights. Such weights result in songs rated R played as often as songs
            // rated R-1 and R-2 combined. The exponent is adjusted to the number of slots when it's different from 5.
            const double phi = 1.618033989;

            // If you change the weights make sure ALL of them are strictly positive.
            var weights = Enumerable.Range (0, Slots).Select (i => Math.Pow (phi, i * 5 / (double) Slots)).ToArray ();

            // Apply weights to the counts.
            var weighted_counts = counts.Select ((c, i) => c * weights[i]);

            // Normalise the counts.
            var weighted_total = weighted_counts.Sum ();
            weighted_counts = weighted_counts.Select (c => c / weighted_total);

            // Now that we have our counts, get the slot a weighted random track belongs to.
            double random_value = random.NextDouble ();
            int current_slot = -1;
            foreach (var weighted_count in weighted_counts) {
                current_slot++;
                random_value -= weighted_count;
                if (random_value <= 0.0) {
                    break;
                }
            }

            slot = current_slot;
            return IsReady;
        }

        private HyenaSqliteCommand SlotQuery {
            get {
                if (query == null) {
                    query = new HyenaSqliteCommand (String.Format (SlotQuerySql,
                        Model.JoinFragment,
                        Model.CachesJoinTableEntries
                            ? String.Format ("CoreCache.ItemID = {0}.{1} AND", Model.JoinTable, Model.JoinPrimaryKey)
                            : "CoreCache.ItemId = CoreTracks.TrackID AND",
                        Model.CacheId,
                        Model.ConditionFragment
                    ));
                }
                return query;
            }
        }

        private string SlotQuerySql {
            get {
                return Shuffler == Shuffler.Playback ? PlaybackSlotQuerySql : ShufflerSlotQuerySql;
            }
        }

        protected abstract int Slots { get; }

        protected abstract string PlaybackSlotQuerySql { get; }
        protected abstract string ShufflerSlotQuerySql { get; }
    }
}