Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

# -*- coding: utf-8 -*- 

 

# Licensed under the MIT license 

# http://opensource.org/licenses/mit-license.php 

 

# Copyright 2008, Frank Scholz <coherence@beebits.net> 

 

""" transcoder classes to be used in combination with 

    a Coherence MediaServer 

 

    using GStreamer pipelines for the actually work 

    and feeding the output into a http response 

""" 

 

import gi 

gi.require_version('Gst', '1.0') 

from gi.repository import Gst 

from gi.repository import GObject 

Gst.init(None) 

 

import os.path 

import urllib.request 

import urllib.parse 

import urllib.error 

 

from twisted.web import resource, server 

from twisted.internet import protocol 

 

from coherence import log 

 

import struct 

 

 

def get_transcoder_name(transcoder): 

    return transcoder.name 

 

 

class InternalTranscoder(object): 

    """ just a class to inherit from and 

        which we can look for upon creating our 

        list of available transcoders 

    """ 

 

 

class FakeTransformer(Gst.Element, log.LogAble): 

    logCategory = 'faker_datasink' 

 

    _sinkpadtemplate = Gst.PadTemplate.new( 

        "sinkpadtemplate", 

        Gst.PadDirection.SINK, 

        Gst.PadPresence.ALWAYS, 

        Gst.Caps.new_any()) 

 

    _srcpadtemplate = Gst.PadTemplate.new( 

        "srcpadtemplate", 

        Gst.PadDirection.SRC, 

        Gst.PadPresence.ALWAYS, 

        Gst.Caps.new_any()) 

 

    def __init__(self, destination=None, request=None): 

        Gst.Element.__init__(self) 

        log.LogAble.__init__(self) 

        self.sinkpad = Gst.Pad.new_from_template( 

            self._sinkpadtemplate, "sink") 

        self.srcpad = Gst.Pad.new_from_template( 

            self._srcpadtemplate, "src") 

        self.add_pad(self.sinkpad) 

        self.add_pad(self.srcpad) 

 

        self.sinkpad.set_chain_function_full(self.chainfunc) 

 

        self.buffer = '' 

        self.buffer_size = 0 

        self.proxy = False 

        self.got_new_segment = False 

        self.closed = False 

 

    def get_fake_header(self): 

        return \ 

            struct.pack( 

                ">L4s", 32, 'ftyp') + \ 

            b"mp42\x00\x00\x00\x00mp42mp41isomiso2" 

 

    def chainfunc(self, pad, buffer): 

        if self.proxy: 

            # we are in proxy mode already 

            self.srcpad.push(buffer) 

            return Gst.FlowReturn.OK 

 

        self.buffer = self.buffer + buffer.data 

        if not self.buffer_size: 

            try: 

                self.buffer_size, a_type = \ 

                    struct.unpack(">L4s", self.buffer[:8]) 

            except Exception: 

                return Gst.FlowReturn.OK 

 

        if len(self.buffer) < self.buffer_size: 

            # we need to buffer more 

            return Gst.FlowReturn.OK 

 

        buffer = self.buffer[self.buffer_size:] 

        fake_header = self.get_fake_header() 

        n_buf = Gst.Buffer(fake_header + buffer) 

        self.proxy = True 

        self.srcpad.push(n_buf) 

 

        return Gst.FlowReturn.OK 

 

 

GObject.type_register(FakeTransformer) 

 

 

