├── LICENSE
├── README.org
└── mpdsync.py
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.org:
--------------------------------------------------------------------------------
1 | * mpdsync
2 |
3 | =mpdsync= is a simple way to synchronize multiple MPD servers so that they're all playing the same thing, at the same time, with the same playlist.
4 |
5 | ** Requirements
6 |
7 | + Two or more MPD servers (duh!) which have identical music databases, like a network share
8 | + Python 2.6+ or 3.6+
9 | + [[https://pypi.python.org/pypi/python-mpd2][python-mpd2]] (This is a new fork of python-mpd, and it may not be in your distro's repo yet. You can install it with =pip=. Use the =--user= switch if you want to install it as a user instead of as root).
10 |
11 | ** Setup
12 |
13 | One MPD server will be considered the master and all the others will be slaves. Once that's taken care of, all you have to is run the =mpdsync.py= file!
14 |
15 | Upon startup, =mpdsync= will propagate the playlist and player state from the master to all of the slaves. Then =mpdsync= waits for the master server to do something, such as modify the playlist, and then makes the same changes to the slaves.
16 |
17 | ** Examples
18 |
19 | Usage is very simple:
20 |
21 | #+BEGIN_SRC
22 | usage: mpdsync.py [-h] [-m MASTER] [-s [SLAVES [SLAVES ...]]] [-p PASSWORD]
23 | [-l] [-v]
24 |
25 | Syncs multiple mpd servers.
26 |
27 | optional arguments:
28 | -h, --help show this help message and exit
29 | -m MASTER, --master MASTER
30 | Name or address of master server, optionally with port
31 | in HOST:PORT format
32 | -s [SLAVES [SLAVES ...]], --slaves [SLAVES [SLAVES ...]]
33 | Name or address of slave servers, optionally with port
34 | in HOST:PORT/LATENCY format
35 | -p PASSWORD, --password PASSWORD
36 | Password to connect to servers with
37 | -l, --latency-adjust Monitor latency between master and slaves and try to
38 | keep slaves' playing position in sync with the
39 | master's
40 | -v, --verbose Be verbose, up to -vv
41 | #+END_SRC
42 |
43 | So if your master server were on the local machine, and you wanted to also play music on a machine in the kitchen and a machine in the basement, you would simply run:
44 |
45 | =mpdsync.py -m localhost -s kitchen basement=
46 |
47 | Or if your master server were in the living room, and occasionally you wanted to sync your bedroom's MPD instance with it, you could run this from the bedroom machine:
48 |
49 | =mpdsync.py -m livingroom -s localhost=
50 |
51 | ** Development
52 |
53 | Contributions are welcome!
54 |
55 | *** TODOs
56 |
57 | + Sync player settings (e.g. shuffle, repeat). Simple, just haven't bothered yet. Although some of these should probably /not/ be synced, because the master should control which tracks play, etc.
58 | + Due to network latency and and MPD's idle command, playback can't be perfectly synced. We try to workaround this by adjusting for latency (the =-l= option), but it's not perfect. It probably cannot be completely fixed without implementing it in MPD itself. For some interesting reading, see:
59 | - https://snarfed.org/synchronizing_mp3_playback
60 | - https://github.com/snarfed/p4sync
61 | + It might be handy for adjusting the volume on the master to (optionally) proportionally adjust the volume on all of the slaves.
62 |
63 | ** Credits
64 |
65 | =mpdsync= was originally written by Nick Pegg (https://github.com/nickpegg/mpdsync). Nick doesn't use it much anymore, so he transferred the project to me.
66 |
67 | ** License
68 |
69 | GPLv3
70 |
--------------------------------------------------------------------------------
/mpdsync.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 |
3 | # * mpdsync.py
4 | # Originally written by Nick Pegg
5 | # Rewritten and updated to use python-mpd2 by Adam Porter
6 |
7 | # ** Imports
8 | import argparse
9 | from collections import defaultdict
10 | import logging
11 | import re
12 | import sys
13 | from threading import Thread
14 | import time
15 |
16 | import mpd # Using python-mpd2
17 |
18 | # Verify python-mpd2 is being used
19 | if mpd.VERSION < (0, 5, 4):
20 | print('ERROR: This script requires python-mpd2 >= 0.5.4.')
21 | sys.exit(1)
22 |
23 | # ** Constants
24 |
25 | DEFAULT_PORT = 6600
26 | FILE_PREFIX_RE = re.compile('^file: ')
27 |
28 | # Max number of adjustments to make before adjusting by ping again
29 | MAX_ADJUSTMENTS = 5
30 |
31 | # Max adjustment size in ms (larger than this will trigger an adjustment by ping)
32 | MAX_ADJUSTMENT = 0.300
33 |
34 | # Stop reseeking when average difference gets below:
35 | MIN_DIFFERENCE = 0.030
36 |
37 | # ** Classes
38 | class MyFloat(float):
39 | '''Rounds and pads to 3 decimal places when printing. Also overrides
40 | built-in operator methods to return myFloats instead of regular
41 | floats.'''
42 |
43 | # There must be a better, cleaner way to do this, maybe using
44 | # decorators or overriding __metaclass__, but I haven't been able
45 | # to figure it out. Since you can't override float's methods, you
46 | # can't simply override __str__, for all floats. And because
47 | # whenever you +|-|/|* on a subclassed float, it returns a regular
48 | # float, you have to also override those built-in methods to keep
49 | # returning the subclass.
50 |
51 | if sys.version_info[0] < 3:
52 | def __init__(self, num, roundBy=3):
53 | super(MyFloat, self).__init__(num)
54 | self.roundBy = roundBy
55 | else:
56 | def __new__(cls, num, roundBy=3):
57 | instance = super().__new__(cls, num)
58 | instance.roundBy = roundBy
59 | return instance
60 |
61 | def __abs__(self):
62 | return MyFloat(float.__abs__(self))
63 |
64 | def __add__(self, val):
65 | return MyFloat(float.__add__(self, val))
66 |
67 | def __div__(self, val):
68 | return MyFloat(float.__div__(self, val))
69 |
70 | def __mul__(self, val):
71 | return MyFloat(float.__mul__(self, val))
72 |
73 | def __sub__(self, val):
74 | return MyFloat(float.__sub__(self, val))
75 |
76 | def __str__(self):
77 | return "{:.3f}".format(round(self, self.roundBy))
78 |
79 | # __repr__ is used in, e.g. mpd.seek(), so it gets a rounded
80 | # float. MPD doesn't support more than 3 decimal places, anyway.
81 | __repr__ = __str__
82 |
83 |
84 | class AveragedList(list):
85 |
86 | def __init__(self, data=None, length=None, name=None, printDebug=False):
87 | self.log = logging.getLogger(self.__class__.__name__)
88 |
89 | # TODO: Add weighted average. Might be better than using the range.
90 |
91 | self.name = name
92 | self.length = length
93 | self.max = 0
94 | self.min = 0
95 | self.range = 0
96 | self.average = 0 # actually the moving average; not renaming right now...
97 | self.overall_average = 0
98 | self.printDebug = printDebug
99 |
100 | # TODO: Isn't there a more Pythonic way to do this?
101 | if data:
102 | super(AveragedList, self).__init__(data)
103 | self._updateStats()
104 | else:
105 | super(AveragedList, self).__init__()
106 |
107 | def __str__(self):
108 | return 'name:%s length:%s overall-average:%s moving-average:%s range:%s max:%s min:%s' % (
109 | self.name, len(self), self.overall_average, self.average, self.range, self.max, self.min)
110 |
111 | __repr__ = __str__
112 |
113 | def append(self, arg):
114 | arg = MyFloat(arg)
115 | super(AveragedList, self).append(arg)
116 | self._updateStats()
117 |
118 | def clear(self):
119 | '''Empties the list.'''
120 |
121 | while len(self) > 0:
122 | self.pop()
123 |
124 | def extend(self, *args):
125 | args = [[MyFloat(a) for l in args for a in l]]
126 | super(AveragedList, self).extend(*args)
127 | self._updateStats()
128 |
129 | def insert(self, pos, *args):
130 | args = [MyFloat(a) for a in args]
131 | super(AveragedList, self).insert(pos, *args)
132 |
133 | # Remove elements if length is limited
134 | while (self.length
135 | and len(self) > self.length):
136 | self.pop()
137 | self._updateStats()
138 |
139 | def _updateStats(self):
140 | # Actually the moving average. Taking the first 10 elements
141 | # since I usually insert rather than append (not sure why,
142 | # though; maybe I should change that)
143 | to_average = self[:10]
144 | self.average = MyFloat(sum(to_average) / len(to_average))
145 |
146 | self.overall_average = MyFloat(sum(self) / len(self))
147 | self.max = MyFloat(max(self))
148 | self.min = MyFloat(min(self))
149 | self.overall_range = MyFloat(self.max - self.min)
150 |
151 | # "Moving range" of first 10 elements (necessary for properly
152 | # setting the max difference)
153 | self.range = MyFloat(max(to_average) - min(to_average))
154 |
155 | if self.printDebug:
156 | self.log.debug(self)
157 |
158 |
159 | class Client(mpd.MPDClient):
160 | '''Subclasses mpd.MPDClient, keeping state data, reconnecting as
161 | needed, etc.'''
162 |
163 | initAttrs = {None: ['currentStatus', 'lastSong',
164 | 'currentSongFiletype', 'playlist',
165 | 'playlistVersion', 'playlistLength',
166 | 'song', 'duration', 'elapsed', 'state',
167 | 'hasBeenSynced', 'playing', 'paused'],
168 | False: ['consume', 'random', 'repeat',
169 | 'single']}
170 |
171 | def __init__(self, host, port=DEFAULT_PORT, password=None, latency=None,
172 | logger=None):
173 |
174 | super(Client, self).__init__()
175 |
176 | # Command timeout
177 | self.timeout = 10
178 |
179 | # Split host/latency
180 | if '/' in host:
181 | host, latency = host.split('/')
182 |
183 | if latency is not None:
184 | self.latency = float(latency)
185 | else:
186 | self.latency = None
187 |
188 | # Split host/port
189 | if ':' in host:
190 | host, port = host.split(':')
191 |
192 | self.host = host
193 | self.port = port
194 | self.password = password
195 |
196 | self.log = logger.getChild('%s(%s)' %
197 | (self.__class__.__name__, self.host))
198 |
199 | self.syncLoopLocked = False
200 | self.playedSinceLastPlaylistUpdate = False
201 |
202 | self.currentSongShouldSeek = True
203 | self.currentSongAdjustments = None
204 | self.currentSongDifferences = AveragedList(
205 | name='currentSongDifferences')
206 |
207 | self.pings = AveragedList(name='%s.pings' % self.host, length=10)
208 | self.adjustments = AveragedList(name='%sadjustments' % self.host,
209 | length=20)
210 | self.initialPlayTimes = AveragedList(name='%s.initialPlayTimes'
211 | % self.host, length=20,
212 | printDebug=True)
213 |
214 | # MAYBE: Should I reset this in _initAttrs() ?
215 | self.reSeekedTimes = 0
216 |
217 | # Record adjustments by file type to see if there's a pattern
218 | self.fileTypeAdjustments = defaultdict(AveragedList)
219 |
220 | # TODO: Record each song's number of adjustments in a list (by
221 | # filename), and print on exit. This way I can play a short
222 | # playlist in a loop and see if there is a pattern with
223 | # certain songs being consistently bad at syncing and seeking.
224 | self.song_adjustments = []
225 |
226 | self.song_differences = []
227 |
228 | def ping(self):
229 | '''Pings the daemon and records how long it took.'''
230 |
231 | self.pings.insert(0, timeFunction(super(Client, self).ping))
232 |
233 | def checkConnection(self):
234 | '''Pings the daemon and tries to reconnect if necessary.'''
235 |
236 | # I don't know why this is necessary, but for some reason the
237 | # slave connections tend to get dropped.
238 | try:
239 | self.ping()
240 |
241 | except Exception as e:
242 | self.log.debug('Connection to "%s" seems to be down. '
243 | 'Trying to reconnect...', self.host)
244 |
245 | # Try to disconnect first
246 | try:
247 | self.disconnect() # Maybe this will help it reconnect
248 | except Exception as e:
249 | self.log.exception("Couldn't DISconnect from client %s: %s",
250 | self.host, e)
251 |
252 | # Try to reconnect
253 | try:
254 | self.connect()
255 | except Exception as e:
256 | self.log.critical('Unable to reconnect to "%s"', self.host)
257 |
258 | return False
259 | else:
260 | self.log.debug('Reconnected to "%s"', self.host)
261 |
262 | return True
263 |
264 | else:
265 | self.log.debug("Connection still up to %s", self.host)
266 |
267 | return True
268 |
269 | def connect(self):
270 | '''Connects to the daemon, sets the password if necessary, and tests
271 | the ping time.'''
272 |
273 | # Reset initial values
274 | for val, attrs in self.initAttrs.items():
275 | for attr in attrs:
276 | setattr(self, attr, val)
277 |
278 | super(Client, self).connect(self.host, self.port)
279 |
280 | if self.password:
281 | super(Client, self).password(self.password)
282 |
283 | self.testPing()
284 |
285 | self.log.debug("Connected.")
286 |
287 | def disconnect(self):
288 | "Disconnect from MPD."
289 |
290 | super(Client, self).disconnect()
291 |
292 | self.log.debug("Disconnected.")
293 |
294 | def getPlaylist(self):
295 | '''Gets the playlist from the daemon.'''
296 |
297 | self.playlist = super(Client, self).playlist()
298 |
299 | self.log.debug("Got playlist")
300 |
301 | def pause(self):
302 | '''Pauses the daemon and tracks the playing state.'''
303 |
304 | super(Client, self).pause()
305 | self.playing = False
306 | self.paused = True
307 |
308 | def play(self, initial=False):
309 | '''Plays the daemon, adjusting starting position as necessary.'''
310 |
311 | # FIXME: I was checking if (self.playedSinceLastPlaylistUpdate
312 | # == False), but I removed that code. I'm not sure if it's
313 | # still necessary.
314 |
315 | if initial:
316 | # Slave is not already playing, or is playing a different song
317 | self.log.debug("%s.play(initial=True)", self.host)
318 |
319 | # Calculate adjustment
320 | if self.latency is not None:
321 | # Use user-set adjustment
322 | offset = self.latency
323 | elif self.initialPlayTimes.average:
324 | self.log.debug("Adjusting by average initial play time")
325 |
326 | offset = self.initialPlayTimes.average
327 | else:
328 | self.log.debug("Adjusting by average ping")
329 |
330 | offset = self.pings.average
331 |
332 | self.log.debug('Adjusting initial play by %s seconds', offset)
333 |
334 | # Update status (not sure if this is still necessary, but
335 | # it might help avoid race conditions or something)
336 | self.status()
337 |
338 | # Execute in command list
339 | # TODO: Is a command list necessary or helpful here?
340 | try:
341 | self.command_list_ok_begin()
342 | except mpd.CommandListError as e:
343 | # Server was already in a command list; probably a
344 | # lost client connection, so try again
345 | self.log.exception("mpd.CommandListError: %s", e)
346 |
347 | self.command_list_end()
348 | self.command_list_ok_begin()
349 |
350 | # Adjust starting position if necessary
351 | # TODO: Is it necessary or good to make sure it's a
352 | # positive adjustment? There seem to be some tracks that
353 | # require negative adjustments, but I don't know if that
354 | # would be the case when playing from a stop
355 | if offset > 0:
356 | tries = 0
357 |
358 | # Wait for the server to...catch up? I don't remember
359 | # exactly why this code is here, because it seems like
360 | # the master shouldn't be behind the slaves, but I
361 | # suppose it could happen on song changes
362 | while self.elapsed is None and tries < 10:
363 | time.sleep(0.2)
364 | self.status()
365 | self.log.debug(self.song)
366 | tries += 1
367 |
368 | # Seek to the adjusted playing position
369 | self.seek(self.song, self.elapsed + offset)
370 |
371 | # Issue the play command
372 | super(Client, self).play()
373 |
374 | # Execute command list
375 | try:
376 | result = self.command_list_end()
377 | except mpd.ProtocolError:
378 | self.log.exception("Unable to play client: %s. Trying to resync...", self.host)
379 |
380 | return False
381 |
382 | else:
383 | # Slave is already playing current song
384 | self.log.debug("%s.play(initial=False)", self.host)
385 |
386 | # Issue the play command
387 | result = super(Client, self).play()
388 |
389 | # TODO: Not sure if this is still necessary to track...
390 | self.playedSinceLastPlaylistUpdate = True
391 |
392 | return result
393 |
394 | def seek(self, song, elapsed):
395 | '''Seeks daemon to a position and updates local attributes for current
396 | song and elapsed time.'''
397 |
398 | self.song = song
399 | self.elapsed = elapsed
400 | super(Client, self).seek(self.song, self.elapsed)
401 |
402 | def status(self):
403 | '''Gets daemon's status and updates local attributes.'''
404 |
405 | self.currentStatus = super(Client, self).status()
406 |
407 | # Wrap whole thing in try/except because of MPD protocol
408 | # errors. But I may have fixed this by "locking" each client
409 | # in the loop, so this may not be necessary anymore.
410 | try:
411 |
412 | # Not sure why, but sometimes this ends up as None when
413 | # the track or playlist is changed...?
414 | if self.currentStatus:
415 | # Status response received
416 |
417 | # Set playlist attrs
418 | self.playlistLength = int(self.currentStatus['playlistlength'])
419 | if self.playlist:
420 | if self.song:
421 | if int(self.song) >= len(self.playlist):
422 | self.log.exception(
423 | 'Current song number > (playlist length - 1)'
424 | ' (%s>%s). What is causing this pesky bug?',
425 | int(self.song), len(self.playlist))
426 | else:
427 | self.currentSongFiletype = (
428 | self.playlist[int(self.song)].split('.')[-1])
429 | else:
430 | self.currentSongFiletype = None
431 |
432 | self.log.debug('Current filetype: %s',
433 | self.currentSongFiletype)
434 |
435 | # Set True/False attrs
436 | for attr in self.initAttrs[False]:
437 | val = (True
438 | if self.currentStatus[attr] == '1'
439 | else False)
440 | setattr(self, attr, val)
441 |
442 | # Set playing state attrs
443 | self.state = self.currentStatus['state']
444 | self.playing = (True
445 | if self.state == 'play'
446 | else False)
447 | self.paused = (True
448 | if self.state == 'pause'
449 | else False)
450 |
451 | # Set song attrs
452 | self.song = (self.currentStatus['song']
453 | if 'song' in self.currentStatus
454 | else None)
455 | for attr in ['duration', 'elapsed']:
456 | val = (MyFloat(self.currentStatus[attr])
457 | if attr in self.currentStatus
458 | else None)
459 | setattr(self, attr, val)
460 |
461 | else:
462 | # None? Sigh... This shouldn't happen...if it does
463 | # I'll need to reconnect, I think...
464 | self.log.error("No status received for client %s", self.host)
465 |
466 | except Exception as e:
467 | # No status response :(
468 | self.log.exception("Unable to get status for client %s: %s",
469 | self.host, e)
470 |
471 | # Try to reconnect
472 | self.checkConnection()
473 |
474 | # TODO: Add other attributes, e.g. {'playlistlength': '55',
475 | # 'playlist': '3868', 'repeat': '0', 'consume': '0',
476 | # 'mixrampdb': '0.000000', 'random': '0', 'state': 'stop',
477 | # 'volume': '-1', 'single': '0'}
478 |
479 | def testPing(self):
480 | '''Pings the daemon 5 times and sets the initial maxDifference.'''
481 |
482 | for i in range(5):
483 | self.ping()
484 | time.sleep(0.1)
485 |
486 | self.maxDifference = self.pings.average * 5
487 |
488 | self.log.debug('Average ping for %s: %s seconds; '
489 | 'setting maxDifference: %s',
490 | self.host, self.pings.average, self.maxDifference)
491 |
492 |
493 | class Master(Client):
494 | def __init__(self, *args, **kwargs):
495 |
496 | # Don't pass adjustLatency to Client
497 | # FIXME: Is there a nicer way to do this?
498 | attr = 'adjustLatency'
499 | if attr in kwargs:
500 | self.adjustLatency = kwargs[attr]
501 | del kwargs[attr]
502 | else:
503 | self.adjustLatency = None
504 |
505 | super(Master, self).__init__(*args, **kwargs)
506 |
507 | self.slaves = []
508 | self.slaveDifferences = AveragedList(name='slaveDifferences', length=10)
509 | self.elapsedLoopRunning = False
510 |
511 | self.seeker = None
512 |
513 | def _average_difference(self, slave):
514 | """Return absolute value of average difference between slave and
515 | master, recording data in attributes as side-effect."""
516 |
517 | # TODO: Some songs MPD seems unable to sync properly. If the
518 | # seek value is higher than a certain position, it will always
519 | # seek to around the same value, meaning it basically can't
520 | # seek past a certain point in the song. This leads to
521 | # endless syncs, and it means the slave seeks to the same
522 | # place over and over again until the master moves on to the
523 | # next song. This causes the slave to sound like a broken
524 | # record. Perhaps charming in a nostalgic kind of way, but
525 | # not exactly desirable... So I guess I need to try to detect
526 | # this somehow. Sigh.
527 |
528 | # Check pings
529 | self.ping()
530 | slave.ping()
531 | masterPing = self.pings[0]
532 | slavePing = slave.pings[0]
533 | ping = abs(masterPing - slavePing)
534 |
535 | self.log.debug("Last ping time for slave %s: %s", slave.host, ping)
536 |
537 | # Get master status and time how long it takes
538 | masterStatusLatency = MyFloat(timeFunction(self.status))
539 |
540 | self.log.debug("masterStatusLatency:%s", masterStatusLatency)
541 |
542 | # Get slave status and time how long it takes
543 | slaveStatusLatency = MyFloat(timeFunction(slave.status))
544 |
545 | self.log.debug("slaveStatusLatency:%s", slaveStatusLatency)
546 |
547 | # If song changed, reset differences
548 | if slave.lastSong != slave.song:
549 | self.log.debug("Song changed (%s -> %s); "
550 | "resetting %s.currentSongDifferences",
551 | slave.lastSong, slave.song, slave.host)
552 |
553 | # TODO: Put this in a function?
554 | slave.currentSongShouldSeek = True
555 | slave.currentSongAdjustments = AveragedList(name='%s.currentSongAdjustments' % slave.host,
556 | length=10, printDebug=True)
557 | slave.currentSongDifferences = AveragedList(name='%s.currentSongDifferences' % slave.host)
558 | slave.lastSong = slave.song
559 |
560 | # Record song differences and adjustments for later debugging
561 | slave.song_adjustments.append({'file': slave.playlist[int(slave.song)],
562 | 'adjustments': slave.currentSongAdjustments})
563 | slave.song_differences.append({'file': slave.playlist[int(slave.song)],
564 | 'differences': slave.currentSongDifferences})
565 |
566 | if slave.elapsed:
567 |
568 | # Seems like it would make sense to add the
569 | # masterStatusLatency, but I seem to be observing that the
570 | # opposite is the case...
571 | difference = self.elapsed - (slave.elapsed + slaveStatusLatency)
572 |
573 | # Record the difference
574 | slave.currentSongDifferences.insert(0, difference)
575 |
576 | # "Difference" is approximately aligned with the average
577 | # below in the debug output
578 | self.log.debug('Master/%s elapsed:%s/%s Difference:%s',
579 | slave.host, self.elapsed, slave.elapsed, difference)
580 | self.log.debug(slave.currentSongDifferences)
581 | self.log.debug(slave.currentSongAdjustments)
582 |
583 | return abs(slave.currentSongDifferences.average)
584 |
585 | def status(self):
586 | '''Gets the master's status and updates its playlistVersion
587 | attribute.'''
588 |
589 | super(Master, self).status()
590 |
591 | # Use the master's reported playlist version (for the slaves
592 | # we update it manually to match the master)
593 | self.playlistVersion = self.currentStatus['playlist']
594 |
595 | def addSlave(self, host, password=None):
596 | '''Connects to a slave, gets its status, and adds it to the list of
597 | slaves.'''
598 |
599 | slave = Client(host, password=password, logger=self.log)
600 |
601 | # Connect to slave
602 | try:
603 | slave.connect()
604 | except Exception as e:
605 | self.log.exception('Unable to connect to slave: %s:%s: %s',
606 | slave.host, slave.port, e)
607 | else:
608 | self.log.debug('Connected to slave: %s' % slave.host)
609 |
610 | self.slaves.append(slave)
611 |
612 | # Get initial status (this is not automatic upon connection)
613 | slave.status()
614 |
615 | def syncAll(self):
616 | '''Syncs all slaves completely.'''
617 |
618 | self.syncPlaylists()
619 | self.syncOptions()
620 | self.syncPlayers()
621 |
622 | def syncPlaylists(self):
623 | '''Syncs all slaves' playlists.'''
624 |
625 | # Get master info
626 | self.status()
627 | self.getPlaylist()
628 |
629 | # Sync slaves
630 | for slave in self.slaves:
631 |
632 | # Reconnect if necessary (slave connections tend to drop for
633 | # some reason)
634 | if not slave.checkConnection():
635 | # If it can't reconnect...we can't sync the playlists,
636 | # or it will raise an exception
637 | raise Exception("Unable to reconnect to slave: %s", slave.host)
638 |
639 | if not slave.hasBeenSynced:
640 | # Do a full sync the first time
641 |
642 | # Compare playlists; don't clear if they're the same
643 | slave.getPlaylist()
644 | if slave.playlist != self.playlist:
645 | # Playlists differ
646 | self.log.debug("Playlist differs on slave %s; syncing...",
647 | slave.host)
648 |
649 | #Start command list
650 | slave.command_list_ok_begin()
651 |
652 | # Clear playlist
653 | slave.clear()
654 |
655 | # Add tracks
656 | for song in self.playlist:
657 | # Remove "file: " from song filename
658 | slave.add(FILE_PREFIX_RE.sub('', song))
659 |
660 | # Execute command list
661 | result = slave.command_list_end()
662 |
663 | if not result:
664 | self.log.critical("Couldn't add tracks to playlist on slave: %s",
665 | slave.host)
666 | continue
667 | else:
668 | self.log.debug("Added to playlist on slave %s, result: %s",
669 | slave.host, result)
670 |
671 | slave.hasBeenSynced = True
672 |
673 | else:
674 | # Playlists are the same
675 | self.log.debug("Playlist is the same on slave %s", slave.host)
676 |
677 | slave.hasBeenSynced = True
678 |
679 | else:
680 | # Slave has been synced before; sync playlist changes
681 |
682 | # TODO: if slave.playlistVersion is None, handle it
683 |
684 | # Get list of changes
685 | changes = self.plchanges(slave.playlistVersion)
686 |
687 | # Start command list
688 | slave.command_list_ok_begin()
689 |
690 | # Make changes
691 | for change in changes:
692 | self.log.debug('Adding to slave:"%s" file:"%s" at pos:%s',
693 | slave.host, change['file'], change['pos'])
694 |
695 | slave.addid(change['file'], change['pos'])
696 |
697 | # Execute command list
698 | try:
699 | results = slave.command_list_end()
700 | except mpd.ProtocolError as e:
701 | if e.message == "Got unexpected 'OK'":
702 | self.log.exception("mpd.ProtocolError: Got unexpected 'OK'")
703 |
704 | continue # Maybe it will work next time around...
705 |
706 | # Check results
707 | if not results:
708 | # This should not happen. SIGH.
709 | self.log.error("SIGH.")
710 |
711 | continue
712 |
713 | # Add tags for remote tracks (e.g. files streaming
714 | # over HTTP) that have tags in playlist
715 | slave.command_list_ok_begin()
716 | for num, change in enumerate(changes):
717 | if 'http' in change['file']:
718 | for tag in ['artist', 'album', 'title', 'genre']:
719 | if tag in change:
720 |
721 | # results is a list of song IDs that
722 | # were added; it corresponds to
723 | # changes
724 | slave.addtagid(int(results[num]), tag, change[tag])
725 | try:
726 | slave.command_list_end()
727 | except mpd.ProtocolError as e:
728 | if e.message == "Got unexpected 'OK'":
729 | self.log.exception("mpd.ProtocolError: Got unexpected 'OK'")
730 |
731 | # Update slave status
732 | slave.status()
733 |
734 | # Truncate the slave playlist to the same length as the master
735 | if self.playlistLength == 0:
736 | slave.clear()
737 | elif self.playlistLength < slave.playlistLength:
738 | self.log.debug("Deleting from %s to %s",
739 | self.playlistLength - 1, slave.playlistLength - 1)
740 |
741 | slave.delete((self.playlistLength - 1, slave.playlistLength - 1))
742 |
743 | # Check result
744 | slave.status()
745 | if slave.playlistLength != self.playlistLength:
746 | self.log.error("Playlist lengths don't match for slave %s: %s / %s",
747 | slave.host, slave.playlistLength, self.playlistLength)
748 |
749 | # Make sure the slave's playing status still matches the
750 | # master (for some reason, deleting a track lower-numbered
751 | # than the currently playing track makes the slaves stop
752 | # playing)
753 | if slave.state != self.state:
754 | # Resync the slave
755 | self.syncPlayer(slave)
756 |
757 | # Update slave playlist version number to match the master's
758 | slave.playlistVersion = self.playlistVersion
759 |
760 | # Not sure if this is still necessary
761 | self.playedSinceLastPlaylistUpdate = False
762 |
763 | def syncOptions(self):
764 | '''TBI: Sync player options (e.g. random).'''
765 | pass
766 |
767 | def syncPlayers(self):
768 | '''Syncs all slaves' player status.'''
769 |
770 | # SOMEDAY: do this in parallel?
771 | for slave in self.slaves:
772 | if not self.syncPlayer(slave):
773 | self.log.debug("Unable to sync slave: %s. Trying to resync all...", slave.host)
774 |
775 | self.syncAll()
776 |
777 | return None # What should we return here?
778 |
779 | # Restart sync thread if necessary
780 | if self.adjustLatency:
781 | if self.playing:
782 | self.checkSeeker()
783 | else:
784 | if not self.paused:
785 | # Stopped
786 | self.stopSeeker()
787 |
788 | def syncPlayer(self, slave):
789 | '''Sync's a slave's player status.'''
790 |
791 | # Try 5 times
792 | tries = 0
793 | while tries < 5:
794 |
795 | try:
796 | # Update master info
797 | self.status()
798 |
799 | # Reconnect if connection dropped
800 | slave.checkConnection()
801 |
802 | # Update slave status
803 | slave.status()
804 |
805 | # Sync player status
806 | if self.playing:
807 |
808 | # Verify playlist is set. Sometimes this can get emptied somehow, when connections drop...
809 | if not slave.playlist:
810 | self.syncPlaylists()
811 |
812 | # Don't re-sync if the slave is already playing
813 | # the same song at the right place
814 | if (slave.playing
815 | and slave.song == self.song
816 | and self._average_difference(slave) < 1):
817 |
818 | self.log.debug('Slave %s and master already playing same song, less than 1 second apart',
819 | slave.host)
820 |
821 | else:
822 | # Slave not playing, or playing a different song
823 | self.log.debug('Playing slave %s, initial=True' % slave.host)
824 |
825 | # Seek to current master position before playing
826 | try:
827 | slave.seek(self.song, self.elapsed)
828 | except Exception as e:
829 | self.log.exception("Couldn't seek slave %s: %s", slave.host, e)
830 |
831 | return False
832 |
833 | # Play it
834 | if not slave.play(initial=True):
835 | self.log.critical("Couldn't play slave: %s", slave.host)
836 |
837 | return False
838 |
839 | # Wait a moment and then check the difference
840 | time.sleep(0.2)
841 | playLatency = self._average_difference(slave)
842 |
843 | if not playLatency:
844 | # This probably means the slave isn't playing at all for some reason
845 | self.log.error('No playLatency for slave "%s"', slave.host)
846 |
847 | slave.stop() # Maybe...?
848 |
849 | return False
850 |
851 | self.log.debug('Client %s took %s seconds to start playing',
852 | slave.host, playLatency)
853 |
854 | # Update initial play times
855 | slave.initialPlayTimes.insert(0, playLatency)
856 |
857 | elif self.paused:
858 | slave.pause()
859 | else:
860 | slave.stop()
861 |
862 | except Exception as e:
863 | self.log.exception("Unable to syncPlayer for slave %s. Tries:%s Error:%s",
864 | slave.host, tries, e)
865 | tries += 1
866 |
867 | return False
868 | else:
869 | # Sync succeeded
870 | return True
871 |
872 | def startSeeker(self):
873 | '''Runs a loop trying to keep the slaves in sync with the master.'''
874 |
875 | # Make new connection to master server that won't idle()
876 | self.seeker = Seeker(self)
877 | self.seeker.connect()
878 | self.seeker.start_loop()
879 |
880 | def checkSeeker(self):
881 | "Restart seeker thread if necessary."
882 |
883 | if self.seeker:
884 | self.seeker.check_loop()
885 | else:
886 | self.startSeeker()
887 |
888 | def stopSeeker(self):
889 | "Stop sync loop thread, disconnect seeker connection, and cleanup Seeker instance."
890 |
891 | if self.seeker:
892 | # Stop thread
893 | self.seeker.sync = False
894 | while self.seeker.thread.is_alive():
895 | self.log.debug("Waiting for seeker thread to stop...")
896 | time.sleep(0.1)
897 |
898 | self.log.debug("Seeker thread stopped.")
899 |
900 | # Disconnect and cleanup object
901 | self.seeker.disconnect()
902 | self.seeker = None
903 |
904 |
905 | class Seeker(Master):
906 | '''Used to make a second connection to the master server that doesn't
907 | idle, which can be used to re-seek slaves' playing positions.'''
908 |
909 | # TODO: It would seem like a good idea to avoid doing some things
910 | # in this instance, like syncing the playlist, since that's not
911 | # relevant to the seeker and takes some time.
912 |
913 | def __init__(self, master):
914 | super(Seeker, self).__init__(master.host, logger=master.log)
915 |
916 | # By doing this, we don't have to run status() in the loop,
917 | # because it can get the master's playing status from the
918 | # other instance
919 | self.master = master
920 | self.slaves = master.slaves
921 | self.sync = False
922 |
923 | def start_loop(self):
924 | "Start sync thread (_syncLoop)."
925 |
926 | self.sync = True
927 |
928 | # Remove any stale locks
929 | for slave in self.slaves:
930 | slave.syncLoopLocked = False
931 |
932 | self.thread = Thread(target=self._syncLoop)
933 | self.thread.daemon = True
934 | self.thread.start()
935 |
936 | def check_loop(self):
937 | "Restart _syncLoop if necessary."
938 |
939 | if self.sync and not self.thread.is_alive():
940 | self.log.warning("Sync thread died; restarting...")
941 |
942 | self.checkConnection()
943 | self.start_loop()
944 |
945 | def _syncLoop(self):
946 | "Run loop keeping slaves' position in sync."
947 |
948 | # Run the loop
949 | while self.sync:
950 | sleepTime = None
951 |
952 | # NOTE: This works, but the thread won't stop while it's
953 | # sleeping, so it can take several seconds in the worst
954 | # case for the thread to notice that it should stop. This
955 | # doesn't seem like a problem most of the time, unless the
956 | # user stops MPD and then starts it playing again before
957 | # this thread has terminated, in which case the slaves
958 | # won't start playing again until the thread terminates
959 | # and the script catches up with the subsystem updates.
960 | # I'm not sure how to fix this short of switching to a
961 | # subprocess, because killing threads is not supported,
962 | # and any workarounds are necessarily ugly hacks which
963 | # might have bad side effects.
964 |
965 | if self.master.playing:
966 |
967 | # Check each slave's average difference
968 | for slave in self.slaves:
969 |
970 | # Don't run the loop if an earlier one is already
971 | # waiting for a result (this might be helping to
972 | # cause the MPD protocol errors)
973 | if slave.syncLoopLocked:
974 | self.log.debug("syncLoopLocked for slave %s", slave.host)
975 |
976 | continue
977 | else:
978 | # Lock the slave
979 | slave.syncLoopLocked = True
980 |
981 | # TODO: If finished seeking, stop the loop until
982 | # the next track (and restart it on track change)
983 |
984 | if self._reseek_necessary(slave):
985 | self._reseek_slave(slave)
986 | sleepTime = 2 # Sleep 2 seconds after reseeking
987 |
988 | # Unlock the slave
989 | slave.syncLoopLocked = False
990 |
991 | # Sleep for 400ms for each measurement, but at least 2 s
992 | if not sleepTime:
993 | sleepTime = max(2, 0.4 * len(slave.currentSongDifferences))
994 |
995 | # Print comparison between two slaves
996 | if len(self.slaves) > 1:
997 | self.slaveDifferences.insert(0, abs(self.slaves[0].currentSongDifferences.average
998 | - self.slaves[1].currentSongDifferences.average))
999 | self.log.debug("Average difference between slaves 1 and 2: %s",
1000 | self.slaveDifferences.average)
1001 |
1002 | else:
1003 | # Not playing; sleep 2 seconds
1004 | sleepTime = 2
1005 |
1006 | # TODO: Instead, stop this thread, and restart it when playing resumes
1007 |
1008 | # BUG: If there are multiple slaves, this sleeps for
1009 | # whatever sleepTime was set to for the last slave. Not a
1010 | # big deal, but might need fixing.
1011 | self.log.debug('Sleeping for %s seconds', sleepTime)
1012 |
1013 | time.sleep(sleepTime)
1014 |
1015 | def _reseek_slave(self, slave):
1016 | "Seek slave position to match master's."
1017 |
1018 | # TODO: Idea: Maybe part of the problem is that MPD can't seek
1019 | # songs precisely, but only to certain places, like between
1020 | # frames, or something like that. So maybe if the master and
1021 | # slaves were both seeked to the same value initially, it
1022 | # would cause them to both seek to about the same place, once
1023 | # or twice, instead of the slaves trying repeatedly to get a
1024 | # good sync.
1025 |
1026 | adjustBy = self._calc_adjustment(slave)
1027 |
1028 | # Calculate position
1029 | position = self.elapsed - adjustBy
1030 | if position < 0:
1031 | self.log.debug("Position for %s was < 0 (%s); skipping adjustment",
1032 | slave.host, position)
1033 |
1034 | return False
1035 |
1036 | self.log.debug('Master elapsed:%s Adjusting %s to:%s (song: %s)',
1037 | self.elapsed, slave.host, position, self.song)
1038 |
1039 | # For some reason this is getting weird errors like
1040 | # "mpd.ProtocolError: Got unexpected return value: 'volume:
1041 | # 0'", and I don't want the script to quit, so wrapping it in
1042 | # a try/except should help it try again
1043 | try:
1044 | # Try to seek to current playing position, adjusted for
1045 | # latency
1046 | slave.seek(self.song, position)
1047 |
1048 | except Exception as e:
1049 | # Seek failed
1050 | self.log.exception("Unable to seek slave %s: %s", slave.host, e)
1051 |
1052 | # Try to completely resync the slave
1053 | slave.playlistVersion = None
1054 | self.syncPlaylists()
1055 |
1056 | # Clear song adjustments to prevent wild jittering after
1057 | # seek timeouts
1058 | slave.currentSongAdjustments.clear()
1059 | slave.checkConnection()
1060 |
1061 | return False
1062 |
1063 | else:
1064 | # Seek succeeded
1065 |
1066 | slave.adjustments.insert(0, adjustBy)
1067 | slave.currentSongAdjustments.append(adjustBy)
1068 | slave.fileTypeAdjustments[slave.currentSongFiletype].append(adjustBy)
1069 |
1070 | # Reset song differences
1071 | slave.currentSongDifferences.clear()
1072 |
1073 | return True
1074 |
1075 | def _calc_adjustment(self, slave):
1076 | "Return adjustment to make to sync slave with master."
1077 |
1078 | # Choose adjustment
1079 | if slave.latency is not None:
1080 | # Use the user-set adjustment
1081 | self.log.debug("Adjusting %s by slave.latency: %s", slave.host, slave.latency)
1082 |
1083 | adjustBy = MyFloat(slave.latency)
1084 |
1085 | else:
1086 | # Calculate adjustment automatically
1087 |
1088 | if len(slave.currentSongAdjustments) < 1:
1089 | # First adjustment for song
1090 | self.log.debug("First adjustment for song...")
1091 |
1092 | if len(slave.adjustments) > 5:
1093 | # More than 5 total adjustments made to this
1094 | # slave. Adjust by average adjustment, slightly
1095 | # reduced to avoid swinging back and forth
1096 | adjustBy = slave.adjustments.average * 0.75
1097 |
1098 | self.log.debug("Adjusting %s by average slave adjustment: %s", slave.host, adjustBy)
1099 | else:
1100 | # 5 or fewer total adjustments made to this slave.
1101 | # Adjust by average ping
1102 | adjustBy = slave.pings.average
1103 |
1104 | self.log.debug("Adjusting %s by average ping: %s", slave.host, adjustBy)
1105 | else:
1106 | # Not the first adjustment for song
1107 |
1108 | if len(slave.currentSongAdjustments) > MAX_ADJUSTMENTS:
1109 | # Too many adjustments; alternate between ping and average difference
1110 | self.log.debug("Too many adjustments (%s > %s)", len(slave.currentSongAdjustments), MAX_ADJUSTMENTS)
1111 |
1112 | if not even(len(slave.currentSongAdjustments)):
1113 | # Adjust by ping
1114 | self.log.debug("Adjusting by ping...")
1115 |
1116 | adjustBy = slave.pings.average
1117 | else:
1118 | # Try adjusting by difference again
1119 | self.log.debug("Trying to adjust by difference...")
1120 |
1121 | adjustBy = slave.currentSongDifferences.average
1122 |
1123 | else:
1124 | # Adjust by average difference
1125 | adjustBy = slave.currentSongDifferences.average
1126 |
1127 | self.log.debug("Adjusting %s by average difference: %s",
1128 | slave.host, adjustBy)
1129 |
1130 | # TODO: If the difference is too great, it seems that the
1131 | # slave MPD has hit a bug where it thinks that song
1132 | # duration is shorter than it is and won't seek past that
1133 | # point. Stopping the slave playback and re-playing the
1134 | # track seems to fix it.
1135 |
1136 | absAdjustBy = abs(adjustBy)
1137 | if absAdjustBy > MAX_ADJUSTMENT:
1138 | # Adjustment too large; use ping
1139 | self.log.debug("Adjustment too large (%s > %s); adjusting by ping", absAdjustBy, MAX_ADJUSTMENT)
1140 |
1141 | adjustBy = slave.pings.average
1142 |
1143 | if adjustBy == slave.pings.average:
1144 | # Adjusting by ping, clear differences
1145 | self.log.debug("Clearing differences")
1146 |
1147 | slave.currentSongDifferences.clear()
1148 | else:
1149 | # Invert final difference-based adjustment
1150 | adjustBy = adjustBy * -1
1151 |
1152 | return adjustBy
1153 |
1154 | def _reseek_necessary(self, slave):
1155 | "Return True if reseek is necessary."
1156 |
1157 | # Update master info
1158 | self.status()
1159 |
1160 | # Reconnect if connection dropped
1161 | slave.checkConnection()
1162 |
1163 | if not slave.currentSongShouldSeek:
1164 | self.log.debug('Not seeking this song anymore')
1165 |
1166 | return False
1167 |
1168 | average_difference = self._average_difference(slave) # Absolute value
1169 | max_difference = self._max_difference(slave)
1170 |
1171 | if len(slave.currentSongDifferences) < 3:
1172 | self.log.debug("Less than 3 measurements; not seeking")
1173 |
1174 | return False
1175 |
1176 | # Commenting out for now. Not sure if it's really necessary now that we have backing-off.
1177 | # if (len(slave.currentSongDifferences) >= 5 and average_difference < MIN_DIFFERENCE):
1178 | # self.log.debug("Average difference %s < %s; not seeking this song anymore", average_difference, MIN_DIFFERENCE)
1179 |
1180 | # slave.currentSongShouldSeek = False
1181 |
1182 | # return False
1183 |
1184 | if (average_difference > max_difference
1185 | and abs(slave.currentSongDifferences[0]) > max_difference):
1186 | # Average and current difference too large; reseek
1187 | self.log.debug("Average difference (%s) > max difference (%s); reseeking..." % (average_difference, max_difference))
1188 |
1189 | return True
1190 | else:
1191 | self.log.debug("Average difference within acceptable range; not reseeking")
1192 |
1193 | return False
1194 |
1195 | def _max_difference(self, slave):
1196 | "Return max difference between slave and master."
1197 |
1198 | if len(slave.currentSongDifferences) >= 5:
1199 | # At least 5 measurements for current song
1200 |
1201 | if len(slave.currentSongDifferences) >= 10:
1202 | # 10 or more measurements; use 1/4 of the range
1203 | maxDifference = slave.currentSongDifferences.range / 4
1204 |
1205 | # Add half the average to prevent it from being too
1206 | # small and causing excessive reseeks. For some songs
1207 | # the range can be very small, like 38ms, but for
1208 | # others it can be consistently 100-200 ms.
1209 | maxDifference += (abs(slave.currentSongDifferences.average) / 2)
1210 | else:
1211 | # 5-9 measurements; use 1/2 of the range
1212 | maxDifference = slave.currentSongDifferences.range / 2
1213 |
1214 | # Use at least half of the biggest difference to prevent
1215 | # the occasional small range from causing unnecessary
1216 | # syncs. This may not be necessary with adding half the
1217 | # average a few lines up, but it may be a good extra
1218 | # precaution.
1219 |
1220 | # Use the max and min of the last 10 measurements, but not less than 30ms
1221 | minimumMaxDifference = max(0.030, (0.5 * max(abs(max(slave.currentSongDifferences[:10])),
1222 | abs(min(slave.currentSongDifferences[:10])))))
1223 |
1224 | if maxDifference < minimumMaxDifference:
1225 | self.log.debug('maxDifference too small (%s); setting maxDifference to half of the biggest difference', maxDifference)
1226 |
1227 | maxDifference = minimumMaxDifference
1228 |
1229 | elif slave.pings.average:
1230 | # Use average ping
1231 |
1232 | # Use the larger of master or slave ping so the script can
1233 | # run on either one, multiplied by 30 (e.g. a 2 ms LAN
1234 | # ping becomes 60 ms max difference), but not less than 30ms
1235 | maxDifference = max(0.030, (30 * max([slave.pings.average, self.pings.average])))
1236 |
1237 | # But don't go over 200 ms; if it's that high, better to
1238 | # just resync again. But this does not work well for
1239 | # remote files. The difference sometimes never gets lower
1240 | # than the maxDifference, so it resyncs forever, and
1241 | # always by the average ping or average slave adjustment,
1242 | # which basically loops doing the same syncs forever.
1243 | # Sigh.
1244 | maxDifference = min(0.200, maxDifference)
1245 |
1246 | else:
1247 | # This shouldn't happen, but if it does, use 200ms until we
1248 | # have something better. 200ms seems like a lot, and for
1249 | # local files it is, but remote files don't seek as
1250 | # quickly or consistently, so 100ms can cause excessive
1251 | # reseeking in a short period of time
1252 | maxDifference = 0.200
1253 |
1254 | if len(slave.currentSongAdjustments) > 3:
1255 | # Many adjustments means trouble seeking this song. Begin
1256 | # increasing the acceptable range by 25ms per adjustment over 3.
1257 | increase_by = 0.025 * (len(slave.currentSongAdjustments) - 3)
1258 |
1259 | maxDifference += increase_by
1260 |
1261 | self.log.debug("More than 3 adjustments; increasing max difference by %s", increase_by)
1262 |
1263 | maxDifference = round(maxDifference, 3)
1264 |
1265 | self.log.debug("maxDifference for slave %s: %s", slave.host, maxDifference)
1266 |
1267 | return maxDifference
1268 |
1269 | # ** Functions
1270 |
1271 | def even(num):
1272 | return (num % 2) == 0
1273 |
1274 | def timeFunction(f):
1275 | t1 = time.time()
1276 | f()
1277 | t2 = time.time()
1278 | return t2 - t1
1279 |
1280 | def main():
1281 |
1282 | # Parse args
1283 | parser = argparse.ArgumentParser(
1284 | description='Syncs multiple mpd servers.')
1285 | parser.add_argument('-m', '--master',
1286 | dest='master',
1287 | help='Name or address of master server, optionally with port in HOST:PORT format')
1288 | parser.add_argument('-s', '--slaves',
1289 | dest="slaves", nargs='*',
1290 | help='Name or address of slave servers, optionally with port in HOST:PORT/LATENCY format')
1291 | parser.add_argument('-p', '--password', default=None,
1292 | dest="password",
1293 | help='Password to connect to servers with')
1294 | parser.add_argument('-l', '--latency-adjust',
1295 | dest="adjustLatency", action="store_true",
1296 | help="Monitor latency between master and slaves and try to keep slaves' "
1297 | "playing position in sync with the master's")
1298 | parser.add_argument("-v", "--verbose", action="count", default=0, dest="verbose", help="Be verbose, up to -vvv")
1299 | args = parser.parse_args()
1300 |
1301 | # Setup logging
1302 | log = logging.getLogger('mpdsync')
1303 | if args.verbose >= 3:
1304 | # Debug everything, including MPD module. This sets the root
1305 | # logger, which python-mpd2 uses. Too bad it doesn't use a
1306 | # logging.NullHandler to make this cleaner. See
1307 | # https://docs.python.org/2/howto/logging.html#library-config
1308 | LOG_LEVEL = logging.DEBUG
1309 | logging.basicConfig(level=LOG_LEVEL, format="%(levelname)s: %(name)s: %(message)s")
1310 |
1311 | else:
1312 | # Don't debug MPD. Don't set the root logger. Do manually
1313 | # what basicConfig() does, because basicConfig() sets the root
1314 | # logger. This seems more confusing than it should be. I
1315 | # think the key is that logging.logger.getChild() is not in
1316 | # the logging howto tutorials. When I found getChild() (which
1317 | # is in the API docs, which are also not obviously linked in
1318 | # the howto), it started falling into place. But without
1319 | # getchild(), it was a confusing mess.
1320 | if args.verbose == 1:
1321 | LOG_LEVEL = logging.INFO
1322 | elif args.verbose == 2:
1323 | LOG_LEVEL = logging.DEBUG
1324 | else:
1325 | LOG_LEVEL = logging.WARNING
1326 |
1327 | handler = logging.StreamHandler()
1328 | handler.setFormatter(logging.Formatter("%(levelname)s: %(name)s: %(message)s"))
1329 | log.addHandler(handler)
1330 | log.setLevel(LOG_LEVEL)
1331 |
1332 | log.debug('Using python-mpd version: %s', str(mpd.VERSION))
1333 | log.debug("Args: %s", args)
1334 |
1335 | # Check args
1336 | if not args.master:
1337 | log.error("Please provide a master server with -m.")
1338 | return False
1339 |
1340 | if not args.slaves:
1341 | log.error("Please provide at least one slave server with -c.")
1342 | return False
1343 |
1344 | # Connect to the master server
1345 | master = Master(host=args.master, password=args.password,
1346 | adjustLatency=args.adjustLatency, logger=log)
1347 |
1348 | try:
1349 | master.connect()
1350 | except Exception as e:
1351 | log.exception('Unable to connect to master server: %s', e)
1352 | return False
1353 | else:
1354 | log.debug('Connected to master server.')
1355 |
1356 | # Connect to slaves
1357 | for slave in args.slaves:
1358 | master.addSlave(slave, password=args.password)
1359 |
1360 | # Make sure there is at least one slave connected
1361 | if not master.slaves:
1362 | log.error("Couldn't connect to any slaves.")
1363 | return False
1364 |
1365 | # Sync master and slaves
1366 | master.syncAll()
1367 |
1368 | # try/except to catch Ctrl+C and print debug info
1369 | try:
1370 | # Enter idle loop
1371 | while True:
1372 | # Wait for something to happen
1373 | subsystems = master.idle()
1374 |
1375 | # Sync stuff
1376 | for subsystem in subsystems:
1377 | if subsystem == 'playlist':
1378 | log.debug("Subsystem update: playlist")
1379 | master.syncPlaylists()
1380 | elif subsystem == 'player':
1381 | log.debug("Subsystem update: player")
1382 | master.syncPlayers()
1383 | elif subsystem == 'options':
1384 | log.debug("Subsystem update: options")
1385 | master.syncOptions()
1386 |
1387 | except KeyboardInterrupt:
1388 | log.debug("Interrupted. Filetype adjustments for slave 0: %s",
1389 | [{a: master.slaves[0].fileTypeAdjustments[a]}
1390 | for a in master.slaves[0].fileTypeAdjustments])
1391 | log.debug("Song adjustments for slave 0: %s",
1392 | "\n" + "\n".join([str(a)
1393 | for a in sorted(master.slaves[0].song_adjustments,
1394 | key=lambda i: len(i['adjustments']))]))
1395 | log.debug("Song differences for slave 0: %s",
1396 | "\n" + "\n".join([str(a)
1397 | for a in sorted(master.slaves[0].song_differences,
1398 | key=lambda i: i['differences'].overall_average)]))
1399 |
1400 | if __name__ == '__main__':
1401 | sys.exit(main())
1402 |
--------------------------------------------------------------------------------