Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 511 lines (428 sloc) 14.005 kb
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
#include "taskcontext.h"

using namespace transcoding;
using namespace transcoding::io;

// Number of packets to keep in the FIFO
#define FIFO_MIN_COUNT 64

TaskContext::TaskContext(IOReader* input, Profile* profile,
    TaskOptions* options) :
    input(input), profile(profile), options(options),
    ictx(NULL), bitStreamFilter(NULL), fifo(NULL), doneReading(false) {
  TC_LOG_D("TaskContext::TaskContext()\n");
}

TaskContext::~TaskContext() {
  TC_LOG_D("TaskContext::~TaskContext()\n");

  if (this->fifo) {
    delete this->fifo;
  }

  if (this->bitStreamFilter) {
    av_bitstream_filter_close(this->bitStreamFilter);
  }

  if (this->ictx) {
    avformat_free_context(this->ictx);
  }

  delete this->profile;
  delete this->options;

  IOHandle::CloseWhenDone(this->input);
}

int TaskContext::PrepareInput() {
  TC_LOG_D("TaskContext::PrepareInput()\n");
  int ret = 0;

  AVFormatContext* ictx = createInputContext(this->input, &ret);
  if (ret) {
    TC_LOG_D("TaskContext::PrepareInput(): failed createInputContext (%d)\n",
        ret);
  }

  if (!ret) {
    this->ictx = ictx;
  } else {
    if (ictx) {
      avformat_free_context(ictx);
    }
    ictx = NULL;
  }

  TC_LOG_D("TaskContext::PrepareInput() = %d\n", ret);
  return ret;
}

int TaskContext::PrepareOutput() {
  TC_LOG_D("TaskContext::PrepareOutput()\n");
  int ret = 0;

  AVFormatContext* octx = avformat_alloc_context();

  // Setup output container
  if (!ret) {
    AVOutputFormat* ofmt = av_guess_format(
        profile->container.c_str(), NULL, NULL);
    if (ofmt) {
      octx->oformat = ofmt;
    } else {
      ret = AVERROR_NOFMT;
      TC_LOG_D("TaskContext::PrepareOutput(): oformat %s not found (%d)\n",
          profile->container.c_str(), ret);
    }
    octx->duration = ictx->duration;
    octx->start_time = ictx->start_time;
    octx->bit_rate = ictx->bit_rate;
  }

  // Setup input FIFO
  if (!ret) {
    this->fifo = new PacketFifo(ictx->nb_streams);
  }

  // Setup streams
  if (!ret) {
    for (int n = 0; n < ictx->nb_streams; n++) {
      AVStream* stream = ictx->streams[n];
      switch (stream->codec->codec_type) {
      case CODEC_TYPE_VIDEO:
      case CODEC_TYPE_AUDIO:
        stream->discard = AVDISCARD_NONE;
        this->AddOutputStreamCopy(octx, stream, &ret);
        break;
      // TODO: subtitles
      case CODEC_TYPE_SUBTITLE:
      default:
        stream->discard = AVDISCARD_ALL;
        break;
      }
      if (ret) {
        TC_LOG_D("TaskContext::PrepareOutput(): failed stream add (%d)\n", ret);
        break;
      }
    }
  }

  // Scan video streams to see if we need to set up the bitstream filter for
  // fixing h264 in mpegts
  // This is equivalent to the -vbsf h264_mp4toannexb option
  if (!ret && strcmp(octx->oformat->name, "mpegts") == 0) {
    for (int n = 0; n < octx->nb_streams; n++) {
      AVStream* stream = octx->streams[n];
      if (stream->codec->codec_id == CODEC_ID_H264) {
        TC_LOG_D("TaskContext::PrepareOutput(): h264_mp4toannexb on stream "
            "%d\n", n);
        AVBitStreamFilterContext* bsfc =
            av_bitstream_filter_init("h264_mp4toannexb");
        if (!bsfc) {
          ret = AVERROR_BSF_NOT_FOUND;
          TC_LOG_D("TaskContext::PrepareOutput(): h264_mp4toannexb missing\n");
        } else {
          bsfc->next = this->bitStreamFilter;
          this->bitStreamFilter = bsfc;
        }
      }
    }
  }

  if (!ret) {
    this->octx = octx;
  } else {
    if (octx) {
      avformat_free_context(octx);
    }
    octx = NULL;
  }

  TC_LOG_D("TaskContext::PrepareOutput() = %d\n", ret);
  return ret;
}