class DataSink(Gst.Element, log.LogAble): 

    logCategory = 'transcoder_datasink' 

 

    _sinkpadtemplate = Gst.PadTemplate.new( 

        "sinkpadtemplate", 

        Gst.PadDirection.SINK, 

        Gst.PadPresence.ALWAYS, 

        Gst.Caps.new_any()) 

 

    def __init__(self, destination=None, request=None): 

        Gst.Element.__init__(self) 

        log.LogAble.__init__(self) 

        self.sinkpad = Gst.Pad.new_from_template( 

            self._sinkpadtemplate, "sink") 

        self.add_pad(self.sinkpad) 

 

        self.sinkpad.set_chain_function_full(self.chainfunc) 

        self.sinkpad.set_event_function_full(self.eventfunc) 

        self.destination = destination 

        self.request = request 

 

        if self.destination is not None: 

            self.destination = open(self.destination, 'wb') 

        self.buffer = '' 

        self.data_size = 0 

        self.got_new_segment = False 

        self.closed = False 

 

    def chainfunc(self, pad, inst, buffer): 

        size = buffer.get_size() 

        buf_data = buffer.extract_dup(0, size) 

        if not isinstance(buf_data, bytes): 

            buf = buffer.encode('ascii') 

        if self.closed: 

            return Gst.FlowReturn.OK 

        if self.destination is not None: 

            self.destination.write(buf_data) 

        elif self.request is not None: 

            self.buffer += buf_data 

            if len(self.buffer) > 200000: 

                self.request.write(self.buffer) 

                self.buffer = b'' 

        else: 

            self.buffer += buffer.data 

 

        self.data_size += size 

        return Gst.FlowReturn.OK 

 

    def eventfunc(self, pad, inst, event): 

        if event.type == Gst.Event.new_stream_start('').type: 

            if not self.got_new_segment: 

                self.got_new_segment = True 

            else: 

                self.closed = True 

        elif event.type == Gst.Event.new_eos().type: 

            if self.destination is not None: 

                self.destination.close() 

            elif self.request is not None: 

                if len(self.buffer) > 0: 

                    self.request.write(self.buffer) 

                self.request.finish() 

        return True 

 

 

GObject.type_register(DataSink) 

 

 

class GStreamerPipeline(resource.Resource, log.LogAble): 

    logCategory = 'gstreamer' 

    addSlash = True 

 

    def __init__(self, pipeline, content_type): 

        self.pipeline_description = pipeline 

        self.contentType = content_type 

        self.requests = [] 

        # if stream has a streamheader (something that has to be prepended 

        # before any data), then it will be a tuple of GstBuffers 

        self.streamheader = None 

        self.parse_pipeline() 

        resource.Resource.__init__(self) 

        log.LogAble.__init__(self) 

 

    def parse_pipeline(self): 

        self.pipeline = Gst.parse_launch(self.pipeline_description) 

        self.appsink = Gst.ElementFactory.make("appsink", "sink") 

        self.appsink.set_property('emit-signals', True) 

        self.pipeline.add(self.appsink) 

        enc = self.pipeline.get_by_name("enc") 

        enc.link(self.appsink) 

        self.appsink.connect("new-preroll", self.new_preroll) 

        self.appsink.connect("new-buffer", self.new_buffer) 

        self.appsink.connect("eos", self.eos) 

 

    def start(self, request=None): 

        self.info("GStreamerPipeline start %r %r", request, 

                  self.pipeline_description) 

        self.requests.append(request) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished, request) 

 

    def new_preroll(self, appsink): 

        self.debug("new preroll") 

        buffer = appsink.emit('pull-preroll') 

        if not self.streamheader: 

            # check caps for streamheader buffer 

            caps = buffer.get_caps() 

            s = caps[0] 

            if "streamheader" in s: 

                self.streamheader = s["streamheader"] 

                self.debug("setting streamheader") 

                for r in self.requests: 

                    self.debug("writing streamheader") 

                    for h in self.streamheader: 

                        r.write(h.data) 

        for r in self.requests: 

            self.debug("writing preroll") 

            r.write(buffer.data) 

 

    def new_buffer(self, appsink): 

        buffer = appsink.emit('pull-buffer') 

        if not self.streamheader: 

            # check caps for streamheader buffers 

            caps = buffer.get_caps() 

            s = caps[0] 

            if "streamheader" in s: 

                self.streamheader = s["streamheader"] 

                self.debug("setting streamheader") 

                for r in self.requests: 

                    self.debug("writing streamheader") 

                    for h in self.streamheader: 

                        r.write(h.data) 

        for r in self.requests: 

            r.write(buffer.data) 

 

    def eos(self, appsink): 

        self.info("eos") 

        for r in self.requests: 

            r.finish() 

        self.cleanup() 

 

    def getChild(self, name, request): 

        self.info('getChild %s, %s', name, request) 

        return self 

 

    def render_GET(self, request): 

        self.info('render GET %r', request) 

        request.setResponseCode(200) 

        if hasattr(self, 'contentType'): 

            request.setHeader(b'Content-Type', self.contentType) 

        request.write(b'') 

 

        headers = request.getAllHeaders() 

        if ('connection' in headers and 

                headers['connection'] == 'close'): 

            pass 

        if self.requests: 

            if self.streamheader: 

                self.debug("writing streamheader") 

                for h in self.streamheader: 

                    request.write(h.data) 

            self.requests.append(request) 

        else: 

            self.parse_pipeline() 

            self.start(request) 

        return server.NOT_DONE_YET 

 

    def render_HEAD(self, request): 

        self.info('render HEAD %r', request) 

        request.setResponseCode(200) 

        request.setHeader(b'Content-Type', self.contentType) 

        request.write(b'') 

 

    def requestFinished(self, result, request): 

        self.info("requestFinished %r", result) 

        """ we need to find a way to destroy the pipeline here 

        """ 

        # from twisted.internet import reactor 

        # reactor.callLater(0, self.pipeline.set_state, Gst.State.NULL) 

        self.requests.remove(request) 

        if not self.requests: 

            self.cleanup() 

 

    def on_message(self, bus, message): 

        t = message.type 

        print("on_message", t) 

        if t == Gst.Message.ERROR: 

            # err, debug = message.parse_error() 

            # print "Error: %s" % err, debug 

            self.cleanup() 

        elif t == Gst.Message.EOS: 

            self.cleanup() 

 

    def cleanup(self): 

        self.info("pipeline cleanup") 

        self.pipeline.set_state(Gst.State.NULL) 

        self.requests = [] 

        self.streamheader = None 

 

 

