[youtube] Skip unsupported adaptive stream type (#18804)
[youtube-dl] / youtube_dl / extractor / bbc.py
1 # coding: utf-8
2 from __future__ import unicode_literals
3
4 import re
5 import itertools
6
7 from .common import InfoExtractor
8 from ..utils import (
9     clean_html,
10     dict_get,
11     ExtractorError,
12     float_or_none,
13     get_element_by_class,
14     int_or_none,
15     js_to_json,
16     parse_duration,
17     parse_iso8601,
18     try_get,
19     unescapeHTML,
20     urlencode_postdata,
21     urljoin,
22 )
23 from ..compat import (
24     compat_HTTPError,
25     compat_urlparse,
26 )
27
28
29 class BBCCoUkIE(InfoExtractor):
30     IE_NAME = 'bbc.co.uk'
31     IE_DESC = 'BBC iPlayer'
32     _ID_REGEX = r'(?:[pbm][\da-z]{7}|w[\da-z]{7,14})'
33     _VALID_URL = r'''(?x)
34                     https?://
35                         (?:www\.)?bbc\.co\.uk/
36                         (?:
37                             programmes/(?!articles/)|
38                             iplayer(?:/[^/]+)?/(?:episode/|playlist/)|
39                             music/(?:clips|audiovideo/popular)[/#]|
40                             radio/player/|
41                             events/[^/]+/play/[^/]+/
42                         )
43                         (?P<id>%s)(?!/(?:episodes|broadcasts|clips))
44                     ''' % _ID_REGEX
45
46     _LOGIN_URL = 'https://account.bbc.com/signin'
47     _NETRC_MACHINE = 'bbc'
48
49     _MEDIASELECTOR_URLS = [
50         # Provides HQ HLS streams with even better quality that pc mediaset but fails
51         # with geolocation in some cases when it's even not geo restricted at all (e.g.
52         # http://www.bbc.co.uk/programmes/b06bp7lf). Also may fail with selectionunavailable.
53         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
54         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/pc/vpid/%s',
55     ]
56
57     _MEDIASELECTION_NS = 'http://bbc.co.uk/2008/mp/mediaselection'
58     _EMP_PLAYLIST_NS = 'http://bbc.co.uk/2008/emp/playlist'
59
60     _NAMESPACES = (
61         _MEDIASELECTION_NS,
62         _EMP_PLAYLIST_NS,
63     )
64
65     _TESTS = [
66         {
67             'url': 'http://www.bbc.co.uk/programmes/b039g8p7',
68             'info_dict': {
69                 'id': 'b039d07m',
70                 'ext': 'flv',
71                 'title': 'Leonard Cohen, Kaleidoscope - BBC Radio 4',
72                 'description': 'The Canadian poet and songwriter reflects on his musical career.',
73             },
74             'params': {
75                 # rtmp download
76                 'skip_download': True,
77             }
78         },
79         {
80             'url': 'http://www.bbc.co.uk/iplayer/episode/b00yng5w/The_Man_in_Black_Series_3_The_Printed_Name/',
81             'info_dict': {
82                 'id': 'b00yng1d',
83                 'ext': 'flv',
84                 'title': 'The Man in Black: Series 3: The Printed Name',
85                 'description': "Mark Gatiss introduces Nicholas Pierpan's chilling tale of a writer's devilish pact with a mysterious man. Stars Ewan Bailey.",
86                 'duration': 1800,
87             },
88             'params': {
89                 # rtmp download
90                 'skip_download': True,
91             },
92             'skip': 'Episode is no longer available on BBC iPlayer Radio',
93         },
94         {
95             'url': 'http://www.bbc.co.uk/iplayer/episode/b03vhd1f/The_Voice_UK_Series_3_Blind_Auditions_5/',
96             'info_dict': {
97                 'id': 'b00yng1d',
98                 'ext': 'flv',
99                 'title': 'The Voice UK: Series 3: Blind Auditions 5',
100                 'description': 'Emma Willis and Marvin Humes present the fifth set of blind auditions in the singing competition, as the coaches continue to build their teams based on voice alone.',
101                 'duration': 5100,
102             },
103             'params': {
104                 # rtmp download
105                 'skip_download': True,
106             },
107             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
108         },
109         {
110             'url': 'http://www.bbc.co.uk/iplayer/episode/p026c7jt/tomorrows-worlds-the-unearthly-history-of-science-fiction-2-invasion',
111             'info_dict': {
112                 'id': 'b03k3pb7',
113                 'ext': 'flv',
114                 'title': "Tomorrow's Worlds: The Unearthly History of Science Fiction",
115                 'description': '2. Invasion',
116                 'duration': 3600,
117             },
118             'params': {
119                 # rtmp download
120                 'skip_download': True,
121             },
122             'skip': 'Currently BBC iPlayer TV programmes are available to play in the UK only',
123         }, {
124             'url': 'http://www.bbc.co.uk/programmes/b04v20dw',
125             'info_dict': {
126                 'id': 'b04v209v',
127                 'ext': 'flv',
128                 'title': 'Pete Tong, The Essential New Tune Special',
129                 'description': "Pete has a very special mix - all of 2014's Essential New Tunes!",
130                 'duration': 10800,
131             },
132             'params': {
133                 # rtmp download
134                 'skip_download': True,
135             },
136             'skip': 'Episode is no longer available on BBC iPlayer Radio',
137         }, {
138             'url': 'http://www.bbc.co.uk/music/clips/p022h44b',
139             'note': 'Audio',
140             'info_dict': {
141                 'id': 'p022h44j',
142                 'ext': 'flv',
143                 'title': 'BBC Proms Music Guides, Rachmaninov: Symphonic Dances',
144                 'description': "In this Proms Music Guide, Andrew McGregor looks at Rachmaninov's Symphonic Dances.",
145                 'duration': 227,
146             },
147             'params': {
148                 # rtmp download
149                 'skip_download': True,
150             }
151         }, {
152             'url': 'http://www.bbc.co.uk/music/clips/p025c0zz',
153             'note': 'Video',
154             'info_dict': {
155                 'id': 'p025c103',
156                 'ext': 'flv',
157                 'title': 'Reading and Leeds Festival, 2014, Rae Morris - Closer (Live on BBC Three)',
158                 'description': 'Rae Morris performs Closer for BBC Three at Reading 2014',
159                 'duration': 226,
160             },
161             'params': {
162                 # rtmp download
163                 'skip_download': True,
164             }
165         }, {
166             'url': 'http://www.bbc.co.uk/iplayer/episode/b054fn09/ad/natural-world-20152016-2-super-powered-owls',
167             'info_dict': {
168                 'id': 'p02n76xf',
169                 'ext': 'flv',
170                 'title': 'Natural World, 2015-2016: 2. Super Powered Owls',
171                 'description': 'md5:e4db5c937d0e95a7c6b5e654d429183d',
172                 'duration': 3540,
173             },
174             'params': {
175                 # rtmp download
176                 'skip_download': True,
177             },
178             'skip': 'geolocation',
179         }, {
180             'url': 'http://www.bbc.co.uk/iplayer/episode/b05zmgwn/royal-academy-summer-exhibition',
181             'info_dict': {
182                 'id': 'b05zmgw1',
183                 'ext': 'flv',
184                 'description': 'Kirsty Wark and Morgan Quaintance visit the Royal Academy as it prepares for its annual artistic extravaganza, meeting people who have come together to make the show unique.',
185                 'title': 'Royal Academy Summer Exhibition',
186                 'duration': 3540,
187             },
188             'params': {
189                 # rtmp download
190                 'skip_download': True,
191             },
192             'skip': 'geolocation',
193         }, {
194             # iptv-all mediaset fails with geolocation however there is no geo restriction
195             # for this programme at all
196             'url': 'http://www.bbc.co.uk/programmes/b06rkn85',
197             'info_dict': {
198                 'id': 'b06rkms3',
199                 'ext': 'flv',
200                 'title': "Best of the Mini-Mixes 2015: Part 3, Annie Mac's Friday Night - BBC Radio 1",
201                 'description': "Annie has part three in the Best of the Mini-Mixes 2015, plus the year's Most Played!",
202             },
203             'params': {
204                 # rtmp download
205                 'skip_download': True,
206             },
207             'skip': 'Now it\'s really geo-restricted',
208         }, {
209             # compact player (https://github.com/rg3/youtube-dl/issues/8147)
210             'url': 'http://www.bbc.co.uk/programmes/p028bfkf/player',
211             'info_dict': {
212                 'id': 'p028bfkj',
213                 'ext': 'flv',
214                 'title': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
215                 'description': 'Extract from BBC documentary Look Stranger - Giant Leeks and Magic Brews',
216             },
217             'params': {
218                 # rtmp download
219                 'skip_download': True,
220             },
221         }, {
222             'url': 'http://www.bbc.co.uk/iplayer/playlist/p01dvks4',
223             'only_matching': True,
224         }, {
225             'url': 'http://www.bbc.co.uk/music/clips#p02frcc3',
226             'only_matching': True,
227         }, {
228             'url': 'http://www.bbc.co.uk/iplayer/cbeebies/episode/b0480276/bing-14-atchoo',
229             'only_matching': True,
230         }, {
231             'url': 'http://www.bbc.co.uk/radio/player/p03cchwf',
232             'only_matching': True,
233         }, {
234             'url': 'https://www.bbc.co.uk/music/audiovideo/popular#p055bc55',
235             'only_matching': True,
236         }, {
237             'url': 'http://www.bbc.co.uk/programmes/w3csv1y9',
238             'only_matching': True,
239         }, {
240             'url': 'https://www.bbc.co.uk/programmes/m00005xn',
241             'only_matching': True,
242         }, {
243             'url': 'https://www.bbc.co.uk/programmes/w172w4dww1jqt5s',
244             'only_matching': True,
245         }]
246
247     _USP_RE = r'/([^/]+?)\.ism(?:\.hlsv2\.ism)?/[^/]+\.m3u8'
248
249     def _login(self):
250         username, password = self._get_login_info()
251         if username is None:
252             return
253
254         login_page = self._download_webpage(
255             self._LOGIN_URL, None, 'Downloading signin page')
256
257         login_form = self._hidden_inputs(login_page)
258
259         login_form.update({
260             'username': username,
261             'password': password,
262         })
263
264         post_url = urljoin(self._LOGIN_URL, self._search_regex(
265             r'<form[^>]+action=(["\'])(?P<url>.+?)\1', login_page,
266             'post url', default=self._LOGIN_URL, group='url'))
267
268         response, urlh = self._download_webpage_handle(
269             post_url, None, 'Logging in', data=urlencode_postdata(login_form),
270             headers={'Referer': self._LOGIN_URL})
271
272         if self._LOGIN_URL in urlh.geturl():
273             error = clean_html(get_element_by_class('form-message', response))
274             if error:
275                 raise ExtractorError(
276                     'Unable to login: %s' % error, expected=True)
277             raise ExtractorError('Unable to log in')
278
279     def _real_initialize(self):
280         self._login()
281
282     class MediaSelectionError(Exception):
283         def __init__(self, id):
284             self.id = id
285
286     def _extract_asx_playlist(self, connection, programme_id):
287         asx = self._download_xml(connection.get('href'), programme_id, 'Downloading ASX playlist')
288         return [ref.get('href') for ref in asx.findall('./Entry/ref')]
289
290     def _extract_items(self, playlist):
291         return playlist.findall('./{%s}item' % self._EMP_PLAYLIST_NS)
292
293     def _findall_ns(self, element, xpath):
294         elements = []
295         for ns in self._NAMESPACES:
296             elements.extend(element.findall(xpath % ns))
297         return elements
298
299     def _extract_medias(self, media_selection):
300         error = media_selection.find('./{%s}error' % self._MEDIASELECTION_NS)
301         if error is None:
302             media_selection.find('./{%s}error' % self._EMP_PLAYLIST_NS)
303         if error is not None:
304             raise BBCCoUkIE.MediaSelectionError(error.get('id'))
305         return self._findall_ns(media_selection, './{%s}media')
306
307     def _extract_connections(self, media):
308         return self._findall_ns(media, './{%s}connection')
309
310     def _get_subtitles(self, media, programme_id):
311         subtitles = {}
312         for connection in self._extract_connections(media):
313             captions = self._download_xml(connection.get('href'), programme_id, 'Downloading captions')
314             lang = captions.get('{http://www.w3.org/XML/1998/namespace}lang', 'en')
315             subtitles[lang] = [
316                 {
317                     'url': connection.get('href'),
318                     'ext': 'ttml',
319                 },
320             ]
321         return subtitles
322
323     def _raise_extractor_error(self, media_selection_error):
324         raise ExtractorError(
325             '%s returned error: %s' % (self.IE_NAME, media_selection_error.id),
326             expected=True)
327
328     def _download_media_selector(self, programme_id):
329         last_exception = None
330         for mediaselector_url in self._MEDIASELECTOR_URLS:
331             try:
332                 return self._download_media_selector_url(
333                     mediaselector_url % programme_id, programme_id)
334             except BBCCoUkIE.MediaSelectionError as e:
335                 if e.id in ('notukerror', 'geolocation', 'selectionunavailable'):
336                     last_exception = e
337                     continue
338                 self._raise_extractor_error(e)
339         self._raise_extractor_error(last_exception)
340
341     def _download_media_selector_url(self, url, programme_id=None):
342         media_selection = self._download_xml(
343             url, programme_id, 'Downloading media selection XML',
344             expected_status=(403, 404))
345         return self._process_media_selector(media_selection, programme_id)
346
347     def _process_media_selector(self, media_selection, programme_id):
348         formats = []
349         subtitles = None
350         urls = []
351
352         for media in self._extract_medias(media_selection):
353             kind = media.get('kind')
354             if kind in ('video', 'audio'):
355                 bitrate = int_or_none(media.get('bitrate'))
356                 encoding = media.get('encoding')
357                 service = media.get('service')
358                 width = int_or_none(media.get('width'))
359                 height = int_or_none(media.get('height'))
360                 file_size = int_or_none(media.get('media_file_size'))
361                 for connection in self._extract_connections(media):
362                     href = connection.get('href')
363                     if href in urls:
364                         continue
365                     if href:
366                         urls.append(href)
367                     conn_kind = connection.get('kind')
368                     protocol = connection.get('protocol')
369                     supplier = connection.get('supplier')
370                     transfer_format = connection.get('transferFormat')
371                     format_id = supplier or conn_kind or protocol
372                     if service:
373                         format_id = '%s_%s' % (service, format_id)
374                     # ASX playlist
375                     if supplier == 'asx':
376                         for i, ref in enumerate(self._extract_asx_playlist(connection, programme_id)):
377                             formats.append({
378                                 'url': ref,
379                                 'format_id': 'ref%s_%s' % (i, format_id),
380                             })
381                     elif transfer_format == 'dash':
382                         formats.extend(self._extract_mpd_formats(
383                             href, programme_id, mpd_id=format_id, fatal=False))
384                     elif transfer_format == 'hls':
385                         formats.extend(self._extract_m3u8_formats(
386                             href, programme_id, ext='mp4', entry_protocol='m3u8_native',
387                             m3u8_id=format_id, fatal=False))
388                         if re.search(self._USP_RE, href):
389                             usp_formats = self._extract_m3u8_formats(
390                                 re.sub(self._USP_RE, r'/\1.ism/\1.m3u8', href),
391                                 programme_id, ext='mp4', entry_protocol='m3u8_native',
392                                 m3u8_id=format_id, fatal=False)
393                             for f in usp_formats:
394                                 if f.get('height') and f['height'] > 720:
395                                     continue
396                                 formats.append(f)
397                     elif transfer_format == 'hds':
398                         formats.extend(self._extract_f4m_formats(
399                             href, programme_id, f4m_id=format_id, fatal=False))
400                     else:
401                         if not service and not supplier and bitrate:
402                             format_id += '-%d' % bitrate
403                         fmt = {
404                             'format_id': format_id,
405                             'filesize': file_size,
406                         }
407                         if kind == 'video':
408                             fmt.update({
409                                 'width': width,
410                                 'height': height,
411                                 'tbr': bitrate,
412                                 'vcodec': encoding,
413                             })
414                         else:
415                             fmt.update({
416                                 'abr': bitrate,
417                                 'acodec': encoding,
418                                 'vcodec': 'none',
419                             })
420                         if protocol in ('http', 'https'):
421                             # Direct link
422                             fmt.update({
423                                 'url': href,
424                             })
425                         elif protocol == 'rtmp':
426                             application = connection.get('application', 'ondemand')
427                             auth_string = connection.get('authString')
428                             identifier = connection.get('identifier')
429                             server = connection.get('server')
430                             fmt.update({
431                                 'url': '%s://%s/%s?%s' % (protocol, server, application, auth_string),
432                                 'play_path': identifier,
433                                 'app': '%s?%s' % (application, auth_string),
434                                 'page_url': 'http://www.bbc.co.uk',
435                                 'player_url': 'http://www.bbc.co.uk/emp/releases/iplayer/revisions/617463_618125_4/617463_618125_4_emp.swf',
436                                 'rtmp_live': False,
437                                 'ext': 'flv',
438                             })
439                         else:
440                             continue
441                         formats.append(fmt)
442             elif kind == 'captions':
443                 subtitles = self.extract_subtitles(media, programme_id)
444         return formats, subtitles
445
446     def _download_playlist(self, playlist_id):
447         try:
448             playlist = self._download_json(
449                 'http://www.bbc.co.uk/programmes/%s/playlist.json' % playlist_id,
450                 playlist_id, 'Downloading playlist JSON')
451
452             version = playlist.get('defaultAvailableVersion')
453             if version:
454                 smp_config = version['smpConfig']
455                 title = smp_config['title']
456                 description = smp_config['summary']
457                 for item in smp_config['items']:
458                     kind = item['kind']
459                     if kind not in ('programme', 'radioProgramme'):
460                         continue
461                     programme_id = item.get('vpid')
462                     duration = int_or_none(item.get('duration'))
463                     formats, subtitles = self._download_media_selector(programme_id)
464                 return programme_id, title, description, duration, formats, subtitles
465         except ExtractorError as ee:
466             if not (isinstance(ee.cause, compat_HTTPError) and ee.cause.code == 404):
467                 raise
468
469         # fallback to legacy playlist
470         return self._process_legacy_playlist(playlist_id)
471
472     def _process_legacy_playlist_url(self, url, display_id):
473         playlist = self._download_legacy_playlist_url(url, display_id)
474         return self._extract_from_legacy_playlist(playlist, display_id)
475
476     def _process_legacy_playlist(self, playlist_id):
477         return self._process_legacy_playlist_url(
478             'http://www.bbc.co.uk/iplayer/playlist/%s' % playlist_id, playlist_id)
479
480     def _download_legacy_playlist_url(self, url, playlist_id=None):
481         return self._download_xml(
482             url, playlist_id, 'Downloading legacy playlist XML')
483
484     def _extract_from_legacy_playlist(self, playlist, playlist_id):
485         no_items = playlist.find('./{%s}noItems' % self._EMP_PLAYLIST_NS)
486         if no_items is not None:
487             reason = no_items.get('reason')
488             if reason == 'preAvailability':
489                 msg = 'Episode %s is not yet available' % playlist_id
490             elif reason == 'postAvailability':
491                 msg = 'Episode %s is no longer available' % playlist_id
492             elif reason == 'noMedia':
493                 msg = 'Episode %s is not currently available' % playlist_id
494             else:
495                 msg = 'Episode %s is not available: %s' % (playlist_id, reason)
496             raise ExtractorError(msg, expected=True)
497
498         for item in self._extract_items(playlist):
499             kind = item.get('kind')
500             if kind not in ('programme', 'radioProgramme'):
501                 continue
502             title = playlist.find('./{%s}title' % self._EMP_PLAYLIST_NS).text
503             description_el = playlist.find('./{%s}summary' % self._EMP_PLAYLIST_NS)
504             description = description_el.text if description_el is not None else None
505
506             def get_programme_id(item):
507                 def get_from_attributes(item):
508                     for p in('identifier', 'group'):
509                         value = item.get(p)
510                         if value and re.match(r'^[pb][\da-z]{7}$', value):
511                             return value
512                 get_from_attributes(item)
513                 mediator = item.find('./{%s}mediator' % self._EMP_PLAYLIST_NS)
514                 if mediator is not None:
515                     return get_from_attributes(mediator)
516
517             programme_id = get_programme_id(item)
518             duration = int_or_none(item.get('duration'))
519
520             if programme_id:
521                 formats, subtitles = self._download_media_selector(programme_id)
522             else:
523                 formats, subtitles = self._process_media_selector(item, playlist_id)
524                 programme_id = playlist_id
525
526         return programme_id, title, description, duration, formats, subtitles
527
528     def _real_extract(self, url):
529         group_id = self._match_id(url)
530
531         webpage = self._download_webpage(url, group_id, 'Downloading video page')
532
533         error = self._search_regex(
534             r'<div\b[^>]+\bclass=["\']smp__message delta["\'][^>]*>([^<]+)<',
535             webpage, 'error', default=None)
536         if error:
537             raise ExtractorError(error, expected=True)
538
539         programme_id = None
540         duration = None
541
542         tviplayer = self._search_regex(
543             r'mediator\.bind\(({.+?})\s*,\s*document\.getElementById',
544             webpage, 'player', default=None)
545
546         if tviplayer:
547             player = self._parse_json(tviplayer, group_id).get('player', {})
548             duration = int_or_none(player.get('duration'))
549             programme_id = player.get('vpid')
550
551         if not programme_id:
552             programme_id = self._search_regex(
553                 r'"vpid"\s*:\s*"(%s)"' % self._ID_REGEX, webpage, 'vpid', fatal=False, default=None)
554
555         if programme_id:
556             formats, subtitles = self._download_media_selector(programme_id)
557             title = self._og_search_title(webpage, default=None) or self._html_search_regex(
558                 (r'<h2[^>]+id="parent-title"[^>]*>(.+?)</h2>',
559                  r'<div[^>]+class="info"[^>]*>\s*<h1>(.+?)</h1>'), webpage, 'title')
560             description = self._search_regex(
561                 (r'<p class="[^"]*medium-description[^"]*">([^<]+)</p>',
562                  r'<div[^>]+class="info_+synopsis"[^>]*>([^<]+)</div>'),
563                 webpage, 'description', default=None)
564             if not description:
565                 description = self._html_search_meta('description', webpage)
566         else:
567             programme_id, title, description, duration, formats, subtitles = self._download_playlist(group_id)
568
569         self._sort_formats(formats)
570
571         return {
572             'id': programme_id,
573             'title': title,
574             'description': description,
575             'thumbnail': self._og_search_thumbnail(webpage, default=None),
576             'duration': duration,
577             'formats': formats,
578             'subtitles': subtitles,
579         }
580
581
582 class BBCIE(BBCCoUkIE):
583     IE_NAME = 'bbc'
584     IE_DESC = 'BBC'
585     _VALID_URL = r'https?://(?:www\.)?bbc\.(?:com|co\.uk)/(?:[^/]+/)+(?P<id>[^/#?]+)'
586
587     _MEDIASELECTOR_URLS = [
588         # Provides HQ HLS streams but fails with geolocation in some cases when it's
589         # even not geo restricted at all
590         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/iptv-all/vpid/%s',
591         # Provides more formats, namely direct mp4 links, but fails on some videos with
592         # notukerror for non UK (?) users (e.g.
593         # http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
594         'http://open.live.bbc.co.uk/mediaselector/4/mtis/stream/%s',
595         # Provides fewer formats, but works everywhere for everybody (hopefully)
596         'http://open.live.bbc.co.uk/mediaselector/5/select/version/2.0/mediaset/journalism-pc/vpid/%s',
597     ]
598
599     _TESTS = [{
600         # article with multiple videos embedded with data-playable containing vpids
601         'url': 'http://www.bbc.com/news/world-europe-32668511',
602         'info_dict': {
603             'id': 'world-europe-32668511',
604             'title': 'Russia stages massive WW2 parade despite Western boycott',
605             'description': 'md5:00ff61976f6081841f759a08bf78cc9c',
606         },
607         'playlist_count': 2,
608     }, {
609         # article with multiple videos embedded with data-playable (more videos)
610         'url': 'http://www.bbc.com/news/business-28299555',
611         'info_dict': {
612             'id': 'business-28299555',
613             'title': 'Farnborough Airshow: Video highlights',
614             'description': 'BBC reports and video highlights at the Farnborough Airshow.',
615         },
616         'playlist_count': 9,
617         'skip': 'Save time',
618     }, {
619         # article with multiple videos embedded with `new SMP()`
620         # broken
621         'url': 'http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460',
622         'info_dict': {
623             'id': '3662a707-0af9-3149-963f-47bea720b460',
624             'title': 'BUGGER',
625         },
626         'playlist_count': 18,
627     }, {
628         # single video embedded with data-playable containing vpid
629         'url': 'http://www.bbc.com/news/world-europe-32041533',
630         'info_dict': {
631             'id': 'p02mprgb',
632             'ext': 'mp4',
633             'title': 'Aerial footage showed the site of the crash in the Alps - courtesy BFM TV',
634             'description': 'md5:2868290467291b37feda7863f7a83f54',
635             'duration': 47,
636             'timestamp': 1427219242,
637             'upload_date': '20150324',
638         },
639         'params': {
640             # rtmp download
641             'skip_download': True,
642         }
643     }, {
644         # article with single video embedded with data-playable containing XML playlist
645         # with direct video links as progressiveDownloadUrl (for now these are extracted)
646         # and playlist with f4m and m3u8 as streamingUrl
647         'url': 'http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu',
648         'info_dict': {
649             'id': '150615_telabyad_kentin_cogu',
650             'ext': 'mp4',
651             'title': "YPG: Tel Abyad'ın tamamı kontrolümüzde",
652             'description': 'md5:33a4805a855c9baf7115fcbde57e7025',
653             'timestamp': 1434397334,
654             'upload_date': '20150615',
655         },
656         'params': {
657             'skip_download': True,
658         }
659     }, {
660         # single video embedded with data-playable containing XML playlists (regional section)
661         'url': 'http://www.bbc.com/mundo/video_fotos/2015/06/150619_video_honduras_militares_hospitales_corrupcion_aw',
662         'info_dict': {
663             'id': '150619_video_honduras_militares_hospitales_corrupcion_aw',
664             'ext': 'mp4',
665             'title': 'Honduras militariza sus hospitales por nuevo escándalo de corrupción',
666             'description': 'md5:1525f17448c4ee262b64b8f0c9ce66c8',
667             'timestamp': 1434713142,
668             'upload_date': '20150619',
669         },
670         'params': {
671             'skip_download': True,
672         }
673     }, {
674         # single video from video playlist embedded with vxp-playlist-data JSON
675         'url': 'http://www.bbc.com/news/video_and_audio/must_see/33376376',
676         'info_dict': {
677             'id': 'p02w6qjc',
678             'ext': 'mp4',
679             'title': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
680             'duration': 56,
681             'description': '''Judge Mindy Glazer: "I'm sorry to see you here... I always wondered what happened to you"''',
682         },
683         'params': {
684             'skip_download': True,
685         }
686     }, {
687         # single video story with digitalData
688         'url': 'http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret',
689         'info_dict': {
690             'id': 'p02q6gc4',
691             'ext': 'flv',
692             'title': 'Sri Lanka’s spicy secret',
693             'description': 'As a new train line to Jaffna opens up the country’s north, travellers can experience a truly distinct slice of Tamil culture.',
694             'timestamp': 1437674293,
695             'upload_date': '20150723',
696         },
697         'params': {
698             # rtmp download
699             'skip_download': True,
700         }
701     }, {
702         # single video story without digitalData
703         'url': 'http://www.bbc.com/autos/story/20130513-hyundais-rock-star',
704         'info_dict': {
705             'id': 'p018zqqg',
706             'ext': 'mp4',
707             'title': 'Hyundai Santa Fe Sport: Rock star',
708             'description': 'md5:b042a26142c4154a6e472933cf20793d',
709             'timestamp': 1415867444,
710             'upload_date': '20141113',
711         },
712         'params': {
713             # rtmp download
714             'skip_download': True,
715         }
716     }, {
717         # single video embedded with Morph
718         'url': 'http://www.bbc.co.uk/sport/live/olympics/36895975',
719         'info_dict': {
720             'id': 'p041vhd0',
721             'ext': 'mp4',
722             'title': "Nigeria v Japan - Men's First Round",
723             'description': 'Live coverage of the first round from Group B at the Amazonia Arena.',
724             'duration': 7980,
725             'uploader': 'BBC Sport',
726             'uploader_id': 'bbc_sport',
727         },
728         'params': {
729             # m3u8 download
730             'skip_download': True,
731         },
732         'skip': 'Georestricted to UK',
733     }, {
734         # single video with playlist.sxml URL in playlist param
735         'url': 'http://www.bbc.com/sport/0/football/33653409',
736         'info_dict': {
737             'id': 'p02xycnp',
738             'ext': 'mp4',
739             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
740             'description': 'BBC Sport\'s David Ornstein has the latest transfer gossip, including rumours of a Manchester United return for Cristiano Ronaldo.',
741             'duration': 140,
742         },
743         'params': {
744             # rtmp download
745             'skip_download': True,
746         }
747     }, {
748         # article with multiple videos embedded with playlist.sxml in playlist param
749         'url': 'http://www.bbc.com/sport/0/football/34475836',
750         'info_dict': {
751             'id': '34475836',
752             'title': 'Jurgen Klopp: Furious football from a witty and winning coach',
753             'description': 'Fast-paced football, wit, wisdom and a ready smile - why Liverpool fans should come to love new boss Jurgen Klopp.',
754         },
755         'playlist_count': 3,
756     }, {
757         # school report article with single video
758         'url': 'http://www.bbc.co.uk/schoolreport/35744779',
759         'info_dict': {
760             'id': '35744779',
761             'title': 'School which breaks down barriers in Jerusalem',
762         },
763         'playlist_count': 1,
764     }, {
765         # single video with playlist URL from weather section
766         'url': 'http://www.bbc.com/weather/features/33601775',
767         'only_matching': True,
768     }, {
769         # custom redirection to www.bbc.com
770         'url': 'http://www.bbc.co.uk/news/science-environment-33661876',
771         'only_matching': True,
772     }, {
773         # single video article embedded with data-media-vpid
774         'url': 'http://www.bbc.co.uk/sport/rowing/35908187',
775         'only_matching': True,
776     }, {
777         'url': 'https://www.bbc.co.uk/bbcthree/clip/73d0bbd0-abc3-4cea-b3c0-cdae21905eb1',
778         'info_dict': {
779             'id': 'p06556y7',
780             'ext': 'mp4',
781             'title': 'Transfers: Cristiano Ronaldo to Man Utd, Arsenal to spend?',
782             'description': 'md5:4b7dfd063d5a789a1512e99662be3ddd',
783         },
784         'params': {
785             'skip_download': True,
786         }
787     }, {
788         # window.__PRELOADED_STATE__
789         'url': 'https://www.bbc.co.uk/radio/play/b0b9z4yl',
790         'info_dict': {
791             'id': 'b0b9z4vz',
792             'ext': 'mp4',
793             'title': 'Prom 6: An American in Paris and Turangalila',
794             'description': 'md5:51cf7d6f5c8553f197e58203bc78dff8',
795             'uploader': 'Radio 3',
796             'uploader_id': 'bbc_radio_three',
797         },
798     }, {
799         'url': 'http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227',
800         'info_dict': {
801             'id': 'p06w9tws',
802             'ext': 'mp4',
803             'title': 'md5:2fabf12a726603193a2879a055f72514',
804             'description': 'Learn English words and phrases from this story',
805         },
806         'add_ie': [BBCCoUkIE.ie_key()],
807     }]
808
809     @classmethod
810     def suitable(cls, url):
811         EXCLUDE_IE = (BBCCoUkIE, BBCCoUkArticleIE, BBCCoUkIPlayerPlaylistIE, BBCCoUkPlaylistIE)
812         return (False if any(ie.suitable(url) for ie in EXCLUDE_IE)
813                 else super(BBCIE, cls).suitable(url))
814
815     def _extract_from_media_meta(self, media_meta, video_id):
816         # Direct links to media in media metadata (e.g.
817         # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
818         # TODO: there are also f4m and m3u8 streams incorporated in playlist.sxml
819         source_files = media_meta.get('sourceFiles')
820         if source_files:
821             return [{
822                 'url': f['url'],
823                 'format_id': format_id,
824                 'ext': f.get('encoding'),
825                 'tbr': float_or_none(f.get('bitrate'), 1000),
826                 'filesize': int_or_none(f.get('filesize')),
827             } for format_id, f in source_files.items() if f.get('url')], []
828
829         programme_id = media_meta.get('externalId')
830         if programme_id:
831             return self._download_media_selector(programme_id)
832
833         # Process playlist.sxml as legacy playlist
834         href = media_meta.get('href')
835         if href:
836             playlist = self._download_legacy_playlist_url(href)
837             _, _, _, _, formats, subtitles = self._extract_from_legacy_playlist(playlist, video_id)
838             return formats, subtitles
839
840         return [], []
841
842     def _extract_from_playlist_sxml(self, url, playlist_id, timestamp):
843         programme_id, title, description, duration, formats, subtitles = \
844             self._process_legacy_playlist_url(url, playlist_id)
845         self._sort_formats(formats)
846         return {
847             'id': programme_id,
848             'title': title,
849             'description': description,
850             'duration': duration,
851             'timestamp': timestamp,
852             'formats': formats,
853             'subtitles': subtitles,
854         }
855
856     def _real_extract(self, url):
857         playlist_id = self._match_id(url)
858
859         webpage = self._download_webpage(url, playlist_id)
860
861         json_ld_info = self._search_json_ld(webpage, playlist_id, default={})
862         timestamp = json_ld_info.get('timestamp')
863
864         playlist_title = json_ld_info.get('title')
865         if not playlist_title:
866             playlist_title = self._og_search_title(
867                 webpage, default=None) or self._html_search_regex(
868                 r'<title>(.+?)</title>', webpage, 'playlist title', default=None)
869             if playlist_title:
870                 playlist_title = re.sub(r'(.+)\s*-\s*BBC.*?$', r'\1', playlist_title).strip()
871
872         playlist_description = json_ld_info.get(
873             'description') or self._og_search_description(webpage, default=None)
874
875         if not timestamp:
876             timestamp = parse_iso8601(self._search_regex(
877                 [r'<meta[^>]+property="article:published_time"[^>]+content="([^"]+)"',
878                  r'itemprop="datePublished"[^>]+datetime="([^"]+)"',
879                  r'"datePublished":\s*"([^"]+)'],
880                 webpage, 'date', default=None))
881
882         entries = []
883
884         # article with multiple videos embedded with playlist.sxml (e.g.
885         # http://www.bbc.com/sport/0/football/34475836)
886         playlists = re.findall(r'<param[^>]+name="playlist"[^>]+value="([^"]+)"', webpage)
887         playlists.extend(re.findall(r'data-media-id="([^"]+/playlist\.sxml)"', webpage))
888         if playlists:
889             entries = [
890                 self._extract_from_playlist_sxml(playlist_url, playlist_id, timestamp)
891                 for playlist_url in playlists]
892
893         # news article with multiple videos embedded with data-playable
894         data_playables = re.findall(r'data-playable=(["\'])({.+?})\1', webpage)
895         if data_playables:
896             for _, data_playable_json in data_playables:
897                 data_playable = self._parse_json(
898                     unescapeHTML(data_playable_json), playlist_id, fatal=False)
899                 if not data_playable:
900                     continue
901                 settings = data_playable.get('settings', {})
902                 if settings:
903                     # data-playable with video vpid in settings.playlistObject.items (e.g.
904                     # http://www.bbc.com/news/world-us-canada-34473351)
905                     playlist_object = settings.get('playlistObject', {})
906                     if playlist_object:
907                         items = playlist_object.get('items')
908                         if items and isinstance(items, list):
909                             title = playlist_object['title']
910                             description = playlist_object.get('summary')
911                             duration = int_or_none(items[0].get('duration'))
912                             programme_id = items[0].get('vpid')
913                             formats, subtitles = self._download_media_selector(programme_id)
914                             self._sort_formats(formats)
915                             entries.append({
916                                 'id': programme_id,
917                                 'title': title,
918                                 'description': description,
919                                 'timestamp': timestamp,
920                                 'duration': duration,
921                                 'formats': formats,
922                                 'subtitles': subtitles,
923                             })
924                     else:
925                         # data-playable without vpid but with a playlist.sxml URLs
926                         # in otherSettings.playlist (e.g.
927                         # http://www.bbc.com/turkce/multimedya/2015/10/151010_vid_ankara_patlama_ani)
928                         playlist = data_playable.get('otherSettings', {}).get('playlist', {})
929                         if playlist:
930                             entry = None
931                             for key in ('streaming', 'progressiveDownload'):
932                                 playlist_url = playlist.get('%sUrl' % key)
933                                 if not playlist_url:
934                                     continue
935                                 try:
936                                     info = self._extract_from_playlist_sxml(
937                                         playlist_url, playlist_id, timestamp)
938                                     if not entry:
939                                         entry = info
940                                     else:
941                                         entry['title'] = info['title']
942                                         entry['formats'].extend(info['formats'])
943                                 except Exception as e:
944                                     # Some playlist URL may fail with 500, at the same time
945                                     # the other one may work fine (e.g.
946                                     # http://www.bbc.com/turkce/haberler/2015/06/150615_telabyad_kentin_cogu)
947                                     if isinstance(e.cause, compat_HTTPError) and e.cause.code == 500:
948                                         continue
949                                     raise
950                             if entry:
951                                 self._sort_formats(entry['formats'])
952                                 entries.append(entry)
953
954         if entries:
955             return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
956
957         # http://www.bbc.co.uk/learningenglish/chinese/features/lingohack/ep-181227
958         group_id = self._search_regex(
959             r'<div[^>]+\bclass=["\']video["\'][^>]+\bdata-pid=["\'](%s)' % self._ID_REGEX,
960             webpage, 'group id', default=None)
961         if playlist_id:
962             return self.url_result(
963                 'https://www.bbc.co.uk/programmes/%s' % group_id,
964                 ie=BBCCoUkIE.ie_key())
965
966         # single video story (e.g. http://www.bbc.com/travel/story/20150625-sri-lankas-spicy-secret)
967         programme_id = self._search_regex(
968             [r'data-(?:video-player|media)-vpid="(%s)"' % self._ID_REGEX,
969              r'<param[^>]+name="externalIdentifier"[^>]+value="(%s)"' % self._ID_REGEX,
970              r'videoId\s*:\s*["\'](%s)["\']' % self._ID_REGEX],
971             webpage, 'vpid', default=None)
972
973         if programme_id:
974             formats, subtitles = self._download_media_selector(programme_id)
975             self._sort_formats(formats)
976             # digitalData may be missing (e.g. http://www.bbc.com/autos/story/20130513-hyundais-rock-star)
977             digital_data = self._parse_json(
978                 self._search_regex(
979                     r'var\s+digitalData\s*=\s*({.+?});?\n', webpage, 'digital data', default='{}'),
980                 programme_id, fatal=False)
981             page_info = digital_data.get('page', {}).get('pageInfo', {})
982             title = page_info.get('pageName') or self._og_search_title(webpage)
983             description = page_info.get('description') or self._og_search_description(webpage)
984             timestamp = parse_iso8601(page_info.get('publicationDate')) or timestamp
985             return {
986                 'id': programme_id,
987                 'title': title,
988                 'description': description,
989                 'timestamp': timestamp,
990                 'formats': formats,
991                 'subtitles': subtitles,
992             }
993
994         # Morph based embed (e.g. http://www.bbc.co.uk/sport/live/olympics/36895975)
995         # There are several setPayload calls may be present but the video
996         # seems to be always related to the first one
997         morph_payload = self._parse_json(
998             self._search_regex(
999                 r'Morph\.setPayload\([^,]+,\s*({.+?})\);',
1000                 webpage, 'morph payload', default='{}'),
1001             playlist_id, fatal=False)
1002         if morph_payload:
1003             components = try_get(morph_payload, lambda x: x['body']['components'], list) or []
1004             for component in components:
1005                 if not isinstance(component, dict):
1006                     continue
1007                 lead_media = try_get(component, lambda x: x['props']['leadMedia'], dict)
1008                 if not lead_media:
1009                     continue
1010                 identifiers = lead_media.get('identifiers')
1011                 if not identifiers or not isinstance(identifiers, dict):
1012                     continue
1013                 programme_id = identifiers.get('vpid') or identifiers.get('playablePid')
1014                 if not programme_id:
1015                     continue
1016                 title = lead_media.get('title') or self._og_search_title(webpage)
1017                 formats, subtitles = self._download_media_selector(programme_id)
1018                 self._sort_formats(formats)
1019                 description = lead_media.get('summary')
1020                 uploader = lead_media.get('masterBrand')
1021                 uploader_id = lead_media.get('mid')
1022                 duration = None
1023                 duration_d = lead_media.get('duration')
1024                 if isinstance(duration_d, dict):
1025                     duration = parse_duration(dict_get(
1026                         duration_d, ('rawDuration', 'formattedDuration', 'spokenDuration')))
1027                 return {
1028                     'id': programme_id,
1029                     'title': title,
1030                     'description': description,
1031                     'duration': duration,
1032                     'uploader': uploader,
1033                     'uploader_id': uploader_id,
1034                     'formats': formats,
1035                     'subtitles': subtitles,
1036                 }
1037
1038         preload_state = self._parse_json(self._search_regex(
1039             r'window\.__PRELOADED_STATE__\s*=\s*({.+?});', webpage,
1040             'preload state', default='{}'), playlist_id, fatal=False)
1041         if preload_state:
1042             current_programme = preload_state.get('programmes', {}).get('current') or {}
1043             programme_id = current_programme.get('id')
1044             if current_programme and programme_id and current_programme.get('type') == 'playable_item':
1045                 title = current_programme.get('titles', {}).get('tertiary') or playlist_title
1046                 formats, subtitles = self._download_media_selector(programme_id)
1047                 self._sort_formats(formats)
1048                 synopses = current_programme.get('synopses') or {}
1049                 network = current_programme.get('network') or {}
1050                 duration = int_or_none(
1051                     current_programme.get('duration', {}).get('value'))
1052                 thumbnail = None
1053                 image_url = current_programme.get('image_url')
1054                 if image_url:
1055                     thumbnail = image_url.replace('{recipe}', '1920x1920')
1056                 return {
1057                     'id': programme_id,
1058                     'title': title,
1059                     'description': dict_get(synopses, ('long', 'medium', 'short')),
1060                     'thumbnail': thumbnail,
1061                     'duration': duration,
1062                     'uploader': network.get('short_title'),
1063                     'uploader_id': network.get('id'),
1064                     'formats': formats,
1065                     'subtitles': subtitles,
1066                 }
1067
1068         bbc3_config = self._parse_json(
1069             self._search_regex(
1070                 r'(?s)bbcthreeConfig\s*=\s*({.+?})\s*;\s*<', webpage,
1071                 'bbcthree config', default='{}'),
1072             playlist_id, transform_source=js_to_json, fatal=False)
1073         if bbc3_config:
1074             bbc3_playlist = try_get(
1075                 bbc3_config, lambda x: x['payload']['content']['bbcMedia']['playlist'],
1076                 dict)
1077             if bbc3_playlist:
1078                 playlist_title = bbc3_playlist.get('title') or playlist_title
1079                 thumbnail = bbc3_playlist.get('holdingImageURL')
1080                 entries = []
1081                 for bbc3_item in bbc3_playlist['items']:
1082                     programme_id = bbc3_item.get('versionID')
1083                     if not programme_id:
1084                         continue
1085                     formats, subtitles = self._download_media_selector(programme_id)
1086                     self._sort_formats(formats)
1087                     entries.append({
1088                         'id': programme_id,
1089                         'title': playlist_title,
1090                         'thumbnail': thumbnail,
1091                         'timestamp': timestamp,
1092                         'formats': formats,
1093                         'subtitles': subtitles,
1094                     })
1095                 return self.playlist_result(
1096                     entries, playlist_id, playlist_title, playlist_description)
1097
1098         def extract_all(pattern):
1099             return list(filter(None, map(
1100                 lambda s: self._parse_json(s, playlist_id, fatal=False),
1101                 re.findall(pattern, webpage))))
1102
1103         # Multiple video article (e.g.
1104         # http://www.bbc.co.uk/blogs/adamcurtis/entries/3662a707-0af9-3149-963f-47bea720b460)
1105         EMBED_URL = r'https?://(?:www\.)?bbc\.co\.uk/(?:[^/]+/)+%s(?:\b[^"]+)?' % self._ID_REGEX
1106         entries = []
1107         for match in extract_all(r'new\s+SMP\(({.+?})\)'):
1108             embed_url = match.get('playerSettings', {}).get('externalEmbedUrl')
1109             if embed_url and re.match(EMBED_URL, embed_url):
1110                 entries.append(embed_url)
1111         entries.extend(re.findall(
1112             r'setPlaylist\("(%s)"\)' % EMBED_URL, webpage))
1113         if entries:
1114             return self.playlist_result(
1115                 [self.url_result(entry_, 'BBCCoUk') for entry_ in entries],
1116                 playlist_id, playlist_title, playlist_description)
1117
1118         # Multiple video article (e.g. http://www.bbc.com/news/world-europe-32668511)
1119         medias = extract_all(r"data-media-meta='({[^']+})'")
1120
1121         if not medias:
1122             # Single video article (e.g. http://www.bbc.com/news/video_and_audio/international)
1123             media_asset = self._search_regex(
1124                 r'mediaAssetPage\.init\(\s*({.+?}), "/',
1125                 webpage, 'media asset', default=None)
1126             if media_asset:
1127                 media_asset_page = self._parse_json(media_asset, playlist_id, fatal=False)
1128                 medias = []
1129                 for video in media_asset_page.get('videos', {}).values():
1130                     medias.extend(video.values())
1131
1132         if not medias:
1133             # Multiple video playlist with single `now playing` entry (e.g.
1134             # http://www.bbc.com/news/video_and_audio/must_see/33767813)
1135             vxp_playlist = self._parse_json(
1136                 self._search_regex(
1137                     r'<script[^>]+class="vxp-playlist-data"[^>]+type="application/json"[^>]*>([^<]+)</script>',
1138                     webpage, 'playlist data'),
1139                 playlist_id)
1140             playlist_medias = []
1141             for item in vxp_playlist:
1142                 media = item.get('media')
1143                 if not media:
1144                     continue
1145                 playlist_medias.append(media)
1146                 # Download single video if found media with asset id matching the video id from URL
1147                 if item.get('advert', {}).get('assetId') == playlist_id:
1148                     medias = [media]
1149                     break
1150             # Fallback to the whole playlist
1151             if not medias:
1152                 medias = playlist_medias
1153
1154         entries = []
1155         for num, media_meta in enumerate(medias, start=1):
1156             formats, subtitles = self._extract_from_media_meta(media_meta, playlist_id)
1157             if not formats:
1158                 continue
1159             self._sort_formats(formats)
1160
1161             video_id = media_meta.get('externalId')
1162             if not video_id:
1163                 video_id = playlist_id if len(medias) == 1 else '%s-%s' % (playlist_id, num)
1164
1165             title = media_meta.get('caption')
1166             if not title:
1167                 title = playlist_title if len(medias) == 1 else '%s - Video %s' % (playlist_title, num)
1168
1169             duration = int_or_none(media_meta.get('durationInSeconds')) or parse_duration(media_meta.get('duration'))
1170
1171             images = []
1172             for image in media_meta.get('images', {}).values():
1173                 images.extend(image.values())
1174             if 'image' in media_meta:
1175                 images.append(media_meta['image'])
1176
1177             thumbnails = [{
1178                 'url': image.get('href'),
1179                 'width': int_or_none(image.get('width')),
1180                 'height': int_or_none(image.get('height')),
1181             } for image in images]
1182
1183             entries.append({
1184                 'id': video_id,
1185                 'title': title,
1186                 'thumbnails': thumbnails,
1187                 'duration': duration,
1188                 'timestamp': timestamp,
1189                 'formats': formats,
1190                 'subtitles': subtitles,
1191             })
1192
1193         return self.playlist_result(entries, playlist_id, playlist_title, playlist_description)
1194
1195
1196 class BBCCoUkArticleIE(InfoExtractor):
1197     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/articles/(?P<id>[a-zA-Z0-9]+)'
1198     IE_NAME = 'bbc.co.uk:article'
1199     IE_DESC = 'BBC articles'
1200
1201     _TEST = {
1202         'url': 'http://www.bbc.co.uk/programmes/articles/3jNQLTMrPlYGTBn0WV6M2MS/not-your-typical-role-model-ada-lovelace-the-19th-century-programmer',
1203         'info_dict': {
1204             'id': '3jNQLTMrPlYGTBn0WV6M2MS',
1205             'title': 'Calculating Ada: The Countess of Computing - Not your typical role model: Ada Lovelace the 19th century programmer - BBC Four',
1206             'description': 'Hannah Fry reveals some of her surprising discoveries about Ada Lovelace during filming.',
1207         },
1208         'playlist_count': 4,
1209         'add_ie': ['BBCCoUk'],
1210     }
1211
1212     def _real_extract(self, url):
1213         playlist_id = self._match_id(url)
1214
1215         webpage = self._download_webpage(url, playlist_id)
1216
1217         title = self._og_search_title(webpage)
1218         description = self._og_search_description(webpage).strip()
1219
1220         entries = [self.url_result(programme_url) for programme_url in re.findall(
1221             r'<div[^>]+typeof="Clip"[^>]+resource="([^"]+)"', webpage)]
1222
1223         return self.playlist_result(entries, playlist_id, title, description)
1224
1225
1226 class BBCCoUkPlaylistBaseIE(InfoExtractor):
1227     def _entries(self, webpage, url, playlist_id):
1228         single_page = 'page' in compat_urlparse.parse_qs(
1229             compat_urlparse.urlparse(url).query)
1230         for page_num in itertools.count(2):
1231             for video_id in re.findall(
1232                     self._VIDEO_ID_TEMPLATE % BBCCoUkIE._ID_REGEX, webpage):
1233                 yield self.url_result(
1234                     self._URL_TEMPLATE % video_id, BBCCoUkIE.ie_key())
1235             if single_page:
1236                 return
1237             next_page = self._search_regex(
1238                 r'<li[^>]+class=(["\'])pagination_+next\1[^>]*><a[^>]+href=(["\'])(?P<url>(?:(?!\2).)+)\2',
1239                 webpage, 'next page url', default=None, group='url')
1240             if not next_page:
1241                 break
1242             webpage = self._download_webpage(
1243                 compat_urlparse.urljoin(url, next_page), playlist_id,
1244                 'Downloading page %d' % page_num, page_num)
1245
1246     def _real_extract(self, url):
1247         playlist_id = self._match_id(url)
1248
1249         webpage = self._download_webpage(url, playlist_id)
1250
1251         title, description = self._extract_title_and_description(webpage)
1252
1253         return self.playlist_result(
1254             self._entries(webpage, url, playlist_id),
1255             playlist_id, title, description)
1256
1257
1258 class BBCCoUkIPlayerPlaylistIE(BBCCoUkPlaylistBaseIE):
1259     IE_NAME = 'bbc.co.uk:iplayer:playlist'
1260     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/iplayer/(?:episodes|group)/(?P<id>%s)' % BBCCoUkIE._ID_REGEX
1261     _URL_TEMPLATE = 'http://www.bbc.co.uk/iplayer/episode/%s'
1262     _VIDEO_ID_TEMPLATE = r'data-ip-id=["\'](%s)'
1263     _TESTS = [{
1264         'url': 'http://www.bbc.co.uk/iplayer/episodes/b05rcz9v',
1265         'info_dict': {
1266             'id': 'b05rcz9v',
1267             'title': 'The Disappearance',
1268             'description': 'French thriller serial about a missing teenager.',
1269         },
1270         'playlist_mincount': 6,
1271         'skip': 'This programme is not currently available on BBC iPlayer',
1272     }, {
1273         # Available for over a year unlike 30 days for most other programmes
1274         'url': 'http://www.bbc.co.uk/iplayer/group/p02tcc32',
1275         'info_dict': {
1276             'id': 'p02tcc32',
1277             'title': 'Bohemian Icons',
1278             'description': 'md5:683e901041b2fe9ba596f2ab04c4dbe7',
1279         },
1280         'playlist_mincount': 10,
1281     }]
1282
1283     def _extract_title_and_description(self, webpage):
1284         title = self._search_regex(r'<h1>([^<]+)</h1>', webpage, 'title', fatal=False)
1285         description = self._search_regex(
1286             r'<p[^>]+class=(["\'])subtitle\1[^>]*>(?P<value>[^<]+)</p>',
1287             webpage, 'description', fatal=False, group='value')
1288         return title, description
1289
1290
1291 class BBCCoUkPlaylistIE(BBCCoUkPlaylistBaseIE):
1292     IE_NAME = 'bbc.co.uk:playlist'
1293     _VALID_URL = r'https?://(?:www\.)?bbc\.co\.uk/programmes/(?P<id>%s)/(?:episodes|broadcasts|clips)' % BBCCoUkIE._ID_REGEX
1294     _URL_TEMPLATE = 'http://www.bbc.co.uk/programmes/%s'
1295     _VIDEO_ID_TEMPLATE = r'data-pid=["\'](%s)'
1296     _TESTS = [{
1297         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1298         'info_dict': {
1299             'id': 'b05rcz9v',
1300             'title': 'The Disappearance - Clips - BBC Four',
1301             'description': 'French thriller serial about a missing teenager.',
1302         },
1303         'playlist_mincount': 7,
1304     }, {
1305         # multipage playlist, explicit page
1306         'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips?page=1',
1307         'info_dict': {
1308             'id': 'b00mfl7n',
1309             'title': 'Frozen Planet - Clips - BBC One',
1310             'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1311         },
1312         'playlist_mincount': 24,
1313     }, {
1314         # multipage playlist, all pages
1315         'url': 'http://www.bbc.co.uk/programmes/b00mfl7n/clips',
1316         'info_dict': {
1317             'id': 'b00mfl7n',
1318             'title': 'Frozen Planet - Clips - BBC One',
1319             'description': 'md5:65dcbf591ae628dafe32aa6c4a4a0d8c',
1320         },
1321         'playlist_mincount': 142,
1322     }, {
1323         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/broadcasts/2016/06',
1324         'only_matching': True,
1325     }, {
1326         'url': 'http://www.bbc.co.uk/programmes/b05rcz9v/clips',
1327         'only_matching': True,
1328     }, {
1329         'url': 'http://www.bbc.co.uk/programmes/b055jkys/episodes/player',
1330         'only_matching': True,
1331     }]
1332
1333     def _extract_title_and_description(self, webpage):
1334         title = self._og_search_title(webpage, fatal=False)
1335         description = self._og_search_description(webpage)
1336         return title, description