AVStream* TaskContext::AddOutputStreamCopy(AVFormatContext* octx,
    AVStream* istream, int* pret) {
  int ret = 0;
  AVStream* ostream = NULL;
  AVCodec* codec = NULL;
  AVCodecContext* icodec = NULL;
  AVCodecContext* ocodec = NULL;

  codec = avcodec_find_encoder(istream->codec->codec_id);
  if (!codec) {
    ret = AVERROR_ENCODER_NOT_FOUND;
    goto CLEANUP;
  }

  ostream = av_new_stream(octx, 0);
  if (!ostream) {
    ret = AVERROR_NOMEM;
    goto CLEANUP;
  }

  icodec = istream->codec;
  ocodec = ostream->codec;

  // May not do anything
  ostream->stream_copy = 1;

  avcodec_get_context_defaults3(ocodec, codec);

  ocodec->codec_id = icodec->codec_id;
  ocodec->codec_type = icodec->codec_type;
  ocodec->codec_tag = icodec->codec_tag;
  ocodec->profile = icodec->profile;
  ocodec->level = icodec->level;
  ocodec->bit_rate = icodec->bit_rate;
  ocodec->bits_per_raw_sample = icodec->bits_per_raw_sample;
  ocodec->chroma_sample_location = icodec->chroma_sample_location;
  ocodec->rc_max_rate = icodec->rc_max_rate;
  ocodec->rc_buffer_size = icodec->rc_buffer_size;

  // Input stream may not end on frame boundaries
  if (codec->capabilities & CODEC_CAP_TRUNCATED) {
    icodec->flags |= CODEC_FLAG_TRUNCATED;
  }

  // Try to write output headers at the start
  if (octx->oformat->flags & AVFMT_GLOBALHEADER) {
    ocodec->flags |= CODEC_FLAG_GLOBAL_HEADER;
  }

  ocodec->extradata = (uint8_t*)av_mallocz(
      icodec->extradata_size + FF_INPUT_BUFFER_PADDING_SIZE);
  if (!ocodec->extradata) {
    ret = AVERROR(ENOMEM);
    goto CLEANUP;
  }
  memcpy(ocodec->extradata, icodec->extradata, icodec->extradata_size);
  ocodec->extradata_size = icodec->extradata_size;

  // Code from avconv, but doesn't seem to work all the time - for now just
  // copy the timebase
  ocodec->time_base = istream->time_base;
  if (av_q2d(icodec->time_base) * icodec->ticks_per_frame >
     av_q2d(istream->time_base) && av_q2d(istream->time_base) < 1 / 1000.0) {
   ocodec->time_base = icodec->time_base;
   ocodec->time_base.num *= icodec->ticks_per_frame;
  } else {
   ocodec->time_base = istream->time_base;
  }

  switch (icodec->codec_type) {
  case CODEC_TYPE_VIDEO:
    ocodec->pix_fmt = icodec->pix_fmt;
    ocodec->width = icodec->width;
    ocodec->height = icodec->height;
    ocodec->has_b_frames = icodec->has_b_frames;
    if (!ocodec->sample_aspect_ratio.num) {
      ocodec->sample_aspect_ratio = ostream->sample_aspect_ratio =
          istream->sample_aspect_ratio.num ? istream->sample_aspect_ratio :
          icodec->sample_aspect_ratio.num ? icodec->sample_aspect_ratio :
          (AVRational){0, 1};
    }
    if (octx->oformat->flags & AVFMT_GLOBALHEADER) {
      ocodec->flags |= CODEC_FLAG_GLOBAL_HEADER;
    }
    break;
  case CODEC_TYPE_AUDIO:
    ocodec->channel_layout = icodec->channel_layout;
    ocodec->sample_rate = icodec->sample_rate;
    ocodec->sample_fmt = icodec->sample_fmt;
    ocodec->channels = icodec->channels;
    ocodec->frame_size = icodec->frame_size;
    ocodec->audio_service_type = icodec->audio_service_type;
    if ((icodec->block_align == 1 && icodec->codec_id == CODEC_ID_MP3) ||
        icodec->codec_id == CODEC_ID_AC3) {
      ocodec->block_align = 0;
    } else {
      ocodec->block_align = icodec->block_align;
    }
    break;
  case CODEC_TYPE_SUBTITLE:
    // ?
    ocodec->width = icodec->width;
    ocodec->height = icodec->height;
    break;
  default:
    break;
  }

  // TODO: threading settings
  ocodec->thread_count = 2;

  return ostream;

CLEANUP:
  *pret = ret;
  // TODO: cleanup ostream?
  return NULL;
}