class BaseTranscoder(resource.Resource, log.LogAble): 

    logCategory = 'transcoder' 

    addSlash = True 

 

    def __init__(self, uri, destination=None, content_type=None): 

        if uri[:7] not in ['file://', 'http://']: 

            uri = 'file://' + urllib.parse.quote(uri)  # FIXME 

        self.uri = uri 

        self.destination = destination 

        self.contentType = None 

        self.pipeline = None 

        resource.Resource.__init__(self) 

        log.LogAble.__init__(self) 

        self.info('uri %s %r', uri, type(uri)) 

 

    def getChild(self, name, request): 

        self.info('getChild %s, %s', name, request) 

        return self 

 

    def render_GET(self, request): 

        self.info('render GET %r', request) 

        request.setResponseCode(200) 

        if self.contentType is not None: 

            request.setHeader(b'Content-Type', self.contentType) 

        request.write(b'') 

 

        headers = request.getAllHeaders() 

        if ('connection' in headers and 

                headers['connection'] == 'close'): 

            pass 

 

        self.start(request) 

        return server.NOT_DONE_YET 

 

    def render_HEAD(self, request): 

        self.info('render HEAD %r', request) 

        request.setResponseCode(200) 

        request.setHeader(b'Content-Type', self.contentType) 

        request.write(b'') 

 

    def requestFinished(self, result): 

        self.info("requestFinished %r", result) 

        """ we need to find a way to destroy the pipeline here 

        """ 

        # from twisted.internet import reactor 

        # reactor.callLater(0, self.pipeline.set_state, Gst.State.NULL) 

        GObject.idle_add(self.cleanup) 

 

    def on_message(self, bus, message): 

        t = message.type 

        print("on_message", t) 

        if t == Gst.Message.ERROR: 

            # err, debug = message.parse_error() 

            # print "Error: %s" % err, debug 

            self.cleanup() 

        elif t == Gst.Message.EOS: 

            self.cleanup() 

 

    def cleanup(self): 

        self.pipeline.set_state(Gst.State.NULL) 

 

    def start(self, request=None): 

        """This method should be sub classed for each 

        class which inherits from BaseTranscoder""" 

        pass 

 

 

class PCMTranscoder(BaseTranscoder, InternalTranscoder): 

    contentType = 'audio/L16;rate=44100;channels=2' 

    name = 'lpcm' 

 

    def start(self, request=None): 

        self.info("PCMTranscoder start %r %r", request, self.uri) 

        self.pipeline = Gst.parse_launch( 

            "%s ! decodebin ! audioconvert name=conv" % self.uri) 

 

        conv = self.pipeline.get_by_name('conv') 

        caps = Gst.Caps.from_string( 

            "audio/x-raw-int,rate=44100,endianness=4321," 

            "channels=2,width=16,depth=16,signed=true") 

        # FIXME: UGLY. 'filter' is a python builtin! 

        filter = Gst.ElementFactory.make("capsfilter", "filter") 

        filter.set_property("caps", caps) 

        self.pipeline.add(filter) 

        conv.link(filter) 

 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        filter.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class WAVTranscoder(BaseTranscoder, InternalTranscoder): 

    contentType = 'audio/x-wav' 

    name = 'wav' 

 

    def start(self, request=None): 

        self.info("start %r", request) 

        self.pipeline = Gst.parse_launch( 

            "%s ! decodebin ! audioconvert ! wavenc name=enc" % self.uri) 

        enc = self.pipeline.get_by_name('enc') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        enc.link(sink) 

        # bus = self.pipeline.get_bus() 

        # bus.connect('message', self.on_message) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class MP3Transcoder(BaseTranscoder, InternalTranscoder): 

    contentType = 'audio/mpeg' 

    name = 'mp3' 

 

    def start(self, request=None): 

        self.info("start %r", request) 

        self.pipeline = Gst.parse_launch( 

            "%s ! decodebin ! audioconvert ! lame name=enc" % self.uri) 

        enc = self.pipeline.get_by_name('enc') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        enc.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class MP4Transcoder(BaseTranscoder, InternalTranscoder): 

    """ Only works if H264 inside Quicktime/MP4 container is input 

        Source has to be a valid uri 

    """ 

    contentType = 'video/mp4' 

    name = 'mp4' 

 

    def start(self, request=None): 

        self.info("start %r", request) 

        self.pipeline = Gst.parse_launch( 

            "%s ! qtdemux name=d ! queue ! h264parse ! " 

            "mp4mux name=mux d. ! queue ! mux." % self.uri) 

        mux = self.pipeline.get_by_name('mux') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        mux.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class MP2TSTranscoder(BaseTranscoder, InternalTranscoder): 

    contentType = 'video/mpeg' 

    name = 'mpegts' 

 

    def start(self, request=None): 

        self.info("start %r", request) 

        # FIXME - mpeg2enc 

        self.pipeline = Gst.parse_launch( 

            "mpegtsmux name=mux %s ! decodebin2 name=d ! queue ! " 

            "ffmpegcolorspace ! mpeg2enc ! queue ! mux. d. ! " 

            "queue ! audioconvert ! twolame ! queue ! mux." % self.uri) 

        enc = self.pipeline.get_by_name('mux') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        enc.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class ThumbTranscoder(BaseTranscoder, InternalTranscoder): 

    """ should create a valid thumbnail according to the DLNA spec 

        neither width nor height must exceed 160px 

    """ 

    contentType = 'image/jpeg' 

    name = 'thumb' 

 

    def start(self, request=None): 

        self.info("start %r", request) 

        """ 

        # what we actually want here is a pipeline that calls 

        # us when it knows about the size of the original image, 

        # and allows us now to adjust the caps-filter with the 

        # calculated values for width and height 

        new_width = 160 

        new_height = 160 

        if original_width > 160: 

            new_heigth = \ 

                int(float(original_height) * (160.0/float(original_width))) 

            if new_height > 160: 

                new_width = \ 

                    int(float(new_width) * (160.0/float(new_height))) 

        elif original_height > 160: 

            new_width = \ 

                int(float(original_width) * (160.0/float(original_height))) 

        """ 

        try: 

            type = request.args['type'][0] 

        except IndexError: 

            type = 'jpeg' 

        if type == 'png': 

            self.pipeline = Gst.parse_launch( 

                "%s ! decodebin2 ! videoscale ! " 

                "video/x-raw-yuv,width=160,height=160 ! pngenc name=enc" % 

                self.uri) 

            self.contentType = 'image/png' 

        else: 

            self.pipeline = Gst.parse_launch( 

                "%s ! decodebin2 ! videoscale ! " 

                "video/x-raw-yuv,width=160,height=160 ! jpegenc name=enc" % 

                self.uri) 

            self.contentType = 'image/jpeg' 

        enc = self.pipeline.get_by_name('enc') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        enc.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class GStreamerTranscoder(BaseTranscoder): 

    """ a generic Transcode based on GStreamer 

 

        the pipeline which will be parsed upon 

        calling the start method, as to be set as 

        the attribute pipeline_description to the 

        instantiated class 

 

        same for the attribute contentType 

    """ 

    pipeline_description = None 

 

    def start(self, request=None): 

        if self.pipeline_description is None: 

            raise NotImplementedError( 

                "Warning: operation cancelled. You must set a value for " 

                "GStreamerTranscoder.pipeline_description") 

        self.info("start %r", request) 

        self.pipeline = Gst.parse_launch(self.pipeline_description % self.uri) 

        enc = self.pipeline.get_by_name('mux') 

        sink = DataSink(destination=self.destination, request=request) 

        self.pipeline.add(sink) 

        enc.link(sink) 

        self.pipeline.set_state(Gst.State.PLAYING) 

 

        d = request.notifyFinish() 

        d.addBoth(self.requestFinished) 

 

 