bool TaskContext::NextPacket(int* pret, Progress* progress, AVPacket& packet) {
  TC_LOG_D("TaskContext::NextPacket()\n");

  AVFormatContext* ictx = this->ictx;

  int ret = 0;

  // Read a few packets to fill our queue before we process
  if (!this->doneReading) {
    while (this->fifo->GetCount() <= FIFO_MIN_COUNT) {
      AVPacket readPacket;
      int done = av_read_frame(ictx, &readPacket);
      if (done) {
        TC_LOG_D("TaskContext::NextPacket(): done/failed to read frame (%d)\n",
            ret);
        *pret = 0;
        this->doneReading = true;
        break;
      } else {
        double timestamp = readPacket.pts *
            (double)ictx->streams[readPacket.stream_index]->time_base.num /
            (double)ictx->streams[readPacket.stream_index]->time_base.den;
        this->fifo->QueuePacket(readPacket.stream_index, readPacket, timestamp);
      }
    }
  }
  if (this->doneReading && !this->fifo->GetCount()) {
    return true;
  }

  // Grab the next packet
  if (!this->fifo->DequeuePacket(packet)) {
    return true;
  }
  double timestamp = packet.pts *
      (double)ictx->streams[packet.stream_index]->time_base.num /
      (double)ictx->streams[packet.stream_index]->time_base.den;

  AVStream* stream = ictx->streams[packet.stream_index];

  // Ignore if we don't care about this stream
  if (stream->discard == AVDISCARD_ALL) {
    return false;
  }

  ret = av_dup_packet(&packet);
  if (ret) {
    TC_LOG_D("TaskContext::NextPacket(): failed to duplicate packet (%d)\n",
        ret);
    av_free_packet(&packet);
    *pret = ret;
    return true;
  }

  AVBitStreamFilterContext* bsfc = this->bitStreamFilter;
  while (bsfc) {
    AVPacket newPacket = packet;
    ret = av_bitstream_filter_filter(bsfc, stream->codec, NULL,
        &newPacket.data, &newPacket.size, packet.data, packet.size,
        packet.flags & AV_PKT_FLAG_KEY);
    if (ret > 0) {
       av_free_packet(&packet);
       newPacket.destruct = av_destruct_packet;
       ret = 0;
    } else if (ret < 0) {
       // Error!
       break;
    }
    packet = newPacket;
    bsfc = bsfc->next;
  }
  if (ret) {
    TC_LOG_D("TaskContext::NextPacket(): failed to filter packet (%d)\n", ret);
    *pret = ret;
    av_free_packet(&packet);
    return true;
  }

  // Update progress (only on success)
  if (!ret) {
    progress->timestamp = timestamp;
  }

  if (ret) {
    TC_LOG_D("TaskContext::NextPacket() = %d\n", ret);
  }
  *pret = ret;
  return false;
}

bool TaskContext::WritePacket(int* pret, AVPacket& packet) {
  TC_LOG_D("TaskContext::WritePacket()\n");

  AVFormatContext* ictx = this->ictx;
  AVFormatContext* octx = this->octx;

  int ret = 0;

  ret = av_interleaved_write_frame(octx, &packet);
  if (ret < 0) {
    TC_LOG_D("TaskContext::WritePacket(): could not write frame of "
        "stream (%d)\n", ret);
  } else if (ret > 0) {
    TC_LOG_D("TaskContext::WritePacket(): end of stream requested (%d)\n", ret);
    av_free_packet(&packet);
    *pret = ret;
    return true;
  }

  if (ret) {
    TC_LOG_D("TaskContext::WritePacket() = %d\n", ret);
  }
  *pret = ret;
  return false;
}