class ExternalProcessProtocol(protocol.ProcessProtocol): 

 

    def __init__(self, caller): 

        self.caller = caller 

 

    def connectionMade(self): 

        print("pp connection made") 

 

    def outReceived(self, data): 

        # print "outReceived with %d bytes!" % len(data) 

        self.caller.write_data(data) 

 

    def errReceived(self, data): 

        # print "errReceived! with %d bytes!" % len(data) 

        print("pp (err):", data.strip()) 

 

    def inConnectionLost(self): 

        # print "inConnectionLost! stdin is closed! (we probably did it)" 

        pass 

 

    def outConnectionLost(self): 

        # print "outConnectionLost! The child closed their stdout!" 

        pass 

 

    def errConnectionLost(self): 

        # print "errConnectionLost! The child closed their stderr." 

        pass 

 

    def processEnded(self, status_object): 

        print("processEnded, status %d" % status_object.value.exitCode) 

        print("processEnded quitting") 

        self.caller.ended = True 

        self.caller.write_data('') 

 

 

class ExternalProcessProducer(object): 

    logCategory = 'externalprocess' 

 

    def __init__(self, pipeline, request): 

        self.pipeline = pipeline 

        self.request = request 

        self.process = None 

        self.written = 0 

        self.data = '' 

        self.ended = False 

        request.registerProducer(self, 0) 

 

    def write_data(self, data): 

        if data: 

            # print "write %d bytes of data" % len(data) 

            self.written += len(data) 

            # this .write will spin the reactor, calling .doWrite and then 

            # .resumeProducing again, so be prepared for a re-entrant call 

            self.request.write(data) 

        if self.request and self.ended: 

            print("closing") 

            self.request.unregisterProducer() 

            self.request.finish() 

            self.request = None 

 

    def resumeProducing(self): 

        # print "resumeProducing", self.request 

        if not self.request: 

            return 

        if self.process is None: 

            argv = self.pipeline.split() 

            executable = argv[0] 

            argv[0] = os.path.basename(argv[0]) 

            from twisted.internet import reactor 

            self.process = reactor.spawnProcess(ExternalProcessProtocol(self), 

                                                executable, argv, {}) 

 

    def pauseProducing(self): 

        pass 

 

    def stopProducing(self): 

        print("stopProducing", self.request) 

        self.request.unregisterProducer() 

        self.process.loseConnection() 

        self.request.finish() 

        self.request = None 

 

 

class ExternalProcessPipeline(resource.Resource, log.LogAble): 

    logCategory = 'externalprocess' 

    addSlash = False 

    pipeline_description = None 

    contentType = None 

 

    def __init__(self, uri): 

        self.uri = uri 

        resource.Resource.__init__(self) 

        log.LogAble.__init__(self) 

 

    def getChildWithDefault(self, path, request): 

        return self 

 

    def render(self, request): 

        print("ExternalProcessPipeline render") 

        if self.pipeline_description is None: 

            raise NotImplementedError( 

                "Warning: operation cancelled. You must set a value for " 

                "ExternalProcessPipeline.pipeline_description") 

        if self.contentType is not None: 

            request.setHeader(b'Content-Type', self.contentType) 

 

        ExternalProcessProducer(self.pipeline_description % self.uri, request) 

        return server.NOT_DONE_YET 

 

 

def transcoder_class_wrapper(klass, content_type, pipeline): 

    def create_object(uri): 

        transcoder = klass(uri) 

        transcoder.contentType = content_type 

        transcoder.pipeline_description = pipeline 

        return transcoder 

 

    return create_object 

 

 

class TranscoderManager(log.LogAble): 

    """ singleton class which holds information 

        about all available transcoders 

 

        they are put into a transcoders dict with 

        their id as the key 

 

        we collect all internal transcoders by searching 

        for all subclasses of InternalTranscoder, the class 

        will be the value 

 

        transcoders defined in the config are parsed and 

        stored as a dict in the transcoders dict 

 

        in the config a transcoder description has to look like this: 

 

        *** preliminary, will be extended and 

        might even change without further notice *** 

 

        <transcoder> 

            <pipeline>%s ...</pipeline> <!-- we need a %s here to insert the 

                                            source uri (or can we have all the 

                                            times pipelines we can prepend with 

                                            a '%s !') and an element named mux 

                                            where we can attach our sink --> 

            <type>gstreamer</type>      <!-- could be gstreamer or process --> 

            <name>mpegts</name> 

            <target>video/mpeg</target> 

            <fourth_field>              <!-- value for the 4th field of the 

                                            protocolInfo phalanx, default is 

                                            '*' --> 

        </transcoder> 

 

    """ 

 

    logCategory = 'transcoder_manager' 

    _instance_ = None  # Singleton 

 

    def __new__(cls, *args, **kwargs): 

        """ creates the singleton """ 

        if cls._instance_ is None: 

            obj = super(TranscoderManager, cls).__new__(cls) 

            if 'coherence' in kwargs: 

                obj.coherence = kwargs['coherence'] 

            cls._instance_ = obj 

        return cls._instance_ 

 

    def __init__(self, coherence=None): 

        """ initializes the class 

 

            it should be called at least once 

            with the main coherence class passed as an argument, 

            so we have access to the config 

        """ 

        log.LogAble.__init__(self) 

        self.transcoders = {} 

        for transcoder in InternalTranscoder.__subclasses__(): 

            self.transcoders[get_transcoder_name(transcoder)] = transcoder 

 

        if coherence is not None: 

            self.coherence = coherence 

            try: 

                transcoders_from_config = self.coherence.config['transcoder'] 

                if isinstance(transcoders_from_config, dict): 

                    transcoders_from_config = [transcoders_from_config] 

            except KeyError: 

                transcoders_from_config = [] 

 

            for transcoder in transcoders_from_config: 

                # FIXME: is anyone checking if all keys are given ? 

                pipeline = transcoder['pipeline'] 

                if '%s' not in pipeline: 

                    self.warning("Can't create transcoder %r:" 

                                 " missing placehoder '%%s' in 'pipeline'", 

                                 transcoder) 

                    continue 

 

                try: 

                    transcoder_name = transcoder['name']  # .decode('ascii') 

                except UnicodeEncodeError: 

                    self.warning("Can't create transcoder %r:" 

                                 " the 'name' contains non-ascii letters", 

                                 transcoder) 

                    continue 

 

                transcoder_type = transcoder['type'].lower() 

 

                if transcoder_type == 'gstreamer': 

                    wrapped = transcoder_class_wrapper(GStreamerTranscoder, 

                                                       transcoder['target'], 

                                                       transcoder['pipeline']) 

                elif transcoder_type == 'process': 

                    wrapped = transcoder_class_wrapper(ExternalProcessPipeline, 

                                                       transcoder['target'], 

                                                       transcoder['pipeline']) 

                else: 

                    self.warning("unknown transcoder type %r", transcoder_type) 

                    continue 

 

                self.transcoders[transcoder_name] = wrapped 

 

        # FIXME reduce that to info later 

        self.warning("available transcoders %r", self.transcoders) 

 

    def select(self, name, uri, backend=None): 

        # FIXME:why do we specify the name when trying to get it? 

 

        if backend is not None: 

            """ try to find a transcoder provided by the backend 

                and return that here, 

                if there isn't one continue with the ones 

                provided by the config or the internal ones 

            """ 

            pass 

 

        transcoder = self.transcoders[name](uri) 

        return transcoder