bool TaskContext::Pump(int* pret, Progress* progress) {
  TC_LOG_D("TaskContext::Pump()\n");

  AVPacket packet;
  if (this->NextPacket(pret, progress, packet)) {
    TC_LOG_D("TaskContext::Pump() = %d\n", *pret);
    return true;
  }

  if (this->WritePacket(pret, packet)) {
    TC_LOG_D("TaskContext::Pump() = %d\n", *pret);
    av_free_packet(&packet);
    return true;
  }

  av_free_packet(&packet);

  return false;
}

void TaskContext::End() {
  TC_LOG_D("TaskContext::End()\n");

  AVFormatContext* ictx = this->ictx;
  AVFormatContext* octx = this->octx;

  av_write_trailer(octx);
  avio_flush(octx->pb);
}

SingleFileTaskContext::SingleFileTaskContext(io::IOReader* input,
    io::IOWriter* output, Profile* profile, TaskOptions* options) :
    TaskContext(input, profile, options),
    output(output) {
  TC_LOG_D("SingleFileTaskContext::SingleFileTaskContext()\n");
}

SingleFileTaskContext::~SingleFileTaskContext() {
  TC_LOG_D("SingleFileTaskContext::~SingleFileTaskContext()\n");

  if (this->octx) {
    avformat_free_context(this->octx);
  }
  IOHandle::CloseWhenDone(this->output);
}

int SingleFileTaskContext::PrepareOutput() {
  TC_LOG_D("SingleFileTaskContext::PrepareOutput()\n");

  int ret = TaskContext::PrepareOutput();

  AVFormatContext* octx = this->octx;

  // Open output
  if (!ret) {
    ret = this->output->Open();
    if (ret) {
      TC_LOG_D("SingleFileTaskContext::PrepareOutput(): failed open (%d)\n",
          ret);
    }
  }
  if (!ret) {
    octx->pb = this->output->context;
    if (!octx->pb) {
      ret = AVERROR_NOENT;
      TC_LOG_D("SingleFileTaskContext::PrepareOutput(): no pb (%d)\n", ret);
    }
  }

  // Write header
  if (!ret) {
    ret = avformat_write_header(octx, NULL);
    if (ret) {
      TC_LOG_D("SingleFileTaskContext::PrepareOutput(): failed write_header "
          " (%d)\n", ret);
    }
  }

  TC_LOG_D("SingleFileTaskContext::PrepareOutput() = %d\n", ret);
  return ret;
}

LiveStreamingTaskContext::LiveStreamingTaskContext(
    io::IOReader* input, Profile* profile, TaskOptions* options) :
    TaskContext(input, profile, options) {
  TC_LOG_D("LiveStreamingTaskContext::LiveStreamingTaskContext()\n");

  this->playlist = new hls::Playlist(
      options->liveStreaming->path, options->liveStreaming->name,
      options->liveStreaming->segmentDuration,
      options->liveStreaming->allowCaching);
}

LiveStreamingTaskContext::~LiveStreamingTaskContext() {
  TC_LOG_D("LiveStreamingTaskContext::~LiveStreamingTaskContext()\n");

  delete this->playlist;
}

int LiveStreamingTaskContext::PrepareOutput() {
  TC_LOG_D("LiveStreamingTaskContext::PrepareOutput()\n");

  int ret = 0;

  if (ret) {
    TC_LOG_D("LiveStreamingTaskContext::PrepareOutput() = %d\n", ret);
  }
  return ret;
}

bool LiveStreamingTaskContext::Pump(int* pret, Progress* progress) {
  TC_LOG_D("LiveStreamingTaskContext::Pump()\n");

  AVPacket packet;
  if (this->NextPacket(pret, progress, packet)) {
    TC_LOG_D("LiveStreamingTaskContext::Pump() = %d\n", *pret);
    return true;
  }

  // TODO: switch segment/etc based on packet timeestamp/duration

  if (this->WritePacket(pret, packet)) {
    TC_LOG_D("LiveStreamingTaskContext::Pump() = %d\n", *pret);
    av_free_packet(&packet);
    return true;
  }

  av_free_packet(&packet);

  return false;
}
Something went wrong with that request. Please try again.